Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

Rental shipments and receipts (#1874)

Brad Barbind24f763d52f8
diff --git a/.ai/plans/2026-10-07-rental-shipments-and-receipts.md b/.ai/plans/2026-10-07-rental-shipments-and-receipts.md
new file mode 100644
index 0000000000..99b377770f
--- /dev/null
+++ b/.ai/plans/2026-10-07-rental-shipments-and-receipts.md
@@ -0,0 +1,1845 @@
+# 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
+
+- [x] Task 1: Add the enum migration
+- [x] Task 2: Add the fixed-asset line migration
+- [x] Task 3: Apply the migrations, regenerate types and fix the nullable readers
+- [x] Task 4: Build the rental test fixture and pin today's return
+- [x] Task 5: Move the return body into `returnRentalUnit`
+- [x] Task 6: Add the pure rental document rules
+- [x] Task 7: Add the two `create` cases
+- [x] Task 8: Post a rental shipment
+- [x] Task 9: Void a rental shipment
+- [x] Task 10: Post a rental receipt and refuse its void
+- [x] Task 11: Add the Close guard
+- [x] Task 12: Add the ERP models, service reads and the line-documents helper
+- [x] Task 13: Add the rental branches to the inventory `new` and `details` routes
+- [x] Task 14: Load the rental lines and save their fields
+- [x] Task 15: Pass the posting date from the post routes
+- [x] Task 16: Turn the per-unit Deliver and Return routes into shortcuts
+- [x] Task 17: Show the rental units on the shipment page
+- [x] Task 18: Show the rental units on the receipt page
+- [x] Task 19: Add the source to tables, forms, document panels and traceability
+- [x] Task 20: Print a Delivery Ticket
+- [x] Task 21: Add Deliver and Return to the agreement header
+- [x] Task 22: Replace the `return` type with `release`
+- [x] Task 23: Repoint the unit actions and add Release unit
+- [x] Task 24: Run the full verification sweep
+- [x] Task 25: Extract and translate the new strings
+- [x] Task 26: Update the docs
+- [x] 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.md` sections "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 `InvalidInputError` from `../errors`.
+ A missing record throws `NotFoundError`.
+- Every new source file starts with its SPDX header. Run
+ `pnpm --filter @carbon/checks license-headers` after 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:
+
+ ```bash
+ 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:**
+1. 🛑 Check that no `crbn up`, `crbn migrate` or `pnpm db:migrate` runs now. A running migrate records a new empty file as applied.
+2. Run `pnpm db:migrate:new rental-documents-enums`.
+3. Write this SQL into the new file. Write nothing else into it.
+
+ ```sql
+ -- 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:**
+```bash
+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:**
+1. 🛑 Check again that no migrate runs now.
+2. Run `pnpm db:migrate:new rental-documents`. The new file must sort after the Task 1 file.
+3. Write this SQL into the file:
+
+ ```sql
+ -- 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';
+ ```
+
+4. Do not add RLS policies. The tables keep their manifest rules
+ (`packages/database/src/authz/manifest.ts:1219` and `:1383`). The rules are
+ per table, so new columns inherit them. `migration.test.ts` hashes the
+ rendered rules, which do not change. Do not write an authz migration.
+5. Do not add a `TABLE_RENAMES` entry: nothing is renamed or dropped. Do not add
+ an `ID_REF_COLUMNS` entry: `rentalAgreementLineId` has a FK.
+
+**Verify:**
+```bash
+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.ts` and 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:**
+1. Run `pnpm db:migrate`. It applies both files and regenerates the types and swagger.
+2. Run `pnpm run generate:types`.
+3. In `post-shipment/index.ts:630-635`, add `companyId` to the `many(...)` filter object.
+4. In `post-shipment/index.ts:636-638`, build `shippedFaSoLineIds` from `(shipmentFaLines ?? []).filter((r) => r.salesOrderLineId !== null)`.
+5. In `post-receipt/index.ts:1891-1896`, add `companyId` to the `many(...)` filter object.
+6. Directly after that read, narrow the rows once:
+
+ ```ts
+ const poFaLines = (receiptFaLines ?? []).filter(
+ (r): r is typeof r & { purchaseOrderLineId: string } =>
+ r.purchaseOrderLineId !== null
+ );
+ ```
+
+7. Replace each `receiptFaLines ?? []` in `post-receipt/index.ts:1897-1905` with `poFaLines`.
+8. In `convert/index.ts:1435`, add `if (!lineId) continue;` after `const lineId = line.salesOrderLineId;`.
+9. In `$shipmentId.tsx`, add `.not("salesOrderLineId", "is", null)` to the `shipmentFixedAssetLine` query at line 79-84.
+10. In `$receiptId.tsx`, add `.not("purchaseOrderLineId", "is", null)` to the `receiptFixedAssetLine` query at line 107-112.
+11. Run the two typechecks below. Fix each error that the nullable order-line columns cause with a null check of the same shape.
+12. If the `erp` typecheck shows TS2589 ("excessively deep") in a file that embeds `rentalAgreementLine`, `shipmentFixedAssetLine` or `receiptFixedAssetLine`, name the FK in that embed. Precedent: the TS2589 lesson in `.ai/lessons.md`.
+13. If the typecheck shows any other kind of error, STOP and report — do not improvise.
+
+**Verify:**
+```bash
+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:**
+1. Create `rental-test-fixture.ts`. Export this function:
+
+ ```ts
+ 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>;
+ }>;
+ ```
+
+2. Insert these rows in one transaction with `app.sync_in_progress` set, as the precedent does:
+ 1. `companyGroup`, `company` (timezone `America/New_York`), `currency` USD with 2 decimals, `companySettings`.
+ 2. `sequence` rows for `shipment` (prefix `SHP-`), `receipt` (prefix `RCV-`) and `fixedAsset` (prefix `FA`).
+ 3. One `customer`. Two `location` rows: `locationId` and `otherLocationId`.
+ 4. One `item`: type `Part`, `itemTrackingType` `Serial`.
+ 5. One `fixedAssetClass`, then one `fixedAsset` per unit: status `Active`, `locationId`, name `Scissor lift N`, `fixedAssetId` `FA-N`, `serialNumber` `SN-N`.
+ 6. One `trackedEntity` per unit. Set `fixedAsset.trackedEntityId` to it.
+ 7. One `rentalAgreement`: `rentalAgreementId` `RA-TEST`, status `Active`, `startDate` `2026-09-01`, `endDate` null, `billingCycle` `Calendar Month`, the `billingTiming` option, `discountRate` 0, `currencyCode` USD, `locationId`.
+ 8. One `rentalAgreementLine` per unit: status `Pending`, `rateUnit` `Month`, `rate` 300, `lessorClassification` `Rental`, its `fixedAssetId` and `trackedEntityId`.
+ 9. Two `rentalBillingPeriod` rows per line: `2026-09-01`–`2026-09-30` (30 days, 300, due `2026-09-01`, status `Invoiced`) and `2026-10-01`–`2026-10-31` (31 days, 300, due `2026-10-01`, status `Pending`).
+3. Read the NOT NULL columns of `fixedAssetClass`, `fixedAsset` and `trackedEntity` in `packages/database/src/types.ts` (`Insert` types). Fill only the required ones.
+4. Copy `cleanup()` from the precedent (`create-rental-invoices.test.ts:164-182`).
+5. Create `return-unit.test.ts` with one `databaseTest` named `"an early return of an Advance unit re-cuts its periods"`:
+ 1. Build `rentalFixture()`.
+ 2. Set the line `On Rent` with `deliveredAt` `2026-09-01` by a direct Kysely update.
+ 3. Act through a local function `returnUnitOnSeptember20(f)`. For now it calls the default export of `./index` with `{ type: "return", rentalAgreementId: f.agreementId, rentalAgreementLineId: f.lineIds[0], returnedAt: "2026-09-20" }`.
+ 4. Expect `result.error` to be `null`.
+ 5. Read the line's periods: `periodStart::text`, `periodEnd::text`, `days`, `Number(amount)`, `isAdjustment`, `status`, `rateUnitApplied`, `dueOn::text`. Order by `periodStart`, then `isAdjustment`.
+ 6. Read the line's `status` and `returnedAt::text`.
+ 7. Run `expect({ periods, line }).toMatchSnapshot()`.
+ 8. Call `f.cleanup()` in a `finally`.
+
+**Verify:**
+```bash
+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; `returnUnit` becomes a wrapper
+
+**Steps:**
+1. Move these declarations from `index.ts` into `agreement.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 LeaseAccounting` and `loadLeaseAccounting` (`:202-285`)
+ - `postLeaseJournal` (`:288-347`), `insertUnitActivity` (`:350-392`)
+2. Move each import that only these declarations use into `agreement.ts`.
+3. In `return-unit.ts`, export this type and function:
+
+ ```ts
+ 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 }>;
+ ```
+
+4. Set the body of `returnRentalUnit` to `index.ts:1065-1253`: from the `rentalAgreementLine` read to the end of the out-of-service update.
+5. In the moved body, rename `payload.` to `unit.`. Return `{ fixedAssetId: fleetAssetId }`. Change nothing else.
+6. Move `returnResidual` with its doc comment (`index.ts:1258-1655`) into `return-unit.ts`.
+7. Add `locationId: string` to the `args` type of `returnResidual`.
+8. In `returnResidual`, replace `agreement.locationId` with `args.locationId` at exactly these 3 places:
+ - the `fixedAsset` insert (`index.ts:1489`)
+ - the `fixedAssetTransfer` insert (`index.ts:1520`)
+ - the `bookAdjustment` ledger row (`index.ts:1565`)
+9. Leave `tags.locationId` (`index.ts:1409`) on `agreement.locationId`. The journal stays the same as today (plan decision P4).
+10. In `returnRentalUnit`, pass `locationId: args.locationId ?? agreement.locationId` to `returnResidual`.
+11. Rewrite `returnUnit` in `index.ts` as this wrapper. It passes no `locationId`:
+
+ ```ts
+ 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 };
+ });
+ }
+ ```
+
+12. Remove the imports from `index.ts` that nothing uses any more.
+13. Run `pnpm --filter @carbon/checks license-headers`.
+
+**Verify:**
+```bash
+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:**
+1. Split `returnValidator` (`validators.ts:45-63`). Move its fields except `type` and `rentalAgreementId` into `const unitReturnFields = { … }`.
+2. Export `unitReturnValidator = z.object(unitReturnFields).refine(…)`. Use the existing out-of-service refine.
+3. Rebuild `returnValidator` as `z.object({ type: z.literal("return"), ...unitReturnFields, ...scope }).refine(…)`. Keep the same refine.
+4. Add these exports:
+
+ ```ts
+ /** 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;
+ ```
+
+5. Use these exact messages:
+
+ | Helper | Case | Message |
+ |--------|------|---------|
+ | `rentalShipmentVoidBlocker` | a unit is not `On Rent` | `` `${label} is ${status}; a rental shipment can be voided only while every unit is On Rent` `` |
+ | `rentalShipmentVoidBlocker` | `accrual` = `"Posted"` | `` `A posted revenue recognition run holds accrued rent for ${label}; the shipment cannot be voided` `` |
+ | `rentalShipmentVoidBlocker` | `accrual` = `"Draft run"` | `` `A draft revenue recognition run holds accrued rent for ${label}; delete the run before voiding the shipment` `` |
+ | `openRentalDocumentBlocker` | `shipmentId` set | `` `Shipment ${shipmentId} is still open; post or delete it before closing the agreement` `` |
+ | `openRentalDocumentBlocker` | `receiptId` set | `` `Receipt ${receiptId} is still open; post or delete it before closing the agreement` `` |
+ | `receiptReturnError` | status not in `RETURNABLE_LINE_STATUSES` | `` `${label} is ${status}; only a Pending or On Rent unit can be returned` `` |
+ | `releaseBlocker` | status not `Pending` | `` `${label} is ${status}; only a Pending unit can be released` `` |
+ | `releaseBlocker` | `classification` = `"Sale"` | `` `${label} is treated as a sale; return it on a rental receipt instead` `` |
+ | `releaseBlocker` | `openDocument` set | `` `${label} is on ${openDocument}; remove it there before releasing the unit` `` |
+
+6. In `rentalShipmentVoidBlocker`, check the first unit that is not `On Rent` first. Then check accruals in unit order.
+7. In `openRentalDocumentBlocker`, check the shipment first.
+8. In `receiptReturnError`, use the existing `RETURNABLE_LINE_STATUSES` (`validators.ts:95-102`). It already holds `Pending` and `On Rent`.
+9. In `releaseBlocker`, check in this order: status, classification, open document.
+10. Add one test per message, one test for each null result, and 3 `unitReturnValidator` tests. Copy the shape of the existing return tests (`validators.test.ts:33-110`), without `type` and `rentalAgreementId`.
+
+**Verify:**
+```bash
+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 before `case "journalEntry"` (line 3372)
+- Create: `packages/server-functions/src/create/rental-agreement.test.ts`
+- Modify: `packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap` — by `vitest -u` only
+- Copy from (precedent): `create/index.ts:2007-2221` (`shipmentFromSalesReturnOrder`, the insert of the header) and `create/index.ts:3031-3051` (the asset-line insert)
+
+**Steps:**
+1. Add these members to `createInput`:
+
+ ```ts
+ 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()
+ }),
+ ```
+
+2. Add `shipmentFromRentalAgreement: { create: "inventory" }` and `receiptFromRentalAgreement: { create: "inventory" }` to `permissions.rules`.
+3. Add `case "shipmentFromRentalAgreement"`. Run the whole case in one `db.transaction()`. Do these steps in order:
+ 1. Read `rentalAgreement` (`id`, `rentalAgreementId`, `status`, `customerId`, `locationId`) by `id` and `companyId`, `forUpdate()`. If none, throw `NotFoundError("Rental agreement not found")`.
+ 2. If `status !== "Active"`, throw `InvalidInputError` with `` `Rental agreement ${rentalAgreementId} is ${status}; units are delivered from an Active agreement` ``.
+ 3. Read the Draft shipment: `sourceDocument = 'Rental Agreement'`, `sourceDocumentId = agreement.id`, `status = 'Draft'`, `companyId`, `forUpdate()`.
+ 4. Read the line ids on open documents: join `shipmentFixedAssetLine` to `shipment`, where the shipment is `Draft` or `Pending` and has this source.
+ 5. Read the candidate lines: `rentalAgreementLine` of this agreement and company, `status = 'Pending'`. If a line id is given, read only that id.
+ 6. If a line id is given and no `Pending` line matches, throw `InvalidInputError("Only a Pending unit can be delivered")`.
+4. 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 `shipped` to 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")` | — |
+
+5. Insert the header with these values. Leave `postingDate` unset.
+
+ ```ts
+ {
+ 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
+ }
+ ```
+
+6. Insert each asset line as `{ shipmentId, rentalAgreementLineId, shipped: true, companyId, createdBy: userId }`.
+7. Add `case "receiptFromRentalAgreement"` with the same structure and these differences (spec Q8):
+
+ | Item | Shipment case | Receipt case |
+ |------|---------------|--------------|
+ | Candidate status | `Pending` | `Pending` or `On Rent` |
+ | Header table and sequence | `shipment` | `receipt` (`receiptId` from `getNextSequence(trx, "receipt", companyId)`) |
+ | `customerId` | set | not set (`receipt` has no such column) |
+ | Asset line, no line id given | `shipmentFixedAssetLine`, `shipped: true` | `receiptFixedAssetLine`: `received: true` for an `On Rent` unit, `received: false` for a `Pending` unit; `residualDestination` left null |
+ | Asset line, line id given | `shipped: true` | `received: true`, whether the unit is `Pending` or `On Rent` |
+ | Unticked unit already on the Draft, line id given | set `shipped` to true | set `received` to true |
+ | Agreement refusal | `units are delivered from an Active agreement` | `units are returned from an Active agreement` |
+ | Line refusal | `Only a Pending unit can be delivered` | `Only a Pending or On Rent unit can be returned` |
+ | Open-document refusal | `The unit is already on an open shipment` | `The unit is already on an open receipt` |
+ | Empty refusal | `No units to deliver` | `No units to return` |
+
+ The receipt case skips units on another open receipt only. A `Pending` unit 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.
+
+8. Create `create/rental-agreement.test.ts`. Use `rentalFixture({ units: 5 })` from Task 4. Write these `databaseTest` cases:
+ 1. A shipment without a line id: one Draft, 5 asset lines with `shipped = true`, `locationId` = `f.locationId`, `sourceDocumentReadableId` = `RA-TEST`, `postingDate` null.
+ 2. A second call without a line id returns the same id. The shipment still has 5 lines.
+ 3. A raw Kysely insert of a second Draft `shipment` with this source fails. The error message contains `shipment_oneOpenDraftPerRentalAgreement_idx`.
+ 4. Set every line `Returned`. A receipt fails with `No units to return`.
+ 5. Set 3 lines `On Rent`. A receipt without a line id has 5 lines: 3 with `received = true`, 2 `Pending` units with `received = false`.
+ 6. In the same fixture, the receipt call with the line id of an unticked `Pending` unit returns the same receipt id. That line now has `received = true`.
+ 7. Set 2 lines `On Rent` and delete the Draft shipment. A shipment then holds only the 3 `Pending` units.
+ 8. On a `Closed` agreement, the shipment call fails with `is Closed`.
+ 9. With no Draft receipt, the receipt call with the line id of a `Pending` unit creates a receipt with 1 line, `received = true`.
+9. Update the permissions snapshot.
+
+**Verify:**
+```bash
+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), `run` signature (line 64), new case before `default` (line 3038)
+- Modify: `packages/server-functions/src/post-rental-agreement/agreement.ts` — widen `insertUnitActivity`
+- 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:**
+1. Change `postShipmentInput` to:
+
+ ```ts
+ 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()
+ });
+ ```
+
+2. Destructure `postingDate` in `run(ctx, { type, shipmentId, postingDate })`.
+3. In `agreement.ts`, widen `insertUnitActivity`: `type` adds `"Rental Delivery" | "Rental Return" | "Void Shipment"`. `sourceDocument` adds `"Shipment" | "Receipt"`.
+4. In `post-shipment/rental-agreement.ts`, export:
+
+ ```ts
+ export async function postRentalShipment(
+ db: Kysely<KyselyDatabase>,
+ args: { shipmentId: string; companyId: string; userId: string; today: string; postingDate?: string }
+ ): Promise<void>;
+ ```
+
+5. Write its body as one `db.transaction()`, in this order:
+ 1. Set `deliveredOn = postingDate ?? today`. If `futureDeliveryError(deliveredOn, today)` returns a message, throw it as `InvalidInputError`.
+ 2. Lock the shipment `forUpdate()` by `id` and `companyId`. Read `shipmentId`, `sourceDocumentId`, `status`.
+ 3. Read the ticked asset lines: `shipped = true`, `rentalAgreementLineId` not null. If none, throw `InvalidInputError("Select at least one unit to deliver")`.
+ 4. Lock the agreement with `lockAgreement(trx, companyId, sourceDocumentId)`. If it is not `Active`, refuse with the Task 7 agreement message.
+ 5. Lock the lines: `rentalAgreementLine` by id list, `companyId`, `forUpdate()`. Read `id`, `rentalAgreementId`, `status`, `fixedAssetId`, `trackedEntityId`.
+ 6. Read the assets: `fixedAsset` `id`, `fixedAssetId`, `name`, `outOfServiceSince`, `outOfServiceReason` by id list and `companyId`.
+ 7. For each line in asset-line order, build `label = unitLabel(asset, line.id)`.
+ 8. If a line is missing or belongs to another agreement, throw `NotFoundError("Rental agreement line not found")`.
+ 9. If a line is not `Pending`, throw `` `${label} is ${status}; only a Pending unit can be delivered` ``.
+ 10. If `outOfServiceSince` is set, throw `` `${label} is out of service: ${outOfServiceReason ?? "no reason given"}` ``.
+ 11. Update each line: `status: "On Rent"`, `deliveredAt: deliveredOn`, `meterOut: assetLine.meter`, `updatedBy`, `updatedAt: datetime.timestamp()`.
+ 12. For each line with a `trackedEntityId`, call `insertUnitActivity` with `type: "Rental Delivery"`, `direction: "input"`, `sourceDocument: "Shipment"`, the shipment ids, and `attributes: { Shipment: shipmentId, "Rental Agreement": agreement.id }`.
+ 13. Update the shipment: `status: "Posted"`, `postingDate: deliveredOn`, `postedBy: userId`.
+6. In `post-shipment/index.ts`, add before `default` (line 3038):
+
+ ```ts
+ case "Rental Agreement": {
+ await postRentalShipment(db, { shipmentId, companyId, userId, today, postingDate });
+ break;
+ }
+ ```
+
+7. Write no `itemLedger`, `costLedger` or journal row.
+8. Create `post-shipment/rental-agreement.test.ts`. Use `rentalFixture({ units: 5 })` and the Task 7 `create` case to make the shipment. Write these `databaseTest` cases:
+ 1. Untick 2 asset lines and set `meter` 120 on one ticked line. Post with `postingDate` = company today minus 3 days (`datetime.today("America/New_York").subtract({ days: 3 }).toString()`). Expect: 3 lines `On Rent` with that `deliveredAt`, one with `meterOut` 120, 2 lines `Pending`, the shipment `Posted` with that `postingDate`.
+ 2. In the same case, expect 0 `itemLedger`, 0 `costLedger` and 0 `journalLine` rows for `f.companyId`. Expect 3 `trackedActivity` rows of type `Rental Delivery`.
+ 3. A `postingDate` of today plus 1 day fails with `The delivery date cannot be in the future`. The shipment status is `Draft` afterwards.
+ 4. Set `outOfServiceSince` and `outOfServiceReason` = `Hydraulic leak` on one asset. The post fails, and the message contains `Hydraulic leak`.
+ 5. Set one ticked line `On Rent` by a direct update. The post fails, and the message contains `FA-` and `is On Rent`.
+ 6. Untick every line. The post fails with `Select at least one unit to deliver`.
+9. Add one more `databaseTest` for C1, the backdated accrual:
+ 1. Use `rentalFixture({ billingTiming: "Arrears" })`. Set both periods `Pending`.
+ 2. Post a shipment with `postingDate` `2026-09-25`.
+ 3. Call `synthesizeRentalAccruals` (exported from `../propose-revenue-recognition-run`) in a transaction with `periodEnd` `2026-10-31`. Expect no `Accrual` row with a `periodStart` in September.
+ 4. Call it again with `periodEnd` `2026-09-30`. Expect one `Accrual` row from `2026-09-25` to `2026-09-30`.
+10. Run `pnpm --filter @carbon/checks license-headers`.
+
+**Verify:**
+```bash
+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` — add `voidRentalShipment`
+- Modify: `packages/server-functions/src/post-shipment/index.ts` — new void case before `default` (line 4694)
+- Modify: `packages/server-functions/src/post-shipment/rental-agreement.test.ts` — void tests
+- Copy from (precedent): `post-shipment/index.ts:3487-3530` (the `Void Shipment` activity)
+
+**Steps:**
+1. Export from `rental-agreement.ts`:
+
+ ```ts
+ export async function voidRentalShipment(
+ db: Kysely<KyselyDatabase>,
+ args: { shipmentId: string; companyId: string; userId: string }
+ ): Promise<void>;
+ ```
+
+2. Write its body as one `db.transaction()`, in this order:
+ 1. Lock the shipment `forUpdate()`. Read the ticked asset lines (`shipped = true`, `rentalAgreementLineId` not null).
+ 2. Lock the agreement with `lockAgreement`.
+ 3. Lock the lines `forUpdate()`. Read the assets for labels, as Task 8 does.
+ 4. Read the `Accrual` rows of the lines from `revenueRecognitionSchedule`: `type = 'Accrual'`, `companyId`, line id list. Select `rentalAgreementLineId`, `status`, `runLineId`.
+ 5. For each unit, set `accrual` to `"Posted"` if a row is `Posted`. Else set it to `"Draft run"` if a `Planned` row has a `runLineId`. Else set it to null.
+ 6. If `rentalShipmentVoidBlocker(units)` returns a message, throw it as `InvalidInputError`.
+ 7. Delete the `Planned` `Accrual` rows of the lines that have no `runLineId`.
+ 8. Update each line: `status: "Pending"`, `deliveredAt: null`, `meterOut: null`, `updatedBy`, `updatedAt`.
+ 9. For each line with a `trackedEntityId`, call `insertUnitActivity` with `type: "Void Shipment"`, `direction: "input"`, `sourceDocument: "Shipment"`, and the Task 8 attributes.
+ 10. Update the shipment: `status: "Voided"`, `updatedBy`, `updatedAt: datetime.timestamp()`.
+3. In `post-shipment/index.ts`, add before the void `default` (line 4694):
+
+ ```ts
+ case "Rental Agreement": {
+ await voidRentalShipment(db, { shipmentId, companyId, userId });
+ break;
+ }
+ ```
+
+4. Add these `databaseTest` cases:
+ 1. Post, then void. Expect each delivered line `Pending` with `deliveredAt` null and `meterOut` null. Expect the shipment `Voided`.
+ 2. Post. Insert a `Posted` `Accrual` row for one delivered line. Read the NOT NULL columns of `revenueRecognitionSchedule` in `20261006220201_revenue-recognition-core.sql:205-235`. The void fails with `A posted revenue recognition run holds accrued rent for FA-`. The shipment stays `Posted`.
+ 3. Post. Set one delivered line `Returned` by a direct update. The void fails with `is Returned`.
+
+**Verify:**
+```bash
+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), `run` signature (line 66), void refusal (before line 280), new case before `default` (line 3553), import `InvalidInputError`
+- 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.ts` `returnUnit` wrapper (Task 5) for the lock order
+
+**Steps:**
+1. Change `postReceiptInput` to:
+
+ ```ts
+ 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()
+ });
+ ```
+
+2. Destructure `postingDate` in `run`.
+3. In the void block, after the `invoiced` check (`index.ts:274-279`), add:
+
+ ```ts
+ if (receiptHeader.sourceDocument === "Rental Agreement") {
+ throw new InvalidInputError(
+ "A rental return cannot be voided. Correct the unit by hand."
+ );
+ }
+ ```
+
+4. In `post-receipt/rental-agreement.ts`, export:
+
+ ```ts
+ export async function postRentalReceipt(
+ db: Kysely<KyselyDatabase>,
+ args: { receiptId: string; companyId: string; userId: string; today: string; postingDate?: string }
+ ): Promise<void>;
+ ```
+
+5. Write its body as one `db.transaction()`, in this order:
+ 1. Set `returnedAt = postingDate ?? today`. If `futureReturnError(returnedAt, today)` returns a message, throw it as `InvalidInputError`.
+ 2. Lock the receipt `forUpdate()`. Read `receiptId`, `sourceDocumentId`, `locationId`.
+ 3. Read the ticked asset lines: `received = true`, `rentalAgreementLineId` not null. Read `meter`, `notes`, `takeOutOfService`, `outOfServiceReason`, `residualDestination`. If none, throw `InvalidInputError("Select at least one unit to return")`.
+ 4. Lock the agreement with `lockAgreement`. If it is not `Active`, refuse with the Task 5 wrapper message.
+ 5. Read the lines (`id`, `status`, `lessorClassification`, `trackedEntityId`) and the assets for labels.
+ 6. If `receiptReturnError(label, line.status)` returns a message, throw it as `InvalidInputError`. A receipt returns a `Pending` or an `On Rent` unit (spec Q8).
+ 7. Parse each unit with `unitReturnValidator` (Task 6): `rentalAgreementLineId`, `returnedAt`, `meterIn: meter`, `returnNotes: notes`, `takeOutOfService`, `outOfServiceReason`, `residualDestination`. On a parse error, throw `` `${label}: ${firstIssueMessage}` `` as `InvalidInputError`.
+ 8. Call `returnRentalUnit(trx, { agreement, unit, companyId, userId, today, locationId: receipt.locationId ?? undefined })` for each unit (spec Q7).
+ 9. If the result's `fixedAssetId` is set and the receipt has a `locationId`, update that `fixedAsset`: `locationId`, `updatedBy`, `updatedAt`. This also covers a `Pending` unit.
+ 10. If the line is `Rental` and has a `trackedEntityId`, call `insertUnitActivity` with `type: "Rental Return"`, `direction: "output"`, `sourceDocument: "Receipt"`, and `attributes: { Receipt: receiptId, "Rental Agreement": agreement.id }`.
+ 11. Update the receipt: `status: "Posted"`, `postingDate: returnedAt`, `postedBy: userId`.
+6. In `post-receipt/index.ts`, add before `default` (line 3553):
+
+ ```ts
+ case "Rental Agreement": {
+ await postRentalReceipt(db, { receiptId, companyId, userId, today, postingDate });
+ break;
+ }
+ ```
+
+7. Create `post-receipt/rental-agreement.test.ts`. Use `rentalFixture({ units: 3 })`. Set the 3 lines `On Rent` with `deliveredAt` `2026-09-01`. Write these `databaseTest` cases:
+ 1. Create a receipt with the Task 7 case. Untick 2 lines. On the ticked line set `meter` 130, `takeOutOfService` true, `outOfServiceReason` `Hydraulic leak`. Set the receipt `locationId` to `f.otherLocationId`. Post with `postingDate` `2026-09-20`.
+ 2. In the same case, expect these 5 facts:
+ - the line is `Returned`, with `returnedAt` `2026-09-20` and `meterIn` 130
+ - the asset `locationId` is `f.otherLocationId`
+ - `fleetAssets.fleetStatus` is `In Maintenance`
+ - 1 `Rental Return` activity exists
+ - the receipt is `Posted`, with `postingDate` `2026-09-20`
+ 3. Untick every line. The post fails with `Select at least one unit to return`, and the receipt is `Draft` afterwards.
+ 4. Post a receipt, then call with `type: "void"`. It fails with `A rental return cannot be voided. Correct the unit by hand.` The receipt stays `Posted`.
+ 5. A `Sale` line: set `lessorClassification` `Sale` and `initialNetInvestment` 1000 on one line. Leave `residualDestination` null. The post fails, and the message names the missing destination (the `salesTypeReturnError` text).
+ 6. The same `Sale` line with `residualDestination` `Inventory`, `endDate` `2026-09-20` on the agreement, and an `itemCost` row for the item. Set the receipt `locationId` to `f.otherLocationId` (spec Q7). Expect 1 `itemLedger` row: `entryType` `Positive Adjmt.`, `documentType` `Rental Agreement`, quantity 1, `locationId` = `f.otherLocationId`.
+ 7. A `Pending` unit (spec Q8). Use `rentalFixture({ units: 2 })`. Set line 1 `On Rent` with `deliveredAt` `2026-09-01`. Leave line 2 `Pending`.
+ 1. Create a receipt. Expect line 2's asset line with `received = false`.
+ 2. Post with `postingDate` `2026-09-20`. Expect line 1 `Returned` and line 2 still `Pending`.
+ 3. Create a second receipt. Tick line 2. Post with `postingDate` `2026-09-25`.
+ 4. Expect line 2 `Returned` with `returnedAt` `2026-09-25`. Expect no `Pending` billing period of line 2 that starts after `2026-09-25`.
+8. If case 6 needs more setup than an `itemCost` row (for example a lease schedule), STOP and report.
+9. In `return-unit.test.ts`, change only `returnUnitOnSeptember20`:
+ 1. Create a receipt with the Task 7 case and `rentalAgreementLineId`.
+ 2. Post it with `postingDate` `2026-09-20`.
+ 3. Keep the test name and every assertion.
+10. Run `pnpm --filter @carbon/checks license-headers`.
+
+**Verify:**
+```bash
+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-1764` before Task 5)
+- Create: `packages/server-functions/src/post-rental-agreement/close.test.ts`
+
+**Steps:**
+1. In `close`, after the `Active` check and BEFORE `loadSettlementState`, read the first open shipment with a line:
+
+ ```ts
+ 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();
+ ```
+
+2. Read `openReceipt` the same way from `receipt` and `receiptFixedAssetLine`.
+3. Throw `openRentalDocumentBlocker({ shipmentId: openShipment?.shipmentId ?? null, receiptId: openReceipt?.receiptId ?? null })` as `InvalidInputError` when it returns a message.
+4. Create `close.test.ts` with one `databaseTest`:
+ 1. Use `rentalFixture()`. Set the line `On Rent`.
+ 2. Create a receipt with the Task 7 case.
+ 3. Call the default export of `./index` with `{ type: "close", rentalAgreementId }`.
+ 4. Expect the error message to contain `Receipt RCV-` and `is still open`.
+
+**Verify:**
+```bash
+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 after `getShipmentTracking` (`:1423`)
+- Modify: `apps/erp/app/modules/inventory/types.ts` — 2 types
+- Modify: `apps/erp/app/modules/sales/sales.service.ts` — 1 read after `getRentalAgreementDeposits` (`:9582`)
+- Modify: `apps/erp/app/modules/sales/sales.utils.ts` and `sales.utils.test.ts` — `rentalLineDocuments`
+- Copy from (precedent): `inventory.service.ts:1423-1433` (`getShipmentTracking`), `sales.service.ts:1777-1834` (`getSalesOrderRelatedItems`)
+
+**Steps:**
+1. Add `"Rental Agreement"` to `receiptSourceDocumentType` and to `shipmentSourceDocumentType`.
+2. Add these validators to `inventory.models.ts`:
+
+ ```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"]) })
+ ]);
+ ```
+
+3. Add tests to `inventory.models.test.ts`: a meter of `-1` fails, `""` and `"120"` pass, an unknown `field` fails.
+4. Add to `inventory.service.ts`:
+
+ ```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");
+ }
+ ```
+
+5. Add `getRentalReceiptLines` with the same shape. It reads `receiptFixedAssetLine` with `received`, `meter`, `notes`, `takeOutOfService`, `outOfServiceReason`, `residualDestination`, and the embed through `receiptFixedAssetLine_rentalAgreementLineId_fkey`.
+6. If PostgREST refuses the embed of `fixedAsset`, `item` or `trackedEntity` from `rentalAgreementLine`, name its FK. Copy the name from `packages/database/src/types.ts`.
+7. Add to `inventory/types.ts`:
+
+ ```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;
+ };
+ ```
+
+8. Add to `sales.service.ts`:
+
+ ```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
+ };
+ }
+ ```
+
+9. Add to `sales.utils.ts`:
+
+ ```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;
+ };
+ ```
+
+10. Add 3 tests to `sales.utils.test.ts`: no documents, a Posted shipment with the unit ticked, a Draft shipment ignored.
+11. Regenerate the MCP manifest digest.
+
+**Verify:**
+```bash
+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 before `default` (line 271)
+- Modify: `apps/erp/app/routes/x+/receipt+/new.tsx` — new case before `default` (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` (the `Sales Return Order` branch)
+
+**Steps:**
+1. In `shipment+/new.tsx`, add `case "Rental Agreement":`. Copy `receipt+/new.tsx:56-111` with these changes:
+ - The Draft lookup reads `shipment` with `.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"`.
+2. In `receipt+/new.tsx`, add the same case with `receipt`, `receiptFromRentalAgreement`, `path.to.receiptDetails` and `"Failed to create receipt"`.
+3. In `$shipmentId.details.tsx`, before `if (shipmentDataHasChanged)`, add:
+
+ ```ts
+ 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."))
+ );
+ }
+ ```
+
+4. Change `if (shipmentDataHasChanged)` to `if (shipmentDataHasChanged && !isRental)`. A location change on a rental shipment then saves through `upsertShipment`.
+5. Add `| "Rental Agreement"` to the cast at lines 278-281.
+6. Do steps 3–5 in `$receiptId.details.tsx`. Use the text `"A rental receipt keeps its rental agreement. Create it from the agreement."`.
+
+**Verify:**
+```bash
+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, return `rentalLines` (lines 106-116)
+- Modify: `apps/erp/app/routes/x+/receipt+/$receiptId.tsx` — rental branch after line 132, return `rentalLines` (lines 134-154)
+- Modify: `apps/erp/app/routes/x+/shipment+/fixed-asset-lines.update.tsx` — validator and `meter`
+- 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:**
+1. In `$shipmentId.tsx`, declare `let rentalLines: RentalShipmentLine[] = [];`.
+2. If `shipment.data.sourceDocument === "Rental Agreement"`, call `getRentalShipmentLines(getCarbonServiceRole(), shipmentId, companyId)`. Use the service role: `rentalAgreementLine` needs `sales_view`, which an inventory user may not hold.
+3. On an error, redirect to `path.to.shipments` with the flash `"Failed to load the rental units"`.
+4. Map each row:
+
+ | Field | Value |
+ |-------|-------|
+ | `rentalAgreementLineId` | `row.rentalAgreementLineId!` |
+ | `unitName` | `fixedAsset?.name ?? item?.name ?? "Rental unit"` |
+ | `assetReadableId` | `fixedAsset?.fixedAssetId ?? null` |
+ | `serialNumber` | `fixedAsset?.serialNumber ?? trackedEntity?.readableId ?? null` |
+ | `lineStatus` | `rentalAgreementLine.status` |
+ | `meter` | `row.meter === null ? null : Number(row.meter)` |
+
+5. Return `rentalLines` with the other loader values.
+6. Do steps 1–5 in `$receiptId.tsx` with `getRentalReceiptLines` and `RentalReceiptLine`. Map the 5 receipt fields and `lessorClassification` as they are.
+7. In `shipment+/fixed-asset-lines.update.tsx`, parse `Object.fromEntries(await request.formData())` with `shipmentFixedAssetLineUpdateValidator.safeParse`.
+8. On a parse failure, return `data({ error: parsed.error.issues[0]?.message }, { status: 400 })`.
+9. Build the update from the parsed field:
+
+ | `field` | Update |
+ |---------|--------|
+ | `shipped` | `{ shipped: value === "true" }` |
+ | `serialNumber` | `{ serialNumber: value || null }` |
+ | `meter` | `{ meter: value === "" ? null : Number(value) }` |
+
+10. Keep the existing service-role write with `.eq("id", id).eq("companyId", companyId)`. Add `updatedBy: userId` to the update.
+11. In `receipt+/fixed-asset-lines.update.tsx`, do steps 7–10 with `receiptFixedAssetLineUpdateValidator` and this map:
+
+ | `field` | Update |
+ |---------|--------|
+ | `received` | `{ received: value === "true" }` |
+ | `serialNumber` | `{ serialNumber: value || null }` |
+ | `meter` | `{ meter: value === "" ? null : Number(value) }` |
+ | `notes` | `{ notes: value.trim() || null }` |
+ | `outOfService` | `value.trim() === "" ? { takeOutOfService: false, outOfServiceReason: null } : { takeOutOfService: true, outOfServiceReason: value.trim() }` |
+ | `residualDestination` | `{ residualDestination: value || null }` |
+
+**Verify:**
+```bash
+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` — read `postingDate` (near line 50), pass it (lines 372-377)
+- Modify: `apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx` — read `postingDate` (near line 37), pass it (lines 221-225)
+
+**Steps:**
+1. In `$shipmentId.post.tsx`, after the `acknowledged` read, add:
+
+ ```ts
+ const postingDateValue = formData.get("postingDate");
+ const postingDate =
+ typeof postingDateValue === "string" && postingDateValue !== ""
+ ? postingDateValue
+ : undefined;
+ ```
+
+2. Change the invoke to `{ type: "post", shipmentId, postingDate }`.
+3. Do steps 1–2 in `$receiptId.post.tsx`. The invoke becomes `{ receiptId, postingDate }`.
+4. Leave the rule evaluation as it is. A rental document has no `shipmentLine` or `receiptLine` rows, so the storage and sales rules see no lines.
+
+**Verify:**
+```bash
+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:**
+1. Replace the whole action of `$id.$lineId.deliver.tsx` with:
+
+ ```ts
+ 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));
+ }
+ ```
+
+2. Replace the action of `$id.$lineId.return.tsx` the same way with `receiptFromRentalAgreement`, `path.to.receiptDetails` and `"Failed to create the receipt"`. The `create` case accepts a `Pending` or an `On Rent` unit 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 `11a7a60999` with `git show`.
+3. Remove the imports that the old actions used and the new ones do not.
+4. In `$id.tsx`, add `getRentalAgreementRelatedDocuments(client, id, companyId)` to the `Promise.all` at lines 65-83.
+5. Return `shipments: related.data.shipments` and `receipts: related.data.receipts` from the loader. On `related.error`, keep the empty lists and do not fail the page.
+6. In `types.ts`, add to `RentalAgreementRouteData`:
+
+ ```ts
+ shipments: RentalAgreementShipment[];
+ receipts: RentalAgreementReceipt[];
+ ```
+
+7. Derive the two types from `getRentalAgreementRelatedDocuments`:
+
+ ```ts
+ type RelatedDocuments = NonNullable<
+ Awaited<ReturnType<typeof getRentalAgreementRelatedDocuments>>["data"]
+ >;
+ export type RentalAgreementShipment = RelatedDocuments["shipments"][number];
+ export type RentalAgreementReceipt = RelatedDocuments["receipts"][number];
+ ```
+
+**Verify:**
+```bash
+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:**
+1. Add `rentalLines: RentalShipmentLine[]` to the route-data type in `ShipmentLines.tsx`.
+2. Set `const isRental = routeData?.shipment?.sourceDocument === "Rental Agreement";`.
+3. Render the "Shipment Lines" card (lines 238-299) only when `!isRental`.
+4. Add a "Rental Units" card after the "Fixed Assets" card. Copy the card at lines 300-324. It renders `ShipmentRentalLineItem` for each `rentalLines` row.
+5. Create `ShipmentRentalLineItem` in the same file. Copy `ShipmentFixedAssetLineItem` (lines 330-395) with these changes:
+ - It shows the `shipped` checkbox, `unitName`, then `assetReadableId` and `serialNumber` in small muted text.
+ - It has no serial `Input`, no storage-unit picker and no tracking form.
+ - It shows a `NumberField` labelled "Meter". It submits `field` `meter` on blur when the value changed. An empty field sends `""`.
+6. In `ShipmentHeader.tsx`, read `rentalLines` from the same route data. `canPost` is also true when a `rentalLines` row has `shipped`.
+7. In `ShipmentPostModal.tsx`, add `rentalLines: { id: string; shipped: boolean }[]` to the route data.
+8. Treat a ticked rental line as "not empty" in the check at lines 119-134.
+9. If the source is `Rental Agreement`, render a `DatePicker` from `@carbon/react` above the alerts:
+ - label "Delivered on"
+ - `value={parseDate(postingDate)}`, with `const companyToday = useCompanyToday();` and `const [postingDate, setPostingDate] = useState(companyToday);`
+ - `maxValue={parseDate(companyToday)}`
+ - `onChange={(d) => d && setPostingDate(d.toString())}`
+10. In the submit (lines 350-354), build a `FormData`. Set `postingDate` on it only for a rental shipment.
+11. Import `useCompanyToday` from `~/hooks`. Import `parseDate` from `@internationalized/date`, which the file already imports.
+12. Wrap every new visible string in `<Trans>` or `` t`…` ``.
+
+**Verify:**
+```bash
+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` (`RadioGroup` from `@carbon/react`)
+
+**Steps:**
+1. Add `rentalLines: RentalReceiptLine[]` to the route-data type. Set `isRental` as Task 17 does.
+2. Render the "Receipt Lines" card only when `!isRental`. Add a "Rental Units" card that renders `ReceiptRentalLineItem`.
+3. Create `ReceiptRentalLineItem`. Copy `ReceiptFixedAssetLineItem`. It shows these controls, each saved through `path.to.receiptFixedAssetLineUpdate`:
+
+ | Control | `field` | Saves |
+ |---------|---------|-------|
+ | `received` checkbox | `received` | on change |
+ | "Meter" `NumberField` | `meter` | on blur, when changed |
+ | "Notes" `Textarea` | `notes` | on blur, when changed |
+ | "Take out of service" `Checkbox` plus a "Reason" `Input` | `outOfService` | unticking sends `""` at once; ticking shows the input, and a non-empty reason saves on blur |
+ | "Return To" `RadioGroup` (Fleet / Inventory), only when `lessorClassification === "Sale"` | `residualDestination` | on change |
+
+4. 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".
+5. If `lineStatus === "Pending"`, show a `Badge` "Not delivered" next to the unit name (spec Q8). The `create` case leaves such a row unticked.
+6. In `ReceiptHeader.tsx`, `canPost` is also true when a `rentalLines` row has `received`.
+7. In `ReceiptPostModal.tsx`, add `rentalLines` to the route data. Treat a received rental line as "not empty".
+8. For each received rental line with `lessorClassification === "Sale"` and no `residualDestination`, add a validation error: `` t`Choose Return To for ${unitName}` ``. The existing errors list disables the Post button.
+9. Add the date field as Task 17 step 9 does, with the label "Returned on".
+10. Set `postingDate` on the submitted `FormData` only for a rental receipt.
+
+**Verify:**
+```bash
+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` (the `Sales Order` link case), `ShipmentDocuments.tsx:94-105` (the `Sales Return Order` case)
+
+**Steps:**
+1. In both tables, add `case "Rental Agreement":`. It renders a `Hyperlink` to `path.to.rentalAgreementDetails(row.original.sourceDocumentId!)` with `sourceDocumentReadableId`.
+2. In `useShipmentForm.tsx` and `useReceiptForm.tsx`, add `case "Rental Agreement": break;`. The initial option already holds the agreement's readable id.
+3. In `ShipmentForm.tsx`, set `const isRental = initialValues.sourceDocument === "Rental Agreement";`.
+4. Filter the `Select` options: drop `"Rental Agreement"` unless `isRental`.
+5. Set `isReadOnly={isPosted || isRental}` on the source `Select` and the source `Combobox`.
+6. Do steps 3–5 in `ReceiptForm.tsx`.
+7. In `ShipmentDocuments.tsx`, add `"Rental Agreement"` to `PACKING_SLIP_SOURCES`.
+8. In both `useSourceDocument` switches, add a `"Rental Agreement"` case. Copy the `Sales Return Order` case. Link to `path.to.rentalAgreementDetails(id)`, gate on `permissions.can("view", "sales")`, and use the label "Rental Agreement".
+9. In `ReceiptDocuments.tsx` line 165, hide the supplier row for a rental receipt too: `const isSalesReturn = … || receipt.sourceDocument === "Rental Agreement"`. If that variable also gates `ReturnCustomerRow` (lines 433-438), use a second variable for the supplier row only.
+10. In `sourceLinkHref`, add this case before `default`:
+
+ ```ts
+ case "Rental Agreement":
+ return `/x/rental-agreement/${id}/details`;
+ ```
+
+**Verify:**
+```bash
+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`, `rentalUnits` on `PackingSlipData`
+- 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 before `default` (line 596)
+- Copy from (precedent): `$id[.]pdf.tsx:123-240` (the `Sales Order` case)
+
+**Steps:**
+1. In `types.ts`, export:
+
+ ```ts
+ export type PackingSlipRentalUnit = {
+ id: string;
+ name: string;
+ assetReadableId: string | null;
+ serialNumber: string | null;
+ };
+ ```
+
+2. Add `title: string` and `rentalUnits?: PackingSlipRentalUnit[]` to `PackingSlipData`.
+3. In `HeaderBlock.tsx`, change `title="Packing Slip"` to `title={data.title}`.
+4. In `PackingSlipPDF.tsx`, add `rentalUnits?: PackingSlipRentalUnit[]` to `PackingSlipProps`. Put `title` and `rentalUnits` into `data`.
+5. In `LineItemsBlock.tsx`, if `data.rentalUnits` has rows, render one row per unit and return:
+ - Description column: `name`, then `assetReadableId` in the small grey text.
+ - Qty column: `1`.
+ - A `Serial` column: `serialNumber`.
+ - Use the same zebra and border styles as the shipment rows.
+6. In `$id[.]pdf.tsx`, add `case "Rental Agreement":`. Copy the `Sales Order` case with these changes:
+ - Read the agreement with `getRentalAgreement(serviceRole, shipment.data.sourceDocumentId, companyId)`.
+ - Read the customer and the customer location from `rentalAgreement.customerId` and `customerLocationId`.
+ - Read the units with `getRentalShipmentLines(serviceRole, id, companyId)`. Keep only `shipped` rows. Map them with the Task 14 rules to `PackingSlipRentalUnit`.
+ - Pass `sourceDocument="Rental Agreement"`, `sourceDocumentId={rentalAgreement.rentalAgreementId}`, `title="Delivery Ticket"`, `rentalUnits`, `trackedEntities={[]}`.
+ - Set the PDF meta subject to "Delivery Ticket".
+ - Pass `paymentTerm` and `shippingMethod` the way the `Outbound Transfer` case does (lines 483-595) when the agreement has none.
+7. Pass `title="Packing Slip"` explicitly in every other case, so `data.title` is always set.
+
+**Verify:**
+```bash
+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 the `HStack` at line 190)
+- Modify: `apps/erp/app/routes/x+/rental-agreement+/$id.tsx` — pass `shipments` and `receipts` to 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:**
+1. Add `"shipments" | "receipts"` to the `Pick` in `RentalAgreementHeaderProps`. Pass both from `$id.tsx`.
+2. Add `const submit = useSubmit();` and these two functions. Copy the shape of `SalesReturnOrderHeader.tsx:77-89`:
+ - `deliver()` posts `sourceDocument` `Rental Agreement` and `sourceDocumentId` `id` to `path.to.newShipment`.
+ - `returnUnits()` posts the same to `path.to.newReceipt`.
+3. Set these flags:
+
+ ```ts
+ const canMoveUnits = canUpdate && permissions.can("create", "inventory");
+ const hasPendingUnit = lines.some((line) => line.status === "Pending");
+ const hasUnitOnRent = …; // already exists at line 85
+ ```
+
+4. Before the Invoice button, render the delivery control when `isActive && canMoveUnits`:
+ - If `shipments.length === 0`, render a `Button` "Deliver" with `LuTruck`, disabled when `!hasPendingUnit`. It calls `deliver()`.
+ - Else render a "Shipments" `DropdownMenu`. Copy `SalesOrderHeader.tsx:506-555`. "New Shipment" is disabled when `!hasPendingUnit` and calls `deliver()`. Each shipment row links to `path.to.shipment(shipment.id)` and shows `ShipmentStatus`.
+5. After it, render the return control the same way:
+ - "Return" with `LuPackageCheck`, disabled when `!hasUnitOnRent && !hasPendingUnit`, calls `returnUnits()`. A receipt also holds `Pending` units (spec Q8).
+ - The "Receipts" dropdown has "New Receipt", disabled on the same rule, and links to `path.to.receipt(receipt.id)` with `ReceiptStatus`.
+6. Import `ShipmentStatus` from `~/modules/inventory/ui/Shipments` and `ReceiptStatus` from `~/modules/inventory/ui/Receipts`.
+7. Use the variant `primary` for Deliver when `hasPendingUnit`, else `secondary`. Use `secondary` for Return.
+
+**Verify:**
+```bash
+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` — replace `returnValidator` with `releaseValidator`
+- Modify: `packages/server-functions/src/post-rental-agreement/validators.test.ts` — replace the `type: "return"` tests
+- Modify: `packages/server-functions/src/post-rental-agreement/index.ts` — replace `case "return"` and the `returnUnit` wrapper; header comment (lines 60-81)
+- Create: `packages/server-functions/src/post-rental-agreement/release.test.ts`
+- Copy from (precedent): the `returnUnit` wrapper written in Task 5, and the open-document query of Task 11
+
+**Steps:**
+1. Run `grep -rn 'type: "return"' apps/erp/app packages/jobs/src`. If a caller still sends `type: "return"` to `post-rental-agreement`, STOP and report. (`post-asset-transfer` also has a `return` type; ignore its callers.)
+2. In `validators.ts`, delete `returnValidator`. Keep `unitReturnFields` and `unitReturnValidator`. Keep the out-of-service refine on `unitReturnValidator`.
+3. Add and export, then put it into `payloadValidator` in place of `returnValidator`:
+
+ ```ts
+ /** 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
+ });
+ ```
+
+4. Keep `RETURNABLE_LINE_STATUSES`. `returnRentalUnit` and `receiptReturnError` use it.
+5. In `index.ts`, replace the `returnUnit` wrapper with `releaseUnit`. Write its body in this order:
+ 1. If `futureReleaseError(payload.returnedAt, today)` returns a message, throw it as `InvalidInputError`.
+ 2. Open `db.transaction()`. Lock the agreement with `lockAgreement`.
+ 3. If the agreement is not `Active`, throw `` `Rental agreement ${agreement.rentalAgreementId} is ${agreement.status}; units are released from an Active agreement` ``.
+ 4. Read the line `forUpdate()`: `id`, `status`, `lessorClassification`, `fixedAssetId`, by `id`, `rentalAgreementId = agreement.id` and `companyId`. If none, throw `NotFoundError("Rental agreement line not found")`.
+ 5. Read the asset (`fixedAssetId`, `name`) for `unitLabel`.
+ 6. Find the first open document that holds the line. Copy the Task 11 queries and add `.where("l.rentalAgreementLineId", "=", line.id)`. Set `openDocument` to `` `shipment ${shipmentId}` ``, else `` `receipt ${receiptId}` ``, else null.
+ 7. If `releaseBlocker({ label, status, classification, openDocument })` returns a message, throw it as `InvalidInputError`.
+ 8. Call `returnRentalUnit(trx, { agreement, unit: { rentalAgreementLineId: line.id, returnedAt: payload.returnedAt }, companyId, userId, today })`. Pass no `locationId`, no meter, no notes and no out-of-service fields.
+ 9. Return `{ id: agreement.id }`.
+6. In the dispatch, replace `case "return"` with `case "release"`. It computes `today` exactly as the old case did and calls `releaseUnit`.
+7. Release passes no residual destination. So a `Sale` line can never pass `salesTypeReturnError`. Step 5.7 refuses it first with a clear message (plan decision P1).
+8. In the header comment, replace the `return` paragraph with these 2 lines:
+ - "A unit comes back through a rental receipt (`post-receipt`), which calls `returnRentalUnit`."
+ - "release: a Pending unit that never left the yard stops billing at the release date and is free again."
+9. Update the doc comment above `postRentalAgreement` (`/** Activates, returns a unit of, closes or cancels …`): it activates, releases a unit of, closes or cancels.
+10. In `validators.test.ts`, delete each test that parses `type: "return"`. Add 2 `release` tests: it needs the line id and a `YYYY-MM-DD` date; it strips `meterIn`.
+11. Create `release.test.ts`. Use `rentalFixture()` from Task 4 (the line is `Pending`, Advance billing, September invoiced, October pending). Write these `databaseTest` cases:
+ 1. Release with `returnedAt` `2026-09-20`. Expect the line `Returned` with `returnedAt` `2026-09-20`. Expect no `Pending` period that starts after `2026-09-20`. Expect 1 `isAdjustment` row. Expect `fleetAssets.fleetStatus` = `Available`. Expect `fixedAsset.locationId` unchanged.
+ 2. Set the line `On Rent`. The release fails with `is On Rent; only a Pending unit can be released`.
+ 3. A `returnedAt` of company today plus 1 day fails with `The release date cannot be in the future`.
+ 4. Set `lessorClassification` `Sale`. The release fails with `is treated as a sale; return it on a rental receipt instead`.
+ 5. Create a Draft shipment with the Task 7 case. The release fails with `is on shipment SHP-`.
+
+**Verify:**
+```bash
+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` — add `rentalAgreementLineRelease` after `rentalAgreementLineReturn` (lines 2174-2175)
+- Create: `apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.release.tsx`
+- Modify: `apps/erp/app/modules/sales/sales.models.ts` — replace `rentalAgreementReturnValidator` (lines 1528-1566) with `rentalAgreementReleaseValidator`
+- 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 commit `11a7a60999`, before Task 16), `SalesReturnOrderHeader.tsx:77-89` (submit)
+
+**Steps:**
+1. In `path.ts`, add:
+
+ ```ts
+ rentalAgreementLineRelease: (id: string, lineId: string) =>
+ generatePath(`${x}/rental-agreement/${id}/${lineId}/release`),
+ ```
+
+2. In `sales.models.ts`, replace `rentalAgreementReturnValidator` with:
+
+ ```ts
+ 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" })
+ });
+ ```
+
+3. Keep `rentalResidualDestinations`. Task 12's receipt validator and Task 18 use it.
+4. Create `$id.$lineId.release.tsx`. Copy the old return route from `git show`. Change it like this:
+ - Permissions: `{ update: "sales" }`.
+ - Validate with `rentalAgreementReleaseValidator`.
+ - Drop the line re-read and the `isSalesType` branch. 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.
+5. Run `git mv` to rename the form to `RentalAgreementReleaseForm.tsx`. Rename the component and its props type.
+6. In the form, keep the `ValidatedForm`, the fetcher, the `Hidden` line id and the `DatePicker`. Delete the meter, notes, out-of-service and Return To fields and the `isSalesType` hidden field.
+7. Set the `DatePicker` label to "Release date". Pass `maxValue={parseDate(today)}`, with `today` from `useCompanyToday()`.
+8. 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".
+9. Update `index.ts` to import and export `RentalAgreementReleaseForm`.
+10. In `useRentalLineActions.tsx`:
+ 1. Add `"release"` to `RentalLineAction`. Add `canRelease` and `releaseDisabled` to `RentalLineActionState`.
+ 2. Set `canReturn = isActive && (line.status === "On Rent" || line.status === "Pending")` (spec Q8).
+ 3. Set `canRelease = isActive && line.status === "Pending" && line.lessorClassification !== "Sale"` (plan decision P1).
+ 4. Set `canSell` on `isActive && line.status === "On Rent"`, not on `canReturn`, so a `Pending` unit is never offered Sell.
+ 5. Set `const canMoveUnits = canUpdate && permissions.can("create", "inventory")`. Set `deliverDisabled` and `returnDisabled` to `!canMoveUnits`. Set `releaseDisabled` to `!canUpdate`.
+ 6. Make `open("deliver", line)` call `submit(new FormData(), { method: "post", action: path.to.rentalAgreementLineDeliver(id, line.id) })`. Use `useSubmit` from `react-router`.
+ 7. Make `open("return", line)` post the same way to `path.to.rentalAgreementLineReturn(id, line.id)`.
+ 8. Make `open("release", line)` set the pending action, as `sell` does.
+ 9. Delete the Deliver `Confirm` and the return modal. Add a modal for `"release"`: `RentalAgreementReleaseForm` with `action={path.to.rentalAgreementLineRelease(id, pending.line.id)}` and `initialValues={{ rentalAgreementLineId: pending.line.id, returnedAt: today }}`.
+ 10. Update the hook's doc comment: Deliver and Return open a document; Release unit opens a date modal.
+11. In `RentalAgreementLineSummary.tsx`, add a "Release unit" `Button` after the Return button. Show it when `state.canRelease`. Use `variant="secondary"`, `leftIcon={<LuCircleSlash />}` and `isDisabled={state.releaseDisabled}`.
+12. In `RentalAgreementExplorer.tsx`, add a "Release unit" `DropdownMenuItem` after the Return item, with the same rule.
+13. In `RentalAgreementSummary.tsx` and `RentalAgreementLineSummary.tsx`, read `shipments` and `receipts` from `useRouteData<RentalAgreementRouteData>(path.to.rentalAgreement(id))`.
+14. Call `rentalLineDocuments(line.id, shipments, receipts)` for each unit.
+15. In `SummaryLine`, show a `Link` to `path.to.shipment(shipment.id)` labelled with `shipmentId`, and one to `path.to.receipt(receipt.id)` labelled with `receiptId`, when each exists.
+16. In `RentalAgreementLineSummary`, put the same links next to the "Delivered" and "Returned" dates.
+17. If `grep -rn "rentalAgreementReturnValidator\|RentalAgreementReturnForm" apps/erp/app` finds a user, STOP and report.
+
+**Verify:**
+```bash
+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:**
+1. Run `pnpm --filter @carbon/checks license-headers`.
+2. Run each command below in order.
+3. Fix a failure only when its cause is a file this plan changed. Otherwise STOP and report.
+
+**Verify:**
+```bash
+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 `/translate` skill only
+
+**Steps:**
+1. Run `pnpm lingui:extract`.
+2. Invoke the `/translate` skill to fill the empty `msgstr` entries.
+3. Run `pnpm lingui:clean`.
+
+**Verify:**
+```bash
+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` — the `post-rental-agreement` mention (around line 134)
+- Modify: `.claude/rules/shipments-receipts-ui-patterns.md` — the rental source and `PACKING_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.mdx` and `docs/content/docs/reference/receipts.mdx` — the source document field
+
+Do not edit the spec. It already carries the planning corrections.
+
+**Steps:**
+1. Load the `carbon-docs` skill before you edit an `.mdx` file.
+2. In `sales/AGENTS.md`, state these facts:
+ - Deliver and Return go through a rental shipment and a rental receipt (`create` types `shipmentFromRentalAgreement` / `receiptFromRentalAgreement`).
+ - `post-shipment` and `post-receipt` own the `Rental Agreement` source. They take an optional `postingDate`.
+ - `$id.$lineId.deliver` / `return` are shortcuts that open a one-unit document. They need `update: sales` and `create: inventory`.
+ - `returnRentalUnit` (`post-rental-agreement/return-unit.ts`) holds the return body. It takes an optional `locationId`: a rental receipt passes its own location, so a `Sale` line's residual lands there (spec Q7).
+ - A rental receipt holds every `On Rent` unit ticked and every `Pending` unit unticked (spec Q8).
+ - `post-rental-agreement` has no `return` type. Its `release` type ends a `Pending` unit with no document. It refuses a `Sale` line 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.
+3. In `inventory/AGENTS.md`, add `Rental Agreement` to both source lists. Describe `rentalAgreementLineId`, `meter` and the receipt condition columns on the fixed-asset line tables.
+4. In `server-functions/AGENTS.md`, list `post-rental-agreement` as `activate` / `release` / `close` / `cancel` if the file lists its types.
+5. In the two rules files, replace the old Deliver route facts with the document flow.
+6. 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.
+7. In `shipments.mdx` and `receipts.mdx`, add the rental agreement to the source document field. State that a rental unit posts no inventory or journal entry.
+8. Note for the release: the changelog entry, written later with `/changelog-entry`, must say that delivery now needs inventory create permission.
+
+**Verify:**
+```bash
+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 `/test` skill only
+
+**Steps:**
+1. Ask the user for permission to drive the browser.
+2. Invoke the `/test` skill with this plan's acceptance table below as the test list.
+3. Use the `/auth` skill to sign in.
+4. Set up an Active agreement with 5 serial fleet units. Use the agreement setup wizard, or `pnpm db:seed:dev` data if it has rentals.
+5. For the release rows, use a second Active agreement with 1 `Pending` unit. Release it with a date 2 days ago. Then check the Billing Periods card and the fleet register.
+6. Run each row of the coverage table that names Task 27.
+7. On any failure, use the `/error` skill and STOP. Report the row and the screenshot path.
+
+**Verify:**
+```text
+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
+
+- [x] 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".
+- [x] Every task has exact paths, exact commands and an expected output.
+- [x] Both migration tasks follow the hard rules, and Task 3 runs `generate:types` after them.
+- [x] Every UI task names its precedent file.
+- [x] No whole-repo typecheck.
+- [x] Every acceptance criterion maps to a task, and the last task is browser verification through `/test`.
diff --git a/.ai/playbooks/rental-shipments-and-receipts.md b/.ai/playbooks/rental-shipments-and-receipts.md
new file mode 100644
index 0000000000..d2d19526cb
--- /dev/null
+++ b/.ai/playbooks/rental-shipments-and-receipts.md
@@ -0,0 +1,44 @@
+# Rental Shipments and Receipts
+
+Last tested: 2026-10-08
+Routes: /x/rental-agreement/:id/details, /x/rental-agreement/:id/:lineId/details,
+/x/shipment/:id/details, /x/receipt/:id/details, /x/inventory/shipments,
+/x/accounting/fleet, /file/shipment/:id.pdf, /x/fixed-asset/:id/sell
+
+## Prerequisites
+- Fleet units: serial part SAT-1000 → Part → Inventory → "Update Inventory"
+ (fill `[role=dialog] input[name=readableId]`, requestSubmit the dialog form),
+ then `/x/fixed-asset/capitalize?itemId=…&trackedEntityId=…&locationId=…`
+ → requestSubmit the form whose button contains "Capitalize".
+- Agreement: see `rental-agreement-setup-wizard.md`. Backdate the start date
+ (month spinbutton → `keyboard type "09282026"` → Tab) so a backdated
+ Delivered on is inside the term.
+- Isolated session (`AGENT_BROWSER_SESSION=<name>`), viewport 1440x1000.
+- Other sessions may test RA000001 concurrently — create your own agreements.
+
+## Steps
+1. Agreement header "Deliver" → Draft rental shipment, all Pending units ticked.
+ After the first shipment the button is a "Shipments" dropdown: "New
+ Shipment" opens the existing Draft instead of creating one.
+2. Unit rows: tick = `button[role=checkbox]` inside the row whose text has the
+ serial (rows can reorder after a save — locate by serial, not index). Meter =
+ input labelled "Meter"; fill + Tab saves.
+3. Post → modal "Delivered on" date group (month spinbutton, type MMDDYYYY,
+ Tab) → click "Post Shipment" (a plain click works here).
+4. Header "Return" (later a "Receipts" dropdown → "New Receipt") → Draft
+ receipt: On Rent ticked, Pending unticked. Location combobox → option,
+ requestSubmit the Save form. "Take out of service" switch reveals "Reason".
+ Post → "Returned on" → "Post Receipt".
+5. Unit page "Return" → one-unit Draft receipt → Post → Post Receipt.
+6. Void: shipment ⋮ (More options) → "Void" → "Void Shipment".
+7. Release: unit page "Release unit" → date group → requestSubmit the dialog
+ form ("Release unit"). Reload before reading the Billing Periods card.
+8. PDF: fetch `/file/shipment/<id>.pdf` in the page, save, `qlmanage -t` to PNG.
+9. Regression: `/x/fixed-asset/<id>/sell` → customer → "Create Sales Order" →
+ Confirm → Confirm → Ship → Post → Post Shipment.
+
+## Common Failures
+- `agent-browser open` sometimes lands on a hydration failure with an empty
+ body and dead header buttons — reload once.
+- Posting a Draft shipment that still ticks a Returned unit fails with only
+ "Failed to post shipment".
diff --git a/.ai/research/rental-delivery-and-return.md b/.ai/research/rental-delivery-and-return.md
new file mode 100644
index 0000000000..524ef19ab6
--- /dev/null
+++ b/.ai/research/rental-delivery-and-return.md
@@ -0,0 +1,216 @@
+# Rental Delivery and Return Research: Best Practices Survey
+
+> Date: 2026-10-07
+> Prepared for: the rental delivery and return documents (branch `rental-shipment-receipt`). This builds on `.ai/research/2026-09-21-sell-vs-rent-rental-revenue-recognition.md`, which covers the accounting of a rental fleet.
+> Method: web survey of vendor help sites and community threads. SAP Community pages refused direct fetch (HTTP 403), so the SAP claims come from search-result extracts of those threads. The file marks these claims **search-synthesized**.
+
+## Summary
+
+This survey asks how rental systems record the physical delivery (check-out) and the physical return (check-in) of serialized rental units against a rental contract. Most products surveyed use a separate logistics document for each trip. The document links to the contract and can carry units from one contract or from several. The delivery document names the units that go. The return document names the units that come back, so a partial return is normal. Every dedicated rental system splits the return into two events. The **off-rent date** stops billing. The **physical return** happens later, at the yard. Check-in captures a meter reading, condition, photos, a damage code and a signature per unit. A returned unit does not become available at once. It goes through an inspection, and the inspection can raise damage charges and a repair order. When the unit is company-owned equipment, the delivery and the return change custody and location only. No product surveyed posts a GL entry for the move itself. A return to another branch updates the unit's location. One product also splits the rental revenue between the two branches.
+
+## Competitors Surveyed
+
+- **SAP S/4HANA** — the enterprise reference. SD rental contracts (document type MV) bill from a billing plan. Physical moves use outbound deliveries with special-stock movement types and serial-number statuses.
+- **SAP partner add-on FIT-Rent** — shows how a rental vertical builds on SAP outbound and inbound deliveries.
+- **NetSuite (rental SuiteApps: RentalSeries, Luxent Rental & Lease, SuiteWorks)** — NetSuite has no native rental module. SuiteApps build rental on sales orders, item fulfillments, item receipts and return authorizations.
+- **Microsoft Dynamics 365 F&SCM with STAEDEAN Rental Management (formerly DynaRent)** — the most complete documented ERP rental add-on. Its help site documents each step of delivery and return.
+- **Texada (SRM, Rental Management "Next", Texada Mobile)** — dedicated equipment-rental system with delivery tickets, pickup tickets and mobile check-in.
+- **Wynne Systems RentalMan** — dedicated equipment-rental ERP for large rental companies. It has pickup tickets, full and partial returns, and branch transfers.
+- **Point of Rental (Essentials and the 2020 desktop help)** — counter-based rental system for general and party rental stores.
+- **HirePOS** (UK "hire" terminology) and **Odoo Rental** — secondary checks for the off-hire split and for a general ERP's pickup and return buttons.
+
+## Key Consensus Patterns
+
+### 1. Delivery and return are separate documents linked to the contract
+
+- **SAP**: The rental contract (VA41, type MV, item category MVN) holds the terms and the billing plan. The physical move is an outbound delivery. The delivery uses consignment fill-up (movement type 631) or returnable packaging issue (621). The return uses consignment pick-up (632), returnable packaging pick-up (622), or a customer return with an inbound delivery. **Search-synthesized.**
+- **FIT-Rent (on SAP)**: A swap "automatically creates inbound delivery (for return equipment) and outbound delivery (for sent equipment)". The contract stays valid for the swapped unit.
+- **STAEDEAN (D365)**: The user posts a **packing slip** from the rental order to deliver. The user posts a **return note** from the rental order (Post-rental → Return note) to return. The mobile app also generates the return note when the driver closes the collection task.
+- **NetSuite (RentalSeries)**: "Quick Ship" creates **Delivery Orders** and their item fulfillments to move units to the customer location. "Quick Return" creates **Pickup Orders** and an item fulfillment plus an item receipt. These move the units from the customer location to the company's inspection location.
+- **Texada**: A **Delivery ticket** moves assets from inventory to the customer site. A **Pickup ticket** moves them back. A **Task ticket** moves assets between locations. Each ticket links to a parent contract.
+- **Wynne RentalMan**: The rental contract records delivery or customer pickup, with the driver, the carrier and the charges. A **Pickup Ticket** requests collection from the job site. **Full Return**, **Partial Return** and **Consolidated Return** record the check-in.
+- **Point of Rental** (the exception): It has no separate document. The contract line status changes from Out to Returned when the user closes the item.
+- **Rationale**: One contract can run for months and see many trips. A separate document per trip gives each trip its own date, driver, signature and printout. The contract keeps the terms.
+
+### 2. One document carries many units, and the user picks which units go or come back
+
+- **STAEDEAN**: A serialized rental line holds quantity 1 with one assigned business object. Post packing slip asks for the quantity to post. The return flow branches into "Full return" and "Partial return".
+- **Texada**: One ticket can hold several assets "from the same Contract". Mobile check-in can process "Products for multiple different Contracts, at the same time".
+- **Wynne**: A Consolidated Pickup Ticket covers several contracts for one customer and job. Partial Return selects "the quantities of equipment returned".
+- **Point of Rental**: Partial Return splits the line. The returned quantity moves to a new line, and the original line keeps the rest.
+- **SAP**: The outbound delivery assigns serial numbers per item. **Search-synthesized.**
+- **Rationale**: Units come back on different days. The line per unit, not the document, holds the on-rent and off-rent state.
+
+### 3. The return has two dates: off-rent (billing stops) and physical return (unit arrives)
+
+- **Wynne**: A pickup ticket "stops further billing for all of the rental contracts on the ticket". After the return, billing resumes "for any items on the pickup ticket that were not returned".
+- **Point of Rental**: **Called Off Rent** "stop[s] the rental time but doesn't close out the contract or the item". The user closes the item later, when it is back at the store.
+- **Texada**: The Off Rent status means "billing for an Asset has been paused" and earns no revenue. A pickup ticket has a Requested and an Actual date and time.
+- **STAEDEAN**: The user enters the **Off-rent date** on the rental order line, or on the header for all lines. Then the user plans a collection task.
+- **HirePOS**: "Billing stops as of the Off-Hire date, even though the equipment remains with the customer". The collection date and the return date come later.
+- **Rationale**: The customer stops paying when it releases the unit, not when the truck arrives. The yard records the arrival separately.
+
+### 4. Check-out and check-in capture per-unit evidence
+
+| Captured | Who captures it |
+|---|---|
+| Actual date and time | Wynne (return date and time; warns if before the billed-through date), Texada (Actual Date/Time) |
+| Meter reading | Point of Rental (asks for the meter reading when a metered item changes status), Texada (Confirm Meter Reading when a metered product goes on a contract), STAEDEAN (business object meters) |
+| Fuel | STAEDEAN (fuel tanks per business object, fuel transactions on the rental order), Point of Rental (standard fuel charge per item) |
+| Condition, inspection checklist | Texada (inspection forms per product group), STAEDEAN (quality check task per product), FIT-Rent (model and checklist inspection) |
+| Photos, damage code | Texada ("Damaged" check box reveals photos and a damage code), STAEDEAN (notes and pictures on the collection task) |
+| Customer signature | Texada (check-in and check-out), Odoo (Sign before pickup) |
+| Driver, carrier, charges | Wynne (driver name, carrier code, delivery and pickup charges), Texada (driver on the ticket) |
+
+### 5. Moving a company-owned unit changes custody, not the ledger
+
+- **SAP**: Consignment fill-up (631) moves stock to customer special stock W with no accounting document. Pick-up (632) moves it back, again with no accounting document. Returnable packaging (621/622) updates quantity only. After goods issue, the serial number status changes from ESTO (in the warehouse) to ECUS (at the customer). EDEL marks a serial number on an open delivery. **Search-synthesized.**
+- **STAEDEAN**: Purchased rental units become fixed assets ("Auto convert asset purchases"). The packing slip and the return update inventory quantities and the business object status: Assigned → On-rent → Off-rent → Rental-ready.
+- **NetSuite (RentalSeries)**: The item fulfillment and the item receipt move units between company locations: stock, customer location, inspection location.
+- **Point of Rental and Texada**: The contract and the tickets change the item status. They do not post a stock movement.
+- **Rationale**: The company still owns the unit, and the unit is on the books as a fixed asset or as rental stock. Only the custodian and the place change. Revenue and depreciation follow other documents.
+
+### 6. A returned unit goes through inspection before it is available again
+
+- **STAEDEAN**: After collection, the user plans a **Quality check** task for each product. A failed check leads to an inspection list and a repair work order. The asset statuses include Off-rent, Maintenance and Rental-ready.
+- **NetSuite (RentalSeries)**: The return lands in the inspection location and "automatically create[s] inspection orders". Versich: "assets should not move to available inventory immediately upon receipt".
+- **HirePOS**: With "Auto-create post-hire inspections" or "Lag Time" on, the unit stays unavailable until the inspection completes.
+- **Texada**: An item returned to the yard but not yet closed on the contract shows status "O", not "F" (off rent).
+- **Damage charges**: FIT-Rent bills "customer damages" and "late returns" as extra charges. Versich uses the inspection record "to add damage or cleaning charges". Texada records a damage code at check-in.
+- **Rationale**: The next customer must get a safe, complete unit. The inspection is also the evidence for a damage charge.
+
+### 7. Delivery starts billing and the off-rent date stops it in rental systems, but not in SAP standard
+
+- **STAEDEAN**: Each line carries an **On-rent date** and an **Expected off-rent date** from the header. The off-rent date ends the rental.
+- **Versich (NetSuite)**: "A billing process might use the dispatch date as the start event, the actual return date as the end event".
+- **Wynne, Point of Rental, HirePOS**: The pickup ticket, the call-off or the off-hire date stops billing.
+- **SAP standard SD**: The billing plan runs from the contract's start and end dates, not from the delivery (SAPinsider). Rental add-ons on SAP add the delivery link.
+- **Rationale**: A customer pays for the time it has the unit. Billing from the contract start charges for days before delivery.
+
+## Answers to Research Questions
+
+1. **Is delivery or return a separate document? What is it called?** — Yes, in every product except Point of Rental. Point of Rental changes the contract line status directly. The names:
+ - SAP: outbound delivery; returns delivery or pick-up
+ - STAEDEAN: packing slip; return note
+ - NetSuite RentalSeries: delivery order with item fulfillment; pickup order with item receipt
+ - Texada and Wynne: delivery ticket; pickup ticket
+ - Odoo: pickup receipt; return receipt
+2. **One document per contract or per unit? Partial deliveries and returns?** — One document per trip, holding many units. The user selects the units. A partial return is a standard function (STAEDEAN, Wynne, Point of Rental, FIT-Rent). Texada and Wynne also let one ticket or one return cover several contracts.
+3. **What is captured?** — See the table in pattern 4. Backdating: Point of Rental requires a Store Manager password for a call-off date before today. Wynne warns when the return date is before the last billed-through date, and the user decides on a credit.
+4. **Inventory or GL entries for a capitalized unit? Custody tracking?** — No GL entry for the move in any product surveyed. SAP moves the unit to customer special stock with no accounting document and sets the serial status ECUS. STAEDEAN updates the business object status. NetSuite SuiteApps move the unit to a customer location. Texada keeps Division and Location on the asset.
+5. **Return to a different branch?** — Point of Rental asks the counter user to transfer the unit to the receiving store. Its current location then changes to that store. Texada credits a **Cross-Store Check-In Account** with the part of the rental revenue that goes to the return division. STAEDEAN changes the business object's depot with a depot start date. Wynne has inventory transfer programs; this survey found no documented cross-branch return step for Wynne.
+6. **Inspection before availability? Damage charges?** — Yes. STAEDEAN, NetSuite RentalSeries, HirePOS and FIT-Rent all put an inspection between return and availability. Damage findings become extra charges on the contract (FIT-Rent, Versich) or a repair work order (STAEDEAN).
+7. **Delivery date starts billing, return date stops it?** — Yes in STAEDEAN, the NetSuite SuiteApps, Wynne, Point of Rental and HirePOS. The stop event is the off-rent date, which can come before the physical return. SAP standard SD bills from the contract dates instead.
+
+## Competitor-Specific Details
+
+### SAP S/4HANA
+- Rental contract: VA41, document type MV, item category MVN, periodic billing plan run by V.07 / RVFPLA01. The billing plan uses the contract's start and end dates.
+- Physical move without a rental add-on: consignment fill-up 631 / pick-up 632 (special stock W), or returnable packaging 621 / 622 (special stock V). Neither posts an accounting document. **Search-synthesized.**
+- Serial number statuses: ESTO (in the warehouse), EDEL (on a delivery), ECUS (at the customer). **Search-synthesized.**
+- S/4HANA Public Cloud practice: receive a rented unit back as a customer return with no refund, through an inbound delivery and a goods receipt. **Search-synthesized.**
+
+### FIT-Rent (SAP add-on)
+- Delivery planning board, in-transit monitoring, optional IoT tracking.
+- Partial or full return, checklist inspection per model, swap with an automatic inbound and outbound delivery.
+- Billing adds charges for "late returns, customer damages, over-usage".
+
+### NetSuite rental SuiteApps
+- Luxent: "A single sales order drives the entire rental lifecycle: fulfillment, return authorization, and recurring monthly invoicing". It creates the return authorization on fulfillment.
+- RentalSeries: Delivery Orders, Pickup Orders, an Inspection Location, inspection orders on return, and asset records created from item transactions.
+
+### STAEDEAN Rental Management (D365)
+- Business object = one serialized unit. A serialized line holds quantity 1.
+- Flow:
+ 1. Confirm the rental order.
+ 2. Post the packing slip.
+ 3. Change the off-rent date.
+ 4. Plan the collection task.
+ 5. Collect the unit (notes, pictures).
+ 6. Close the collection task. This generates the return note.
+ 7. Do the quality check.
+ 8. If the check fails, create a repair work order.
+- Technical exchange: the user sets the off-rent date and time and the requested pickup date and time. The replacement unit must be the same item.
+- Depot: "a business location used to receive and distribute business objects". "Change depot" sets a new depot and a depot start date.
+
+### Texada
+- Ticket types: Delivery, Pickup, Task. A ticket prefills from its parent contract.
+- 2019 field names: delivery ticket "Deliver By", "Drop Off Date/Time", "Date/Time On"; pickup ticket "Requested Date/Time", "Actual Date/Time", "Close Date/Time".
+- Pickup and Delivery inspection form types, with inspector name, signature and date.
+- Cross-Store Check-In Account per rental class.
+
+### Wynne RentalMan
+- Return launch screen: customer, contract, equipment, pickup ticket, return date, return time, credit days, credit hours.
+- The user must set the actual return date and time before searching. Otherwise the program uses the current system date and time.
+
+### Point of Rental
+- Line statuses: Reserved, Out, Hold (rental time stopped), Returned, Sold Asset.
+- Close options:
+ - Close All Items
+ - Partial Return
+ - Called Off Rent
+ - Line Item Billing: bills the returned lines and moves the open lines to a new contract
+ - Site Transfer: calls the units off rent at one site and opens a delivery to the new site
+
+## Recommended Approach for Carbon
+
+Carbon context: `rentalAgreementLine` already holds one fleet unit (quantity 1), `status` Pending / On Rent / Returned / Sold, `deliveredAt`, `returnedAt`, `meterIn` and `returnNotes`. Deliver and Return are actions on the line. Billing periods run from the agreement's start date, whatever the delivery date (`apps/erp/app/modules/sales/AGENTS.md`).
+
+1. **Add one delivery document and one return document per trip, linked to the rental agreement.** Each document holds one or more units of that agreement, and the user picks the units. This follows STAEDEAN (packing slip, return note), Texada (delivery and pickup tickets) and SAP (outbound and returns delivery). If Carbon reuses `shipment` and `receipt` for this, add the rental agreement as a source document type.
+2. **Keep the rental agreement line as the unit's state.** Posting a delivery sets the line On Rent and stamps `deliveredAt`. Posting a return sets it Returned and stamps `returnedAt`. A partial return is then only a return document with fewer units (STAEDEAN, Wynne).
+3. **Post no item ledger row and no journal for a fixed-asset unit.** The document changes custody and location only. SAP 631/632 and the rental systems surveyed work this way. If Carbon reuses `shipment` and `receipt`, their posting must skip the inventory and GL legs for these lines.
+4. **Store two return dates: the off-rent date and the received date.** The off-rent date stops billing. The received date records arrival at the yard. Allow an off-rent date before today with a warning when it falls inside an already billed period. Carbon's existing early-return credit memo then handles the credit (Wynne, Point of Rental, HirePOS).
+5. **Capture per unit on each document:** meter out and meter in, condition notes, photos as attachments, and an optional signature. Put the driver, the carrier and the tracking number on the document header (Texada, Wynne). Leave fuel out of v1. Only STAEDEAN and Point of Rental model fuel, and both bill it as a separate charge.
+6. **Record the receiving location on the return and move the asset there.** Update the fixed asset's `locationId` to the receiving location. Do not create an inter-branch transfer document (Point of Rental, STAEDEAN depot change). Leave revenue allocation between branches out of scope (Texada's cross-store account).
+7. **Put a returned unit into an inspection state before it is Available.** Let the inspection raise a `rentalAgreementCharge` for damage and an optional maintenance dispatch (STAEDEAN, NetSuite RentalSeries, HirePOS).
+8. **Open question for the spec: should the delivery date start billing?** Every rental system surveyed bills from the on-rent (delivery) date. Carbon bills from the agreement start date, the SAP standard SD pattern. Carry this into the spec's Open Questions.
+
+## Sources
+
+- https://sapinsider.org/manage-rental-contracts-with-help-from-sales-and-distribution-functionality/
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/consignment-fill-up-accounting-entry-required-in-631w-movement-type/qaq-p/9164502
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/movement-types-in-consignment-processing/qaq-p/3682302
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/serial-number-status-esto-and-ecus/qaq-p/9773461
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/serial-number-status-edel-esto-in-sd/qaq-p/5431627
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/rental-process-through-solution-order-how-to-manage-returns/qaq-p/14246357
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/rental-process-delivery-with-movement-type-621/qaq-p/12703815
+- https://userapps.support.sap.com/sap/support/knowledge/en/2686854
+- https://fit-global.com/sap-equipment-management-solutions/equipment-rental-software/
+- https://sererra.com/rentalseries/
+- https://luxent.com/products/rental-lease
+- https://versich.com/blog/netsuite-rental-management-for-cleaner-returns-and-billing-control/
+- https://docs.staedean.com/equipment-rental/docs/post-packing-slip.md
+- https://docs.staedean.com/equipment-rental/docs/return-business-object-on-rental-order.md
+- https://docs.staedean.com/equipment-rental/docs/receive-rental-orders-including-field-service-app.md
+- https://docs.staedean.com/equipment-rental/docs/change-rental-order-off-rent-date.md
+- https://docs.staedean.com/equipment-rental/docs/change-rental-order-line-off-rent-date.md
+- https://docs.staedean.com/equipment-rental/docs/collect-the-assets-mobile-app.md
+- https://docs.staedean.com/equipment-rental/docs/close-the-collection-task-mobile-app.md
+- https://docs.staedean.com/equipment-rental/docs/close-the-quality-check-task-mobile-app.md
+- https://docs.staedean.com/equipment-rental/docs/manually-create-a-repair-work-order-mobile-app.md
+- https://docs.staedean.com/equipment-rental/docs/add-rental-order-line-with-rental-item.md
+- https://docs.staedean.com/equipment-rental/docs/technical-exchange.md
+- https://docs.staedean.com/equipment-rental/docs/add-fuel-transaction.md
+- https://docs.staedean.com/equipment-rental/docs/maintain-released-product.md
+- https://docs.staedean.com/equipment-rental/docs/manage-business-object-depot.md
+- https://docs.staedean.com/equipment-rental/docs/change-depot-on-the-business-object.md
+- https://staedean.com/rental/blog/managing-daily-rental-operations-dynarent-dynamics-365
+- https://staedean.com/rental/blog/rental-inventory-management-dynamics-365
+- https://help.texadasoftware.com/en/knowledge/187/create-a-ticket-in-texada-web
+- https://help.texadasoftware.com/en/knowledge/480/complete-a-check-in-or-check-out-in-service-and-rental-mobile
+- https://help.texadasoftware.com/en/knowledge/474/2019-systematic-rental-management-srm-release-notes
+- https://help.texadasoftware.com/en/knowledge/1044/texada-srm-data-import-toolbox
+- https://help.texadasoftware.com/en/knowledge/knowledge/171/the-asset-list-page
+- https://help.texadasoftware.com/en/knowledge/809/the-contract-reservation-details-page
+- https://support.wynnesystems.com/help/rm/ENU/Content/Operations_Overview.htm
+- https://support.wynnesystems.com/help/rm/ENU/Content/RASUST102.htm
+- https://support.wynnesystems.com/help/rm/ENU/Content/RARINT10.htm
+- https://support.wynnesystems.com/help/rm/ENU/Content/RARINT101.htm
+- https://support.wynnesystems.com/help/rm/ENU/Content/RAOUTT20.htm
+- https://help.point-of-rental.com/2020/Content/Close%20Contract.htm
+- https://help.point-of-rental.com/2020/Content/Items%20Tab.htm
+- https://help.point-of-rental.com/2016/Documents/calledoffrent.htm
+- https://help.point-of-rental.com/2016/Documents/partialreturn.htm
+- https://help.point-of-rental.com/2021/Content/Transfer%20Contract.htm
+- https://docs.hirepos.com/en/articles/2324865
+- https://www.odoo.com/documentation/17.0/applications/sales/rental.html
diff --git a/.ai/specs/2026-10-07-rental-shipments-and-receipts.md b/.ai/specs/2026-10-07-rental-shipments-and-receipts.md
new file mode 100644
index 0000000000..1ff5d26777
--- /dev/null
+++ b/.ai/specs/2026-10-07-rental-shipments-and-receipts.md
@@ -0,0 +1,542 @@
+# Rental Shipments and Receipts
+
+> Status: draft
+> Author: Claude (with Brad)
+> Date: 2026-10-07
+
+## TLDR
+
+A rental unit now goes out on a **rental shipment** and comes back on a
+**rental receipt**. Both are ordinary `shipment` and `receipt` documents with
+the new source document `'Rental Agreement'`. They replace the Deliver and
+Return actions on the rental agreement. A unit rides on the existing
+fixed-asset line tables, so posting writes no `itemLedger` row and no journal
+for a `Rental` line. Posting a rental shipment puts the unit On Rent. Posting
+a rental receipt returns it, re-cuts its billing and moves the asset to the
+receipt's location. The agreement header gets one Deliver button and one
+Return button, like the sales order's Ship button. Each unit's page keeps a
+shortcut that opens a document for that one unit.
+
+## Overview diagram
+
+```mermaid
+stateDiagram-v2
+ [*] --> Pending: Activate agreement
+ Pending --> OnRent: Post rental shipment
+ OnRent --> Pending: Void rental shipment
+ OnRent --> Returned: Post rental receipt
+ Pending --> Returned: Post rental receipt or Release unit
+ OnRent --> Sold: Post purchase option invoice
+ Returned --> [*]
+ Sold --> [*]
+ classDef hot stroke-width:3px
+ class OnRent hot
+ class Returned hot
+```
+
+The bold states change: a document now moves the line into them. The void
+edge and the Pending to Returned edge are new.
+
+## Problem Statement
+
+Delivery and return of a rental unit are physical events. Today they leave
+no document behind.
+
+1. **Deliver is a button.** `x+/rental-agreement+/$id.$lineId.deliver.tsx`
+ sets the line `On Rent` and stamps `deliveredAt` with the company's today.
+ The user cannot backdate it. Nothing records the carrier, the tracking
+ number, the ship-from location or the meter reading. `rentalAgreementLine.meterOut`
+ exists, but no code writes it.
+2. **Return is a form on the agreement.** `post-rental-agreement` type
+ `return` records `returnedAt`, `meterIn` and notes. It records no
+ location. A `Rental` line return writes no `trackedActivity`.
+3. **The warehouse cannot see the work.** Neither event shows in
+ Inventory → Shipments or Inventory → Receipts. The warehouse team must open
+ a sales document to deliver a unit.
+4. **No delivery ticket.** The customer gets no packing slip for a rental
+ unit.
+5. **The asset's location never changes.** A unit that comes back to a
+ different yard still shows its old `fixedAsset.locationId`.
+
+Example: agreement RA-000012 rents 5 units. The driver delivers 3 on Monday
+and 2 on Wednesday. Today the user must press Deliver 5 times, on the day of
+each delivery. No shipment shows what left the yard, and the customer gets no
+delivery ticket.
+
+## Proposed Solution
+
+### Research
+
+`.ai/research/rental-delivery-and-return.md` surveys SAP S/4HANA, NetSuite
+rental SuiteApps, Dynamics 365 rental add-ons (DynaRent), Texada, Wynne and
+Point of Rental. The consensus:
+
+- Delivery and return are separate documents linked to the contract. One
+ document holds many units. Partial returns are normal.
+- The move of a capitalized rental unit posts no inventory value and no
+ journal. SAP movement types 631 and 632 work this way.
+- The unit's current location updates at return. No transfer document is
+ necessary.
+- Rental systems bill from delivery. SAP contract billing bills from the
+ contract dates. Carbon bills from the agreement start date and keeps that
+ rule (Q4).
+
+### Flow
+
+**Deliver** (agreement header, Active agreement):
+
+1. If the agreement has a Draft rental shipment, the button opens it.
+2. Otherwise the route creates a Draft rental shipment.
+3. The shipment's location is `rentalAgreement.locationId`.
+4. The shipment has one asset line for each `Pending` unit that is not on
+ another open rental shipment.
+5. Each asset line starts with `shipped = true`.
+6. The user unticks the units that do not go.
+7. The user enters meter out, carrier and tracking.
+8. The user clicks **Post**. The post modal asks for **Delivered on**.
+9. The user confirms, and the shipment posts.
+
+**Return** (agreement header, Active agreement): the same steps, with a rental
+receipt, with 2 differences:
+
+1. The receipt holds every `On Rent` unit with `received = true`.
+2. The receipt also holds every `Pending` unit with `received = false` (Q8).
+
+The user unticks the units that do not come back. A `Pending` unit on a
+receipt is a unit that never left the yard. Ticking it stops its billing at the
+return date.
+
+**Per-unit shortcut** (unit page, `Deliver` or `Return`):
+
+1. If the agreement has a Draft document of that kind, the route adds the unit
+ to it when it is missing. Then the route opens the document.
+2. Otherwise the route creates a Draft document with that one unit.
+3. The shortcut always adds its unit ticked, also a `Pending` unit on a
+ receipt.
+
+For a counter pickup this is two clicks: the shortcut, then **Post**.
+
+After an agreement has a rental shipment, the header's Deliver button becomes
+a **Shipments** dropdown: "New Shipment" plus the list of the agreement's
+shipments. Return becomes a **Receipts** dropdown in the same way. This copies
+`SalesOrderHeader`.
+
+### Posting a rental shipment (`post-shipment`, new case `'Rental Agreement'`)
+
+In one Kysely transaction:
+
+1. Lock the shipment `FOR UPDATE`.
+2. Read the ticked asset lines (`shipped = true`). If there is none, refuse
+ with "Select at least one unit to deliver".
+3. Lock each rental line `FOR UPDATE`.
+4. If a rental line is not `Pending`, or its agreement is not `Active`, refuse
+ the whole shipment. The message names the unit.
+5. If a unit is out of service, refuse. The message names the reason.
+6. Set each line `On Rent`, `deliveredAt` = the date from the post modal, and
+ `meterOut` = the asset line's meter.
+7. If the line has a `trackedEntityId`, write a `trackedActivity` of type
+ `Rental Delivery`.
+8. Set the shipment `Posted`, with `postingDate` = the date from the post
+ modal.
+
+The posting writes no `itemLedger`, `costLedger` or journal row. A `Sale`
+line uses the same path. Activation already derecognized its unit, so
+delivery only records custody.
+
+### Posting a rental receipt (`post-receipt`, new case `'Rental Agreement'`)
+
+In one Kysely transaction:
+
+1. Lock the receipt `FOR UPDATE`.
+2. Read the ticked asset lines (`received = true`). If there is none, refuse
+ with "Select at least one unit to return".
+3. For each line, run the shared `returnRentalUnit` function. It holds the
+ body of today's `returnUnit` in `post-rental-agreement`:
+ 1. It locks the rental line. The receipt case refuses a line that is not
+ `Pending` or `On Rent` before the call.
+ 2. It refuses a `returnedAt` in the future (`futureReturnError`).
+ 3. For a `Rental` line, it re-cuts the billing periods and adds the
+ early-return adjustment row.
+ 4. For a `Sale` line, it runs `returnResidual` with the line's
+ `residualDestination` and the receipt's `locationId` (Q7).
+ 5. It sets the line `Returned` with `returnedAt`, `meterIn` and
+ `returnNotes`.
+ 6. If `takeOutOfService` is true, it sets `fixedAsset.outOfServiceSince`
+ and `outOfServiceReason`.
+4. Set `fixedAsset.locationId` to the receipt's `locationId`. A `Sale` line
+ returned to Fleet gets a new asset at that location. A `Sale` line returned
+ to Inventory books its stock at that location (Q7).
+5. If the line has a `trackedEntityId`, write a `trackedActivity` of type
+ `Rental Return`. A `Sale` line keeps its existing `Return to Inventory`
+ activity instead.
+6. Set the receipt `Posted`, with `postingDate` = the date from the post
+ modal.
+
+`returnedAt` is the date from the post modal. A `Rental` line return writes no
+`itemLedger` row and no journal. A `Sale` line return to Inventory writes the
+same stock adjustment and journal as today, at the receipt's location. The
+receipt's location defaults to the agreement's location, so the two differ
+only when the user changes it.
+
+### Void
+
+| Document | Rule |
+|----------|------|
+| Rental shipment | The void needs 2 conditions for every ticked unit. The unit is still `On Rent`. No `Accrual` row in `revenueRecognitionSchedule` for its line is `Posted` or claimed by a Draft run (`runLineId` set). If both hold, the void sets each line back to `Pending` and clears `deliveredAt` and `meterOut`. It deletes the unit's unclaimed `Planned` `Accrual` rows and sets the shipment `Voided`. Otherwise `post-shipment` refuses the void with a message that names the unit and the reason. |
+| Rental receipt | `post-receipt` refuses the void: "A rental return cannot be voided. Correct the unit by hand." This matches today, where a return has no undo. |
+
+### Agreement actions that touch open documents
+
+- **Cancel** deletes the `Pending` lines. The FK on the asset line cascades, so
+ the lines leave any Draft rental shipment.
+- **Close** refuses while a Draft or Pending rental shipment or receipt of the
+ agreement still has a line. The message names the document. This check runs
+ before the existing "every unit returned or sold" check.
+
+### Release unit (Q8)
+
+A `Pending` unit that the customer no longer wants never leaves the yard. The
+billing job still bills it, because billing runs from the agreement start date.
+**Release unit** ends it without a document:
+
+1. The unit page of a `Pending` unit on an `Active` agreement shows
+ **Release unit**.
+2. A modal asks for the release date. It defaults to today. It cannot be in
+ the future.
+3. `post-rental-agreement` type `release` runs `returnRentalUnit` for that one
+ line. It refuses a line that is not `Pending`.
+4. Billing stops at the release date. An Advance-billed period gets the same
+ early-return adjustment as a return.
+5. The line becomes `Returned`. The unit is Available again. Its
+ `fixedAsset.locationId` does not change.
+
+A rental receipt can also return a `Pending` unit (see Flow). Release unit is
+the shorter path when nothing moves.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Documents replace the actions | Deliver and Return always go through a rental shipment or rental receipt. `post-rental-agreement` replaces its `return` type with `release`, for `Pending` units only. | One path changes a line's status when a unit moves (Q1). Every move shows in Inventory. A release moves nothing (Q8). |
+| Where a unit sits on the document | `shipmentFixedAssetLine` / `receiptFixedAssetLine`, with a new nullable `rentalAgreementLineId` | These tables already carry assets that are not stock, with their own UI and posting. An ordinary `shipmentLine` needs an `itemId` and serial tracking, and its tracking refuses a `Consumed` entity. |
+| Stock and GL effect | None for a `Rental` line. A `Sale` line's residual return keeps today's stock adjustment and journal. | The unit is a capitalized asset. SAP movement types 631 and 632 also post no value. The PO-sourced shipment already posts no `itemLedger` (`.ai/lessons.md`). |
+| Ship-from location | `rentalAgreement.locationId`, which the user can change on the shipment. No warning when a unit's own yard differs. | Q2. The document records whether, when and where. One document per trip is the industry pattern. |
+| Return location | Posting sets `fixedAsset.locationId` to the receipt's location. No transfer document and no journal. | Q2. Texada and Wynne do the same. The fleet register then shows where the unit is. |
+| Dates | One date per document (Delivered on / Returned on). The post modal asks for it. It defaults to today. The user can backdate it but cannot set it in the future. `post-shipment` and `post-receipt` take an optional `postingDate` input and use it for the rental source only. Posting writes it to `postingDate`. | Q3. No separate off-rent date. A Draft keeps `postingDate` null, because the UI reads a set `postingDate` as posted (`$shipmentId.delete.tsx`, `ShipmentsTable.tsx`). |
+| Billing start | Unchanged: billing runs from the agreement start date. Delivery only records custody and starts accruals. | Q4. Billing from delivery needs its own spec. |
+| Condition data | Shipment asset line: `meter`. Receipt asset line: `meter`, `notes`, `takeOutOfService`, `outOfServiceReason`, `residualDestination`. Photos use the document's attachments. Damage stays an agreement charge. | Q5. No signature and no inspection status. |
+| Void | `post-shipment` voids a rental shipment within the guards above. `post-receipt` refuses a rental receipt void. | Q6. A receipt void must rebuild deleted periods and reverse a residual return. |
+| Open drafts | One Draft rental shipment and one Draft rental receipt per agreement, backed by partial unique indexes | Copies the returns module (`20260908142501_returns-module.sql`). The header button opens the existing draft. |
+| Double booking | A new document skips units on another open document. Posting locks each rental line and rechecks its status. | A rental line has a status, not a running quantity, so posting must check it. |
+| `post-receipt` default case | The new case is explicit. | Today's default case returns success and leaves the receipt `Pending`. |
+| `trackedActivity` types | `Rental Delivery` and `Rental Return`, with `sourceDocument` `"Shipment"` / `"Receipt"`. The agreement goes in `attributes`. | `trackedActivity.type` is TEXT. The other shipment and receipt activities use the same `sourceDocument` values, and `sourceLinkHref` already links them. The traceability graph then shows custody at the customer. |
+| Multi-tenancy (heuristic 1) | The new columns sit on existing tables. Every new read and write filters on `companyId`. | The fixed-asset line tables keep their existing single-column PK. This spec does not change it. |
+| Service shape (heuristic 2) | New service functions take `client` first and return `{ data, error }`. Posting stays in the server functions. | `conventions-services.md` |
+| RLS (heuristic 3) | No new table. The fixed-asset line tables keep their `inventory_*` policies. | The new columns inherit the table policies. |
+| Permissions (heuristic 4) | Creating a rental shipment or receipt needs `create: inventory`. Posting needs `update: inventory`, the same as every shipment and receipt. The header buttons show for users with `update: sales` and `create: inventory`. | A sales-only user can no longer deliver alone. This matches the sales order, where shipping needs inventory permissions. |
+| Forms (heuristic 5) | The asset line fields save through the existing `fixed-asset-lines.update` routes, extended with the new fields and a zod validator. | `conventions-forms.md` |
+| Module layout (heuristic 6) | Create functions go in `packages/server-functions/src/create`. Service reads go in `inventory.service.ts` and `sales.service.ts`. | No new files outside the existing modules. |
+| Backward compatibility (heuristic 7) | Existing lines keep their state. `deliveredAt` and `returnedAt` on lines from before this change stay. Those lines have no document. | No backfill. A rental receipt can still return a line that was delivered before the change. |
+
+## Data Model Changes
+
+Two migrations. Postgres cannot use a new enum value in the transaction that
+adds it, so the indexes go in the second migration.
+
+**Migration 1 — enum values:**
+
+```sql
+ALTER TYPE "shipmentSourceDocument" ADD VALUE IF NOT EXISTS 'Rental Agreement';
+ALTER TYPE "receiptSourceDocument" ADD VALUE IF NOT EXISTS 'Rental Agreement';
+```
+
+**Migration 2 — lines and indexes:**
+
+```sql
+ALTER TABLE "shipmentFixedAssetLine"
+ ALTER COLUMN "salesOrderLineId" DROP NOT NULL,
+ ADD COLUMN "rentalAgreementLineId" TEXT,
+ ADD COLUMN "meter" NUMERIC,
+ ADD CONSTRAINT "shipmentFixedAssetLine_rentalAgreementLineId_fkey"
+ FOREIGN KEY ("rentalAgreementLineId", "companyId")
+ REFERENCES "rentalAgreementLine"("id", "companyId")
+ ON DELETE CASCADE ON UPDATE CASCADE,
+ ADD CONSTRAINT "shipmentFixedAssetLine_source_check"
+ CHECK (num_nonnulls("salesOrderLineId", "rentalAgreementLineId") = 1);
+
+CREATE INDEX "shipmentFixedAssetLine_rentalAgreementLineId_idx"
+ ON "shipmentFixedAssetLine" ("rentalAgreementLineId");
+
+ALTER TABLE "receiptFixedAssetLine"
+ ALTER COLUMN "purchaseOrderLineId" DROP NOT NULL,
+ ADD COLUMN "rentalAgreementLineId" TEXT,
+ ADD COLUMN "meter" NUMERIC,
+ ADD COLUMN "notes" TEXT,
+ ADD COLUMN "takeOutOfService" BOOLEAN NOT NULL DEFAULT false,
+ ADD COLUMN "outOfServiceReason" TEXT,
+ ADD COLUMN "residualDestination" TEXT
+ CHECK ("residualDestination" IN ('Fleet', 'Inventory')),
+ ADD CONSTRAINT "receiptFixedAssetLine_rentalAgreementLineId_fkey"
+ FOREIGN KEY ("rentalAgreementLineId", "companyId")
+ REFERENCES "rentalAgreementLine"("id", "companyId")
+ ON DELETE CASCADE ON UPDATE CASCADE,
+ ADD CONSTRAINT "receiptFixedAssetLine_source_check"
+ CHECK (num_nonnulls("purchaseOrderLineId", "rentalAgreementLineId") = 1),
+ ADD CONSTRAINT "receiptFixedAssetLine_outOfService_check"
+ CHECK (NOT "takeOutOfService" OR "outOfServiceReason" IS NOT NULL);
+
+CREATE INDEX "receiptFixedAssetLine_rentalAgreementLineId_idx"
+ ON "receiptFixedAssetLine" ("rentalAgreementLineId");
+
+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';
+```
+
+`rentalAgreementLine` has the composite PK `("id", "companyId")`, so the FK
+uses both columns. The CHECK values match `rentalResidualDestinations`
+(`sales.models.ts:1526`).
+
+After the migrations, run `pnpm run generate:types`.
+
+The demo datasets seed no rental documents today. Run `pnpm db:check:datasets`
+and `pnpm db:check:backups` to confirm that both still pass.
+
+## API / Service Changes
+
+**`packages/server-functions/src/create`** — two new source types:
+
+- `shipmentFromRentalAgreement({ rentalAgreementId, rentalAgreementLineId? })`.
+ Refuses an agreement that is not `Active`. Without a line id, it inserts one
+ asset line for each `Pending` unit that is not on another open rental
+ shipment. With a line id, it adds that one unit to the Draft shipment, or
+ creates a Draft shipment for it. It sets the header `customerId`,
+ `locationId` = `rentalAgreement.locationId`, and `sourceDocumentReadableId` =
+ the agreement's readable id. It leaves `postingDate` null. If no unit
+ qualifies, it refuses with "No units to deliver".
+- `receiptFromRentalAgreement({ rentalAgreementId, rentalAgreementLineId? })`.
+ The same rules, with `On Rent` units. If no unit qualifies, it refuses with
+ "No units to return". For a `Sale` line it leaves `residualDestination` empty
+ so that the user must choose it.
+
+**`post-shipment`** — the `'Rental Agreement'` post case and void case, as
+described above. The input gains an optional `postingDate` (`YYYY-MM-DD`).
+The rental case refuses a date after the company's today. Other cases ignore
+the field.
+
+**`post-receipt`** — the `'Rental Agreement'` post case. The input gains the
+same optional `postingDate`. The void block refuses the rental source with its
+own message.
+
+**`post-rental-agreement`**:
+
+- Move the body of `returnUnit` into an exported `returnRentalUnit(trx, …)` in
+ a new file `post-rental-agreement/return-unit.ts`. Both server functions are
+ in `packages/server-functions`, so `post-receipt` imports it directly.
+- Move the 6 helpers that `activate` and the return share (`lockAgreement`,
+ `currencyDecimals`, `billingPeriodRow`, `loadLeaseAccounting`,
+ `postLeaseJournal`, `insertUnitActivity`) into a new file
+ `post-rental-agreement/agreement.ts`. Otherwise `return-unit.ts` and
+ `index.ts` import each other.
+- `returnRentalUnit` takes an optional `locationId`. `returnResidual` uses it
+ for the stock adjustment and the new fleet asset. Without it, both use the
+ agreement's location.
+- Replace the `return` type with `release` (`rentalAgreementLineId`,
+ `returnedAt`). It accepts a `Pending` line only and passes no location.
+- `close` refuses while a Draft or Pending rental document has a line.
+
+**Routes:**
+
+- `x+/rental-agreement+/$id.$lineId.deliver.tsx` and `$id.$lineId.return.tsx`
+ become the per-unit shortcuts. They call the create functions with the line
+ id and redirect to the document.
+- `x+/shipment+/new.tsx` and `x+/receipt+/new.tsx` accept the source
+ `'Rental Agreement'`. They redirect to the agreement's Draft when one exists.
+- The `fixed-asset-lines.update` routes of shipment and receipt accept the new
+ fields.
+
+**Service reads:**
+
+- `getRentalAgreementRelatedDocuments` (`sales.service.ts`) reads the
+ agreement's shipments and receipts for the header dropdowns.
+- `getRentalShipmentLines` / `getRentalReceiptLines` (`inventory.service.ts`)
+ read the asset lines with their rental line and asset: the unit name, the
+ serial number and the line status. Today the `$shipmentId.tsx` and
+ `$receiptId.tsx` loaders read the fixed-asset lines inline, only for a Sales
+ Order or Purchase Order source. Each loader gets a rental branch that calls
+ the new function.
+
+**Enum arrays and switches** that need the new value:
+
+| Place | Change |
+|-------|--------|
+| `shipmentSourceDocumentType` / `receiptSourceDocumentType` (`inventory.models.ts`) | Add `'Rental Agreement'` |
+| `ShipmentsTable.tsx` / `ReceiptsTable.tsx` source link | Link to `path.to.rentalAgreementDetails` |
+| `useShipmentForm.tsx` / `useReceiptForm.tsx` | Handle the source |
+| `shipment+/$shipmentId.details.tsx` / `receipt+/$receiptId.details.tsx` | Refuse a change of source on a rental document |
+| `file+/shipment+/$id[.]pdf.tsx`, `PACKING_SLIP_SOURCES` | Add the rental source |
+| `ShipmentDocuments.tsx` / `ReceiptDocuments.tsx` | Link the agreement |
+| `Traceability/utils.ts` `sourceLinkHref` | Link the existing `Rental Agreement` activities (`Lease Commencement`, `Return to Inventory`) to the agreement |
+
+## UI Changes
+
+- **`RentalAgreementHeader`**: Deliver and Return buttons. After the first
+ document they become the Shipments and Receipts dropdowns. They show only on
+ an `Active` agreement. Next to the agreement's status, an `Active` agreement
+ shows where its units are: To Deliver, Partially Delivered, On Rent,
+ Partially Returned or Returned (`rentalEquipmentStatus`; a Sold unit counts
+ as back).
+- **`useRentalLineActions`**: Deliver and Return open the per-unit shortcut
+ routes. A `Pending` unit also offers Return and **Release unit**. The Deliver
+ confirm dialog and `RentalAgreementReturnForm` go away. Release unit opens a
+ date modal that posts to a new route `$id.$lineId.release.tsx`.
+- **`ShipmentLines`**: on a rental shipment, a sibling component
+ `ShipmentRentalLineItem` shows the unit name, serial number, the shipped checkbox and a Meter field. It
+ shows no storage unit picker and no serial tracking form. Both rental line
+ components draw the unit through the shared `RentalUnitRow` (thumbnail, name,
+ asset id and serial, Meter). The units are sorted by asset id. On a posted
+ document the Meter is text, and `fixed-asset-lines.update` refuses an edit
+ to a line whose document is not Draft.
+- **`ReceiptLines`**: on a rental receipt, a sibling component
+ `ReceiptRentalLineItem` shows the received checkbox and these fields. The
+ existing fixed-asset components require an order line id, so the rental
+ lines load under their own key, `rentalLines`.
+ 1. Meter
+ 2. Notes
+ 3. Take out of service (a switch), with its reason. The switch and the reason save
+ together as one field, so the CHECK never sees a tick without a reason.
+ 4. Return To (Fleet / Inventory), only for a `Sale` line
+- **`ShipmentPostModal` / `ReceiptPostModal`**: show the date field as
+ "Delivered on" or "Returned on". The date cannot be in the future. For a
+ rental receipt, the modal blocks a `Sale` line that has no Return To value.
+- **Packing slip**: a rental shipment prints one row for each shipped unit,
+ with the unit name and serial number. The title is "Delivery Ticket". The
+heading is a literal in `HeaderBlock.tsx`, so `PackingSlipData` gains a
+`title` field.
+- **`RentalAgreementSummary` / `RentalAgreementLineSummary`**: each unit links to
+ the shipment and receipt that moved it. The summary has no per-unit Deliver
+ or Return: the header starts a document for the agreement, and the unit's
+ page keeps the per-unit shortcuts.
+
+## Acceptance Criteria
+
+- [ ] On Active agreement RA-1 with 5 Pending units, Deliver creates one Draft
+ rental shipment with 5 ticked asset lines. The location is RA-1's
+ location.
+- [ ] The user unticks 2 units, sets Delivered on to 3 days ago, enters
+ meter 120 on one unit and posts. Those 3 lines read `On Rent`, with
+ `deliveredAt` = 3 days ago, and the meter shows as `meterOut` = 120. The
+ other 2 stay `Pending`.
+- [ ] After that post, `itemLedger`, `costLedger` and `journalLine` have no new
+ row for the shipment. Each delivered unit with a tracked entity has one
+ `Rental Delivery` activity.
+- [ ] A second Deliver creates a Draft rental shipment with the 2 remaining
+ units only. Deliver while that Draft exists opens it.
+- [ ] Two Draft rental shipments for one agreement cannot exist. The second
+ insert fails on `shipment_oneOpenDraftPerRentalAgreement_idx`.
+- [ ] If another document delivered a unit in the meantime, `post-shipment`
+ refuses the shipment, and the message names the unit.
+- [ ] `post-shipment` refuses a rental shipment with a Delivered on date in
+ the future.
+- [ ] `post-shipment` refuses a rental shipment that holds an out-of-service
+ unit, and the message names the reason.
+- [ ] Return on RA-1 with 3 units On Rent creates a Draft rental receipt with 3
+ lines. The user receives 1 unit at location B and ticks Take out of
+ service with reason "Hydraulic leak". After the post, the line is
+ `Returned`, the asset's `locationId` is B, and the fleet register shows
+ the unit `In Maintenance`.
+- [ ] A returned `Rental` line billed in Advance gets the same early-return
+ adjustment row as today's Return action. A test pins the periods against
+ the old path.
+- [ ] A `Sale` line on a rental receipt cannot post without Return To. With
+ Return To = Inventory it writes the same `itemLedger` row and journal as
+ today's return.
+- [ ] The per-unit Return shortcut on a unit page creates a one-unit Draft
+ receipt. A user can post it from that page in 2 clicks.
+- [ ] Voiding a rental shipment returns its units to `Pending` and clears
+ `deliveredAt` and `meterOut`. If a posted revenue recognition run holds
+ an `Accrual` row for one of its units, `post-shipment` refuses the void.
+- [ ] `post-receipt` refuses to void a rental receipt with "A rental return
+ cannot be voided. Correct the unit by hand."
+- [ ] Close refuses an agreement with a Draft rental receipt that has a line,
+ and the message names the receipt.
+- [ ] Inventory → Shipments lists the rental shipment with source "Rental
+ Agreement", and the source links to the agreement.
+- [ ] The rental shipment's PDF prints a Delivery Ticket with the 3 delivered
+ units and their serial numbers.
+- [ ] A sales order shipment with a fixed-asset line posts exactly as before.
+ Its asset line keeps `salesOrderLineId`, and `rentalAgreementLineId` is
+ null.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Moving `returnUnit` changes the billing re-cut | High | Move the code without edits. Pin the periods with a test that runs the old and the new path on the same fixture. |
+| A reader of `shipmentFixedAssetLine` assumes `salesOrderLineId` is set | Med | Check every reader: post-shipment SO case, `shipmentToSalesInvoice`, and `accounting.service.ts` related documents. Filter on `salesOrderLineId IS NOT NULL` where the code means a sales order line. |
+| A backdated delivery falls in a month that a posted recognition run already closed | Med | The next month's run does not accrue the earlier month's days. A new run for that month does. If that month is closed, the invoice posting recognizes the rent. A test pins this behavior. |
+| A sales-only user can no longer deliver | Low | This matches the sales order. Note it in the changelog entry. |
+| `post-receipt` reaches the silent default case for a rental receipt | High | Add the explicit case. Add a test that a rental receipt ends `Posted`. |
+| A unit delivered before this change has no shipment | Low | The rental receipt reads the line status, not the shipment. That unit returns normally. |
+
+## Out of Scope
+
+- Billing from the delivery date (Q4).
+- A separate off-rent date on the receipt (Q3).
+- An "Awaiting Inspection" fleet status, an inspection step and signature
+ capture (Q5).
+- Rental receipt void (Q6).
+- A transfer document when a unit returns to another yard (Q2).
+- Bulk or non-serialized rental units. A rental line still holds one unit.
+
+## Open Questions
+
+- [x] **Q1 — Do the documents replace the Deliver and Return actions, or sit
+ next to them?** — **Answer:** Replace them. The per-unit shortcut opens
+ a one-unit draft, so a counter pickup takes 2 clicks. The billing
+ re-cut becomes shared code that the receipt posting calls.
+- [x] **Q2 — Which yard does a delivery ship from, and where does a returned
+ unit end up?** — **Answer:** The shipment ships from the agreement's
+ location. A unit from another yard gets no warning. Posting a receipt
+ sets `fixedAsset.locationId` to the receipt's location. The document
+ must record whether, when and where. Exact yard matching is not
+ important.
+- [x] **Q3 — Which date stops billing on a return?** — **Answer:** One date.
+ The post modal asks for Delivered on or Returned on. The user can
+ backdate it but cannot set it in the future. No separate off-rent date.
+- [x] **Q4 — Does the delivery date start billing?** — **Answer:** No.
+ Billing runs from the agreement start date. Billing from delivery is out
+ of scope.
+- [x] **Q5 — What do we record about the condition of a unit?** — **Answer:**
+ Meter out on the shipment line. Meter in, notes and Take out of service
+ on the receipt line. Photos use the document attachments. Damage stays
+ an agreement charge. No inspection status and no signature.
+- [x] **Q6 — Can a user void a rental shipment or receipt?** — **Answer:** A
+ user can void a rental shipment while every unit is still On Rent. No
+ posted recognition run may hold an `Accrual` row for its units. A user
+ cannot void a rental receipt.
+
+- [x] **Q7 — A `Sale` line returns to Inventory or Fleet at which location?**
+ — **Answer:** The receipt's location. It defaults to the agreement's
+ location, so the two differ only when the user changes it.
+- [x] **Q8 — A `Pending` unit can no longer be returned. How does an
+ agreement end it?** — **Answer:** Both paths. A rental receipt holds
+ every `Pending` unit with `received = false`, and the user ticks it to
+ return it. A **Release unit** action ends it without a document.
+
+## Changelog
+
+- 2026-10-07: Created. Q1–Q6 resolved with Brad before writing. Research:
+ `.ai/research/rental-delivery-and-return.md`.
+- 2026-10-07: The post modal supplies the date. A set `postingDate` means
+ posted in the UI, so a Draft cannot hold it.
+- 2026-10-08: Planning corrections. The void also refuses an `Accrual` row
+ claimed by a Draft run. The Close check runs first. Rental lines get their
+ own components. Q7 and Q8 resolved with Brad.
+- 2026-10-08: Browser-test polish. The header shows the units' equipment
+ status. The agreement summary drops its per-unit Deliver and Return. Rental
+ unit rows share `RentalUnitRow` and sort by asset id. A posted document's
+ unit lines are read-only, in the UI and in `fixed-asset-lines.update`.
diff --git a/.claude/rules/fixed-asset-lifecycle.md b/.claude/rules/fixed-asset-lifecycle.md
index f96fa65f5c..6871083f09 100644
--- a/.claude/rules/fixed-asset-lifecycle.md
+++ b/.claude/rules/fixed-asset-lifecycle.md
@@ -493,14 +493,19 @@ line's accounting treatment (`lessorClassification`) is set at activation:
`Rental` / `Sale` / `Financing` (ASC 842 operating / sales-type / direct
financing lease; `Financing` has no input). A **`Rental`** line posts no journal at activation, the asset stays `Active` and keeps
depreciating, and only the derived fleet status changes (Reserved → On Rent →
-Available again, or In Maintenance when the return form's out-of-service box is
-ticked — `post-rental-agreement` `return` sets `outOfServiceSince =
-returnedAt` and the reason). `post-rental-agreement` `activate` accepts a unit
+Available again, or In Maintenance when the rental receipt line's **Take out of
+service** box is ticked — `returnRentalUnit`, `post-rental-agreement/return-unit.ts`,
+sets `outOfServiceSince = returnedAt` and the reason). A unit goes On Rent when a
+rental shipment posts (`post-shipment`, source `'Rental Agreement'`) and comes back
+when a rental receipt posts (`post-receipt`); neither writes an `itemLedger` row or a
+journal for a `Rental` line. Posting the receipt sets `fixedAsset.locationId` to the
+receipt's location. **Release unit** (`post-rental-agreement` `release`) ends a
+Pending unit that never left the yard and does not move it. See
+`apps/erp/app/modules/sales/AGENTS.md` → Rentals → Deliver and return. `post-rental-agreement` `activate` accepts a unit
whose `fleetStatus` is `Available`, or `Reserved` by the same agreement, and
whose asset status is `Active` / `Fully Depreciated`; `In Maintenance` is
-refused with "<unit> is out of service: <reason>". Deliver
-(`x+/rental-agreement+/$id.$lineId.deliver.tsx`) is refused while the unit
-reads In Maintenance. **Return to Inventory is refused while the unit is on a
+refused with "<unit> is out of service: <reason>". Posting a rental shipment
+refuses an out-of-service unit with the same message. **Return to Inventory is refused while the unit is on a
live rental line**: `post-asset-transfer` `returnToInventory` checks for a
`rentalAgreementLine` with `status IN ('Pending','On Rent')` inside its
transaction and throws "Asset <id> is on rent|reserved on rental agreement
@@ -530,8 +535,8 @@ refuses a line without a fleet unit, so the spec's from-stock commencement has
no entry point in v1.
**Residual return capitalizes a NEW Rental Fleet asset.** Returning a
-`Sale` line at or after `endDate` with `residualDestination: "Fleet"`
-(`returnResidual`) inserts a new `fixedAsset` (new `fixedAssetId` from the
+`Sale` line on a rental receipt at or after `endDate` with `residualDestination: "Fleet"`
+(`returnResidual`) inserts a new `fixedAsset` at the receipt's location (new `fixedAssetId` from the
sequence) in the non-CIP class named "Rental Fleet" (else the class the unit
left at commencement; neither → "No Rental Fleet asset class to return the
unit into; create one or return the unit to inventory") with `acquisitionCost`
@@ -549,7 +554,7 @@ Cr Net Investment in Leases (skipped when accounting is off or closing is 0);
the entity stays `Consumed` with `Fixed Asset` = the new asset and a
`Capitalize` activity. The disposed original is untouched (the live-serial
unique index ignores Disposed rows). `residualDestination: "Inventory"`
-instead books `bookAdjustment` +1 at `fixedUnitCost` = closing and Dr the
+instead books `bookAdjustment` +1 at the receipt's location at `fixedUnitCost` = closing and Dr the
item's inventory account. Schedule lines and Planned Interest rows dated on or
before the return STAY and post through later recognition runs (that is what
brings Net Investment in Leases to zero: initial NI + Σ interest − Σ rent −
@@ -681,7 +686,9 @@ two-step (ship → invoice) flow.
- `Reserved` means "named on a live Pending line", which includes every line of
a DRAFT agreement. Cancelling an agreement deletes its Pending lines (the
line status enum has no Cancelled), which is what frees the unit.
-- A `Rental` line (operating lease) never changes `fixedAsset.status` or `locationId`:
- custody is the agreement's `customerLocationId`, exposed on `fleetAssets`. A
+- A `Rental` line (operating lease) never changes `fixedAsset.status`. Its
+ `locationId` changes only when a rental receipt posts: the unit is then at the
+ receipt's location. While it is out, custody is the agreement's
+ `customerLocationId`, exposed on `fleetAssets`. A
`Sale` line (sales-type lease) disposes the asset at activation (above), and a residual
return creates a different asset row rather than reviving the old one.
diff --git a/.claude/rules/shipments-receipts-ui-patterns.md b/.claude/rules/shipments-receipts-ui-patterns.md
index 3acfe1977d..639ca81c63 100644
--- a/.claude/rules/shipments-receipts-ui-patterns.md
+++ b/.claude/rules/shipments-receipts-ui-patterns.md
@@ -18,13 +18,19 @@ only holds the two list routes `shipments.tsx` / `receipts.tsx`).
- `new.tsx` — **action only**. Creates the doc by calling the **`create` server function**
(`create(ServerFnContext.system({ db, companyId, userId }), { type, locationId, ...sourceIds })`),
then `throw redirect(path.to.shipmentDetails(id))`. There is **no `upsert` on create** — the
- server function allocates the human ID and copies source-document lines.
+ server function allocates the human ID and copies source-document lines. For the
+ `'Rental Agreement'` source it first redirects to the agreement's existing Draft (one Draft
+ rental shipment and one Draft rental receipt per agreement, enforced by the partial unique
+ indexes `shipment_oneOpenDraftPerRentalAgreement_idx` / `receipt_oneOpenDraftPerRentalAgreement_idx`),
+ else invokes `create` with `shipmentFromRentalAgreement` / `receiptFromRentalAgreement`.
- `$id.tsx` — layout loader: parallel `getShipment` / `getShipmentLines` / `getShipmentTracking`,
plus fixed-asset lines (`shipmentFixedAssetLine`) and related items. Receipt also loads
`getReceiptFiles`, `getBatchProperties`, `getShelfLifeForItems`, `companySettings`. Renders `<Outlet/>`.
- `$id._index.tsx` — redirects to `…/details`.
- `$id.details.tsx` — renders Form + Lines + Notes. **Action**: validate, then if `sourceDocument`
changed re-invoke `create`, else `upsertShipment` / `upsertReceipt` (Supabase upsert, sets `updatedBy`).
+ A rental document refuses a change of source ("A rental shipment keeps its rental agreement.
+ Create it from the agreement.").
- `$id.post.tsx` — see posting flow below.
- `$id.void.tsx` — guards status, invokes post fn with `type: "void"`.
- `$id.delete.tsx` — `deleteShipment` / `deleteReceipt` service fn; **guard: blocked once `postingDate` is set**.
@@ -38,7 +44,13 @@ only holds the two list routes `shipments.tsx` / `receipts.tsx`).
return line's item and shipped to that return's customer on a posted shipment).
- `lines.split.tsx` — invokes `create` with `type: "shipmentLineSplit"` / `receiptLineSplit`.
- `lines.$id.delete.tsx` — `deleteShipmentLine` / `deleteReceiptLine`.
-- `fixed-asset-lines.update.tsx` — upsert `shipmentFixedAssetLine` (`shipped`/`received` bool, `serialNumber`).
+- `fixed-asset-lines.update.tsx` — update one field of a `shipmentFixedAssetLine` / `receiptFixedAssetLine`,
+ parsed by `shipmentFixedAssetLineUpdateValidator` / `receiptFixedAssetLineUpdateValidator`
+ (`inventory.models.ts`): `shipped`/`received`, `serialNumber`, `meter`; the receipt also takes
+ `notes`, `outOfService` ("" clears the tick, any other text is the reason, so tick and reason save
+ together) and `residualDestination`. It refuses a line whose document is not Draft ("A posted
+ shipment can no longer be changed" / "A posted receipt can no longer be changed"): a posted
+ document is a record, the meter included.
- `_layout.tsx` — breadcrumb handle back to `path.to.inventory`.
Navigate via the typed `path.to.*` helpers (`shipmentDetails`, `shipment`, `shipmentPost`,
@@ -53,7 +65,9 @@ Navigate via the typed `path.to.*` helpers (`shipmentDetails`, `shipment`, `ship
(shipment: `getShipmentRelatedItems`; receipt: `getReceiptRelatedItems`, which also resolves a
sales return's customer), receipt inspections and line attachments, the shipment's packing slip
(only for the sources its PDF route renders: Sales Order, Sales Invoice, Purchase Order,
- Outbound Transfer — `PACKING_SLIP_SOURCES`) — and whose Activity tab is the audit log.
+ Outbound Transfer, Rental Agreement — `PACKING_SLIP_SOURCES`; a rental shipment prints as a
+ "Delivery Ticket", one row per shipped unit with its serial number, through the `title` field of
+ `PackingSlipData`) — and whose Activity tab is the audit log.
- **Form** (`ShipmentForm.tsx`, `ReceiptForm/ReceiptForm.tsx`): flat `ValidatedForm` (no Card),
source-document `Select` + dependent `Combobox` (ID), `Location`, custom fields. The
`use{Shipment,Receipt}Form` hook fetches
@@ -68,6 +82,17 @@ Navigate via the typed `path.to.*` helpers (`shipmentDetails`, `shipment`, `ship
`requiresSerialTracking`. **Receipt** batch/serial forms add an **expiration date** (batch date
shows only when item shelf-life mode is "Set on Receipt") and a per-line **FileDropzone**;
shipment forms do not.
+- **Rental lines**: on a `'Rental Agreement'` document the loader reads `getRentalShipmentLines` /
+ `getRentalReceiptLines` into `rentalLines`, rendered by the siblings `ShipmentRentalLineItem` /
+ `ReceiptRentalLineItem` (no storage unit picker, no serial tracking). Both render the unit through
+ the shared `RentalUnitRow` (`ui/Shipments/RentalUnitRow.tsx`: tick, item thumbnail, unit name, asset
+ id and serial, and **Meter** — a `NumberField` while Draft, plain text once posted; laid out on the
+ row's own `@container`). Shipment: the shipped tick and **Meter**. Receipt adds **Notes**, the
+ **Take out of service** switch (a `@carbon/form` `Boolean` inside a field-context-only
+ `ValidatedForm`, saved through the same per-field update) with its reason, and **Return To**
+ (Fleet / Inventory) for a unit treated as a sale. The loaders sort `rentalLines` by asset id so the
+ list holds still across edits. The existing fixed-asset components need an order line id, which a
+ rental line does not have.
- **Notes**: shipment uses `ShipmentNotes` (Card with **internal + external** tabbed editors).
Receipt details reuses `SupplierInteractionNotes` (**internal notes only**) — there is no
`ReceiptNotes` component.
@@ -77,6 +102,9 @@ Navigate via the typed `path.to.*` helpers (`shipmentDetails`, `shipment`, `ship
serials reconciled across indices `0..receivedQuantity`; uses `useRuleViolations`),
`ShipmentVoidModal` / `ReceiptVoidModal` (destructive `Alert` + bulleted consequences, submit
via `fetcher.Form` to the void route). Shipment posting is gated by `ShipmentPostModal.tsx`.
+ On a rental document the post modals show a date field, **Delivered on** / **Returned on**
+ (default company today, no future date), sent as `postingDate`; `ReceiptPostModal` also blocks a
+ ticked unit treated as a sale that has no Return To.
**Both post modals are source-aware for return flows**, and must stay in step with
`lines.tracking`'s guard or they reject what tracking accepted:
`ReceiptPostModal` counts a serial slot as filled when the entity is merely ASSIGNED on a
@@ -94,17 +122,21 @@ On error it reverts status to `Draft`. May then auto-print and (sales shipment)
slip PDF; receipt may call `update-purchased-prices` when `updateLeadTimesOnReceipt` is set.
`post-receipt` and `post-shipment` (`packages/server-functions/src/`) take
-`{ type: "post" | "void", {receipt,shipment}Id }` (the context carries `companyId` / `userId`), run
+`{ type: "post" | "void", {receipt,shipment}Id, postingDate? }` (the context carries `companyId` / `userId`;
+`postingDate` is read only by the rental source, and `$id.post.tsx` passes it from the modal), run
the service-role client + Kysely `db.transaction()`, and branch on `sourceDocument`:
-- **post-receipt** handles `Purchase Order`, `Inbound Transfer`, and `Sales Return Order`
+- **post-receipt** handles `Purchase Order`, `Inbound Transfer`, `Rental Agreement` (returns each
+ ticked unit through `returnRentalUnit` and moves its `fixedAsset.locationId` to the receipt's
+ location; `post-receipt/rental-agreement.ts`), and `Sales Return Order`
(customer RMA re-entry at original outbound cost, entities to On Hold). PO path: inserts `itemLedger`
(entry types `Positive/Negative Adjmt.` by sign), GR/IR + inventory `journalLine`s when
`accountingEnabled`, advances PO line `quantityReceived`/`receivedComplete` and PO `status`,
flips tracked entities to `Available` (**`On Hold` if the item has a Receipt-usage inspection
document assignment**), and
creates one `inspection` lot per inspected line (see `inspection-system.md`).
-- **post-shipment** handles `Sales Order`, `Purchase Order`, `Outbound Transfer`,
+- **post-shipment** handles `Rental Agreement` (puts each ticked unit On Rent on the delivery
+ date; no `itemLedger`, `costLedger` or journal; `post-shipment/rental-agreement.ts`), `Sales Order`, `Purchase Order`, `Outbound Transfer`,
`Sales Return Order` (return-to-customer), and `Purchase Return Order` (supplier return,
Cr Inventory / Dr GR/IR; the `create` server function seeds the shipment's tracked entities from
`purchaseReturnOrderLineTrackedEntity`, and this path **splits** a batch when the returned
@@ -128,6 +160,10 @@ applies.
- **`void`** (post fn, `type: "void"`): requires `status === "Posted"`; receipt also blocks if
`invoiced` (and only PO-sourced receipts can void). Posts reversing `itemLedger` + `journalLine`s,
rolls back source-document quantities, restores tracked entities to `Available`, sets `status: "Voided"`.
+ A rental shipment voids while every unit is still On Rent and no `Accrual` row of its lines is
+ Posted or held by a Draft run: the units go back to Pending. `post-receipt` refuses a rental
+ receipt void ("A rental return cannot be voided. Correct the unit by hand.").
+ The rental lifecycle itself is in `apps/erp/app/modules/sales/AGENTS.md` → Rentals.
## Gotchas
diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.md
index aeb809b1e4..2ff5e31e17 100644
--- a/apps/erp/app/modules/inventory/AGENTS.md
+++ b/apps/erp/app/modules/inventory/AGENTS.md
@@ -7,8 +7,8 @@ Tracks item quantities across locations and storage units. Manages receipts, shi
- **Storage Unit** — hierarchical container (bin, shelf, rack, zone) within a location. Tree structure via `parentId`. Renamed from `shelf` in migration `20260417000100`. MUST use `storageUnit` naming, never `shelf`. Bulk **CSV import** is wired via the shared import system (`table: "storageUnit"`, permission `inventory`): fields `id`, `name`, `locationId`, `parentName`, `storageTypeNames`, `active`; matched on `(locationId, lower(name))` since names are unique per location, parents linked in a second pass. See `.claude/rules/csv-import-system.md`.
- **Tracked Entity** — serial/batch/lot-tracked item instance with `readableId` (serial or batch number), `status` (Available/Reserved/On Hold/Consumed/Rejected/Scrapped), `quantity`, and `expirationDate`. `Scrapped` is terminal but recoverable via the Unscrap adjustment. Batch items have `batchProperty` definitions. A serialized unit can leave stock as a fixed asset: the storage-unit row action **Capitalize as Fixed Asset** (`ui/Inventory/InventoryStorageUnits.tsx`, rows with a `trackedEntityId`, needs `create: accounting`) opens `path.to.fixedAssetCapitalize` with `itemId`, `trackedEntityId`, `locationId` and `storageUnitId` as search params; the `post-asset-transfer` server function then consumes the unit (`Consumed`, `attributes["Fixed Asset"]`, a `'Capitalize'` `trackedActivity`, `itemLedger` −1 `'Asset Transfer'`) at its carrying cost, and **Return to Inventory** on the asset brings the same unit back `Available` at net book value. See `.claude/rules/fixed-asset-lifecycle.md`.
- **Item Ledger** — append-only log of every inventory movement (`itemLedger` table). Source of truth for on-hand quantities. MUST never INSERT directly — always go through service functions.
-- **Receipt** — inbound inventory from POs, transfers, or customer RMAs (source "Sales Return Order"). Lines link to `purchaseOrderLine`, jobs, or `salesReturnOrderLine`. Posting creates ledger entries and tracked entities; RMA receipts re-enter at the original outbound cost (shipment consumption rows), current cost for blind returns, or zero when the return reason flags `inventoryValueZero`, and reactivate the SAME tracked entity On Hold (ReturnEntityForm re-tags the Consumed entity instead of minting a new serial).
-- **Shipment** — outbound inventory to customers, or return flows: source "Purchase Return Order" ships supplier returns (Cr Inventory / Dr GRNI at carried cost), source "Sales Return Order" ships rejected RMA claims back to the customer (On Hold entities allowed in lines.tracking for that source only).
+- **Receipt** — inbound inventory from POs, transfers, customer RMAs (source "Sales Return Order"), or rental units coming back (source "Rental Agreement"). Lines link to `purchaseOrderLine`, jobs, or `salesReturnOrderLine`. Posting creates ledger entries and tracked entities; RMA receipts re-enter at the original outbound cost (shipment consumption rows), current cost for blind returns, or zero when the return reason flags `inventoryValueZero`, and reactivate the SAME tracked entity On Hold (ReturnEntityForm re-tags the Consumed entity instead of minting a new serial). A rental receipt holds no `receiptLine`: each unit is a `receiptFixedAssetLine` with `rentalAgreementLineId`, and posting returns the unit on its agreement and moves its `fixedAsset.locationId` to the receipt's location, with no `itemLedger` row or journal for a `Rental` line (see sales AGENTS → Rentals → Deliver and return). A rental receipt cannot be voided.
+- **Shipment** — outbound inventory to customers, or return flows: source "Purchase Return Order" ships supplier returns (Cr Inventory / Dr GRNI at carried cost), source "Sales Return Order" ships rejected RMA claims back to the customer (On Hold entities allowed in lines.tracking for that source only), source "Rental Agreement" delivers rental units: each unit is a `shipmentFixedAssetLine` with `rentalAgreementLineId`, posting puts it On Rent and writes no `itemLedger`, `costLedger` or journal row, and its PDF prints as a "Delivery Ticket".
- **Stock Transfer** — moves inventory between storage units within the same location.
- **Warehouse Transfer** — moves inventory between locations (inter-location).
- **Picking List** — generated pick instructions with FEFO/FIFO ordering and tracked entity allocation.
@@ -49,7 +49,9 @@ pnpm exec turbo run typecheck --filter=erp # the app's package name is "erp",
| `storageType` | Storage unit type definitions (capacity, constraints) |
| `trackedEntity` | Serial/batch/lot instances with readableId, status, quantity, expirationDate |
| `receipt` / `receiptLine` | Inbound documents from POs or production |
+| `receiptFixedAssetLine` | One fixed asset per row on a receipt: `purchaseOrderLineId` (a PO receipt) XOR `rentalAgreementLineId` (a rental receipt; CHECK `receiptFixedAssetLine_source_check`), `received`, `serialNumber`. The rental return fields: `meter`, `notes`, `takeOutOfService` + `outOfServiceReason` (CHECK: a tick needs a reason; the UI saves both as one `outOfService` field), `residualDestination` (`Fleet` / `Inventory`, a `Sale` line only). Edited through `receipt+/fixed-asset-lines.update.tsx` (`receiptFixedAssetLineUpdateValidator`), which refuses a line on a non-Draft receipt |
| `shipment` / `shipmentLine` | Outbound documents to customers |
+| `shipmentFixedAssetLine` | One fixed asset per row on a shipment: `salesOrderLineId` (a sales order shipment) XOR `rentalAgreementLineId` (a rental shipment; CHECK `shipmentFixedAssetLine_source_check`), `shipped`, `serialNumber`, and `meter` (a rental unit's meter out). Edited through `shipment+/fixed-asset-lines.update.tsx` (`shipmentFixedAssetLineUpdateValidator`), which refuses a line on a non-Draft shipment. A reader that means a sales order line filters `salesOrderLineId IS NOT NULL` |
| `stockTransfer` / `stockTransferLine` | Intra-location moves between storage units |
| `warehouseTransfer` / `warehouseTransferLine` | Inter-location moves |
| `kanban` | Pull-based replenishment signals |
@@ -69,6 +71,7 @@ pnpm exec turbo run typecheck --filter=erp # the app's package name is "erp",
- `getAvailableTrackedEntities` — calls `get_available_tracked_entities` RPC
- `getReceipts` / `getReceiptLines` / `reconcileReceiptSerialEntities` — receipt management
- `getShipments` / `getShipmentLines` / `getShipmentRelatedItems` — shipment management
+- `getRentalShipmentLines` / `getRentalReceiptLines` — a rental document's asset lines with their rental line, fleet asset, item and tracked entity; the `$shipmentId.tsx` / `$receiptId.tsx` loaders call them for the `'Rental Agreement'` source and pass them as `rentalLines` (sorted by asset id, else unit name) to `ShipmentRentalLineItem` / `ReceiptRentalLineItem`. Both readers order by `createdAt, id`: a document's units are inserted in one statement and share a `createdAt`
- `getReceiptRelatedItems` / `getWarehouseTransferRelatedItems` / `getPickingListRelatedItems` — the `DocumentPage` Documents panels (receipt invoices + a sales return's customer; a transfer's shipments and receipts; a picking list's jobs). Query errors are logged and degrade to empty lists
- `generatePickingList` / `getPickingListAvailability` / `getPickingSchedule` — picking operations
- `getDefaultStorageUnitOrStorageUnitWithHighestQuantity` — picking defaults
diff --git a/apps/erp/app/modules/inventory/inventory.models.test.ts b/apps/erp/app/modules/inventory/inventory.models.test.ts
index b162736900..8c1aadbb7b 100644
--- a/apps/erp/app/modules/inventory/inventory.models.test.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.test.ts
@@ -4,7 +4,9 @@
import { describe, expect, it } from "vitest";
import {
+ receiptFixedAssetLineUpdateValidator,
resolveStockTransferPickForward,
+ shipmentFixedAssetLineUpdateValidator,
storageTypeValidator,
storageUnitValidator
} from "./inventory.models";
@@ -132,3 +134,65 @@ describe("resolveStockTransferPickForward", () => {
expect(r.ok).toBe(true);
});
});
+
+describe("shipmentFixedAssetLineUpdateValidator", () => {
+ it("rejects a negative meter reading", () => {
+ const r = shipmentFixedAssetLineUpdateValidator.safeParse({
+ id: "sfal1",
+ field: "meter",
+ value: "-1"
+ });
+ expect(r.success).toBe(false);
+ });
+
+ it("accepts an empty or a positive meter reading", () => {
+ for (const value of ["", "120"]) {
+ const r = shipmentFixedAssetLineUpdateValidator.safeParse({
+ id: "sfal1",
+ field: "meter",
+ value
+ });
+ expect(r.success).toBe(true);
+ }
+ });
+
+ it("rejects an unknown field", () => {
+ const r = shipmentFixedAssetLineUpdateValidator.safeParse({
+ id: "sfal1",
+ field: "notes",
+ value: "scratched"
+ });
+ expect(r.success).toBe(false);
+ });
+});
+
+describe("receiptFixedAssetLineUpdateValidator", () => {
+ it("rejects a negative meter reading", () => {
+ const r = receiptFixedAssetLineUpdateValidator.safeParse({
+ id: "rfal1",
+ field: "meter",
+ value: "-1"
+ });
+ expect(r.success).toBe(false);
+ });
+
+ it("accepts an empty or a positive meter reading", () => {
+ for (const value of ["", "120"]) {
+ const r = receiptFixedAssetLineUpdateValidator.safeParse({
+ id: "rfal1",
+ field: "meter",
+ value
+ });
+ expect(r.success).toBe(true);
+ }
+ });
+
+ it("rejects an unknown field", () => {
+ const r = receiptFixedAssetLineUpdateValidator.safeParse({
+ id: "rfal1",
+ field: "shipped",
+ value: "true"
+ });
+ expect(r.success).toBe(false);
+ });
+});
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.ts
index 464b94f7e8..4fc69ca134 100644
--- a/apps/erp/app/modules/inventory/inventory.models.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.ts
@@ -99,7 +99,8 @@ export const receiptSourceDocumentType = [
"Purchase Order",
"Purchase Invoice",
// "Purchase Return Order",
- "Inbound Transfer"
+ "Inbound Transfer",
+ "Rental Agreement"
// "Outbound Transfer",
// "Manufacturing Consumption",
// "Manufacturing Output",
@@ -368,7 +369,8 @@ export const shipmentSourceDocumentType = [
// "Purchase Invoice",
"Purchase Return Order",
// "Inbound Transfer",
- "Outbound Transfer"
+ "Outbound Transfer",
+ "Rental Agreement"
] as const;
export const shippingCarrierType = [
@@ -393,6 +395,70 @@ export const shipmentValidator = z.object({
customerId: zfd.text(z.string().optional())
});
+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"])
+ })
+ ]
+);
+
export const shippingMethodValidator = z.object({
id: zfd.text(z.string().optional()),
name: z.string().trim().min(1, { message: "Name is required" }),
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 97d2f965c4..4abb073da8 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -1433,6 +1433,50 @@ export async function getShipmentTracking(
.eq("companyId", companyId);
}
+/** @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, thumbnailPath, type), trackedEntity(readableId))"
+ )
+ .eq("shipmentId", shipmentId)
+ .eq("companyId", companyId)
+ .not("rentalAgreementLineId", "is", null)
+ // A document's units are inserted in one statement and share a createdAt;
+ // without a tie-breaker an update reorders them.
+ .order("createdAt")
+ .order("id")
+ );
+}
+
+/** @mcp read */
+export async function getRentalReceiptLines(
+ client: SupabaseClient<Database>,
+ receiptId: string,
+ companyId: string
+) {
+ return (
+ client
+ .from("receiptFixedAssetLine")
+ .select(
+ "id, received, meter, notes, takeOutOfService, outOfServiceReason, residualDestination, rentalAgreementLineId, rentalAgreementLine!receiptFixedAssetLine_rentalAgreementLineId_fkey(id, status, lessorClassification, fixedAsset(id, fixedAssetId, name, serialNumber), item(name, readableIdWithRevision, thumbnailPath, type), trackedEntity(readableId))"
+ )
+ .eq("receiptId", receiptId)
+ .eq("companyId", companyId)
+ .not("rentalAgreementLineId", "is", null)
+ // A document's units are inserted in one statement and share a createdAt;
+ // without a tie-breaker an update reorders them.
+ .order("createdAt")
+ .order("id")
+ );
+}
+
/** @mcp read */
export async function getShipmentLineTracking(
client: SupabaseClient<Database>,
diff --git a/apps/erp/app/modules/inventory/types.ts b/apps/erp/app/modules/inventory/types.ts
index a6296752eb..56015a6719 100644
--- a/apps/erp/app/modules/inventory/types.ts
+++ b/apps/erp/app/modules/inventory/types.ts
@@ -104,6 +104,30 @@ export type ShippingMethod = NonNullable<
export type ShipmentSourceDocument =
Database["public"]["Enums"]["shipmentSourceDocument"];
+export type RentalShipmentLine = {
+ id: string;
+ rentalAgreementLineId: string;
+ shipped: boolean;
+ meter: number | null;
+ unitName: string;
+ thumbnailPath: string | null;
+ itemType: Database["public"]["Enums"]["itemType"] | null;
+ 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;
+};
+
export type StockTransfer = NonNullable<
Awaited<ReturnType<typeof getStockTransfers>>["data"]
>[number];
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptDocuments.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptDocuments.tsx
index 02b26570a7..290e072946 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptDocuments.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptDocuments.tsx
@@ -9,6 +9,7 @@ import {
LuClipboardCheck,
LuContainer,
LuCreditCard,
+ LuKeyRound,
LuShoppingCart,
LuSquareUser,
LuTruck,
@@ -94,6 +95,14 @@ function useSourceDocument(receipt?: Receipt): DocumentLink | null {
label: t`Sales Return`
}
: null;
+ case "Rental Agreement":
+ return permissions.can("view", "sales")
+ ? {
+ to: path.to.rentalAgreementDetails(id),
+ icon: <LuKeyRound />,
+ label: t`Rental Agreement`
+ }
+ : null;
default:
return null;
}
@@ -163,6 +172,9 @@ const ReceiptDocuments = () => {
if (!receipt) return null;
const isSalesReturn = receipt.sourceDocument === "Sales Return Order";
+ // A rental receipt has no supplier, and `receipt` has no customer.
+ const hidesSupplier =
+ isSalesReturn || receipt.sourceDocument === "Rental Agreement";
const inspections = permissions.can("view", "quality")
? (routeData?.receiptInspections ?? [])
: [];
@@ -171,7 +183,7 @@ const ReceiptDocuments = () => {
const receiptFiles = routeData?.receiptFiles;
const supplierRow =
- !isSalesReturn && supplierParty ? (
+ !hidesSupplier && supplierParty ? (
<RelatedDocument
to={supplierParty.to}
icon={supplierParty.icon}
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
index 7fd3f5a612..cfdc6f88c4 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
@@ -48,6 +48,7 @@ const ReceiptForm = ({ initialValues, status }: ReceiptFormProps) => {
} = useReceiptForm({ status, initialValues });
const isPosted = status === "Posted";
+ const isRental = initialValues.sourceDocument === "Rental Agreement";
const isEditing = initialValues.id !== undefined;
return (
@@ -70,16 +71,18 @@ const ReceiptForm = ({ initialValues, status }: ReceiptFormProps) => {
name="sourceDocument"
label={t`Source Document`}
termId="receipt-source-document"
- options={receiptSourceDocumentType.map((v) => ({
- label: v,
- value: v
- }))}
+ options={receiptSourceDocumentType
+ .filter((v) => isRental || v !== "Rental Agreement")
+ .map((v) => ({
+ label: v,
+ value: v
+ }))}
onChange={(newValue) => {
if (newValue) {
setSourceDocument(newValue.value as ReceiptSourceDocument);
}
}}
- isReadOnly={isPosted}
+ isReadOnly={isPosted || isRental}
/>
<Combobox
name="sourceDocumentId"
@@ -89,7 +92,7 @@ const ReceiptForm = ({ initialValues, status }: ReceiptFormProps) => {
label: d.name,
value: d.id
}))}
- isReadOnly={isPosted}
+ isReadOnly={isPosted || isRental}
/>
<Location
name="locationId"
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
index 34766ed38d..ecb8ef2d8d 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
@@ -113,6 +113,10 @@ export default function useReceiptForm({
});
break;
+ case "Rental Agreement":
+ // Created from the agreement; the initial option already holds its
+ // readable id, and the source cannot change.
+ break;
default:
setSourceDocuments([]);
}
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
index 4e58c34e87..96763c7e2f 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
@@ -33,6 +33,7 @@ const ReceiptHeader = () => {
receiptLines: ReceiptLine[];
receiptLineTracking: ItemTracking[];
fixedAssetLines: { id: string; received: boolean }[];
+ rentalLines: { id: string; received: boolean }[];
}>(path.to.receipt(receiptId));
const permissions = usePermissions();
@@ -57,9 +58,13 @@ const ReceiptHeader = () => {
const hasReceivableFaLines = (routeData?.fixedAssetLines ?? []).some(
(line) => line.received
);
+ const hasReceivableRentalLines = (routeData?.rentalLines ?? []).some(
+ (line) => line.received
+ );
const canPost =
receiptLines.some((line) => (line.receivedQuantity ?? 0) !== 0) ||
- hasReceivableFaLines;
+ hasReceivableFaLines ||
+ hasReceivableRentalLines;
const hasTrackingLabels = (routeData?.receiptLineTracking ?? []).length > 0;
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index 833d8f03ba..e941dca031 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -4,7 +4,7 @@
import { useCarbon } from "@carbon/auth";
import { isPreviewableDocumentType, storage } from "@carbon/files";
-import { Number, Submit, ValidatedForm } from "@carbon/form";
+import { Boolean, Number, Submit, ValidatedForm } from "@carbon/form";
import { useAction, useRevalidator } from "@carbon/query";
import {
Button,
@@ -34,6 +34,9 @@ import {
ModalTitle,
NumberField,
NumberInput,
+ RadioGroup,
+ RadioGroupItem,
+ Textarea,
Tooltip,
TooltipContent,
TooltipTrigger,
@@ -63,6 +66,7 @@ import {
useParams,
useSubmit
} from "react-router";
+import { z } from "zod";
import {
DocumentPreview,
Empty,
@@ -80,7 +84,8 @@ import type {
BatchProperty,
ItemTracking,
Receipt,
- ReceiptLine
+ ReceiptLine,
+ RentalReceiptLine
} from "~/modules/inventory";
import { splitValidator } from "~/modules/inventory";
import { getDocumentType } from "~/modules/shared/shared.service";
@@ -90,6 +95,7 @@ import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
import BatchPropertiesConfig from "../Batches/BatchPropertiesConfig";
import { BatchPropertiesFields } from "../Batches/BatchPropertiesFields";
+import { RentalUnitRow } from "../Shipments/RentalUnitRow";
import { ReturnEntityForm } from "./ReturnEntityForm";
const ReceiptLines = () => {
@@ -112,6 +118,7 @@ const ReceiptLines = () => {
received: boolean;
serialNumber: string | null;
}[];
+ rentalLines: RentalReceiptLine[];
receiptFiles: PostgrestResponse<StorageItem>;
receiptLineTracking: ItemTracking[];
batchProperties: PostgrestResponse<BatchProperty>;
@@ -243,61 +250,65 @@ const ReceiptLines = () => {
const isPosted =
routeData?.receipt.status === "Posted" ||
routeData?.receipt.status === "Voided";
+ const isRental = routeData?.receipt?.sourceDocument === "Rental Agreement";
return (
<>
- <Card>
- <CardHeader>
- <CardTitle>
- <Trans>Receipt Lines</Trans>
- </CardTitle>
- </CardHeader>
-
- <CardContent>
- <div className="border rounded-lg">
- {receiptLines.length === 0 ? (
- <Empty className="py-6" />
- ) : (
- receiptLines.map((line, index) => {
- const trackingCandidates =
- routeData?.receiptLineTracking?.filter((t) => {
- const attributes = t.attributes as TrackedEntityAttributes;
- return attributes["Receipt Line"] === line.id;
- }) ?? [];
- const tracking =
- trackingCandidates.find((t) => t.expirationDate) ??
- trackingCandidates[0];
- return (
- <ReceiptLineItem
- key={line.id}
- line={line}
- receipt={routeData?.receipt}
- isReadOnly={isPosted}
- onUpdate={onUpdateReceiptLine}
- files={routeData?.receiptFiles}
- className={
- index === receiptLines.length - 1 ? "border-none" : ""
- }
- serialNumbers={serialNumbersByLineId[line.id!] || []}
- getPath={(file) => getPath(file, line.id!)}
- onSerialNumbersChange={(newSerialNumbers) => {
- setSerialNumbersByLineId((prev) => ({
- ...prev,
- [line.id!]: newSerialNumbers
- }));
- }}
- batchProperties={routeData?.batchProperties}
- itemShelfLife={routeData?.itemShelfLife}
- tracking={tracking}
- upload={(files) => upload(files, line.id!)}
- deleteFile={(file) => deleteFile(file, line.id!)}
- />
- );
- })
- )}
- </div>
- </CardContent>
- </Card>
+ {!isRental && (
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <Trans>Receipt Lines</Trans>
+ </CardTitle>
+ </CardHeader>
+
+ <CardContent>
+ <div className="border rounded-lg">
+ {receiptLines.length === 0 ? (
+ <Empty className="py-6" />
+ ) : (
+ receiptLines.map((line, index) => {
+ const trackingCandidates =
+ routeData?.receiptLineTracking?.filter((t) => {
+ const attributes =
+ t.attributes as TrackedEntityAttributes;
+ return attributes["Receipt Line"] === line.id;
+ }) ?? [];
+ const tracking =
+ trackingCandidates.find((t) => t.expirationDate) ??
+ trackingCandidates[0];
+ return (
+ <ReceiptLineItem
+ key={line.id}
+ line={line}
+ receipt={routeData?.receipt}
+ isReadOnly={isPosted}
+ onUpdate={onUpdateReceiptLine}
+ files={routeData?.receiptFiles}
+ className={
+ index === receiptLines.length - 1 ? "border-none" : ""
+ }
+ serialNumbers={serialNumbersByLineId[line.id!] || []}
+ getPath={(file) => getPath(file, line.id!)}
+ onSerialNumbersChange={(newSerialNumbers) => {
+ setSerialNumbersByLineId((prev) => ({
+ ...prev,
+ [line.id!]: newSerialNumbers
+ }));
+ }}
+ batchProperties={routeData?.batchProperties}
+ itemShelfLife={routeData?.itemShelfLife}
+ tracking={tracking}
+ upload={(files) => upload(files, line.id!)}
+ deleteFile={(file) => deleteFile(file, line.id!)}
+ />
+ );
+ })
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ )}
{routeData?.fixedAssetLines && routeData.fixedAssetLines.length > 0 && (
<Card>
<CardHeader>
@@ -323,6 +334,35 @@ const ReceiptLines = () => {
</CardContent>
</Card>
)}
+ {isRental && (
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <Trans>Rental Units</Trans>
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <div className="border rounded-lg">
+ {(routeData?.rentalLines ?? []).length === 0 ? (
+ <Empty className="py-6" />
+ ) : (
+ routeData!.rentalLines.map((line, index) => (
+ <ReceiptRentalLineItem
+ key={line.id}
+ line={line}
+ isReadOnly={isPosted}
+ className={
+ index < routeData!.rentalLines.length - 1
+ ? "border-b"
+ : ""
+ }
+ />
+ ))
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ )}
<Outlet />
</>
);
@@ -395,6 +435,155 @@ function ReceiptFixedAssetLineItem({
);
}
+function ReceiptRentalLineItem({
+ line,
+ isReadOnly,
+ className
+}: {
+ line: RentalReceiptLine;
+ isReadOnly: boolean;
+ className?: string;
+}) {
+ const { t } = useLingui();
+ const fetcher = useFetcher();
+ const [notes, setNotes] = useState(line.notes ?? "");
+ const [takeOutOfService, setTakeOutOfService] = useState(
+ line.takeOutOfService
+ );
+ const [outOfServiceReason, setOutOfServiceReason] = useState(
+ line.outOfServiceReason ?? ""
+ );
+ // Unique per line: the switch's id is its field name.
+ const outOfServiceField = `takeOutOfService-${line.id}`;
+
+ const updateField = (field: string, value: string) => {
+ const formData = new FormData();
+ formData.append("id", line.id);
+ formData.append("field", field);
+ formData.append("value", value);
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.receiptFixedAssetLineUpdate
+ });
+ };
+
+ return (
+ <div className={cn("@container flex flex-col gap-6 p-6", className)}>
+ <RentalUnitRow
+ line={line}
+ checked={line.received}
+ checkedLabel={t`Received`}
+ isReadOnly={isReadOnly}
+ onCheckedChange={(checked) => updateField("received", String(checked))}
+ onMeterChange={(meter) => updateField("meter", meter)}
+ />
+ <VStack spacing={4}>
+ <VStack spacing={1}>
+ <label className="text-xs text-muted-foreground">
+ <Trans>Notes</Trans>
+ </label>
+ <Textarea
+ aria-label={t`Notes`}
+ value={notes}
+ disabled={isReadOnly}
+ onChange={(e) => setNotes(e.target.value)}
+ onBlur={() => {
+ if (notes !== (line.notes ?? "")) {
+ updateField("notes", notes);
+ }
+ }}
+ />
+ </VStack>
+ <VStack spacing={2}>
+ {/* A form only for the field's context: the switch saves through
+ updateField like every other field on the line. */}
+ <ValidatedForm
+ defaultValues={{ [outOfServiceField]: line.takeOutOfService }}
+ validator={z.object({ [outOfServiceField]: z.any() })}
+ className="w-full"
+ >
+ <Boolean
+ name={outOfServiceField}
+ label={t`Take out of service`}
+ bordered
+ value={takeOutOfService}
+ isDisabled={isReadOnly}
+ onChange={(isTicked) => {
+ setTakeOutOfService(isTicked);
+ if (!isTicked) {
+ setOutOfServiceReason("");
+ updateField("outOfService", "");
+ }
+ }}
+ />
+ </ValidatedForm>
+ {takeOutOfService && (
+ <>
+ <Input
+ aria-label={t`Reason`}
+ placeholder={t`Reason`}
+ value={outOfServiceReason}
+ isDisabled={isReadOnly}
+ onChange={(e) => setOutOfServiceReason(e.target.value)}
+ onBlur={() => {
+ const reason = outOfServiceReason.trim();
+ if (reason && reason !== (line.outOfServiceReason ?? "")) {
+ updateField("outOfService", reason);
+ }
+ }}
+ />
+ {!line.outOfServiceReason && (
+ <span className="text-xs text-muted-foreground">
+ <Trans>Enter a reason to take the unit out of service</Trans>
+ </span>
+ )}
+ </>
+ )}
+ {line.lessorClassification === "Sale" && (
+ <VStack spacing={1} className="pt-2">
+ <label className="text-xs text-muted-foreground">
+ <Trans>Return To</Trans>
+ </label>
+ <RadioGroup
+ value={line.residualDestination ?? ""}
+ disabled={isReadOnly}
+ onValueChange={(value) =>
+ updateField("residualDestination", value)
+ }
+ >
+ <HStack spacing={2}>
+ <RadioGroupItem
+ value="Fleet"
+ id={`${line.id}:residualDestination:Fleet`}
+ />
+ <label
+ htmlFor={`${line.id}:residualDestination:Fleet`}
+ className="text-sm"
+ >
+ <Trans>Rental fleet, as a new fleet asset</Trans>
+ </label>
+ </HStack>
+ <HStack spacing={2}>
+ <RadioGroupItem
+ value="Inventory"
+ id={`${line.id}:residualDestination:Inventory`}
+ />
+ <label
+ htmlFor={`${line.id}:residualDestination:Inventory`}
+ className="text-sm"
+ >
+ <Trans>Inventory, as finished goods</Trans>
+ </label>
+ </HStack>
+ </RadioGroup>
+ </VStack>
+ )}
+ </VStack>
+ </VStack>
+ </div>
+ );
+}
+
function ReceiptLineItem({
line,
receipt,
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
index 4b6bbebb50..22901a426c 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
@@ -9,6 +9,9 @@ import {
AlertDescription,
AlertTitle,
Button,
+ DatePicker,
+ FormControl,
+ FormLabel,
HStack,
Modal,
ModalBody,
@@ -23,16 +26,17 @@ import {
} from "@carbon/react";
import type { TrackedEntityAttributes } from "@carbon/utils";
import { getItemReadableId } from "@carbon/utils";
+import { parseDate } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import { LuTriangleAlert } from "react-icons/lu";
import { useNavigation, useParams } from "react-router";
-import { useUser } from "~/hooks";
+import { useCompanyToday, useUser } from "~/hooks";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import { reconcileReceiptLineSerials } from "../../inventory.models";
import { getReceiptTracking } from "../../inventory.service";
-import type { Receipt, ReceiptLine } from "../../types";
+import type { Receipt, ReceiptLine, RentalReceiptLine } from "../../types";
const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
const { receiptId } = useParams();
@@ -47,8 +51,13 @@ const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
id: string;
received: boolean;
}[];
+ rentalLines: RentalReceiptLine[];
}>(path.to.receipt(receiptId));
+ const isRental = routeData?.receipt?.sourceDocument === "Rental Agreement";
+ const companyToday = useCompanyToday();
+ const [postingDate, setPostingDate] = useState(companyToday);
+
const navigation = useNavigation();
const [validated, setValidated] = useState(false);
@@ -89,8 +98,11 @@ const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
const hasFaLines = (routeData?.fixedAssetLines ?? []).some(
(line) => line.received
);
+ const hasRentalLines = (routeData?.rentalLines ?? []).some(
+ (line) => line.received
+ );
- if (!hasReceiptLines && !hasFaLines) {
+ if (!hasReceiptLines && !hasFaLines && !hasRentalLines) {
setValidationErrors([
{
itemReadableId: null,
@@ -165,6 +177,22 @@ const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
}
});
+ // A unit returned from a rental treated as a sale must say where it goes.
+ (routeData?.rentalLines ?? []).forEach((line) => {
+ if (
+ line.received &&
+ line.lessorClassification === "Sale" &&
+ !line.residualDestination
+ ) {
+ const unitName = line.unitName;
+ errors.push({
+ itemReadableId: line.assetReadableId,
+ receivedQuantity: 1,
+ receivedQuantityError: t`Choose Return To for ${unitName}`
+ });
+ }
+ });
+
setValidationErrors(errors);
setValidated(true);
};
@@ -194,6 +222,19 @@ const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
</ModalTitle>
</ModalHeader>
<ModalBody>
+ {isRental && (
+ <FormControl className="mb-4">
+ <FormLabel>
+ <Trans>Returned on</Trans>
+ </FormLabel>
+ <DatePicker
+ aria-label={t`Returned on`}
+ value={parseDate(postingDate)}
+ maxValue={parseDate(companyToday)}
+ onChange={(d) => d && setPostingDate(d.toString())}
+ />
+ </FormControl>
+ )}
{validationErrors.length > 0 ? (
<Alert variant="destructive">
<LuTriangleAlert className="h-4 w-4" />
@@ -230,7 +271,9 @@ const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
<form
onSubmit={(e) => {
e.preventDefault();
- ruleViolations.submit(new FormData());
+ const formData = new FormData();
+ if (isRental) formData.set("postingDate", postingDate);
+ ruleViolations.submit(formData);
}}
>
<Button
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
index e7675df488..93cc22cf9b 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
@@ -143,6 +143,16 @@ const ReceiptsTable = memo(({ data, count }: ReceiptsTableProps) => {
{row.original.sourceDocumentReadableId}
</Hyperlink>
);
+ case "Rental Agreement":
+ return (
+ <Hyperlink
+ to={path.to.rentalAgreementDetails(
+ row.original.sourceDocumentId!
+ )}
+ >
+ {row.original.sourceDocumentReadableId}
+ </Hyperlink>
+ );
default:
return null;
}
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/RentalUnitRow.tsx b/apps/erp/app/modules/inventory/ui/Shipments/RentalUnitRow.tsx
new file mode 100644
index 0000000000..bc25866be1
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/Shipments/RentalUnitRow.tsx
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import {
+ Badge,
+ Checkbox,
+ HStack,
+ NumberField,
+ NumberInput,
+ VStack
+} from "@carbon/react";
+import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { ItemThumbnail } from "~/components";
+import { useQuantityFormatter } from "~/hooks";
+import type { RentalShipmentLine } from "../../types";
+
+type RentalUnitRowProps = {
+ line: Omit<RentalShipmentLine, "shipped">;
+ checked: boolean;
+ checkedLabel: string;
+ isReadOnly: boolean;
+ onCheckedChange: (checked: boolean) => void;
+ onMeterChange: (meter: string) => void;
+};
+
+/** One rental unit on a rental shipment or receipt, laid out like an
+ * ordinary document line: the unit (thumbnail, name, asset id and serial)
+ * takes what the meter leaves, and the meter stays on the same line once the
+ * row is wide enough. Sized by the row's own `@container`. */
+export function RentalUnitRow({
+ line,
+ checked,
+ checkedLabel,
+ isReadOnly,
+ onCheckedChange,
+ onMeterChange
+}: RentalUnitRowProps) {
+ const { t } = useLingui();
+ const formatQuantity = useQuantityFormatter();
+ const identifiers = [line.assetReadableId, line.serialNumber]
+ .filter(Boolean)
+ .join(" · ");
+
+ return (
+ <div className="flex flex-col @3xl:flex-row @3xl:items-center gap-4 w-full">
+ <HStack spacing={4} className="flex-1 min-w-0">
+ <Checkbox
+ aria-label={checkedLabel}
+ isChecked={checked}
+ disabled={isReadOnly}
+ onCheckedChange={(value) => onCheckedChange(value === true)}
+ />
+ <ItemThumbnail
+ size="md"
+ thumbnailPath={line.thumbnailPath}
+ type={(line.itemType as "Part") ?? "Part"}
+ />
+ <VStack spacing={0} className="flex-1 min-w-0">
+ <HStack spacing={2} className="w-full min-w-0">
+ <span
+ className="text-sm font-medium truncate"
+ title={line.unitName}
+ >
+ {line.unitName}
+ </span>
+ {line.lineStatus === "Pending" && (
+ <Badge variant="secondary" className="shrink-0">
+ <Trans>Not delivered</Trans>
+ </Badge>
+ )}
+ </HStack>
+ {identifiers && (
+ <span className="text-xs text-muted-foreground truncate w-full">
+ {identifiers}
+ </span>
+ )}
+ </VStack>
+ </HStack>
+ <VStack spacing={1} className="w-auto shrink-0 pl-8 @3xl:pl-0">
+ <label className="text-xs text-muted-foreground">
+ <Trans>Meter</Trans>
+ </label>
+ {isReadOnly ? (
+ // Posted: the meter is a record of what was read, not an input.
+ <span className="text-sm py-1.5">
+ {line.meter === null ? "—" : formatQuantity(line.meter)}
+ </span>
+ ) : (
+ // react-aria commits on blur (or Enter); an emptied field commits NaN.
+ <NumberField
+ aria-label={t`Meter`}
+ defaultValue={line.meter ?? undefined}
+ formatOptions={INPUT_FORMAT.quantity}
+ step={INPUT_STEP.quantity}
+ minValue={0}
+ onChange={(value) => {
+ const next = value == null || isNaN(value) ? null : value;
+ if (next === line.meter) return;
+ onMeterChange(next === null ? "" : String(next));
+ }}
+ >
+ <NumberInput size="sm" className="w-32" />
+ </NumberField>
+ )}
+ </VStack>
+ </div>
+ );
+}
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentDocuments.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentDocuments.tsx
index 9dfefdab0e..770fdfe3e1 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentDocuments.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentDocuments.tsx
@@ -9,6 +9,7 @@ import {
LuBarcode,
LuContainer,
LuCreditCard,
+ LuKeyRound,
LuShoppingCart,
LuSquareUser,
LuTruck,
@@ -34,7 +35,8 @@ const PACKING_SLIP_SOURCES = new Set<string>([
"Sales Order",
"Sales Invoice",
"Purchase Order",
- "Outbound Transfer"
+ "Outbound Transfer",
+ "Rental Agreement"
]);
type SourceDocument = {
@@ -99,6 +101,14 @@ function useSourceDocument(shipment?: Shipment): SourceDocument | null {
label: t`Sales Return`
}
: null;
+ case "Rental Agreement":
+ return permissions.can("view", "sales")
+ ? {
+ to: path.to.rentalAgreementDetails(id),
+ icon: <LuKeyRound />,
+ label: t`Rental Agreement`
+ }
+ : null;
default:
return null;
}
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx
index 5b4ea2ea06..04d1cdb1a0 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx
@@ -53,6 +53,7 @@ const ShipmentForm = ({ initialValues, status }: ShipmentFormProps) => {
} = useShipmentForm({ status, initialValues });
const isPosted = status === "Posted";
+ const isRental = initialValues.sourceDocument === "Rental Agreement";
const isEditing = initialValues.id !== undefined;
return (
@@ -75,16 +76,18 @@ const ShipmentForm = ({ initialValues, status }: ShipmentFormProps) => {
name="sourceDocument"
label={t`Source Document`}
termId="shipment-source-document"
- options={shipmentSourceDocumentType.map((v) => ({
- label: v,
- value: v
- }))}
+ options={shipmentSourceDocumentType
+ .filter((v) => isRental || v !== "Rental Agreement")
+ .map((v) => ({
+ label: v,
+ value: v
+ }))}
onChange={(newValue) => {
if (newValue) {
setSourceDocument(newValue.value as ShipmentSourceDocument);
}
}}
- isReadOnly={isPosted}
+ isReadOnly={isPosted || isRental}
/>
<Combobox
key={sourceDocument}
@@ -95,7 +98,7 @@ const ShipmentForm = ({ initialValues, status }: ShipmentFormProps) => {
label: d.name,
value: d.id
}))}
- isReadOnly={isPosted}
+ isReadOnly={isPosted || isRental}
/>
<Location
name="locationId"
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/useShipmentForm.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/useShipmentForm.tsx
index 439f0303a1..646c709840 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/useShipmentForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/useShipmentForm.tsx
@@ -148,6 +148,10 @@ export default function useShipmentForm({
}
});
break;
+ case "Rental Agreement":
+ // Created from the agreement; the initial option already holds its
+ // readable id, and the source cannot change.
+ break;
default:
setSourceDocuments([]);
}
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
index 9b8b900dda..ce9ac2f453 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
@@ -35,6 +35,7 @@ const ShipmentHeader = () => {
shipmentLines: ShipmentLine[];
shipmentLineTracking: ItemTracking[];
fixedAssetLines: { id: string; shipped: boolean }[];
+ rentalLines: { id: string; shipped: boolean }[];
relatedItems?: Promise<{ invoices: SalesInvoice[] }>;
}>(path.to.shipment(shipmentId));
@@ -54,9 +55,13 @@ const ShipmentHeader = () => {
const hasShippableFaLines = (routeData?.fixedAssetLines ?? []).some(
(line) => line.shipped
);
+ const hasShippableRentalLines = (routeData?.rentalLines ?? []).some(
+ (line) => line.shipped
+ );
const canPost =
shipmentLines.some((line) => (line.shippedQuantity ?? 0) !== 0) ||
- hasShippableFaLines;
+ hasShippableFaLines ||
+ hasShippableRentalLines;
const hasTrackingLabels = (routeData?.shipmentLineTracking ?? []).length > 0;
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
index 2746127760..e42b2db63e 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
@@ -72,6 +72,7 @@ import type {
getBatchNumbersForItem,
getSerialNumbersForItem,
ItemTracking,
+ RentalShipmentLine,
Shipment,
ShipmentLine,
ShipmentLineTracking
@@ -80,6 +81,7 @@ import { splitValidator } from "~/modules/inventory";
import type { action as shipmentLinesUpdateAction } from "~/routes/x+/shipment+/lines.update";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
+import { RentalUnitRow } from "./RentalUnitRow";
const ShipmentLines = () => {
const { shipmentId } = useParams();
@@ -102,6 +104,7 @@ const ShipmentLines = () => {
shipped: boolean;
serialNumber: string | null;
}[];
+ rentalLines: RentalShipmentLine[];
}>(path.to.shipment(shipmentId));
const shipmentsById = new Map<string, ShipmentLine>(
@@ -232,71 +235,76 @@ const ShipmentLines = () => {
const isPosted = routeData?.shipment?.status === "Posted";
const isVoided = routeData?.shipment?.status === "Voided";
const isReadOnly = isPosted || isVoided;
+ const isRental = routeData?.shipment?.sourceDocument === "Rental Agreement";
return (
<>
- <Card>
- <HStack className="justify-between items-start">
- <CardHeader>
- <CardTitle>
- <Trans>Shipment Lines</Trans>
- </CardTitle>
- </CardHeader>
- </HStack>
+ {!isRental && (
+ <Card>
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>
+ <Trans>Shipment Lines</Trans>
+ </CardTitle>
+ </CardHeader>
+ </HStack>
- <CardContent>
- <div className="border rounded-lg">
- {shipmentLines.length === 0 ? (
- <Empty className="py-6" />
- ) : (
- shipmentLines
- .map((line) => ({
- ...line,
- itemReadableId: getItemReadableId(items, line.itemId) ?? ""
- }))
- .sort((a, b) =>
- a.itemReadableId.localeCompare(b.itemReadableId)
- )
- .map((line, index) => {
- const tracking = routeData?.shipmentLineTracking?.find(
- (t) => {
- const attributes =
- t.attributes as TrackedEntityAttributes;
- return attributes["Shipment Line"] === line.id;
- }
- );
- return (
- <ShipmentLineItem
- key={line.id}
- line={line}
- shipment={routeData?.shipment}
- hasTrackingLabel={
- routeData?.shipmentLineTracking?.some((t) => {
- const attributes =
- t.attributes as TrackedEntityAttributes;
- return attributes["Shipment Line"] === line.id;
- }) ?? false
- }
- isReadOnly={isReadOnly}
- onUpdate={onUpdateShipmentLine}
- className={
- index === shipmentLines.length - 1 ? "border-none" : ""
+ <CardContent>
+ <div className="border rounded-lg">
+ {shipmentLines.length === 0 ? (
+ <Empty className="py-6" />
+ ) : (
+ shipmentLines
+ .map((line) => ({
+ ...line,
+ itemReadableId: getItemReadableId(items, line.itemId) ?? ""
+ }))
+ .sort((a, b) =>
+ a.itemReadableId.localeCompare(b.itemReadableId)
+ )
+ .map((line, index) => {
+ const tracking = routeData?.shipmentLineTracking?.find(
+ (t) => {
+ const attributes =
+ t.attributes as TrackedEntityAttributes;
+ return attributes["Shipment Line"] === line.id;
}
- serialNumbers={serialNumbersByLineId[line.id!] || []}
- onSerialNumbersChange={(newSerialNumbers) => {
- setSerialNumbersByLineId((prev) => ({
- ...prev,
- [line.id!]: newSerialNumbers
- }));
- }}
- tracking={tracking}
- />
- );
- })
- )}
- </div>
- </CardContent>
- </Card>
+ );
+ return (
+ <ShipmentLineItem
+ key={line.id}
+ line={line}
+ shipment={routeData?.shipment}
+ hasTrackingLabel={
+ routeData?.shipmentLineTracking?.some((t) => {
+ const attributes =
+ t.attributes as TrackedEntityAttributes;
+ return attributes["Shipment Line"] === line.id;
+ }) ?? false
+ }
+ isReadOnly={isReadOnly}
+ onUpdate={onUpdateShipmentLine}
+ className={
+ index === shipmentLines.length - 1
+ ? "border-none"
+ : ""
+ }
+ serialNumbers={serialNumbersByLineId[line.id!] || []}
+ onSerialNumbersChange={(newSerialNumbers) => {
+ setSerialNumbersByLineId((prev) => ({
+ ...prev,
+ [line.id!]: newSerialNumbers
+ }));
+ }}
+ tracking={tracking}
+ />
+ );
+ })
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ )}
{routeData?.fixedAssetLines && routeData.fixedAssetLines.length > 0 && (
<Card>
<CardHeader>
@@ -322,6 +330,35 @@ const ShipmentLines = () => {
</CardContent>
</Card>
)}
+ {isRental && (
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <Trans>Rental Units</Trans>
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <div className="border rounded-lg">
+ {(routeData?.rentalLines ?? []).length === 0 ? (
+ <Empty className="py-6" />
+ ) : (
+ routeData!.rentalLines.map((line, index) => (
+ <ShipmentRentalLineItem
+ key={line.id}
+ line={line}
+ isReadOnly={isReadOnly}
+ className={
+ index < routeData!.rentalLines.length - 1
+ ? "border-b"
+ : ""
+ }
+ />
+ ))
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ )}
<Outlet />
</>
);
@@ -394,6 +431,43 @@ function ShipmentFixedAssetLineItem({
);
}
+function ShipmentRentalLineItem({
+ line,
+ isReadOnly,
+ className
+}: {
+ line: RentalShipmentLine;
+ isReadOnly: boolean;
+ className?: string;
+}) {
+ const { t } = useLingui();
+ const fetcher = useFetcher();
+
+ const updateField = (field: string, value: string) => {
+ const formData = new FormData();
+ formData.append("id", line.id);
+ formData.append("field", field);
+ formData.append("value", value);
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.shipmentFixedAssetLineUpdate
+ });
+ };
+
+ return (
+ <div className={cn("@container p-6", className)}>
+ <RentalUnitRow
+ line={line}
+ checked={line.shipped}
+ checkedLabel={t`Shipped`}
+ isReadOnly={isReadOnly}
+ onCheckedChange={(checked) => updateField("shipped", String(checked))}
+ onMeterChange={(meter) => updateField("meter", meter)}
+ />
+ </div>
+ );
+}
+
function ShipmentLineItem({
line,
shipment,
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
index 81a73cbc69..f753e0f6c0 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
@@ -9,6 +9,9 @@ import {
AlertDescription,
AlertTitle,
Button,
+ DatePicker,
+ FormControl,
+ FormLabel,
HStack,
Modal,
ModalBody,
@@ -29,7 +32,7 @@ import { useState } from "react";
import { LuTriangleAlert } from "react-icons/lu";
import { useNavigation, useParams } from "react-router";
import { DateTime } from "~/components";
-import { useSettings, useUser } from "~/hooks";
+import { useCompanyToday, useSettings, useUser } from "~/hooks";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import type { Shipment, ShipmentLine } from "../..";
@@ -50,8 +53,13 @@ const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {
id: string;
shipped: boolean;
}[];
+ rentalLines: { id: string; shipped: boolean }[];
}>(path.to.shipment(shipmentId));
+ const isRental = routeData?.shipment?.sourceDocument === "Rental Agreement";
+ const companyToday = useCompanyToday();
+ const [postingDate, setPostingDate] = useState(companyToday);
+
// Return-to-customer shipments (source "Sales Return Order") ship returned
// stock, which is deliberately On Hold until shipped back — mirror the
// status lines.tracking required when the entity was assigned.
@@ -122,8 +130,11 @@ const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {
const hasFaLines = (routeData?.fixedAssetLines ?? []).some(
(line) => line.shipped
);
+ const hasRentalLines = (routeData?.rentalLines ?? []).some(
+ (line) => line.shipped
+ );
- if (!hasShipmentLines && !hasFaLines) {
+ if (!hasShipmentLines && !hasFaLines && !hasRentalLines) {
setValidationErrors([
{
itemReadableId: null,
@@ -267,6 +278,19 @@ const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {
<p className="text-sm text-muted-foreground mb-4">
<Trans>Are you sure you want to post this shipment?</Trans>
</p>
+ {isRental && (
+ <FormControl className="mb-4">
+ <FormLabel>
+ <Trans>Delivered on</Trans>
+ </FormLabel>
+ <DatePicker
+ aria-label={t`Delivered on`}
+ value={parseDate(postingDate)}
+ maxValue={parseDate(companyToday)}
+ onChange={(d) => d && setPostingDate(d.toString())}
+ />
+ </FormControl>
+ )}
{validationErrors.length > 0 && (
<Alert variant="destructive">
<LuTriangleAlert className="h-4 w-4" />
@@ -350,7 +374,9 @@ const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {
<form
onSubmit={(e) => {
e.preventDefault();
- ruleViolations.submit(new FormData());
+ const formData = new FormData();
+ if (isRental) formData.set("postingDate", postingDate);
+ ruleViolations.submit(formData);
}}
>
<Button
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx
index 2d5e721319..aee7b5acc3 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx
@@ -153,6 +153,16 @@ const ShipmentsTable = memo(({ data, count }: ShipmentsTableProps) => {
{row.original.sourceDocumentReadableId}
</Hyperlink>
);
+ case "Rental Agreement":
+ return (
+ <Hyperlink
+ to={path.to.rentalAgreementDetails(
+ row.original.sourceDocumentId!
+ )}
+ >
+ {row.original.sourceDocumentReadableId}
+ </Hyperlink>
+ );
default:
return null;
}
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/utils.ts b/apps/erp/app/modules/inventory/ui/Traceability/utils.ts
index c0c09160ae..9a389d3825 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/utils.ts
+++ b/apps/erp/app/modules/inventory/ui/Traceability/utils.ts
@@ -756,6 +756,8 @@ export function sourceLinkHref(
return `/x/picking-list/${id}`;
case "Stock Transfer":
return `/x/stock-transfer/${id}`;
+ case "Rental Agreement":
+ return `/x/rental-agreement/${id}/details`;
default:
return null;
}
diff --git a/apps/erp/app/modules/sales/AGENTS.md b/apps/erp/app/modules/sales/AGENTS.md
index 429084eec3..ec861095e4 100644
--- a/apps/erp/app/modules/sales/AGENTS.md
+++ b/apps/erp/app/modules/sales/AGENTS.md
@@ -122,14 +122,14 @@ Service functions: the admin CRUD is NOT in `sales.service.ts`. The read helpers
## Rentals (sub-area)
-Rental of serialized fleet units (fixed assets with an `itemId`), each line's accounting treatment (`lessorClassification`) set at activation: `Rental` or `Sale` (ASC 842 operating / sales-type lease; the enum's third value `Financing`, a direct financing lease, has no input). UI heading "Accounting treatment". Lives inside this module: validators in `sales.models.ts`, services in the "Rental agreements (spec §3)" section of `sales.service.ts`, Kysely wrappers in `sales.server.ts`, UI in `ui/Rentals/`, routes `x+/sales+/rental-agreements.tsx` (list, nav entry "Rental Agreements" in the `Manage` group of `useSalesSubmodules`) and `x+/rental-agreement+/` (`new` = setup step 1; `$id.setup` + `$id.setup.{details,units,billing,accounting,review}` = the wizard (see Setup wizard below); `$id` is the sales-order-style shell — `RentalAgreementHeader` top bar + `ResizablePanels` with `RentalAgreementExplorer` (one row per unit, Add Unit while Draft), the center `<Outlet />` and `RentalAgreementProperties` (every term, editable while Draft and read-only after; each field saves through `x+/rental-agreement+/update.tsx`, which re-reads the agreement, swaps the one field in and runs the whole `rentalAgreementValidator` + `updateRentalAgreement` on the merged terms, so a cross-field rule such as "reasonably certain needs an end date" still holds; a customer change clears the site and contact); `$id.details` renders `RentalAgreementSummary` (sales-order-style: units as line items with rates, status and their Deliver / Return buttons from `useRentalLineActions`, then billed / unbilled / monthly rent / deposit / next due), the Accounting Treatment preview while Draft, Charges, Billing Periods and Deposits; `$id.$lineId.details` is the unit's page: `RentalAgreementLineSummary` (status, Deliver / Return / Sell / Remove), `RentalAgreementLineForm` as a card, and that unit's charges and periods). Unit lifecycle actions live in one hook, `useRentalLineActions`, and open as page state (confirms, the return form, the charge form, the add-unit form) posting through fetchers to action-only routes (`lines.new`, `charges.new`, `$lineId.return`, `$lineId.deliver`, `$lineId.sell`, …), which redirect to `requestReferrer(request)` so acting from a unit's page stays there — except Close / Cancel (`$id.status`, Cancel deletes Pending lines) and line delete, which go to `/details`. Schema: `20261006220301_fleet-rental-lease-enums.sql` (incl. `journalEntrySourceType` `'Lease'`), `20261006220501_rental-agreements.sql` (tables incl. `customerItemRentalRate` and `rentalLeaseScheduleLine`), `20261006221101_rental-invoice-automation.sql`. Spec §3–§4 of `.ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md` Part I; the plan's execution notes (Tasks 36–54) record where the build deviated.
+Rental of serialized fleet units (fixed assets with an `itemId`), each line's accounting treatment (`lessorClassification`) set at activation: `Rental` or `Sale` (ASC 842 operating / sales-type lease; the enum's third value `Financing`, a direct financing lease, has no input). UI heading "Accounting treatment". Lives inside this module: validators in `sales.models.ts`, services in the "Rental agreements (spec §3)" section of `sales.service.ts`, Kysely wrappers in `sales.server.ts`, UI in `ui/Rentals/`, routes `x+/sales+/rental-agreements.tsx` (list, nav entry "Rental Agreements" in the `Manage` group of `useSalesSubmodules`) and `x+/rental-agreement+/` (`new` = setup step 1; `$id.setup` + `$id.setup.{details,units,billing,accounting,review}` = the wizard (see Setup wizard below); `$id` is the sales-order-style shell — `RentalAgreementHeader` top bar (beside `RentalStatus`, an Active agreement shows `RentalEquipmentStatusBadge`: To Deliver / Partially Delivered / On Rent / Partially Returned / Returned, derived from the line statuses by the pure `rentalEquipmentStatus` in `sales.utils.ts` (Sold counts as back; pinned by `sales.utils.test.ts`); on an Active agreement, for `update: sales` + `create: inventory`, **Deliver** / **Return** POST the agreement to `shipment+/new` / `receipt+/new`, which open the agreement's Draft rental document or create one; once the agreement has a document the button becomes a **Shipments** / **Receipts** dropdown with New Shipment / New Receipt and the agreement's documents, read by `getRentalAgreementRelatedDocuments`) + `ResizablePanels` with `RentalAgreementExplorer` (one row per unit, Add Unit while Draft), the center `<Outlet />` and `RentalAgreementProperties` (every term, editable while Draft and read-only after; each field saves through `x+/rental-agreement+/update.tsx`, which re-reads the agreement, swaps the one field in and runs the whole `rentalAgreementValidator` + `updateRentalAgreement` on the merged terms, so a cross-field rule such as "reasonably certain needs an end date" still holds; a customer change clears the site and contact); `$id.details` renders `RentalAgreementSummary` (sales-order-style: units as line items with rates, status, the Posted shipment and receipt that moved each unit (`rentalLineDocuments` in `sales.utils.ts`) — no per-unit actions, delivery and return start from the header — then billed / unbilled / monthly rent / deposit / next due), the Accounting Treatment preview while Draft, Charges, Billing Periods and Deposits; `$id.$lineId.details` is the unit's page: `RentalAgreementLineSummary` (status, Delivered / Returned with their documents, Deliver / Return / Release unit / Sell to Customer / Remove Unit), `RentalAgreementLineForm` as a card, and that unit's charges and periods). Unit lifecycle actions live in one hook, `useRentalLineActions`, and share one rule set: Deliver and Return submit straight to the per-unit shortcut routes `$lineId.deliver` / `$lineId.return` (see Deliver and return below), which redirect into the document. The others open as page state (confirms, `RentalAgreementReleaseForm`, the charge form, the add-unit form) posting through fetchers to action-only routes (`lines.new`, `charges.new`, `$lineId.release`, `$lineId.sell`, …), which redirect to `requestReferrer(request)` so acting from a unit's page stays there — except Close / Cancel (`$id.status`, Cancel deletes Pending lines) and line delete, which go to `/details`. Schema: `20261006220301_fleet-rental-lease-enums.sql` (incl. `journalEntrySourceType` `'Lease'`), `20261006220501_rental-agreements.sql` (tables incl. `customerItemRentalRate` and `rentalLeaseScheduleLine`), `20261006221101_rental-invoice-automation.sql`; the delivery and return documents `20261008155050_rental-documents-enums.sql` + `20261008155056_rental-documents.sql` (spec `.ai/specs/2026-10-07-rental-shipments-and-receipts.md`). Spec §3–§4 of `.ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md` Part I; the plan's execution notes (Tasks 36–54) record where the build deviated.
| Table / View | Purpose |
|---|---|
| `itemRentalRate` | Day / week / month rate ladder per item AND currency (unique `(companyId, itemId, currencyCode)`, CHECK ≥ 1 tier). Edited on the part Sales tab ("Rental Rates" card, serial-tracked parts, base currency only) |
| `customerItemRentalRate` | A ladder agreed with ONE customer or ONE customer type (`num_nonnulls(customerId, customerTypeId) = 1`) for an item and currency, optional `validFrom` / `validTo` (inclusive, gated on the agreement's `startDate`), `notes`. Partial unique indexes: one row per (customer, item, currency) and per (type, item, currency). Migration `20261006220501_rental-agreements.sql`; RLS `company("sales", { read: "sales_view" })`. Edited on the part Sales tab ("Customer Rental Rates" card, `CustomerRentalRates` + `CustomerRentalRateForm` in `modules/items/ui/Item/`, routes `x+/part+/$itemId.sales.rental-rates.{new,$rateId,delete.$rateId}.tsx`). A separate table from `customerItemPriceOverride` on purpose: a rental price is a rate per frequency with no quantity breaks, and pricing rules (percent / fixed on one unit price, quantity ranges) do not apply to rentals |
| `rentalAgreement` / `rentalAgreements` (view) | Header, readable `rentalAgreementId` (sequence `RA`, drawn in `new.tsx` via `getNextSequence`). `status` Draft / Active / Closed / Cancelled; `billingCycle` Calendar Month / 28 Days; `billingTiming` Advance / Arrears; `taxPercent` (0–1 fraction, the rent lines' tax); `depositAmount`; lease-classification inputs `discountRate` (annual %, prefilled in `new.tsx` from `companySettings.leaseDefaultDiscountRate`), `ownershipTransfers`, `specializedAsset`, `purchaseOptionAmount`, `purchaseOptionReasonablyCertain` (the validator refuses it without `endDate`). View adds `customerName`, `lineCount`, `onRentCount`, `nextDueOn`, `unbilledAmount` |
-| `rentalAgreementLine` | One fleet unit (`fixedAssetId`, `quantity` CHECK = 1). `status` Pending / On Rent / Returned / Sold (no Cancelled). `rateUnit` (Day / Week / Month, NOT NULL — the "Rate Frequency") and `rate` (NOT NULL, ≥ 0) = the unit's ONE rate, what billing and classification read. The line form starts `rate` from `getDefaultRentalRates` for the chosen frequency (customer → customer type → item, per frequency, effective on `startDate`) and re-starts it when the unit's item or the frequency changes; the value is the user's to overwrite. `upsertRentalAgreementLine` fills an omitted `rate` the same way (API / the fleet Rent action) and refuses `RENTAL_LINE_NO_RATE` when nothing is on file, `deliveredAt`, `returnedAt`, `meterIn`, `returnNotes`. Lease: inputs `fairValue`, `economicLifeMonths`, `guaranteedResidualValue`, `unguaranteedResidualValue`; set at activation `lessorClassification` (`Rental` / `Sale`; null on a Draft line; `Financing` has no input), `classificationInputs` (JSON `ClassificationInputs` from `lessor-lease` in `@carbon/utils`), `initialNetInvestment` / `sellingProfit` / `commencementJournalId` (`Sale` only); `classificationOverride` + `classificationOverrideReason` (the override route, Draft only). Partial unique index `rentalAgreementLine_asset_live_idx`: one live (Pending / On Rent) line per asset |
+| `rentalAgreementLine` | One fleet unit (`fixedAssetId`, `quantity` CHECK = 1). `status` Pending / On Rent / Returned / Sold (no Cancelled). `rateUnit` (Day / Week / Month, NOT NULL — the "Rate Frequency") and `rate` (NOT NULL, ≥ 0) = the unit's ONE rate, what billing and classification read. The line form starts `rate` from `getDefaultRentalRates` for the chosen frequency (customer → customer type → item, per frequency, effective on `startDate`) and re-starts it when the unit's item or the frequency changes; the value is the user's to overwrite. `upsertRentalAgreementLine` fills an omitted `rate` the same way (API / the fleet Rent action) and refuses `RENTAL_LINE_NO_RATE` when nothing is on file, `deliveredAt` + `meterOut` (written by a posted rental shipment), `returnedAt` + `meterIn` + `returnNotes` (written by a posted rental receipt; Release unit writes `returnedAt` only). Lease: inputs `fairValue`, `economicLifeMonths`, `guaranteedResidualValue`, `unguaranteedResidualValue`; set at activation `lessorClassification` (`Rental` / `Sale`; null on a Draft line; `Financing` has no input), `classificationInputs` (JSON `ClassificationInputs` from `lessor-lease` in `@carbon/utils`), `initialNetInvestment` / `sellingProfit` / `commencementJournalId` (`Sale` only); `classificationOverride` + `classificationOverrideReason` (the override route, Draft only). Partial unique index `rentalAgreementLine_asset_live_idx`: one live (Pending / On Rent) line per asset |
| `rentalAgreementCharge` | Variable charges per line (`chargeType` from enum `rentalInvoiceLineType`, default Charge — set server-side only: `upsertRentalAgreementCharge` always writes `Charge`, `insertRentalPurchaseOptionCharge` writes `Purchase Option`), `chargeDate`, `amount`, `taxPercent`, `salesInvoiceLineId` stamp when billed, `voidedSalesInvoiceId` (set by VOID; makes the re-bill a held draft; sticky across a deleted draft, overwritten by a later VOID) |
| `rentalBillingPeriod` | Persisted periods per line: `periodStart/End`, `days`, `rateUnitApplied`, `amount`, `isAdjustment`, `dueOn`, `status` Pending / Invoiced, `salesInvoiceLineId`, `memoId` (an `isAdjustment` row is billed by a credit memo, never an invoice line — CHECK `rentalBillingPeriod_memo_check`; FK `ON DELETE RESTRICT`, so a Draft rental credit is deleted only through `deleteRentalCreditMemoReleasingPeriods`), `voidedSalesInvoiceId` (set by VOID; makes the re-bill a held draft; sticky across a deleted draft, overwritten by a later VOID). Unique `(companyId, rentalAgreementLineId, periodStart, isAdjustment)` |
| `rentalLeaseScheduleLine` | Effective-interest schedule of a `Sale` line, one row per payment (`periodDate` = its billing period's end, `openingNetInvestment`, `paymentAmount`, `interestAmount`, `principalAmount`, `closingNetInvestment`), written at activation; `journalId` / `postedAt` stamped by `postRevenueRecognitionRun` when its `Interest` row posts (a line that earns no interest has no row and stays unstamped; `earnsInterest`, `lessor-lease` in `@carbon/utils`). Unique `(companyId, rentalAgreementLineId, periodDate)`; `revenueRecognitionSchedule.rentalLeaseScheduleLineId` points at it |
@@ -137,26 +137,29 @@ Rental of serialized fleet units (fixed assets with an `itemId`), each line's ac
RLS on all seven: `sales_view` to read, `sales_create/update/delete` to write — each a `company("sales", { read: "sales_view" })` rule in `packages/database/src/authz/manifest.ts`, shipped by `20261006221501_revenue-recognition-rentals-contracts-rls.sql` (the schedule is written only by service-role posting paths).
- **Billing math** — `packages/utils/src/rental-periods.ts` (pure, `@carbon/utils`). Every amount is billed, so `rateCharge`, `calendarMonthCharge`, `periodCharge` and `generateRentalBillingPeriods` take `decimals` (the agreement currency's `decimalPlaces`, read from `currency` by `post-rental-agreement` and `create-rental-invoices`, `useCurrencyDecimals` in the ERP) and round to it — a part month, an early-return credit and a rate carrying the storage scale; `leasePaymentTerms` (`lessor-lease`) values a sales-type unit on the same rounded payment. `rateCharge` (whole units of the frequency × rate — Month = 28 days), `periodCharge` (a Monthly unit on a Calendar Month agreement is `calendarMonthCharge`, month rate × days ÷ days in month; every other frequency / cycle is `rateCharge`, so a Daily unit bills the days and a Weekly unit the whole weeks of a calendar month), `defaultRentalRates` (a unit's starting rate per frequency), `billingHorizon` (end of next month / today + 28; activation cuts to it through `activationBillingThrough` in `lessor.ts`, capped at `endDate` for a `Sale` line), `generateRentalBillingPeriods` (cuts from the AGREEMENT start date, never delivery; fixed term cut in full; open-ended rolls one period past `through`; holdover keeps billing past `endDate` (`Rental` only — a `Sale` line never gets a period past `endDate`); a return re-cuts the Pending period, and an Advance-billed period past the return gets one negative `isAdjustment` row = billed − charge(days used) priced by the line's own frequency and rate, never positive). Pinned by `packages/utils/src/rental-periods.test.ts`.
-- **Lifecycle** — server function `post-rental-agreement` (`packages/server-functions/src/post-rental-agreement/`; `activate` / `return` / `close` / `cancel`, permissions `update: "sales"`, called by the routes through `serverFns.system`, validators + pure blockers in `validators.ts`). Activate: Draft only, refuses a unit at rate 0 (`unpricedUnitError`), refuses a non-base currency ("Rental agreements in a foreign currency are not supported yet"), checks every unit via the `fleetAssets` view (Available, or Reserved by this same agreement; asset Active / Fully Depreciated; not In Maintenance), bills each line at its own `rateUnit` + `rate` (activation reads no rate card), classifies every line (below), cuts periods to `billingHorizon(today)` (a `Sale` line only up to `endDate`), leaves undelivered lines Pending. No journal for a `Rental` line; a `Sale` line books its commencement. Return: refused when `returnedAt` is after company today (`futureReturnError`: "The return date cannot be in the future"); re-cuts a `Rental` line's periods (a `Sale` line's billing is its term and is left alone), optional `takeOutOfService` sets `fixedAsset.outOfServiceSince/Reason`; a `Sale` line needs `residualDestination` and is refused before `endDate` (below). Close: every line Returned/Sold, no Pending period, no unbilled charge. Cancel: Draft, or Active with no commenced `Sale` line and nothing On Rent/Sold/invoiced/recognized — DELETES the Pending lines (frees the units) and their Pending periods. Deliver is not in the server function: `$id.$lineId.deliver.tsx` updates the line (`deliveredAt` = company today, `On Rent`), refused while the unit is In Maintenance — the `fleetAssets` read uses the service role (scoped to company + unit; a failed or empty read refuses), since a sales user may lack `accounting_view`. `fixed-asset+/$fixedAssetId.out-of-service.tsx` likewise reads `getOnRentLineForAsset` with the service role (an accountant may lack `sales_view`).
+- **Lifecycle** — server function `post-rental-agreement` (`packages/server-functions/src/post-rental-agreement/`; `activate` / `release` / `close` / `cancel`, permissions `update: "sales"`, called by the routes through `serverFns.system`, validators + pure blockers in `validators.ts`). Activate: Draft only, refuses a unit at rate 0 (`unpricedUnitError`), refuses a non-base currency ("Rental agreements in a foreign currency are not supported yet"), checks every unit via the `fleetAssets` view (Available, or Reserved by this same agreement; asset Active / Fully Depreciated; not In Maintenance), bills each line at its own `rateUnit` + `rate` (activation reads no rate card), classifies every line (below), cuts periods to `billingHorizon(today)` (a `Sale` line only up to `endDate`), leaves undelivered lines Pending. No journal for a `Rental` line; a `Sale` line books its commencement. Release (`rentalAgreementLineId`, `returnedAt`): ends a `Pending` unit that never left the yard through `returnRentalUnit` with no location, so its billing stops at the release date (an Advance period gets the early-return adjustment), the line goes Returned and `fixedAsset.locationId` is unchanged; refused for a date after company today ("The release date cannot be in the future"), a line that is not Pending, a `Sale` line ("UNIT is treated as a sale; return it on a rental receipt instead" — plan decision P1; the UI hides Release unit for it) and a unit on an open (Draft / Pending) rental shipment or receipt ("UNIT is on shipment SHP…; remove it there before releasing the unit"). Close: refused FIRST while a Draft or Pending rental shipment or receipt of the agreement still has a line (`openRentalDocumentBlocker`: "Shipment SHP… is still open; post or delete it before closing the agreement"), then needs every line Returned/Sold, no Pending period, no unbilled charge. Cancel: Draft, or Active with no commenced `Sale` line and nothing On Rent/Sold/invoiced/recognized — DELETES the Pending lines (frees the units) and their Pending periods. `fixed-asset+/$fixedAssetId.out-of-service.tsx` likewise reads `getOnRentLineForAsset` with the service role (an accountant may lack `sales_view`).
+- **Deliver and return** — a unit leaves on a rental shipment and comes back on a rental receipt: ordinary `shipment` / `receipt` documents with `sourceDocument` `'Rental Agreement'` (`sourceDocumentId` = the agreement), one unit per `shipmentFixedAssetLine` / `receiptFixedAssetLine` row through `rentalAgreementLineId` (see inventory AGENTS). The `create` server function builds them with types `shipmentFromRentalAgreement` / `receiptFromRentalAgreement` (`{ rentalAgreementId, rentalAgreementLineId? }`, Active agreement only, location = the agreement's, `postingDate` left null because a set `postingDate` reads as posted). Without a line id, a shipment holds every `Pending` unit not on another open rental shipment, ticked; a receipt holds every `On Rent` unit ticked and every `Pending` unit unticked (spec Q8: ticking a Pending unit returns it, and its billing stops at the return date). With a line id, the unit is added ticked to the agreement's Draft (or ticked when it sits there unticked), else a one-unit Draft is created. Refusals: "No units to deliver" / "No units to return", "The unit is already on an open shipment" / "… receipt". Partial unique indexes `shipment_oneOpenDraftPerRentalAgreement_idx` / `receipt_oneOpenDraftPerRentalAgreement_idx` allow one Draft of each per agreement. `post-shipment` and `post-receipt` own the `'Rental Agreement'` source (`post-shipment/rental-agreement.ts`, `post-receipt/rental-agreement.ts`) and take an optional `postingDate` (`YYYY-MM-DD`; the post modal's **Delivered on** / **Returned on**, default company today; a future date is refused; other sources ignore it). Posting a shipment locks the agreement and the ticked lines, refuses a line that is not Pending or a unit out of service (the message names the unit), sets `On Rent` + `deliveredAt` + `meterOut` and writes a `Rental Delivery` `trackedActivity`; no `itemLedger`, `costLedger` or journal, for a `Rental` and a `Sale` line alike. Its void is allowed while every unit is still On Rent and no `Accrual` row of its lines is Posted or claimed by a Draft run: the lines go back to Pending with `deliveredAt` / `meterOut` cleared, and their unclaimed Planned `Accrual` rows are deleted. Posting a receipt runs `returnRentalUnit` for each ticked line (Pending or On Rent), sets the unit's `fixedAsset.locationId` to the receipt's location (for a `Sale` line returned to Fleet, the new asset) and writes a `Rental Return` activity for a `Rental` line. A rental receipt is never voided ("A rental return cannot be voided. Correct the unit by hand."). Posting either needs `update: inventory`.
+- **Per-unit shortcuts** — `$id.$lineId.deliver.tsx` / `$id.$lineId.return.tsx` (`update: sales` + `create: inventory`) invoke `create` with the line id and redirect into the shipment or receipt, so a counter pickup is the shortcut, then **Post**. `shipment+/new` / `receipt+/new` take the `'Rental Agreement'` source from the header buttons and redirect to the agreement's Draft when one exists. The inventory `$id.details` actions refuse a change of source on a rental document.
+- **The return body** — `returnRentalUnit` (`post-rental-agreement/return-unit.ts`; the helpers it shares with activation are in `agreement.ts`), called by `post-receipt` and by `release`. The caller locks the agreement and checks it is Active. It refuses a `returnedAt` after company today (`futureReturnError`: "The return date cannot be in the future"), re-cuts a `Rental` line's periods (a `Sale` line's billing is its term and is left alone), sets `fixedAsset.outOfServiceSince/Reason` when `takeOutOfService` is set, and runs `returnResidual` for a `Sale` line, which needs `residualDestination` and is refused before `endDate` (below). Its optional `locationId` is where a `Sale` line's residual lands: a rental receipt passes its own location (spec Q7), so the stock adjustment, or the new fleet asset and its `Capitalization` transfer, are at the receipt's location; the `'Lease'` journal's Location dimension keeps the agreement's location (plan decision P4). Without it (release), the agreement's location.
- **Invoice generation and automation** — the `create-rental-invoices` server function (`packages/server-functions/src/create-rental-invoices/`; `{ asOf, rentalAgreementId? }`, permissions `update: sales` + `create: invoicing`; an agreement that throws is returned in `failures`, never stops the others): per Active agreement, first rolls every live `Rental` (or unclassified) line's periods to `billingHorizon(asOf)` — a `Sale` line never rolls a holdover period, its whole term was cut at activation — then drafts Draft `salesInvoice`s with a `Rental` line per due non-adjustment period (`dueOn <= asOf`) and per charge dated `<= asOf`, stamping `salesInvoiceLineId`. Due early-return adjustments (`isAdjustment`) never go on an invoice — a negative line could net it below zero, which no payment can apply and no refund can pay out: they go on ONE Draft credit memo per agreement (`insertRentalCreditMemo`: `memo.rentalAgreementId`, `creditMemo` sequence, amount = Σ credits at currency decimals, `reference` = the readable agreement id, notes = the "Early return credit — N days used" descriptions), stamped `memoId` + `Invoiced`, returned in `creditMemos`; it stays Draft in every automation mode and a person posts it (`post-memo`, below). The Invoice action redirects to the memo when nothing else was drafted. The agreement's effective invoice automation (`rentalAgreement.invoiceAutomation ?? companySettings.invoiceAutomation`, view column `rentalAgreements.effectiveInvoiceAutomation`; `Draft Only` / `Post` / `Post and Email` / `Post and Send via Stripe`) decides the split: `Draft Only` drafts ONE combined invoice and automates nothing; otherwise rent and charges become separate invoices (`planRentalInvoices`, `@carbon/utils`) and holds are stamped on `salesInvoice.automationHoldReason` — charges and purchase options always, a rent invoice with an early-return credit, and a re-bill of a voided invoice (wins over the credit). Called by the Inngest `recurring-billing` job (cron `0 5 * * *`, `userId "system"`), which then posts, files the invoice PDF on (`attachPostedInvoicePdf`, every posting mode), and emails or sends via Stripe, every unheld non-Draft-Only draft it created — read back from the database (`findInvoicesToAutomate`), so drafts from a failed or retried attempt are automated too (`packages/jobs/src/invoicing/automate-invoice.ts`) and sends each agreement owner (`salesPersonId ?? createdBy`) a "Recurring invoicing" digest; and by "Invoice" (`$id.invoice.tsx` → `generateRentalInvoicesNow`, needs `update: sales` AND `create: invoicing`) and Sell to Customer, which fire `carbon/invoice.automate` for the same invoices. The per-agreement override is `updateRentalAgreementInvoiceAutomation` (intent `invoiceAutomation` on `rental-agreement+/update.tsx`; Draft/Active only; `Post and Email` refused without a contact email, `RENTAL_INVOICE_EMAIL_NO_CONTACT`). Spec: `.ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md` Part II.
- **Rental credit memos** — `post-memo` books a memo with `rentalAgreementId` through `loadRentalCredit` + the pure `planRentalCredit` (`packages/server-functions/src/post-memo/rental-credit.ts`, tested): the memo is apportioned over its adjustment periods (`distributeRoundingResidual`; a mismatch with an edited amount is refused), each period planned by the invoice path's own `planRentalLine` / `rentalScheduleRows`, so the legs replacing the memo's reason leg are Dr Deferred Revenue up to the period's Planned Deferral rows and Dr Rental Income for the rest (Cr AR), and the negative Deferral rows carry `revenueRecognitionSchedule.memoId`. Once posted it is applied to invoices from a payment (credits) or refunded like any credit memo. Void (`post-memo` `index.ts`) is refused once a run holds or has posted one of its rows; otherwise it reverses the journal, deletes its Planned rows and returns its periods to Pending. A Draft one is deleted by `deleteRentalCreditMemoReleasingPeriods` (`sales.server.ts`, called by `credits+/$memoId.delete.tsx`), which returns the periods to Pending. The Billing Periods card links an adjustment to its memo; the memo's Documents panel links the agreement (`getSettlementRelatedItems` `rentalAgreementId`).
- **Invoice deletion** — `deleteSalesInvoiceReleasingRentals` / `deleteSalesInvoiceLineReleasingRentals` (`sales.server.ts`) delete and `releaseRecurringInvoiceStamps` in ONE Kysely transaction (the stamps have no FK). It releases rental periods and charges AND contract schedule rows (`customerContractInvoiceLine.salesInvoiceLineId`; a planned invoice returns to `Planned` once none of its rows is stamped). The line variant takes the route's `invoiceId` and, under `FOR UPDATE`, refuses a line of another invoice or of a non-Draft invoice (releasing a posted line's stamps would bill its period again). The MCP tools `invoicing_deleteSalesInvoice` / `invoicing_deleteSalesInvoiceLine` still call the plain service functions and leave stamps behind (open follow-up).
- **The `Rental` invoice line** — `salesInvoiceLineType` value `Rental`, no item; columns `rentalAgreementId`, `rentalAgreementLineId`, `rentalBillingPeriodId`, `rentalAgreementChargeId`, `rentalLineType` (enum `rentalInvoiceLineType`: Rent / Charge / Purchase Option), CHECK `salesInvoiceLine_rental_check`. Rendered read-only by `SalesInvoiceLineForm`; `salesInvoiceLineValidator` accepts but never offers it. Posting (`post-sales-invoice`, decisions in `rental-posting.ts`): Rent → Cr Contract Assets for unbilled accruals, rest Cr Deferred Revenue + Deferral schedule rows; negative Rent (an early-return credit on an invoice drafted before credits became memos; new ones are credit memos, above) → Dr Deferred Revenue (negative Deferral rows) / Dr Rental Income for the recognized part; Charge → Cr Rental Income; on a `Sale` line Rent and Purchase Option → Cr Net Investment in Leases (no schedule rows, no accrual consumption; a negative Rent line is refused) and Charge → Cr Rental Income; Purchase Option on a `Rental` line → refused ("Purchase option billing requires a line treated as a sale"). A `Sale` line's Purchase Option line also posts the NI settlement (below). Posting a Purchase Option line flips its agreement line to `Sold` (only a `Sale` line `On Rent`, in the posting transaction, regardless of accounting); VOID returns a still-`Sold` line to `On Rent`. Revenue legs carry `documentType 'Rental Agreement'`.
- **Deposits** — `payment.rentalAgreementId` / `payment.salesOrderId` (at most one). The Deposits card lists `getRentalAgreementDeposits`; "Record Deposit" links to `payments/new?customerId&rentalAgreementId&amount`. Posting is in `post-payment` (see accounting AGENTS, Payments).
- **Lease classification** — pure math in `packages/utils/src/lessor-lease.ts` (`@carbon/utils`): `presentValue` (`pvRent`, `pvPayments` incl. a reasonably certain option + guaranteed residual, `pvResidual`, `netInvestment`), `classifyLessorLease` (tests a–e; any true ⇒ `Sale`; `termMonths` null ⇒ always `Rental`), `buildLessorSchedule` (last line closes on option + residuals), `wholeMonthsInTerm`, `leasePaymentTerms` (Calendar Month: the month rate over whole months — a Daily or Weekly unit at its average month over a 365-day year; 28 Days: the unit's 28-day charge over whole 28-day periods at annual × 28/365), `salesTypeRequirementError` (also refuses a Daily / Weekly unit treated as a sale on a Calendar Month agreement: its invoices would not match a level payment, and — given `today` — an agreement starting before the activation month: commencement posts on the activation day while interest is dated from the start), `netInvestmentExceedsFairValue` (a WARNING, shown on the unit's Accounting treatment panel and in `RentalCommencementPreview`: payments + residual discounted at the entered rate are worth more than the fair value, i.e. the rate is below the rate implicit in the lease), `classifyRentalLine` (the stored `ClassificationInputs` record). Thresholds from `companySettings.leaseMajorPartThresholdPercent` / `leaseSubstantiallyAllThresholdPercent`. The Draft preview (`sales.utils.ts`: `leaseTermMonths`, `draftLeasePaymentTerms`, `previewLeaseClassification`, `readLeaseClassification`, `leaseCommencementPreview`) calls the same functions; UI `ui/Rentals/RentalLeaseClassification.tsx` (`LeaseClassificationPanel` on the line form, headed "Accounting treatment" with Rental / Sale cards and the ASC 842 names as secondary text (Financing has no input and is not shown), `LeaseClassificationOverrideModal`, `RentalCommencementPreview` in the Activate confirmation — the `$id.tsx` loader reads the units' cost and accumulated depreciation with the user's client, so `fixedAsset` RLS hides them from a user without accounting view and the preview shows only the NI / revenue legs). Override route `$id.$lineId.classification.tsx`: `update: accounting`, Draft only, reason required, reads and writes with the service role (an accountant may lack sales RLS), best-effort audit entry (`entityType "rentalAgreement"`, `tableName "rentalAgreementLine"`, reason as a `classificationOverrideReason` diff entry).
-- **Sales-type commencement / end of term** — `post-rental-agreement` (`lessor.ts` holds the pure decisions, pinned by `lessor.test.ts`). Activation, per `Sale` line (`salesTypeRequirementError`, `lessor-lease` in `@carbon/utils`: needs `endDate`, `fairValue` > 0, and WHOLE billing periods — Calendar Month starts on the 1st and ends on a month end, 28 Days is a multiple of 28 days — so the rent billed equals payment × periods the NI was valued on; messages read "UNIT is treated as a sale, which …"; `RentalCommencementPreview` shows the same message in the Activate confirmation): asset `Disposed` by `Sale` + `fixedAssetDisposal` (`saleProceeds` NI, `netBookValueAtDisposal` C, `gainLoss` selling profit); with accounting on a `'Lease'` journal (Dr NI, Dr COGS C − PVres, Dr class accumulated depreciation / Cr Lease Revenue PVpay, Cr class asset at cost); tracked entity `Consumed` with `Rental Agreement` + `Customer` attributes and a `Lease Commencement` activity; `rentalLeaseScheduleLine` rows and, with accounting on, Planned `Interest` recognition rows (Dr NI / Cr lease interest income). Fleet units only (activation already refuses an asset-less line). Return of a `Sale` line (`residualDestination` Fleet / Inventory, not before `endDate`, not in the future, not while a Draft run holds its Interest rows dated after the return): closing NI = `netInvestmentAt` — the `closingNetInvestment` of the last schedule line dated on or before `returnedAt` (the closing target at/after `endDate`; `initialNetInvestment` when there are no lines); Fleet → new `fixedAsset` in the class named "Rental Fleet" (else the class the unit left) at that cost + a Posted `Capitalization` `fixedAssetTransfer`; Inventory → `bookAdjustment` +1 at that unit cost; `'Lease'` journal Dr asset / inventory, Cr NI; only unposted Interest rows and schedule lines dated AFTER the return are deleted — those on or before it stay and post through recognition runs, bringing NI to zero. **Sell to Customer** (`$id.$lineId.sell.tsx`, `create: [sales, invoicing]` + `update: sales`): an Active agreement's `Sale` line `On Rent` with `purchaseOptionAmount`, once per line, not before `endDate` (early exercise is an early termination — a manual journal) — inserts a `Purchase Option` charge dated company today through the server-only `insertRentalPurchaseOptionCharge` (`sales.server.ts`) and calls `generateRentalInvoicesNow`; the invoice's posting marks the line Sold and settles the line's remaining NI against the schedule's closing balance (`purchaseOptionSettlement` in `post-sales-invoice/rental-posting.ts`: shortfall Dr `costOfGoodsSoldAccount` / Cr NI, excess Dr NI / Cr `leaseRevenueAccount`, same journal line reference so VOID reverses it; each default required only when its leg is). The return form (`RentalAgreementReturnForm`) shows the Return To radios for a `Sale` line; the route re-reads the classification.
-- **Fleet** — `fleetAssets` derives Reserved (live Pending line) and On Rent (a commenced `Sale` unit reads Sold: its asset is Disposed); the fleet table's **Rent** row action (Available units) opens `newRentalAgreement?fixedAssetId=`. `post-asset-transfer` `return` refuses a unit on a live line.
+- **Sales-type commencement / end of term** — `post-rental-agreement` (`lessor.ts` holds the pure decisions, pinned by `lessor.test.ts`). Activation, per `Sale` line (`salesTypeRequirementError`, `lessor-lease` in `@carbon/utils`: needs `endDate`, `fairValue` > 0, and WHOLE billing periods — Calendar Month starts on the 1st and ends on a month end, 28 Days is a multiple of 28 days — so the rent billed equals payment × periods the NI was valued on; messages read "UNIT is treated as a sale, which …"; `RentalCommencementPreview` shows the same message in the Activate confirmation): asset `Disposed` by `Sale` + `fixedAssetDisposal` (`saleProceeds` NI, `netBookValueAtDisposal` C, `gainLoss` selling profit); with accounting on a `'Lease'` journal (Dr NI, Dr COGS C − PVres, Dr class accumulated depreciation / Cr Lease Revenue PVpay, Cr class asset at cost); tracked entity `Consumed` with `Rental Agreement` + `Customer` attributes and a `Lease Commencement` activity; `rentalLeaseScheduleLine` rows and, with accounting on, Planned `Interest` recognition rows (Dr NI / Cr lease interest income). Fleet units only (activation already refuses an asset-less line). Return of a `Sale` line (on a rental receipt; `residualDestination` Fleet / Inventory, not before `endDate`, not in the future, not while a Draft run holds its Interest rows dated after the return): closing NI = `netInvestmentAt` — the `closingNetInvestment` of the last schedule line dated on or before `returnedAt` (the closing target at/after `endDate`; `initialNetInvestment` when there are no lines); Fleet → new `fixedAsset` in the class named "Rental Fleet" (else the class the unit left) at that cost + a Posted `Capitalization` `fixedAssetTransfer`; Inventory → `bookAdjustment` +1 at that unit cost; `'Lease'` journal Dr asset / inventory, Cr NI; only unposted Interest rows and schedule lines dated AFTER the return are deleted — those on or before it stay and post through recognition runs, bringing NI to zero. **Sell to Customer** (`$id.$lineId.sell.tsx`, `create: [sales, invoicing]` + `update: sales`): an Active agreement's `Sale` line `On Rent` with `purchaseOptionAmount`, once per line, not before `endDate` (early exercise is an early termination — a manual journal) — inserts a `Purchase Option` charge dated company today through the server-only `insertRentalPurchaseOptionCharge` (`sales.server.ts`) and calls `generateRentalInvoicesNow`; the invoice's posting marks the line Sold and settles the line's remaining NI against the schedule's closing balance (`purchaseOptionSettlement` in `post-sales-invoice/rental-posting.ts`: shortfall Dr `costOfGoodsSoldAccount` / Cr NI, excess Dr NI / Cr `leaseRevenueAccount`, same journal line reference so VOID reverses it; each default required only when its leg is). On a rental receipt, `ReceiptRentalLineItem` shows the **Return To** radios for a `Sale` line (saved to `receiptFixedAssetLine.residualDestination`), `ReceiptPostModal` blocks a ticked `Sale` line without one, and the post re-reads the classification.
+- **Fleet** — `fleetAssets` derives Reserved (live Pending line) and On Rent (a commenced `Sale` unit reads Sold: its asset is Disposed); the fleet table's **Rent** row action (Available units) opens `newRentalAgreement?fixedAssetId=`. `post-asset-transfer` `return` refuses a unit on a live line. A posted rental receipt moves the unit's `fixedAsset.locationId` to the receipt's location; a release does not move it.
-Service functions (`sales.service.ts`): `getRentalAgreements` / `getRentalAgreement` / `insertRentalAgreement` / `updateRentalAgreement` / `deleteRentalAgreement`, `getRentalAgreementLines` / `getRentalAgreementLine` / `upsertRentalAgreementLine` / `insertRentalAgreementLines` (the wizard's Add Units; not an MCP tool) / `deleteRentalAgreementLine`, `getRentalAgreementCharges` / `upsertRentalAgreementCharge` / `deleteRentalAgreementCharge`, (these are MCP tools, so they carry their own guards: `updateRentalAgreement` and line upsert/delete only while the agreement is Draft, a line never moves agreements and its fleet unit is read under the line's company; a charge insert only on a Draft/Active agreement's line and always as charge type `Charge` — `rentalAgreementChargeValidator` has no `chargeType`; a charge update only while unbilled; refusals are PostgrestError-shaped `RENTAL_*` codes; every writer picks its fields explicitly rather than spreading the payload, so `status`, lifecycle timestamps, the rate snapshot, the classification columns, a charge's `chargeType` and its billing stamp cannot be set through them), `getRentalBillingPeriods`, `getRentableFleetAssets` (`fleetStatus = 'Available'`), `getItemRentalRate` (takes the currency) / `upsertItemRentalRate` / `deleteItemRentalRate`, `getDefaultRentalRates` (batch over `itemIds`, one query per table, keyed by item → per frequency `{ rate, source }` with `source` Customer / Customer Type / Item; used by the line upsert for an omitted rate, the line form on unit change, and the `$id.$lineId.details` loader while Draft for the "where did this rate come from" hint and frequency changes), `getCustomerItemRentalRates` / `getCustomerItemRentalRate` / `upsertCustomerItemRentalRate` / `deleteCustomerItemRentalRate`, `getRentalAgreementDeposits`. Validators: `rentalAgreementValidator`, `rentalAgreementLineValidator`, `rentalAgreementLinesAddValidator`, `rentalAgreementChargeValidator`, `rentalAgreementReturnValidator` (`isSalesType` + `residualDestination`), `rentalAgreementLineClassificationValidator`, `itemRentalRateValidator`, `customerItemRentalRateValidator`, const arrays `lessorClassificationOverrides`, `rentalResidualDestinations`, `rentalAgreementStatuses`, `rentalAgreementLineStatuses`, `rentalBillingCycles`, `rentalBillingTimings`, `rentalRateUnits`, `rentalInvoiceLineTypes`.
+Service functions (`sales.service.ts`): `getRentalAgreements` / `getRentalAgreement` / `insertRentalAgreement` / `updateRentalAgreement` / `deleteRentalAgreement`, `getRentalAgreementLines` / `getRentalAgreementLine` / `upsertRentalAgreementLine` / `insertRentalAgreementLines` (the wizard's Add Units; not an MCP tool) / `deleteRentalAgreementLine`, `getRentalAgreementCharges` / `upsertRentalAgreementCharge` / `deleteRentalAgreementCharge`, (these are MCP tools, so they carry their own guards: `updateRentalAgreement` and line upsert/delete only while the agreement is Draft, a line never moves agreements and its fleet unit is read under the line's company; a charge insert only on a Draft/Active agreement's line and always as charge type `Charge` — `rentalAgreementChargeValidator` has no `chargeType`; a charge update only while unbilled; refusals are PostgrestError-shaped `RENTAL_*` codes; every writer picks its fields explicitly rather than spreading the payload, so `status`, lifecycle timestamps, the rate snapshot, the classification columns, a charge's `chargeType` and its billing stamp cannot be set through them), `getRentalBillingPeriods`, `getRentableFleetAssets` (`fleetStatus = 'Available'`), `getItemRentalRate` (takes the currency) / `upsertItemRentalRate` / `deleteItemRentalRate`, `getDefaultRentalRates` (batch over `itemIds`, one query per table, keyed by item → per frequency `{ rate, source }` with `source` Customer / Customer Type / Item; used by the line upsert for an omitted rate, the line form on unit change, and the `$id.$lineId.details` loader while Draft for the "where did this rate come from" hint and frequency changes), `getCustomerItemRentalRates` / `getCustomerItemRentalRate` / `upsertCustomerItemRentalRate` / `deleteCustomerItemRentalRate`, `getRentalAgreementDeposits`, `getRentalAgreementRelatedDocuments` (the agreement's rental shipments and receipts with their asset lines, for the header dropdowns and `rentalLineDocuments`). Validators: `rentalAgreementValidator`, `rentalAgreementLineValidator`, `rentalAgreementLinesAddValidator`, `rentalAgreementChargeValidator`, `rentalAgreementReleaseValidator` (`rentalAgreementLineId` + `returnedAt`), `rentalAgreementLineClassificationValidator`, `itemRentalRateValidator`, `customerItemRentalRateValidator`, const arrays `lessorClassificationOverrides`, `rentalResidualDestinations`, `rentalAgreementStatuses`, `rentalAgreementLineStatuses`, `rentalBillingCycles`, `rentalBillingTimings`, `rentalRateUnits`, `rentalInvoiceLineTypes`.
- **Setup wizard** — creating an agreement is five routed steps, built on the same `~/components/Setup` pieces as the contract wizard (`rentalAgreementSetupSteps` in `RentalSetupSteps.tsx`: details → units → billing → accounting → review; `path.to.rentalAgreementSetup(id, step)`). `new.tsx` is step 1 (`RentalAgreementDetailsForm`: customer, rental site, contact, shipping location, Open-ended / Fixed Term choice cards with the end date, sales person defaulted to the current user, currency, notes; the terms later steps own are carried as hidden fields) and redirects to `setup/units` — also when the fleet register's Rent action pre-adds a unit. `$id.setup.tsx` (layout, `update: sales`) redirects a non-Draft to `$id.details` and renders `SetupFrame` + `SetupFooter` (unit count and, when every unit is Monthly, the monthly rent; Back / Next, Next disabled on Units until there is a unit; on Review "Save as Draft" (→ list) and "Activate", which opens the same `Confirm` + `RentalCommencementPreview` as the header). `$id.setup._index` redirects to units; `setup.details` re-saves step 1 through `updateRentalAgreement` (a currency change re-reads the exchange rate). Steps: Units = `RentalUnitsGrid` (Rate Frequency and Rate cells → `$lineId.update`, which merges one field into the line and runs `rentalAgreementLineValidator` + `upsertRentalAgreementLine`, a new frequency restarting the rate from `getDefaultRentalRates`, else 0; "Add Units" → `lines.add` → `insertRentalAgreementLines`, several Available fleet units at their rate on file for one frequency, 0 when none — not an MCP tool; Remove Unit → `$lineId.delete`, which now returns to the referrer unless it was the removed unit's page); Billing = `RentalAgreementBilling` (billing cycle and timing as choice cards, payment terms, deposit, tax percent, invoicing mode — each saved alone through `update.tsx` via `useRentalTermSave`); Accounting = `RentalAgreementAccounting` (`LeaseClassificationPreview` from the saved terms; with an end date the discount rate, purchase option and the three switches, plus a unit-inputs grid — fair value, economic life, residuals — through `$lineId.update`); Review = `RentalAgreementSummary`, the blockers linked to their step (no units; a unit at rate 0 — `post-rental-agreement` activate refuses it, `unpricedUnitError` in `validators.ts`, and the wizard footer and header disable Activate) and `RentalCommencementPreview`. The Add Units modal and the no-units state carry an info alert: a serial number missing from the list must first be capitalized (part Inventory tab → Storage Units → Capitalize as Fixed Asset). Opening a Draft lands in the wizard: `$id._index` and the `$id.details` loader redirect anyone with `update: sales` (`draftRentalAgreementSetupPath`, `sales.server.ts`), so the list and every action that falls back to the agreement page continue setup; a viewer without it gets the page, whose header has "Continue Setup". A successful Activate from the wizard redirects to `$id.details` rather than back into it.
### Rentals safety
-- Never write `rentalBillingPeriod` / line status transitions from app code except Deliver — activate / return / close / cancel go through `post-rental-agreement`.
+- Never write `rentalBillingPeriod` / line status transitions from app code; no app code writes a line status. Activate / release / close / cancel go through `post-rental-agreement`, delivery and return through `post-shipment` / `post-receipt` (source `'Rental Agreement'`).
- Never delete a sales invoice (or line) that may carry Rental lines with a plain delete — use the `*ReleasingRentals` server functions.
- Terms and units are editable only while Draft; the line details route refuses a unit change after activation.
-- Delivery puts the unit on rent (it starts accruals); billing periods run from the agreement's start date and cycle, whatever the delivery date.
+- Delivery (a posted rental shipment) puts the unit on rent (it starts accruals); billing periods run from the agreement's start date and cycle, whatever the delivery date.
- A `Sale` line (sales-type lease) is derecognized at ACTIVATION, not delivery. Never unwind it from app code: early termination is a manual journal (return before `endDate` and cancel both refuse "Ending a rental treated as a sale early is a manual journal").
- A stored classification is final once Active; thresholds changed in settings apply only to later activations.
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index 8625b49749..2ad36c627f 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -1525,45 +1525,12 @@ export const rentalAgreementChargeValidator = z.object({
* (spec §4): a new asset in the Rental Fleet class, or finished goods. */
export const rentalResidualDestinations = ["Fleet", "Inventory"] as const;
-export const rentalAgreementReturnValidator = z
- .object({
- rentalAgreementLineId: z
- .string()
- .min(1, { message: "Rental agreement line is required" }),
- returnedAt: z.string().min(1, { message: "Return date is required" }),
- meterIn: zfd.numeric(z.number().min(0).optional()),
- returnNotes: zfd.text(z.string().optional()),
- takeOutOfService: zfd.checkbox(),
- outOfServiceReason: zfd.text(z.string().optional()),
- /** Posted by the form for a Sale line so the destination can be
- * required client-side; the route re-reads the line's classification. */
- isSalesType: zfd.checkbox({ trueValue: "true" }),
- residualDestination: zfd.text(z.enum(rentalResidualDestinations).optional())
- })
- .refine(
- (data) => (data.takeOutOfService ? !!data.outOfServiceReason : true),
- {
- message: "A reason is required to take the unit out of service",
- path: ["outOfServiceReason"]
- }
- )
- .refine((data) => (data.isSalesType ? !!data.residualDestination : true), {
- message: "Choose where the returned unit goes",
- path: ["residualDestination"]
- })
- .refine(
- (data) =>
- !(
- data.isSalesType &&
- data.residualDestination === "Inventory" &&
- data.takeOutOfService
- ),
- {
- message:
- "A unit returned to inventory cannot be taken out of service; return it to the fleet instead",
- path: ["takeOutOfService"]
- }
- );
+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" })
+});
export const lessorClassificationOverrides = ["Rental", "Sale"] as const;
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index e8df6a04e5..43b443a343 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -9594,6 +9594,38 @@ export async function getRentalAgreementDeposits(
.order("paymentDate", { ascending: true });
}
+/** @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
+ };
+}
+
// ----------------------------------------------------------------------
// Customer contracts (`.ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md` Part III). Confirm, schedule
// edits, amend, cancel and revert go through the `post-customer-contract`
diff --git a/apps/erp/app/modules/sales/sales.utils.test.ts b/apps/erp/app/modules/sales/sales.utils.test.ts
index 4edcb711e9..f3b8e27c40 100644
--- a/apps/erp/app/modules/sales/sales.utils.test.ts
+++ b/apps/erp/app/modules/sales/sales.utils.test.ts
@@ -14,6 +14,8 @@ import {
previewLeaseClassification,
readLeaseClassification,
reconcileQuantityBreaks,
+ rentalEquipmentStatus,
+ rentalLineDocuments,
repricedUnitPrice,
resolveJobConfiguration,
resolvePreservedQuoteLinePriceFields,
@@ -679,3 +681,86 @@ describe("repricedUnitPrice", () => {
expect(repricedUnitPrice(current(104.5678), 110, 4)).toBe(104.5678);
});
});
+
+describe("rentalEquipmentStatus", () => {
+ const lines = (
+ ...statuses: ("Pending" | "On Rent" | "Returned" | "Sold")[]
+ ) => statuses.map((status) => ({ status }));
+
+ it("has no status without units", () => {
+ expect(rentalEquipmentStatus([])).toBeNull();
+ });
+
+ it("is To Deliver while every unit is in the yard", () => {
+ expect(rentalEquipmentStatus(lines("Pending", "Pending"))).toBe(
+ "To Deliver"
+ );
+ });
+
+ it("is Partially Delivered while any unit is still to deliver", () => {
+ expect(rentalEquipmentStatus(lines("Pending", "On Rent"))).toBe(
+ "Partially Delivered"
+ );
+ expect(rentalEquipmentStatus(lines("Pending", "Returned"))).toBe(
+ "Partially Delivered"
+ );
+ });
+
+ it("is On Rent when every unit is out", () => {
+ expect(rentalEquipmentStatus(lines("On Rent", "On Rent"))).toBe("On Rent");
+ });
+
+ it("is Partially Returned when some units are back", () => {
+ expect(rentalEquipmentStatus(lines("On Rent", "Returned"))).toBe(
+ "Partially Returned"
+ );
+ expect(rentalEquipmentStatus(lines("On Rent", "Sold"))).toBe(
+ "Partially Returned"
+ );
+ });
+
+ it("is Returned when every unit is back or sold", () => {
+ expect(rentalEquipmentStatus(lines("Returned", "Sold"))).toBe("Returned");
+ });
+});
+
+describe("rentalLineDocuments", () => {
+ const shipment = (
+ status: string,
+ lines: { rentalAgreementLineId: string | null; shipped: boolean }[]
+ ) => ({
+ id: `shp-${status}`,
+ shipmentId: `SHP-${status}`,
+ status,
+ shipmentFixedAssetLine: lines
+ });
+
+ it("finds nothing when the agreement has no documents", () => {
+ expect(rentalLineDocuments("ral1", [], [])).toEqual({
+ shipment: null,
+ receipt: null
+ });
+ });
+
+ it("finds the Posted shipment that delivered the unit", () => {
+ const result = rentalLineDocuments(
+ "ral1",
+ [shipment("Posted", [{ rentalAgreementLineId: "ral1", shipped: true }])],
+ []
+ );
+ expect(result.shipment).toEqual({
+ id: "shp-Posted",
+ shipmentId: "SHP-Posted"
+ });
+ expect(result.receipt).toBeNull();
+ });
+
+ it("ignores a Draft shipment", () => {
+ const result = rentalLineDocuments(
+ "ral1",
+ [shipment("Draft", [{ rentalAgreementLineId: "ral1", shipped: true }])],
+ []
+ );
+ expect(result.shipment).toBeNull();
+ });
+});
diff --git a/apps/erp/app/modules/sales/sales.utils.ts b/apps/erp/app/modules/sales/sales.utils.ts
index 8c83b80f48..194830acd2 100644
--- a/apps/erp/app/modules/sales/sales.utils.ts
+++ b/apps/erp/app/modules/sales/sales.utils.ts
@@ -2,7 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import type { Json } from "@carbon/database";
+import type { Database, Json } from "@carbon/database";
import type { LeasePaymentTerms, RateUnit, Timing } from "@carbon/utils";
import {
classifyLessorLease,
@@ -416,6 +416,84 @@ export function leaseCommencementPreview(
};
}
+export type RentalEquipmentStatus =
+ | "To Deliver"
+ | "Partially Delivered"
+ | "On Rent"
+ | "Partially Returned"
+ | "Returned";
+
+/** Where an agreement's units are, from their line statuses: the header badge
+ * next to the agreement's own status. Sold counts as back — the unit no
+ * longer rents. Null with no units. */
+export function rentalEquipmentStatus(
+ lines: {
+ status: Database["public"]["Enums"]["rentalAgreementLineStatus"];
+ }[]
+): RentalEquipmentStatus | null {
+ if (lines.length === 0) return null;
+ const pending = lines.filter((line) => line.status === "Pending").length;
+ const onRent = lines.filter((line) => line.status === "On Rent").length;
+ const back = lines.length - pending - onRent;
+
+ if (pending === lines.length) return "To Deliver";
+ // A unit still in the yard while others have left.
+ if (pending > 0) return "Partially Delivered";
+ if (onRent === lines.length) return "On Rent";
+ if (onRent > 0) return "Partially Returned";
+ return back > 0 ? "Returned" : null;
+}
+
+/** 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;
+} {
+ let shipment: { id: string; shipmentId: string } | null = null;
+ for (const s of shipments) {
+ if (s.status !== "Posted") continue;
+ if (
+ s.shipmentFixedAssetLine.some(
+ (l) => l.rentalAgreementLineId === lineId && l.shipped
+ )
+ ) {
+ shipment = { id: s.id, shipmentId: s.shipmentId };
+ }
+ }
+ let receipt: { id: string; receiptId: string } | null = null;
+ for (const r of receipts) {
+ if (r.status !== "Posted") continue;
+ if (
+ r.receiptFixedAssetLine.some(
+ (l) => l.rentalAgreementLineId === lineId && l.received
+ )
+ ) {
+ receipt = { id: r.id, receiptId: r.receiptId };
+ }
+ }
+ return { shipment, receipt };
+}
+
// The surcharge one configuration price adds for a line's configuration: the
// amount per unit of a numeric value (`value` null), else the amount when the
// chosen value equals `value` (a list option, or "true" for a boolean).
diff --git a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementExplorer.tsx b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementExplorer.tsx
index 3b89562c7f..4f83d6f73a 100644
--- a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementExplorer.tsx
+++ b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementExplorer.tsx
@@ -19,6 +19,7 @@ import { Trans, useLingui } from "@lingui/react/macro";
import {
LuBadgeDollarSign,
LuCirclePlus,
+ LuCircleSlash,
LuEllipsisVertical,
LuTrash,
LuTruck,
@@ -160,7 +161,11 @@ function ExplorerLine({
const to = path.to.rentalAgreementLine(agreementId, line.id);
const isSelected = location.pathname === to;
const hasActions =
- state.canDeliver || state.canReturn || state.canSell || state.canDelete;
+ state.canDeliver ||
+ state.canReturn ||
+ state.canRelease ||
+ state.canSell ||
+ state.canDelete;
return (
<HStack
@@ -218,6 +223,15 @@ function ExplorerLine({
<Trans>Return</Trans>
</DropdownMenuItem>
)}
+ {state.canRelease && (
+ <DropdownMenuItem
+ disabled={state.releaseDisabled}
+ onClick={() => onAction("release", line)}
+ >
+ <DropdownMenuIcon icon={<LuCircleSlash />} />
+ <Trans>Release unit</Trans>
+ </DropdownMenuItem>
+ )}
{state.canSell && (
<DropdownMenuItem
disabled={state.sellDisabled}
diff --git a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementHeader.tsx b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementHeader.tsx
index 8e39db1588..a47a50bbb7 100644
--- a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementHeader.tsx
+++ b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementHeader.tsx
@@ -10,6 +10,7 @@ import {
DropdownMenuContent,
DropdownMenuIcon,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
Heading,
HStack,
@@ -22,27 +23,40 @@ import {
import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import {
+ LuChevronDown,
LuCircleCheck,
+ LuCirclePlus,
LuCircleStop,
LuCreditCard,
LuEllipsisVertical,
LuListChecks,
+ LuPackageCheck,
LuPanelLeft,
LuPlay,
- LuTrash
+ LuTrash,
+ LuTruck
} from "react-icons/lu";
-import { Link } from "react-router";
+import { Link, useSubmit } from "react-router";
import { usePanels } from "~/components/Layout";
import { Confirm, ConfirmDelete } from "~/components/Modals";
import { useCompanyToday, usePermissions } from "~/hooks";
+import { ReceiptStatus } from "~/modules/inventory/ui/Receipts";
+import { ShipmentStatus } from "~/modules/inventory/ui/Shipments";
import { path } from "~/utils/path";
+import { rentalEquipmentStatus } from "../../sales.utils";
import { RentalCommencementPreview } from "./RentalLeaseClassification";
-import RentalStatus from "./RentalStatus";
+import RentalStatus, { RentalEquipmentStatusBadge } from "./RentalStatus";
import type { RentalAgreementRouteData } from "./types";
type RentalAgreementHeaderProps = Pick<
RentalAgreementRouteData,
- "rentalAgreement" | "lines" | "periods" | "leasePolicy" | "leaseInputs"
+ | "rentalAgreement"
+ | "lines"
+ | "periods"
+ | "leasePolicy"
+ | "leaseInputs"
+ | "shipments"
+ | "receipts"
>;
type PendingAction = "activate" | "invoice" | "close" | "cancel";
@@ -52,10 +66,13 @@ const RentalAgreementHeader = ({
lines,
periods,
leasePolicy,
- leaseInputs
+ leaseInputs,
+ shipments,
+ receipts
}: RentalAgreementHeaderProps) => {
const { t } = useLingui();
const permissions = usePermissions();
+ const submit = useSubmit();
const { toggleExplorer } = usePanels();
const today = useCompanyToday();
@@ -82,6 +99,11 @@ const RentalAgreementHeader = ({
(period) => period.status === "Invoiced"
);
const hasUnitOnRent = lines.some((line) => line.status === "On Rent");
+ // Delivering and returning draft inventory documents.
+ const canMoveUnits = canUpdate && permissions.can("create", "inventory");
+ const hasPendingUnit = lines.some((line) => line.status === "Pending");
+ // A receipt also holds Pending units (spec Q8).
+ const canReturn = hasUnitOnRent || hasPendingUnit;
const hasInvoicedPeriod = periods.some(
(period) => period.status === "Invoiced"
);
@@ -96,6 +118,21 @@ const RentalAgreementHeader = ({
rentalAgreement.endDate < today &&
hasUnitOnRent;
+ // POST the agreement to the create route, which drafts the document (or
+ // finds the open Draft) and redirects into it.
+ const deliver = () => {
+ const formData = new FormData();
+ formData.set("sourceDocument", "Rental Agreement");
+ formData.set("sourceDocumentId", id);
+ submit(formData, { method: "post", action: path.to.newShipment });
+ };
+ const returnUnits = () => {
+ const formData = new FormData();
+ formData.set("sourceDocument", "Rental Agreement");
+ formData.set("sourceDocumentId", id);
+ submit(formData, { method: "post", action: path.to.newReceipt });
+ };
+
const open = (next: PendingAction) => {
setAction(next);
confirm.onOpen();
@@ -181,6 +218,11 @@ const RentalAgreementHeader = ({
</DropdownMenuContent>
</DropdownMenu>
<RentalStatus status={status} />
+ {isActive && (
+ <RentalEquipmentStatusBadge
+ status={rentalEquipmentStatus(lines)}
+ />
+ )}
{isPastEndDate && (
<Badge variant="orange">
<Trans>Past end date</Trans>
@@ -188,6 +230,96 @@ const RentalAgreementHeader = ({
)}
</HStack>
<HStack>
+ {isActive &&
+ canMoveUnits &&
+ (shipments.length === 0 ? (
+ <Button
+ variant={hasPendingUnit ? "primary" : "secondary"}
+ leftIcon={<LuTruck />}
+ isDisabled={!hasPendingUnit}
+ onClick={deliver}
+ >
+ <Trans>Deliver</Trans>
+ </Button>
+ ) : (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ leftIcon={<LuTruck />}
+ variant={hasPendingUnit ? "primary" : "secondary"}
+ rightIcon={<LuChevronDown />}
+ >
+ <Trans>Shipments</Trans>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ disabled={!hasPendingUnit}
+ onClick={deliver}
+ >
+ <DropdownMenuIcon icon={<LuCirclePlus />} />
+ <Trans>New Shipment</Trans>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ {shipments.map((shipment) => (
+ <DropdownMenuItem key={shipment.id} asChild>
+ <Link to={path.to.shipment(shipment.id)}>
+ <DropdownMenuIcon icon={<LuTruck />} />
+ <HStack spacing={8}>
+ <span>{shipment.shipmentId}</span>
+ <ShipmentStatus status={shipment.status} />
+ </HStack>
+ </Link>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ))}
+ {isActive &&
+ canMoveUnits &&
+ (receipts.length === 0 ? (
+ <Button
+ variant="secondary"
+ leftIcon={<LuPackageCheck />}
+ isDisabled={!canReturn}
+ onClick={returnUnits}
+ >
+ <Trans>Return</Trans>
+ </Button>
+ ) : (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ leftIcon={<LuPackageCheck />}
+ variant="secondary"
+ rightIcon={<LuChevronDown />}
+ >
+ <Trans>Receipts</Trans>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ disabled={!canReturn}
+ onClick={returnUnits}
+ >
+ <DropdownMenuIcon icon={<LuCirclePlus />} />
+ <Trans>New Receipt</Trans>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ {receipts.map((receipt) => (
+ <DropdownMenuItem key={receipt.id} asChild>
+ <Link to={path.to.receipt(receipt.id)}>
+ <DropdownMenuIcon icon={<LuPackageCheck />} />
+ <HStack spacing={8}>
+ <span>{receipt.receiptId}</span>
+ <ReceiptStatus status={receipt.status} />
+ </HStack>
+ </Link>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ))}
{isActive && (
<Button
variant="secondary"
diff --git a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementLineSummary.tsx b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementLineSummary.tsx
index 74803d3966..57fb1ea95a 100644
--- a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementLineSummary.tsx
+++ b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementLineSummary.tsx
@@ -13,13 +13,25 @@ import {
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import type { ReactNode } from "react";
-import { LuBadgeDollarSign, LuTrash, LuTruck, LuUndo2 } from "react-icons/lu";
+import {
+ LuBadgeDollarSign,
+ LuCircleSlash,
+ LuTrash,
+ LuTruck,
+ LuUndo2
+} from "react-icons/lu";
import { Link } from "react-router";
import { DateTime } from "~/components";
+import { useRouteData } from "~/hooks";
import { path } from "~/utils/path";
+import { rentalLineDocuments } from "../../sales.utils";
import { LeaseClassificationBadge } from "./RentalLeaseClassification";
import RentalStatus from "./RentalStatus";
-import type { RentalAgreement, RentalAgreementLine } from "./types";
+import type {
+ RentalAgreement,
+ RentalAgreementLine,
+ RentalAgreementRouteData
+} from "./types";
import { rentalUnitLabel, useRentalLineActions } from "./useRentalLineActions";
type RentalAgreementLineSummaryProps = {
@@ -37,7 +49,19 @@ const RentalAgreementLineSummary = ({
const actions = useRentalLineActions(rentalAgreement);
const state = actions.stateOf(line);
const hasActions =
- state.canDeliver || state.canReturn || state.canSell || state.canDelete;
+ state.canDeliver ||
+ state.canReturn ||
+ state.canRelease ||
+ state.canSell ||
+ state.canDelete;
+ const routeData = useRouteData<RentalAgreementRouteData>(
+ path.to.rentalAgreement(rentalAgreement.id!)
+ );
+ const documents = rentalLineDocuments(
+ line.id,
+ routeData?.shipments ?? [],
+ routeData?.receipts ?? []
+ );
return (
<>
@@ -74,10 +98,34 @@ const RentalAgreementLineSummary = ({
{line.fixedAsset?.serialNumber || "—"}
</DetailRow>
<DetailRow label={t`Delivered`}>
- <DateTime value={line.deliveredAt} variant="date" fallback="—" />
+ <HStack spacing={2}>
+ <DateTime
+ value={line.deliveredAt}
+ variant="date"
+ fallback="—"
+ />
+ {documents.shipment && (
+ <Link
+ to={path.to.shipment(documents.shipment.id)}
+ className="hover:underline"
+ >
+ {documents.shipment.shipmentId}
+ </Link>
+ )}
+ </HStack>
</DetailRow>
<DetailRow label={t`Returned`}>
- <DateTime value={line.returnedAt} variant="date" fallback="—" />
+ <HStack spacing={2}>
+ <DateTime value={line.returnedAt} variant="date" fallback="—" />
+ {documents.receipt && (
+ <Link
+ to={path.to.receipt(documents.receipt.id)}
+ className="hover:underline"
+ >
+ {documents.receipt.receiptId}
+ </Link>
+ )}
+ </HStack>
</DetailRow>
</div>
</CardContent>
@@ -104,6 +152,16 @@ const RentalAgreementLineSummary = ({
<Trans>Return</Trans>
</Button>
)}
+ {state.canRelease && (
+ <Button
+ variant="secondary"
+ leftIcon={<LuCircleSlash />}
+ isDisabled={state.releaseDisabled}
+ onClick={() => actions.open("release", line)}
+ >
+ <Trans>Release unit</Trans>
+ </Button>
+ )}
{state.canSell && (
<Button
variant="secondary"
diff --git a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementReleaseForm.tsx b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementReleaseForm.tsx
new file mode 100644
index 0000000000..75125c9b32
--- /dev/null
+++ b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementReleaseForm.tsx
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
+ VStack
+} from "@carbon/react";
+import { parseDate } from "@internationalized/date";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useFetcher } from "react-router";
+import type { z } from "zod";
+import { DatePicker, Hidden, Submit } from "~/components/Form";
+import { useCompanyToday, usePermissions } from "~/hooks";
+import { rentalAgreementReleaseValidator } from "../../sales.models";
+
+type RentalAgreementReleaseFormProps = {
+ initialValues: z.infer<typeof rentalAgreementReleaseValidator>;
+ unitLabel: string;
+ /** Where the form posts when it is opened from a page rather than as its
+ * own route; it then also closes on submit. */
+ action?: string;
+ onClose: () => void;
+};
+
+const RentalAgreementReleaseForm = ({
+ initialValues,
+ unitLabel,
+ action,
+ onClose
+}: RentalAgreementReleaseFormProps) => {
+ const { t } = useLingui();
+ const permissions = usePermissions();
+ const fetcher = useFetcher<{}>();
+ const today = useCompanyToday();
+
+ return (
+ <ModalDrawerProvider type="modal">
+ <ModalDrawer
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ validator={rentalAgreementReleaseValidator}
+ method="post"
+ action={action}
+ fetcher={action ? fetcher : undefined}
+ defaultValues={initialValues}
+ className="flex flex-col h-full"
+ onSubmit={action ? onClose : undefined}
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>{t`Release ${unitLabel}`}</ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <Hidden name="rentalAgreementLineId" />
+ <VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ The unit never left the yard. Billing stops on the release
+ date, and the unit is free again.
+ </Trans>
+ </p>
+ <DatePicker
+ name="returnedAt"
+ label={t`Release date`}
+ maxValue={parseDate(today)}
+ />
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={!permissions.can("update", "sales")}>
+ <Trans>Release unit</Trans>
+ </Submit>
+ <Button size="md" variant="solid" onClick={onClose}>
+ <Trans>Cancel</Trans>
+ </Button>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
+ );
+};
+
+export default RentalAgreementReleaseForm;
diff --git a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementReturnForm.tsx b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementReturnForm.tsx
deleted file mode 100644
index 2dfb22fb19..0000000000
--- a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementReturnForm.tsx
+++ /dev/null
@@ -1,181 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
-// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-
-import { ValidatedForm } from "@carbon/form";
-import {
- Button,
- HStack,
- ModalDrawer,
- ModalDrawerBody,
- ModalDrawerContent,
- ModalDrawerFooter,
- ModalDrawerHeader,
- ModalDrawerProvider,
- ModalDrawerTitle,
- VStack
-} from "@carbon/react";
-import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
-import { Trans, useLingui } from "@lingui/react/macro";
-import { useState } from "react";
-import { useFetcher } from "react-router";
-import type { z } from "zod";
-import {
- Boolean,
- DatePicker,
- Hidden,
- Input,
- Number,
- Radios,
- Submit,
- TextArea
-} from "~/components/Form";
-import { useDateFormatter, usePermissions } from "~/hooks";
-import { rentalAgreementReturnValidator } from "../../sales.models";
-
-type RentalAgreementReturnFormProps = {
- initialValues: z.infer<typeof rentalAgreementReturnValidator>;
- unitLabel: string;
- /** A Sale unit carries a net investment that must land somewhere. */
- isSalesType?: boolean;
- /** The agreement's end date — a sales-type unit comes back on or after it. */
- endDate?: string | null;
- /** Where the form posts when it is opened from a page rather than as its
- * own route; it then also closes on submit. */
- action?: string;
- onClose: () => void;
-};
-
-const RentalAgreementReturnForm = ({
- initialValues,
- unitLabel,
- isSalesType = false,
- endDate,
- action,
- onClose
-}: RentalAgreementReturnFormProps) => {
- const { t } = useLingui();
- const permissions = usePermissions();
- const fetcher = useFetcher<{}>();
- const { formatDate } = useDateFormatter();
- const [takeOutOfService, setTakeOutOfService] = useState(
- initialValues.takeOutOfService
- );
-
- return (
- <ModalDrawerProvider type="modal">
- <ModalDrawer
- open
- onOpenChange={(open) => {
- if (!open) onClose();
- }}
- >
- <ModalDrawerContent>
- <ValidatedForm
- validator={rentalAgreementReturnValidator}
- method="post"
- action={action}
- fetcher={action ? fetcher : undefined}
- defaultValues={initialValues}
- className="flex flex-col h-full"
- onSubmit={action ? onClose : undefined}
- >
- <ModalDrawerHeader>
- <ModalDrawerTitle>
- <Trans>Return {unitLabel}</Trans>
- </ModalDrawerTitle>
- </ModalDrawerHeader>
- <ModalDrawerBody>
- <Hidden name="rentalAgreementLineId" />
- {/* A checkbox field: absent means false. An empty value fails
- zfd.checkbox({ trueValue: "true" }) and the form never posts. */}
- {isSalesType && <Hidden name="isSalesType" value="true" />}
- <VStack spacing={4}>
- {/* A sales-type term never re-cuts: its billing was fixed
- at activation and the unit comes back on or after the end
- date. */}
- {!isSalesType && (
- <p className="text-sm text-muted-foreground">
- <Trans>
- The final billing period is re-cut to the return date. A
- period already billed in advance gets an adjustment for
- the unused days.
- </Trans>
- </p>
- )}
- {isSalesType && (
- <>
- <p className="text-sm text-muted-foreground">
- <Trans>
- This rental is treated as a sale. The closing net
- investment comes back onto the balance sheet with the
- unit, and the unposted interest schedule is removed.
- </Trans>
- </p>
- {endDate && (
- <p className="text-sm text-muted-foreground">
- <Trans>
- The unit can be returned on or after the end date,{" "}
- {formatDate(endDate)}. Ending a rental treated as a
- sale early is a manual journal.
- </Trans>
- </p>
- )}
- <Radios
- name="residualDestination"
- label={t`Return To`}
- options={[
- {
- value: "Fleet",
- label: t`Rental fleet, as a new fleet asset`
- },
- {
- value: "Inventory",
- label: t`Inventory, as finished goods`
- }
- ]}
- />
- </>
- )}
- <DatePicker name="returnedAt" label={t`Return Date`} />
- <Number
- name="meterIn"
- label={t`Meter Reading`}
- minValue={0}
- step={INPUT_STEP.quantity}
- formatOptions={INPUT_FORMAT.quantity}
- />
- <TextArea name="returnNotes" label={t`Return Notes`} />
- <Boolean
- name="takeOutOfService"
- label={t`Take out of service`}
- description={t`The unit goes to maintenance instead of back to available.`}
- onChange={setTakeOutOfService}
- bordered
- />
- {takeOutOfService && (
- <Input
- name="outOfServiceReason"
- label={t`Out of Service Reason`}
- />
- )}
- </VStack>
- </ModalDrawerBody>
- <ModalDrawerFooter>
- <HStack>
- <Submit isDisabled={!permissions.can("update", "sales")}>
- <Trans>Return Unit</Trans>
- </Submit>
- <Button size="md" variant="solid" onClick={onClose}>
- <Trans>Cancel</Trans>
- </Button>
- </HStack>
- </ModalDrawerFooter>
- </ValidatedForm>
- </ModalDrawerContent>
- </ModalDrawer>
- </ModalDrawerProvider>
- );
-};
-
-export default RentalAgreementReturnForm;
diff --git a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementSummary.tsx b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementSummary.tsx
index 1876b27767..f1d7934bb8 100644
--- a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementSummary.tsx
+++ b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementSummary.tsx
@@ -14,24 +14,22 @@ import {
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import type { ReactNode } from "react";
-import { LuImage, LuTruck, LuUndo2 } from "react-icons/lu";
+import { LuImage } from "react-icons/lu";
import { Link } from "react-router";
import { CustomerAvatar, DateTime, MotionMoney } from "~/components";
-import { useCurrencyDecimals } from "~/hooks";
+import { useCurrencyDecimals, useRouteData } from "~/hooks";
import { getPrivateUrl, path } from "~/utils/path";
+import { rentalLineDocuments } from "../../sales.utils";
import { LeaseClassificationBadge } from "./RentalLeaseClassification";
import RentalStatus from "./RentalStatus";
import type {
RentalAgreement,
RentalAgreementLine,
+ RentalAgreementRouteData,
RentalAgreementStatusType,
RentalBillingPeriod
} from "./types";
-import {
- type RentalLineActionState,
- rentalUnitLabel,
- useRentalLineActions
-} from "./useRentalLineActions";
+import { rentalUnitLabel } from "./useRentalLineActions";
type RentalAgreementSummaryProps = {
rentalAgreement: RentalAgreement;
@@ -40,9 +38,9 @@ type RentalAgreementSummaryProps = {
};
/** The agreement at a glance, laid out like the sales order summary: its
- * units as line items with their rates (and Deliver / Return, so a unit
- * need not be opened to move it), then what has been billed, what is still
- * to bill, the deposit and the next due date. */
+ * units as line items with their rates, then what has been billed, what is
+ * still to bill, the deposit and the next due date. Units are delivered and
+ * returned from the header's Shipments / Receipts actions. */
const RentalAgreementSummary = ({
rentalAgreement,
lines,
@@ -50,7 +48,11 @@ const RentalAgreementSummary = ({
}: RentalAgreementSummaryProps) => {
const currencyCode = rentalAgreement.currencyCode ?? "USD";
const currencyDecimals = useCurrencyDecimals(currencyCode);
- const actions = useRentalLineActions(rentalAgreement);
+ const routeData = useRouteData<RentalAgreementRouteData>(
+ path.to.rentalAgreement(rentalAgreement.id!)
+ );
+ const shipments = routeData?.shipments ?? [];
+ const receipts = routeData?.receipts ?? [];
const billed = periods
.filter((period) => period.status === "Invoiced")
@@ -73,117 +75,112 @@ const RentalAgreementSummary = ({
);
return (
- <>
- <Card>
- <CardHeader>
- <HStack className="justify-between items-center">
- <div className="flex flex-col gap-1">
- <CardTitle>{rentalAgreement.rentalAgreementId}</CardTitle>
- </div>
- <div className="flex flex-col gap-1 items-end">
- <CustomerAvatar customerId={rentalAgreement.customerId ?? null} />
- <span className="text-xs text-muted-foreground tracking-tight">
- <DateTime value={rentalAgreement.startDate} variant="date" />
- {" – "}
- {rentalAgreement.endDate ? (
- <DateTime value={rentalAgreement.endDate} variant="date" />
- ) : (
- <Trans>Open-ended</Trans>
- )}
- </span>
- </div>
- </HStack>
- </CardHeader>
- <CardContent>
- {lines.length === 0 ? (
- <p className="text-sm text-muted-foreground">
- <Trans>
- No units yet. Add a fleet unit from the Units list before
- activating the agreement.
- </Trans>
- </p>
- ) : (
- <VStack spacing={0} className="w-full overflow-hidden">
- {lines.map((line) => (
- <SummaryLine
- key={line.id}
- agreementId={rentalAgreement.id!}
- currencyCode={currencyCode}
- line={line}
- state={actions.stateOf(line)}
- onDeliver={() => actions.open("deliver", line)}
- onReturn={() => actions.open("return", line)}
- />
- ))}
- </VStack>
- )}
-
- <VStack spacing={2} className="mt-8">
- <HStack className="justify-between text-sm text-muted-foreground w-full">
- <span>
- <Trans>Billed:</Trans>
- </span>
- <MotionMoney
- value={billed}
- currency={currencyCode}
- decimalPlaces={currencyDecimals}
- />
- </HStack>
- <HStack className="justify-between text-sm text-muted-foreground w-full">
- <span>
- <Trans>Unbilled:</Trans>
- </span>
- <MotionMoney
- value={Number(rentalAgreement.unbilledAmount ?? 0)}
- currency={currencyCode}
- decimalPlaces={currencyDecimals}
+ <Card>
+ <CardHeader>
+ <HStack className="justify-between items-center">
+ <div className="flex flex-col gap-1">
+ <CardTitle>{rentalAgreement.rentalAgreementId}</CardTitle>
+ </div>
+ <div className="flex flex-col gap-1 items-end">
+ <CustomerAvatar customerId={rentalAgreement.customerId ?? null} />
+ <span className="text-xs text-muted-foreground tracking-tight">
+ <DateTime value={rentalAgreement.startDate} variant="date" />
+ {" – "}
+ {rentalAgreement.endDate ? (
+ <DateTime value={rentalAgreement.endDate} variant="date" />
+ ) : (
+ <Trans>Open-ended</Trans>
+ )}
+ </span>
+ </div>
+ </HStack>
+ </CardHeader>
+ <CardContent>
+ {lines.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ No units yet. Add a fleet unit from the Units list before
+ activating the agreement.
+ </Trans>
+ </p>
+ ) : (
+ <VStack spacing={0} className="w-full overflow-hidden">
+ {lines.map((line) => (
+ <SummaryLine
+ key={line.id}
+ agreementId={rentalAgreement.id!}
+ currencyCode={currencyCode}
+ line={line}
+ documents={rentalLineDocuments(line.id, shipments, receipts)}
/>
- </HStack>
- {monthlyRent !== null && (
- <HStack className="justify-between text-xl font-semibold w-full">
- <span>
- <Trans>Monthly Rent:</Trans>
- </span>
- <MotionMoney
- value={monthlyRent}
- currency={currencyCode}
- decimalPlaces={currencyDecimals}
- />
- </HStack>
- )}
- <div className="h-px bg-border my-2 w-full" />
- <HStack className="justify-between text-sm text-muted-foreground w-full">
+ ))}
+ </VStack>
+ )}
+
+ <VStack spacing={2} className="mt-8">
+ <HStack className="justify-between text-sm text-muted-foreground w-full">
+ <span>
+ <Trans>Billed:</Trans>
+ </span>
+ <MotionMoney
+ value={billed}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
+ />
+ </HStack>
+ <HStack className="justify-between text-sm text-muted-foreground w-full">
+ <span>
+ <Trans>Unbilled:</Trans>
+ </span>
+ <MotionMoney
+ value={Number(rentalAgreement.unbilledAmount ?? 0)}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
+ />
+ </HStack>
+ {monthlyRent !== null && (
+ <HStack className="justify-between text-xl font-semibold w-full">
<span>
- <Trans>Deposit:</Trans>
+ <Trans>Monthly Rent:</Trans>
</span>
<MotionMoney
- value={Number(rentalAgreement.depositAmount ?? 0)}
+ value={monthlyRent}
currency={currencyCode}
decimalPlaces={currencyDecimals}
/>
</HStack>
- <HStack className="justify-between text-sm text-muted-foreground w-full">
- <span>
- <Trans>Next Due:</Trans>
- </span>
- <span>
- {rentalAgreement.nextDueOn ? (
- <DateTime value={rentalAgreement.nextDueOn} variant="date" />
- ) : (
- "—"
- )}
- </span>
- </HStack>
- {invoicingSchedule && (
- <p className="text-xs text-muted-foreground w-full">
- {invoicingSchedule}
- </p>
- )}
- </VStack>
- </CardContent>
- </Card>
- {actions.modals}
- </>
+ )}
+ <div className="h-px bg-border my-2 w-full" />
+ <HStack className="justify-between text-sm text-muted-foreground w-full">
+ <span>
+ <Trans>Deposit:</Trans>
+ </span>
+ <MotionMoney
+ value={Number(rentalAgreement.depositAmount ?? 0)}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
+ />
+ </HStack>
+ <HStack className="justify-between text-sm text-muted-foreground w-full">
+ <span>
+ <Trans>Next Due:</Trans>
+ </span>
+ <span>
+ {rentalAgreement.nextDueOn ? (
+ <DateTime value={rentalAgreement.nextDueOn} variant="date" />
+ ) : (
+ "—"
+ )}
+ </span>
+ </HStack>
+ {invoicingSchedule && (
+ <p className="text-xs text-muted-foreground w-full">
+ {invoicingSchedule}
+ </p>
+ )}
+ </VStack>
+ </CardContent>
+ </Card>
);
};
@@ -191,16 +188,12 @@ function SummaryLine({
agreementId,
currencyCode,
line,
- state,
- onDeliver,
- onReturn
+ documents
}: {
agreementId: string;
currencyCode: string;
line: RentalAgreementLine;
- state: RentalLineActionState;
- onDeliver: () => void;
- onReturn: () => void;
+ documents: ReturnType<typeof rentalLineDocuments>;
}) {
const { t } = useLingui();
const currencyDecimals = useCurrencyDecimals(currencyCode);
@@ -255,38 +248,32 @@ function SummaryLine({
{line.lessorClassification && (
<LeaseClassificationBadge value={line.lessorClassification} />
)}
+ {documents.shipment && (
+ <Link
+ to={path.to.shipment(documents.shipment.id)}
+ className="text-xs text-muted-foreground hover:underline"
+ >
+ {documents.shipment.shipmentId}
+ </Link>
+ )}
+ {documents.receipt && (
+ <Link
+ to={path.to.receipt(documents.receipt.id)}
+ className="text-xs text-muted-foreground hover:underline"
+ >
+ {documents.receipt.receiptId}
+ </Link>
+ )}
</HStack>
</VStack>
- <VStack spacing={2} className="flex-shrink-0 items-end w-auto">
- <VStack spacing={0} className="items-end">
- <MotionMoney
- className="font-semibold text-xl whitespace-nowrap"
- value={Number(line.rate)}
- currency={currencyCode}
- decimalPlaces={currencyDecimals}
- />
- <span className="text-xs text-muted-foreground">{per}</span>
- </VStack>
- {state.canDeliver && (
- <Button
- variant="primary"
- leftIcon={<LuTruck />}
- isDisabled={state.deliverDisabled}
- onClick={onDeliver}
- >
- <Trans>Deliver</Trans>
- </Button>
- )}
- {state.canReturn && (
- <Button
- variant="primary"
- leftIcon={<LuUndo2 />}
- isDisabled={state.returnDisabled}
- onClick={onReturn}
- >
- <Trans>Return</Trans>
- </Button>
- )}
+ <VStack spacing={0} className="flex-shrink-0 items-end w-auto">
+ <MotionMoney
+ className="font-semibold text-xl whitespace-nowrap"
+ value={Number(line.rate)}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
+ />
+ <span className="text-xs text-muted-foreground">{per}</span>
</VStack>
</div>
</HStack>
diff --git a/apps/erp/app/modules/sales/ui/Rentals/RentalStatus.tsx b/apps/erp/app/modules/sales/ui/Rentals/RentalStatus.tsx
index dc10b4f2bd..01cad2d324 100644
--- a/apps/erp/app/modules/sales/ui/Rentals/RentalStatus.tsx
+++ b/apps/erp/app/modules/sales/ui/Rentals/RentalStatus.tsx
@@ -4,6 +4,7 @@
import { Status } from "@carbon/react";
import { Trans } from "@lingui/react/macro";
+import type { RentalEquipmentStatus } from "../../sales.utils";
import type {
RentalAgreementLineStatusType,
RentalAgreementStatusType,
@@ -81,4 +82,47 @@ const RentalStatus = ({ status }: RentalStatusProps) => {
}
};
+/** Where the agreement's units are (`rentalEquipmentStatus`), beside the
+ * agreement's own status in the header. */
+export const RentalEquipmentStatusBadge = ({
+ status
+}: {
+ status: RentalEquipmentStatus | null;
+}) => {
+ switch (status) {
+ case "To Deliver":
+ return (
+ <Status color="orange">
+ <Trans>To Deliver</Trans>
+ </Status>
+ );
+ case "Partially Delivered":
+ return (
+ <Status color="yellow">
+ <Trans>Partially Delivered</Trans>
+ </Status>
+ );
+ case "On Rent":
+ return (
+ <Status color="blue">
+ <Trans>On Rent</Trans>
+ </Status>
+ );
+ case "Partially Returned":
+ return (
+ <Status color="yellow">
+ <Trans>Partially Returned</Trans>
+ </Status>
+ );
+ case "Returned":
+ return (
+ <Status color="green">
+ <Trans>Returned</Trans>
+ </Status>
+ );
+ default:
+ return null;
+ }
+};
+
export default RentalStatus;
diff --git a/apps/erp/app/modules/sales/ui/Rentals/index.ts b/apps/erp/app/modules/sales/ui/Rentals/index.ts
index cf984be8f6..858703580e 100644
--- a/apps/erp/app/modules/sales/ui/Rentals/index.ts
+++ b/apps/erp/app/modules/sales/ui/Rentals/index.ts
@@ -12,7 +12,7 @@ import RentalAgreementHeader from "./RentalAgreementHeader";
import RentalAgreementLineForm from "./RentalAgreementLineForm";
import RentalAgreementLineSummary from "./RentalAgreementLineSummary";
import RentalAgreementProperties from "./RentalAgreementProperties";
-import RentalAgreementReturnForm from "./RentalAgreementReturnForm";
+import RentalAgreementReleaseForm from "./RentalAgreementReleaseForm";
import RentalAgreementSummary from "./RentalAgreementSummary";
import RentalAgreementsTable from "./RentalAgreementsTable";
import RentalBillingPeriods from "./RentalBillingPeriods";
@@ -51,7 +51,7 @@ export {
RentalAgreementLineForm,
RentalAgreementLineSummary,
RentalAgreementProperties,
- RentalAgreementReturnForm,
+ RentalAgreementReleaseForm,
RentalAgreementSummary,
RentalAgreementsTable,
RentalBillingPeriods,
diff --git a/apps/erp/app/modules/sales/ui/Rentals/types.ts b/apps/erp/app/modules/sales/ui/Rentals/types.ts
index acd132dd57..d69d8e9bfb 100644
--- a/apps/erp/app/modules/sales/ui/Rentals/types.ts
+++ b/apps/erp/app/modules/sales/ui/Rentals/types.ts
@@ -8,6 +8,7 @@ import type {
getRentalAgreementCharges,
getRentalAgreementDeposits,
getRentalAgreementLines,
+ getRentalAgreementRelatedDocuments,
getRentalBillingPeriods
} from "../../sales.service";
import type { LeasePolicy } from "../../sales.utils";
@@ -63,6 +64,12 @@ export type RentalLeaseLineInputs = {
accumulatedDepreciation: number | null;
};
+type RelatedDocuments = NonNullable<
+ Awaited<ReturnType<typeof getRentalAgreementRelatedDocuments>>["data"]
+>;
+export type RentalAgreementShipment = RelatedDocuments["shipments"][number];
+export type RentalAgreementReceipt = RelatedDocuments["receipts"][number];
+
/** The shell route's loader data, read by every section through
* `useRouteData(path.to.rentalAgreement(id))`. */
export type RentalAgreementRouteData = {
@@ -71,6 +78,8 @@ export type RentalAgreementRouteData = {
charges: RentalAgreementCharge[];
periods: RentalBillingPeriod[];
deposits: RentalAgreementDeposit[];
+ shipments: RentalAgreementShipment[];
+ receipts: RentalAgreementReceipt[];
rentableAssets: RentableFleetAsset[];
invoiceLinks: RentalInvoiceLinks;
/** The customer contact's email; null when there is none to send to. */
diff --git a/apps/erp/app/modules/sales/ui/Rentals/useRentalLineActions.tsx b/apps/erp/app/modules/sales/ui/Rentals/useRentalLineActions.tsx
index c4d72bb516..822b7172f8 100644
--- a/apps/erp/app/modules/sales/ui/Rentals/useRentalLineActions.tsx
+++ b/apps/erp/app/modules/sales/ui/Rentals/useRentalLineActions.tsx
@@ -4,23 +4,26 @@
import { useLingui } from "@lingui/react/macro";
import { useState } from "react";
+import { useSubmit } from "react-router";
import { Confirm, ConfirmDelete } from "~/components/Modals";
import { useCompanyToday, useCurrencyFormatter, usePermissions } from "~/hooks";
import { path } from "~/utils/path";
-import RentalAgreementReturnForm from "./RentalAgreementReturnForm";
+import RentalAgreementReleaseForm from "./RentalAgreementReleaseForm";
import type { RentalAgreement, RentalAgreementLine } from "./types";
-type RentalLineAction = "deliver" | "return" | "sell" | "delete";
+type RentalLineAction = "deliver" | "return" | "release" | "sell" | "delete";
export type RentalLineActionState = {
/** Shown at all: the line is in the state the action applies to. */
canDeliver: boolean;
canReturn: boolean;
+ canRelease: boolean;
canSell: boolean;
canDelete: boolean;
/** Shown but refused for want of a permission. */
deliverDisabled: boolean;
returnDisabled: boolean;
+ releaseDisabled: boolean;
sellDisabled: boolean;
deleteDisabled: boolean;
};
@@ -32,14 +35,16 @@ export const rentalUnitLabel = (line: RentalAgreementLine) =>
line.item?.readableIdWithRevision ||
"";
-/** The one home of a unit's lifecycle actions — Deliver, Return, Sell to
- * Customer and Delete — so the units table, the explorer and the unit page
- * offer the same actions under the same rules. Each opens its confirmation
- * (or the return form) as page state and posts to the action route, which
- * redirects back to the page it came from. */
+/** The one home of a unit's lifecycle actions — Deliver, Return, Release
+ * unit, Sell to Customer and Delete — so the units table, the explorer and
+ * the unit page offer the same actions under the same rules. Deliver and
+ * Return open a rental shipment or receipt holding the unit; Release unit
+ * opens a date modal; Sell and Delete open their confirmation. Each posts to
+ * its action route, which redirects to the document or back to the page. */
export function useRentalLineActions(rentalAgreement: RentalAgreement) {
const { t } = useLingui();
const permissions = usePermissions();
+ const submit = useSubmit();
const today = useCompanyToday();
const [pending, setPending] = useState<{
action: RentalLineAction;
@@ -50,6 +55,8 @@ export function useRentalLineActions(rentalAgreement: RentalAgreement) {
const isDraft = rentalAgreement.status === "Draft";
const isActive = rentalAgreement.status === "Active";
const canUpdate = permissions.can("update", "sales");
+ // Deliver and Return draft an inventory document.
+ const canMoveUnits = canUpdate && permissions.can("create", "inventory");
// Selling bills a charge and drafts its invoice.
const canSellPermission =
canUpdate &&
@@ -61,45 +68,59 @@ export function useRentalLineActions(rentalAgreement: RentalAgreement) {
});
const stateOf = (line: RentalAgreementLine): RentalLineActionState => {
- // Returned and Sold lines are finished; only a unit on rent comes back.
- const canReturn = isActive && line.status === "On Rent";
+ // Returned and Sold lines are finished. A receipt also takes back a
+ // Pending unit (spec Q8).
+ const canReturn =
+ isActive && (line.status === "On Rent" || line.status === "Pending");
return {
canDeliver: isActive && line.status === "Pending",
canReturn,
+ // A unit treated as a sale comes back on a receipt, with Return To
+ // (plan decision P1).
+ canRelease:
+ isActive &&
+ line.status === "Pending" &&
+ line.lessorClassification !== "Sale",
// The purchase option ends a sales-type lease by sale, at the end of
// the term (the sell route refuses it earlier).
canSell:
- canReturn &&
+ isActive &&
+ line.status === "On Rent" &&
line.lessorClassification === "Sale" &&
purchaseOptionAmount > 0 &&
(!rentalAgreement.endDate || today >= rentalAgreement.endDate),
canDelete: isDraft,
- deliverDisabled: !canUpdate,
- returnDisabled: !canUpdate,
+ deliverDisabled: !canMoveUnits,
+ returnDisabled: !canMoveUnits,
+ releaseDisabled: !canUpdate,
sellDisabled: !canSellPermission,
deleteDisabled: !permissions.can("delete", "sales")
};
};
- const open = (action: RentalLineAction, line: RentalAgreementLine) =>
+ const open = (action: RentalLineAction, line: RentalAgreementLine) => {
+ if (action === "deliver") {
+ submit(new FormData(), {
+ method: "post",
+ action: path.to.rentalAgreementLineDeliver(id, line.id)
+ });
+ return;
+ }
+ if (action === "return") {
+ submit(new FormData(), {
+ method: "post",
+ action: path.to.rentalAgreementLineReturn(id, line.id)
+ });
+ return;
+ }
setPending({ action, line });
+ };
const close = () => setPending(null);
const label = pending ? rentalUnitLabel(pending.line) : "";
const modals = pending ? (
<>
- {pending.action === "deliver" && (
- <Confirm
- action={path.to.rentalAgreementLineDeliver(id, pending.line.id)}
- title={t`Deliver ${label}`}
- text={t`Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle.`}
- confirmText={t`Deliver`}
- confirmVariant="primary"
- onCancel={close}
- onSubmit={close}
- />
- )}
{pending.action === "sell" && (
<Confirm
action={path.to.rentalAgreementLineSell(id, pending.line.id)}
@@ -121,19 +142,14 @@ export function useRentalLineActions(rentalAgreement: RentalAgreement) {
onSubmit={close}
/>
)}
- {pending.action === "return" && (
- <RentalAgreementReturnForm
- action={path.to.rentalAgreementLineReturn(id, pending.line.id)}
+ {pending.action === "release" && (
+ <RentalAgreementReleaseForm
+ action={path.to.rentalAgreementLineRelease(id, pending.line.id)}
initialValues={{
rentalAgreementLineId: pending.line.id,
- returnedAt: today,
- takeOutOfService: false,
- isSalesType: pending.line.lessorClassification === "Sale",
- residualDestination: undefined
+ returnedAt: today
}}
unitLabel={label}
- isSalesType={pending.line.lessorClassification === "Sale"}
- endDate={rentalAgreement.endDate}
onClose={close}
/>
)}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 6b15d5a129..191ab91754 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1,5 +1,5 @@
{
- "totalTools": 1542,
+ "totalTools": 1545,
"modules": 15,
"tools": [
{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},
@@ -217,22 +217,24 @@
{"name":"inventory_getPickingSchedule","classification":"READ","paramCount":2,"schema":"b3a9deeaf0d0","response":"19467666efcd","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickOrder","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"7fa0311f0d0a","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPicksByJobMaterial","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"b53992cb5f0c","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getReceipt","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"912bc3c9329d","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getReceipt","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"b7c00288df9c","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getReceiptFiles","classification":"READ","paramCount":1,"schema":"749e5d81384a","response":"5483e69d7515","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getReceiptLines","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"15b7b17f7652","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getReceiptLineTracking","classification":"READ","paramCount":1,"schema":"17337505bb69","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getReceiptRelatedItems","classification":"READ","paramCount":2,"schema":"bc54dac2bca6","response":"0f4d8e489d1b","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getReceipts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"a19e9d631841","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},
+ {"name":"inventory_getReceipts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"4aa48aba067d","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},
{"name":"inventory_getReceiptTracking","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getRentalReceiptLines","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"2e9dfef414a9","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getRentalShipmentLines","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"1ab616adb2e0","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getSerialNumbersForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getShelfLifeForItems","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"4c5d680d898e","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getShipment","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"d8a84a1f08ec","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getShipment","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"cf99c31d666e","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getShipmentFiles","classification":"READ","paramCount":1,"schema":"749e5d81384a","response":"5483e69d7515","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getShipmentLines","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"1b1f740f30c6","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getShipmentLinesWithDetails","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"c158915aa9b9","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getShipmentLineTracking","classification":"READ","paramCount":1,"schema":"84320a09c1ac","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getShipmentRelatedItems","classification":"READ","paramCount":2,"schema":"f81a81d39efa","response":"0e975679737c","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getShipments","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"b8b287b3a17f","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},
+ {"name":"inventory_getShipments","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"92c56e0fa40a","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},
{"name":"inventory_getShipmentTracking","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getShippingMethod","classification":"READ","paramCount":1,"schema":"493e990b5f3d","response":"65413dd34c52","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getShippingMethods","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"104aa0df039d","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},
@@ -291,8 +293,8 @@
{"name":"inventory_upsertBatchProperty","classification":"WRITE","paramCount":6,"schema":"6fcfef7093ed","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"inventory:create+update","paginates":false},
{"name":"inventory_upsertKanban","classification":"WRITE","paramCount":14,"schema":"9500a3f1264b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id","defaults":"create"},
{"name":"inventory_upsertPickingList","classification":"WRITE","paramCount":7,"schema":"dbe65909f79e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},
- {"name":"inventory_upsertReceipt","classification":"WRITE","paramCount":9,"schema":"a3061dfb8ce9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},
- {"name":"inventory_upsertShipment","classification":"WRITE","paramCount":10,"schema":"b672e5466228","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},
+ {"name":"inventory_upsertReceipt","classification":"WRITE","paramCount":9,"schema":"fd0848682b0b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},
+ {"name":"inventory_upsertShipment","classification":"WRITE","paramCount":10,"schema":"efe95221a775","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},
{"name":"inventory_upsertShippingMethod","classification":"WRITE","paramCount":6,"schema":"6d157a6086d0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},
{"name":"inventory_upsertStockTransferLine","classification":"WRITE","paramCount":9,"schema":"9d7761b29bb0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},
{"name":"inventory_upsertStorageType","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},
@@ -1282,6 +1284,7 @@
{"name":"sales_getRentalAgreementDeposits","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"d1712908bacb","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getRentalAgreementLine","classification":"READ","paramCount":1,"schema":"9729319c460e","response":"241639dc09ac","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getRentalAgreementLines","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"3ed7f3538cc6","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getRentalAgreementRelatedDocuments","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"e6faf3cc340a","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getRentalAgreements","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"e6c6ed5e084e","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},
{"name":"sales_getRentalBillingPeriods","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"10915ab32ad5","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getReturnableLinesForCustomer","classification":"READ","paramCount":2,"schema":"e9ef772b4706","response":"8b3d2e7917fd","injectAuth":"companyId","permission":"sales:view","paginates":false},
@@ -1300,9 +1303,9 @@
{"name":"sales_getSalesOrderLines","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"64e0b7280c5e","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderLinesByItemId","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"64e0b7280c5e","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderLinesByItemIds","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"64e0b7280c5e","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getSalesOrderLineShipments","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"131473831fc0","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getSalesOrderLineShipments","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"2414f4b5bcaf","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderPayment","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"e52a6a8beddf","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getSalesOrderRelatedItems","classification":"READ","paramCount":2,"schema":"651e9f51b36d","response":"797511531d8e","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getSalesOrderRelatedItems","classification":"READ","paramCount":2,"schema":"651e9f51b36d","response":"de3f79e02cdb","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrders","classification":"READ","paramCount":5,"schema":"ef4d06fef47e","response":"f397c1f3b176","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},
{"name":"sales_getSalesOrdersByIds","classification":"READ","paramCount":1,"schema":"0eb0c2be01ed","response":"5cc20a44d4fe","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderShipment","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"0f0a39ddefae","injectAuth":"companyId","permission":"sales:view","paginates":false},
diff --git a/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx
index 1adb693ce0..e860badca1 100644
--- a/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx
@@ -18,6 +18,7 @@ import { renderToStream } from "@react-pdf/renderer";
import type { LoaderFunctionArgs } from "react-router";
import { getPaymentTerm } from "~/modules/accounting";
import {
+ getRentalShipmentLines,
getShipment,
getShipmentLinesWithDetails,
getShipmentTracking,
@@ -31,6 +32,7 @@ import {
} from "~/modules/purchasing";
import {
getCustomerLocation,
+ getRentalAgreement,
getSalesOrder,
getSalesOrderShipment,
getSalesTerms
@@ -593,6 +595,118 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
headers: transferHeaders
});
}
+ case "Rental Agreement": {
+ const rentalAgreement = await getRentalAgreement(
+ serviceRole,
+ shipment.data.sourceDocumentId,
+ companyId
+ );
+
+ if (rentalAgreement.error) {
+ logger.error("Failed to load rentalAgreement", {
+ error: rentalAgreement.error
+ });
+ throw new Error("Failed to load rental agreement");
+ }
+
+ const [
+ customer,
+ customerLocation,
+ paymentTerm,
+ shippingMethod,
+ rentalLines
+ ] = await Promise.all([
+ serviceRole
+ .from("customer")
+ .select("*")
+ .eq("id", rentalAgreement.data.customerId ?? "")
+ .eq("companyId", companyId)
+ .single(),
+ getCustomerLocation(
+ serviceRole,
+ rentalAgreement.data.customerLocationId ?? ""
+ ),
+ getPaymentTerm(serviceRole, rentalAgreement.data.paymentTermId ?? ""),
+ getShippingMethod(serviceRole, shipment.data.shippingMethodId ?? ""),
+ getRentalShipmentLines(serviceRole, id, companyId)
+ ]);
+
+ if (customer.error) {
+ logger.error("Failed to load customer", { error: customer.error });
+ throw new Error("Failed to load customer");
+ }
+
+ if (rentalLines.error) {
+ logger.error("Failed to load rental units", {
+ error: rentalLines.error
+ });
+ throw new Error("Failed to load rental units");
+ }
+
+ const rentalUnits = (rentalLines.data ?? [])
+ .filter((row) => row.shipped)
+ .map((row) => {
+ // The read filters out rows with no rental line.
+ const line = row.rentalAgreementLine!;
+ return {
+ id: row.id,
+ name: line.fixedAsset?.name ?? line.item?.name ?? "Rental unit",
+ assetReadableId: line.fixedAsset?.fixedAssetId ?? null,
+ serialNumber:
+ line.fixedAsset?.serialNumber ??
+ line.trackedEntity?.readableId ??
+ null
+ };
+ });
+
+ const rentalStream = await renderToStream(
+ <PackingSlipPDF
+ company={company.data as any}
+ customer={customer.data}
+ locale={locale}
+ meta={{
+ author: "Carbon",
+ keywords: "delivery ticket",
+ subject: "Delivery Ticket"
+ }}
+ sourceDocument="Rental Agreement"
+ sourceDocumentId={rentalAgreement.data.rentalAgreementId ?? undefined}
+ shipment={shipment.data}
+ shipmentLines={shipmentLines.data ?? []}
+ // @ts-expect-error
+ shippingAddress={customerLocation.data?.address ?? null}
+ terms={(terms?.data?.salesTerms ?? {}) as JSONContent}
+ paymentTerm={paymentTerm.data ?? { id: "", name: "" }}
+ shippingMethod={shippingMethod.data ?? { id: "", name: "" }}
+ trackedEntities={[]}
+ rentalUnits={rentalUnits}
+ title="Delivery Ticket"
+ thumbnails={{}}
+ template={templateConfig}
+ sections={templateSections}
+ />
+ );
+
+ const rentalBody: Buffer = await new Promise((resolve, reject) => {
+ const buffers: Uint8Array[] = [];
+ rentalStream.on("data", (data) => {
+ buffers.push(data);
+ });
+ rentalStream.on("end", () => {
+ resolve(Buffer.concat(buffers));
+ });
+ rentalStream.on("error", reject);
+ });
+
+ const rentalHeaders = new Headers({
+ "Content-Type": "application/pdf",
+ "Content-Disposition": `inline; filename="${company.data.name} - ${shipment.data.shipmentId}.pdf"`
+ });
+ return new Response(new Uint8Array(rentalBody), {
+ status: 200,
+ headers: rentalHeaders
+ });
+ }
default:
throw new Error("Invalid source document");
}
diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.details.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.details.tsx
index 9784fbaecc..afead002d9 100644
--- a/apps/erp/app/routes/x+/receipt+/$receiptId.details.tsx
+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.details.tsx
@@ -58,7 +58,26 @@ export async function action({ request }: ActionFunctionArgs) {
currentReceipt.data.sourceDocumentId !== d.sourceDocumentId ||
currentReceipt.data.locationId !== d.locationId;
- if (receiptDataHasChanged) {
+ const sourceChanged =
+ currentReceipt.data.sourceDocument !== d.sourceDocument ||
+ currentReceipt.data.sourceDocumentId !== d.sourceDocumentId;
+ const isRental =
+ currentReceipt.data.sourceDocument === "Rental Agreement" ||
+ d.sourceDocument === "Rental Agreement";
+ if (isRental && sourceChanged) {
+ return data(
+ {},
+ await flash(
+ request,
+ error(
+ null,
+ "A rental receipt keeps its rental agreement. Create it from the agreement."
+ )
+ )
+ );
+ }
+
+ if (receiptDataHasChanged && !isRental) {
switch (d.sourceDocument) {
case "Purchase Order":
const purchaseOrderReceipt = await serverFns
@@ -178,7 +197,8 @@ export default function ReceiptDetailsRoute() {
externalDocumentId: routeData.receipt.externalDocumentId ?? undefined,
sourceDocument: (routeData.receipt.sourceDocument ?? "Purchase Order") as
| "Purchase Order"
- | "Inbound Transfer",
+ | "Inbound Transfer"
+ | "Rental Agreement",
sourceDocumentId: routeData.receipt.sourceDocumentId ?? undefined,
sourceDocumentReadableId:
routeData.receipt.sourceDocumentReadableId ?? undefined,
diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx
index 55cecac1f4..ee8cb421c1 100644
--- a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx
+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx
@@ -35,6 +35,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
const formData = await request.formData();
const acknowledged = formData.get("acknowledged") === "true";
+ const postingDateValue = formData.get("postingDate");
+ const postingDate =
+ typeof postingDateValue === "string" && postingDateValue !== ""
+ ? postingDateValue
+ : undefined;
// Storage Rule evaluation across every line on this receipt before posting.
// Use service role so item / storageUnit reads are not blocked by RLS for
@@ -221,7 +226,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
const posted = await serverFns
.system({ db: getDatabaseClient(), companyId, userId })
.invoke("post-receipt", {
- receiptId: receiptId
+ receiptId,
+ postingDate
});
if (posted.error) {
diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
index eb49823051..babb8733c3 100644
--- a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
@@ -19,7 +19,9 @@ import {
getReceiptLines,
getReceiptRelatedItems,
getReceiptTracking,
- getShelfLifeForItems
+ getRentalReceiptLines,
+ getShelfLifeForItems,
+ type RentalReceiptLine
} from "~/modules/inventory";
import {
ReceiptDocuments,
@@ -109,7 +111,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
"id, purchaseOrderLineId, received, serialNumber, purchaseOrderLine:purchaseOrderLineId(assetId, description, fixedAsset:assetId(name, fixedAssetId, serialNumber))"
)
.eq("receiptId", receiptId)
- .eq("companyId", companyId);
+ .eq("companyId", companyId)
+ .not("purchaseOrderLineId", "is", null);
fixedAssetLines = (faLineRecords.data ?? [])
.filter((row) => {
@@ -131,11 +134,66 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
});
}
+ let rentalLines: RentalReceiptLine[] = [];
+
+ if (receipt.data.sourceDocument === "Rental Agreement") {
+ // Service role: rentalAgreementLine needs sales_view, which an inventory
+ // user may not hold.
+ const rentalLineRecords = await getRentalReceiptLines(
+ serviceRole,
+ receiptId,
+ companyId
+ );
+ if (rentalLineRecords.error) {
+ throw redirect(
+ path.to.receipts,
+ await flash(
+ request,
+ error(rentalLineRecords.error, "Failed to load the rental units")
+ )
+ );
+ }
+
+ rentalLines = (rentalLineRecords.data ?? []).map((row) => {
+ // The read filters out rows with no rental line.
+ const line = row.rentalAgreementLine!;
+ return {
+ id: row.id,
+ rentalAgreementLineId: row.rentalAgreementLineId!,
+ received: row.received,
+ meter: row.meter === null ? null : Number(row.meter),
+ notes: row.notes,
+ takeOutOfService: row.takeOutOfService,
+ outOfServiceReason: row.outOfServiceReason,
+ // A CHECK constraint holds the column to these two values.
+ residualDestination:
+ row.residualDestination as RentalReceiptLine["residualDestination"],
+ lessorClassification: line.lessorClassification ?? null,
+ unitName: line.fixedAsset?.name ?? line.item?.name ?? "Rental unit",
+ thumbnailPath: line.item?.thumbnailPath ?? null,
+ itemType: line.item?.type ?? null,
+ assetReadableId: line.fixedAsset?.fixedAssetId ?? null,
+ serialNumber:
+ line.fixedAsset?.serialNumber ??
+ line.trackedEntity?.readableId ??
+ null,
+ lineStatus: line.status
+ };
+ });
+ // By unit, like ordinary lines by part number, so the list holds still.
+ rentalLines.sort((a, b) =>
+ (a.assetReadableId ?? a.unitName).localeCompare(
+ b.assetReadableId ?? b.unitName
+ )
+ );
+ }
+
return {
receipt: receipt.data,
receiptLines: receiptLines.data ?? [],
receiptInspections: receiptInspections.data ?? [],
fixedAssetLines,
+ rentalLines,
receiptFiles: getReceiptFiles(serviceRole, companyId, receiptLineIds) ?? [],
receiptLineTracking: receiptLineTracking.data ?? [],
batchProperties:
diff --git a/apps/erp/app/routes/x+/receipt+/fixed-asset-lines.update.tsx b/apps/erp/app/routes/x+/receipt+/fixed-asset-lines.update.tsx
index af3ba91147..cc225ea22c 100644
--- a/apps/erp/app/routes/x+/receipt+/fixed-asset-lines.update.tsx
+++ b/apps/erp/app/routes/x+/receipt+/fixed-asset-lines.update.tsx
@@ -4,39 +4,80 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { unchecked } from "@carbon/utils";
+import type { Database } from "@carbon/database";
import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { receiptFixedAssetLineUpdateValidator } from "~/modules/inventory";
+
+type ReceiptFixedAssetLineUpdate =
+ Database["public"]["Tables"]["receiptFixedAssetLine"]["Update"];
export async function action({ request }: ActionFunctionArgs) {
- const { companyId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "inventory"
});
- const formData = await request.formData();
- const id = formData.get("id") as string;
- const field = formData.get("field") as string;
- const value = formData.get("value") as string | null;
-
- if (!id || !field) {
- return { error: { message: "Invalid form data" }, data: null };
+ const parsed = receiptFixedAssetLineUpdateValidator.safeParse(
+ Object.fromEntries(await request.formData())
+ );
+ if (!parsed.success) {
+ return data({ error: parsed.error.issues[0]?.message }, { status: 400 });
}
- if (field !== "received" && field !== "serialNumber") {
- return { error: { message: `Invalid field: ${field}` }, data: null };
+ const { id, ...change } = parsed.data;
+ let updateData: ReceiptFixedAssetLineUpdate;
+ switch (change.field) {
+ case "received":
+ updateData = { received: change.value === "true" };
+ break;
+ case "serialNumber":
+ updateData = { serialNumber: change.value || null };
+ break;
+ case "meter":
+ updateData = {
+ meter: change.value === "" ? null : Number(change.value)
+ };
+ break;
+ case "notes":
+ updateData = { notes: change.value.trim() || null };
+ break;
+ case "outOfService":
+ updateData =
+ change.value.trim() === ""
+ ? { takeOutOfService: false, outOfServiceReason: null }
+ : { takeOutOfService: true, outOfServiceReason: change.value.trim() };
+ break;
+ case "residualDestination":
+ updateData = { residualDestination: change.value || null };
+ break;
}
const serviceRole = getCarbonServiceRole();
- const updateData: Record<string, unknown> = {};
- if (field === "received") {
- updateData.received = value === "true";
- } else if (field === "serialNumber") {
- updateData.serialNumber = value || null;
+ // A posted (or voided) receipt is a record: its lines, the meter included,
+ // no longer change.
+ const line = await serviceRole
+ .from("receiptFixedAssetLine")
+ .select("receipt!receiptFixedAssetLine_receiptId_fkey(status)")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single();
+ if (line.error || !line.data?.receipt) {
+ return data(
+ { error: "The receipt line could not be found" },
+ { status: 404 }
+ );
+ }
+ if (line.data.receipt.status !== "Draft") {
+ return data(
+ { error: "A posted receipt can no longer be changed" },
+ { status: 400 }
+ );
}
const update = await serviceRole
.from("receiptFixedAssetLine")
- .update(unchecked(updateData))
+ .update({ ...updateData, updatedBy: userId })
.eq("id", id)
.eq("companyId", companyId);
diff --git a/apps/erp/app/routes/x+/receipt+/new.tsx b/apps/erp/app/routes/x+/receipt+/new.tsx
index 65ed66908d..7954ee577f 100644
--- a/apps/erp/app/routes/x+/receipt+/new.tsx
+++ b/apps/erp/app/routes/x+/receipt+/new.tsx
@@ -128,6 +128,58 @@ export async function action({ request }: ActionFunctionArgs) {
}
throw redirect(path.to.receiptDetails(warehouseTransferReceipt.data.id));
+ case "Rental Agreement":
+ // One open draft per agreement: Deliver or Return again goes to the
+ // existing draft instead of stacking up duplicates.
+ const existingRentalReceipt = await client
+ .from("receipt")
+ .select("id")
+ .eq("sourceDocument", "Rental Agreement")
+ .eq("sourceDocumentId", sourceDocumentId)
+ .eq("status", "Draft")
+ .eq("companyId", companyId)
+ .order("createdAt", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+ if (existingRentalReceipt.error) {
+ throw redirect(
+ path.to.rentalAgreementDetails(sourceDocumentId),
+ await flash(
+ request,
+ error(
+ existingRentalReceipt.error,
+ "Failed to check for an existing receipt"
+ )
+ )
+ );
+ }
+ if (existingRentalReceipt.data) {
+ throw redirect(path.to.receiptDetails(existingRentalReceipt.data.id));
+ }
+
+ const rentalAgreementReceipt = await serverFns
+ .system({ db: getDatabaseClient(), companyId, userId })
+ .invoke("create", {
+ type: "receiptFromRentalAgreement",
+ rentalAgreementId: sourceDocumentId
+ });
+ if (!rentalAgreementReceipt.data || rentalAgreementReceipt.error) {
+ throw redirect(
+ path.to.rentalAgreementDetails(sourceDocumentId),
+ await flash(
+ request,
+ error(
+ rentalAgreementReceipt.error,
+ getErrorMessage(
+ rentalAgreementReceipt.error,
+ "Failed to create receipt"
+ )
+ )
+ )
+ );
+ }
+
+ throw redirect(path.to.receiptDetails(rentalAgreementReceipt.data.id));
default:
const defaultReceipt = await serverFns
.system({ db: getDatabaseClient(), companyId, userId })
diff --git a/apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.deliver.tsx b/apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.deliver.tsx
index 58fbeaa418..c2481f4cbe 100644
--- a/apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.deliver.tsx
+++ b/apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.deliver.tsx
@@ -2,119 +2,44 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import { assertIsPost, error, notFound, success } from "@carbon/auth";
+import { assertIsPost, error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
-import { datetime, redirect } from "@carbon/utils";
+import { serverFns } from "@carbon/server-functions";
+import { getErrorMessage, redirect } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
-import { getRentalAgreement, getRentalAgreementLine } from "~/modules/sales";
-import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
+import { getDatabaseClient } from "~/services/database.server";
import { path, requestReferrer } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- update: "sales"
+ 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 [agreement, line] = await Promise.all([
- getRentalAgreement(client, id, companyId),
- getRentalAgreementLine(client, lineId, companyId)
- ]);
-
- if (
- agreement.error ||
- agreement.data?.companyId !== companyId ||
- line.error ||
- line.data.rentalAgreementId !== id
- ) {
- throw redirect(
- requestReferrer(request) ?? path.to.rentalAgreementDetails(id),
- await flash(
- request,
- error(null, "This unit does not belong to this rental agreement")
- )
- );
- }
-
- if (agreement.data.status !== "Active" || line.data.status !== "Pending") {
+ 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(
- null,
- "Only a pending unit on an active agreement can be delivered"
+ result.error,
+ getErrorMessage(result.error, "Failed to create the shipment")
)
)
);
}
-
- // A unit out of service stays in the yard until it is returned to service.
- // Read with the service role, scoped to the company and the line's unit:
- // the fleet register needs accounting_view, which a sales user may not
- // hold, and under RLS an unreadable unit looked available. A failed or
- // empty read refuses the delivery.
- if (line.data.fixedAssetId) {
- const asset = await getCarbonServiceRole()
- .from("fleetAssets")
- .select("fleetStatus, outOfServiceReason")
- .eq("id", line.data.fixedAssetId)
- .eq("companyId", companyId)
- .maybeSingle();
- if (asset.error || !asset.data) {
- throw redirect(
- requestReferrer(request) ?? path.to.rentalAgreementDetails(id),
- await flash(request, error(asset.error, "Failed to load the unit"))
- );
- }
- if (asset.data.fleetStatus === "In Maintenance") {
- throw redirect(
- requestReferrer(request) ?? path.to.rentalAgreementDetails(id),
- await flash(
- request,
- error(
- null,
- asset.data.outOfServiceReason
- ? `The unit is out of service: ${asset.data.outOfServiceReason}`
- : "The unit is out of service"
- )
- )
- );
- }
- }
-
- const timeZone = await getCompanyTimeZone(client, companyId);
-
- const update = await client
- .from("rentalAgreementLine")
- .update({
- deliveredAt: datetime.today(timeZone).toString(),
- status: "On Rent",
- updatedBy: userId,
- updatedAt: datetime.timestamp()
- })
- .eq("id", lineId)
- .eq("companyId", companyId)
- .eq("status", "Pending")
- .select("id")
- .single();
-
- if (update.error) {
- throw redirect(
- requestReferrer(request) ?? path.to.rentalAgreementDetails(id),
- await flash(request, error(update.error, "Failed to deliver the unit"))
- );
- }
-
- throw redirect(
- requestReferrer(request) ?? path.to.rentalAgreementDetails(id),
- await flash(request, success("Unit delivered"))
- );
+ throw redirect(path.to.shipmentDetails(result.data.id));
}
diff --git a/apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.release.tsx b/apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.release.tsx
new file mode 100644
index 0000000000..66c6e9ab10
--- /dev/null
+++ b/apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.release.tsx
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { assertIsPost, error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { serverFns } from "@carbon/server-functions";
+import { getErrorMessage, redirect } from "@carbon/utils";
+import type { ActionFunctionArgs } from "react-router";
+
+import { rentalAgreementReleaseValidator } from "~/modules/sales";
+import { getDatabaseClient } from "~/services/database.server";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "sales"
+ });
+
+ const { id, lineId } = params;
+ if (!id) throw notFound("id not found");
+ if (!lineId) throw notFound("lineId not found");
+
+ const formData = await request.formData();
+ const validation = await validator(rentalAgreementReleaseValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ // The line comes from the URL; the server function re-reads it under the
+ // agreement and company, and refuses a unit that is not Pending, one
+ // treated as a sale, or one on an open rental document.
+ const result = await serverFns
+ .system({ db: getDatabaseClient(), companyId, userId })
+ .invoke("post-rental-agreement", {
+ type: "release",
+ rentalAgreementId: id,
+ rentalAgreementLineId: lineId,
+ returnedAt: validation.data.returnedAt
+ });
+
+ if (result.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.rentalAgreementDetails(id),
+ await flash(
+ request,
+ error(
+ result.error,
+ getErrorMessage(result.error, "Failed to release the unit")
+ )
+ )
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.rentalAgreementDetails(id),
+ await flash(request, success("Unit released"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.return.tsx b/apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.return.tsx
index 2037f02926..c406211e3e 100644
--- a/apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.return.tsx
+++ b/apps/erp/app/routes/x+/rental-agreement+/$id.$lineId.return.tsx
@@ -2,102 +2,44 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import { assertIsPost, error, notFound, success } from "@carbon/auth";
+import { assertIsPost, error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { validationError, validator } from "@carbon/form";
import { serverFns } from "@carbon/server-functions";
import { getErrorMessage, redirect } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
-import {
- getRentalAgreementLine,
- rentalAgreementReturnValidator
-} from "~/modules/sales";
import { getDatabaseClient } from "~/services/database.server";
import { path, requestReferrer } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- update: "sales"
+ 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 formData = await request.formData();
- const validation = await validator(rentalAgreementReturnValidator).validate(
- formData
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const {
- meterIn,
- returnNotes,
- takeOutOfService,
- outOfServiceReason,
- residualDestination
- } = validation.data;
-
- // The posted `isSalesType` only drives the form; the line decides. A
- // Sale line's closing net investment must land somewhere.
- const line = await getRentalAgreementLine(client, lineId, companyId);
- if (line.error || line.data.rentalAgreementId !== id) {
- throw redirect(
- requestReferrer(request) ?? path.to.rentalAgreementDetails(id),
- await flash(
- request,
- error(null, "This unit does not belong to this rental agreement")
- )
- );
- }
- const isSalesType = line.data.lessorClassification === "Sale";
- if (isSalesType && !residualDestination) {
- return validationError({
- fieldErrors: {
- residualDestination: "Choose where the returned unit goes"
- }
- });
- }
-
- // The line comes from the URL; the edge function re-reads it under the
- // agreement and company before touching anything.
const result = await serverFns
.system({ db: getDatabaseClient(), companyId, userId })
- .invoke("post-rental-agreement", {
- type: "return",
+ .invoke("create", {
+ type: "receiptFromRentalAgreement",
rentalAgreementId: id,
- rentalAgreementLineId: lineId,
- returnedAt: validation.data.returnedAt,
- meterIn: meterIn ?? null,
- returnNotes: returnNotes ?? null,
- takeOutOfService,
- outOfServiceReason: takeOutOfService
- ? (outOfServiceReason ?? null)
- : null,
- ...(isSalesType ? { residualDestination } : {})
+ rentalAgreementLineId: lineId
});
-
- if (result.error) {
+ if (result.error || !result.data) {
throw redirect(
requestReferrer(request) ?? path.to.rentalAgreementDetails(id),
await flash(
request,
error(
result.error,
- getErrorMessage(result.error, "Failed to return the unit")
+ getErrorMessage(result.error, "Failed to create the receipt")
)
)
);
}
-
- throw redirect(
- requestReferrer(request) ?? path.to.rentalAgreementDetails(id),
- await flash(request, success("Unit returned"))
- );
+ throw redirect(path.to.receiptDetails(result.data.id));
}
diff --git a/apps/erp/app/routes/x+/rental-agreement+/$id.tsx b/apps/erp/app/routes/x+/rental-agreement+/$id.tsx
index 160f087f73..522682f8ae 100644
--- a/apps/erp/app/routes/x+/rental-agreement+/$id.tsx
+++ b/apps/erp/app/routes/x+/rental-agreement+/$id.tsx
@@ -17,6 +17,7 @@ import {
getRentalAgreementCharges,
getRentalAgreementDeposits,
getRentalAgreementLines,
+ getRentalAgreementRelatedDocuments,
getRentalBillingPeriods
} from "~/modules/sales";
import type {
@@ -62,7 +63,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
const customerContactId = rentalAgreement.data.customerContactId;
- const [lines, charges, periods, deposits, rentableAssets, contact] =
+ const [lines, charges, periods, deposits, rentableAssets, contact, related] =
await Promise.all([
getRentalAgreementLines(client, id, companyId),
getRentalAgreementCharges(client, id, companyId),
@@ -79,7 +80,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
.eq("id", customerContactId)
.eq("companyId", companyId)
.maybeSingle()
- : Promise.resolve({ data: null, error: null })
+ : Promise.resolve({ data: null, error: null }),
+ getRentalAgreementRelatedDocuments(client, id, companyId)
]);
// `salesInvoiceLineId` on periods and charges has no foreign key, so the
@@ -165,6 +167,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
charges: charges.data ?? [],
periods: periods.data ?? [],
deposits: deposits.data ?? [],
+ // A failed read leaves the lists empty rather than failing the page.
+ shipments: related.error ? [] : related.data.shipments,
+ receipts: related.error ? [] : related.data.receipts,
rentableAssets: rentableAssets.data ?? [],
invoiceLinks,
contactEmail: contact.data?.contact?.email || null,
@@ -178,8 +183,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
export default function RentalAgreementRoute() {
- const { rentalAgreement, lines, periods, leasePolicy, leaseInputs } =
- useLoaderData<typeof loader>();
+ const {
+ rentalAgreement,
+ lines,
+ periods,
+ leasePolicy,
+ leaseInputs,
+ shipments,
+ receipts
+ } = useLoaderData<typeof loader>();
const { id } = useParams();
const matches = useMatches();
if (!id) throw new Error("Could not find id");
@@ -199,6 +211,8 @@ export default function RentalAgreementRoute() {
periods={periods}
leasePolicy={leasePolicy}
leaseInputs={leaseInputs}
+ shipments={shipments}
+ receipts={receipts}
/>
<div className="flex h-[calc(100dvh-var(--topbar-height)-var(--header-height)-var(--content-inset))] overflow-hidden w-full">
<div className="flex flex-grow overflow-hidden">
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.details.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.details.tsx
index 2c49a5f75b..a3e45cff72 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.details.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.details.tsx
@@ -63,7 +63,26 @@ export async function action({ request }: ActionFunctionArgs) {
currentShipment.data.sourceDocumentId !== d.sourceDocumentId ||
currentShipment.data.locationId !== d.locationId;
- if (shipmentDataHasChanged) {
+ 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."
+ )
+ )
+ );
+ }
+
+ if (shipmentDataHasChanged && !isRental) {
switch (d.sourceDocument) {
case "Sales Order":
const salesOrderShipment = await serverFns
@@ -278,7 +297,8 @@ export default function ShipmentDetailsRoute() {
sourceDocument: (routeData.shipment.sourceDocument ?? "Sales Order") as
| "Sales Order"
| "Purchase Order"
- | "Outbound Transfer",
+ | "Outbound Transfer"
+ | "Rental Agreement",
sourceDocumentId: routeData.shipment.sourceDocumentId ?? undefined,
sourceDocumentReadableId:
routeData.shipment.sourceDocumentReadableId ?? undefined,
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
index d45740c85d..a2cf60ee0c 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
@@ -48,6 +48,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
const formData = await request.formData();
const acknowledged = formData.get("acknowledged") === "true";
+ const postingDateValue = formData.get("postingDate");
+ const postingDate =
+ typeof postingDateValue === "string" && postingDateValue !== ""
+ ? postingDateValue
+ : undefined;
// Storage Rule evaluation across every line on this shipment before posting.
const serviceRole = getCarbonServiceRole();
@@ -373,7 +378,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
.system({ db: getDatabaseClient(), companyId, userId })
.invoke("post-shipment", {
type: "post",
- shipmentId: shipmentId
+ shipmentId,
+ postingDate
});
if (posted.error) {
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx
index fdb4e5064a..dd865a9bd3 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx
@@ -13,10 +13,12 @@ import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import { DocumentPage, DocumentSidebar } from "~/components/DocumentPage";
import {
+ getRentalShipmentLines,
getShipment,
getShipmentLines,
getShipmentRelatedItems,
- getShipmentTracking
+ getShipmentTracking,
+ type RentalShipmentLine
} from "~/modules/inventory";
import {
ShipmentDocuments,
@@ -81,7 +83,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
"id, salesOrderLineId, shipped, serialNumber, salesOrderLine:salesOrderLineId(assetId, description, fixedAsset:assetId(name, fixedAssetId, serialNumber))"
)
.eq("shipmentId", shipmentId)
- .eq("companyId", companyId);
+ .eq("companyId", companyId)
+ .not("salesOrderLineId", "is", null);
fixedAssetLines = (faLineRecords.data ?? [])
.filter((row) => {
@@ -103,10 +106,58 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
});
}
+ let rentalLines: RentalShipmentLine[] = [];
+
+ if (shipment.data.sourceDocument === "Rental Agreement") {
+ // Service role: rentalAgreementLine needs sales_view, which an inventory
+ // user may not hold.
+ const rentalLineRecords = await getRentalShipmentLines(
+ getCarbonServiceRole(),
+ shipmentId,
+ companyId
+ );
+ if (rentalLineRecords.error) {
+ throw redirect(
+ path.to.shipments,
+ await flash(
+ request,
+ error(rentalLineRecords.error, "Failed to load the rental units")
+ )
+ );
+ }
+
+ rentalLines = (rentalLineRecords.data ?? []).map((row) => {
+ // The read filters out rows with no rental line.
+ const line = row.rentalAgreementLine!;
+ return {
+ id: row.id,
+ rentalAgreementLineId: row.rentalAgreementLineId!,
+ shipped: row.shipped,
+ meter: row.meter === null ? null : Number(row.meter),
+ unitName: line.fixedAsset?.name ?? line.item?.name ?? "Rental unit",
+ thumbnailPath: line.item?.thumbnailPath ?? null,
+ itemType: line.item?.type ?? null,
+ assetReadableId: line.fixedAsset?.fixedAssetId ?? null,
+ serialNumber:
+ line.fixedAsset?.serialNumber ??
+ line.trackedEntity?.readableId ??
+ null,
+ lineStatus: line.status
+ };
+ });
+ // By unit, like ordinary lines by part number, so the list holds still.
+ rentalLines.sort((a, b) =>
+ (a.assetReadableId ?? a.unitName).localeCompare(
+ b.assetReadableId ?? b.unitName
+ )
+ );
+ }
+
return {
shipment: shipment.data,
shipmentLines: shipmentLines.data ?? [],
fixedAssetLines,
+ rentalLines,
shipmentLineTracking: shipmentLineTracking.data ?? [],
relatedItems: getShipmentRelatedItems(
client,
diff --git a/apps/erp/app/routes/x+/shipment+/fixed-asset-lines.update.tsx b/apps/erp/app/routes/x+/shipment+/fixed-asset-lines.update.tsx
index 397fcf78de..c5f7c2db00 100644
--- a/apps/erp/app/routes/x+/shipment+/fixed-asset-lines.update.tsx
+++ b/apps/erp/app/routes/x+/shipment+/fixed-asset-lines.update.tsx
@@ -4,39 +4,56 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { unchecked } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { shipmentFixedAssetLineUpdateValidator } from "~/modules/inventory";
export async function action({ request }: ActionFunctionArgs) {
- const { companyId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "inventory"
});
- const formData = await request.formData();
- const id = formData.get("id") as string;
- const field = formData.get("field") as string;
- const value = formData.get("value") as string | null;
-
- if (!id || !field) {
- return { error: { message: "Invalid form data" }, data: null };
+ const parsed = shipmentFixedAssetLineUpdateValidator.safeParse(
+ Object.fromEntries(await request.formData())
+ );
+ if (!parsed.success) {
+ return data({ error: parsed.error.issues[0]?.message }, { status: 400 });
}
- if (field !== "shipped" && field !== "serialNumber") {
- return { error: { message: `Invalid field: ${field}` }, data: null };
- }
+ const { id, ...change } = parsed.data;
+ const updateData =
+ change.field === "shipped"
+ ? { shipped: change.value === "true" }
+ : change.field === "serialNumber"
+ ? { serialNumber: change.value || null }
+ : { meter: change.value === "" ? null : Number(change.value) };
const serviceRole = getCarbonServiceRole();
- const updateData: Record<string, unknown> = {};
- if (field === "shipped") {
- updateData.shipped = value === "true";
- } else if (field === "serialNumber") {
- updateData.serialNumber = value || null;
+ // A posted (or voided) shipment is a record: its lines, the meter included,
+ // no longer change.
+ const line = await serviceRole
+ .from("shipmentFixedAssetLine")
+ .select("shipment!shipmentFixedAssetLine_shipmentId_fkey(status)")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single();
+ if (line.error || !line.data?.shipment) {
+ return data(
+ { error: "The shipment line could not be found" },
+ { status: 404 }
+ );
+ }
+ if (line.data.shipment.status !== "Draft") {
+ return data(
+ { error: "A posted shipment can no longer be changed" },
+ { status: 400 }
+ );
}
const update = await serviceRole
.from("shipmentFixedAssetLine")
- .update(unchecked(updateData))
+ .update({ ...updateData, updatedBy: userId })
.eq("id", id)
.eq("companyId", companyId);
diff --git a/apps/erp/app/routes/x+/shipment+/new.tsx b/apps/erp/app/routes/x+/shipment+/new.tsx
index 969b05214a..1195d9a312 100644
--- a/apps/erp/app/routes/x+/shipment+/new.tsx
+++ b/apps/erp/app/routes/x+/shipment+/new.tsx
@@ -268,6 +268,58 @@ export async function action({ request }: ActionFunctionArgs) {
throw redirect(
path.to.shipmentDetails(warehouseTransferShipment.data.id)
);
+ case "Rental Agreement":
+ // One open draft per agreement: Deliver or Return again goes to the
+ // existing draft instead of stacking up duplicates.
+ const existingRentalShipment = await client
+ .from("shipment")
+ .select("id")
+ .eq("sourceDocument", "Rental Agreement")
+ .eq("sourceDocumentId", sourceDocumentId)
+ .eq("status", "Draft")
+ .eq("companyId", companyId)
+ .order("createdAt", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+ if (existingRentalShipment.error) {
+ throw redirect(
+ path.to.rentalAgreementDetails(sourceDocumentId),
+ await flash(
+ request,
+ error(
+ existingRentalShipment.error,
+ "Failed to check for an existing shipment"
+ )
+ )
+ );
+ }
+ if (existingRentalShipment.data) {
+ throw redirect(path.to.shipmentDetails(existingRentalShipment.data.id));
+ }
+
+ const rentalAgreementShipment = await serverFns
+ .system({ db: getDatabaseClient(), companyId, userId })
+ .invoke("create", {
+ type: "shipmentFromRentalAgreement",
+ rentalAgreementId: sourceDocumentId
+ });
+ if (!rentalAgreementShipment.data || rentalAgreementShipment.error) {
+ throw redirect(
+ path.to.rentalAgreementDetails(sourceDocumentId),
+ await flash(
+ request,
+ error(
+ rentalAgreementShipment.error,
+ getErrorMessage(
+ rentalAgreementShipment.error,
+ "Failed to create shipment"
+ )
+ )
+ )
+ );
+ }
+
+ throw redirect(path.to.shipmentDetails(rentalAgreementShipment.data.id));
default:
const defaultShipment = await serverFns
.system({ db: getDatabaseClient(), companyId, userId })
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 832710cf35..de1c57b445 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -2179,6 +2179,8 @@ export const path = {
generatePath(`${x}/rental-agreement/${id}/${lineId}/classification`),
rentalAgreementLineDeliver: (id: string, lineId: string) =>
generatePath(`${x}/rental-agreement/${id}/${lineId}/deliver`),
+ rentalAgreementLineRelease: (id: string, lineId: string) =>
+ generatePath(`${x}/rental-agreement/${id}/${lineId}/release`),
rentalAgreementLineReturn: (id: string, lineId: string) =>
generatePath(`${x}/rental-agreement/${id}/${lineId}/return`),
rentalAgreementLineSell: (id: string, lineId: string) =>
diff --git a/docs/content/docs/reference/receipts.mdx b/docs/content/docs/reference/receipts.mdx
index 71f315ae7e..4ad6e3fe2c 100644
--- a/docs/content/docs/reference/receipts.mdx
+++ b/docs/content/docs/reference/receipts.mdx
@@ -3,14 +3,14 @@ title: Receipts
description: "Goods coming in: receiving against a purchase order and posting to inventory."
---
-A **receipt** records incoming goods from a <Term id="purchase-order">purchase order</Term> or inbound transfer. <Term id="posting">Posting</Term> the receipt adds the delivery to stock on hand.
+A **receipt** records incoming goods from a <Term id="purchase-order">purchase order</Term>, an inbound transfer, or a [rental agreement](/docs/reference/rental-agreements). <Term id="posting">Posting</Term> the receipt adds the delivery to stock on hand.
Each receipt line references the purchase-order line it fulfills. Posting increases inventory and the order line's received quantity. When accounting is enabled, it debits inventory—or <Term id="wip">work-in-process</Term> for outside processing—and credits a <Term id="gr-ir">goods-received-not-invoiced</Term> accrual that the supplier invoice later clears.
## Fields
<FieldTable>
- <Field name="Source document" type="reference">The purchase order (or transfer) being received.</Field>
+ <Field name="Source document" type="reference">The purchase order, transfer, or rental agreement being received. A rental receipt keeps its agreement: create it from the agreement's **"Return"** button, not by changing the source.</Field>
<Field name="Received quantity" type="number">Units on this receipt, per line.</Field>
<Field name="Conversion factor" type="number">Converts the supplier's purchase unit to the stock unit.</Field>
<Field name="Location" type="reference">Where the goods land.</Field>
@@ -29,6 +29,14 @@ Each receipt line references the purchase-order line it fulfills. Posting increa
Receive an item flagged for inspection and its units land **On Hold**, with an inbound inspection opened at *Pending* — they don't become available stock until the inspection clears.
</Callout>
+## Rental receipts
+
+A receipt from a rental agreement brings fleet units back. It lists every unit on rent, ticked, and every unit not yet delivered, unticked. Each row takes a **"Meter"** reading, **"Notes"**, and a **"Take out of service"** switch with a reason. A unit treated as a sale also needs **"Return To"**: the rental fleet or inventory.
+
+The post dialog asks for **"Returned on"**, which cannot be later than today. Posting ends each ticked unit's rental on that date and records the unit at the receipt's location. The rows are read-only from then on. A unit treated as a rental stays a fixed asset, so it writes no inventory movement and no journal entry. A posted rental receipt cannot be voided.
+
+<Screenshot label="Draft rental receipt listing fleet units with tick boxes, Meter, Notes and Take out of service" caption="A rental receipt: units on rent are ticked, units not yet delivered are not." />
+
## Related
<Cards>
@@ -38,6 +46,9 @@ Receive an item flagged for inspection and its units land **On Hold**, with an i
<Card title="Purchase orders" href="/docs/reference/purchase-orders">
The document a receipt advances.
</Card>
+ <Card title="Rental agreements" href="/docs/reference/rental-agreements">
+ Units returned on a rental receipt.
+ </Card>
</Cards>
<AgentContext>
@@ -54,6 +65,12 @@ A batch-tracked line has no batch number assigned. Fill in the batch number in t
### "Serial numbers are missing"
A serial-tracked line has fewer serial numbers entered than its received quantity. Every received unit needs a serial number before the receipt can post.
+### "A rental return cannot be voided. Correct the unit by hand."
+A posted rental receipt (source Rental Agreement) is never voided: the return re-cut the unit's billing and may have booked a residual return. Fix the agreement line and asset by hand.
+
+### "A posted receipt can no longer be changed"
+A unit row on a rental receipt was edited after the receipt left Draft. Its meter, notes and out-of-service choice are a record once posted; correct the unit on its agreement or asset instead.
+
### "Can only void posted receipts"
Voiding applies only to a receipt at **"Posted"**. A Draft or Pending receipt can be edited or deleted instead — there is nothing to reverse yet.
diff --git a/docs/content/docs/reference/rental-agreements.mdx b/docs/content/docs/reference/rental-agreements.mdx
index 1128c32b85..c0dec8e8e8 100644
--- a/docs/content/docs/reference/rental-agreements.mdx
+++ b/docs/content/docs/reference/rental-agreements.mdx
@@ -48,23 +48,34 @@ Activation then fixes each unit's rate, so a later price change never touches a
An agreement in a foreign currency can be saved as a draft but not activated: rent is accrued and deferred in base-currency amounts.
</Callout>
-**"Close"** needs every unit returned or sold and every billing period and charge invoiced. **"Cancel"** works on a draft, or on an active agreement while nothing is on rent, sold, invoiced, or recognized; it removes the undelivered units so they read Available again. An active agreement with a unit treated as a sale cannot be cancelled at all, because that unit was already derecognized at activation. Both buttons ask you to confirm with **"Close Agreement"** or **"Cancel Agreement"**. **"Delete Agreement"**, in the header menu, is for drafts only.
+**"Close"** needs every unit returned or sold, every billing period and charge invoiced, and no open shipment or receipt of the agreement that still holds a unit.
+
+**"Cancel"** works on a draft, or on an active agreement while nothing is on rent, sold, invoiced, or recognized; it removes the undelivered units so they read Available again. An active agreement with a unit treated as a sale cannot be cancelled at all, because that unit was already derecognized at activation. Both buttons ask you to confirm with **"Close Agreement"** or **"Cancel Agreement"**. **"Delete Agreement"**, in the header menu, is for drafts only.
## Units and the fleet
-The agreement is laid out like a sales order. Its units are listed down the left; select one to open its own page, with its status and its **"Deliver"**, **"Return"** and **"Sell to Customer"** actions, its rates and accounting treatment, and its own charges and billing periods. The agreement's ID in the header opens the agreement as a whole: a summary of its units and their rates with what has been billed, what is unbilled, the monthly rent, the deposit and what falls due next, then how the units will be accounted for, and every charge, billing period and deposit. The terms (customer, dates, billing cycle and timing, payment terms, currency, deposit, tax and the accounting-treatment inputs) are in the **Properties** panel on the right, editable while the agreement is a draft.
+The agreement is laid out like a sales order. Its units are listed down the left; select one to open its own page, with its status, the shipment and receipt that moved it, and its **"Deliver"**, **"Return"**, **"Release unit"** and **"Sell to Customer"** actions, its rates and accounting treatment, and its own charges and billing periods.
+
+The agreement's ID in the header opens the agreement as a whole: a summary of its units, with their rates and the shipment and receipt that moved each one, then what has been billed, what is unbilled, the monthly rent, the deposit and what falls due next, then how the units will be accounted for, and every charge, billing period and deposit.
+
+The terms (customer, dates, billing cycle and timing, payment terms, currency, deposit, tax and the accounting-treatment inputs) are in the **Properties** panel on the right, editable while the agreement is a draft.
-Each unit on the agreement moves through its own status: **"Pending"** until delivered, **"On Rent"** once delivered, then **"Returned"**, or **"Sold"** when the customer buys a unit treated as a sale on its purchase option. The Fleet register reflects the same thing from the asset's side: a unit on a draft or an undelivered line reads **Reserved**, a delivered one reads **<Term>On Rent</Term>**, and a unit can only be on one live agreement at a time.
+Each unit on the agreement moves through its own status: **"Pending"** until delivered, **"On Rent"** once delivered, then **"Returned"**, or **"Sold"** when the customer buys a unit treated as a sale on its purchase option. On an active agreement, a second badge beside the agreement's status sums the units up: **"To Deliver"**, **"Partially Delivered"**, **"On Rent"**, **"Partially Returned"** or **"Returned"**. A sold unit counts as returned. The Fleet register reflects the same thing from the asset's side: a unit on a draft or an undelivered line reads **Reserved**, a delivered one reads **<Term>On Rent</Term>**, and a unit can only be on one live agreement at a time.
- **"Add Unit"**, at the foot of the units list while the agreement is a draft, lists fleet units that are Available right now. Choose its **"Rate Frequency"** (*Daily*, *Weekly* or *Monthly*); its **"Rate"** fills in from the [rates on file](#rates) and can be changed.
-- **"Deliver"** marks a pending unit on an active agreement as delivered today. It is refused while the unit is out of service.
-- **"Return"** records the **"Return Date"**, an optional **"Meter Reading"** and **"Return Notes"**, and re-cuts a rental unit's billing (below). The return date cannot be later than today. Tick **"Take out of service"** with a reason and the unit goes straight to In Maintenance instead of back to Available.
+- **"Deliver"** sends units out on a [shipment](/docs/reference/shipments). On an active agreement, **"Deliver"** in the header opens the agreement's draft shipment, or creates one that lists every pending unit, ticked. Untick the units that stay, enter each unit's **"Meter"** reading, and post. The post dialog asks for **"Delivered on"**: today by default, never later. Posting puts the ticked units on rent and refuses a unit that is out of service.
+- **"Return"** brings units back on a [receipt](/docs/reference/receipts). The receipt lists every unit on rent, ticked, and every unit not yet delivered, unticked. Tick an undelivered unit to end it too: its billing stops at the return date. Each unit takes a **"Meter"** reading and **"Notes"**. Turn on **"Take out of service"** with a reason and the unit goes straight to In Maintenance instead of back to Available.
+- The post dialog of a receipt asks for **"Returned on"**, which cannot be later than today. Posting re-cuts a rental unit's billing (below) and records each returned unit at the receipt's location.
+- On a unit's page, **"Deliver"** and **"Return"** open a document for that one unit, so a counter pickup takes two clicks: the button, then **"Post"**. Once the agreement has a document, the header buttons become **"Shipments"** and **"Receipts"** menus that list the agreement's documents.
+- **"Release unit"** ends a pending unit that never left the yard, with no document. Its **"Release date"** cannot be later than today. Billing stops on that date and the unit reads Available again. It is not offered for a unit treated as a sale, which comes back on a receipt instead.
+
+Delivering and returning needs sales update and inventory create permission, and posting the document needs inventory update permission. A posted shipment can be voided while every unit on it is still on rent and no revenue recognition run holds its accrued rent; the units go back to pending. A posted receipt cannot be voided. Once a shipment or receipt is posted, its units and their meter readings can no longer be edited.
<Callout type="note" title="Billing runs from the agreement start, not from delivery">
A unit's billing periods begin on the agreement's **"Start Date"** whether or not it has been delivered. Delivery decides when rent is *earned* for accounting (accruals start on the delivery date), not when it is *billed*.
</Callout>
-While a unit is reserved or on rent, **"Return to Inventory"** on the asset is refused; return it from the agreement first.
+While a unit is reserved or on rent, **"Return to Inventory"** on the asset is refused; return it on a receipt, or release it, first.
<Screenshot label="Active rental agreement page showing the Units, Charges, Billing Periods and Deposits sections" caption="An active agreement: one unit on rent, its billing periods, and the deposit received." />
@@ -222,7 +233,7 @@ The whole term of a unit treated as a sale is billed from the periods cut at act
### End of the term
- **"Sell to Customer"** appears in the row menu of a unit treated as a sale that is on rent when the agreement has a purchase option. It bills a purchase option charge dated today and drafts its invoice. Before the agreement's end date the action is refused: exercising earlier is an early termination, which is a manual journal. Posting that invoice marks the unit **"Sold"**; voiding it puts the unit back on rent. It needs sales create and update and invoicing create permission, and bills the option only once.
-- **"Return"** on or after the end date asks where the unit goes in **"Return To"**: *Rental fleet, as a new fleet asset* or *Inventory, as finished goods*. The closing net investment moves with it (Dr the Rental Fleet class asset account or inventory, Cr Net Investment in Leases), and the fleet option creates a new asset at that cost depreciating from today. A unit returned to inventory keeps that cost: under FIFO or LIFO costing it is later sold or consumed at the closing net investment, not at the cost of the oldest stock.
+- **Return** the unit on a [receipt](/docs/reference/receipts) on or after the end date. Its receipt line asks where it goes in **"Return To"**: *Rental fleet, as a new fleet asset* or *Inventory, as finished goods*, and the receipt does not post until you choose. The unit goes into stock, or becomes a fleet asset, at the receipt's location. The closing net investment moves with it (Dr the Rental Fleet class asset account or inventory, Cr Net Investment in Leases), and the fleet option creates a new asset at that cost depreciating from today. A unit returned to inventory keeps that cost: under FIFO or LIFO costing it is later sold or consumed at the closing net investment, not at the cost of the oldest stock.
The closing net investment is read off the lease schedule: the closing balance of the last schedule line dated on or before the return. On or after the end date that is the purchase option plus residuals, 5,000.00 in the example. Interest dated on or before the return stays on the schedule and still posts through recognition runs, which brings Net Investment in Leases to zero. Only schedule lines dated after the return are removed.
@@ -309,6 +320,9 @@ A unit at a rate of zero would go on rent and bill nothing. Set its **"Rate"** o
### "Add at least one fleet unit before activating the agreement" / "Every line needs a fleet unit"
The agreement has no units, or a line has no fleet unit.
+### "Shipment … is still open; post or delete it before closing the agreement" / "Receipt … is still open; post or delete it before closing the agreement"
+Close blocker, checked first. A Draft or Pending rental shipment or receipt of the agreement still holds a unit. Post it or delete it, then close.
+
### "Every unit must be returned or sold before the agreement closes" / "Every billing period must be invoiced before the agreement closes" / "Every charge must be invoiced before the agreement closes"
Close blockers. Return units, then use **"Invoice"** (and post any held invoice) for the remaining periods and charges. Note a charge dated in the future is not billed until its date.
@@ -318,8 +332,23 @@ Cancel blockers. Once anything is billed or accrued the agreement is closed inst
### "Only a Draft rental agreement can be deleted. Cancel it instead."
Delete is Draft-only.
-### "Only a pending unit on an active agreement can be delivered" / "Only a unit on rent can be returned"
-Deliver needs an Active agreement and a Pending line; the Return form opens for On Rent lines.
+### Creating a rental shipment or receipt is refused
+Header Deliver / Return or the per-unit shortcut (`create` types `shipmentFromRentalAgreement` / `receiptFromRentalAgreement`). A shipment takes Pending units not on another open rental shipment; a receipt takes On Rent and Pending units. The agreement must be Active. The messages: "No units to deliver", "No units to return", "Only a Pending unit can be delivered", "Only a Pending or On Rent unit can be returned", "The unit is already on an open shipment", "The unit is already on an open receipt", "Rental agreement RA… is STATUS; units are delivered from an Active agreement".
+
+### Posting a rental shipment or receipt is refused
+- "Select at least one unit to deliver" / "Select at least one unit to return": no unit is ticked.
+- "The delivery date cannot be in the future": the Delivered on date is after the company's today.
+- "UNIT is STATUS; only a Pending unit can be delivered" / "UNIT is STATUS; only a Pending or On Rent unit can be returned": posting re-checks every ticked unit, and another document or a release moved it in the meantime. Untick or remove the unit.
+
+### Voiding a rental shipment or receipt is refused
+- "UNIT is STATUS; a rental shipment can be voided only while every unit is On Rent", "A posted revenue recognition run holds accrued rent for UNIT; the shipment cannot be voided", "A draft revenue recognition run holds accrued rent for UNIT; delete the run before voiding the shipment": the void guards of a rental shipment. A void sets the units back to Pending and deletes their unclaimed Planned Accrual rows.
+- "A rental return cannot be voided. Correct the unit by hand.": a posted rental receipt is never voided. The return deleted billing periods and may have booked a residual return.
+
+### Editing a posted rental shipment or receipt is refused
+"A posted shipment can no longer be changed" / "A posted receipt can no longer be changed": a unit row (tick, Meter, Notes, Take out of service, Return To) was edited after its document left Draft. `fixed-asset-lines.update` refuses it, because a posted document is a record.
+
+### Releasing a unit is refused
+Release unit (`post-rental-agreement` `release`, `update: sales`) ends a Pending unit with no document. A unit treated as a sale comes back on a rental receipt with Return To; a unit on an open rental shipment or receipt must leave that document first. The messages: "The release date cannot be in the future", "UNIT is STATUS; only a Pending unit can be released", "UNIT is treated as a sale; return it on a rental receipt instead", "UNIT is on shipment SHP…; remove it there before releasing the unit".
### "Charges can only be added to an open rental agreement" / "The charge is on an invoice. Delete or void the invoice first."
Charges are added on Draft or Active agreements; an invoiced charge cannot be deleted. `upsertRentalAgreementCharge` always writes charge type `Charge` (the form and MCP tool cannot choose a charge type); a Purchase Option charge comes only from Sell to Customer.
@@ -381,14 +410,14 @@ The classification override (`update: accounting`) works only while the agreemen
### "Ending a rental treated as a sale early is a manual journal"
Returned on a return dated before the agreement's End Date, and on Cancel for an agreement with a commenced `Sale` line. Post the termination as a manual journal.
-### "Choose where the returned unit goes: back to the fleet or into inventory" / "Choose where the returned unit goes"
-Returning a unit treated as a sale needs Return To (Fleet or Inventory).
+### "Choose where the returned unit goes: back to the fleet or into inventory" / "Choose Return To for UNIT"
+Returning a unit treated as a sale needs Return To (Fleet or Inventory) on its rental receipt line; the receipt's post dialog blocks without it.
### "A unit returned to inventory cannot be taken out of service; return it to the fleet instead"
Take out of service only applies to a unit returned to the fleet.
### "The return date cannot be in the future"
-A return records what has happened, so `returnedAt` must be on or before the company's today (rental and sale alike). Record the return on the day the unit comes back.
+A return records what has happened, so the receipt's Returned on date (`returnedAt`) must be on or before the company's today (rental and sale alike). Set it to the day the unit came back.
### "A draft revenue recognition run includes this lease's interest; post or delete the run before returning the unit"
A Draft run has claimed Planned Interest rows of this line dated AFTER the return date; the return deletes those, so post or delete the run first. Interest rows dated on or before the return are kept (and keep posting through recognition runs), so a run holding only those does not block.
@@ -427,5 +456,5 @@ Expected: commencement disposes the asset (`disposalMethod` Sale), and `fleetAss
The report subtracts principal for schedule lines dated on or before As of whose Interest row a recognition run has posted (`rentalLeaseScheduleLine.postedAt`), or that earn no interest and so have no Interest row (`earnsInterest`, `lessor-lease` in `@carbon/utils`: zero, or the one-unit drift an Advance lease closing on zero leaves on its last line); the ledger drops by the payment when the rent invoice posts. They agree once both the run and the invoices for the same months are posted. A return does not use this figure: it moves the schedule's balance on the return date, and interest rows dated on or before the return keep posting through recognition runs, which brings 1160 to zero for the line.
## Internals
-Tables: `itemRentalRate` (unique per item and currency), `customerItemRentalRate` (one customer or one customer type, unique per scope, item and currency, optional `validFrom` / `validTo`; a line's starting rate, per frequency, is the customer's, then the customer type's, then the item's, effective on the agreement start date: `defaultRentalRates` in `@carbon/utils` `rental-periods`), `rentalAgreement` (sequence `RA`), `rentalAgreementLine` (one fixed asset each, `quantity` = 1, unique live line per asset; `rateUnit` Day / Week / Month and `rate`, which billing and classification read), `rentalAgreementCharge` (`chargeType`: Charge or Purchase Option), `rentalBillingPeriod` (`dueOn`, `isAdjustment`, `status` Pending / Invoiced; an adjustment is billed by `memoId`, a Draft credit memo with `memo.rentalAgreementId`, never by an invoice line; the memo's negative Deferral rows carry `revenueRecognitionSchedule.memoId`). Views `rentalAgreements` and `fleetAssets` (fleet status precedence: Returned to Stock, Sold, Under Construction, On Rent, In Maintenance, Reserved, Available). Invoice lines: `invoiceLineType` `Rental` with `rentalLineType` (enum `rentalInvoiceLineType`) Rent / Charge / Purchase Option. Payments: `payment.salesOrderId` / `payment.rentalAgreementId` (at most one); deposit journal lines carry the description "Customer Deposit". Server function `post-rental-agreement` (`activate`, `return`, `close`, `cancel`); Inngest `recurring-billing` (cron 05:00 UTC); invoice generation is the `create-rental-invoices` server function. Routes: `/x/sales/rental-agreements`, `/x/rental-agreement/:id`, `/x/reports/rental-utilization`. Accounting treatment: `rentalAgreementLine.lessorClassification` (enum `Rental` / `Sale` / `Financing` = ASC 842 operating / sales-type / direct financing lease; `Financing` exists in the enum but has no input), `classificationInputs` (JSON: inputs, thresholds, tests a–e, pvToFairValuePercent, termToLifePercent, pv, payment, periods, annualRate, timing), `classificationOverride` + `classificationOverrideReason`, `initialNetInvestment`, `sellingProfit`, `commencementJournalId`. Thresholds and default rate: `companySettings.leaseMajorPartThresholdPercent` (75), `leaseSubstantiallyAllThresholdPercent` (90), `leaseDefaultDiscountRate` (6). Math: `lessor-lease` in `@carbon/utils` (`presentValue`, `classifyLessorLease`, `buildLessorSchedule`, `wholeMonthsInTerm`, `leasePaymentTerms`, `classifyRentalLine`), re-exported through `@carbon/utils`; a 28 Days lease is valued over whole 28-day periods at annual × 28/365 per period, a Calendar Month lease over whole months of the term (a Daily or Weekly unit at its average month over a 365-day year; a sale needs a Monthly unit). Schedule table `rentalLeaseScheduleLine` (one row per payment; `journalId` / `postedAt` stamped when a recognition run posts its Interest row; a line that earns no interest gets no Interest row). A residual returned to inventory books a serial cost layer (`costLedger.trackedEntityId`) at the closing net investment, which `calculateCOGS` relieves first when that serial leaves. Commencement and residual-return journals use source type `Lease` (off by default in accounting sync); Interest posts in the `Revenue Recognition` journal. Commencement is fleet-only (activation already requires a fleet unit per line). Activation caps a `Sale` line's billing at the end date (`activationBillingThrough`); the daily pass rolls only `Rental` or unclassified lines; a `Sale` return does not re-cut billing. Purchase Option posting settles the remaining NI (shortfall Dr COGS, excess Cr Lease Revenue) on the option line's journal line reference, so VOID reverses it. Override audit entry: entityType `rentalAgreement`, tableName `rentalAgreementLine`. Routes: `/x/rental-agreement/:id/:lineId/classification`, `/x/rental-agreement/:id/:lineId/sell`, `/x/reports/lease-net-investment`; lease policy on `/x/settings/accounting` (intent `leasePolicy`).
+Tables: `itemRentalRate` (unique per item and currency), `customerItemRentalRate` (one customer or one customer type, unique per scope, item and currency, optional `validFrom` / `validTo`; a line's starting rate, per frequency, is the customer's, then the customer type's, then the item's, effective on the agreement start date: `defaultRentalRates` in `@carbon/utils` `rental-periods`), `rentalAgreement` (sequence `RA`), `rentalAgreementLine` (one fixed asset each, `quantity` = 1, unique live line per asset; `rateUnit` Day / Week / Month and `rate`, which billing and classification read), `rentalAgreementCharge` (`chargeType`: Charge or Purchase Option), `rentalBillingPeriod` (`dueOn`, `isAdjustment`, `status` Pending / Invoiced; an adjustment is billed by `memoId`, a Draft credit memo with `memo.rentalAgreementId`, never by an invoice line; the memo's negative Deferral rows carry `revenueRecognitionSchedule.memoId`). Views `rentalAgreements` and `fleetAssets` (fleet status precedence: Returned to Stock, Sold, Under Construction, On Rent, In Maintenance, Reserved, Available). Invoice lines: `invoiceLineType` `Rental` with `rentalLineType` (enum `rentalInvoiceLineType`) Rent / Charge / Purchase Option. Payments: `payment.salesOrderId` / `payment.rentalAgreementId` (at most one); deposit journal lines carry the description "Customer Deposit". Server function `post-rental-agreement` (`activate`, `release`, `close`, `cancel`); a unit is delivered and returned by `post-shipment` / `post-receipt` with source document `Rental Agreement` (one `shipmentFixedAssetLine` / `receiptFixedAssetLine` per unit, `rentalAgreementLineId`), and posting a receipt sets `fixedAsset.locationId` to the receipt's location; Inngest `recurring-billing` (cron 05:00 UTC); invoice generation is the `create-rental-invoices` server function. Routes: `/x/sales/rental-agreements`, `/x/rental-agreement/:id`, `/x/reports/rental-utilization`. Accounting treatment: `rentalAgreementLine.lessorClassification` (enum `Rental` / `Sale` / `Financing` = ASC 842 operating / sales-type / direct financing lease; `Financing` exists in the enum but has no input), `classificationInputs` (JSON: inputs, thresholds, tests a–e, pvToFairValuePercent, termToLifePercent, pv, payment, periods, annualRate, timing), `classificationOverride` + `classificationOverrideReason`, `initialNetInvestment`, `sellingProfit`, `commencementJournalId`. Thresholds and default rate: `companySettings.leaseMajorPartThresholdPercent` (75), `leaseSubstantiallyAllThresholdPercent` (90), `leaseDefaultDiscountRate` (6). Math: `lessor-lease` in `@carbon/utils` (`presentValue`, `classifyLessorLease`, `buildLessorSchedule`, `wholeMonthsInTerm`, `leasePaymentTerms`, `classifyRentalLine`), re-exported through `@carbon/utils`; a 28 Days lease is valued over whole 28-day periods at annual × 28/365 per period, a Calendar Month lease over whole months of the term (a Daily or Weekly unit at its average month over a 365-day year; a sale needs a Monthly unit). Schedule table `rentalLeaseScheduleLine` (one row per payment; `journalId` / `postedAt` stamped when a recognition run posts its Interest row; a line that earns no interest gets no Interest row). A residual returned to inventory books a serial cost layer (`costLedger.trackedEntityId`) at the closing net investment, which `calculateCOGS` relieves first when that serial leaves. Commencement and residual-return journals use source type `Lease` (off by default in accounting sync); Interest posts in the `Revenue Recognition` journal. Commencement is fleet-only (activation already requires a fleet unit per line). Activation caps a `Sale` line's billing at the end date (`activationBillingThrough`); the daily pass rolls only `Rental` or unclassified lines; a `Sale` return does not re-cut billing. Purchase Option posting settles the remaining NI (shortfall Dr COGS, excess Cr Lease Revenue) on the option line's journal line reference, so VOID reverses it. Override audit entry: entityType `rentalAgreement`, tableName `rentalAgreementLine`. Routes: `/x/rental-agreement/:id/:lineId/classification`, `/x/rental-agreement/:id/:lineId/sell`, `/x/reports/lease-net-investment`; lease policy on `/x/settings/accounting` (intent `leasePolicy`).
</AgentContext>
diff --git a/docs/content/docs/reference/shipments.mdx b/docs/content/docs/reference/shipments.mdx
index 5137493f03..8fabb4e0e0 100644
--- a/docs/content/docs/reference/shipments.mdx
+++ b/docs/content/docs/reference/shipments.mdx
@@ -3,14 +3,14 @@ title: Shipments
description: Goods going out — one posting model serving sales orders, returns, and transfers.
---
-A **shipment** records goods leaving the company against a <Term id="sales-order">sales order</Term>, purchase order, or outbound transfer. Its source type selects the corresponding posting behavior.
+A **shipment** records goods leaving the company against a <Term id="sales-order">sales order</Term>, purchase order, outbound transfer, or [rental agreement](/docs/reference/rental-agreements). Its source type selects the corresponding posting behavior.
Creating a shipment does not affect inventory. **<Term id="posting">Posting</Term>** relieves inventory, updates the source document, and records cost when accounting is enabled. Partial shipments allow one order to be fulfilled in multiple deliveries.
## Fields
<FieldTable>
- <Field name="Source document" type="reference">The order, return, or transfer being shipped.</Field>
+ <Field name="Source document" type="reference">The order, return, transfer, or rental agreement being shipped. A rental shipment keeps its agreement: create it from the agreement's **"Deliver"** button, not by changing the source.</Field>
<Field name="Shipped quantity" type="number">Units on this shipment, per line.</Field>
<Field name="Fulfillment" type="enum">Where a line is sourced: *Inventory* (from stock) or *Job* (from a production job).</Field>
</FieldTable>
@@ -28,6 +28,12 @@ Creating a shipment does not affect inventory. **<Term id="posting">Posting</Ter
Posting decrements inventory and bumps the source line's sent quantity; a sales order line's *sent complete* flag flips only once the cumulative shipped quantity reaches the ordered quantity. Posting a shipment does **not** create the <Term id="invoice">invoice</Term> — billing is a separate step.
</Callout>
+## Rental shipments
+
+A shipment from a rental agreement delivers fleet units. It lists one row per unit with a tick box and a **"Meter"** reading, and its post dialog asks for **"Delivered on"**, which cannot be later than today. Posting puts the ticked units on rent, and the rows, meter readings included, become read-only. A rental unit stays a fixed asset, so posting writes no inventory movement and no journal entry. Its PDF prints as a **Delivery Ticket** that lists each unit with its serial number.
+
+<Screenshot label="Draft rental shipment listing fleet units with tick boxes and Meter fields" caption="A rental shipment from an agreement: untick the units that stay, then post." />
+
## Related
<Cards>
@@ -37,6 +43,9 @@ Posting decrements inventory and bumps the source line's sent quantity; a sales
<Card title="Sales orders" href="/docs/reference/sales-orders">
The document a sales shipment advances.
</Card>
+ <Card title="Rental agreements" href="/docs/reference/rental-agreements">
+ Units delivered on a rental shipment.
+ </Card>
</Cards>
<AgentContext>
@@ -68,6 +77,9 @@ Voiding applies only to a shipment at **"Posted"**. A Draft or Pending shipment
### "Cannot delete a posted shipment"
A posted shipment can't be deleted — void it instead, which writes reversing entries.
+### "A posted shipment can no longer be changed"
+A unit row on a rental shipment was edited after the shipment left Draft. The meter reading out is a record once posted; correct the unit on its agreement or asset instead.
+
### "Failed to post shipment"
Generic wrapper when the posting function fails. Common underlying causes: the [accounting period](/docs/reference/accounting) for the posting date is closed or locked, or default accounts are missing ("Error getting account defaults"). Ask the user for the full error text if available.
</AgentContext>
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 7e82fffea0..5dc5beb9f8 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -52652,10 +52652,16 @@ export type Database = {
createdAt: string
createdBy: string
id: string
- purchaseOrderLineId: string
+ meter: number | null
+ notes: string | null
+ outOfServiceReason: string | null
+ purchaseOrderLineId: string | null
receiptId: string
received: boolean
+ rentalAgreementLineId: string | null
+ residualDestination: string | null
serialNumber: string | null
+ takeOutOfService: boolean
updatedAt: string | null
updatedBy: string | null
}
@@ -52664,10 +52670,16 @@ export type Database = {
createdAt?: string
createdBy: string
id?: string
- purchaseOrderLineId: string
+ meter?: number | null
+ notes?: string | null
+ outOfServiceReason?: string | null
+ purchaseOrderLineId?: string | null
receiptId: string
received?: boolean
+ rentalAgreementLineId?: string | null
+ residualDestination?: string | null
serialNumber?: string | null
+ takeOutOfService?: boolean
updatedAt?: string | null
updatedBy?: string | null
}
@@ -52676,10 +52688,16 @@ export type Database = {
createdAt?: string
createdBy?: string
id?: string
- purchaseOrderLineId?: string
+ meter?: number | null
+ notes?: string | null
+ outOfServiceReason?: string | null
+ purchaseOrderLineId?: string | null
receiptId?: string
received?: boolean
+ rentalAgreementLineId?: string | null
+ residualDestination?: string | null
serialNumber?: string | null
+ takeOutOfService?: boolean
updatedAt?: string | null
updatedBy?: string | null
}
@@ -52781,6 +52799,13 @@ export type Database = {
isOneToOne: false
referencedRelation: "receipts"
referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "receiptFixedAssetLine_rentalAgreementLineId_fkey"
+ columns: ["rentalAgreementLineId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "rentalAgreementLine"
+ referencedColumns: ["id", "companyId"]
}
]
}
@@ -60915,7 +60940,9 @@ export type Database = {
createdAt: string
createdBy: string
id: string
- salesOrderLineId: string
+ meter: number | null
+ rentalAgreementLineId: string | null
+ salesOrderLineId: string | null
serialNumber: string | null
shipmentId: string
shipped: boolean
@@ -60927,7 +60954,9 @@ export type Database = {
createdAt?: string
createdBy: string
id?: string
- salesOrderLineId: string
+ meter?: number | null
+ rentalAgreementLineId?: string | null
+ salesOrderLineId?: string | null
serialNumber?: string | null
shipmentId: string
shipped?: boolean
@@ -60939,7 +60968,9 @@ export type Database = {
createdAt?: string
createdBy?: string
id?: string
- salesOrderLineId?: string
+ meter?: number | null
+ rentalAgreementLineId?: string | null
+ salesOrderLineId?: string | null
serialNumber?: string | null
shipmentId?: string
shipped?: boolean
@@ -61010,6 +61041,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "shipmentFixedAssetLine_rentalAgreementLineId_fkey"
+ columns: ["rentalAgreementLineId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "rentalAgreementLine"
+ referencedColumns: ["id", "companyId"]
+ },
{
foreignKeyName: "shipmentFixedAssetLine_salesOrderLineId_fkey"
columns: ["salesOrderLineId"]
@@ -92856,6 +92894,7 @@ export type Database = {
| "Outbound Transfer"
| "Manufacturing Consumption"
| "Manufacturing Output"
+ | "Rental Agreement"
receiptStatus: "Draft" | "Pending" | "Posted" | "Voided"
reimbursementStatus: "Draft" | "Posted" | "Voided"
rentalAgreementLineStatus: "Pending" | "On Rent" | "Returned" | "Sold"
@@ -92944,6 +92983,7 @@ export type Database = {
| "Purchase Return Order"
| "Inbound Transfer"
| "Outbound Transfer"
+ | "Rental Agreement"
shipmentStatus: "Draft" | "Pending" | "Posted" | "Voided"
shippingCarrier: "UPS" | "FedEx" | "USPS" | "DHL" | "Other"
sourcingType: "Specified" | "Drop Ship" | "Ship from Inventory"
@@ -94389,6 +94429,7 @@ export const Constants = {
"Outbound Transfer",
"Manufacturing Consumption",
"Manufacturing Output",
+ "Rental Agreement",
],
receiptStatus: ["Draft", "Pending", "Posted", "Voided"],
reimbursementStatus: ["Draft", "Posted", "Voided"],
@@ -94484,6 +94525,7 @@ export const Constants = {
"Purchase Return Order",
"Inbound Transfer",
"Outbound Transfer",
+ "Rental Agreement",
],
shipmentStatus: ["Draft", "Pending", "Posted", "Voided"],
shippingCarrier: ["UPS", "FedEx", "USPS", "DHL", "Other"],
diff --git a/packages/database/supabase/migrations/20261008155050_rental-documents-enums.sql b/packages/database/supabase/migrations/20261008155050_rental-documents-enums.sql
new file mode 100644
index 0000000000..be11633051
--- /dev/null
+++ b/packages/database/supabase/migrations/20261008155050_rental-documents-enums.sql
@@ -0,0 +1,4 @@
+-- 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';
diff --git a/packages/database/supabase/migrations/20261008155056_rental-documents.sql b/packages/database/supabase/migrations/20261008155056_rental-documents.sql
new file mode 100644
index 0000000000..46de979294
--- /dev/null
+++ b/packages/database/supabase/migrations/20261008155056_rental-documents.sql
@@ -0,0 +1,52 @@
+-- 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';
diff --git a/packages/documents/src/pdf/PackingSlipPDF.tsx b/packages/documents/src/pdf/PackingSlipPDF.tsx
index 9118c71502..379aa2b941 100644
--- a/packages/documents/src/pdf/PackingSlipPDF.tsx
+++ b/packages/documents/src/pdf/PackingSlipPDF.tsx
@@ -13,7 +13,10 @@ import {
} from "../template";
import type { PDF } from "../types";
import { resolveRegistrationLine } from "../utils/shared";
-import type { PackingSlipData } from "./blocks/packingSlip";
+import type {
+ PackingSlipData,
+ PackingSlipRentalUnit
+} from "./blocks/packingSlip";
import {
buildPackingSlipVars,
packingSlipBlockRegistry
@@ -34,6 +37,7 @@ interface PackingSlipProps extends PDF {
shippingMethod: { id: string; name: string };
terms: JSONContent;
trackedEntities: Database["public"]["Tables"]["trackedEntity"]["Row"][];
+ rentalUnits?: PackingSlipRentalUnit[];
thumbnails?: Record<string, string | null>;
template?: DocumentTemplate | null;
sections?: Record<string, ResolvedSection>;
@@ -55,6 +59,7 @@ const PackingSlipPDF = ({
title = "Packing Slip",
locale,
trackedEntities,
+ rentalUnits,
thumbnails,
template,
sections = {}
@@ -83,6 +88,7 @@ const PackingSlipPDF = ({
});
const data: PackingSlipData = {
+ title,
company,
locale,
customer,
@@ -96,6 +102,7 @@ const PackingSlipPDF = ({
shippingMethod,
terms,
trackedEntities,
+ rentalUnits,
thumbnails,
theme,
sections,
diff --git a/packages/documents/src/pdf/blocks/packingSlip/HeaderBlock.tsx b/packages/documents/src/pdf/blocks/packingSlip/HeaderBlock.tsx
index 258bd6899e..0fcb2e0f89 100644
--- a/packages/documents/src/pdf/blocks/packingSlip/HeaderBlock.tsx
+++ b/packages/documents/src/pdf/blocks/packingSlip/HeaderBlock.tsx
@@ -9,7 +9,7 @@ export function HeaderBlock({ data }: { data: PackingSlipData }) {
return (
<Header
company={data.company}
- title="Packing Slip"
+ title={data.title}
documentId={data.shipment?.shipmentId}
date={data.shipment?.postingDate}
locale={data.locale}
diff --git a/packages/documents/src/pdf/blocks/packingSlip/LineItemsBlock.tsx b/packages/documents/src/pdf/blocks/packingSlip/LineItemsBlock.tsx
index 998276997e..0aa49bd5e7 100644
--- a/packages/documents/src/pdf/blocks/packingSlip/LineItemsBlock.tsx
+++ b/packages/documents/src/pdf/blocks/packingSlip/LineItemsBlock.tsx
@@ -43,6 +43,58 @@ export function LineItemsBlock({
const hasTrackedEntities = trackedEntities.length > 0;
let rowIndex = 0;
+ // A rental shipment lists its units instead of shipment lines: one unit per
+ // row, with its serial number.
+ if (data.rentalUnits && data.rentalUnits.length > 0) {
+ return (
+ <View style={tw("mb-4")}>
+ <View
+ style={[
+ tw("flex flex-row py-2 px-3 text-[9px] font-bold"),
+ { backgroundColor: theme.accent, color: theme.accentForeground }
+ ]}
+ >
+ <Text style={tw("w-6/12 text-left")}>Description</Text>
+ <Text style={tw("w-2/12 text-right")}>Qty</Text>
+ <Text style={tw("w-4/12 text-right")}>Serial</Text>
+ </View>
+ {data.rentalUnits.map((unit, index) => {
+ const rowBg =
+ !opts.zebra || index % 2 === 0 ? "bg-white" : "bg-gray-50";
+ return (
+ <View
+ key={unit.id}
+ style={tw(
+ `flex flex-row py-2 px-3 border-b border-gray-200 text-[10px] ${rowBg}`
+ )}
+ wrap={false}
+ >
+ <View style={tw("w-6/12 pr-2")}>
+ <Text style={{ ...tw("text-gray-800"), ...overflow }}>
+ {unit.name}
+ </Text>
+ {unit.assetReadableId ? (
+ <Text
+ style={{
+ ...tw("text-[8px] text-gray-400 mt-0.5"),
+ ...overflow
+ }}
+ >
+ {unit.assetReadableId}
+ </Text>
+ ) : null}
+ </View>
+ <Text style={tw("w-2/12 text-right text-gray-600")}>1</Text>
+ <Text style={tw("w-4/12 text-right text-gray-600")}>
+ {unit.serialNumber ?? ""}
+ </Text>
+ </View>
+ );
+ })}
+ </View>
+ );
+ }
+
return (
<View style={tw("mb-4")}>
<View
diff --git a/packages/documents/src/pdf/blocks/packingSlip/index.ts b/packages/documents/src/pdf/blocks/packingSlip/index.ts
index 2f6accef2f..a47b35874b 100644
--- a/packages/documents/src/pdf/blocks/packingSlip/index.ts
+++ b/packages/documents/src/pdf/blocks/packingSlip/index.ts
@@ -3,5 +3,9 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
export { packingSlipBlockRegistry } from "./registry";
-export type { BlockRenderer, PackingSlipData } from "./types";
+export type {
+ BlockRenderer,
+ PackingSlipData,
+ PackingSlipRentalUnit
+} from "./types";
export { buildPackingSlipVars } from "./vars";
diff --git a/packages/documents/src/pdf/blocks/packingSlip/types.ts b/packages/documents/src/pdf/blocks/packingSlip/types.ts
index d00765cb27..a6fa95a7ac 100644
--- a/packages/documents/src/pdf/blocks/packingSlip/types.ts
+++ b/packages/documents/src/pdf/blocks/packingSlip/types.ts
@@ -12,8 +12,18 @@ import type {
} from "../../../template";
import type { Company } from "../../../types";
+/** One rental unit on a Delivery Ticket. */
+export type PackingSlipRentalUnit = {
+ id: string;
+ name: string;
+ assetReadableId: string | null;
+ serialNumber: string | null;
+};
+
/** Everything a Packing Slip block renderer might need. */
export interface PackingSlipData {
+ /** "Packing Slip", or "Delivery Ticket" for a rental shipment. */
+ title: string;
company: Company;
locale: string;
customer:
@@ -29,6 +39,8 @@ export interface PackingSlipData {
shippingMethod: { id: string; name: string };
terms: JSONContent;
trackedEntities: Database["public"]["Tables"]["trackedEntity"]["Row"][];
+ /** A rental shipment's units; when present they replace the shipment lines. */
+ rentalUnits?: PackingSlipRentalUnit[];
thumbnails?: Record<string, string | null>;
theme: DocumentTheme;
sections: Record<string, ResolvedSection>;
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 325ac297cf..28e29eb366 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -4430,6 +4430,9 @@ msgstr "Avatar auswählen"
msgid "Choose how to add lines to this return."
msgstr "Wählen Sie, wie Sie Positionen zu dieser Rückgabe hinzufügen möchten."
+msgid "Choose Return To for {unitName}"
+msgstr "Wählen Sie Rückgabeziel für {unitName}"
+
msgid "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
msgstr "Wählen Sie die Flotteneinheiten, die diese Vereinbarung mietet. Jede beginnt mit ihrem Satz in der Datei für die Häufigkeit; ändern Sie ihn im Raster."
@@ -6980,12 +6983,12 @@ msgstr "Workflow löschen"
msgid "Deliver"
msgstr "Liefern"
-msgid "Deliver {label}"
-msgstr "{label} liefern"
-
msgid "Delivered"
msgstr "Geliefert"
+msgid "Delivered on"
+msgstr "Geliefert am"
+
msgid "Delivery Date"
msgstr "Liefertermin"
@@ -8313,6 +8316,9 @@ msgstr "Geben Sie eine Losnummer ein, bevor Sie das Verfallsdatum festlegen"
msgid "Enter a quantity between 1 and {0}."
msgstr "Geben Sie eine Menge zwischen 1 und {0} ein."
+msgid "Enter a reason to take the unit out of service"
+msgstr "Geben Sie einen Grund an, um die Einheit außer Betrieb zu nehmen"
+
msgid "Enter an item and quantity yourself."
msgstr "Geben Sie einen Artikel und eine Menge selbst ein."
@@ -12062,9 +12068,6 @@ msgstr "Umfang als vereinbart markieren"
msgid "Mark Short"
msgstr "Als kurz markieren"
-msgid "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-msgstr "Markieren Sie die Einheit heute als an den Kunden geliefert. Sie wird heute vermietet; die Abrechnung richtet sich nach dem Startdatum und dem Zyklus des Vertrags."
-
msgid "Mark to delete"
msgstr "Zum Löschen markieren"
@@ -12312,7 +12315,7 @@ msgstr "Nachricht"
msgid "Metadata"
msgstr "Metadaten"
-msgid "Meter Reading"
+msgid "Meter"
msgstr "Zählerstand"
msgid "Method"
@@ -13831,6 +13834,9 @@ msgstr "Nicht konfiguriert"
msgid "Not Configured"
msgstr "Nicht konfiguriert"
+msgid "Not delivered"
+msgstr "Nicht geliefert"
+
msgid "Not enough jobs to cover quantity"
msgstr "Nicht genug Fertigungsaufträge zur Abdeckung der Menge"
@@ -14811,6 +14817,12 @@ msgstr "Teil-Ablösung"
msgid "Partial"
msgstr "Teilweise"
+msgid "Partially Delivered"
+msgstr "Teilweise geliefert"
+
+msgid "Partially Returned"
+msgstr "Teilweise zurückgegeben"
+
msgid "Partly Recognized"
msgstr "Teilweise erfasst"
@@ -16726,6 +16738,9 @@ msgstr "Relative Zeitleiste · Daten müssen noch bestätigt werden"
msgid "Release"
msgstr "Freigeben"
+msgid "Release {unitLabel}"
+msgstr "Freigeben {unitLabel}"
+
msgid "Release Batch"
msgstr "Los freigeben"
@@ -16743,6 +16758,9 @@ msgstr "Freigabenkontrolle"
msgid "Release Control"
msgstr "Freigabenkontrolle"
+msgid "Release date"
+msgstr "Freigabedatum"
+
msgid "Release Job"
msgstr "Auftrag freigeben"
@@ -16755,6 +16773,9 @@ msgstr "Fertigungsaufträge freigeben"
msgid "Release purchase order {target} by {date}"
msgstr "Bestellung {target} bis {date} freigeben"
+msgid "Release unit"
+msgstr "Einheit freigeben"
+
msgid "Released"
msgstr "Freigegeben"
@@ -16957,6 +16978,9 @@ msgstr "Leihsätze"
msgid "Rental Site"
msgstr "Vermietungsstandort"
+msgid "Rental Units"
+msgstr "Mieteinheiten"
+
msgid "Rental Utilization"
msgstr "Leihauslastung"
@@ -17320,12 +17344,6 @@ msgstr "Zurücksetzen erneut versuchen"
msgid "Return"
msgstr "Rückgabe"
-msgid "Return {unitLabel}"
-msgstr "Rückgabe {unitLabel}"
-
-msgid "Return Date"
-msgstr "Rückgabedatum"
-
msgid "Return Home"
msgstr "Zur Startseite zurück"
@@ -17335,9 +17353,6 @@ msgstr "Rückgabe-ID"
msgid "Return Location"
msgstr "Rückgabeort"
-msgid "Return Notes"
-msgstr "Rückgabenotizen"
-
msgid "Return Number"
msgstr "Rückgabenummer"
@@ -17365,9 +17380,6 @@ msgstr "Zurück in Bestände"
msgid "Return to Service"
msgstr "Wieder in Betrieb nehmen"
-msgid "Return Unit"
-msgstr "Rückgabeeinheit"
-
msgid "returnable"
msgstr "rückgabefähig"
@@ -17380,6 +17392,9 @@ msgstr "Zurückgegebene Charge"
msgid "Returned goods re-enter inventory at zero value"
msgstr "Zurückgegebene Waren treten mit Nullwert wieder in den Bestand"
+msgid "Returned on"
+msgstr "Zurückgegeben am"
+
msgid "Returned serial numbers"
msgstr "Zurückgegebene Seriennummern"
@@ -20637,9 +20652,6 @@ msgstr "Das Aufwandskonto, auf das diese indirekte Ausgabenzeile gebucht wird; e
msgid "The file you uploaded and the mappings you've made will be lost."
msgstr "Die hochgeladene Datei und die vorgenommenen Zuordnungen gehen verloren."
-msgid "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-msgstr "Die letzte Abrechnungsperiode wird auf das Rückgabedatum angepasst. Ein bereits im Voraus abgerechneter Zeitraum erhält eine Korrektur für die ungenutzten Tage."
-
msgid "the first 3 to 4 weeks"
msgstr "die ersten 3 bis 4 Wochen"
@@ -21234,16 +21246,9 @@ msgstr "Die Einheit, in der eine Arbeitsplanzeit ausgedrückt wird, z. B. Stunde
msgid "The unit and its rates are fixed once the agreement is activated."
msgstr "Die Einheit und ihre Sätze werden festgelegt, sobald die Vereinbarung aktiviert ist."
-#. placeholder {0}: formatDate(endDate)
-msgid "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-msgstr "Die Einheit kann am oder nach dem Enddatum {0} zurückgegeben werden. Eine frühzeitig als Verkauf behandelte Miete wird manuell gebucht."
-
msgid "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
msgstr "Die Einheit wird zum Restbuchwert wieder in den Bestand aufgenommen und der Vermögenswert wird ohne Gewinn oder Verlust abgeschlossen."
-msgid "The unit goes to maintenance instead of back to available."
-msgstr "Die Einheit geht zur Instandhaltung statt in den verfügbaren Bestand zurück."
-
msgid "The unit has no other use to you once the term ends."
msgstr "Die Einheit hat für Sie keine weitere Verwendung, wenn die Vertragslaufzeit endet."
@@ -21253,6 +21258,9 @@ msgstr "Die Einheit wird aus der Verfügbarkeit entfernt, bis sie wieder in Betr
msgid "The unit leaves stock and becomes an asset at the cost inventory carries it at."
msgstr "Die Einheit verlässt den Bestand und wird zu einem Anlagevermögen mit den Kosten, zu denen sie im Bestand erfasst ist."
+msgid "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+msgstr "Die Einheit hat das Gelände nie verlassen. Die Abrechnung endet am Freigabedatum, und die Einheit ist wieder frei."
+
msgid "The unit price of the item at the time of the purchase"
msgstr "Der Einzelpreis des Artikels zum Zeitpunkt des Kaufs"
@@ -21577,9 +21585,6 @@ msgstr "Dieses Quartal"
msgid "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
msgstr "Dies entfernt ihre Authentifizierungs-App, daher benötigt ihre nächste Anmeldung nur einen Magic Link. Verwenden Sie dies, wenn sie den Zugriff auf ihre Authentifizierungs-App verloren haben. Dies wirkt sich auf ihre Anmeldung bei jedem Unternehmen aus, zu dem sie gehören."
-msgid "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-msgstr "Diese Miete wird als Verkauf behandelt. Die Nettoinvestition am Ende kommt mit der Einheit zurück auf die Bilanz, und die ungebuchte Zinsplanung wird entfernt."
-
msgid "This resets {resets} edited invoices from {effectiveDate}"
msgstr "Dies setzt {resets} bearbeitete Rechnungen ab {effectiveDate} zurück"
@@ -21849,6 +21854,9 @@ msgstr "Stichtag"
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Um zu deaktivieren, verwenden Sie das Zeilenmenü und wählen Sie Konto deaktivieren."
+msgid "To Deliver"
+msgstr "Zu liefern"
+
msgid "To Location"
msgstr "Zielort"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 0c9441be8f..ae0007564e 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -4430,6 +4430,9 @@ msgstr "Choose avatar"
msgid "Choose how to add lines to this return."
msgstr "Choose how to add lines to this return."
+msgid "Choose Return To for {unitName}"
+msgstr "Choose Return To for {unitName}"
+
msgid "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
msgstr "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
@@ -6980,12 +6983,12 @@ msgstr "Delete Workflow"
msgid "Deliver"
msgstr "Deliver"
-msgid "Deliver {label}"
-msgstr "Deliver {label}"
-
msgid "Delivered"
msgstr "Delivered"
+msgid "Delivered on"
+msgstr "Delivered on"
+
msgid "Delivery Date"
msgstr "Delivery Date"
@@ -8313,6 +8316,9 @@ msgstr "Enter a batch number before setting the expiration date"
msgid "Enter a quantity between 1 and {0}."
msgstr "Enter a quantity between 1 and {0}."
+msgid "Enter a reason to take the unit out of service"
+msgstr "Enter a reason to take the unit out of service"
+
msgid "Enter an item and quantity yourself."
msgstr "Enter an item and quantity yourself."
@@ -12062,9 +12068,6 @@ msgstr "Mark scope as agreed"
msgid "Mark Short"
msgstr "Mark Short"
-msgid "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-msgstr "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-
msgid "Mark to delete"
msgstr "Mark to delete"
@@ -12312,8 +12315,8 @@ msgstr "Message"
msgid "Metadata"
msgstr "Metadata"
-msgid "Meter Reading"
-msgstr "Meter Reading"
+msgid "Meter"
+msgstr "Meter"
msgid "Method"
msgstr "Method"
@@ -13831,6 +13834,9 @@ msgstr "Not configured"
msgid "Not Configured"
msgstr "Not Configured"
+msgid "Not delivered"
+msgstr "Not delivered"
+
msgid "Not enough jobs to cover quantity"
msgstr "Not enough jobs to cover quantity"
@@ -14811,6 +14817,12 @@ msgstr "Part Supersession"
msgid "Partial"
msgstr "Partial"
+msgid "Partially Delivered"
+msgstr "Partially Delivered"
+
+msgid "Partially Returned"
+msgstr "Partially Returned"
+
msgid "Partly Recognized"
msgstr "Partly Recognized"
@@ -16726,6 +16738,9 @@ msgstr "Relative timeline · dates to be confirmed"
msgid "Release"
msgstr "Release"
+msgid "Release {unitLabel}"
+msgstr "Release {unitLabel}"
+
msgid "Release Batch"
msgstr "Release Batch"
@@ -16743,6 +16758,9 @@ msgstr "Release control"
msgid "Release Control"
msgstr "Release Control"
+msgid "Release date"
+msgstr "Release date"
+
msgid "Release Job"
msgstr "Release Job"
@@ -16755,6 +16773,9 @@ msgstr "Release Jobs"
msgid "Release purchase order {target} by {date}"
msgstr "Release purchase order {target} by {date}"
+msgid "Release unit"
+msgstr "Release unit"
+
msgid "Released"
msgstr "Released"
@@ -16957,6 +16978,9 @@ msgstr "Rental Rates"
msgid "Rental Site"
msgstr "Rental Site"
+msgid "Rental Units"
+msgstr "Rental Units"
+
msgid "Rental Utilization"
msgstr "Rental Utilization"
@@ -17320,12 +17344,6 @@ msgstr "Retry revert"
msgid "Return"
msgstr "Return"
-msgid "Return {unitLabel}"
-msgstr "Return {unitLabel}"
-
-msgid "Return Date"
-msgstr "Return Date"
-
msgid "Return Home"
msgstr "Return Home"
@@ -17335,9 +17353,6 @@ msgstr "Return ID"
msgid "Return Location"
msgstr "Return Location"
-msgid "Return Notes"
-msgstr "Return Notes"
-
msgid "Return Number"
msgstr "Return Number"
@@ -17365,9 +17380,6 @@ msgstr "Return to Inventory"
msgid "Return to Service"
msgstr "Return to Service"
-msgid "Return Unit"
-msgstr "Return Unit"
-
msgid "returnable"
msgstr "returnable"
@@ -17380,6 +17392,9 @@ msgstr "Returned batch"
msgid "Returned goods re-enter inventory at zero value"
msgstr "Returned goods re-enter inventory at zero value"
+msgid "Returned on"
+msgstr "Returned on"
+
msgid "Returned serial numbers"
msgstr "Returned serial numbers"
@@ -20637,9 +20652,6 @@ msgstr "The expense account this indirect-spend line posts to; required because
msgid "The file you uploaded and the mappings you've made will be lost."
msgstr "The file you uploaded and the mappings you've made will be lost."
-msgid "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-msgstr "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-
msgid "the first 3 to 4 weeks"
msgstr "the first 3 to 4 weeks"
@@ -21234,16 +21246,9 @@ msgstr "The unit a routing time is expressed in, such as Hours/Piece or Total Ho
msgid "The unit and its rates are fixed once the agreement is activated."
msgstr "The unit and its rates are fixed once the agreement is activated."
-#. placeholder {0}: formatDate(endDate)
-msgid "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-msgstr "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-
msgid "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
msgstr "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
-msgid "The unit goes to maintenance instead of back to available."
-msgstr "The unit goes to maintenance instead of back to available."
-
msgid "The unit has no other use to you once the term ends."
msgstr "The unit has no other use to you once the term ends."
@@ -21253,6 +21258,9 @@ msgstr "The unit is removed from availability until it is returned to service. D
msgid "The unit leaves stock and becomes an asset at the cost inventory carries it at."
msgstr "The unit leaves stock and becomes an asset at the cost inventory carries it at."
+msgid "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+msgstr "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+
msgid "The unit price of the item at the time of the purchase"
msgstr "The unit price of the item at the time of the purchase"
@@ -21577,9 +21585,6 @@ msgstr "This Quarter"
msgid "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
msgstr "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
-msgid "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-msgstr "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-
msgid "This resets {resets} edited invoices from {effectiveDate}"
msgstr "This resets {resets} edited invoices from {effectiveDate}"
@@ -21849,6 +21854,9 @@ msgstr "To Date"
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "To deactivate, use the row menu and choose Deactivate Account."
+msgid "To Deliver"
+msgstr "To Deliver"
+
msgid "To Location"
msgstr "To Location"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index f74e413cb4..e1405fe468 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -4430,6 +4430,9 @@ msgstr "Elegir avatar"
msgid "Choose how to add lines to this return."
msgstr "Elija cómo agregar líneas a esta devolución."
+msgid "Choose Return To for {unitName}"
+msgstr "Elegir devolución a para {unitName}"
+
msgid "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
msgstr "Elige las unidades de flota que este acuerdo renta. Cada una comienza a su tarifa archivada para la frecuencia; cámbiala en la cuadrícula."
@@ -6980,12 +6983,12 @@ msgstr "Eliminar flujo de trabajo"
msgid "Deliver"
msgstr "Entregar"
-msgid "Deliver {label}"
-msgstr "Entregar {label}"
-
msgid "Delivered"
msgstr "Entregado"
+msgid "Delivered on"
+msgstr "Entregado el"
+
msgid "Delivery Date"
msgstr "Fecha de Entrega"
@@ -8313,6 +8316,9 @@ msgstr "Ingrese un número de lote antes de establecer la fecha de caducidad"
msgid "Enter a quantity between 1 and {0}."
msgstr "Ingrese una cantidad entre 1 y {0}."
+msgid "Enter a reason to take the unit out of service"
+msgstr "Ingrese una razón para retirar la unidad del servicio"
+
msgid "Enter an item and quantity yourself."
msgstr "Ingrese un artículo y cantidad usted mismo."
@@ -12062,9 +12068,6 @@ msgstr "Marcar alcance como acordado"
msgid "Mark Short"
msgstr "Marcar como faltante"
-msgid "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-msgstr "Marca la unidad como entregada al cliente hoy. Entra en alquiler hoy; la facturación sigue la fecha de inicio del acuerdo y el ciclo."
-
msgid "Mark to delete"
msgstr "Marcar para eliminar"
@@ -12312,8 +12315,8 @@ msgstr "Mensaje"
msgid "Metadata"
msgstr "Metadatos"
-msgid "Meter Reading"
-msgstr "Lectura del medidor"
+msgid "Meter"
+msgstr "Contador"
msgid "Method"
msgstr "Método"
@@ -13831,6 +13834,9 @@ msgstr "No configurado"
msgid "Not Configured"
msgstr "No configurado"
+msgid "Not delivered"
+msgstr "No entregado"
+
msgid "Not enough jobs to cover quantity"
msgstr "No hay suficientes órdenes de trabajo para cubrir la cantidad"
@@ -14811,6 +14817,12 @@ msgstr "Reemplazo de pieza"
msgid "Partial"
msgstr "Parcial"
+msgid "Partially Delivered"
+msgstr "Parcialmente Entregado"
+
+msgid "Partially Returned"
+msgstr "Parcialmente Devuelto"
+
msgid "Partly Recognized"
msgstr "Parcialmente reconocido"
@@ -16726,6 +16738,9 @@ msgstr "Cronograma relativo · fechas por confirmar"
msgid "Release"
msgstr "Liberar"
+msgid "Release {unitLabel}"
+msgstr "Liberar {unitLabel}"
+
msgid "Release Batch"
msgstr "Liberar lote de producción"
@@ -16743,6 +16758,9 @@ msgstr "Control de liberación"
msgid "Release Control"
msgstr "Control de liberación"
+msgid "Release date"
+msgstr "Fecha de liberación"
+
msgid "Release Job"
msgstr "Liberar Trabajo"
@@ -16755,6 +16773,9 @@ msgstr "Liberar órdenes de trabajo"
msgid "Release purchase order {target} by {date}"
msgstr "Liberar orden de compra {target} antes de {date}"
+msgid "Release unit"
+msgstr "Liberar unidad"
+
msgid "Released"
msgstr "Liberado"
@@ -16957,6 +16978,9 @@ msgstr "Tarifas de Alquiler"
msgid "Rental Site"
msgstr "Sitio de Alquiler"
+msgid "Rental Units"
+msgstr "Unidades de alquiler"
+
msgid "Rental Utilization"
msgstr "Utilización de Alquiler"
@@ -17320,12 +17344,6 @@ msgstr "Reintentar reverso"
msgid "Return"
msgstr "Devolución"
-msgid "Return {unitLabel}"
-msgstr "Devolver {unitLabel}"
-
-msgid "Return Date"
-msgstr "Fecha de Devolución"
-
msgid "Return Home"
msgstr "Volver al Inicio"
@@ -17335,9 +17353,6 @@ msgstr "ID de devolución"
msgid "Return Location"
msgstr "Ubicación de devolución"
-msgid "Return Notes"
-msgstr "Notas de Devolución"
-
msgid "Return Number"
msgstr "Número de devolución"
@@ -17365,9 +17380,6 @@ msgstr "Devolver al Inventario"
msgid "Return to Service"
msgstr "Devolver al Servicio"
-msgid "Return Unit"
-msgstr "Unidad de Devolución"
-
msgid "returnable"
msgstr "retornable"
@@ -17380,6 +17392,9 @@ msgstr "Lote devuelto"
msgid "Returned goods re-enter inventory at zero value"
msgstr "Los bienes devueltos reingresan al inventario a valor cero"
+msgid "Returned on"
+msgstr "Devuelto el"
+
msgid "Returned serial numbers"
msgstr "Números de serie devueltos"
@@ -20637,9 +20652,6 @@ msgstr "La cuenta de gastos en la que se contabiliza esta línea de gasto indire
msgid "The file you uploaded and the mappings you've made will be lost."
msgstr "Se perderán el archivo que subiste y las asignaciones que hiciste."
-msgid "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-msgstr "El período de facturación final se reajusta a la fecha de devolución. Un período que ya fue facturado por adelantado recibe un ajuste por los días no utilizados."
-
msgid "the first 3 to 4 weeks"
msgstr "las primeras 3 a 4 semanas"
@@ -21234,16 +21246,9 @@ msgstr "La Unidad en la que se expresa un tiempo de Ruta de fabricación, como H
msgid "The unit and its rates are fixed once the agreement is activated."
msgstr "La unidad y sus tarifas se fijan una vez que se activa el acuerdo."
-#. placeholder {0}: formatDate(endDate)
-msgid "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-msgstr "La unidad puede devolverse en o después de la fecha de finalización, {0}. Finalizar una renta tratada como venta antes de tiempo es un asiento manual."
-
msgid "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
msgstr "La unidad regresa a existencias a su valor neto en libros y el activo se cierra sin ganancia ni pérdida."
-msgid "The unit goes to maintenance instead of back to available."
-msgstr "La unidad va a mantenimiento en lugar de volver a estar disponible."
-
msgid "The unit has no other use to you once the term ends."
msgstr "La unidad no tiene otro uso para ti una vez que termina el plazo."
@@ -21253,6 +21258,9 @@ msgstr "La unidad se retira de disponibilidad hasta que se devuelva al servicio.
msgid "The unit leaves stock and becomes an asset at the cost inventory carries it at."
msgstr "La unidad sale de las existencias y se convierte en un activo al costo registrado en existencias."
+msgid "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+msgstr "La unidad nunca salió del patio. La facturación se detiene en la fecha de liberación y la unidad queda disponible nuevamente."
+
msgid "The unit price of the item at the time of the purchase"
msgstr "El precio unitario del artículo en el momento de la compra"
@@ -21577,9 +21585,6 @@ msgstr "Este Trimestre"
msgid "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
msgstr "Esto elimina su aplicación autenticadora, por lo que su próximo inicio de sesión solo necesita un enlace mágico. Usa esto cuando hayan perdido acceso a su autenticador. Afecta su inicio de sesión en cada empresa a la que pertenecen."
-msgid "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-msgstr "Esta renta se trata como una venta. La inversión neta de cierre vuelve al balance general con la unidad, y se elimina el programa de intereses no contabilizado."
-
msgid "This resets {resets} edited invoices from {effectiveDate}"
msgstr "Esto reinicia {resets} facturas editadas desde {effectiveDate}."
@@ -21849,6 +21854,9 @@ msgstr "Hasta la Fecha"
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Para desactivar, utilice el menú de la fila y seleccione Desactivar cuenta."
+msgid "To Deliver"
+msgstr "A Entregar"
+
msgid "To Location"
msgstr "Ubicación de destino"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 0a0c06f7c0..ce7bd78c0a 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -4430,6 +4430,9 @@ msgstr "Choisir un avatar"
msgid "Choose how to add lines to this return."
msgstr "Choisissez comment ajouter des lignes à ce retour."
+msgid "Choose Return To for {unitName}"
+msgstr "Choisir la destination de retour pour {unitName}"
+
msgid "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
msgstr "Choisissez les unités de parc que cet accord loue. Chacune commence à son taux en file pour la fréquence ; changez-le dans la grille."
@@ -6980,12 +6983,12 @@ msgstr "Supprimer le flux de travail"
msgid "Deliver"
msgstr "Livrer"
-msgid "Deliver {label}"
-msgstr "Livrer {label}"
-
msgid "Delivered"
msgstr "Livré"
+msgid "Delivered on"
+msgstr "Livré le"
+
msgid "Delivery Date"
msgstr "Date de livraison"
@@ -8313,6 +8316,9 @@ msgstr "Entrez un numéro de lot avant de définir la date d'expiration"
msgid "Enter a quantity between 1 and {0}."
msgstr "Entrez une quantité entre 1 et {0}."
+msgid "Enter a reason to take the unit out of service"
+msgstr "Entrez une raison pour retirer l'unité du service"
+
msgid "Enter an item and quantity yourself."
msgstr "Entrez un article et une quantité vous-même."
@@ -12062,9 +12068,6 @@ msgstr "Marquer le périmètre comme convenu"
msgid "Mark Short"
msgstr "Marquer comme manquant"
-msgid "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-msgstr "Marquer l'unité comme livrée au client aujourd'hui. Elle entre en location aujourd'hui ; la facturation suit la date de début et le cycle du contrat."
-
msgid "Mark to delete"
msgstr "Marquer pour supprimer"
@@ -12312,8 +12315,8 @@ msgstr "Message"
msgid "Metadata"
msgstr "Métadonnées"
-msgid "Meter Reading"
-msgstr "Relevé de compteur"
+msgid "Meter"
+msgstr "Compteur"
msgid "Method"
msgstr "Méthode"
@@ -13831,6 +13834,9 @@ msgstr "Non configuré"
msgid "Not Configured"
msgstr "Non configuré"
+msgid "Not delivered"
+msgstr "Non livré"
+
msgid "Not enough jobs to cover quantity"
msgstr "Pas assez d'ordres de fabrication pour couvrir la quantité"
@@ -14811,6 +14817,12 @@ msgstr "Remplacement de pièce"
msgid "Partial"
msgstr "Partielle"
+msgid "Partially Delivered"
+msgstr "Partiellement livré"
+
+msgid "Partially Returned"
+msgstr "Partiellement retourné"
+
msgid "Partly Recognized"
msgstr "Partiellement Reconnu"
@@ -16726,6 +16738,9 @@ msgstr "Chronologie relative · dates à confirmer"
msgid "Release"
msgstr "Lancer"
+msgid "Release {unitLabel}"
+msgstr "Libérer {unitLabel}"
+
msgid "Release Batch"
msgstr "Lancer le lot de production"
@@ -16743,6 +16758,9 @@ msgstr "Contrôle de lancement"
msgid "Release Control"
msgstr "Contrôle de lancement"
+msgid "Release date"
+msgstr "Date de libération"
+
msgid "Release Job"
msgstr "Lancer le travail"
@@ -16755,6 +16773,9 @@ msgstr "Lancer les ordres de fabrication"
msgid "Release purchase order {target} by {date}"
msgstr "Lancer le bon de commande {target} avant le {date}"
+msgid "Release unit"
+msgstr "Libérer l'unité"
+
msgid "Released"
msgstr "Libéré"
@@ -16957,6 +16978,9 @@ msgstr "Tarifs de location"
msgid "Rental Site"
msgstr "Site de location"
+msgid "Rental Units"
+msgstr "Unités de location"
+
msgid "Rental Utilization"
msgstr "Utilisation de la location"
@@ -17320,12 +17344,6 @@ msgstr "Réessayer l'annulation"
msgid "Return"
msgstr "Retour"
-msgid "Return {unitLabel}"
-msgstr "Retourner {unitLabel}"
-
-msgid "Return Date"
-msgstr "Date de retour"
-
msgid "Return Home"
msgstr "Retour à l'accueil"
@@ -17335,9 +17353,6 @@ msgstr "Identifiant de retour"
msgid "Return Location"
msgstr "Lieu de retour"
-msgid "Return Notes"
-msgstr "Notes de retour"
-
msgid "Return Number"
msgstr "Numéro de retour"
@@ -17365,9 +17380,6 @@ msgstr "Retour aux stocks"
msgid "Return to Service"
msgstr "Retour en service"
-msgid "Return Unit"
-msgstr "Unité de retour"
-
msgid "returnable"
msgstr "retournable"
@@ -17380,6 +17392,9 @@ msgstr "Lot retourné"
msgid "Returned goods re-enter inventory at zero value"
msgstr "Les marchandises retournées réintègrent l'inventaire à valeur zéro"
+msgid "Returned on"
+msgstr "Retourné le"
+
msgid "Returned serial numbers"
msgstr "Numéros de série retournés"
@@ -20637,9 +20652,6 @@ msgstr "Le compte de charge auquel cette ligne de dépenses indirectes se compta
msgid "The file you uploaded and the mappings you've made will be lost."
msgstr "Le fichier que vous avez importé et les correspondances que vous avez définies seront perdus."
-msgid "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-msgstr "La période de facturation finale est réajustée à la date de retour. Une période déjà facturée à l'avance reçoit un ajustement pour les jours non utilisés."
-
msgid "the first 3 to 4 weeks"
msgstr "les 3 à 4 premières semaines"
@@ -21234,16 +21246,9 @@ msgstr "L'unité dans laquelle un temps de gamme est exprimé, par exemple Heure
msgid "The unit and its rates are fixed once the agreement is activated."
msgstr "L'unité et ses tarifs sont fixes une fois que l'accord est activé."
-#. placeholder {0}: formatDate(endDate)
-msgid "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-msgstr "L'unité peut être retournée à partir de la date de fin, {0}. L'arrêt d'une location traitée comme une vente anticipée est une écriture manuelle."
-
msgid "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
msgstr "L'unité retourne aux stocks à sa valeur nette comptable et l'actif est clôturé sans gain ni perte."
-msgid "The unit goes to maintenance instead of back to available."
-msgstr "L'unité va à la maintenance au lieu de retourner disponible."
-
msgid "The unit has no other use to you once the term ends."
msgstr "L'unité n'a pas d'autre utilité pour vous une fois la durée terminée."
@@ -21253,6 +21258,9 @@ msgstr "L'unité est retirée de la disponibilité jusqu'à ce qu'elle soit reto
msgid "The unit leaves stock and becomes an asset at the cost inventory carries it at."
msgstr "L'unité quitte le stock et devient une immobilisation au coût auquel le stock la porte."
+msgid "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+msgstr "L'unité n'a jamais quitté le parc. La facturation s'arrête à la date de libération, et l'unité est de nouveau disponible."
+
msgid "The unit price of the item at the time of the purchase"
msgstr "Le prix unitaire de l'article au moment de l'achat"
@@ -21577,9 +21585,6 @@ msgstr "Ce trimestre"
msgid "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
msgstr "Ceci supprime leur application d'authentification, de sorte que leur prochain accès ne nécessite qu'un lien magique. Utilisez cette option lorsqu'ils ont perdu l'accès à leur authentificateur. Cela affecte leur accès pour chaque société à laquelle ils appartiennent."
-msgid "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-msgstr "Cette location est traitée comme une vente. L'investissement net de clôture revient au bilan avec l'unité, et le calendrier des intérêts non comptabilisé est supprimé."
-
msgid "This resets {resets} edited invoices from {effectiveDate}"
msgstr "Cela réinitialise {resets} factures modifiées à partir de {effectiveDate}"
@@ -21849,6 +21854,9 @@ msgstr "À la date"
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Pour désactiver, utilisez le menu de ligne et choisissez Désactiver le compte."
+msgid "To Deliver"
+msgstr "À livrer"
+
msgid "To Location"
msgstr "Vers l'emplacement"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index ac938fc3a6..f293d53df1 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -4430,6 +4430,9 @@ msgstr "अवतार चुनें"
msgid "Choose how to add lines to this return."
msgstr "इस रिटर्न में पंक्तियाँ कैसे जोड़ें, यह चुनें।"
+msgid "Choose Return To for {unitName}"
+msgstr "{unitName} के लिए रिटर्न स्थान चुनें"
+
msgid "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
msgstr "उन फ्लीट इकाइयों को चुनें जो यह समझौता किराए पर देता है। प्रत्येक आवृत्ति के लिए फ़ाइल पर अपनी दर से शुरू होता है; इसे ग्रिड में बदलें।"
@@ -6980,12 +6983,12 @@ msgstr "वर्कफ़्लो हटाएँ"
msgid "Deliver"
msgstr "डिलीवर करें"
-msgid "Deliver {label}"
-msgstr "डिलीवर करें {label}"
-
msgid "Delivered"
msgstr "डिलीवर किया गया"
+msgid "Delivered on"
+msgstr "को डिलीवर किया गया"
+
msgid "Delivery Date"
msgstr "डिलीवरी तिथि"
@@ -8313,6 +8316,9 @@ msgstr "समाप्ति तिथि सेट करने से पह
msgid "Enter a quantity between 1 and {0}."
msgstr "1 और {0} के बीच मात्रा दर्ज करें।"
+msgid "Enter a reason to take the unit out of service"
+msgstr "इकाई को सेवा से बाहर निकालने का कारण दर्ज करें"
+
msgid "Enter an item and quantity yourself."
msgstr "आइटम और मात्रा स्वयं दर्ज करें।"
@@ -12062,9 +12068,6 @@ msgstr "स्कोप को सहमत के रूप में चिह
msgid "Mark Short"
msgstr "कम चिह्नित करें"
-msgid "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-msgstr "इकाई को आज ग्राहक को डिलीवर किए गए के रूप में चिह्नित करें। यह आज किराये पर जाता है; बिलिंग समझौते की प्रारंभ तिथि और चक्र का पालन करता है।"
-
msgid "Mark to delete"
msgstr "हटाने के लिए चिह्नित करें"
@@ -12312,8 +12315,8 @@ msgstr "संदेश"
msgid "Metadata"
msgstr "मेटाडेटा"
-msgid "Meter Reading"
-msgstr "मीटर रीडिंग"
+msgid "Meter"
+msgstr "मीटर"
msgid "Method"
msgstr "तरीका"
@@ -13831,6 +13834,9 @@ msgstr "कॉन्फ़िगर नहीं किया गया"
msgid "Not Configured"
msgstr "कॉन्फ़िगर नहीं किया गया"
+msgid "Not delivered"
+msgstr "डिलीवर नहीं किया गया"
+
msgid "Not enough jobs to cover quantity"
msgstr "मात्रा को कवर करने के लिए पर्याप्त जॉबें नहीं हैं"
@@ -14811,6 +14817,12 @@ msgstr "भाग प्रतिस्थापन"
msgid "Partial"
msgstr "आंशिक"
+msgid "Partially Delivered"
+msgstr "आंशिक डिलीवरी"
+
+msgid "Partially Returned"
+msgstr "आंशिक रिटर्न"
+
msgid "Partly Recognized"
msgstr "आंशिक रूप से मान्य"
@@ -16726,6 +16738,9 @@ msgstr "सापेक्ष समयरेखा · तारीखें प
msgid "Release"
msgstr "जारी करें"
+msgid "Release {unitLabel}"
+msgstr "{unitLabel} को जारी करें"
+
msgid "Release Batch"
msgstr "बैच जारी करें"
@@ -16743,6 +16758,9 @@ msgstr "नियंत्रण जारी करें"
msgid "Release Control"
msgstr "नियंत्रण जारी करें"
+msgid "Release date"
+msgstr "जारी करने की तारीख"
+
msgid "Release Job"
msgstr "जॉब जारी करें"
@@ -16755,6 +16773,9 @@ msgstr "जॉब को जारी करें"
msgid "Release purchase order {target} by {date}"
msgstr "क्रय आदेश {target} को {date} तक जारी करें"
+msgid "Release unit"
+msgstr "इकाई को जारी करें"
+
msgid "Released"
msgstr "जारी किया गया"
@@ -16957,6 +16978,9 @@ msgstr "किराया दरें"
msgid "Rental Site"
msgstr "किराया स्थल"
+msgid "Rental Units"
+msgstr "किराये की इकाइयाँ"
+
msgid "Rental Utilization"
msgstr "किराया उपयोग"
@@ -17320,12 +17344,6 @@ msgstr "पूर्ववत् करने का पुन: प्रया
msgid "Return"
msgstr "वापसी"
-msgid "Return {unitLabel}"
-msgstr "वापस करें {unitLabel}"
-
-msgid "Return Date"
-msgstr "वापसी की तारीख"
-
msgid "Return Home"
msgstr "घर लौटें"
@@ -17335,9 +17353,6 @@ msgstr "रिटर्न ID"
msgid "Return Location"
msgstr "रिटर्न स्थान"
-msgid "Return Notes"
-msgstr "वापसी नोट्स"
-
msgid "Return Number"
msgstr "रिटर्न संख्या"
@@ -17365,9 +17380,6 @@ msgstr "इन्वेंटरी में वापसी"
msgid "Return to Service"
msgstr "सेवा में वापसी"
-msgid "Return Unit"
-msgstr "रिटर्न इकाई"
-
msgid "returnable"
msgstr "रिटर्न योग्य"
@@ -17380,6 +17392,9 @@ msgstr "रिटर्न किया गया बैच"
msgid "Returned goods re-enter inventory at zero value"
msgstr "रिटर्न किए गए सामान शून्य मूल्य पर इन्वेंटरी में फिर से प्रवेश करते हैं"
+msgid "Returned on"
+msgstr "को वापस किया गया"
+
msgid "Returned serial numbers"
msgstr "लौटाए गए सीरियल नंबर"
@@ -20637,9 +20652,6 @@ msgstr "व्यय खाता जिस पर यह अप्रत्य
msgid "The file you uploaded and the mappings you've made will be lost."
msgstr "आपके द्वारा अपलोड की गई फ़ाइल और की गई मैपिंग खो जाएँगी।"
-msgid "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-msgstr "अंतिम बिलिंग अवधि वापसी की तारीख तक पुनः काट दी जाती है। पहले से बिल की गई अवधि को अप्रयुक्त दिनों के लिए समायोजन मिलता है।"
-
msgid "the first 3 to 4 weeks"
msgstr "पहले 3 से 4 सप्ताह"
@@ -21234,16 +21246,9 @@ msgstr "वह इकाई जिसमें रूटिंग समय व
msgid "The unit and its rates are fixed once the agreement is activated."
msgstr "समझौता सक्रिय होने के बाद इकाई और इसकी दरें तय हो जाती हैं।"
-#. placeholder {0}: formatDate(endDate)
-msgid "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-msgstr "इकाई को समाप्ति तिथि {0} के बाद या उसके बाद वापस किया जा सकता है। किराये को जल्दी बिक्री के रूप में समाप्त करना एक मैनुअल जर्नल है।"
-
msgid "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
msgstr "इकाई अपने शुद्ध बही मूल्य पर स्टॉक में वापस जाती है और संपत्ति बिना लाभ या हानि के बंद कर दी जाती है।"
-msgid "The unit goes to maintenance instead of back to available."
-msgstr "इकाई उपलब्ध स्थिति में लौटने के बजाय रखरखाव में जाती है।"
-
msgid "The unit has no other use to you once the term ends."
msgstr "अवधि समाप्त होने के बाद इकाई का आपके लिए कोई अन्य उपयोग नहीं है।"
@@ -21253,6 +21258,9 @@ msgstr "इकाई उपलब्धता से हटा दी जात
msgid "The unit leaves stock and becomes an asset at the cost inventory carries it at."
msgstr "इकाई स्टॉक से निकलती है और इन्वेंटरी में दर्ज लागत पर संपत्ति बन जाती है।"
+msgid "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+msgstr "इकाई कभी यार्ड नहीं छोड़ी। जारी करने की तारीख पर बिलिंग बंद हो जाती है, और इकाई फिर से मुक्त है।"
+
msgid "The unit price of the item at the time of the purchase"
msgstr "खरीद के समय आइटम की इकाई मूल्य"
@@ -21577,9 +21585,6 @@ msgstr "इस त्रैमासिक"
msgid "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
msgstr "यह उनके प्रमाणीकरणकर्ता ऐप को निकालता है, इसलिए उनके अगले साइन-इन के लिए केवल एक जादुई लिंक की आवश्यकता होती है। जब वे अपने प्रमाणीकरणकर्ता तक पहुंच खो गए हों तो इसका उपयोग करें। यह उनके साइन-इन को उन सभी कंपनियों के लिए प्रभावित करता है जिनसे वे संबंधित हैं।"
-msgid "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-msgstr "इस किराये को बिक्री के रूप में माना जाता है। समाप्त करने वाली शुद्ध निवेश इकाई के साथ तुलन पत्र पर वापस आती है, और अनपोस्ट ब्याज शेड्यूल हटा दिया जाता है।"
-
msgid "This resets {resets} edited invoices from {effectiveDate}"
msgstr "यह {resets} संपादित चालान {effectiveDate} से रीसेट करता है।"
@@ -21849,6 +21854,9 @@ msgstr "दिनांक तक"
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "निष्क्रिय करने के लिए, पंक्ति मेनू का उपयोग करें और खाता निष्क्रिय करें चुनें।"
+msgid "To Deliver"
+msgstr "डिलीवरी लंबित"
+
msgid "To Location"
msgstr "स्थान को"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index aad10c5d84..25a4ec29df 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -4430,6 +4430,9 @@ msgstr "Scegli avatar"
msgid "Choose how to add lines to this return."
msgstr "Scegli come aggiungere righe a questo reso."
+msgid "Choose Return To for {unitName}"
+msgstr "Scegli la destinazione di restituzione per {unitName}"
+
msgid "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
msgstr "Scegli le unità flotta che questo accordo noleggia. Ogni unità inizia al suo tasso nei registri per la frequenza; modificalo nella griglia."
@@ -6980,12 +6983,12 @@ msgstr "Elimina flusso di lavoro"
msgid "Deliver"
msgstr "Consegna"
-msgid "Deliver {label}"
-msgstr "Consegna {label}"
-
msgid "Delivered"
msgstr "Consegnato"
+msgid "Delivered on"
+msgstr "Consegnato il"
+
msgid "Delivery Date"
msgstr "Data di consegna"
@@ -8313,6 +8316,9 @@ msgstr "Inserisci un numero di lotto prima di impostare la data di scadenza"
msgid "Enter a quantity between 1 and {0}."
msgstr "Inserisci una quantità tra 1 e {0}."
+msgid "Enter a reason to take the unit out of service"
+msgstr "Inserisci un motivo per mettere l'unità fuori servizio"
+
msgid "Enter an item and quantity yourself."
msgstr "Inserisci un articolo e una quantità tu stesso."
@@ -12062,9 +12068,6 @@ msgstr "Contrassegna ambito come concordato"
msgid "Mark Short"
msgstr "Segna come incompleto"
-msgid "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-msgstr "Contrassegna l'unità come consegnata al cliente oggi. Va a noleggio oggi; la fatturazione segue la Data di inizio dell'accordo e il ciclo."
-
msgid "Mark to delete"
msgstr "Segna per eliminare"
@@ -12312,8 +12315,8 @@ msgstr "Messaggio"
msgid "Metadata"
msgstr "Metadati"
-msgid "Meter Reading"
-msgstr "Lettura del contatore"
+msgid "Meter"
+msgstr "Contatore"
msgid "Method"
msgstr "Metodo"
@@ -13831,6 +13834,9 @@ msgstr "Non configurato"
msgid "Not Configured"
msgstr "Non Configurato"
+msgid "Not delivered"
+msgstr "Non consegnato"
+
msgid "Not enough jobs to cover quantity"
msgstr "Non ci sono abbastanza ordini di produzione per coprire la quantità"
@@ -14811,6 +14817,12 @@ msgstr "Sostituzione Pezzo"
msgid "Partial"
msgstr "Parziale"
+msgid "Partially Delivered"
+msgstr "Consegna Parziale"
+
+msgid "Partially Returned"
+msgstr "Restituzione Parziale"
+
msgid "Partly Recognized"
msgstr "Parzialmente riconosciuto"
@@ -16726,6 +16738,9 @@ msgstr "Cronologia relativa · date da confermare"
msgid "Release"
msgstr "Rilascio"
+msgid "Release {unitLabel}"
+msgstr "Rilascia {unitLabel}"
+
msgid "Release Batch"
msgstr "Rilascia lotto"
@@ -16743,6 +16758,9 @@ msgstr "Controllo rilascio"
msgid "Release Control"
msgstr "Controllo Rilascio"
+msgid "Release date"
+msgstr "Data di rilascio"
+
msgid "Release Job"
msgstr "Rilascia Commessa"
@@ -16755,6 +16773,9 @@ msgstr "Rilascia Ordini di produzione"
msgid "Release purchase order {target} by {date}"
msgstr "Rilascia ordine di acquisto {target} entro {date}"
+msgid "Release unit"
+msgstr "Rilascia unità"
+
msgid "Released"
msgstr "Rilasciato"
@@ -16957,6 +16978,9 @@ msgstr "Tariffe di noleggio"
msgid "Rental Site"
msgstr "Sito di noleggio"
+msgid "Rental Units"
+msgstr "Unità in Noleggio"
+
msgid "Rental Utilization"
msgstr "Utilizzo dei noleggi"
@@ -17320,12 +17344,6 @@ msgstr "Riprova ripristino"
msgid "Return"
msgstr "Restituzione"
-msgid "Return {unitLabel}"
-msgstr "Restituzione {unitLabel}"
-
-msgid "Return Date"
-msgstr "Data di restituzione"
-
msgid "Return Home"
msgstr "Torna alla Home"
@@ -17335,9 +17353,6 @@ msgstr "ID Reso"
msgid "Return Location"
msgstr "Ubicazione Reso"
-msgid "Return Notes"
-msgstr "Note di restituzione"
-
msgid "Return Number"
msgstr "Numero Reso"
@@ -17365,9 +17380,6 @@ msgstr "Restituisci al magazzino"
msgid "Return to Service"
msgstr "Ritorno in servizio"
-msgid "Return Unit"
-msgstr "Unità di restituzione"
-
msgid "returnable"
msgstr "restituibile"
@@ -17380,6 +17392,9 @@ msgstr "Lotto Restituito"
msgid "Returned goods re-enter inventory at zero value"
msgstr "I beni restituiti rientrano in inventario con valore zero"
+msgid "Returned on"
+msgstr "Restituito il"
+
msgid "Returned serial numbers"
msgstr "Numeri di serie restituiti"
@@ -20637,9 +20652,6 @@ msgstr "Il conto spese a cui questa riga di spesa indiretta viene contabilizzata
msgid "The file you uploaded and the mappings you've made will be lost."
msgstr "Il file caricato e le mappature effettuate andranno persi."
-msgid "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-msgstr "Il periodo di fatturazione finale viene ricalcolato alla data di restituzione. Un periodo già fatturato in anticipo riceve una rettifica per i giorni non utilizzati."
-
msgid "the first 3 to 4 weeks"
msgstr "le prime 3-4 settimane"
@@ -21234,16 +21246,9 @@ msgstr "L'unità in cui è espresso un tempo di ciclo di lavorazione, come Ore/P
msgid "The unit and its rates are fixed once the agreement is activated."
msgstr "L'unità e le sue tariffe sono fisse una volta che l'accordo è attivato."
-#. placeholder {0}: formatDate(endDate)
-msgid "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-msgstr "L'unità può essere restituita alla data di fine o successivamente, {0}. Terminare un noleggio trattato come una vendita in anticipo è una prima nota manuale."
-
msgid "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
msgstr "L'unità torna a giacenza al suo valore contabile netto e l'asset viene chiuso senza utili o perdite."
-msgid "The unit goes to maintenance instead of back to available."
-msgstr "L'unità va in manutenzione invece di tornare disponibile."
-
msgid "The unit has no other use to you once the term ends."
msgstr "L'unità non ha altri usi per te una volta terminato il termine."
@@ -21253,6 +21258,9 @@ msgstr "L'unità viene rimossa dalla disponibilità finché non viene ritornata
msgid "The unit leaves stock and becomes an asset at the cost inventory carries it at."
msgstr "L'unità esce dalla giacenza e diventa un'attività al costo al quale il magazzino la tiene."
+msgid "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+msgstr "L'unità non ha mai lasciato il cantiere. La fatturazione si ferma alla data di rilascio e l'unità è di nuovo libera."
+
msgid "The unit price of the item at the time of the purchase"
msgstr "Il prezzo unitario dell'articolo al momento dell'acquisto"
@@ -21577,9 +21585,6 @@ msgstr "Questo Trimestre"
msgid "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
msgstr "Questo rimuove la loro app autenticatore, quindi il loro prossimo accesso ha bisogno solo di un collegamento magico. Usalo quando hanno perso l'accesso al loro autenticatore. Influisce sul loro accesso per ogni azienda a cui appartengono."
-msgid "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-msgstr "Questo noleggio è trattato come una vendita. L'investimento netto di chiusura torna nello stato patrimoniale con l'unità e il programma degli interessi non registrato viene rimosso."
-
msgid "This resets {resets} edited invoices from {effectiveDate}"
msgstr "Questo ripristina {resets} fatture modificate da {effectiveDate}"
@@ -21849,6 +21854,9 @@ msgstr "A data"
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Per disattivare, usa il menu della riga e scegli Disattiva Account."
+msgid "To Deliver"
+msgstr "Da Consegnare"
+
msgid "To Location"
msgstr "Ubicazione di destinazione"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index eee6342c9c..6d287138f1 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -4430,6 +4430,9 @@ msgstr "アバターを選択"
msgid "Choose how to add lines to this return."
msgstr "この返品に明細を追加する方法を選択してください。"
+msgid "Choose Return To for {unitName}"
+msgstr "{unitName}の返却先を選択"
+
msgid "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
msgstr "このアグリーメントでレンタルするフリート個を選択してください。各個の初期レートはファイルに設定されています。グリッドで変更してください。"
@@ -6980,12 +6983,12 @@ msgstr "ワークフローを削除"
msgid "Deliver"
msgstr "配送"
-msgid "Deliver {label}"
-msgstr "{label}を配送"
-
msgid "Delivered"
msgstr "配送済"
+msgid "Delivered on"
+msgstr "配送日"
+
msgid "Delivery Date"
msgstr "納期"
@@ -8313,6 +8316,9 @@ msgstr "有効期限を設定する前にバッチ番号を入力してくださ
msgid "Enter a quantity between 1 and {0}."
msgstr "1~{0}の数量を入力してください。"
+msgid "Enter a reason to take the unit out of service"
+msgstr "ユニットを使用停止にする理由を入力"
+
msgid "Enter an item and quantity yourself."
msgstr "品目と数量を手動で入力してください。"
@@ -12062,9 +12068,6 @@ msgstr "スコープを合意済みとしてマーク"
msgid "Mark Short"
msgstr "短い数量をマーク"
-msgid "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-msgstr "本日、機器を得意先に配送済とマークしてください。本日からレンタル開始となり、請求は契約の開始日およびサイクルに従います。"
-
msgid "Mark to delete"
msgstr "削除対象にマーク"
@@ -12312,8 +12315,8 @@ msgstr "メッセージ"
msgid "Metadata"
msgstr "メタデータ"
-msgid "Meter Reading"
-msgstr "メーター読取値"
+msgid "Meter"
+msgstr "メーター"
msgid "Method"
msgstr "方法"
@@ -13831,6 +13834,9 @@ msgstr "未設定"
msgid "Not Configured"
msgstr "未設定"
+msgid "Not delivered"
+msgstr "未配送"
+
msgid "Not enough jobs to cover quantity"
msgstr "数量をカバーするのに十分な製造指図がありません"
@@ -14811,6 +14817,12 @@ msgstr "部品後継切替"
msgid "Partial"
msgstr "一部"
+msgid "Partially Delivered"
+msgstr "一部納入"
+
+msgid "Partially Returned"
+msgstr "一部返却"
+
msgid "Partly Recognized"
msgstr "部分認識済"
@@ -16726,6 +16738,9 @@ msgstr "相対的なタイムライン・確認待ちの日付"
msgid "Release"
msgstr "リリース"
+msgid "Release {unitLabel}"
+msgstr "{unitLabel}をリリース"
+
msgid "Release Batch"
msgstr "バッチをリリース"
@@ -16743,6 +16758,9 @@ msgstr "リリース管理"
msgid "Release Control"
msgstr "リリース管理"
+msgid "Release date"
+msgstr "リリース日"
+
msgid "Release Job"
msgstr "ジョブをリリース"
@@ -16755,6 +16773,9 @@ msgstr "製造指図をリリース"
msgid "Release purchase order {target} by {date}"
msgstr "発注書{target}を{date}までにリリース"
+msgid "Release unit"
+msgstr "ユニットをリリース"
+
msgid "Released"
msgstr "リリース済み"
@@ -16957,6 +16978,9 @@ msgstr "レンタル料率"
msgid "Rental Site"
msgstr "レンタル拠点"
+msgid "Rental Units"
+msgstr "レンタルユニット"
+
msgid "Rental Utilization"
msgstr "レンタル資産利用率"
@@ -17320,12 +17344,6 @@ msgstr "リバートを再試行"
msgid "Return"
msgstr "返却"
-msgid "Return {unitLabel}"
-msgstr "{unitLabel}を返却"
-
-msgid "Return Date"
-msgstr "返却日"
-
msgid "Return Home"
msgstr "ホームに戻る"
@@ -17335,9 +17353,6 @@ msgstr "返品ID"
msgid "Return Location"
msgstr "返品場所"
-msgid "Return Notes"
-msgstr "返却メモ"
-
msgid "Return Number"
msgstr "返品番号"
@@ -17365,9 +17380,6 @@ msgstr "在庫に返却"
msgid "Return to Service"
msgstr "使用再開"
-msgid "Return Unit"
-msgstr "返却資産"
-
msgid "returnable"
msgstr "返品可能"
@@ -17380,6 +17392,9 @@ msgstr "返品バッチ"
msgid "Returned goods re-enter inventory at zero value"
msgstr "返品商品は在庫にゼロ価値で再入庫されます"
+msgid "Returned on"
+msgstr "返却日"
+
msgid "Returned serial numbers"
msgstr "返品シリアル番号"
@@ -20637,9 +20652,6 @@ msgstr "この間接支出明細が転記される費用勘定。間接明細に
msgid "The file you uploaded and the mappings you've made will be lost."
msgstr "アップロードしたファイルと設定したマッピングは失われます。"
-msgid "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-msgstr "最終請求期間は返却日で再設定されます。事前請求済みの期間には未使用日数に対する調整が反映されます。"
-
msgid "the first 3 to 4 weeks"
msgstr "最初の3~4週間"
@@ -21234,16 +21246,9 @@ msgstr "工順時間が表現される単位で、例えば「時間/個」ま
msgid "The unit and its rates are fixed once the agreement is activated."
msgstr "契約が有効化されるとユニットと料率は確定します。"
-#. placeholder {0}: formatDate(endDate)
-msgid "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-msgstr "単位は終了日{0}以降に返却できます。レンタルを販売として早期に終了することは、手動仕訳です。"
-
msgid "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
msgstr "この品目は未償却残高で在庫に戻り、資産はゲインまたはロスなくクローズされます。"
-msgid "The unit goes to maintenance instead of back to available."
-msgstr "ユニットは利用可能に戻すのではなく保全に移行します。"
-
msgid "The unit has no other use to you once the term ends."
msgstr "契約期間が終了すると、その単位はあなたにとって他に用途がありません。"
@@ -21253,6 +21258,9 @@ msgstr "この品目は使用再開までの間、利用不可となります。
msgid "The unit leaves stock and becomes an asset at the cost inventory carries it at."
msgstr "当該品目は在庫から出庫され、在庫で計上していた原価で固定資産化されます。"
+msgid "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+msgstr "ユニットはヤードから出ていません。リリース日に請求が停止し、ユニットは再び利用可能になります。"
+
msgid "The unit price of the item at the time of the purchase"
msgstr "購入時のアイテムの単価"
@@ -21577,9 +21585,6 @@ msgstr "今四半期"
msgid "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
msgstr "これにより認証器アプリが削除されるため、次回のサインインはマジックリンクのみが必要になります。認証器へのアクセスを失った場合にこれを使用してください。彼らが属するすべての会社のサインインに影響します。"
-msgid "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-msgstr "このレンタルは販売として扱われます。期末純投資が単位とともに貸借対照表に戻り、転記されていない利息スケジュールが削除されます。"
-
msgid "This resets {resets} edited invoices from {effectiveDate}"
msgstr "これは{effectiveDate}から{resets}件の編集済請求書をリセットします"
@@ -21849,6 +21854,9 @@ msgstr "終了日"
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "無効化するには、行メニューを使用して、アカウント無効化を選択します。"
+msgid "To Deliver"
+msgstr "納入待ち"
+
msgid "To Location"
msgstr "到着地"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 7487d841fb..9d1227e395 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -4430,6 +4430,9 @@ msgstr "아바타 선택"
msgid "Choose how to add lines to this return."
msgstr "이 반품에 라인을 추가하는 방법을 선택하세요."
+msgid "Choose Return To for {unitName}"
+msgstr "{unitName}을(를) 반환할 위치 선택"
+
msgid "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
msgstr "이 계약이 렌트하는 플릿 단위를 선택하세요. 각 단위는 빈도에 따라 파일에 저장된 요율부터 시작됩니다. 그리드에서 변경할 수 있습니다."
@@ -6980,12 +6983,12 @@ msgstr "워크플로우 삭제"
msgid "Deliver"
msgstr "배송"
-msgid "Deliver {label}"
-msgstr "{label} 배달"
-
msgid "Delivered"
msgstr "배송됨"
+msgid "Delivered on"
+msgstr "배송일"
+
msgid "Delivery Date"
msgstr "납기일"
@@ -8313,6 +8316,9 @@ msgstr "만료일을 설정하기 전에 배치 번호를 입력하세요."
msgid "Enter a quantity between 1 and {0}."
msgstr "1과 {0} 사이의 수량을 입력하세요."
+msgid "Enter a reason to take the unit out of service"
+msgstr "장비를 운영 중단하는 이유를 입력하세요"
+
msgid "Enter an item and quantity yourself."
msgstr "품목과 수량을 직접 입력하세요."
@@ -12062,9 +12068,6 @@ msgstr "범위를 합의됨으로 표시"
msgid "Mark Short"
msgstr "부족으로 표시"
-msgid "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-msgstr "단위를 오늘 고객에게 인도된 것으로 표시합니다. 오늘부터 임차됩니다. 청구는 계약의 시작일 및 주기를 따릅니다."
-
msgid "Mark to delete"
msgstr "삭제 대상으로 표시"
@@ -12312,8 +12315,8 @@ msgstr "메시지"
msgid "Metadata"
msgstr "메타데이터"
-msgid "Meter Reading"
-msgstr "미터 측정"
+msgid "Meter"
+msgstr "계량기"
msgid "Method"
msgstr "제조방법"
@@ -13831,6 +13834,9 @@ msgstr "구성되지 않음"
msgid "Not Configured"
msgstr "미설정"
+msgid "Not delivered"
+msgstr "배송되지 않음"
+
msgid "Not enough jobs to cover quantity"
msgstr "수량을 충당하기에 충분한 작업 지시가 없습니다."
@@ -14811,6 +14817,12 @@ msgstr "부품 대체"
msgid "Partial"
msgstr "부분"
+msgid "Partially Delivered"
+msgstr "부분 배송"
+
+msgid "Partially Returned"
+msgstr "부분 반품"
+
msgid "Partly Recognized"
msgstr "부분 인식됨"
@@ -16726,6 +16738,9 @@ msgstr "상대적 타임라인 · 확정 예정 날짜"
msgid "Release"
msgstr "릴리스"
+msgid "Release {unitLabel}"
+msgstr "{unitLabel} 릴리스"
+
msgid "Release Batch"
msgstr "배치 릴리스"
@@ -16743,6 +16758,9 @@ msgstr "릴리스 제어"
msgid "Release Control"
msgstr "릴리스 제어"
+msgid "Release date"
+msgstr "릴리스 날짜"
+
msgid "Release Job"
msgstr "작업 지시 릴리스"
@@ -16755,6 +16773,9 @@ msgstr "작업 지시 릴리스"
msgid "Release purchase order {target} by {date}"
msgstr "발주서 {target}을(를) {date}까지 릴리스"
+msgid "Release unit"
+msgstr "장비 릴리스"
+
msgid "Released"
msgstr "릴리즈됨"
@@ -16957,6 +16978,9 @@ msgstr "임차료율"
msgid "Rental Site"
msgstr "임차 현장"
+msgid "Rental Units"
+msgstr "렌탈 장비"
+
msgid "Rental Utilization"
msgstr "임차 자산 이용률"
@@ -17320,12 +17344,6 @@ msgstr "복원 재시도"
msgid "Return"
msgstr "반납"
-msgid "Return {unitLabel}"
-msgstr "{unitLabel} 반납"
-
-msgid "Return Date"
-msgstr "반납 날짜"
-
msgid "Return Home"
msgstr "홈으로 돌아가기"
@@ -17335,9 +17353,6 @@ msgstr "반품 ID"
msgid "Return Location"
msgstr "반품 위치"
-msgid "Return Notes"
-msgstr "반납 메모"
-
msgid "Return Number"
msgstr "반품 번호"
@@ -17365,9 +17380,6 @@ msgstr "재고로 반환"
msgid "Return to Service"
msgstr "서비스 재개"
-msgid "Return Unit"
-msgstr "반납 개"
-
msgid "returnable"
msgstr "반품 가능"
@@ -17380,6 +17392,9 @@ msgstr "반품된 배치"
msgid "Returned goods re-enter inventory at zero value"
msgstr "반품된 상품은 0 가치로 재입고됩니다"
+msgid "Returned on"
+msgstr "반환일"
+
msgid "Returned serial numbers"
msgstr "반환된 시리얼 번호"
@@ -20637,9 +20652,6 @@ msgstr "이 간접비 지출 라인이 계상되는 비용 계정입니다. 간
msgid "The file you uploaded and the mappings you've made will be lost."
msgstr "업로드한 파일과 설정한 매핑이 손실됩니다."
-msgid "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-msgstr "최종 청구 기간은 반납 날짜로 재조정됩니다. 미리 청구된 기간은 미사용 일수에 대한 조정을 받습니다."
-
msgid "the first 3 to 4 weeks"
msgstr "처음 3~4주"
@@ -21234,16 +21246,9 @@ msgstr "라우팅 시간이 표현되는 단위(예: 시간/개 또는 총 시
msgid "The unit and its rates are fixed once the agreement is activated."
msgstr "계약이 활성화되면 개와 요금이 고정됩니다."
-#. placeholder {0}: formatDate(endDate)
-msgid "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-msgstr "개는 종료일 {0} 이후에 반환할 수 있습니다. 임차 계약을 판매로 취급하여 조기 종료하는 것은 수동 전표입니다."
-
msgid "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
msgstr "개 수량이 순장부가액으로 재고로 반환되고 자산은 이익 또는 손실 없이 마감됩니다."
-msgid "The unit goes to maintenance instead of back to available."
-msgstr "개가 가용 상태로 돌아가는 대신 유지보수로 이동합니다."
-
msgid "The unit has no other use to you once the term ends."
msgstr "약관 기간이 종료되면 개는 귀사에게 더 이상 사용 가치가 없습니다."
@@ -21253,6 +21258,9 @@ msgstr "개 수량은 서비스로 복귀할 때까지 사용 불가능으로
msgid "The unit leaves stock and becomes an asset at the cost inventory carries it at."
msgstr "개가 재고에서 떠나 재고에 기록된 원가로 자산이 됩니다."
+msgid "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+msgstr "장비가 사업소를 떠나지 않았습니다. 릴리스 날짜에 청구가 중단되며, 장비는 다시 대여 가능합니다."
+
msgid "The unit price of the item at the time of the purchase"
msgstr "구매 시점의 품목 단가"
@@ -21577,9 +21585,6 @@ msgstr "이번 분기"
msgid "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
msgstr "이것은 그들의 인증 앱을 제거하므로 다음 로그인에는 매직 링크만 필요합니다. 그들이 인증 수단에 대한 접근을 잃었을 때 이것을 사용하세요. 이것은 그들이 속한 모든 회사에 대한 로그인에 영향을 미칩니다."
-msgid "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-msgstr "이 임차는 판매로 취급됩니다. 종료 순투자가 개와 함께 재무상태표로 돌아오고, 전기되지 않은 이자 일정은 제거됩니다."
-
msgid "This resets {resets} edited invoices from {effectiveDate}"
msgstr "이것은 {effectiveDate}부터 {resets}개의 편집된 송장을 재설정합니다."
@@ -21849,6 +21854,9 @@ msgstr "마감일"
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "비활성화하려면 행 메뉴를 사용하여 계정 비활성화를 선택하세요."
+msgid "To Deliver"
+msgstr "배송 예정"
+
msgid "To Location"
msgstr "대상 위치"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index f94e7ea4b2..0bf6b22a7b 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -4430,6 +4430,9 @@ msgstr "Wybierz awatar"
msgid "Choose how to add lines to this return."
msgstr "Wybierz sposób dodania pozycji do tego zwrotu."
+msgid "Choose Return To for {unitName}"
+msgstr "Wybierz lokalizację zwrotu dla {unitName}"
+
msgid "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
msgstr "Wybierz sztuki floty wynajmowanej w ramach tej umowy. Każda rozpoczyna się z jej zapisaną stawką dla okresu; zmień ją w tabeli."
@@ -6980,12 +6983,12 @@ msgstr "Usuń przepływ pracy"
msgid "Deliver"
msgstr "Dostarcz"
-msgid "Deliver {label}"
-msgstr "Dostarcz {label}"
-
msgid "Delivered"
msgstr "Dostarczona"
+msgid "Delivered on"
+msgstr "Dostarczono dnia"
+
msgid "Delivery Date"
msgstr "Data dostawy"
@@ -8313,6 +8316,9 @@ msgstr "Wprowadź numer partii produkcyjnej przed ustawieniem daty ważności."
msgid "Enter a quantity between 1 and {0}."
msgstr "Wprowadź ilość między 1 a {0}."
+msgid "Enter a reason to take the unit out of service"
+msgstr "Podaj powód wycofania jednostki z eksploatacji"
+
msgid "Enter an item and quantity yourself."
msgstr "Wpisz artykuł i ilość samodzielnie."
@@ -12062,9 +12068,6 @@ msgstr "Oznacz zakres jako uzgodniony"
msgid "Mark Short"
msgstr "Oznacz jako brakujące"
-msgid "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-msgstr "Oznacz sztukę jako dostarczoną klientowi dzisiaj. Dzisiaj jest wynajmowana; rozliczenie następuje zgodnie z datą rozpoczęcia i cyklem umowy."
-
msgid "Mark to delete"
msgstr "Oznacz do usunięcia"
@@ -12312,8 +12315,8 @@ msgstr "Wiadomość"
msgid "Metadata"
msgstr "Metadane"
-msgid "Meter Reading"
-msgstr "Odczyt licznika"
+msgid "Meter"
+msgstr "Licznik"
msgid "Method"
msgstr "Metoda"
@@ -13831,6 +13834,9 @@ msgstr "Nie skonfigurowano"
msgid "Not Configured"
msgstr "Nie skonfigurowane"
+msgid "Not delivered"
+msgstr "Nie dostarczone"
+
msgid "Not enough jobs to cover quantity"
msgstr "Niewystarczająco zleceń produkcyjnych aby pokryć ilość"
@@ -14811,6 +14817,12 @@ msgstr "Zastąpienie części"
msgid "Partial"
msgstr "Częściowa"
+msgid "Partially Delivered"
+msgstr "Częściowo dostarczone"
+
+msgid "Partially Returned"
+msgstr "Częściowo zwrócone"
+
msgid "Partly Recognized"
msgstr "Częściowo rozpoznane"
@@ -16726,6 +16738,9 @@ msgstr "Względna oś czasu · daty do potwierdzenia"
msgid "Release"
msgstr "Zwolnienie"
+msgid "Release {unitLabel}"
+msgstr "Zwolnij {unitLabel}"
+
msgid "Release Batch"
msgstr "Zwolnij partię produkcyjną"
@@ -16743,6 +16758,9 @@ msgstr "Kontrola zwolnienia"
msgid "Release Control"
msgstr "Kontrola Zwolnienia"
+msgid "Release date"
+msgstr "Data zwolnienia"
+
msgid "Release Job"
msgstr "Zwolnij zadanie"
@@ -16755,6 +16773,9 @@ msgstr "Zwolnij zlecenia produkcyjne"
msgid "Release purchase order {target} by {date}"
msgstr "Zwolnij zamówienie zakupu {target} do {date}"
+msgid "Release unit"
+msgstr "Zwolnij jednostkę"
+
msgid "Released"
msgstr "Wydane"
@@ -16957,6 +16978,9 @@ msgstr "Stawki wynajmu"
msgid "Rental Site"
msgstr "Miejsce wynajmu"
+msgid "Rental Units"
+msgstr "Jednostki wynajmu"
+
msgid "Rental Utilization"
msgstr "Wykorzystanie wynajmu"
@@ -17320,12 +17344,6 @@ msgstr "Ponów przywracanie"
msgid "Return"
msgstr "Zwrot"
-msgid "Return {unitLabel}"
-msgstr "Zwrot {unitLabel}"
-
-msgid "Return Date"
-msgstr "Data zwrotu"
-
msgid "Return Home"
msgstr "Wróć do domu"
@@ -17335,9 +17353,6 @@ msgstr "Identyfikator zwrotu"
msgid "Return Location"
msgstr "Lokalizacja zwrotu"
-msgid "Return Notes"
-msgstr "Notatki zwrotu"
-
msgid "Return Number"
msgstr "Numer zwrotu"
@@ -17365,9 +17380,6 @@ msgstr "Zwrot do zapasów"
msgid "Return to Service"
msgstr "Powrót do użytku"
-msgid "Return Unit"
-msgstr "Jednostka zwrotu"
-
msgid "returnable"
msgstr "zwrotne"
@@ -17380,6 +17392,9 @@ msgstr "Zwrócona partia"
msgid "Returned goods re-enter inventory at zero value"
msgstr "Zwrócone towary ponownie wchodzą do zapasów z zerową wartością"
+msgid "Returned on"
+msgstr "Zwrócono dnia"
+
msgid "Returned serial numbers"
msgstr "Zwrócone numery seryjne"
@@ -20637,9 +20652,6 @@ msgstr "Konto wydatków, na które ta linia wydatków pośrednich jest księgowa
msgid "The file you uploaded and the mappings you've made will be lost."
msgstr "Przesłany plik i utworzone mapowania zostaną utracone."
-msgid "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-msgstr "Ostatni okres rozliczeniowy jest dostosowywany do daty zwrotu. Okres już rozliczony z wyprzedzeniem otrzymuje korektę za niewykorzystane dni."
-
msgid "the first 3 to 4 weeks"
msgstr "pierwsze 3 do 4 tygodnie"
@@ -21234,16 +21246,9 @@ msgstr "Jednostka, w której wyrażany jest czas marszruty, taka jak Godziny/Szt
msgid "The unit and its rates are fixed once the agreement is activated."
msgstr "Sztuka i jej stawki są zablokowane po aktywacji umowy."
-#. placeholder {0}: formatDate(endDate)
-msgid "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-msgstr "Jednostka może być zwrócona w dniu lub po dacie końcowej {0}. Zakończenie wynajmu traktowanego jako sprzedaż na wczesnym etapie jest ręcznym dowodem księgowym."
-
msgid "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
msgstr "Sztuka wraca do zapasu w swojej wartości księgowej netto, a zasób zostaje zamknięty bez zysku lub straty."
-msgid "The unit goes to maintenance instead of back to available."
-msgstr "Sztuka trafia do utrzymania ruchu zamiast powrócić do dostępnych."
-
msgid "The unit has no other use to you once the term ends."
msgstr "Jednostka nie ma innego użytku dla ciebie po zakończeniu okresu."
@@ -21253,6 +21258,9 @@ msgstr "Sztuka jest usunięta z dostępności, dopóki nie zostanie zwrócona do
msgid "The unit leaves stock and becomes an asset at the cost inventory carries it at."
msgstr "Sztuka wychodzi z zapasów i staje się zasobem po koszcie, w jakim jest ujęta w zapasach."
+msgid "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+msgstr "Jednostka nigdy nie opuściła placu. Naliczanie opłat kończy się w dniu zwolnienia, a jednostka jest znowu dostępna."
+
msgid "The unit price of the item at the time of the purchase"
msgstr "Cena jednostkowa towaru w momencie zakupu"
@@ -21577,9 +21585,6 @@ msgstr "Ten Kwartał"
msgid "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
msgstr "To usuwa ich aplikację uwierzytelniającą, więc ich następny login potrzebuje tylko magicznego linku. Użyj tego, gdy stracili dostęp do swojej aplikacji uwierzytelniającej. To wpływa na ich logowanie dla każdej firmy, do której należą."
-msgid "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-msgstr "Ten wynajem jest traktowany jako sprzedaż. Końcowa inwestycja netto powraca na bilans wraz z jednostką, a niezaksięgowany harmonogram odsetek jest usuwany."
-
msgid "This resets {resets} edited invoices from {effectiveDate}"
msgstr "To przywraca {resets} edytowanych faktur od {effectiveDate}"
@@ -21849,6 +21854,9 @@ msgstr "Do dnia"
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Aby dezaktywować, użyj menu wiersza i wybierz Deaktywuj konto."
+msgid "To Deliver"
+msgstr "Do dostarczenia"
+
msgid "To Location"
msgstr "Do lokalizacji"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 45e503fcf0..8595c05359 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -4430,6 +4430,9 @@ msgstr "Escolher avatar"
msgid "Choose how to add lines to this return."
msgstr "Escolha como adicionar linhas a esta devolução."
+msgid "Choose Return To for {unitName}"
+msgstr "Escolha a Devolução para {unitName}"
+
msgid "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
msgstr "Escolha as unidades da frota que este contrato aluga. Cada uma começa em sua taxa registrada para a frequência; altere-a na grade."
@@ -6980,12 +6983,12 @@ msgstr "Excluir Fluxo de trabalho"
msgid "Deliver"
msgstr "Entregar"
-msgid "Deliver {label}"
-msgstr "Entregar {label}"
-
msgid "Delivered"
msgstr "Entregue"
+msgid "Delivered on"
+msgstr "Entregue em"
+
msgid "Delivery Date"
msgstr "Data de Entrega"
@@ -8313,6 +8316,9 @@ msgstr "Insira um número de lote antes de definir a data de validade"
msgid "Enter a quantity between 1 and {0}."
msgstr "Digite uma quantidade entre 1 e {0}."
+msgid "Enter a reason to take the unit out of service"
+msgstr "Digite um motivo para remover a unidade do serviço"
+
msgid "Enter an item and quantity yourself."
msgstr "Digite um item e quantidade você mesmo."
@@ -12062,9 +12068,6 @@ msgstr "Marcar escopo como acordado"
msgid "Mark Short"
msgstr "Marcar como Falta"
-msgid "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-msgstr "Marque a unidade como entregue ao cliente hoje. Ela vai para aluguel hoje; o faturamento segue a data de início e o ciclo do contrato."
-
msgid "Mark to delete"
msgstr "Marcar para exclusão"
@@ -12312,8 +12315,8 @@ msgstr "Mensagem"
msgid "Metadata"
msgstr "Metadados"
-msgid "Meter Reading"
-msgstr "Leitura de Medidor"
+msgid "Meter"
+msgstr "Medidor"
msgid "Method"
msgstr "Método"
@@ -13831,6 +13834,9 @@ msgstr "Não configurado"
msgid "Not Configured"
msgstr "Não Configurado"
+msgid "Not delivered"
+msgstr "Não entregue"
+
msgid "Not enough jobs to cover quantity"
msgstr "Não há ordens de produção suficientes para cobrir a quantidade"
@@ -14811,6 +14817,12 @@ msgstr "Substituição de Peça"
msgid "Partial"
msgstr "Parcial"
+msgid "Partially Delivered"
+msgstr "Entrega Parcial"
+
+msgid "Partially Returned"
+msgstr "Devolução Parcial"
+
msgid "Partly Recognized"
msgstr "Parcialmente Reconhecido"
@@ -16726,6 +16738,9 @@ msgstr "Cronograma relativo · datas a confirmar"
msgid "Release"
msgstr "Liberação"
+msgid "Release {unitLabel}"
+msgstr "Liberar {unitLabel}"
+
msgid "Release Batch"
msgstr "Liberar lote de produção"
@@ -16743,6 +16758,9 @@ msgstr "Liberar controle"
msgid "Release Control"
msgstr "Liberar Controle"
+msgid "Release date"
+msgstr "Data de Liberação"
+
msgid "Release Job"
msgstr "Liberar Trabalho"
@@ -16755,6 +16773,9 @@ msgstr "Liberar Ordens de produção"
msgid "Release purchase order {target} by {date}"
msgstr "Liberar pedido de compra {target} até {date}"
+msgid "Release unit"
+msgstr "Liberar Unidade"
+
msgid "Released"
msgstr "Liberado"
@@ -16957,6 +16978,9 @@ msgstr "Taxas de Aluguel"
msgid "Rental Site"
msgstr "Local de Aluguel"
+msgid "Rental Units"
+msgstr "Unidades de Aluguel"
+
msgid "Rental Utilization"
msgstr "Utilização de Aluguel"
@@ -17320,12 +17344,6 @@ msgstr "Tentar reverter novamente"
msgid "Return"
msgstr "Devolução"
-msgid "Return {unitLabel}"
-msgstr "Devolver {unitLabel}"
-
-msgid "Return Date"
-msgstr "Data de Devolução"
-
msgid "Return Home"
msgstr "Voltar para Início"
@@ -17335,9 +17353,6 @@ msgstr "ID de Devolução"
msgid "Return Location"
msgstr "Local de Devolução"
-msgid "Return Notes"
-msgstr "Observações de Devolução"
-
msgid "Return Number"
msgstr "Número de Devolução"
@@ -17365,9 +17380,6 @@ msgstr "Retornar ao Estoque"
msgid "Return to Service"
msgstr "Retornar à Operação"
-msgid "Return Unit"
-msgstr "Unidade de Devolução"
-
msgid "returnable"
msgstr "devolvível"
@@ -17380,6 +17392,9 @@ msgstr "Lote Devolvido"
msgid "Returned goods re-enter inventory at zero value"
msgstr "Produtos devolvidos reingressam no inventário com valor zero"
+msgid "Returned on"
+msgstr "Devolvido em"
+
msgid "Returned serial numbers"
msgstr "Números de série devolvidos"
@@ -20637,9 +20652,6 @@ msgstr "A conta de despesas em que essa linha de despesa indireta é lançada; o
msgid "The file you uploaded and the mappings you've made will be lost."
msgstr "O arquivo enviado e os mapeamentos feitos serão perdidos."
-msgid "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-msgstr "O período final de faturamento é reajustado para a data de devolução. Um período já faturado antecipadamente recebe um ajuste pelos dias não utilizados."
-
msgid "the first 3 to 4 weeks"
msgstr "as primeiras 3 a 4 semanas"
@@ -21234,16 +21246,9 @@ msgstr "A unidade em que o tempo de roteiro de produção é expresso, como Hora
msgid "The unit and its rates are fixed once the agreement is activated."
msgstr "A unidade e suas taxas são fixas uma vez que o contrato é ativado."
-#. placeholder {0}: formatDate(endDate)
-msgid "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-msgstr "A unidade pode ser devolvida na data final ou depois dela, {0}. Terminar um aluguel tratado como venda antecipadamente é um diário manual."
-
msgid "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
msgstr "A unidade retorna ao estoque com seu valor contábil líquido e o ativo é fechado sem ganho ou perda."
-msgid "The unit goes to maintenance instead of back to available."
-msgstr "A unidade vai para Manutenção em vez de voltar para Disponível."
-
msgid "The unit has no other use to you once the term ends."
msgstr "A unidade não tem outro uso para você após o término do prazo."
@@ -21253,6 +21258,9 @@ msgstr "A unidade é removida da disponibilidade até ser retornada à operaçã
msgid "The unit leaves stock and becomes an asset at the cost inventory carries it at."
msgstr "A unidade sai do estoque e se torna um ativo ao custo nele registrado."
+msgid "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+msgstr "A unidade nunca deixou o pátio. A cobrança para na data de liberação e a unidade fica livre novamente."
+
msgid "The unit price of the item at the time of the purchase"
msgstr "O preço unitário do item no momento da compra"
@@ -21577,9 +21585,6 @@ msgstr "Este Trimestre"
msgid "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
msgstr "Isso remove seu aplicativo autenticador, portanto seu próximo login só precisa de um link mágico. Use isso quando eles tiverem perdido acesso ao seu autenticador. Afeta seu login para cada empresa a que pertencem."
-msgid "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-msgstr "Este aluguel é tratado como uma venda. O investimento líquido de fechamento volta ao balanço patrimonial com a unidade, e o cronograma de juros não contabilizado é removido."
-
msgid "This resets {resets} edited invoices from {effectiveDate}"
msgstr "Isso redefine {resets} faturas editadas de {effectiveDate}"
@@ -21849,6 +21854,9 @@ msgstr "Até a Data"
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Para desativar, use o menu de linha e escolha Desativar Conta."
+msgid "To Deliver"
+msgstr "A Entregar"
+
msgid "To Location"
msgstr "Para Localização"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 091ee43d54..90e23e04d4 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -4430,6 +4430,9 @@ msgstr "Выбрать аватар"
msgid "Choose how to add lines to this return."
msgstr "Выберите, как добавить строки в этот возврат."
+msgid "Choose Return To for {unitName}"
+msgstr "Выберите место возврата для {unitName}"
+
msgid "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
msgstr "Выберите единицы флота, которые арендует это соглашение. Каждая начинается со своей ставки по файлу для частоты; измените ее в сетке."
@@ -6980,12 +6983,12 @@ msgstr "Удалить рабочий процесс"
msgid "Deliver"
msgstr "Доставить"
-msgid "Deliver {label}"
-msgstr "Доставить {label}"
-
msgid "Delivered"
msgstr "Доставлено"
+msgid "Delivered on"
+msgstr "Доставлено"
+
msgid "Delivery Date"
msgstr "Дата поставки"
@@ -8313,6 +8316,9 @@ msgstr "Введите номер серии перед установкой д
msgid "Enter a quantity between 1 and {0}."
msgstr "Введите количество от 1 до {0}."
+msgid "Enter a reason to take the unit out of service"
+msgstr "Введите причину вывода единицы из эксплуатации"
+
msgid "Enter an item and quantity yourself."
msgstr "Введите номенклатуру и количество самостоятельно."
@@ -12062,9 +12068,6 @@ msgstr "Отметить область как согласованную"
msgid "Mark Short"
msgstr "Отметить как недостача"
-msgid "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-msgstr "Отметить Единицу как доставленную Покупателю сегодня. Она сдается в аренду сегодня; выставление счетов начинается с даты начала договора и следует установленному циклу."
-
msgid "Mark to delete"
msgstr "Отметить к удалению"
@@ -12312,8 +12315,8 @@ msgstr "Сообщение"
msgid "Metadata"
msgstr "Метаданные"
-msgid "Meter Reading"
-msgstr "Показание счетчика"
+msgid "Meter"
+msgstr "Счетчик"
msgid "Method"
msgstr "Метод"
@@ -13831,6 +13834,9 @@ msgstr "Не настроено"
msgid "Not Configured"
msgstr "Не настроено"
+msgid "Not delivered"
+msgstr "Не доставлено"
+
msgid "Not enough jobs to cover quantity"
msgstr "Недостаточно производственных заказов для покрытия количества"
@@ -14811,6 +14817,12 @@ msgstr "Замещение деталей"
msgid "Partial"
msgstr "Частично"
+msgid "Partially Delivered"
+msgstr "Частично доставлено"
+
+msgid "Partially Returned"
+msgstr "Частично возвращено"
+
msgid "Partly Recognized"
msgstr "Частично признано"
@@ -16726,6 +16738,9 @@ msgstr "Относительная шкала времени · даты буд
msgid "Release"
msgstr "Запустить в работу"
+msgid "Release {unitLabel}"
+msgstr "Освободить {unitLabel}"
+
msgid "Release Batch"
msgstr "Запустить серию в работу"
@@ -16743,6 +16758,9 @@ msgstr "Управление запуском в работу"
msgid "Release Control"
msgstr "Управление запуском в работу"
+msgid "Release date"
+msgstr "Дата освобождения"
+
msgid "Release Job"
msgstr "Запустить производственный заказ в работу"
@@ -16755,6 +16773,9 @@ msgstr "Запустить в работу производственные за
msgid "Release purchase order {target} by {date}"
msgstr "Запустить заказ поставщику {target} к {date}"
+msgid "Release unit"
+msgstr "Освободить единицу"
+
msgid "Released"
msgstr "Выпущено"
@@ -16957,6 +16978,9 @@ msgstr "Ставки аренды"
msgid "Rental Site"
msgstr "Объект аренды"
+msgid "Rental Units"
+msgstr "Единицы в аренде"
+
msgid "Rental Utilization"
msgstr "Использование арендованного оборудования"
@@ -17320,12 +17344,6 @@ msgstr "Повторить восстановление"
msgid "Return"
msgstr "Возврат"
-msgid "Return {unitLabel}"
-msgstr "Вернуть {unitLabel}"
-
-msgid "Return Date"
-msgstr "Дата возврата"
-
msgid "Return Home"
msgstr "Вернуться на главную"
@@ -17335,9 +17353,6 @@ msgstr "ID возврата"
msgid "Return Location"
msgstr "Место возврата"
-msgid "Return Notes"
-msgstr "Примечания к возврату"
-
msgid "Return Number"
msgstr "Номер возврата"
@@ -17365,9 +17380,6 @@ msgstr "Вернуть в запасы"
msgid "Return to Service"
msgstr "Вернуть в эксплуатацию"
-msgid "Return Unit"
-msgstr "Возвращаемая единица"
-
msgid "returnable"
msgstr "возвратный"
@@ -17380,6 +17392,9 @@ msgstr "Возвращенная партия"
msgid "Returned goods re-enter inventory at zero value"
msgstr "Возвращенные товары повторно входят в инвентарь с нулевой стоимостью"
+msgid "Returned on"
+msgstr "Возвращено"
+
msgid "Returned serial numbers"
msgstr "Возвращенные серийные номера"
@@ -20637,9 +20652,6 @@ msgstr "Счет расходов, на который относится эта
msgid "The file you uploaded and the mappings you've made will be lost."
msgstr "Загруженный файл и созданные сопоставления будут потеряны."
-msgid "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-msgstr "Последний период выставления счетов переформируется по дате возврата. Период, уже выставленный авансом, получает корректировку за неиспользованные дни."
-
msgid "the first 3 to 4 weeks"
msgstr "первые 3–4 недели"
@@ -21234,16 +21246,9 @@ msgstr "Единица, в которой выражается время мар
msgid "The unit and its rates are fixed once the agreement is activated."
msgstr "Единица и ее ставки фиксируются при активации соглашения."
-#. placeholder {0}: formatDate(endDate)
-msgid "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-msgstr "Единица может быть возвращена на дату {0} или после нее. Досрочное завершение аренды, учитываемой как продажа, является ручной операцией."
-
msgid "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
msgstr "Единица возвращается в запас по остаточной стоимости, и актив закрывается без прибыли и убытка."
-msgid "The unit goes to maintenance instead of back to available."
-msgstr "Единица переходит на техническое обслуживание вместо возврата в доступные."
-
msgid "The unit has no other use to you once the term ends."
msgstr "Единица больше не имеет для вас другого применения по окончании срока."
@@ -21253,6 +21258,9 @@ msgstr "Единица удаляется из доступного до ее в
msgid "The unit leaves stock and becomes an asset at the cost inventory carries it at."
msgstr "Единица выводится из запасов и переводится в активы по их балансовой стоимости."
+msgid "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+msgstr "Единица так и не покинула площадку. Выставление счетов прекращается в дату освобождения, и единица снова доступна."
+
msgid "The unit price of the item at the time of the purchase"
msgstr "Цена за единицу товара на момент покупки"
@@ -21577,9 +21585,6 @@ msgstr "Этот квартал"
msgid "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
msgstr "Это удаляет их приложение аутентификатора, поэтому их следующий вход требует только волшебной ссылки. Используйте это, когда они потеряли доступ к своему аутентификатору. Это влияет на их вход для каждой организации, которой они принадлежат."
-msgid "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-msgstr "Эта аренда учитывается как продажа. Закрывающие чистые инвестиции возвращаются на бухгалтерский баланс вместе с единицей, и непроведенный график процентов удаляется."
-
msgid "This resets {resets} edited invoices from {effectiveDate}"
msgstr "Это сбрасывает {resets} отредактированные счета-фактуры с {effectiveDate}"
@@ -21849,6 +21854,9 @@ msgstr "До даты"
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Чтобы отключить, используйте меню строки и выберите Деактивировать учетную запись."
+msgid "To Deliver"
+msgstr "Требует доставки"
+
msgid "To Location"
msgstr "На локацию"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 336b457c84..edf9b22b5f 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -4430,6 +4430,9 @@ msgstr "Avatar seç"
msgid "Choose how to add lines to this return."
msgstr "Bu iade için satırları nasıl ekleyeceğinizi seçin."
+msgid "Choose Return To for {unitName}"
+msgstr "{unitName} için İade Yeri Seçin"
+
msgid "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
msgstr "Bu anlaşmanın kiraladığı filo adetlerini seçin. Her biri dosyadaki oranında başlar; ızgarada değiştirin."
@@ -6980,12 +6983,12 @@ msgstr "İş Akışını Sil"
msgid "Deliver"
msgstr "Teslim Et"
-msgid "Deliver {label}"
-msgstr "Teslim Et {label}"
-
msgid "Delivered"
msgstr "Teslim Edildi"
+msgid "Delivered on"
+msgstr "Teslim Tarihi"
+
msgid "Delivery Date"
msgstr "Teslimat Tarihi"
@@ -8313,6 +8316,9 @@ msgstr "Son kullanma tarihini ayarlamadan önce bir parti numarası girin"
msgid "Enter a quantity between 1 and {0}."
msgstr "1 ile {0} arasında bir miktar girin."
+msgid "Enter a reason to take the unit out of service"
+msgstr "Üniteyi hizmet dışı bırakmak için bir neden girin"
+
msgid "Enter an item and quantity yourself."
msgstr "Bir stok kartı ve miktar kendiniz girin."
@@ -12062,9 +12068,6 @@ msgstr "Kapsamı kabul edildi olarak işaretle"
msgid "Mark Short"
msgstr "Az eksik olarak işaretle"
-msgid "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-msgstr "Birimi müşteriye bugün teslim edildi olarak işaretleyin. Bugün kiralama başlar; faturalandırma sözleşmenin başlangıç tarihi ve döngüsünü izler."
-
msgid "Mark to delete"
msgstr "Silmek için işaretle"
@@ -12312,8 +12315,8 @@ msgstr "Mesaj"
msgid "Metadata"
msgstr "Meta Veri"
-msgid "Meter Reading"
-msgstr "Sayaç Okuması"
+msgid "Meter"
+msgstr "Sayaç"
msgid "Method"
msgstr "Yöntem"
@@ -13831,6 +13834,9 @@ msgstr "Yapılandırılmadı"
msgid "Not Configured"
msgstr "Yapılandırılmadı"
+msgid "Not delivered"
+msgstr "Teslim Edilmedi"
+
msgid "Not enough jobs to cover quantity"
msgstr "Miktarı karşılamak için yeterli İş emri yok"
@@ -14811,6 +14817,12 @@ msgstr "Parça İkamesi"
msgid "Partial"
msgstr "Kısmi"
+msgid "Partially Delivered"
+msgstr "Kısmen Teslim Edildi"
+
+msgid "Partially Returned"
+msgstr "Kısmen İade Edildi"
+
msgid "Partly Recognized"
msgstr "Kısmen Tanındı"
@@ -16726,6 +16738,9 @@ msgstr "Göreceli zaman çizelgesi · tarihler teyit edilecektir"
msgid "Release"
msgstr "Serbest Bırakma"
+msgid "Release {unitLabel}"
+msgstr "{unitLabel}'ı Serbest Bırak"
+
msgid "Release Batch"
msgstr "Partiyi Serbest Bırak"
@@ -16743,6 +16758,9 @@ msgstr "Serbest bırakma kontrolü"
msgid "Release Control"
msgstr "Serbest Bırakma Kontrolü"
+msgid "Release date"
+msgstr "Serbest Bırakma Tarihi"
+
msgid "Release Job"
msgstr "İş emrini serbest bırak"
@@ -16755,6 +16773,9 @@ msgstr "İş emirlerini Serbest Bırak"
msgid "Release purchase order {target} by {date}"
msgstr "{target} satın alma siparişini {date}'ye kadar serbest bırak"
+msgid "Release unit"
+msgstr "Üniteyi Serbest Bırak"
+
msgid "Released"
msgstr "Yayınlandı"
@@ -16957,6 +16978,9 @@ msgstr "Kiralama Oranları"
msgid "Rental Site"
msgstr "Kiralama Alanı"
+msgid "Rental Units"
+msgstr "Kiralık Üniteler"
+
msgid "Rental Utilization"
msgstr "Kiralama Kullanım Oranı"
@@ -17320,12 +17344,6 @@ msgstr "Geri alma'yı tekrar dene"
msgid "Return"
msgstr "İade"
-msgid "Return {unitLabel}"
-msgstr "İade Et {unitLabel}"
-
-msgid "Return Date"
-msgstr "İade Tarihi"
-
msgid "Return Home"
msgstr "Ana Sayfaya Dön"
@@ -17335,9 +17353,6 @@ msgstr "İade Kimliği"
msgid "Return Location"
msgstr "İade Konumu"
-msgid "Return Notes"
-msgstr "İade Notları"
-
msgid "Return Number"
msgstr "İade Numarası"
@@ -17365,9 +17380,6 @@ msgstr "Envantera Döndür"
msgid "Return to Service"
msgstr "Hizmete Döndür"
-msgid "Return Unit"
-msgstr "İade Adetı"
-
msgid "returnable"
msgstr "iadesine uygun"
@@ -17380,6 +17392,9 @@ msgstr "İade Edilen Parti"
msgid "Returned goods re-enter inventory at zero value"
msgstr "İade Edilen Mallar Stoka Sıfır Değerle Geri Girer"
+msgid "Returned on"
+msgstr "İade Tarihi"
+
msgid "Returned serial numbers"
msgstr "İade Edilen Seri Numaraları"
@@ -20637,9 +20652,6 @@ msgstr "Bu dolaylı harcama satırının nakledildiği gider hesabı; dolaylı s
msgid "The file you uploaded and the mappings you've made will be lost."
msgstr "Yüklediğiniz dosya ve yaptığınız eşleştirmeler kaybolacak."
-msgid "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-msgstr "Son faturalama dönemi iade tarihine göre yeniden ayarlanır. Önceden faturalanan bir dönem, kullanılmayan günler için bir düzeltme alır."
-
msgid "the first 3 to 4 weeks"
msgstr "ilk 3 ila 4 hafta"
@@ -21234,16 +21246,9 @@ msgstr "Rota zamanının ifade edildiği birim, örneğin Saatler/Parça veya To
msgid "The unit and its rates are fixed once the agreement is activated."
msgstr "Sözleşme etkinleştirildikten sonra adet ve oranları sabitlenir."
-#. placeholder {0}: formatDate(endDate)
-msgid "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-msgstr "Birim, {0} bitiş tarihinde veya sonrasında iade edilebilir. Bir kiralama'yı satış olarak ele almayı erkenden sonlandırmak manuel bir muhasebe fişi'dir."
-
msgid "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
msgstr "Birim, net defter değerindeki stoka geri gider ve varlık kar veya zarar olmaksızın kapatılır."
-msgid "The unit goes to maintenance instead of back to available."
-msgstr "Adet, kullanılabilir durumuna geri dönmek yerine bakıma gönderilir."
-
msgid "The unit has no other use to you once the term ends."
msgstr "Dönem sona erdikten sonra birim'in sizin için başka hiçbir kullanımı yoktur."
@@ -21253,6 +21258,9 @@ msgstr "Birim, hizmete döndürülünceye kadar kullanılabilirlikten kaldırıl
msgid "The unit leaves stock and becomes an asset at the cost inventory carries it at."
msgstr "Adet stoktan çıkar ve envanter tarafından taşınan maliyette bir varlık haline gelir."
+msgid "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+msgstr "Ünite sahadan hiç ayrılmadı. Faturalama serbest bırakma tarihinde durur ve ünite yeniden müsait olur."
+
msgid "The unit price of the item at the time of the purchase"
msgstr "Satın alma zamanındaki birim fiyat"
@@ -21577,9 +21585,6 @@ msgstr "Bu Çeyrek"
msgid "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
msgstr "Bu işlem onların kimlik doğrulayıcı uygulamasını kaldırır, bu nedenle sonraki oturum açışları yalnızca sihirli bir bağlantı gerektirir. Kimlik doğrulayıcılarına erişimini kaybettikleri zaman bunu kullanın. Ait oldukları her şirket için oturum açışlarını etkiler."
-msgid "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-msgstr "Bu kiralama satış olarak ele alınır. Kapanış net yatırım birim ile birlikte bilanço'ya geri gelir ve muhasebeleştirilmemiş faiz çizelgesi kaldırılır."
-
msgid "This resets {resets} edited invoices from {effectiveDate}"
msgstr "Bu, {effectiveDate} tarihinden {resets} düzenlenen faturayı sıfırlar"
@@ -21849,6 +21854,9 @@ msgstr "Bitiş Tarihi"
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "Devre dışı bırakmak için satır menüsünü kullanın ve Hesabı Devre Dışı Bırak'ı seçin."
+msgid "To Deliver"
+msgstr "Teslim Edilecek"
+
msgid "To Location"
msgstr "Varış Konumu"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 9ac61051bc..1bba309173 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -4430,6 +4430,9 @@ msgstr "选择头像"
msgid "Choose how to add lines to this return."
msgstr "选择如何向此退货添加行。"
+msgid "Choose Return To for {unitName}"
+msgstr "为 {unitName} 选择返还至"
+
msgid "Choose the fleet units this agreement rents. Each starts at its rate on file for the frequency; change it in the grid."
msgstr "选择本协议租赁的设备。每件在频率的文件费率开始;在网格中更改。"
@@ -6980,12 +6983,12 @@ msgstr "删除工作流"
msgid "Deliver"
msgstr "交付"
-msgid "Deliver {label}"
-msgstr "交付 {label}"
-
msgid "Delivered"
msgstr "已交付"
+msgid "Delivered on"
+msgstr "交付于"
+
msgid "Delivery Date"
msgstr "交货日期"
@@ -8313,6 +8316,9 @@ msgstr "在设置到期日期前输入生产批次号"
msgid "Enter a quantity between 1 and {0}."
msgstr "请输入 1 至 {0} 之间的数量。"
+msgid "Enter a reason to take the unit out of service"
+msgstr "输入停用该设备的原因"
+
msgid "Enter an item and quantity yourself."
msgstr "自己输入物料和数量。"
@@ -12062,9 +12068,6 @@ msgstr "将范围标记为已同意"
msgid "Mark Short"
msgstr "标记短缺"
-msgid "Mark the unit as delivered to the customer today. It goes on rent today; billing follows the agreement's start date and cycle."
-msgstr "将单位标记为今天已交付给客户。它从今天开始出租;计费遵循协议的开始日期和周期。"
-
msgid "Mark to delete"
msgstr "标记删除"
@@ -12312,8 +12315,8 @@ msgstr "消息"
msgid "Metadata"
msgstr "元数据"
-msgid "Meter Reading"
-msgstr "计量读数"
+msgid "Meter"
+msgstr "仪表读数"
msgid "Method"
msgstr "方法"
@@ -13831,6 +13834,9 @@ msgstr "未配置"
msgid "Not Configured"
msgstr "未配置"
+msgid "Not delivered"
+msgstr "未交付"
+
msgid "Not enough jobs to cover quantity"
msgstr "工单数量不足以覆盖所需数量"
@@ -14811,6 +14817,12 @@ msgstr "零件替代"
msgid "Partial"
msgstr "部分"
+msgid "Partially Delivered"
+msgstr "部分已交付"
+
+msgid "Partially Returned"
+msgstr "部分已退回"
+
msgid "Partly Recognized"
msgstr "部分已确认"
@@ -16726,6 +16738,9 @@ msgstr "相对时间表·待确认的日期"
msgid "Release"
msgstr "下达"
+msgid "Release {unitLabel}"
+msgstr "释放 {unitLabel}"
+
msgid "Release Batch"
msgstr "下达生产批次"
@@ -16743,6 +16758,9 @@ msgstr "下达控制"
msgid "Release Control"
msgstr "下达控制"
+msgid "Release date"
+msgstr "释放日期"
+
msgid "Release Job"
msgstr "下达工单"
@@ -16755,6 +16773,9 @@ msgstr "下达工单"
msgid "Release purchase order {target} by {date}"
msgstr "下达采购订单 {target} 至 {date}"
+msgid "Release unit"
+msgstr "释放设备"
+
msgid "Released"
msgstr "已下达"
@@ -16957,6 +16978,9 @@ msgstr "租赁费率"
msgid "Rental Site"
msgstr "租赁场所"
+msgid "Rental Units"
+msgstr "出租设备"
+
msgid "Rental Utilization"
msgstr "租赁设备利用率"
@@ -17320,12 +17344,6 @@ msgstr "重试还原"
msgid "Return"
msgstr "退还"
-msgid "Return {unitLabel}"
-msgstr "退还 {unitLabel}"
-
-msgid "Return Date"
-msgstr "退还日期"
-
msgid "Return Home"
msgstr "返回首页"
@@ -17335,9 +17353,6 @@ msgstr "退货编号"
msgid "Return Location"
msgstr "退货地点"
-msgid "Return Notes"
-msgstr "退还备注"
-
msgid "Return Number"
msgstr "退货号"
@@ -17365,9 +17380,6 @@ msgstr "返回库存"
msgid "Return to Service"
msgstr "恢复服务"
-msgid "Return Unit"
-msgstr "退还单位"
-
msgid "returnable"
msgstr "可退货的"
@@ -17380,6 +17392,9 @@ msgstr "已退货批次"
msgid "Returned goods re-enter inventory at zero value"
msgstr "退回的货物以零价值重新进入库存"
+msgid "Returned on"
+msgstr "返还于"
+
msgid "Returned serial numbers"
msgstr "退货序列号"
@@ -20637,9 +20652,6 @@ msgstr "此间接支出行过账至的费用科目;因为间接行没有物料
msgid "The file you uploaded and the mappings you've made will be lost."
msgstr "您上传的文件和已完成的映射将会丢失。"
-msgid "The final billing period is re-cut to the return date. A period already billed in advance gets an adjustment for the unused days."
-msgstr "最后一个计费周期重新调整到退还日期。提前计费的周期将针对未使用的天数进行调整。"
-
msgid "the first 3 to 4 weeks"
msgstr "前3到4周"
@@ -21234,16 +21246,9 @@ msgstr "路线工时的表达单位,例如小时/件或总小时数,告诉Carbon
msgid "The unit and its rates are fixed once the agreement is activated."
msgstr "协议激活后,单位及其费率被固定。"
-#. placeholder {0}: formatDate(endDate)
-msgid "The unit can be returned on or after the end date, {0}. Ending a rental treated as a sale early is a manual journal."
-msgstr "该单位可以在结束日期 {0} 或之后返回。将此租赁视为销售而提前结束需要手动凭证。"
-
msgid "The unit goes back into stock at its net book value and the asset is closed with no gain or loss."
msgstr "该件按其账面净值返回库存,资产已关闭,无收益或损失。"
-msgid "The unit goes to maintenance instead of back to available."
-msgstr "该单位进入维护而不是返回可用。"
-
msgid "The unit has no other use to you once the term ends."
msgstr "期限结束后,该单位对您没有其他用途。"
@@ -21253,6 +21258,9 @@ msgstr "该件在返回服务前不可用。折旧继续,其会计处理保持
msgid "The unit leaves stock and becomes an asset at the cost inventory carries it at."
msgstr "该件离开库存,并以库存的成本作为资产进行记账。"
+msgid "The unit never left the yard. Billing stops on the release date, and the unit is free again."
+msgstr "该设备从未离开场地。计费在释放日期停止,该设备重新可用。"
+
msgid "The unit price of the item at the time of the purchase"
msgstr "购买时该商品的单价"
@@ -21577,9 +21585,6 @@ msgstr "本季度"
msgid "This removes their authenticator app, so their next sign-in only needs a magic link. Use this when they have lost access to their authenticator. It affects their sign-in for every company they belong to."
msgstr "此操作移除其身份验证应用,因此其下次登录只需要魔法链接。当他们无法访问其身份验证器时使用此选项。它影响其所属每个公司的登录。"
-msgid "This rental is treated as a sale. The closing net investment comes back onto the balance sheet with the unit, and the unposted interest schedule is removed."
-msgstr "此租赁被视为销售。结束净投资与该单位一起回到资产负债表上,未过账的利息计划被删除。"
-
msgid "This resets {resets} edited invoices from {effectiveDate}"
msgstr "这会重置来自{effectiveDate}的{resets}个已编辑发票"
@@ -21849,6 +21854,9 @@ msgstr "截止日期"
msgid "To deactivate, use the row menu and choose Deactivate Account."
msgstr "要停用,请使用行菜单并选择停用账户。"
+msgid "To Deliver"
+msgstr "待交付"
+
msgid "To Location"
msgstr "至位置"
diff --git a/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap b/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap
index d6849c0e42..b63b90f722 100644
--- a/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap
+++ b/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap
@@ -70,6 +70,9 @@ exports[`server function permissions > match the reviewed manifest 1`] = `
"receiptFromPurchaseOrder": {
"create": "inventory",
},
+ "receiptFromRentalAgreement": {
+ "create": "inventory",
+ },
"receiptFromSalesReturnOrder": {
"create": "inventory",
},
@@ -88,6 +91,9 @@ exports[`server function permissions > match the reviewed manifest 1`] = `
"shipmentFromPurchaseReturnOrder": {
"create": "inventory",
},
+ "shipmentFromRentalAgreement": {
+ "create": "inventory",
+ },
"shipmentFromSalesOrder": {
"create": "inventory",
},
diff --git a/packages/server-functions/src/convert/index.ts b/packages/server-functions/src/convert/index.ts
index dca0bc0d23..4a01db9beb 100644
--- a/packages/server-functions/src/convert/index.ts
+++ b/packages/server-functions/src/convert/index.ts
@@ -1434,6 +1434,7 @@ const convert = defineServerFn({
// Each shipped fixed asset line counts as quantity 1
for (const line of shipmentFixedAssetLines.data) {
const lineId = line.salesOrderLineId;
+ if (!lineId) continue;
quantitiesByLine[lineId] = (quantitiesByLine[lineId] || 0) + 1;
}
diff --git a/packages/server-functions/src/create/index.ts b/packages/server-functions/src/create/index.ts
index d5cca72d75..7fba7a58d2 100644
--- a/packages/server-functions/src/create/index.ts
+++ b/packages/server-functions/src/create/index.ts
@@ -146,6 +146,16 @@ export const createInput = z.discriminatedUnion("type", [
shipmentId: z.string(),
shipmentLineId: z.string()
}),
+ 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()
+ }),
z.object({
type: z.literal("journalEntry")
})
@@ -192,6 +202,8 @@ const create = defineServerFn({
shipmentFromSalesReturnOrder: { create: "inventory" },
shipmentFromSalesOrderLine: { create: "inventory" },
shipmentLineSplit: { create: "inventory" },
+ shipmentFromRentalAgreement: { create: "inventory" },
+ receiptFromRentalAgreement: { create: "inventory" },
journalEntry: { create: "accounting" }
}
},
@@ -3369,6 +3381,326 @@ const create = defineServerFn({
return { id: shipmentLineId };
}
+ case "shipmentFromRentalAgreement": {
+ // A rental delivery: one Draft shipment per agreement holds the
+ // Pending units. A per-unit shortcut adds (or ticks) its unit on it.
+ const { rentalAgreementId, rentalAgreementLineId } = payload;
+
+ logger.info({
+ function: "create",
+ type,
+ companyId,
+ rentalAgreementId,
+ rentalAgreementLineId,
+ userId
+ });
+
+ return db.transaction().execute(async (trx) => {
+ const agreement = await trx
+ .selectFrom("rentalAgreement")
+ .select([
+ "id",
+ "rentalAgreementId",
+ "status",
+ "customerId",
+ "locationId"
+ ])
+ .where("id", "=", rentalAgreementId)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ if (!agreement) throw new NotFoundError("Rental agreement not found");
+ if (agreement.status !== "Active") {
+ throw new InvalidInputError(
+ `Rental agreement ${agreement.rentalAgreementId} is ${agreement.status}; units are delivered from an Active agreement`
+ );
+ }
+
+ const draft = await trx
+ .selectFrom("shipment")
+ .select("id")
+ .where("sourceDocument", "=", "Rental Agreement")
+ .where("sourceDocumentId", "=", agreement.id)
+ .where("status", "=", "Draft")
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirst();
+
+ const onOpenShipments = await trx
+ .selectFrom("shipmentFixedAssetLine as sfl")
+ .innerJoin("shipment as s", (join) =>
+ join
+ .onRef("s.id", "=", "sfl.shipmentId")
+ .onRef("s.companyId", "=", "sfl.companyId")
+ )
+ .select([
+ "sfl.id",
+ "sfl.shipmentId",
+ "sfl.rentalAgreementLineId",
+ "sfl.shipped"
+ ])
+ .where("s.sourceDocument", "=", "Rental Agreement")
+ .where("s.sourceDocumentId", "=", agreement.id)
+ .where("s.status", "in", ["Draft", "Pending"])
+ .where("sfl.companyId", "=", companyId)
+ .execute();
+
+ let candidatesQuery = trx
+ .selectFrom("rentalAgreementLine")
+ .select(["id", "status"])
+ .where("rentalAgreementId", "=", agreement.id)
+ .where("companyId", "=", companyId)
+ .where("status", "=", "Pending");
+ if (rentalAgreementLineId) {
+ candidatesQuery = candidatesQuery.where(
+ "id",
+ "=",
+ rentalAgreementLineId
+ );
+ }
+ const candidates = await candidatesQuery.orderBy("id").execute();
+ if (rentalAgreementLineId && candidates.length === 0) {
+ throw new InvalidInputError("Only a Pending unit can be delivered");
+ }
+
+ if (draft) {
+ if (!rentalAgreementLineId) return { id: draft.id };
+ const onDocument = onOpenShipments.find(
+ (row) => row.rentalAgreementLineId === rentalAgreementLineId
+ );
+ if (onDocument && onDocument.shipmentId !== draft.id) {
+ throw new InvalidInputError(
+ "The unit is already on an open shipment"
+ );
+ }
+ if (onDocument) {
+ if (!onDocument.shipped) {
+ await trx
+ .updateTable("shipmentFixedAssetLine")
+ .set({ shipped: true, updatedBy: userId })
+ .where("id", "=", onDocument.id)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+ return { id: draft.id };
+ }
+ await trx
+ .insertInto("shipmentFixedAssetLine")
+ .values({
+ shipmentId: draft.id,
+ rentalAgreementLineId,
+ shipped: true,
+ companyId,
+ createdBy: userId
+ })
+ .execute();
+ return { id: draft.id };
+ }
+
+ const onOpenDocument = new Set(
+ onOpenShipments.map((row) => row.rentalAgreementLineId)
+ );
+ const units = candidates.filter(
+ (line) => !onOpenDocument.has(line.id)
+ );
+ if (units.length === 0) {
+ throw new InvalidInputError("No units to deliver");
+ }
+
+ const header = await trx
+ .insertInto("shipment")
+ .values({
+ 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
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+ await trx
+ .insertInto("shipmentFixedAssetLine")
+ .values(
+ units.map((line) => ({
+ shipmentId: header.id,
+ rentalAgreementLineId: line.id,
+ shipped: true,
+ companyId,
+ createdBy: userId
+ }))
+ )
+ .execute();
+ return { id: header.id };
+ });
+ }
+ case "receiptFromRentalAgreement": {
+ // A rental return: one Draft receipt per agreement holds the units
+ // that can come back — On Rent ticked, Pending unticked (spec Q8). A
+ // per-unit shortcut adds (or ticks) its unit on it.
+ const { rentalAgreementId, rentalAgreementLineId } = payload;
+
+ logger.info({
+ function: "create",
+ type,
+ companyId,
+ rentalAgreementId,
+ rentalAgreementLineId,
+ userId
+ });
+
+ return db.transaction().execute(async (trx) => {
+ const agreement = await trx
+ .selectFrom("rentalAgreement")
+ .select([
+ "id",
+ "rentalAgreementId",
+ "status",
+ "customerId",
+ "locationId"
+ ])
+ .where("id", "=", rentalAgreementId)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ if (!agreement) throw new NotFoundError("Rental agreement not found");
+ if (agreement.status !== "Active") {
+ throw new InvalidInputError(
+ `Rental agreement ${agreement.rentalAgreementId} is ${agreement.status}; units are returned from an Active agreement`
+ );
+ }
+
+ const draft = await trx
+ .selectFrom("receipt")
+ .select("id")
+ .where("sourceDocument", "=", "Rental Agreement")
+ .where("sourceDocumentId", "=", agreement.id)
+ .where("status", "=", "Draft")
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirst();
+
+ // Only another open RECEIPT keeps a unit off this one: a Pending
+ // unit may sit on an open shipment too, and the first to post wins.
+ const onOpenReceipts = await trx
+ .selectFrom("receiptFixedAssetLine as rfl")
+ .innerJoin("receipt as r", (join) =>
+ join
+ .onRef("r.id", "=", "rfl.receiptId")
+ .onRef("r.companyId", "=", "rfl.companyId")
+ )
+ .select([
+ "rfl.id",
+ "rfl.receiptId",
+ "rfl.rentalAgreementLineId",
+ "rfl.received"
+ ])
+ .where("r.sourceDocument", "=", "Rental Agreement")
+ .where("r.sourceDocumentId", "=", agreement.id)
+ .where("r.status", "in", ["Draft", "Pending"])
+ .where("rfl.companyId", "=", companyId)
+ .execute();
+
+ let candidatesQuery = trx
+ .selectFrom("rentalAgreementLine")
+ .select(["id", "status"])
+ .where("rentalAgreementId", "=", agreement.id)
+ .where("companyId", "=", companyId)
+ .where("status", "in", ["Pending", "On Rent"]);
+ if (rentalAgreementLineId) {
+ candidatesQuery = candidatesQuery.where(
+ "id",
+ "=",
+ rentalAgreementLineId
+ );
+ }
+ const candidates = await candidatesQuery.orderBy("id").execute();
+ if (rentalAgreementLineId && candidates.length === 0) {
+ throw new InvalidInputError(
+ "Only a Pending or On Rent unit can be returned"
+ );
+ }
+
+ if (draft) {
+ if (!rentalAgreementLineId) return { id: draft.id };
+ const onDocument = onOpenReceipts.find(
+ (row) => row.rentalAgreementLineId === rentalAgreementLineId
+ );
+ if (onDocument && onDocument.receiptId !== draft.id) {
+ throw new InvalidInputError(
+ "The unit is already on an open receipt"
+ );
+ }
+ if (onDocument) {
+ if (!onDocument.received) {
+ await trx
+ .updateTable("receiptFixedAssetLine")
+ .set({ received: true, updatedBy: userId })
+ .where("id", "=", onDocument.id)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+ return { id: draft.id };
+ }
+ await trx
+ .insertInto("receiptFixedAssetLine")
+ .values({
+ receiptId: draft.id,
+ rentalAgreementLineId,
+ received: true,
+ companyId,
+ createdBy: userId
+ })
+ .execute();
+ return { id: draft.id };
+ }
+
+ const onOpenDocument = new Set(
+ onOpenReceipts.map((row) => row.rentalAgreementLineId)
+ );
+ const units = candidates.filter(
+ (line) => !onOpenDocument.has(line.id)
+ );
+ if (units.length === 0) {
+ throw new InvalidInputError("No units to return");
+ }
+
+ const header = await trx
+ .insertInto("receipt")
+ .values({
+ receiptId: await getNextSequence(trx, "receipt", companyId),
+ sourceDocument: "Rental Agreement",
+ sourceDocumentId: agreement.id,
+ sourceDocumentReadableId: agreement.rentalAgreementId,
+ locationId: agreement.locationId,
+ status: "Draft",
+ companyId,
+ createdBy: userId
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+ await trx
+ .insertInto("receiptFixedAssetLine")
+ .values(
+ units.map((line) => ({
+ receiptId: header.id,
+ rentalAgreementLineId: line.id,
+ // The shortcut names its unit, so it comes back ticked; a
+ // whole-agreement receipt ticks only what is out on rent.
+ received: rentalAgreementLineId
+ ? true
+ : line.status === "On Rent",
+ companyId,
+ createdBy: userId
+ }))
+ )
+ .execute();
+ return { id: header.id };
+ });
+ }
case "journalEntry": {
let createdDocumentId;
const id = await db.transaction().execute(async (trx) => {
diff --git a/packages/server-functions/src/create/rental-agreement.test.ts b/packages/server-functions/src/create/rental-agreement.test.ts
new file mode 100644
index 0000000000..0adc791fb2
--- /dev/null
+++ b/packages/server-functions/src/create/rental-agreement.test.ts
@@ -0,0 +1,258 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The rental shipment and receipt `create` cases against the live database:
+// one Draft per agreement, the units each one holds, and the refusals.
+
+import { sql } from "kysely";
+import { expect } from "vitest";
+import { databaseTest } from "../local-database-test-fixture";
+import { rentalFixture } from "../post-rental-agreement/rental-test-fixture";
+import create from "./index";
+
+type Fixture = Awaited<ReturnType<typeof rentalFixture>>;
+
+function deliver(f: Fixture, rentalAgreementLineId?: string) {
+ return create(f.ctx, {
+ type: "shipmentFromRentalAgreement",
+ rentalAgreementId: f.agreementId,
+ rentalAgreementLineId
+ });
+}
+
+function returnUnits(f: Fixture, rentalAgreementLineId?: string) {
+ return create(f.ctx, {
+ type: "receiptFromRentalAgreement",
+ rentalAgreementId: f.agreementId,
+ rentalAgreementLineId
+ });
+}
+
+async function setLineStatus(
+ f: Fixture,
+ lineIds: string[],
+ status: "Pending" | "On Rent" | "Returned"
+) {
+ await f.db
+ .updateTable("rentalAgreementLine")
+ .set({ status })
+ .where("id", "in", lineIds)
+ .where("companyId", "=", f.companyId)
+ .execute();
+}
+
+function shipmentLines(f: Fixture, shipmentId: string) {
+ return f.db
+ .selectFrom("shipmentFixedAssetLine")
+ .select(["rentalAgreementLineId", "shipped"])
+ .where("shipmentId", "=", shipmentId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+}
+
+function receiptLines(f: Fixture, receiptId: string) {
+ return f.db
+ .selectFrom("receiptFixedAssetLine")
+ .select(["rentalAgreementLineId", "received"])
+ .where("receiptId", "=", receiptId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+}
+
+databaseTest(
+ "a shipment without a line id holds every Pending unit on one Draft",
+ async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const result = await deliver(f);
+ expect(result.error).toBeNull();
+ const shipment = await f.db
+ .selectFrom("shipment")
+ .select([
+ "status",
+ "locationId",
+ "sourceDocument",
+ "sourceDocumentReadableId",
+ sql<string | null>`"postingDate"::text`.as("postingDate")
+ ])
+ .where("id", "=", result.data!.id)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ expect(shipment).toEqual({
+ status: "Draft",
+ locationId: f.locationId,
+ sourceDocument: "Rental Agreement",
+ sourceDocumentReadableId: "RA-TEST",
+ postingDate: null
+ });
+ const lines = await shipmentLines(f, result.data!.id);
+ expect(lines).toHaveLength(5);
+ expect(lines.every((line) => line.shipped)).toBe(true);
+ expect(new Set(lines.map((line) => line.rentalAgreementLineId))).toEqual(
+ new Set(f.lineIds)
+ );
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "a second shipment without a line id opens the same Draft",
+ async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const first = await deliver(f);
+ const second = await deliver(f);
+ expect(second.error).toBeNull();
+ expect(second.data!.id).toEqual(first.data!.id);
+ expect(await shipmentLines(f, first.data!.id)).toHaveLength(5);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "the database refuses a second Draft shipment for one agreement",
+ async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const first = await deliver(f);
+ expect(first.error).toBeNull();
+ await expect(
+ f.db
+ .insertInto("shipment")
+ .values({
+ shipmentId: "SHP-DUPLICATE",
+ sourceDocument: "Rental Agreement",
+ sourceDocumentId: f.agreementId,
+ sourceDocumentReadableId: f.agreementReadableId,
+ locationId: f.locationId,
+ status: "Draft",
+ companyId: f.companyId,
+ createdBy: "system"
+ })
+ .execute()
+ ).rejects.toThrow("shipment_oneOpenDraftPerRentalAgreement_idx");
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest("a receipt with every unit Returned is refused", async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ await setLineStatus(f, f.lineIds, "Returned");
+ const result = await returnUnits(f);
+ expect(result.error?.message).toContain("No units to return");
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest(
+ "a receipt without a line id ticks the On Rent units and holds the Pending ones unticked",
+ async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const onRent = f.lineIds.slice(0, 3);
+ await setLineStatus(f, onRent, "On Rent");
+ const result = await returnUnits(f);
+ expect(result.error).toBeNull();
+ const lines = await receiptLines(f, result.data!.id);
+ expect(lines).toHaveLength(5);
+ const received = lines
+ .filter((line) => line.received)
+ .map((line) => line.rentalAgreementLineId);
+ expect(new Set(received)).toEqual(new Set(onRent));
+ expect(lines.filter((line) => !line.received)).toHaveLength(2);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "a receipt shortcut for an unticked Pending unit ticks it on the same Draft",
+ async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ await setLineStatus(f, f.lineIds.slice(0, 3), "On Rent");
+ const first = await returnUnits(f);
+ expect(first.error).toBeNull();
+ const pendingLineId = f.lineIds[4]!;
+
+ const shortcut = await returnUnits(f, pendingLineId);
+ expect(shortcut.error).toBeNull();
+ expect(shortcut.data!.id).toEqual(first.data!.id);
+ const lines = await receiptLines(f, first.data!.id);
+ expect(lines).toHaveLength(5);
+ expect(
+ lines.find((line) => line.rentalAgreementLineId === pendingLineId)
+ ?.received
+ ).toBe(true);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest("a shipment holds only the Pending units", async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const first = await deliver(f);
+ expect(first.error).toBeNull();
+ await setLineStatus(f, f.lineIds.slice(0, 2), "On Rent");
+ await f.db
+ .deleteFrom("shipment")
+ .where("id", "=", first.data!.id)
+ .where("companyId", "=", f.companyId)
+ .execute();
+
+ const result = await deliver(f);
+ expect(result.error).toBeNull();
+ const lines = await shipmentLines(f, result.data!.id);
+ expect(new Set(lines.map((line) => line.rentalAgreementLineId))).toEqual(
+ new Set(f.lineIds.slice(2))
+ );
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("a Closed agreement delivers nothing", async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ await f.db
+ .updateTable("rentalAgreement")
+ .set({ status: "Closed" })
+ .where("id", "=", f.agreementId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ const result = await deliver(f);
+ expect(result.error?.message).toContain("is Closed");
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest(
+ "a receipt shortcut with no Draft receipt returns its Pending unit ticked",
+ async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const lineId = f.lineIds[0]!;
+ const result = await returnUnits(f, lineId);
+ expect(result.error).toBeNull();
+ const lines = await receiptLines(f, result.data!.id);
+ expect(lines).toEqual([
+ { rentalAgreementLineId: lineId, received: true }
+ ]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
diff --git a/packages/server-functions/src/post-receipt/index.ts b/packages/server-functions/src/post-receipt/index.ts
index 93fe5ab601..0b0c3a33c8 100644
--- a/packages/server-functions/src/post-receipt/index.ts
+++ b/packages/server-functions/src/post-receipt/index.ts
@@ -41,7 +41,7 @@ import type { Insertable } from "kysely";
import { nanoid } from "nanoid";
import { z } from "zod";
import { defineServerFn } from "../define-server-fn";
-import { NotFoundError } from "../errors";
+import { InvalidInputError, NotFoundError } from "../errors";
import { calculateCOGS } from "../lib/calculate-cogs";
import { FixedAssetWrites } from "../lib/fixed-asset-writes";
import { getCurrentAccountingPeriod } from "../lib/get-accounting-period";
@@ -50,12 +50,18 @@ import {
resolveInventoryAccount
} from "../lib/get-posting-group";
import { assertPostable } from "../lib/postable";
+import { postRentalReceipt } from "./rental-agreement";
const logger = getLogger("server-functions", "post-receipt");
export const postReceiptInput = z.object({
type: z.enum(["post", "void"]).default("post"),
- receiptId: z.string()
+ 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()
});
/** Posts or voids a receipt: stock, tracked entities, cost layers and journal. */
@@ -63,7 +69,7 @@ const postReceipt = defineServerFn({
name: "post-receipt",
input: postReceiptInput,
permissions: { update: "inventory" },
- async run(ctx, { type, receiptId }) {
+ async run(ctx, { type, receiptId, postingDate }) {
const { db, companyId, userId } = ctx;
logger.info({ type, receiptId, userId, companyId });
@@ -277,6 +283,12 @@ const postReceipt = defineServerFn({
);
}
+ if (receiptHeader.sourceDocument === "Rental Agreement") {
+ throw new InvalidInputError(
+ "A rental return cannot be voided. Correct the unit by hand."
+ );
+ }
+
if (
receiptHeader.sourceDocument !== "Purchase Order" &&
receiptHeader.sourceDocument !== "Sales Return Order"
@@ -1891,20 +1903,21 @@ const postReceipt = defineServerFn({
const { data: receiptFaLines } = await many(
db,
"receiptFixedAssetLine",
- { receiptId, received: true },
+ { receiptId, received: true, companyId },
{ columns: ["id", "purchaseOrderLineId", "serialNumber"] }
);
+ const poFaLines = (receiptFaLines ?? []).filter(
+ (r): r is typeof r & { purchaseOrderLineId: string } =>
+ r.purchaseOrderLineId !== null
+ );
const receivedFaPoLineIds = new Set(
- (receiptFaLines ?? []).map((r) => r.purchaseOrderLineId)
+ poFaLines.map((r) => r.purchaseOrderLineId)
);
const faSerialNumbers = new Map(
- (receiptFaLines ?? []).map((r) => [
- r.purchaseOrderLineId,
- r.serialNumber
- ])
+ poFaLines.map((r) => [r.purchaseOrderLineId, r.serialNumber])
);
const faReceiptLineIds = new Map<string, string>();
- for (const r of receiptFaLines ?? []) {
+ for (const r of poFaLines) {
faReceiptLineIds.set(r.purchaseOrderLineId, r.id);
}
// A Construction in Progress asset records every posting that adds to
@@ -3550,6 +3563,16 @@ const postReceipt = defineServerFn({
break;
}
+ case "Rental Agreement": {
+ await postRentalReceipt(db, {
+ receiptId,
+ companyId,
+ userId,
+ today,
+ postingDate
+ });
+ break;
+ }
default: {
break;
}
diff --git a/packages/server-functions/src/post-receipt/rental-agreement.test.ts b/packages/server-functions/src/post-receipt/rental-agreement.test.ts
new file mode 100644
index 0000000000..0c71610da6
--- /dev/null
+++ b/packages/server-functions/src/post-receipt/rental-agreement.test.ts
@@ -0,0 +1,331 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Posting a rental receipt against the live database: the ticked units come
+// back on the return date at the receipt's location, a Pending unit can come
+// back too, and a posted rental receipt is never voided.
+
+import { sql } from "kysely";
+import { expect } from "vitest";
+import create from "../create";
+import { databaseTest } from "../local-database-test-fixture";
+import { rentalFixture } from "../post-rental-agreement/rental-test-fixture";
+import postReceipt from "./index";
+
+type Fixture = Awaited<ReturnType<typeof rentalFixture>>;
+
+async function putOnRent(f: Fixture, lineIds: string[]) {
+ await f.db
+ .updateTable("rentalAgreementLine")
+ .set({ status: "On Rent", deliveredAt: "2026-09-01" })
+ .where("id", "in", lineIds)
+ .where("companyId", "=", f.companyId)
+ .execute();
+}
+
+async function draftReceipt(f: Fixture): Promise<string> {
+ const result = await create(f.ctx, {
+ type: "receiptFromRentalAgreement",
+ rentalAgreementId: f.agreementId
+ });
+ if (result.error) throw result.error;
+ return result.data.id;
+}
+
+function post(f: Fixture, receiptId: string, postingDate?: string) {
+ return postReceipt(f.ctx, { type: "post", receiptId, postingDate });
+}
+
+async function setReceived(
+ f: Fixture,
+ receiptId: string,
+ lineIds: string[],
+ received: boolean
+) {
+ await f.db
+ .updateTable("receiptFixedAssetLine")
+ .set({ received })
+ .where("receiptId", "=", receiptId)
+ .where("rentalAgreementLineId", "in", lineIds)
+ .where("companyId", "=", f.companyId)
+ .execute();
+}
+
+async function setAssetLine(
+ f: Fixture,
+ receiptId: string,
+ lineId: string,
+ values: {
+ meter?: number;
+ takeOutOfService?: boolean;
+ outOfServiceReason?: string;
+ residualDestination?: string | null;
+ }
+) {
+ await f.db
+ .updateTable("receiptFixedAssetLine")
+ .set(values)
+ .where("receiptId", "=", receiptId)
+ .where("rentalAgreementLineId", "=", lineId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+}
+
+async function setReceiptLocation(
+ f: Fixture,
+ receiptId: string,
+ locationId: string
+) {
+ await f.db
+ .updateTable("receipt")
+ .set({ locationId })
+ .where("id", "=", receiptId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+}
+
+function receiptStatus(f: Fixture, receiptId: string) {
+ return f.db
+ .selectFrom("receipt")
+ .select([
+ "status",
+ sql<string | null>`"postingDate"::text`.as("postingDate")
+ ])
+ .where("id", "=", receiptId)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+}
+
+function readLine(f: Fixture, lineId: string) {
+ return f.db
+ .selectFrom("rentalAgreementLine")
+ .select([
+ "status",
+ "meterIn",
+ sql<string | null>`"returnedAt"::text`.as("returnedAt")
+ ])
+ .where("id", "=", lineId)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+}
+
+async function makeSaleLine(f: Fixture, lineId: string) {
+ await f.db
+ .updateTable("rentalAgreementLine")
+ .set({ lessorClassification: "Sale", initialNetInvestment: 1000 })
+ .where("id", "=", lineId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+}
+
+databaseTest(
+ "a rental receipt returns the ticked unit at the receipt's location, out of service",
+ async () => {
+ const f = await rentalFixture({ units: 3 });
+ try {
+ await putOnRent(f, f.lineIds);
+ const [returned, kept1, kept2] = f.lineIds as [string, string, string];
+ const receiptId = await draftReceipt(f);
+ await setReceived(f, receiptId, [kept1, kept2], false);
+ await setAssetLine(f, receiptId, returned, {
+ meter: 130,
+ takeOutOfService: true,
+ outOfServiceReason: "Hydraulic leak"
+ });
+ await setReceiptLocation(f, receiptId, f.otherLocationId);
+
+ const result = await post(f, receiptId, "2026-09-20");
+ expect(result.error).toBeNull();
+
+ const line = await readLine(f, returned);
+ expect(line.status).toEqual("Returned");
+ expect(line.returnedAt).toEqual("2026-09-20");
+ expect(Number(line.meterIn)).toEqual(130);
+
+ const asset = await f.db
+ .selectFrom("fixedAsset")
+ .select("locationId")
+ .where("id", "=", f.fixedAssetIds[0]!)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ expect(asset.locationId).toEqual(f.otherLocationId);
+
+ const fleet = await f.db
+ .selectFrom("fleetAssets")
+ .select("fleetStatus")
+ .where("id", "=", f.fixedAssetIds[0]!)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ expect(fleet.fleetStatus).toEqual("In Maintenance");
+
+ const activities = await f.db
+ .selectFrom("trackedActivity")
+ .select(sql<number>`count(*)::int`.as("count"))
+ .where("companyId", "=", f.companyId)
+ .where("type", "=", "Rental Return")
+ .executeTakeFirstOrThrow();
+ expect(Number(activities.count)).toBe(1);
+
+ expect(await receiptStatus(f, receiptId)).toEqual({
+ status: "Posted",
+ postingDate: "2026-09-20"
+ });
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest("a rental receipt with no ticked unit is refused", async () => {
+ const f = await rentalFixture({ units: 3 });
+ try {
+ await putOnRent(f, f.lineIds);
+ const receiptId = await draftReceipt(f);
+ await setReceived(f, receiptId, f.lineIds, false);
+ const result = await post(f, receiptId, "2026-09-20");
+ expect(result.error?.message).toContain(
+ "Select at least one unit to return"
+ );
+ expect((await receiptStatus(f, receiptId)).status).toEqual("Draft");
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("a posted rental receipt is never voided", async () => {
+ const f = await rentalFixture({ units: 3 });
+ try {
+ await putOnRent(f, f.lineIds);
+ const receiptId = await draftReceipt(f);
+ expect((await post(f, receiptId, "2026-09-20")).error).toBeNull();
+
+ const result = await postReceipt(f.ctx, { type: "void", receiptId });
+ expect(result.error?.message).toContain(
+ "A rental return cannot be voided. Correct the unit by hand."
+ );
+ expect((await receiptStatus(f, receiptId)).status).toEqual("Posted");
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest(
+ "a unit treated as a sale needs a residual destination",
+ async () => {
+ const f = await rentalFixture({ units: 3 });
+ try {
+ await putOnRent(f, f.lineIds);
+ const saleLine = f.lineIds[0]!;
+ await makeSaleLine(f, saleLine);
+ const receiptId = await draftReceipt(f);
+ await setReceived(f, receiptId, f.lineIds.slice(1), false);
+
+ const result = await post(f, receiptId, "2026-09-20");
+ expect(result.error?.message).toContain(
+ "Choose where the returned unit goes: back to the fleet or into inventory"
+ );
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "a unit treated as a sale returns into stock at the receipt's location",
+ async () => {
+ const f = await rentalFixture({ units: 3 });
+ try {
+ await putOnRent(f, f.lineIds);
+ const saleLine = f.lineIds[0]!;
+ await makeSaleLine(f, saleLine);
+ await f.db
+ .updateTable("rentalAgreement")
+ .set({ endDate: "2026-09-20" })
+ .where("id", "=", f.agreementId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ await f.db
+ .insertInto("itemCost")
+ .values({
+ itemId: f.itemId,
+ costingMethod: "FIFO",
+ unitCost: 0,
+ companyId: f.companyId,
+ createdBy: "system"
+ })
+ .execute();
+ const receiptId = await draftReceipt(f);
+ await setReceived(f, receiptId, f.lineIds.slice(1), false);
+ await setAssetLine(f, receiptId, saleLine, {
+ residualDestination: "Inventory"
+ });
+ await setReceiptLocation(f, receiptId, f.otherLocationId);
+
+ const result = await post(f, receiptId, "2026-09-20");
+ expect(result.error).toBeNull();
+
+ const ledger = await f.db
+ .selectFrom("itemLedger")
+ .select(["entryType", "documentType", "quantity", "locationId"])
+ .where("companyId", "=", f.companyId)
+ .execute();
+ expect(
+ ledger.map((row) => ({ ...row, quantity: Number(row.quantity) }))
+ ).toEqual([
+ {
+ entryType: "Positive Adjmt.",
+ documentType: "Rental Agreement",
+ quantity: 1,
+ locationId: f.otherLocationId
+ }
+ ]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "a Pending unit comes back on its own receipt and stops billing",
+ async () => {
+ const f = await rentalFixture({ units: 2 });
+ try {
+ const [onRentLine, pendingLine] = f.lineIds as [string, string];
+ await putOnRent(f, [onRentLine]);
+
+ const first = await draftReceipt(f);
+ const pendingAssetLine = await f.db
+ .selectFrom("receiptFixedAssetLine")
+ .select("received")
+ .where("receiptId", "=", first)
+ .where("rentalAgreementLineId", "=", pendingLine)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ expect(pendingAssetLine.received).toBe(false);
+
+ expect((await post(f, first, "2026-09-20")).error).toBeNull();
+ expect((await readLine(f, onRentLine)).status).toEqual("Returned");
+ expect((await readLine(f, pendingLine)).status).toEqual("Pending");
+
+ const second = await draftReceipt(f);
+ await setReceived(f, second, [pendingLine], true);
+ expect((await post(f, second, "2026-09-25")).error).toBeNull();
+
+ const line = await readLine(f, pendingLine);
+ expect(line.status).toEqual("Returned");
+ expect(line.returnedAt).toEqual("2026-09-25");
+ const laterPending = await f.db
+ .selectFrom("rentalBillingPeriod")
+ .select("id")
+ .where("rentalAgreementLineId", "=", pendingLine)
+ .where("companyId", "=", f.companyId)
+ .where("status", "=", "Pending")
+ .where("periodStart", ">", "2026-09-25")
+ .execute();
+ expect(laterPending).toEqual([]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
diff --git a/packages/server-functions/src/post-receipt/rental-agreement.ts b/packages/server-functions/src/post-receipt/rental-agreement.ts
new file mode 100644
index 0000000000..7d7e060d0b
--- /dev/null
+++ b/packages/server-functions/src/post-receipt/rental-agreement.ts
@@ -0,0 +1,199 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// A rental receipt returns the ticked units of one Active agreement on the
+// return date, each one through the same `returnRentalUnit` the agreement's
+// own return used. A `Pending` unit can come back too: it was never
+// delivered, so its billing just stops at the return date (spec Q8).
+
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { datetime } from "@carbon/utils";
+import { InvalidInputError, NotFoundError } from "../errors";
+import {
+ insertUnitActivity,
+ lockAgreement
+} from "../post-rental-agreement/agreement";
+import {
+ type RentalUnitReturn,
+ returnRentalUnit
+} from "../post-rental-agreement/return-unit";
+import {
+ futureReturnError,
+ receiptReturnError,
+ unitLabel,
+ unitReturnValidator
+} from "../post-rental-agreement/validators";
+
+export async function postRentalReceipt(
+ db: Kysely<KyselyDatabase>,
+ args: {
+ receiptId: string;
+ companyId: string;
+ userId: string;
+ today: string;
+ postingDate?: string;
+ }
+): Promise<void> {
+ const { receiptId, companyId, userId, today } = args;
+
+ await db.transaction().execute(async (trx) => {
+ const returnedAt = args.postingDate ?? today;
+ const future = futureReturnError(returnedAt, today);
+ if (future) throw new InvalidInputError(future);
+
+ const receipt = await trx
+ .selectFrom("receipt")
+ .select(["id", "receiptId", "sourceDocumentId", "locationId"])
+ .where("id", "=", receiptId)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ if (!receipt) throw new NotFoundError("Receipt not found");
+
+ const assetLines = await trx
+ .selectFrom("receiptFixedAssetLine")
+ .select([
+ "id",
+ "rentalAgreementLineId",
+ "meter",
+ "notes",
+ "takeOutOfService",
+ "outOfServiceReason",
+ "residualDestination"
+ ])
+ .where("receiptId", "=", receiptId)
+ .where("companyId", "=", companyId)
+ .where("received", "=", true)
+ .where("rentalAgreementLineId", "is not", null)
+ .orderBy("createdAt")
+ .orderBy("id")
+ .execute();
+ if (assetLines.length === 0) {
+ throw new InvalidInputError("Select at least one unit to return");
+ }
+
+ if (!receipt.sourceDocumentId) {
+ throw new NotFoundError("Rental agreement not found");
+ }
+ const agreement = await lockAgreement(
+ trx,
+ companyId,
+ receipt.sourceDocumentId
+ );
+ if (agreement.status !== "Active") {
+ throw new InvalidInputError(
+ `Rental agreement ${agreement.rentalAgreementId} is ${agreement.status}; units are returned from an Active agreement`
+ );
+ }
+
+ const lineIds = assetLines.map((line) => line.rentalAgreementLineId!);
+ const lines = await trx
+ .selectFrom("rentalAgreementLine")
+ .select([
+ "id",
+ "rentalAgreementId",
+ "status",
+ "lessorClassification",
+ "fixedAssetId",
+ "trackedEntityId"
+ ])
+ .where("id", "in", lineIds)
+ .where("companyId", "=", companyId)
+ .execute();
+ const linesById = new Map(lines.map((line) => [line.id, line]));
+ const assetIds = lines
+ .map((line) => line.fixedAssetId)
+ .filter((id): id is string => id !== null);
+ const assets =
+ assetIds.length === 0
+ ? []
+ : await trx
+ .selectFrom("fixedAsset")
+ .select(["id", "fixedAssetId", "name"])
+ .where("id", "in", assetIds)
+ .where("companyId", "=", companyId)
+ .execute();
+ const assetsById = new Map(assets.map((asset) => [asset.id, asset]));
+
+ const units = assetLines.map((assetLine) => {
+ const lineId = assetLine.rentalAgreementLineId!;
+ const line = linesById.get(lineId);
+ const asset = line?.fixedAssetId
+ ? assetsById.get(line.fixedAssetId)
+ : undefined;
+ const label = unitLabel(asset, lineId);
+ if (!line || line.rentalAgreementId !== agreement.id) {
+ throw new NotFoundError("Rental agreement line not found");
+ }
+ const statusProblem = receiptReturnError(label, line.status);
+ if (statusProblem) throw new InvalidInputError(statusProblem);
+
+ const parsed = unitReturnValidator.safeParse({
+ rentalAgreementLineId: lineId,
+ returnedAt,
+ meterIn: assetLine.meter === null ? null : Number(assetLine.meter),
+ returnNotes: assetLine.notes,
+ takeOutOfService: assetLine.takeOutOfService,
+ outOfServiceReason: assetLine.outOfServiceReason,
+ residualDestination: assetLine.residualDestination
+ });
+ if (!parsed.success) {
+ throw new InvalidInputError(
+ `${label}: ${parsed.error.issues[0]?.message ?? "invalid return"}`
+ );
+ }
+ const unit: RentalUnitReturn = parsed.data;
+ return { line, unit };
+ });
+
+ for (const { line, unit } of units) {
+ const { fixedAssetId } = await returnRentalUnit(trx, {
+ agreement,
+ unit,
+ companyId,
+ userId,
+ today,
+ locationId: receipt.locationId ?? undefined
+ });
+
+ if (fixedAssetId && receipt.locationId) {
+ await trx
+ .updateTable("fixedAsset")
+ .set({
+ locationId: receipt.locationId,
+ updatedBy: userId,
+ updatedAt: datetime.timestamp()
+ })
+ .where("id", "=", fixedAssetId)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+
+ if (line.lessorClassification === "Rental" && line.trackedEntityId) {
+ await insertUnitActivity(trx, {
+ type: "Rental Return",
+ direction: "output",
+ sourceDocument: "Receipt",
+ sourceDocumentId: receipt.id,
+ sourceDocumentReadableId: receipt.receiptId,
+ attributes: { Receipt: receipt.id, "Rental Agreement": agreement.id },
+ trackedEntityId: line.trackedEntityId,
+ companyId,
+ userId
+ });
+ }
+ }
+
+ await trx
+ .updateTable("receipt")
+ .set({
+ status: "Posted",
+ postingDate: returnedAt,
+ postedBy: userId
+ })
+ .where("id", "=", receiptId)
+ .where("companyId", "=", companyId)
+ .execute();
+ });
+}
diff --git a/packages/server-functions/src/post-rental-agreement/__snapshots__/return-unit.test.ts.snap b/packages/server-functions/src/post-rental-agreement/__snapshots__/return-unit.test.ts.snap
new file mode 100644
index 0000000000..49f178e251
--- /dev/null
+++ b/packages/server-functions/src/post-rental-agreement/__snapshots__/return-unit.test.ts.snap
@@ -0,0 +1,32 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`an early return of an Advance unit re-cuts its periods 1`] = `
+{
+ "line": {
+ "returnedAt": "2026-09-20",
+ "status": "Returned",
+ },
+ "periods": [
+ {
+ "amount": 300,
+ "days": 30,
+ "dueOn": "2026-09-01",
+ "isAdjustment": false,
+ "periodEnd": "2026-09-30",
+ "periodStart": "2026-09-01",
+ "rateUnitApplied": null,
+ "status": "Invoiced",
+ },
+ {
+ "amount": -100,
+ "days": 20,
+ "dueOn": "2026-09-20",
+ "isAdjustment": true,
+ "periodEnd": "2026-09-30",
+ "periodStart": "2026-09-01",
+ "rateUnitApplied": "Month",
+ "status": "Pending",
+ },
+ ],
+}
+`;
diff --git a/packages/server-functions/src/post-rental-agreement/agreement.ts b/packages/server-functions/src/post-rental-agreement/agreement.ts
new file mode 100644
index 0000000000..7a20e00fcd
--- /dev/null
+++ b/packages/server-functions/src/post-rental-agreement/agreement.ts
@@ -0,0 +1,332 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Shared by the rental agreement actions and the rental documents: the
+// agreement row and its lock, billing-period rows, and the 'Lease' journal
+// and traceability writers.
+
+import type { Database } from "@carbon/database";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { round } from "@carbon/database/precision";
+import {
+ buildJournalLineDimensionInserts,
+ type PeriodSpec
+} from "@carbon/utils";
+import { sql, type Transaction } from "kysely";
+import { nanoid } from "nanoid";
+import { InvalidInputError, NotFoundError } from "../errors";
+import { getCurrentAccountingPeriod } from "../lib/get-accounting-period";
+import { createAdjustmentJournal } from "../lib/post-adjustment";
+import type { PostingLine } from "./lessor";
+
+export type Db = Kysely<KyselyDatabase>;
+export type Trx = Transaction<KyselyDatabase>;
+export type Enums = Database["public"]["Enums"];
+
+export type AgreementRow = {
+ id: string;
+ rentalAgreementId: string;
+ status: Enums["rentalAgreementStatus"];
+ customerId: string;
+ locationId: string;
+ startDate: string;
+ endDate: string | null;
+ billingCycle: Enums["rentalBillingCycle"];
+ billingTiming: Enums["rentalBillingTiming"];
+ currencyCode: string;
+ discountRate: number;
+ ownershipTransfers: boolean;
+ specializedAsset: boolean;
+ purchaseOptionAmount: number | null;
+ purchaseOptionReasonablyCertain: boolean;
+};
+
+// Re-read under the caller's company and lock: the id comes from the payload,
+// and the permission check proves nothing about it. The lock serializes two
+// actions on one agreement (a double-clicked Activate, a return racing a
+// cancel). DATE columns decode to JS Dates through the driver, so they are
+// selected as text — the billing math works on `YYYY-MM-DD` strings.
+export async function lockAgreement(
+ trx: Trx,
+ companyId: string,
+ id: string
+): Promise<AgreementRow> {
+ const agreement = await trx
+ .selectFrom("rentalAgreement")
+ .select([
+ "id",
+ "rentalAgreementId",
+ "status",
+ "customerId",
+ "locationId",
+ sql<string>`"startDate"::text`.as("startDate"),
+ sql<string | null>`"endDate"::text`.as("endDate"),
+ "billingCycle",
+ "billingTiming",
+ "currencyCode",
+ "discountRate",
+ "ownershipTransfers",
+ "specializedAsset",
+ "purchaseOptionAmount",
+ "purchaseOptionReasonablyCertain"
+ ])
+ .where("id", "=", id)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ if (!agreement) throw new NotFoundError("Rental agreement not found");
+ return {
+ ...agreement,
+ discountRate: Number(agreement.discountRate),
+ purchaseOptionAmount:
+ agreement.purchaseOptionAmount === null
+ ? null
+ : Number(agreement.purchaseOptionAmount)
+ };
+}
+
+// Billing periods are invoiced, so they are priced at the agreement
+// currency's settlement precision — the group's `currency.decimalPlaces`,
+// never a literal.
+export async function currencyDecimals(
+ trx: Trx,
+ companyId: string,
+ currencyCode: string
+): Promise<number> {
+ const currency = await trx
+ .selectFrom("currency")
+ .innerJoin("company", "company.companyGroupId", "currency.companyGroupId")
+ .select("currency.decimalPlaces")
+ .where("company.id", "=", companyId)
+ .where("currency.code", "=", currencyCode)
+ .executeTakeFirst();
+ if (!currency || currency.decimalPlaces === null) {
+ throw new InvalidInputError(
+ `Currency ${currencyCode} is not set up for this company`
+ );
+ }
+ return currency.decimalPlaces;
+}
+
+export function billingPeriodRow(
+ spec: PeriodSpec,
+ rentalAgreementLineId: string,
+ companyId: string,
+ userId: string
+) {
+ return {
+ rentalAgreementLineId,
+ periodStart: spec.periodStart,
+ periodEnd: spec.periodEnd,
+ days: spec.days,
+ amount: spec.amount,
+ rateUnitApplied: spec.rateUnitApplied,
+ isAdjustment: spec.isAdjustment,
+ dueOn: spec.dueOn,
+ status: "Pending" as const,
+ companyId,
+ createdBy: userId
+ };
+}
+
+// What the 'Lease' journals need, resolved once per request inside the
+// transaction. The period resolver reuses the caller's transaction and locks
+// the period row, so a close cannot slip in between.
+export type LeaseAccounting = {
+ accountingPeriodId: string;
+ accounts: {
+ netInvestmentInLeasesAccount: string;
+ leaseRevenueAccount: string;
+ leaseInterestIncomeAccount: string;
+ costOfGoodsSoldAccount: string;
+ finishedGoodsAccount: string;
+ rawMaterialsAccount: string;
+ };
+ // active dimensions for the company group, entityType → dimension id
+ dimensionMap: Map<string, string>;
+};
+
+export async function loadLeaseAccounting(
+ trx: Trx,
+ args: { companyId: string; companyGroupId: string | null; today: string }
+): Promise<LeaseAccounting> {
+ const { companyId } = args;
+ const defaults = await trx
+ .selectFrom("accountDefault")
+ .select([
+ "netInvestmentInLeasesAccount",
+ "leaseRevenueAccount",
+ "leaseInterestIncomeAccount",
+ "costOfGoodsSoldAccount",
+ "finishedGoodsAccount",
+ "rawMaterialsAccount"
+ ])
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!defaults) throw new Error("Error getting account defaults");
+ const {
+ netInvestmentInLeasesAccount,
+ leaseRevenueAccount,
+ leaseInterestIncomeAccount
+ } = defaults;
+ if (
+ !netInvestmentInLeasesAccount ||
+ !leaseRevenueAccount ||
+ !leaseInterestIncomeAccount
+ ) {
+ throw new InvalidInputError(
+ "Set the Net Investment in Leases, Lease Revenue and Lease Interest Income accounts in the account defaults before activating a rental treated as a sale"
+ );
+ }
+
+ // Dimensions are configured per company group; a company outside one
+ // tags nothing.
+ const dimensions =
+ args.companyGroupId === null
+ ? []
+ : await trx
+ .selectFrom("dimension")
+ .select(["id", "entityType"])
+ .where("companyGroupId", "=", args.companyGroupId)
+ .where("active", "=", true)
+ .where("entityType", "in", ["Customer", "Item", "Location"])
+ .execute();
+
+ const accountingPeriodId = await getCurrentAccountingPeriod(
+ companyId,
+ trx,
+ args.today
+ );
+
+ return {
+ accountingPeriodId,
+ accounts: {
+ netInvestmentInLeasesAccount,
+ leaseRevenueAccount,
+ leaseInterestIncomeAccount,
+ costOfGoodsSoldAccount: defaults.costOfGoodsSoldAccount,
+ finishedGoodsAccount: defaults.finishedGoodsAccount,
+ rawMaterialsAccount: defaults.rawMaterialsAccount
+ },
+ dimensionMap: new Map(
+ dimensions.map((dimension) => [dimension.entityType, dimension.id])
+ )
+ };
+}
+
+// One posted 'Lease' journal from already-balanced lines. Every line carries
+// the agreement as its document and the agreement line as the line
+// reference, tagged with the Customer / Item / Location dimensions the
+// company group has active.
+export async function postLeaseJournal(
+ trx: Trx,
+ args: {
+ accounting: LeaseAccounting;
+ companyId: string;
+ userId: string;
+ postingDate: string;
+ description: string;
+ lines: PostingLine[];
+ rentalAgreementId: string;
+ rentalAgreementLineId: string;
+ tags: { customerId: string; itemId: string; locationId: string };
+ }
+): Promise<string> {
+ const { accounting, companyId, userId } = args;
+ const journalId = await createAdjustmentJournal(trx, {
+ companyId,
+ accountingPeriodId: accounting.accountingPeriodId,
+ description: args.description,
+ postingDate: args.postingDate,
+ userId,
+ sourceType: "Lease"
+ });
+
+ const journalLineReference = nanoid();
+ const journalLines = await trx
+ .insertInto("journalLine")
+ .values(
+ args.lines.map((line) => ({
+ journalId,
+ accountId: line.accountId,
+ description: line.description,
+ amount: round(line.amount),
+ quantity: 1,
+ documentType: "Rental Agreement" as const,
+ documentId: args.rentalAgreementId,
+ documentLineReference: args.rentalAgreementLineId,
+ journalLineReference,
+ companyId
+ }))
+ )
+ .returning(["id"])
+ .execute();
+
+ const dimensionInserts = buildJournalLineDimensionInserts({
+ journalLineIds: journalLines.map((line) => line.id),
+ meta: journalLines.map(() => args.tags),
+ dimensionMap: accounting.dimensionMap,
+ companyId
+ });
+ if (dimensionInserts.length > 0) {
+ await trx
+ .insertInto("journalLineDimension")
+ .values(dimensionInserts)
+ .execute();
+ }
+
+ return journalId;
+}
+
+// The traceability graph records the lease as the consumer of the unit at
+// commencement, and as its producer when it comes back to stock.
+export async function insertUnitActivity(
+ trx: Trx,
+ args: {
+ type:
+ | "Lease Commencement"
+ | "Return to Inventory"
+ | "Capitalize"
+ | "Rental Delivery"
+ | "Rental Return"
+ | "Void Shipment";
+ direction: "input" | "output";
+ sourceDocument: "Rental Agreement" | "Fixed Asset" | "Shipment" | "Receipt";
+ sourceDocumentId: string;
+ sourceDocumentReadableId: string;
+ attributes: Record<string, string>;
+ trackedEntityId: string;
+ companyId: string;
+ userId: string;
+ }
+): Promise<void> {
+ const activityId = nanoid();
+ await trx
+ .insertInto("trackedActivity")
+ .values({
+ id: activityId,
+ type: args.type,
+ sourceDocument: args.sourceDocument,
+ sourceDocumentId: args.sourceDocumentId,
+ sourceDocumentReadableId: args.sourceDocumentReadableId,
+ attributes: args.attributes,
+ companyId: args.companyId,
+ createdBy: args.userId
+ })
+ .execute();
+ await trx
+ .insertInto(
+ args.direction === "input"
+ ? "trackedActivityInput"
+ : "trackedActivityOutput"
+ )
+ .values({
+ trackedActivityId: activityId,
+ trackedEntityId: args.trackedEntityId,
+ quantity: 1,
+ companyId: args.companyId,
+ createdBy: args.userId
+ })
+ .execute();
+}
diff --git a/packages/server-functions/src/post-rental-agreement/close.test.ts b/packages/server-functions/src/post-rental-agreement/close.test.ts
new file mode 100644
index 0000000000..8d51fd892c
--- /dev/null
+++ b/packages/server-functions/src/post-rental-agreement/close.test.ts
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Closing a rental agreement against the live database: a rental document
+// still open refuses the close and names the document.
+
+import { expect } from "vitest";
+import create from "../create";
+import { databaseTest } from "../local-database-test-fixture";
+import postRentalAgreement from "./index";
+import { rentalFixture } from "./rental-test-fixture";
+
+databaseTest(
+ "an open rental receipt refuses the agreement's close",
+ async () => {
+ const f = await rentalFixture();
+ try {
+ await f.db
+ .updateTable("rentalAgreementLine")
+ .set({ status: "On Rent", deliveredAt: "2026-09-01" })
+ .where("id", "=", f.lineIds[0]!)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ const receipt = await create(f.ctx, {
+ type: "receiptFromRentalAgreement",
+ rentalAgreementId: f.agreementId
+ });
+ expect(receipt.error).toBeNull();
+
+ const result = await postRentalAgreement(f.ctx, {
+ type: "close",
+ rentalAgreementId: f.agreementId
+ });
+ expect(result.error?.message).toContain("Receipt RCV-");
+ expect(result.error?.message).toContain("is still open");
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
diff --git a/packages/server-functions/src/post-rental-agreement/index.ts b/packages/server-functions/src/post-rental-agreement/index.ts
index 09dc54396a..848c634398 100644
--- a/packages/server-functions/src/post-rental-agreement/index.ts
+++ b/packages/server-functions/src/post-rental-agreement/index.ts
@@ -2,33 +2,31 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import { type Database, getCompanyTimeZone, type Json } from "@carbon/database";
-import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { getCompanyTimeZone, type Json } from "@carbon/database";
import { toJson } from "@carbon/database/json";
-import { round } from "@carbon/database/precision";
-import { getNextSequence } from "@carbon/database/sequence";
import {
- buildJournalLineDimensionInserts,
buildLessorSchedule,
datetime,
- type ExistingBillingPeriod,
generateRentalBillingPeriods,
type PeriodSpec
} from "@carbon/utils";
-import { sql, type Transaction } from "kysely";
-import { nanoid } from "nanoid";
+import { sql } from "kysely";
import { defineServerFn } from "../define-server-fn";
import { InvalidInputError, NotFoundError } from "../errors";
-import { getCurrentAccountingPeriod } from "../lib/get-accounting-period";
-import { resolveInventoryAccount } from "../lib/get-posting-group";
import {
- bookAdjustment,
- createAdjustmentJournal
-} from "../lib/post-adjustment";
+ type AgreementRow,
+ billingPeriodRow,
+ currencyDecimals,
+ type Db,
+ insertUnitActivity,
+ loadLeaseAccounting,
+ lockAgreement,
+ postLeaseJournal,
+ type Trx
+} from "./agreement";
import {
activationBillingThrough,
buildCommencementLines,
- buildResidualReturnLines,
type ClassificationInputs,
certainPurchaseOption,
classifyRentalLine,
@@ -37,24 +35,23 @@ import {
type LeasePaymentTerms,
leaseClosingTarget,
leasePaymentTerms,
- netInvestmentAt,
- type PostingLine,
salesTypeRequirementError,
- salesTypeReturnError,
scheduleBillingPeriods,
settledClassification
} from "./lessor";
+import { returnRentalUnit } from "./return-unit";
import {
cancelBlocker,
closeBlocker,
- futureReturnError,
+ futureReleaseError,
LIVE_LINE_STATUSES,
+ openRentalDocumentBlocker,
payloadValidator,
RENTABLE_ASSET_STATUSES,
- RETURNABLE_LINE_STATUSES,
type RentalAgreementPayload,
- type ResidualDestination,
+ releaseBlocker,
unitAvailabilityError,
+ unitLabel,
unpricedUnitError
} from "./validators";
@@ -69,328 +66,18 @@ import {
// 'Lease' journal books net investment / COGS / lease revenue, and
// the effective-interest schedule plus its Interest recognition
// rows are written.
-// return a unit comes back, never after today: an operating line's
-// billing is re-cut at the return date (later Pending periods
-// dropped, the current one shortened, an advance-billed period
-// credited), optionally straight to maintenance. A sales-type
-// line's billing is its term and is left alone; the unit's closing
-// net investment (the schedule's balance on the return date) moves
-// into a new Rental Fleet asset or into stock.
+// A unit comes back through a rental receipt (`post-receipt`), which calls `returnRentalUnit`.
+// release a Pending unit that never left the yard stops billing at the release date and is free again.
// close Active → Closed once every unit is back and everything billed.
// cancel Draft, or Active with nothing on rent / billed / recognized /
// commenced → Cancelled; the Pending lines are deleted so their
// units are free.
-type Db = Kysely<KyselyDatabase>;
-type Trx = Transaction<KyselyDatabase>;
-type Enums = Database["public"]["Enums"];
-
// Business-validation failures are 400s (InvalidInputError) with the exact
// message the app shows; a referenced record the caller's company does not own
// is a 404 (NotFoundError); everything else is a 500 so real outages surface in
// monitoring.
-type AgreementRow = {
- id: string;
- rentalAgreementId: string;
- status: Enums["rentalAgreementStatus"];
- customerId: string;
- locationId: string;
- startDate: string;
- endDate: string | null;
- billingCycle: Enums["rentalBillingCycle"];
- billingTiming: Enums["rentalBillingTiming"];
- currencyCode: string;
- discountRate: number;
- ownershipTransfers: boolean;
- specializedAsset: boolean;
- purchaseOptionAmount: number | null;
- purchaseOptionReasonablyCertain: boolean;
-};
-
-// Re-read under the caller's company and lock: the id comes from the payload,
-// and the permission check proves nothing about it. The lock serializes two
-// actions on one agreement (a double-clicked Activate, a return racing a
-// cancel). DATE columns decode to JS Dates through the driver, so they are
-// selected as text — the billing math works on `YYYY-MM-DD` strings.
-async function lockAgreement(
- trx: Trx,
- companyId: string,
- id: string
-): Promise<AgreementRow> {
- const agreement = await trx
- .selectFrom("rentalAgreement")
- .select([
- "id",
- "rentalAgreementId",
- "status",
- "customerId",
- "locationId",
- sql<string>`"startDate"::text`.as("startDate"),
- sql<string | null>`"endDate"::text`.as("endDate"),
- "billingCycle",
- "billingTiming",
- "currencyCode",
- "discountRate",
- "ownershipTransfers",
- "specializedAsset",
- "purchaseOptionAmount",
- "purchaseOptionReasonablyCertain"
- ])
- .where("id", "=", id)
- .where("companyId", "=", companyId)
- .forUpdate()
- .executeTakeFirst();
- if (!agreement) throw new NotFoundError("Rental agreement not found");
- return {
- ...agreement,
- discountRate: Number(agreement.discountRate),
- purchaseOptionAmount:
- agreement.purchaseOptionAmount === null
- ? null
- : Number(agreement.purchaseOptionAmount)
- };
-}
-
-// Billing periods are invoiced, so they are priced at the agreement
-// currency's settlement precision — the group's `currency.decimalPlaces`,
-// never a literal.
-async function currencyDecimals(
- trx: Trx,
- companyId: string,
- currencyCode: string
-): Promise<number> {
- const currency = await trx
- .selectFrom("currency")
- .innerJoin("company", "company.companyGroupId", "currency.companyGroupId")
- .select("currency.decimalPlaces")
- .where("company.id", "=", companyId)
- .where("currency.code", "=", currencyCode)
- .executeTakeFirst();
- if (!currency || currency.decimalPlaces === null) {
- throw new InvalidInputError(
- `Currency ${currencyCode} is not set up for this company`
- );
- }
- return currency.decimalPlaces;
-}
-
-function billingPeriodRow(
- spec: PeriodSpec,
- rentalAgreementLineId: string,
- companyId: string,
- userId: string
-) {
- return {
- rentalAgreementLineId,
- periodStart: spec.periodStart,
- periodEnd: spec.periodEnd,
- days: spec.days,
- amount: spec.amount,
- rateUnitApplied: spec.rateUnitApplied,
- isAdjustment: spec.isAdjustment,
- dueOn: spec.dueOn,
- status: "Pending" as const,
- companyId,
- createdBy: userId
- };
-}
-
-// What the 'Lease' journals need, resolved once per request inside the
-// transaction. The period resolver reuses the caller's transaction and locks
-// the period row, so a close cannot slip in between.
-type LeaseAccounting = {
- accountingPeriodId: string;
- accounts: {
- netInvestmentInLeasesAccount: string;
- leaseRevenueAccount: string;
- leaseInterestIncomeAccount: string;
- costOfGoodsSoldAccount: string;
- finishedGoodsAccount: string;
- rawMaterialsAccount: string;
- };
- // active dimensions for the company group, entityType → dimension id
- dimensionMap: Map<string, string>;
-};
-
-async function loadLeaseAccounting(
- trx: Trx,
- args: { companyId: string; companyGroupId: string | null; today: string }
-): Promise<LeaseAccounting> {
- const { companyId } = args;
- const defaults = await trx
- .selectFrom("accountDefault")
- .select([
- "netInvestmentInLeasesAccount",
- "leaseRevenueAccount",
- "leaseInterestIncomeAccount",
- "costOfGoodsSoldAccount",
- "finishedGoodsAccount",
- "rawMaterialsAccount"
- ])
- .where("companyId", "=", companyId)
- .executeTakeFirst();
- if (!defaults) throw new Error("Error getting account defaults");
- const {
- netInvestmentInLeasesAccount,
- leaseRevenueAccount,
- leaseInterestIncomeAccount
- } = defaults;
- if (
- !netInvestmentInLeasesAccount ||
- !leaseRevenueAccount ||
- !leaseInterestIncomeAccount
- ) {
- throw new InvalidInputError(
- "Set the Net Investment in Leases, Lease Revenue and Lease Interest Income accounts in the account defaults before activating a rental treated as a sale"
- );
- }
-
- // Dimensions are configured per company group; a company outside one
- // tags nothing.
- const dimensions =
- args.companyGroupId === null
- ? []
- : await trx
- .selectFrom("dimension")
- .select(["id", "entityType"])
- .where("companyGroupId", "=", args.companyGroupId)
- .where("active", "=", true)
- .where("entityType", "in", ["Customer", "Item", "Location"])
- .execute();
-
- const accountingPeriodId = await getCurrentAccountingPeriod(
- companyId,
- trx,
- args.today
- );
-
- return {
- accountingPeriodId,
- accounts: {
- netInvestmentInLeasesAccount,
- leaseRevenueAccount,
- leaseInterestIncomeAccount,
- costOfGoodsSoldAccount: defaults.costOfGoodsSoldAccount,
- finishedGoodsAccount: defaults.finishedGoodsAccount,
- rawMaterialsAccount: defaults.rawMaterialsAccount
- },
- dimensionMap: new Map(
- dimensions.map((dimension) => [dimension.entityType, dimension.id])
- )
- };
-}
-
-// One posted 'Lease' journal from already-balanced lines. Every line carries
-// the agreement as its document and the agreement line as the line
-// reference, tagged with the Customer / Item / Location dimensions the
-// company group has active.
-async function postLeaseJournal(
- trx: Trx,
- args: {
- accounting: LeaseAccounting;
- companyId: string;
- userId: string;
- postingDate: string;
- description: string;
- lines: PostingLine[];
- rentalAgreementId: string;
- rentalAgreementLineId: string;
- tags: { customerId: string; itemId: string; locationId: string };
- }
-): Promise<string> {
- const { accounting, companyId, userId } = args;
- const journalId = await createAdjustmentJournal(trx, {
- companyId,
- accountingPeriodId: accounting.accountingPeriodId,
- description: args.description,
- postingDate: args.postingDate,
- userId,
- sourceType: "Lease"
- });
-
- const journalLineReference = nanoid();
- const journalLines = await trx
- .insertInto("journalLine")
- .values(
- args.lines.map((line) => ({
- journalId,
- accountId: line.accountId,
- description: line.description,
- amount: round(line.amount),
- quantity: 1,
- documentType: "Rental Agreement" as const,
- documentId: args.rentalAgreementId,
- documentLineReference: args.rentalAgreementLineId,
- journalLineReference,
- companyId
- }))
- )
- .returning(["id"])
- .execute();
-
- const dimensionInserts = buildJournalLineDimensionInserts({
- journalLineIds: journalLines.map((line) => line.id),
- meta: journalLines.map(() => args.tags),
- dimensionMap: accounting.dimensionMap,
- companyId
- });
- if (dimensionInserts.length > 0) {
- await trx
- .insertInto("journalLineDimension")
- .values(dimensionInserts)
- .execute();
- }
-
- return journalId;
-}
-
-// The traceability graph records the lease as the consumer of the unit at
-// commencement, and as its producer when it comes back to stock.
-async function insertUnitActivity(
- trx: Trx,
- args: {
- type: "Lease Commencement" | "Return to Inventory" | "Capitalize";
- direction: "input" | "output";
- sourceDocument: "Rental Agreement" | "Fixed Asset";
- sourceDocumentId: string;
- sourceDocumentReadableId: string;
- attributes: Record<string, string>;
- trackedEntityId: string;
- companyId: string;
- userId: string;
- }
-): Promise<void> {
- const activityId = nanoid();
- await trx
- .insertInto("trackedActivity")
- .values({
- id: activityId,
- type: args.type,
- sourceDocument: args.sourceDocument,
- sourceDocumentId: args.sourceDocumentId,
- sourceDocumentReadableId: args.sourceDocumentReadableId,
- attributes: args.attributes,
- companyId: args.companyId,
- createdBy: args.userId
- })
- .execute();
- await trx
- .insertInto(
- args.direction === "input"
- ? "trackedActivityInput"
- : "trackedActivityOutput"
- )
- .values({
- trackedActivityId: activityId,
- trackedEntityId: args.trackedEntityId,
- quantity: 1,
- companyId: args.companyId,
- createdBy: args.userId
- })
- .execute();
-}
-
type ActivationPlan = {
lineId: string;
name: string;
@@ -1040,15 +727,13 @@ async function commenceSalesTypeLines(
return result;
}
-async function returnUnit(
+async function releaseUnit(
{ db, companyId, userId }: Scope,
- payload: Extract<RentalAgreementPayload, { type: "return" }>,
+ payload: Extract<RentalAgreementPayload, { type: "release" }>,
today: string
): Promise<{ id: string }> {
- const { returnedAt } = payload;
- const future = futureReturnError(returnedAt, today);
+ const future = futureReleaseError(payload.returnedAt, today);
if (future) throw new InvalidInputError(future);
-
return db.transaction().execute(async (trx) => {
const agreement = await lockAgreement(
trx,
@@ -1057,601 +742,87 @@ async function returnUnit(
);
if (agreement.status !== "Active") {
throw new InvalidInputError(
- `Rental agreement ${agreement.rentalAgreementId} is ${agreement.status}; units are returned from an Active agreement`
+ `Rental agreement ${agreement.rentalAgreementId} is ${agreement.status}; units are released from an Active agreement`
);
}
const line = await trx
.selectFrom("rentalAgreementLine")
- .select([
- "id",
- "status",
- "fixedAssetId",
- "itemId",
- "trackedEntityId",
- "rateUnit",
- "rate",
- "lessorClassification",
- "initialNetInvestment",
- sql<string | null>`"deliveredAt"::text`.as("deliveredAt")
- ])
+ .select(["id", "status", "lessorClassification", "fixedAssetId"])
.where("id", "=", payload.rentalAgreementLineId)
.where("rentalAgreementId", "=", agreement.id)
.where("companyId", "=", companyId)
.forUpdate()
.executeTakeFirst();
if (!line) throw new NotFoundError("Rental agreement line not found");
- if (!RETURNABLE_LINE_STATUSES.has(line.status)) {
- throw new InvalidInputError(
- `The unit is ${line.status}; only a Pending or On Rent unit can be returned`
- );
- }
- // `YYYY-MM-DD` compares chronologically as text.
- if (returnedAt < agreement.startDate) {
- throw new InvalidInputError(
- `The return date is before the agreement starts (${agreement.startDate})`
- );
- }
- if (line.deliveredAt && returnedAt < line.deliveredAt) {
- throw new InvalidInputError(
- `The return date is before the unit was delivered (${line.deliveredAt})`
- );
- }
- // A sales-type unit is off the books until it comes back: where it goes
- // (fleet or stock) is the caller's choice and has to be made. An
- // operating return ignores the destination.
- const salesTypeProblem = salesTypeReturnError({
- classification: line.lessorClassification,
- residualDestination: payload.residualDestination,
- returnedAt,
- endDate: agreement.endDate,
- takeOutOfService: !!payload.takeOutOfService
- });
- if (salesTypeProblem) throw new InvalidInputError(salesTypeProblem);
- const salesType = line.lessorClassification === "Sale";
- if (salesType && line.initialNetInvestment === null) {
- throw new InvalidInputError(
- "This line is treated as a sale but has no commencement booked; it cannot be returned"
- );
- }
-
- const now = datetime.timestamp();
-
- // A sales-type line's billing is its term, cut in full at activation, and
- // the unit comes back only on or after the end date — there is nothing to
- // re-cut. Regenerating would cut holdover periods past the end date that
- // bill rent against a net investment the schedule has already closed.
- if (!salesType) {
- const existingRows = await trx
- .selectFrom("rentalBillingPeriod")
- .select([
- sql<string>`"periodStart"::text`.as("periodStart"),
- sql<string>`"periodEnd"::text`.as("periodEnd"),
- "amount",
- "status",
- "isAdjustment"
- ])
- .where("rentalAgreementLineId", "=", line.id)
- .where("companyId", "=", companyId)
- .forUpdate()
- .execute();
- const existing: ExistingBillingPeriod[] = existingRows.map((row) => ({
- periodStart: row.periodStart,
- periodEnd: row.periodEnd,
- amount: Number(row.amount),
- status: row.status,
- isAdjustment: row.isAdjustment
- }));
-
- const plan = generateRentalBillingPeriods({
- cycle: agreement.billingCycle,
- timing: agreement.billingTiming,
- rateUnit: line.rateUnit,
- rate: Number(line.rate),
- startDate: agreement.startDate,
- endDate: agreement.endDate,
- returnedAt,
- through: returnedAt,
- existing,
- decimals: await currencyDecimals(trx, companyId, agreement.currencyCode)
- });
-
- // The generation stops at the return, so every unbilled period starting
- // after it is gone. An invoiced one is credited through `adjustments`.
- await trx
- .deleteFrom("rentalBillingPeriod")
- .where("rentalAgreementLineId", "=", line.id)
- .where("companyId", "=", companyId)
- .where("status", "=", "Pending")
- .where("isAdjustment", "=", false)
- .where("periodStart", ">", returnedAt)
- .execute();
- // The unbilled period the return falls inside ends on the return date.
- for (const recut of plan.recut) {
- await trx
- .updateTable("rentalBillingPeriod")
- .set({
- periodEnd: recut.periodEnd,
- days: recut.days,
- amount: recut.amount,
- rateUnitApplied: recut.rateUnitApplied,
- dueOn: recut.dueOn,
- updatedBy: userId,
- updatedAt: now
- })
- .where("rentalAgreementLineId", "=", line.id)
- .where("companyId", "=", companyId)
- .where("periodStart", "=", recut.periodStart)
- .where("isAdjustment", "=", false)
- .where("status", "=", "Pending")
- .execute();
- }
-
- // `create` is non-empty when the return falls in a period not generated
- // yet; `adjustments` credits advance billing past the return.
- const inserts = [...plan.create, ...plan.adjustments].map((spec) =>
- billingPeriodRow(spec, line.id, companyId, userId)
- );
- if (inserts.length > 0) {
- await trx.insertInto("rentalBillingPeriod").values(inserts).execute();
- }
- }
-
- await trx
- .updateTable("rentalAgreementLine")
- .set({
- status: "Returned",
- returnedAt,
- meterIn: payload.meterIn ?? null,
- returnNotes: payload.returnNotes ?? null,
- updatedBy: userId,
- updatedAt: now
- })
- .where("id", "=", line.id)
- .where("companyId", "=", companyId)
- .execute();
-
- // A sales-type unit's closing net investment moves back onto the books
- // — as a new Rental Fleet asset or into stock. The asset the line names
- // was disposed at commencement, so a fleet return's unit is the new one.
- let fleetAssetId = line.fixedAssetId;
- if (salesType) {
- const residual = await returnResidual(trx, {
- agreement,
- line: {
- id: line.id,
- itemId: line.itemId,
- fixedAssetId: line.fixedAssetId,
- trackedEntityId: line.trackedEntityId,
- initialNetInvestment: Number(line.initialNetInvestment)
- },
- destination: payload.residualDestination as ResidualDestination,
- returnedAt,
- companyId,
- userId,
- today
- });
- fleetAssetId = residual.fixedAssetId;
- }
-
- // Straight to maintenance: the fleet status reads In Maintenance and the
- // unit cannot go back on rent until it is returned to service.
- if (payload.takeOutOfService && fleetAssetId) {
- await trx
- .updateTable("fixedAsset")
- .set({
- outOfServiceSince: returnedAt,
- outOfServiceReason: (payload.outOfServiceReason ?? "").trim(),
- updatedBy: userId,
- updatedAt: now
- })
- .where("id", "=", fleetAssetId)
- .where("companyId", "=", companyId)
- .execute();
- }
-
- return { id: agreement.id };
- });
-}
-
-/**
- * End of a sales-type term with the unit coming back (spec §4): the closing
- * net investment — the schedule's balance on the return date
- * (`netInvestmentAt`: the closing of the last schedule line dated on or
- * before it, which at or after the end date is the closing target; the
- * initial NI when the line has no schedule) — leaves Net Investment in
- * Leases for either
- *
- * Fleet a new asset in the class named "Rental Fleet" (else the class
- * the unit left at commencement) at that amount, with a Posted
- * Capitalization transfer; Dr class asset / Cr net investment.
- * The unit is consumed into the new asset.
- * Inventory stock at that unit cost (`bookAdjustment` +1, no variance
- * journal); Dr the item's inventory account / Cr net investment.
- * The unit is Available again.
- *
- * The schedule lines and Interest rows dated on or before the return stay,
- * posted or not: they are the term the lease ran, the closing already counts
- * them, and their interest posts through recognition runs after the return,
- * bringing Net Investment in Leases to zero. Only what is dated AFTER the
- * return is dropped — nothing accrues on a lease that has ended (normally
- * nothing, since a unit comes back on or after the end date). With
- * accounting off, the asset / stock moves identically and no journal is
- * posted.
- */
-async function returnResidual(
- trx: Trx,
- args: {
- agreement: AgreementRow;
- line: {
- id: string;
- itemId: string;
- fixedAssetId: string | null;
- trackedEntityId: string | null;
- initialNetInvestment: number;
- };
- destination: ResidualDestination;
- returnedAt: string;
- companyId: string;
- userId: string;
- today: string;
- }
-): Promise<{ fixedAssetId: string | null }> {
- const { agreement, line, destination, returnedAt, companyId, userId, today } =
- args;
-
- // A Draft recognition run that already claimed interest dated after the
- // return would be left pointing at deleted rows. Interest on or before the
- // return is kept, so a run holding it is no obstacle.
- const claimed = await trx
- .selectFrom("revenueRecognitionSchedule")
- .select(sql<number>`count(*)::int`.as("count"))
- .where("rentalAgreementLineId", "=", line.id)
- .where("companyId", "=", companyId)
- .where("type", "=", "Interest")
- .where("status", "=", "Planned")
- .where("scheduledDate", ">", returnedAt)
- .where("runLineId", "is not", null)
- .executeTakeFirstOrThrow();
- if (Number(claimed.count) > 0) {
- throw new InvalidInputError(
- "A draft revenue recognition run includes this lease's interest; post or delete the run before returning the unit"
- );
- }
-
- const schedule = await trx
- .selectFrom("rentalLeaseScheduleLine")
- .select([
- sql<string>`"periodDate"::text`.as("periodDate"),
- "closingNetInvestment"
- ])
- .where("rentalAgreementLineId", "=", line.id)
- .where("companyId", "=", companyId)
- .execute();
- const closing = netInvestmentAt({
- initialNetInvestment: line.initialNetInvestment,
- schedule: schedule.map((row) => ({
- periodDate: row.periodDate,
- closingNetInvestment: Number(row.closingNetInvestment)
- })),
- asOf: returnedAt
- });
- if (closing < 0) {
- throw new InvalidInputError(
- `The lease's closing net investment is negative (${closing})`
- );
- }
-
- // Sequential on purpose: one transaction is one connection.
- const company = await trx
- .selectFrom("company")
- .select("companyGroupId")
- .where("id", "=", companyId)
- .executeTakeFirstOrThrow();
- const settings = await trx
- .selectFrom("companySettings")
- .select("accountingEnabled")
- .where("id", "=", companyId)
- .executeTakeFirstOrThrow();
- const item = await trx
- .selectFrom("item")
- .select([
- "id",
- "name",
- "readableId",
- "itemTrackingType",
- "replenishmentSystem"
- ])
- .where("id", "=", line.itemId)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
- const itemCost = await trx
- .selectFrom("itemCost")
- .select(["costingMethod", "unitCost", "standardCost", "itemPostingGroupId"])
- .where("itemId", "=", line.itemId)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
- // The serial left the line's asset at commencement when the line named
- // only the asset (as `commenceSalesTypeLines` resolves it), so a line
- // without its own serial takes the disposed asset's.
- const disposedAsset =
- !line.trackedEntityId && line.fixedAssetId
+ const asset = line.fixedAssetId
? await trx
.selectFrom("fixedAsset")
- .select("trackedEntityId")
+ .select(["fixedAssetId", "name"])
.where("id", "=", line.fixedAssetId)
.where("companyId", "=", companyId)
.executeTakeFirst()
: undefined;
- const trackedEntityId =
- line.trackedEntityId ?? disposedAsset?.trackedEntityId ?? null;
- const entity = trackedEntityId
- ? await trx
- .selectFrom("trackedEntity")
- .select(["id", "readableId"])
- .where("id", "=", trackedEntityId)
- .where("companyId", "=", companyId)
- .executeTakeFirst()
- : undefined;
- if (!item) throw new NotFoundError("Item not found");
- const serial = entity?.readableId ?? item.readableId;
- const accounting = settings.accountingEnabled
- ? await loadLeaseAccounting(trx, {
- companyId,
- companyGroupId: company.companyGroupId,
- today
- })
- : null;
- const tags = {
- customerId: agreement.customerId,
- itemId: line.itemId,
- locationId: agreement.locationId
- };
- const description = `Lease return ${agreement.rentalAgreementId} ${serial}`;
- let fixedAssetId: string | null = null;
- if (destination === "Fleet") {
- // The class the fleet register and capitalization default to; a company
- // that renamed it falls back to the class the unit was leased out of.
- const byName = await trx
- .selectFrom("fixedAssetClass")
- .select([
- "id",
- "assetAccountId",
- "depreciationMethod",
- "usefulLifeMonths",
- "residualValuePercent"
- ])
- .where("companyId", "=", companyId)
- .where("name", "=", "Rental Fleet")
- .where("isConstructionInProgress", "=", false)
+ // A unit an open rental document still holds would be Returned while
+ // the document names it (plan decision P2).
+ 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"])
+ .where("l.rentalAgreementLineId", "=", line.id)
+ .orderBy("s.createdAt")
.executeTakeFirst();
- const original =
- byName || !line.fixedAssetId
- ? undefined
- : await trx
- .selectFrom("fixedAsset as fa")
- .innerJoin("fixedAssetClass as fac", (join) =>
- join
- .onRef("fac.id", "=", "fa.fixedAssetClassId")
- .onRef("fac.companyId", "=", "fa.companyId")
- )
- .select([
- "fac.id",
- "fac.assetAccountId",
- "fac.depreciationMethod",
- "fac.usefulLifeMonths",
- "fac.residualValuePercent"
- ])
- .where("fa.id", "=", line.fixedAssetId)
- .where("fa.companyId", "=", companyId)
- .where("fac.isConstructionInProgress", "=", false)
- .executeTakeFirst();
- const assetClass = byName ?? original;
- if (!assetClass) {
- throw new InvalidInputError(
- "No Rental Fleet asset class to return the unit into; create one or return the unit to inventory"
- );
- }
+ const openReceipt = await trx
+ .selectFrom("receipt as r")
+ .innerJoin("receiptFixedAssetLine as l", (join) =>
+ join
+ .onRef("l.receiptId", "=", "r.id")
+ .onRef("l.companyId", "=", "r.companyId")
+ )
+ .select("r.receiptId")
+ .where("r.companyId", "=", companyId)
+ .where("r.sourceDocument", "=", "Rental Agreement")
+ .where("r.sourceDocumentId", "=", agreement.id)
+ .where("r.status", "in", ["Draft", "Pending"])
+ .where("l.rentalAgreementLineId", "=", line.id)
+ .orderBy("r.createdAt")
+ .executeTakeFirst();
+ const openDocument = openShipment
+ ? `shipment ${openShipment.shipmentId}`
+ : openReceipt
+ ? `receipt ${openReceipt.receiptId}`
+ : null;
+
+ const blocker = releaseBlocker({
+ label: unitLabel(asset, line.id),
+ status: line.status,
+ classification: line.lessorClassification,
+ openDocument
+ });
+ if (blocker) throw new InvalidInputError(blocker);
- let journalId: string | null = null;
- if (accounting && closing > 0) {
- journalId = await postLeaseJournal(trx, {
- accounting,
- companyId,
- userId,
- postingDate: today,
- description,
- lines: buildResidualReturnLines({
- closing,
- debitAccountId: assetClass.assetAccountId,
- debitDescription: "Fixed Asset Acquisition",
- netInvestmentInLeasesAccountId:
- accounting.accounts.netInvestmentInLeasesAccount
- }),
- rentalAgreementId: agreement.id,
+ await returnRentalUnit(trx, {
+ agreement,
+ unit: {
rentalAgreementLineId: line.id,
- tags
- });
- }
-
- const assetReadableId = await getNextSequence(trx, "fixedAsset", companyId);
- const asset = await trx
- .insertInto("fixedAsset")
- .values({
- fixedAssetId: assetReadableId,
- fixedAssetClassId: assetClass.id,
- name: `${item.name} ${serial}`,
- itemId: line.itemId,
- trackedEntityId,
- serialNumber: entity?.readableId ?? null,
- locationId: agreement.locationId,
- quantity: 1,
- acquisitionCost: closing,
- acquisitionDate: today,
- depreciationStartDate: today,
- depreciationMethod: assetClass.depreciationMethod,
- usefulLifeMonths: assetClass.usefulLifeMonths,
- residualValuePercent: assetClass.residualValuePercent,
- status: "Active",
- companyId,
- createdBy: userId
- })
- .returning(["id"])
- .executeTakeFirstOrThrow();
- fixedAssetId = asset.id;
-
- const transferId = await getNextSequence(
- trx,
- "fixedAssetTransfer",
- companyId
- );
- const now = datetime.timestamp();
- await trx
- .insertInto("fixedAssetTransfer")
- .values({
- transferId,
- type: "Capitalization",
- sourceType: "Inventory",
- fixedAssetId: asset.id,
- itemId: line.itemId,
- trackedEntityId,
- locationId: agreement.locationId,
- quantity: 1,
- transferDate: today,
- amount: closing,
- journalId,
- status: "Posted",
- postedAt: now,
- postedBy: userId,
- companyId,
- createdBy: userId
- })
- .execute();
-
- if (trackedEntityId) {
- await trx
- .updateTable("trackedEntity")
- .set({
- status: "Consumed",
- attributes: sql<Json>`(COALESCE("attributes", '{}'::jsonb) - 'Rental Agreement' - 'Customer') || jsonb_build_object('Fixed Asset', ${asset.id}::text)`
- })
- .where("id", "=", trackedEntityId)
- .where("companyId", "=", companyId)
- .execute();
- await insertUnitActivity(trx, {
- type: "Capitalize",
- direction: "input",
- sourceDocument: "Fixed Asset",
- sourceDocumentId: asset.id,
- sourceDocumentReadableId: assetReadableId,
- attributes: { "Fixed Asset": asset.id },
- trackedEntityId,
- companyId,
- userId
- });
- }
- } else {
- if (!itemCost) throw new NotFoundError("Item cost not found");
- // Into stock at the closing net investment: a cost layer at that amount,
- // so the unit is later sold like any other stock. accounting: null keeps
- // the core from posting a variance journal; the lease journal is below.
- await bookAdjustment(trx, {
- ledger: {
- postingDate: today,
- itemId: line.itemId,
- quantity: 1,
- locationId: agreement.locationId,
- storageUnitId: null,
- trackedEntityId,
- entryType: "Positive Adjmt.",
- documentType: "Rental Agreement",
- documentId: agreement.id,
- companyId,
- createdBy: userId
- },
- item: {
- itemTrackingType: item.itemTrackingType,
- replenishmentSystem: item.replenishmentSystem,
- itemPostingGroupId: itemCost.itemPostingGroupId
- },
- itemCost: {
- costingMethod: itemCost.costingMethod,
- unitCost: itemCost.unitCost,
- standardCost: itemCost.standardCost
+ returnedAt: payload.returnedAt
},
- accounting: null,
- fixedUnitCost: closing
+ companyId,
+ userId,
+ today
});
-
- if (accounting && closing > 0) {
- const inventoryAccount = resolveInventoryAccount(
- item.replenishmentSystem,
- accounting.accounts
- );
- await postLeaseJournal(trx, {
- accounting,
- companyId,
- userId,
- postingDate: today,
- description,
- lines: buildResidualReturnLines({
- closing,
- debitAccountId: inventoryAccount.account,
- debitDescription: inventoryAccount.description,
- netInvestmentInLeasesAccountId:
- accounting.accounts.netInvestmentInLeasesAccount
- }),
- rentalAgreementId: agreement.id,
- rentalAgreementLineId: line.id,
- tags
- });
- }
-
- if (trackedEntityId) {
- await trx
- .updateTable("trackedEntity")
- .set({
- status: "Available",
- attributes: sql<Json>`COALESCE("attributes", '{}'::jsonb) - 'Rental Agreement' - 'Customer'`
- })
- .where("id", "=", trackedEntityId)
- .where("companyId", "=", companyId)
- .execute();
- await insertUnitActivity(trx, {
- type: "Return to Inventory",
- direction: "output",
- sourceDocument: "Rental Agreement",
- sourceDocumentId: agreement.id,
- sourceDocumentReadableId: agreement.rentalAgreementId,
- attributes: { "Rental Agreement": agreement.id },
- trackedEntityId,
- companyId,
- userId
- });
- }
- }
-
- // The lease has ended: nothing dated after the return will ever accrue.
- // Everything on or before it stays and posts through recognition runs.
- await trx
- .deleteFrom("revenueRecognitionSchedule")
- .where("rentalAgreementLineId", "=", line.id)
- .where("companyId", "=", companyId)
- .where("type", "=", "Interest")
- .where("status", "=", "Planned")
- .where("scheduledDate", ">", returnedAt)
- .execute();
- await trx
- .deleteFrom("rentalLeaseScheduleLine")
- .where("rentalAgreementLineId", "=", line.id)
- .where("companyId", "=", companyId)
- .where("postedAt", "is", null)
- .where("periodDate", ">", returnedAt)
- .execute();
-
- return { fixedAssetId };
+ return { id: agreement.id };
+ });
}
// Everything close and cancel decide on, in three reads.
@@ -1738,6 +909,41 @@ async function close(
);
}
+ // A rental document still open holds units the close would strand.
+ 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();
+ const openReceipt = await trx
+ .selectFrom("receipt as r")
+ .innerJoin("receiptFixedAssetLine as l", (join) =>
+ join
+ .onRef("l.receiptId", "=", "r.id")
+ .onRef("l.companyId", "=", "r.companyId")
+ )
+ .select("r.receiptId")
+ .where("r.companyId", "=", companyId)
+ .where("r.sourceDocument", "=", "Rental Agreement")
+ .where("r.sourceDocumentId", "=", agreement.id)
+ .where("r.status", "in", ["Draft", "Pending"])
+ .orderBy("r.createdAt")
+ .executeTakeFirst();
+ const openDocument = openRentalDocumentBlocker({
+ shipmentId: openShipment?.shipmentId ?? null,
+ receiptId: openReceipt?.receiptId ?? null
+ });
+ if (openDocument) throw new InvalidInputError(openDocument);
+
const state = await loadSettlementState(trx, companyId, agreement.id);
const blocker = closeBlocker({
lineStatuses: state.lines.map((line) => line.status),
@@ -1846,7 +1052,7 @@ async function cancel(
export const postRentalAgreementInput = payloadValidator;
export type PostRentalAgreementInput = RentalAgreementPayload;
-/** Activates, returns a unit of, closes or cancels a rental agreement, per
+/** Activates, releases a unit of, closes or cancels a rental agreement, per
* `type` — each one transaction that locks the agreement row first. */
const postRentalAgreement = defineServerFn({
name: "post-rental-agreement",
@@ -1863,11 +1069,11 @@ const postRentalAgreement = defineServerFn({
.toString();
return activate(scope, payload, today);
}
- case "return": {
+ case "release": {
const today = datetime
.today(await getCompanyTimeZone(db, companyId))
.toString();
- return returnUnit(scope, payload, today);
+ return releaseUnit(scope, payload, today);
}
case "close":
return close(scope, payload);
diff --git a/packages/server-functions/src/post-rental-agreement/release.test.ts b/packages/server-functions/src/post-rental-agreement/release.test.ts
new file mode 100644
index 0000000000..37cacea9f7
--- /dev/null
+++ b/packages/server-functions/src/post-rental-agreement/release.test.ts
@@ -0,0 +1,156 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Releasing a Pending rental unit against the live database: the unit never
+// left the yard, so its billing stops at the release date and it is free
+// again, with no document. Refused for a unit that is not Pending, one treated
+// as a sale, one on an open rental document, and a future date.
+
+import { datetime } from "@carbon/utils";
+import { sql } from "kysely";
+import { expect } from "vitest";
+import create from "../create";
+import { databaseTest } from "../local-database-test-fixture";
+import postRentalAgreement from "./index";
+import { rentalFixture } from "./rental-test-fixture";
+
+type Fixture = Awaited<ReturnType<typeof rentalFixture>>;
+
+// The fixture company's timezone.
+const TIME_ZONE = "America/New_York";
+
+function release(f: Fixture, returnedAt: string) {
+ return postRentalAgreement(f.ctx, {
+ type: "release",
+ rentalAgreementId: f.agreementId,
+ rentalAgreementLineId: f.lineIds[0]!,
+ returnedAt
+ });
+}
+
+async function setLine(
+ f: Fixture,
+ values: { status?: "On Rent"; lessorClassification?: "Sale" }
+) {
+ await f.db
+ .updateTable("rentalAgreementLine")
+ .set(values)
+ .where("id", "=", f.lineIds[0]!)
+ .where("companyId", "=", f.companyId)
+ .execute();
+}
+
+databaseTest(
+ "a released Pending unit stops billing and is free again",
+ async () => {
+ const f = await rentalFixture();
+ const lineId = f.lineIds[0]!;
+ try {
+ const result = await release(f, "2026-09-20");
+ expect(result.error).toBeNull();
+
+ const line = await f.db
+ .selectFrom("rentalAgreementLine")
+ .select([
+ "status",
+ sql<string | null>`"returnedAt"::text`.as("returnedAt")
+ ])
+ .where("id", "=", lineId)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ expect(line).toEqual({ status: "Returned", returnedAt: "2026-09-20" });
+
+ const periods = await f.db
+ .selectFrom("rentalBillingPeriod")
+ .select([
+ sql<string>`"periodStart"::text`.as("periodStart"),
+ "status",
+ "isAdjustment"
+ ])
+ .where("rentalAgreementLineId", "=", lineId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ expect(
+ periods.filter(
+ (period) =>
+ period.status === "Pending" && period.periodStart > "2026-09-20"
+ )
+ ).toEqual([]);
+ expect(periods.filter((period) => period.isAdjustment)).toHaveLength(1);
+
+ const fleet = await f.db
+ .selectFrom("fleetAssets")
+ .select("fleetStatus")
+ .where("id", "=", f.fixedAssetIds[0]!)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ expect(fleet.fleetStatus).toEqual("Available");
+
+ const asset = await f.db
+ .selectFrom("fixedAsset")
+ .select("locationId")
+ .where("id", "=", f.fixedAssetIds[0]!)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ expect(asset.locationId).toEqual(f.locationId);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest("an On Rent unit is not released", async () => {
+ const f = await rentalFixture();
+ try {
+ await setLine(f, { status: "On Rent" });
+ const result = await release(f, "2026-09-20");
+ expect(result.error?.message).toContain(
+ "is On Rent; only a Pending unit can be released"
+ );
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("a release is never dated after today", async () => {
+ const f = await rentalFixture();
+ try {
+ const tomorrow = datetime.today(TIME_ZONE).add({ days: 1 }).toString();
+ const result = await release(f, tomorrow);
+ expect(result.error?.message).toContain(
+ "The release date cannot be in the future"
+ );
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("a unit treated as a sale is not released", async () => {
+ const f = await rentalFixture();
+ try {
+ await setLine(f, { lessorClassification: "Sale" });
+ const result = await release(f, "2026-09-20");
+ expect(result.error?.message).toContain(
+ "is treated as a sale; return it on a rental receipt instead"
+ );
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("a unit on an open rental shipment is not released", async () => {
+ const f = await rentalFixture();
+ try {
+ const shipment = await create(f.ctx, {
+ type: "shipmentFromRentalAgreement",
+ rentalAgreementId: f.agreementId
+ });
+ expect(shipment.error).toBeNull();
+
+ const result = await release(f, "2026-09-20");
+ expect(result.error?.message).toContain("is on shipment SHP-");
+ } finally {
+ await f.cleanup();
+ }
+});
diff --git a/packages/server-functions/src/post-rental-agreement/rental-test-fixture.ts b/packages/server-functions/src/post-rental-agreement/rental-test-fixture.ts
new file mode 100644
index 0000000000..e34de83289
--- /dev/null
+++ b/packages/server-functions/src/post-rental-agreement/rental-test-fixture.ts
@@ -0,0 +1,297 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// A live-database rental agreement for the rental tests: one Active agreement
+// that started 2026-09-01, billed monthly, with N serial fleet units on
+// Pending lines. September is invoiced, October is not.
+
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { sql } from "kysely";
+import { connectLocalTestDatabase } from "../local-database-test-fixture";
+import { ServerFnContext } from "../server-fn-context";
+
+const USER = "system";
+
+export async function rentalFixture(options?: {
+ units?: number; // default 1
+ billingTiming?: "Advance" | "Arrears"; // default "Advance"
+}): Promise<{
+ db: Kysely<KyselyDatabase>;
+ ctx: ServerFnContext;
+ companyId: string;
+ agreementId: string;
+ agreementReadableId: string;
+ locationId: string;
+ otherLocationId: string;
+ lineIds: string[];
+ fixedAssetIds: string[];
+ fixedAssetReadableIds: string[];
+ trackedEntityIds: string[];
+ itemId: string;
+ cleanup(): Promise<void>;
+}> {
+ const units = options?.units ?? 1;
+ const billingTiming = options?.billingTiming ?? "Advance";
+
+ const db = await connectLocalTestDatabase();
+ const prefix = `rentfx-${crypto
+ .randomUUID()
+ .replaceAll("-", "")
+ .slice(0, 12)}`;
+ const companyId = `${prefix}-company`;
+ const groupId = `${prefix}-group`;
+ const accountId = `${prefix}-account`;
+ const customerId = `${prefix}-customer`;
+ const itemId = `${prefix}-item`;
+ const locationId = `${prefix}-location`;
+ const otherLocationId = `${prefix}-location-2`;
+ const assetClassId = `${prefix}-class`;
+ const agreementId = `${prefix}-agreement`;
+ const agreementReadableId = "RA-TEST";
+ const unitRows = Array.from({ length: units }, (_, i) => {
+ const n = i + 1;
+ return {
+ n,
+ lineId: `${prefix}-line-${n}`,
+ fixedAssetId: `${prefix}-asset-${n}`,
+ fixedAssetReadableId: `FA-${n}`,
+ trackedEntityId: `${prefix}-entity-${n}`
+ };
+ });
+ const lineIds = unitRows.map((u) => u.lineId);
+ const fixedAssetIds = unitRows.map((u) => u.fixedAssetId);
+ const fixedAssetReadableIds = unitRows.map((u) => u.fixedAssetReadableId);
+ const trackedEntityIds = unitRows.map((u) => u.trackedEntityId);
+
+ await db.transaction().execute(async (trx) => {
+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);
+ await trx
+ .insertInto("companyGroup")
+ .values({ id: groupId, name: prefix, createdBy: USER })
+ .execute();
+ await trx
+ .insertInto("company")
+ .values({
+ id: companyId,
+ name: prefix,
+ companyGroupId: groupId,
+ baseCurrencyCode: "USD",
+ timezone: "America/New_York"
+ })
+ .execute();
+ await trx
+ .insertInto("currency")
+ .values({
+ code: "USD",
+ decimalPlaces: 2,
+ companyGroupId: groupId,
+ createdBy: USER
+ })
+ .execute();
+ await trx
+ .insertInto("companySettings")
+ .values({ id: companyId })
+ .onConflict((oc) => oc.column("id").doNothing())
+ .execute();
+ await trx
+ .insertInto("sequence")
+ .values([
+ { table: "shipment", name: "Shipment", prefix: "SHP-", companyId },
+ { table: "receipt", name: "Receipt", prefix: "RCV-", companyId },
+ { table: "fixedAsset", name: "Fixed Asset", prefix: "FA", companyId }
+ ])
+ .execute();
+ await trx
+ .insertInto("customer")
+ .values({ id: customerId, name: prefix, companyId })
+ .execute();
+ await trx
+ .insertInto("location")
+ .values(
+ [
+ { id: locationId, name: "Headquarters" },
+ { id: otherLocationId, name: "Yard" }
+ ].map((location) => ({
+ ...location,
+ addressLine1: "1 Main St",
+ city: "Springfield",
+ postalCode: "00000",
+ timezone: "America/New_York",
+ companyId,
+ createdBy: USER
+ }))
+ )
+ .execute();
+ await trx
+ .insertInto("item")
+ .values({
+ id: itemId,
+ readableId: `${prefix}-LIFT`,
+ name: "Scissor lift",
+ type: "Part",
+ itemTrackingType: "Serial",
+ companyId,
+ createdBy: USER
+ })
+ .execute();
+ await trx
+ .insertInto("account")
+ .values({
+ id: accountId,
+ name: "Rental fleet",
+ incomeBalance: "Balance Sheet",
+ companyGroupId: groupId,
+ createdBy: USER
+ })
+ .execute();
+ await trx
+ .insertInto("fixedAssetClass")
+ .values({
+ id: assetClassId,
+ name: "Rental Fleet",
+ assetAccountId: accountId,
+ accumulatedDepreciationAccountId: accountId,
+ depreciationExpenseAccountId: accountId,
+ writeOffAccountId: accountId,
+ writeDownAccountId: accountId,
+ lossOnDisposalAccountId: accountId,
+ gainOnDisposalAccountId: accountId,
+ companyId,
+ createdBy: USER
+ })
+ .execute();
+ await trx
+ .insertInto("trackedEntity")
+ .values(
+ unitRows.map((u) => ({
+ id: u.trackedEntityId,
+ readableId: `SN-${u.n}`,
+ itemId,
+ quantity: 1,
+ sourceDocument: "Item",
+ sourceDocumentId: itemId,
+ companyId,
+ createdBy: USER
+ }))
+ )
+ .execute();
+ await trx
+ .insertInto("fixedAsset")
+ .values(
+ unitRows.map((u) => ({
+ id: u.fixedAssetId,
+ fixedAssetId: u.fixedAssetReadableId,
+ name: `Scissor lift ${u.n}`,
+ serialNumber: `SN-${u.n}`,
+ status: "Active" as const,
+ fixedAssetClassId: assetClassId,
+ locationId,
+ itemId,
+ trackedEntityId: u.trackedEntityId,
+ companyId,
+ createdBy: USER
+ }))
+ )
+ .execute();
+ await trx
+ .insertInto("rentalAgreement")
+ .values({
+ id: agreementId,
+ rentalAgreementId: agreementReadableId,
+ customerId,
+ locationId,
+ currencyCode: "USD",
+ discountRate: 0,
+ startDate: "2026-09-01",
+ endDate: null,
+ billingCycle: "Calendar Month",
+ billingTiming,
+ status: "Active",
+ companyId,
+ createdBy: USER
+ })
+ .execute();
+ await trx
+ .insertInto("rentalAgreementLine")
+ .values(
+ unitRows.map((u) => ({
+ id: u.lineId,
+ rentalAgreementId: agreementId,
+ itemId,
+ fixedAssetId: u.fixedAssetId,
+ trackedEntityId: u.trackedEntityId,
+ rateUnit: "Month" as const,
+ rate: 300,
+ lessorClassification: "Rental" as const,
+ status: "Pending" as const,
+ companyId,
+ createdBy: USER
+ }))
+ )
+ .execute();
+ await trx
+ .insertInto("rentalBillingPeriod")
+ .values(
+ lineIds.flatMap((lineId) => [
+ {
+ rentalAgreementLineId: lineId,
+ periodStart: "2026-09-01",
+ periodEnd: "2026-09-30",
+ days: 30,
+ amount: 300,
+ dueOn: "2026-09-01",
+ status: "Invoiced" as const,
+ companyId,
+ createdBy: USER
+ },
+ {
+ rentalAgreementLineId: lineId,
+ periodStart: "2026-10-01",
+ periodEnd: "2026-10-31",
+ days: 31,
+ amount: 300,
+ dueOn: "2026-10-01",
+ status: "Pending" as const,
+ companyId,
+ createdBy: USER
+ }
+ ])
+ )
+ .execute();
+ });
+
+ const ctx = ServerFnContext.system({ db, companyId, userId: USER });
+
+ return {
+ db,
+ ctx,
+ companyId,
+ agreementId,
+ agreementReadableId,
+ locationId,
+ otherLocationId,
+ lineIds,
+ fixedAssetIds,
+ fixedAssetReadableIds,
+ trackedEntityIds,
+ itemId,
+ async cleanup() {
+ await db.transaction().execute(async (trx) => {
+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);
+ await trx.deleteFrom("company").where("id", "=", companyId).execute();
+ await trx
+ .deleteFrom("companyGroup")
+ .where("id", "=", groupId)
+ .execute();
+ await sql`DROP TABLE IF EXISTS ${sql.id(`searchIndex_${companyId}`)}`.execute(
+ trx
+ );
+ await sql`DROP TABLE IF EXISTS ${sql.id(`auditLog_${companyId}`)}`.execute(
+ trx
+ );
+ });
+ await db.destroy();
+ }
+ };
+}
diff --git a/packages/server-functions/src/post-rental-agreement/return-unit.test.ts b/packages/server-functions/src/post-rental-agreement/return-unit.test.ts
new file mode 100644
index 0000000000..b29a4e5e9a
--- /dev/null
+++ b/packages/server-functions/src/post-rental-agreement/return-unit.test.ts
@@ -0,0 +1,85 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Pins today's unit return against the live database, so moving the return
+// body into `returnRentalUnit` cannot change what it writes. It acts through
+// a rental receipt, which re-cuts the periods exactly as the old return did.
+
+import { sql } from "kysely";
+import { expect } from "vitest";
+import create from "../create";
+import { databaseTest } from "../local-database-test-fixture";
+import postReceipt from "../post-receipt";
+import { rentalFixture } from "./rental-test-fixture";
+
+type Fixture = Awaited<ReturnType<typeof rentalFixture>>;
+
+async function returnUnitOnSeptember20(f: Fixture) {
+ const receipt = await create(f.ctx, {
+ type: "receiptFromRentalAgreement",
+ rentalAgreementId: f.agreementId,
+ rentalAgreementLineId: f.lineIds[0]!
+ });
+ if (receipt.error) return receipt;
+ return postReceipt(f.ctx, {
+ type: "post",
+ receiptId: receipt.data.id,
+ postingDate: "2026-09-20"
+ });
+}
+
+databaseTest(
+ "an early return of an Advance unit re-cuts its periods",
+ async () => {
+ const f = await rentalFixture();
+ const lineId = f.lineIds[0]!;
+ try {
+ await f.db
+ .updateTable("rentalAgreementLine")
+ .set({ status: "On Rent", deliveredAt: "2026-09-01" })
+ .where("id", "=", lineId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+
+ const result = await returnUnitOnSeptember20(f);
+ expect(result.error).toBeNull();
+
+ const periodRows = await f.db
+ .selectFrom("rentalBillingPeriod")
+ .select([
+ sql<string>`"periodStart"::text`.as("periodStart"),
+ sql<string>`"periodEnd"::text`.as("periodEnd"),
+ "days",
+ "amount",
+ "isAdjustment",
+ "status",
+ "rateUnitApplied",
+ sql<string>`"dueOn"::text`.as("dueOn")
+ ])
+ .where("rentalAgreementLineId", "=", lineId)
+ .where("companyId", "=", f.companyId)
+ .orderBy("periodStart")
+ .orderBy("isAdjustment")
+ .execute();
+ const periods = periodRows.map((row) => ({
+ ...row,
+ amount: Number(row.amount)
+ }));
+
+ const line = await f.db
+ .selectFrom("rentalAgreementLine")
+ .select([
+ "status",
+ sql<string | null>`"returnedAt"::text`.as("returnedAt")
+ ])
+ .where("id", "=", lineId)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+
+ expect({ periods, line }).toMatchSnapshot();
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
diff --git a/packages/server-functions/src/post-rental-agreement/return-unit.ts b/packages/server-functions/src/post-rental-agreement/return-unit.ts
new file mode 100644
index 0000000000..da75a9852a
--- /dev/null
+++ b/packages/server-functions/src/post-rental-agreement/return-unit.ts
@@ -0,0 +1,659 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// One unit of an Active rental agreement comes back: the line goes Returned,
+// an operating line's billing is re-cut at the return date, and a sales-type
+// line's closing net investment moves into a new fleet asset or into stock.
+
+import type { Json } from "@carbon/database";
+import { getNextSequence } from "@carbon/database/sequence";
+import {
+ datetime,
+ type ExistingBillingPeriod,
+ generateRentalBillingPeriods
+} from "@carbon/utils";
+import { sql } from "kysely";
+import { InvalidInputError, NotFoundError } from "../errors";
+import { resolveInventoryAccount } from "../lib/get-posting-group";
+import { bookAdjustment } from "../lib/post-adjustment";
+import {
+ type AgreementRow,
+ billingPeriodRow,
+ currencyDecimals,
+ insertUnitActivity,
+ loadLeaseAccounting,
+ postLeaseJournal,
+ type Trx
+} from "./agreement";
+import {
+ buildResidualReturnLines,
+ netInvestmentAt,
+ salesTypeReturnError
+} from "./lessor";
+import {
+ RETURNABLE_LINE_STATUSES,
+ type ResidualDestination
+} from "./validators";
+
+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 }> {
+ const { agreement, unit, companyId, userId, today } = args;
+ const { returnedAt } = unit;
+
+ const line = await trx
+ .selectFrom("rentalAgreementLine")
+ .select([
+ "id",
+ "status",
+ "fixedAssetId",
+ "itemId",
+ "trackedEntityId",
+ "rateUnit",
+ "rate",
+ "lessorClassification",
+ "initialNetInvestment",
+ sql<string | null>`"deliveredAt"::text`.as("deliveredAt")
+ ])
+ .where("id", "=", unit.rentalAgreementLineId)
+ .where("rentalAgreementId", "=", agreement.id)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ if (!line) throw new NotFoundError("Rental agreement line not found");
+ if (!RETURNABLE_LINE_STATUSES.has(line.status)) {
+ throw new InvalidInputError(
+ `The unit is ${line.status}; only a Pending or On Rent unit can be returned`
+ );
+ }
+ // `YYYY-MM-DD` compares chronologically as text.
+ if (returnedAt < agreement.startDate) {
+ throw new InvalidInputError(
+ `The return date is before the agreement starts (${agreement.startDate})`
+ );
+ }
+ if (line.deliveredAt && returnedAt < line.deliveredAt) {
+ throw new InvalidInputError(
+ `The return date is before the unit was delivered (${line.deliveredAt})`
+ );
+ }
+ // A sales-type unit is off the books until it comes back: where it goes
+ // (fleet or stock) is the caller's choice and has to be made. An
+ // operating return ignores the destination.
+ const salesTypeProblem = salesTypeReturnError({
+ classification: line.lessorClassification,
+ residualDestination: unit.residualDestination,
+ returnedAt,
+ endDate: agreement.endDate,
+ takeOutOfService: !!unit.takeOutOfService
+ });
+ if (salesTypeProblem) throw new InvalidInputError(salesTypeProblem);
+ const salesType = line.lessorClassification === "Sale";
+ if (salesType && line.initialNetInvestment === null) {
+ throw new InvalidInputError(
+ "This line is treated as a sale but has no commencement booked; it cannot be returned"
+ );
+ }
+
+ const now = datetime.timestamp();
+
+ // A sales-type line's billing is its term, cut in full at activation, and
+ // the unit comes back only on or after the end date — there is nothing to
+ // re-cut. Regenerating would cut holdover periods past the end date that
+ // bill rent against a net investment the schedule has already closed.
+ if (!salesType) {
+ const existingRows = await trx
+ .selectFrom("rentalBillingPeriod")
+ .select([
+ sql<string>`"periodStart"::text`.as("periodStart"),
+ sql<string>`"periodEnd"::text`.as("periodEnd"),
+ "amount",
+ "status",
+ "isAdjustment"
+ ])
+ .where("rentalAgreementLineId", "=", line.id)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .execute();
+ const existing: ExistingBillingPeriod[] = existingRows.map((row) => ({
+ periodStart: row.periodStart,
+ periodEnd: row.periodEnd,
+ amount: Number(row.amount),
+ status: row.status,
+ isAdjustment: row.isAdjustment
+ }));
+
+ const plan = generateRentalBillingPeriods({
+ cycle: agreement.billingCycle,
+ timing: agreement.billingTiming,
+ rateUnit: line.rateUnit,
+ rate: Number(line.rate),
+ startDate: agreement.startDate,
+ endDate: agreement.endDate,
+ returnedAt,
+ through: returnedAt,
+ existing,
+ decimals: await currencyDecimals(trx, companyId, agreement.currencyCode)
+ });
+
+ // The generation stops at the return, so every unbilled period starting
+ // after it is gone. An invoiced one is credited through `adjustments`.
+ await trx
+ .deleteFrom("rentalBillingPeriod")
+ .where("rentalAgreementLineId", "=", line.id)
+ .where("companyId", "=", companyId)
+ .where("status", "=", "Pending")
+ .where("isAdjustment", "=", false)
+ .where("periodStart", ">", returnedAt)
+ .execute();
+
+ // The unbilled period the return falls inside ends on the return date.
+ for (const recut of plan.recut) {
+ await trx
+ .updateTable("rentalBillingPeriod")
+ .set({
+ periodEnd: recut.periodEnd,
+ days: recut.days,
+ amount: recut.amount,
+ rateUnitApplied: recut.rateUnitApplied,
+ dueOn: recut.dueOn,
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("rentalAgreementLineId", "=", line.id)
+ .where("companyId", "=", companyId)
+ .where("periodStart", "=", recut.periodStart)
+ .where("isAdjustment", "=", false)
+ .where("status", "=", "Pending")
+ .execute();
+ }
+
+ // `create` is non-empty when the return falls in a period not generated
+ // yet; `adjustments` credits advance billing past the return.
+ const inserts = [...plan.create, ...plan.adjustments].map((spec) =>
+ billingPeriodRow(spec, line.id, companyId, userId)
+ );
+ if (inserts.length > 0) {
+ await trx.insertInto("rentalBillingPeriod").values(inserts).execute();
+ }
+ }
+
+ await trx
+ .updateTable("rentalAgreementLine")
+ .set({
+ status: "Returned",
+ returnedAt,
+ meterIn: unit.meterIn ?? null,
+ returnNotes: unit.returnNotes ?? null,
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", line.id)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ // A sales-type unit's closing net investment moves back onto the books
+ // — as a new Rental Fleet asset or into stock. The asset the line names
+ // was disposed at commencement, so a fleet return's unit is the new one.
+ let fleetAssetId = line.fixedAssetId;
+ if (salesType) {
+ const residual = await returnResidual(trx, {
+ agreement,
+ line: {
+ id: line.id,
+ itemId: line.itemId,
+ fixedAssetId: line.fixedAssetId,
+ trackedEntityId: line.trackedEntityId,
+ initialNetInvestment: Number(line.initialNetInvestment)
+ },
+ destination: unit.residualDestination as ResidualDestination,
+ returnedAt,
+ companyId,
+ userId,
+ today,
+ locationId: args.locationId ?? agreement.locationId
+ });
+ fleetAssetId = residual.fixedAssetId;
+ }
+
+ // Straight to maintenance: the fleet status reads In Maintenance and the
+ // unit cannot go back on rent until it is returned to service.
+ if (unit.takeOutOfService && fleetAssetId) {
+ await trx
+ .updateTable("fixedAsset")
+ .set({
+ outOfServiceSince: returnedAt,
+ outOfServiceReason: (unit.outOfServiceReason ?? "").trim(),
+ updatedBy: userId,
+ updatedAt: now
+ })
+ .where("id", "=", fleetAssetId)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+
+ return { fixedAssetId: fleetAssetId };
+}
+
+/**
+ * End of a sales-type term with the unit coming back (spec §4): the closing
+ * net investment — the schedule's balance on the return date
+ * (`netInvestmentAt`: the closing of the last schedule line dated on or
+ * before it, which at or after the end date is the closing target; the
+ * initial NI when the line has no schedule) — leaves Net Investment in
+ * Leases for either
+ *
+ * Fleet a new asset in the class named "Rental Fleet" (else the class
+ * the unit left at commencement) at that amount, with a Posted
+ * Capitalization transfer; Dr class asset / Cr net investment.
+ * The unit is consumed into the new asset.
+ * Inventory stock at that unit cost (`bookAdjustment` +1, no variance
+ * journal); Dr the item's inventory account / Cr net investment.
+ * The unit is Available again.
+ *
+ * The schedule lines and Interest rows dated on or before the return stay,
+ * posted or not: they are the term the lease ran, the closing already counts
+ * them, and their interest posts through recognition runs after the return,
+ * bringing Net Investment in Leases to zero. Only what is dated AFTER the
+ * return is dropped — nothing accrues on a lease that has ended (normally
+ * nothing, since a unit comes back on or after the end date). With
+ * accounting off, the asset / stock moves identically and no journal is
+ * posted.
+ */
+async function returnResidual(
+ trx: Trx,
+ args: {
+ agreement: AgreementRow;
+ line: {
+ id: string;
+ itemId: string;
+ fixedAssetId: string | null;
+ trackedEntityId: string | null;
+ initialNetInvestment: number;
+ };
+ destination: ResidualDestination;
+ returnedAt: string;
+ companyId: string;
+ userId: string;
+ today: string;
+ locationId: string;
+ }
+): Promise<{ fixedAssetId: string | null }> {
+ const { agreement, line, destination, returnedAt, companyId, userId, today } =
+ args;
+
+ // A Draft recognition run that already claimed interest dated after the
+ // return would be left pointing at deleted rows. Interest on or before the
+ // return is kept, so a run holding it is no obstacle.
+ const claimed = await trx
+ .selectFrom("revenueRecognitionSchedule")
+ .select(sql<number>`count(*)::int`.as("count"))
+ .where("rentalAgreementLineId", "=", line.id)
+ .where("companyId", "=", companyId)
+ .where("type", "=", "Interest")
+ .where("status", "=", "Planned")
+ .where("scheduledDate", ">", returnedAt)
+ .where("runLineId", "is not", null)
+ .executeTakeFirstOrThrow();
+ if (Number(claimed.count) > 0) {
+ throw new InvalidInputError(
+ "A draft revenue recognition run includes this lease's interest; post or delete the run before returning the unit"
+ );
+ }
+
+ const schedule = await trx
+ .selectFrom("rentalLeaseScheduleLine")
+ .select([
+ sql<string>`"periodDate"::text`.as("periodDate"),
+ "closingNetInvestment"
+ ])
+ .where("rentalAgreementLineId", "=", line.id)
+ .where("companyId", "=", companyId)
+ .execute();
+ const closing = netInvestmentAt({
+ initialNetInvestment: line.initialNetInvestment,
+ schedule: schedule.map((row) => ({
+ periodDate: row.periodDate,
+ closingNetInvestment: Number(row.closingNetInvestment)
+ })),
+ asOf: returnedAt
+ });
+ if (closing < 0) {
+ throw new InvalidInputError(
+ `The lease's closing net investment is negative (${closing})`
+ );
+ }
+
+ // Sequential on purpose: one transaction is one connection.
+ const company = await trx
+ .selectFrom("company")
+ .select("companyGroupId")
+ .where("id", "=", companyId)
+ .executeTakeFirstOrThrow();
+ const settings = await trx
+ .selectFrom("companySettings")
+ .select("accountingEnabled")
+ .where("id", "=", companyId)
+ .executeTakeFirstOrThrow();
+ const item = await trx
+ .selectFrom("item")
+ .select([
+ "id",
+ "name",
+ "readableId",
+ "itemTrackingType",
+ "replenishmentSystem"
+ ])
+ .where("id", "=", line.itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ const itemCost = await trx
+ .selectFrom("itemCost")
+ .select(["costingMethod", "unitCost", "standardCost", "itemPostingGroupId"])
+ .where("itemId", "=", line.itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ // The serial left the line's asset at commencement when the line named
+ // only the asset (as `commenceSalesTypeLines` resolves it), so a line
+ // without its own serial takes the disposed asset's.
+ const disposedAsset =
+ !line.trackedEntityId && line.fixedAssetId
+ ? await trx
+ .selectFrom("fixedAsset")
+ .select("trackedEntityId")
+ .where("id", "=", line.fixedAssetId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : undefined;
+ const trackedEntityId =
+ line.trackedEntityId ?? disposedAsset?.trackedEntityId ?? null;
+ const entity = trackedEntityId
+ ? await trx
+ .selectFrom("trackedEntity")
+ .select(["id", "readableId"])
+ .where("id", "=", trackedEntityId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : undefined;
+ if (!item) throw new NotFoundError("Item not found");
+ const serial = entity?.readableId ?? item.readableId;
+ const accounting = settings.accountingEnabled
+ ? await loadLeaseAccounting(trx, {
+ companyId,
+ companyGroupId: company.companyGroupId,
+ today
+ })
+ : null;
+ const tags = {
+ customerId: agreement.customerId,
+ itemId: line.itemId,
+ locationId: agreement.locationId
+ };
+ const description = `Lease return ${agreement.rentalAgreementId} ${serial}`;
+
+ let fixedAssetId: string | null = null;
+ if (destination === "Fleet") {
+ // The class the fleet register and capitalization default to; a company
+ // that renamed it falls back to the class the unit was leased out of.
+ const byName = await trx
+ .selectFrom("fixedAssetClass")
+ .select([
+ "id",
+ "assetAccountId",
+ "depreciationMethod",
+ "usefulLifeMonths",
+ "residualValuePercent"
+ ])
+ .where("companyId", "=", companyId)
+ .where("name", "=", "Rental Fleet")
+ .where("isConstructionInProgress", "=", false)
+ .executeTakeFirst();
+ const original =
+ byName || !line.fixedAssetId
+ ? undefined
+ : await trx
+ .selectFrom("fixedAsset as fa")
+ .innerJoin("fixedAssetClass as fac", (join) =>
+ join
+ .onRef("fac.id", "=", "fa.fixedAssetClassId")
+ .onRef("fac.companyId", "=", "fa.companyId")
+ )
+ .select([
+ "fac.id",
+ "fac.assetAccountId",
+ "fac.depreciationMethod",
+ "fac.usefulLifeMonths",
+ "fac.residualValuePercent"
+ ])
+ .where("fa.id", "=", line.fixedAssetId)
+ .where("fa.companyId", "=", companyId)
+ .where("fac.isConstructionInProgress", "=", false)
+ .executeTakeFirst();
+ const assetClass = byName ?? original;
+ if (!assetClass) {
+ throw new InvalidInputError(
+ "No Rental Fleet asset class to return the unit into; create one or return the unit to inventory"
+ );
+ }
+
+ let journalId: string | null = null;
+ if (accounting && closing > 0) {
+ journalId = await postLeaseJournal(trx, {
+ accounting,
+ companyId,
+ userId,
+ postingDate: today,
+ description,
+ lines: buildResidualReturnLines({
+ closing,
+ debitAccountId: assetClass.assetAccountId,
+ debitDescription: "Fixed Asset Acquisition",
+ netInvestmentInLeasesAccountId:
+ accounting.accounts.netInvestmentInLeasesAccount
+ }),
+ rentalAgreementId: agreement.id,
+ rentalAgreementLineId: line.id,
+ tags
+ });
+ }
+
+ const assetReadableId = await getNextSequence(trx, "fixedAsset", companyId);
+ const asset = await trx
+ .insertInto("fixedAsset")
+ .values({
+ fixedAssetId: assetReadableId,
+ fixedAssetClassId: assetClass.id,
+ name: `${item.name} ${serial}`,
+ itemId: line.itemId,
+ trackedEntityId,
+ serialNumber: entity?.readableId ?? null,
+ locationId: args.locationId,
+ quantity: 1,
+ acquisitionCost: closing,
+ acquisitionDate: today,
+ depreciationStartDate: today,
+ depreciationMethod: assetClass.depreciationMethod,
+ usefulLifeMonths: assetClass.usefulLifeMonths,
+ residualValuePercent: assetClass.residualValuePercent,
+ status: "Active",
+ companyId,
+ createdBy: userId
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+ fixedAssetId = asset.id;
+
+ const transferId = await getNextSequence(
+ trx,
+ "fixedAssetTransfer",
+ companyId
+ );
+ const now = datetime.timestamp();
+ await trx
+ .insertInto("fixedAssetTransfer")
+ .values({
+ transferId,
+ type: "Capitalization",
+ sourceType: "Inventory",
+ fixedAssetId: asset.id,
+ itemId: line.itemId,
+ trackedEntityId,
+ locationId: args.locationId,
+ quantity: 1,
+ transferDate: today,
+ amount: closing,
+ journalId,
+ status: "Posted",
+ postedAt: now,
+ postedBy: userId,
+ companyId,
+ createdBy: userId
+ })
+ .execute();
+
+ if (trackedEntityId) {
+ await trx
+ .updateTable("trackedEntity")
+ .set({
+ status: "Consumed",
+ attributes: sql<Json>`(COALESCE("attributes", '{}'::jsonb) - 'Rental Agreement' - 'Customer') || jsonb_build_object('Fixed Asset', ${asset.id}::text)`
+ })
+ .where("id", "=", trackedEntityId)
+ .where("companyId", "=", companyId)
+ .execute();
+ await insertUnitActivity(trx, {
+ type: "Capitalize",
+ direction: "input",
+ sourceDocument: "Fixed Asset",
+ sourceDocumentId: asset.id,
+ sourceDocumentReadableId: assetReadableId,
+ attributes: { "Fixed Asset": asset.id },
+ trackedEntityId,
+ companyId,
+ userId
+ });
+ }
+ } else {
+ if (!itemCost) throw new NotFoundError("Item cost not found");
+ // Into stock at the closing net investment: a cost layer at that amount,
+ // so the unit is later sold like any other stock. accounting: null keeps
+ // the core from posting a variance journal; the lease journal is below.
+ await bookAdjustment(trx, {
+ ledger: {
+ postingDate: today,
+ itemId: line.itemId,
+ quantity: 1,
+ locationId: args.locationId,
+ storageUnitId: null,
+ trackedEntityId,
+ entryType: "Positive Adjmt.",
+ documentType: "Rental Agreement",
+ documentId: agreement.id,
+ companyId,
+ createdBy: userId
+ },
+ item: {
+ itemTrackingType: item.itemTrackingType,
+ replenishmentSystem: item.replenishmentSystem,
+ itemPostingGroupId: itemCost.itemPostingGroupId
+ },
+ itemCost: {
+ costingMethod: itemCost.costingMethod,
+ unitCost: itemCost.unitCost,
+ standardCost: itemCost.standardCost
+ },
+ accounting: null,
+ fixedUnitCost: closing
+ });
+
+ if (accounting && closing > 0) {
+ const inventoryAccount = resolveInventoryAccount(
+ item.replenishmentSystem,
+ accounting.accounts
+ );
+ await postLeaseJournal(trx, {
+ accounting,
+ companyId,
+ userId,
+ postingDate: today,
+ description,
+ lines: buildResidualReturnLines({
+ closing,
+ debitAccountId: inventoryAccount.account,
+ debitDescription: inventoryAccount.description,
+ netInvestmentInLeasesAccountId:
+ accounting.accounts.netInvestmentInLeasesAccount
+ }),
+ rentalAgreementId: agreement.id,
+ rentalAgreementLineId: line.id,
+ tags
+ });
+ }
+
+ if (trackedEntityId) {
+ await trx
+ .updateTable("trackedEntity")
+ .set({
+ status: "Available",
+ attributes: sql<Json>`COALESCE("attributes", '{}'::jsonb) - 'Rental Agreement' - 'Customer'`
+ })
+ .where("id", "=", trackedEntityId)
+ .where("companyId", "=", companyId)
+ .execute();
+ await insertUnitActivity(trx, {
+ type: "Return to Inventory",
+ direction: "output",
+ sourceDocument: "Rental Agreement",
+ sourceDocumentId: agreement.id,
+ sourceDocumentReadableId: agreement.rentalAgreementId,
+ attributes: { "Rental Agreement": agreement.id },
+ trackedEntityId,
+ companyId,
+ userId
+ });
+ }
+ }
+
+ // The lease has ended: nothing dated after the return will ever accrue.
+ // Everything on or before it stays and posts through recognition runs.
+ await trx
+ .deleteFrom("revenueRecognitionSchedule")
+ .where("rentalAgreementLineId", "=", line.id)
+ .where("companyId", "=", companyId)
+ .where("type", "=", "Interest")
+ .where("status", "=", "Planned")
+ .where("scheduledDate", ">", returnedAt)
+ .execute();
+ await trx
+ .deleteFrom("rentalLeaseScheduleLine")
+ .where("rentalAgreementLineId", "=", line.id)
+ .where("companyId", "=", companyId)
+ .where("postedAt", "is", null)
+ .where("periodDate", ">", returnedAt)
+ .execute();
+
+ return { fixedAssetId };
+}
diff --git a/packages/server-functions/src/post-rental-agreement/validators.test.ts b/packages/server-functions/src/post-rental-agreement/validators.test.ts
index 621ed2411f..d3acc2db82 100644
--- a/packages/server-functions/src/post-rental-agreement/validators.test.ts
+++ b/packages/server-functions/src/post-rental-agreement/validators.test.ts
@@ -9,10 +9,18 @@ import {
cancelBlocker,
closeBlocker,
type FleetUnit,
+ futureDeliveryError,
+ futureReleaseError,
futureReturnError,
+ openRentalDocumentBlocker,
payloadValidator,
+ receiptReturnError,
+ releaseBlocker,
+ rentalShipmentVoidBlocker,
toRate,
unitAvailabilityError,
+ unitLabel,
+ unitReturnValidator,
unpricedUnitError
} from "./validators";
@@ -31,28 +39,27 @@ it("activate, close and cancel need only the agreement", () => {
}
});
-it("return needs the line and a YYYY-MM-DD return date", () => {
+it("release needs the line and a YYYY-MM-DD date", () => {
const parsed = payloadValidator.parse({
- type: "return",
+ type: "release",
rentalAgreementLineId: "ragl_1",
returnedAt: "2026-10-14",
...scope
});
- if (parsed.type !== "return") throw new Error("wrong variant");
+ if (parsed.type !== "release") throw new Error("wrong variant");
+ expect(parsed.rentalAgreementLineId).toEqual("ragl_1");
expect(parsed.returnedAt).toEqual("2026-10-14");
- expect(parsed.meterIn).toEqual(undefined);
- expect(parsed.takeOutOfService).toEqual(undefined);
expect(() =>
payloadValidator.parse({
- type: "return",
+ type: "release",
returnedAt: "2026-10-14",
...scope
})
).toThrow();
expect(() =>
payloadValidator.parse({
- type: "return",
+ type: "release",
rentalAgreementLineId: "ragl_1",
returnedAt: "2026-10-14T00:00:00.000Z",
...scope
@@ -60,57 +67,15 @@ it("return needs the line and a YYYY-MM-DD return date", () => {
).toThrow();
});
-it("return carries the meter, notes and the out-of-service reason", () => {
+it("release strips a meter reading", () => {
const parsed = payloadValidator.parse({
- type: "return",
+ type: "release",
rentalAgreementLineId: "ragl_1",
returnedAt: "2026-10-14",
meterIn: 1250.5,
- returnNotes: "Scratched boom",
- takeOutOfService: true,
- outOfServiceReason: "Hydraulic leak",
...scope
});
- if (parsed.type !== "return") throw new Error("wrong variant");
- expect(parsed.meterIn).toEqual(1250.5);
- expect(parsed.outOfServiceReason).toEqual("Hydraulic leak");
-});
-
-it("taking a unit out of service at return needs a reason", () => {
- for (const outOfServiceReason of [undefined, null, "", " "]) {
- expect(() =>
- payloadValidator.parse({
- type: "return",
- rentalAgreementLineId: "ragl_1",
- returnedAt: "2026-10-14",
- takeOutOfService: true,
- outOfServiceReason,
- ...scope
- })
- ).toThrow();
- }
- expect(
- payloadValidator.parse({
- type: "return",
- rentalAgreementLineId: "ragl_1",
- returnedAt: "2026-10-14",
- takeOutOfService: false,
- ...scope
- }).type
- ).toEqual("return");
-});
-
-it("a negative meter reading and an unknown type are refused", () => {
- expect(() =>
- payloadValidator.parse({
- type: "return",
- rentalAgreementLineId: "ragl_1",
- returnedAt: "2026-10-14",
- meterIn: -1,
- ...scope
- })
- ).toThrow();
- expect(() => payloadValidator.parse({ type: "deliver", ...scope })).toThrow();
+ expect("meterIn" in parsed).toEqual(false);
});
it("activation generates through one cycle past today", () => {
@@ -354,28 +319,6 @@ it("a commenced sales-type line cannot be cancelled: early termination is a manu
).toEqual(null);
});
-it("return accepts a residual destination of Fleet or Inventory, or none", () => {
- const base = {
- type: "return",
- rentalAgreementLineId: "ragl_1",
- returnedAt: "2029-12-31",
- ...scope
- };
- for (const residualDestination of ["Fleet", "Inventory"] as const) {
- const parsed = payloadValidator.parse({ ...base, residualDestination });
- expect(
- parsed.type === "return" ? parsed.residualDestination : undefined
- ).toEqual(residualDestination);
- }
- const none = payloadValidator.parse(base);
- expect(none.type === "return" ? none.residualDestination : "unset").toEqual(
- undefined
- );
- expect(() =>
- payloadValidator.parse({ ...base, residualDestination: "Scrap" })
- ).toThrow();
-});
-
it("a return is never dated after the company's today", () => {
expect(futureReturnError("2027-03-01", "2027-03-01")).toEqual(null);
expect(futureReturnError("2027-02-28", "2027-03-01")).toEqual(null);
@@ -395,3 +338,203 @@ it("a unit at no rate cannot be activated", () => {
expect(unpricedUnitError("FA000001", Number.NaN)).not.toEqual(null);
expect(unpricedUnitError("FA000001", 0.01)).toEqual(null);
});
+
+it("a unit return needs the line and a YYYY-MM-DD return date", () => {
+ const parsed = unitReturnValidator.parse({
+ rentalAgreementLineId: "ragl_1",
+ returnedAt: "2026-10-14"
+ });
+ expect(parsed.returnedAt).toEqual("2026-10-14");
+ expect(parsed.meterIn).toEqual(undefined);
+ expect(parsed.takeOutOfService).toEqual(undefined);
+
+ expect(() =>
+ unitReturnValidator.parse({ returnedAt: "2026-10-14" })
+ ).toThrow();
+ expect(() =>
+ unitReturnValidator.parse({
+ rentalAgreementLineId: "ragl_1",
+ returnedAt: "2026-10-14T00:00:00.000Z"
+ })
+ ).toThrow();
+});
+
+it("a unit return carries the meter, notes and the out-of-service reason", () => {
+ const parsed = unitReturnValidator.parse({
+ rentalAgreementLineId: "ragl_1",
+ returnedAt: "2026-10-14",
+ meterIn: 1250.5,
+ returnNotes: "Scratched boom",
+ takeOutOfService: true,
+ outOfServiceReason: "Hydraulic leak",
+ residualDestination: "Fleet"
+ });
+ expect(parsed.meterIn).toEqual(1250.5);
+ expect(parsed.outOfServiceReason).toEqual("Hydraulic leak");
+ expect(parsed.residualDestination).toEqual("Fleet");
+});
+
+it("taking a unit out of service on a unit return needs a reason", () => {
+ for (const outOfServiceReason of [undefined, null, "", " "]) {
+ expect(() =>
+ unitReturnValidator.parse({
+ rentalAgreementLineId: "ragl_1",
+ returnedAt: "2026-10-14",
+ takeOutOfService: true,
+ outOfServiceReason
+ })
+ ).toThrow();
+ }
+ expect(
+ unitReturnValidator.parse({
+ rentalAgreementLineId: "ragl_1",
+ returnedAt: "2026-10-14",
+ takeOutOfService: false
+ }).takeOutOfService
+ ).toEqual(false);
+});
+
+it("a unit is named by its asset number, else its asset name, else its line", () => {
+ expect(unitLabel({ fixedAssetId: "FA-1", name: "Lift" }, "ragl_1")).toEqual(
+ "FA-1"
+ );
+ expect(unitLabel({ fixedAssetId: null, name: "Lift" }, "ragl_1")).toEqual(
+ "Lift"
+ );
+ expect(unitLabel(undefined, "ragl_1")).toEqual("ragl_1");
+});
+
+it("a delivery is never dated after today", () => {
+ expect(futureDeliveryError("2026-10-15", "2026-10-14")).toEqual(
+ "The delivery date cannot be in the future"
+ );
+ expect(futureDeliveryError("2026-10-14", "2026-10-14")).toBeNull();
+});
+
+it("a release is never dated after today", () => {
+ expect(futureReleaseError("2026-10-15", "2026-10-14")).toEqual(
+ "The release date cannot be in the future"
+ );
+ expect(futureReleaseError("2026-10-14", "2026-10-14")).toBeNull();
+});
+
+it("a rental shipment voids only while every unit is On Rent", () => {
+ expect(
+ rentalShipmentVoidBlocker([
+ { label: "FA-1", status: "On Rent", accrual: "Posted" },
+ { label: "FA-2", status: "Returned", accrual: null }
+ ])
+ ).toEqual(
+ "FA-2 is Returned; a rental shipment can be voided only while every unit is On Rent"
+ );
+});
+
+it("a rental shipment does not void over a posted accrual", () => {
+ expect(
+ rentalShipmentVoidBlocker([
+ { label: "FA-1", status: "On Rent", accrual: null },
+ { label: "FA-2", status: "On Rent", accrual: "Posted" }
+ ])
+ ).toEqual(
+ "A posted revenue recognition run holds accrued rent for FA-2; the shipment cannot be voided"
+ );
+});
+
+it("a rental shipment does not void over a draft run's accrual", () => {
+ expect(
+ rentalShipmentVoidBlocker([
+ { label: "FA-1", status: "On Rent", accrual: "Draft run" },
+ { label: "FA-2", status: "On Rent", accrual: "Posted" }
+ ])
+ ).toEqual(
+ "A draft revenue recognition run holds accrued rent for FA-1; delete the run before voiding the shipment"
+ );
+});
+
+it("a rental shipment with every unit On Rent and no accrual voids", () => {
+ expect(
+ rentalShipmentVoidBlocker([
+ { label: "FA-1", status: "On Rent", accrual: null },
+ { label: "FA-2", status: "On Rent", accrual: null }
+ ])
+ ).toBeNull();
+});
+
+it("an open rental shipment blocks the close first", () => {
+ expect(
+ openRentalDocumentBlocker({
+ shipmentId: "SHP-000004",
+ receiptId: "RCV-000002"
+ })
+ ).toEqual(
+ "Shipment SHP-000004 is still open; post or delete it before closing the agreement"
+ );
+});
+
+it("an open rental receipt blocks the close", () => {
+ expect(
+ openRentalDocumentBlocker({ shipmentId: null, receiptId: "RCV-000002" })
+ ).toEqual(
+ "Receipt RCV-000002 is still open; post or delete it before closing the agreement"
+ );
+});
+
+it("no open rental document leaves the close alone", () => {
+ expect(
+ openRentalDocumentBlocker({ shipmentId: null, receiptId: null })
+ ).toBeNull();
+});
+
+it("a rental receipt returns a Pending or On Rent unit only", () => {
+ expect(receiptReturnError("FA-1", "Returned")).toEqual(
+ "FA-1 is Returned; only a Pending or On Rent unit can be returned"
+ );
+ expect(receiptReturnError("FA-1", "Pending")).toBeNull();
+ expect(receiptReturnError("FA-1", "On Rent")).toBeNull();
+});
+
+it("only a Pending unit can be released", () => {
+ expect(
+ releaseBlocker({
+ label: "FA-1",
+ status: "On Rent",
+ classification: "Sale",
+ openDocument: "shipment SHP-000004"
+ })
+ ).toEqual("FA-1 is On Rent; only a Pending unit can be released");
+});
+
+it("a unit treated as a sale is not released", () => {
+ expect(
+ releaseBlocker({
+ label: "FA-1",
+ status: "Pending",
+ classification: "Sale",
+ openDocument: "shipment SHP-000004"
+ })
+ ).toEqual("FA-1 is treated as a sale; return it on a rental receipt instead");
+});
+
+it("a unit on an open rental document is not released", () => {
+ expect(
+ releaseBlocker({
+ label: "FA-1",
+ status: "Pending",
+ classification: "Rental",
+ openDocument: "receipt RCV-000002"
+ })
+ ).toEqual(
+ "FA-1 is on receipt RCV-000002; remove it there before releasing the unit"
+ );
+});
+
+it("a Pending rental unit on no open document is released", () => {
+ expect(
+ releaseBlocker({
+ label: "FA-1",
+ status: "Pending",
+ classification: null,
+ openDocument: null
+ })
+ ).toBeNull();
+});
diff --git a/packages/server-functions/src/post-rental-agreement/validators.ts b/packages/server-functions/src/post-rental-agreement/validators.ts
index d2cfaff9ee..acfb212c3d 100644
--- a/packages/server-functions/src/post-rental-agreement/validators.ts
+++ b/packages/server-functions/src/post-rental-agreement/validators.ts
@@ -37,22 +37,20 @@ export const activateValidator = z.object({
export const RESIDUAL_DESTINATIONS = ["Fleet", "Inventory"] as const;
export type ResidualDestination = (typeof RESIDUAL_DESTINATIONS)[number];
-/** A unit comes back: re-cut its billing, optionally straight to maintenance.
- * `residualDestination` is where a SALES-TYPE unit goes at the end of its
- * term — a new Rental Fleet asset, or stock — and is required for such a
- * line (the function refuses without it); an operating return ignores it. */
-export const returnValidator = z
- .object({
- type: z.literal("return"),
- rentalAgreementLineId: z.string().min(1),
- returnedAt: calendarDate,
- meterIn: z.number().min(0).optional().nullable(),
- returnNotes: z.string().optional().nullable(),
- takeOutOfService: z.boolean().optional(),
- outOfServiceReason: z.string().optional().nullable(),
- residualDestination: z.enum(RESIDUAL_DESTINATIONS).optional().nullable(),
- ...scope
- })
+/** One unit coming back, without the agreement: the fields a rental receipt
+ * line and the agreement's return action share. */
+const unitReturnFields = {
+ rentalAgreementLineId: z.string().min(1),
+ returnedAt: calendarDate,
+ meterIn: z.number().min(0).optional().nullable(),
+ returnNotes: z.string().optional().nullable(),
+ takeOutOfService: z.boolean().optional(),
+ outOfServiceReason: z.string().optional().nullable(),
+ residualDestination: z.enum(RESIDUAL_DESTINATIONS).optional().nullable()
+};
+
+export const unitReturnValidator = z
+ .object(unitReturnFields)
.refine(
(data) => !data.takeOutOfService || !!data.outOfServiceReason?.trim(),
{
@@ -61,6 +59,15 @@ export const returnValidator = z
}
);
+/** 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
+});
+
/** Every unit is back (or sold) and everything is billed. */
export const closeValidator = z.object({
type: z.literal("close"),
@@ -75,7 +82,7 @@ export const cancelValidator = z.object({
export const payloadValidator = z.discriminatedUnion("type", [
activateValidator,
- returnValidator,
+ releaseValidator,
closeValidator,
cancelValidator
]);
@@ -242,3 +249,99 @@ export function cancelBlocker(args: {
}
return null;
}
+
+/** 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 {
+ return asset?.fixedAssetId || asset?.name || lineId;
+}
+
+/** Why a delivery cannot be dated `deliveredOn`, or null. */
+export function futureDeliveryError(
+ deliveredOn: string,
+ today: string
+): string | null {
+ // `YYYY-MM-DD` compares chronologically as text.
+ return deliveredOn > today
+ ? "The delivery date cannot be in the future"
+ : null;
+}
+
+/** 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 {
+ const notOnRent = units.find((unit) => unit.status !== "On Rent");
+ if (notOnRent) {
+ return `${notOnRent.label} is ${notOnRent.status}; a rental shipment can be voided only while every unit is On Rent`;
+ }
+ for (const unit of units) {
+ if (unit.accrual === "Posted") {
+ return `A posted revenue recognition run holds accrued rent for ${unit.label}; the shipment cannot be voided`;
+ }
+ if (unit.accrual === "Draft run") {
+ return `A draft revenue recognition run holds accrued rent for ${unit.label}; delete the run before voiding the shipment`;
+ }
+ }
+ return 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 {
+ if (args.shipmentId) {
+ return `Shipment ${args.shipmentId} is still open; post or delete it before closing the agreement`;
+ }
+ if (args.receiptId) {
+ return `Receipt ${args.receiptId} is still open; post or delete it before closing the agreement`;
+ }
+ return 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 {
+ return RETURNABLE_LINE_STATUSES.has(status)
+ ? null
+ : `${label} is ${status}; only a Pending or On Rent unit can be returned`;
+}
+
+/** Why a release date is refused, or null. */
+export function futureReleaseError(
+ releasedOn: string,
+ today: string
+): string | null {
+ // `YYYY-MM-DD` compares chronologically as text.
+ return releasedOn > today ? "The release date cannot be in the future" : null;
+}
+
+/** 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 {
+ if (args.status !== "Pending") {
+ return `${args.label} is ${args.status}; only a Pending unit can be released`;
+ }
+ if (args.classification === "Sale") {
+ return `${args.label} is treated as a sale; return it on a rental receipt instead`;
+ }
+ if (args.openDocument) {
+ return `${args.label} is on ${args.openDocument}; remove it there before releasing the unit`;
+ }
+ return null;
+}
diff --git a/packages/server-functions/src/post-shipment/index.ts b/packages/server-functions/src/post-shipment/index.ts
index 6ed03ffcb0..9e9411da1e 100644
--- a/packages/server-functions/src/post-shipment/index.ts
+++ b/packages/server-functions/src/post-shipment/index.ts
@@ -48,12 +48,18 @@ import {
resolveInventoryAccount
} from "../lib/get-posting-group";
import { assertPostable } from "../lib/postable";
+import { postRentalShipment, voidRentalShipment } from "./rental-agreement";
const logger = getLogger("server-functions", "post-shipment");
export const postShipmentInput = z.object({
type: z.enum(["post", "void"]),
- shipmentId: z.string()
+ 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()
});
/** Posts or voids a shipment: stock, tracked entities, COGS and journal rows. */
@@ -61,7 +67,7 @@ const postShipment = defineServerFn({
name: "post-shipment",
input: postShipmentInput,
permissions: { update: "inventory" },
- async run(ctx, { type, shipmentId }) {
+ async run(ctx, { type, shipmentId, postingDate }) {
const { db, companyId, userId } = ctx;
logger.info({ type, shipmentId, userId, companyId });
@@ -630,11 +636,13 @@ const postShipment = defineServerFn({
const { data: shipmentFaLines } = await many(
db,
"shipmentFixedAssetLine",
- { shipmentId, shipped: true },
+ { shipmentId, shipped: true, companyId },
{ columns: ["salesOrderLineId", "serialNumber"] }
);
const shippedFaSoLineIds = new Set(
- (shipmentFaLines ?? []).map((r) => r.salesOrderLineId)
+ (shipmentFaLines ?? [])
+ .filter((r) => r.salesOrderLineId !== null)
+ .map((r) => r.salesOrderLineId)
);
const faSalesOrderLines = salesOrderLines.data.filter(
@@ -3035,6 +3043,17 @@ const postShipment = defineServerFn({
break;
}
+ case "Rental Agreement": {
+ await postRentalShipment(db, {
+ shipmentId,
+ companyId,
+ userId,
+ today,
+ postingDate
+ });
+ break;
+ }
+
default: {
throw new Error(
`Invalid source document type: ${shipmentHeader.sourceDocument}`
@@ -4691,6 +4710,11 @@ const postShipment = defineServerFn({
break;
}
+ case "Rental Agreement": {
+ await voidRentalShipment(db, { shipmentId, companyId, userId });
+ break;
+ }
+
default: {
throw new Error(
`Invalid source document type: ${shipmentHeader.sourceDocument}`
diff --git a/packages/server-functions/src/post-shipment/rental-agreement.test.ts b/packages/server-functions/src/post-shipment/rental-agreement.test.ts
new file mode 100644
index 0000000000..b59452cea9
--- /dev/null
+++ b/packages/server-functions/src/post-shipment/rental-agreement.test.ts
@@ -0,0 +1,387 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Posting a rental shipment against the live database: the ticked units go On
+// Rent on the delivery date, nothing moves in stock, and the refusals name the
+// unit.
+
+import type { KyselyDatabase } from "@carbon/database/client";
+import { datetime } from "@carbon/utils";
+import { type Insertable, sql } from "kysely";
+import { expect } from "vitest";
+import create from "../create";
+import { databaseTest } from "../local-database-test-fixture";
+import { rentalFixture } from "../post-rental-agreement/rental-test-fixture";
+import { synthesizeRentalAccruals } from "../propose-revenue-recognition-run";
+import postShipment from "./index";
+
+type Fixture = Awaited<ReturnType<typeof rentalFixture>>;
+
+const TIME_ZONE = "America/New_York";
+
+async function draftShipment(f: Fixture): Promise<string> {
+ const result = await create(f.ctx, {
+ type: "shipmentFromRentalAgreement",
+ rentalAgreementId: f.agreementId
+ });
+ if (result.error) throw result.error;
+ return result.data.id;
+}
+
+function post(f: Fixture, shipmentId: string, postingDate?: string) {
+ return postShipment(f.ctx, { type: "post", shipmentId, postingDate });
+}
+
+async function setShipped(
+ f: Fixture,
+ shipmentId: string,
+ lineIds: string[],
+ shipped: boolean
+) {
+ await f.db
+ .updateTable("shipmentFixedAssetLine")
+ .set({ shipped })
+ .where("shipmentId", "=", shipmentId)
+ .where("rentalAgreementLineId", "in", lineIds)
+ .where("companyId", "=", f.companyId)
+ .execute();
+}
+
+function shipmentStatus(f: Fixture, shipmentId: string) {
+ return f.db
+ .selectFrom("shipment")
+ .select([
+ "status",
+ sql<string | null>`"postingDate"::text`.as("postingDate")
+ ])
+ .where("id", "=", shipmentId)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+}
+
+async function countRows(
+ f: Fixture,
+ table: "itemLedger" | "costLedger" | "journalLine"
+): Promise<number> {
+ const row = await f.db
+ .selectFrom(table)
+ .select(sql<number>`count(*)::int`.as("count"))
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ return Number(row.count);
+}
+
+databaseTest(
+ "a rental shipment puts the ticked units On Rent on the delivery date and moves no stock",
+ async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const shipmentId = await draftShipment(f);
+ const [metered, , , unticked1, unticked2] = f.lineIds as [
+ string,
+ string,
+ string,
+ string,
+ string
+ ];
+ await setShipped(f, shipmentId, [unticked1, unticked2], false);
+ await f.db
+ .updateTable("shipmentFixedAssetLine")
+ .set({ meter: 120 })
+ .where("shipmentId", "=", shipmentId)
+ .where("rentalAgreementLineId", "=", metered)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ const deliveredOn = datetime
+ .today(TIME_ZONE)
+ .subtract({ days: 3 })
+ .toString();
+
+ const result = await post(f, shipmentId, deliveredOn);
+ expect(result.error).toBeNull();
+
+ const lines = await f.db
+ .selectFrom("rentalAgreementLine")
+ .select([
+ "id",
+ "status",
+ "meterOut",
+ sql<string | null>`"deliveredAt"::text`.as("deliveredAt")
+ ])
+ .where("rentalAgreementId", "=", f.agreementId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ const onRent = lines.filter((line) => line.status === "On Rent");
+ expect(onRent).toHaveLength(3);
+ expect(onRent.every((line) => line.deliveredAt === deliveredOn)).toBe(
+ true
+ );
+ expect(
+ onRent.filter((line) => Number(line.meterOut) === 120).map((l) => l.id)
+ ).toEqual([metered]);
+ expect(
+ lines
+ .filter((line) => line.status === "Pending")
+ .map((line) => line.id)
+ .sort()
+ ).toEqual([unticked1, unticked2].sort());
+ expect(await shipmentStatus(f, shipmentId)).toEqual({
+ status: "Posted",
+ postingDate: deliveredOn
+ });
+
+ expect(await countRows(f, "itemLedger")).toBe(0);
+ expect(await countRows(f, "costLedger")).toBe(0);
+ expect(await countRows(f, "journalLine")).toBe(0);
+ const activities = await f.db
+ .selectFrom("trackedActivity")
+ .select(sql<number>`count(*)::int`.as("count"))
+ .where("companyId", "=", f.companyId)
+ .where("type", "=", "Rental Delivery")
+ .executeTakeFirstOrThrow();
+ expect(Number(activities.count)).toBe(3);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest("a rental delivery is never dated in the future", async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const shipmentId = await draftShipment(f);
+ const tomorrow = datetime.today(TIME_ZONE).add({ days: 1 }).toString();
+ const result = await post(f, shipmentId, tomorrow);
+ expect(result.error?.message).toContain(
+ "The delivery date cannot be in the future"
+ );
+ expect((await shipmentStatus(f, shipmentId)).status).toEqual("Draft");
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("an out-of-service unit is not delivered", async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const shipmentId = await draftShipment(f);
+ await f.db
+ .updateTable("fixedAsset")
+ .set({
+ outOfServiceSince: "2026-09-01",
+ outOfServiceReason: "Hydraulic leak"
+ })
+ .where("id", "=", f.fixedAssetIds[0]!)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ const result = await post(f, shipmentId);
+ expect(result.error?.message).toContain("Hydraulic leak");
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("a unit already On Rent is not delivered again", async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const shipmentId = await draftShipment(f);
+ await f.db
+ .updateTable("rentalAgreementLine")
+ .set({ status: "On Rent", deliveredAt: "2026-09-01" })
+ .where("id", "=", f.lineIds[0]!)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ const result = await post(f, shipmentId);
+ expect(result.error?.message).toContain("FA-");
+ expect(result.error?.message).toContain("is On Rent");
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest("a rental shipment with no ticked unit is refused", async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const shipmentId = await draftShipment(f);
+ await setShipped(f, shipmentId, f.lineIds, false);
+ const result = await post(f, shipmentId);
+ expect(result.error?.message).toContain(
+ "Select at least one unit to deliver"
+ );
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest(
+ "a backdated delivery accrues from the delivery date in its own month",
+ async () => {
+ const f = await rentalFixture({ billingTiming: "Arrears" });
+ try {
+ await f.db
+ .updateTable("rentalBillingPeriod")
+ .set({ status: "Pending" })
+ .where("rentalAgreementLineId", "=", f.lineIds[0]!)
+ .where("companyId", "=", f.companyId)
+ .execute();
+
+ // The accrual reads the Contract Assets and Rental Income defaults;
+ // every account default points at the fixture's one account.
+ const assetClass = await f.db
+ .selectFrom("fixedAssetClass")
+ .select("assetAccountId")
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ const accountColumns = await sql<{ column_name: string }>`
+ SELECT column_name FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = 'accountDefault'
+ AND column_name LIKE '%Account'`.execute(f.db);
+ await f.db
+ .insertInto("accountDefault")
+ .values({
+ companyId: f.companyId,
+ ...Object.fromEntries(
+ accountColumns.rows.map((row) => [
+ row.column_name,
+ assetClass.assetAccountId
+ ])
+ )
+ } as unknown as Insertable<KyselyDatabase["accountDefault"]>)
+ .execute();
+
+ const shipmentId = await draftShipment(f);
+ const result = await post(f, shipmentId, "2026-09-25");
+ expect(result.error).toBeNull();
+
+ const accrue = (periodEnd: string) =>
+ f.db.transaction().execute((trx) =>
+ synthesizeRentalAccruals(trx, {
+ companyId: f.companyId,
+ periodEnd,
+ userId: "system"
+ })
+ );
+ const septemberAccruals = async () =>
+ (
+ await f.db
+ .selectFrom("revenueRecognitionSchedule")
+ .select([
+ sql<string>`"periodStart"::text`.as("periodStart"),
+ sql<string>`"periodEnd"::text`.as("periodEnd")
+ ])
+ .where("companyId", "=", f.companyId)
+ .where("type", "=", "Accrual")
+ .execute()
+ ).filter((row) => row.periodStart.startsWith("2026-09"));
+
+ await accrue("2026-10-31");
+ expect(await septemberAccruals()).toEqual([]);
+
+ await accrue("2026-09-30");
+ expect(await septemberAccruals()).toEqual([
+ { periodStart: "2026-09-25", periodEnd: "2026-09-30" }
+ ]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+function voidShipment(f: Fixture, shipmentId: string) {
+ return postShipment(f.ctx, { type: "void", shipmentId });
+}
+
+databaseTest(
+ "a voided rental shipment puts its units back to Pending",
+ async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const shipmentId = await draftShipment(f);
+ expect((await post(f, shipmentId)).error).toBeNull();
+
+ const result = await voidShipment(f, shipmentId);
+ expect(result.error).toBeNull();
+
+ const lines = await f.db
+ .selectFrom("rentalAgreementLine")
+ .select(["status", "deliveredAt", "meterOut"])
+ .where("rentalAgreementId", "=", f.agreementId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ expect(lines).toHaveLength(5);
+ for (const line of lines) {
+ expect(line).toEqual({
+ status: "Pending",
+ deliveredAt: null,
+ meterOut: null
+ });
+ }
+ expect((await shipmentStatus(f, shipmentId)).status).toEqual("Voided");
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "a rental shipment does not void over a posted accrual",
+ async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const shipmentId = await draftShipment(f);
+ expect((await post(f, shipmentId)).error).toBeNull();
+ const assetClass = await f.db
+ .selectFrom("fixedAssetClass")
+ .select("assetAccountId")
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ await f.db
+ .insertInto("revenueRecognitionSchedule")
+ .values({
+ companyId: f.companyId,
+ type: "Accrual",
+ status: "Posted",
+ rentalAgreementLineId: f.lineIds[0]!,
+ periodStart: "2026-09-01",
+ periodEnd: "2026-09-30",
+ scheduledDate: "2026-09-30",
+ amount: 300,
+ debitAccountId: assetClass.assetAccountId,
+ creditAccountId: assetClass.assetAccountId,
+ createdBy: "system"
+ })
+ .execute();
+
+ const result = await voidShipment(f, shipmentId);
+ expect(result.error?.message).toContain(
+ "A posted revenue recognition run holds accrued rent for FA-"
+ );
+ expect((await shipmentStatus(f, shipmentId)).status).toEqual("Posted");
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "a rental shipment does not void once a unit is returned",
+ async () => {
+ const f = await rentalFixture({ units: 5 });
+ try {
+ const shipmentId = await draftShipment(f);
+ expect((await post(f, shipmentId)).error).toBeNull();
+ await f.db
+ .updateTable("rentalAgreementLine")
+ .set({ status: "Returned" })
+ .where("id", "=", f.lineIds[0]!)
+ .where("companyId", "=", f.companyId)
+ .execute();
+
+ const result = await voidShipment(f, shipmentId);
+ expect(result.error?.message).toContain("is Returned");
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
diff --git a/packages/server-functions/src/post-shipment/rental-agreement.ts b/packages/server-functions/src/post-shipment/rental-agreement.ts
new file mode 100644
index 0000000000..d41ff5a7a5
--- /dev/null
+++ b/packages/server-functions/src/post-shipment/rental-agreement.ts
@@ -0,0 +1,335 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// A rental shipment delivers the ticked units of one Active agreement: each
+// line goes On Rent on the delivery date. The units stay fleet assets, so
+// nothing moves in stock and no journal is posted.
+
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { datetime } from "@carbon/utils";
+import type { Transaction } from "kysely";
+import { InvalidInputError, NotFoundError } from "../errors";
+import {
+ insertUnitActivity,
+ lockAgreement
+} from "../post-rental-agreement/agreement";
+import {
+ futureDeliveryError,
+ rentalShipmentVoidBlocker,
+ unitLabel
+} from "../post-rental-agreement/validators";
+
+export async function postRentalShipment(
+ db: Kysely<KyselyDatabase>,
+ args: {
+ shipmentId: string;
+ companyId: string;
+ userId: string;
+ today: string;
+ postingDate?: string;
+ }
+): Promise<void> {
+ const { shipmentId, companyId, userId, today } = args;
+
+ await db.transaction().execute(async (trx) => {
+ const deliveredOn = args.postingDate ?? today;
+ const future = futureDeliveryError(deliveredOn, today);
+ if (future) throw new InvalidInputError(future);
+
+ const shipment = await trx
+ .selectFrom("shipment")
+ .select(["id", "shipmentId", "sourceDocumentId", "status"])
+ .where("id", "=", shipmentId)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ if (!shipment) throw new NotFoundError("Shipment not found");
+
+ const assetLines = await trx
+ .selectFrom("shipmentFixedAssetLine")
+ .select(["id", "rentalAgreementLineId", "meter"])
+ .where("shipmentId", "=", shipmentId)
+ .where("companyId", "=", companyId)
+ .where("shipped", "=", true)
+ .where("rentalAgreementLineId", "is not", null)
+ .orderBy("createdAt")
+ .orderBy("id")
+ .execute();
+ if (assetLines.length === 0) {
+ throw new InvalidInputError("Select at least one unit to deliver");
+ }
+
+ if (!shipment.sourceDocumentId) {
+ throw new NotFoundError("Rental agreement not found");
+ }
+ const agreement = await lockAgreement(
+ trx,
+ companyId,
+ shipment.sourceDocumentId
+ );
+ if (agreement.status !== "Active") {
+ throw new InvalidInputError(
+ `Rental agreement ${agreement.rentalAgreementId} is ${agreement.status}; units are delivered from an Active agreement`
+ );
+ }
+
+ const { linesById, assetsById } = await lockRentalUnits(
+ trx,
+ companyId,
+ assetLines.map((line) => line.rentalAgreementLineId!)
+ );
+
+ const units = assetLines.map((assetLine) => {
+ const lineId = assetLine.rentalAgreementLineId!;
+ const line = linesById.get(lineId);
+ const asset = line?.fixedAssetId
+ ? assetsById.get(line.fixedAssetId)
+ : undefined;
+ const label = unitLabel(asset, lineId);
+ if (!line || line.rentalAgreementId !== agreement.id) {
+ throw new NotFoundError("Rental agreement line not found");
+ }
+ if (line.status !== "Pending") {
+ throw new InvalidInputError(
+ `${label} is ${line.status}; only a Pending unit can be delivered`
+ );
+ }
+ if (asset?.outOfServiceSince) {
+ throw new InvalidInputError(
+ `${label} is out of service: ${asset.outOfServiceReason ?? "no reason given"}`
+ );
+ }
+ return { line, meter: assetLine.meter };
+ });
+
+ for (const { line, meter } of units) {
+ await trx
+ .updateTable("rentalAgreementLine")
+ .set({
+ status: "On Rent",
+ deliveredAt: deliveredOn,
+ meterOut: meter,
+ updatedBy: userId,
+ updatedAt: datetime.timestamp()
+ })
+ .where("id", "=", line.id)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+
+ for (const { line } of units) {
+ if (!line.trackedEntityId) continue;
+ await insertUnitActivity(trx, {
+ type: "Rental Delivery",
+ direction: "input",
+ sourceDocument: "Shipment",
+ sourceDocumentId: shipment.id,
+ sourceDocumentReadableId: shipment.shipmentId,
+ attributes: { Shipment: shipment.id, "Rental Agreement": agreement.id },
+ trackedEntityId: line.trackedEntityId,
+ companyId,
+ userId
+ });
+ }
+
+ await trx
+ .updateTable("shipment")
+ .set({
+ status: "Posted",
+ postingDate: deliveredOn,
+ postedBy: userId
+ })
+ .where("id", "=", shipmentId)
+ .where("companyId", "=", companyId)
+ .execute();
+ });
+}
+
+/** Voids a Posted rental shipment: its units go back to Pending, as if never
+ * delivered. Refused once a unit has moved on or its accrued rent is in a
+ * posted or draft recognition run. */
+export async function voidRentalShipment(
+ db: Kysely<KyselyDatabase>,
+ args: { shipmentId: string; companyId: string; userId: string }
+): Promise<void> {
+ const { shipmentId, companyId, userId } = args;
+
+ await db.transaction().execute(async (trx) => {
+ const shipment = await trx
+ .selectFrom("shipment")
+ .select(["id", "shipmentId", "sourceDocumentId"])
+ .where("id", "=", shipmentId)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ if (!shipment) throw new NotFoundError("Shipment not found");
+
+ const assetLines = await trx
+ .selectFrom("shipmentFixedAssetLine")
+ .select(["id", "rentalAgreementLineId"])
+ .where("shipmentId", "=", shipmentId)
+ .where("companyId", "=", companyId)
+ .where("shipped", "=", true)
+ .where("rentalAgreementLineId", "is not", null)
+ .orderBy("createdAt")
+ .orderBy("id")
+ .execute();
+
+ if (!shipment.sourceDocumentId) {
+ throw new NotFoundError("Rental agreement not found");
+ }
+ const agreement = await lockAgreement(
+ trx,
+ companyId,
+ shipment.sourceDocumentId
+ );
+
+ const lineIds = assetLines.map((line) => line.rentalAgreementLineId!);
+ const { linesById, assetsById } = await lockRentalUnits(
+ trx,
+ companyId,
+ lineIds
+ );
+
+ const accruals =
+ lineIds.length === 0
+ ? []
+ : await trx
+ .selectFrom("revenueRecognitionSchedule")
+ .select(["rentalAgreementLineId", "status", "runLineId"])
+ .where("type", "=", "Accrual")
+ .where("companyId", "=", companyId)
+ .where("rentalAgreementLineId", "in", lineIds)
+ .execute();
+
+ const units = assetLines.map((assetLine) => {
+ const lineId = assetLine.rentalAgreementLineId!;
+ const line = linesById.get(lineId);
+ const asset = line?.fixedAssetId
+ ? assetsById.get(line.fixedAssetId)
+ : undefined;
+ if (!line || line.rentalAgreementId !== agreement.id) {
+ throw new NotFoundError("Rental agreement line not found");
+ }
+ const rows = accruals.filter(
+ (row) => row.rentalAgreementLineId === lineId
+ );
+ const accrual: "Posted" | "Draft run" | null = rows.some(
+ (row) => row.status === "Posted"
+ )
+ ? "Posted"
+ : rows.some((row) => row.status === "Planned" && row.runLineId)
+ ? "Draft run"
+ : null;
+ return {
+ line,
+ label: unitLabel(asset, lineId),
+ status: line.status,
+ accrual
+ };
+ });
+
+ const blocker = rentalShipmentVoidBlocker(units);
+ if (blocker) throw new InvalidInputError(blocker);
+
+ if (lineIds.length > 0) {
+ await trx
+ .deleteFrom("revenueRecognitionSchedule")
+ .where("type", "=", "Accrual")
+ .where("status", "=", "Planned")
+ .where("runLineId", "is", null)
+ .where("companyId", "=", companyId)
+ .where("rentalAgreementLineId", "in", lineIds)
+ .execute();
+ }
+
+ for (const { line } of units) {
+ await trx
+ .updateTable("rentalAgreementLine")
+ .set({
+ status: "Pending",
+ deliveredAt: null,
+ meterOut: null,
+ updatedBy: userId,
+ updatedAt: datetime.timestamp()
+ })
+ .where("id", "=", line.id)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+
+ for (const { line } of units) {
+ if (!line.trackedEntityId) continue;
+ await insertUnitActivity(trx, {
+ type: "Void Shipment",
+ direction: "input",
+ sourceDocument: "Shipment",
+ sourceDocumentId: shipment.id,
+ sourceDocumentReadableId: shipment.shipmentId,
+ attributes: { Shipment: shipment.id, "Rental Agreement": agreement.id },
+ trackedEntityId: line.trackedEntityId,
+ companyId,
+ userId
+ });
+ }
+
+ await trx
+ .updateTable("shipment")
+ .set({
+ status: "Voided",
+ updatedBy: userId,
+ updatedAt: datetime.timestamp()
+ })
+ .where("id", "=", shipmentId)
+ .where("companyId", "=", companyId)
+ .execute();
+ });
+}
+
+// Locks the agreement lines a rental document names and reads their assets,
+// whose numbers name the units in a refusal.
+async function lockRentalUnits(
+ trx: Transaction<KyselyDatabase>,
+ companyId: string,
+ lineIds: string[]
+) {
+ const lines =
+ lineIds.length === 0
+ ? []
+ : await trx
+ .selectFrom("rentalAgreementLine")
+ .select([
+ "id",
+ "rentalAgreementId",
+ "status",
+ "fixedAssetId",
+ "trackedEntityId"
+ ])
+ .where("id", "in", lineIds)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .execute();
+ const linesById = new Map(lines.map((line) => [line.id, line]));
+
+ const assetIds = lines
+ .map((line) => line.fixedAssetId)
+ .filter((id): id is string => id !== null);
+ const assets =
+ assetIds.length === 0
+ ? []
+ : await trx
+ .selectFrom("fixedAsset")
+ .select([
+ "id",
+ "fixedAssetId",
+ "name",
+ "outOfServiceSince",
+ "outOfServiceReason"
+ ])
+ .where("id", "in", assetIds)
+ .where("companyId", "=", companyId)
+ .execute();
+ const assetsById = new Map(assets.map((asset) => [asset.id, asset]));
+ return { linesById, assetsById };
+}