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 charges on the rent invoice, avatar pickers, dashed-circle empty state (#1901)

Brad Barbin8c56a4b29421
diff --git a/.ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md b/.ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md
index 88d9944b15..efffa33171 100644
--- a/.ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md
+++ b/.ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md
@@ -866,7 +866,7 @@ automateSalesInvoice(invoiceId, mode) (packages/jobs/src/invoicing/auto
| D4 | Default | `Post and Email` | User decision. Rentals are not on `main`, so no existing company changes behaviour on deploy |
| D5 | `Post and Email` needs an email | The agreement override can only be SET to `Post and Email` when the agreement's contact has an email (the service refuses it; the UI disables it). At run time, a missing email degrades to post + `sendError`, never a skipped post | User decision. Checked at both ends because a contact's email can be removed after the setting is chosen, and a company default can't be validated per agreement |
| D6 | Review window | None. Posted in the same run that drafts | User decision. So there is no "will post on" date, and no "an edit makes it manual" rule |
-| D7 | Charges | When automating, charges (kind `Charge` and `Purchase Option`) go on their OWN Draft invoice, held as "charges are reviewed before posting". Rent periods go on the rent invoice, which posts | User decision. A single charge must not delay the rent. Mirrors NetSuite's Ready/Hold billing stage and Point of Rental's contract hold. `Draft Only` agreements keep today's single combined invoice, since nothing is automated |
+| D7 | Charges | When automating, charges (kind `Charge` and `Purchase Option`) go on their OWN Draft invoice, held as "charges are reviewed before posting". Rent periods go on the rent invoice, which posts | User decision. A single charge must not delay the rent. Mirrors NetSuite's Ready/Hold billing stage and Point of Rental's contract hold. `Draft Only` agreements keep today's single combined invoice, since nothing is automated. Amended 2026-10-12 (user decision): a `Charge` now goes on the rent invoice, unheld, unless marked `invoiceSeparately` (default false); a `Purchase Option` is always separate and held |
| D8 | Holds (left in Draft) | (a) charges invoice; (b) rent invoice carrying an early-return adjustment row; (c) a sales-rule violation of any severity, warnings included; (d) the company requires a customer contact and location and the invoice lacks one; (e) any posting failure (locked or closed period, missing account default, …), with the edge function's message | User decision (holds a–e; first invoice NOT held). The job can't acknowledge a warning, so a warning holds |
| D9 | First invoice | Not held | User decision. The terms were just reviewed at activation |
| D10 | Where automation runs | Inline in the `recurring-billing` cron (renamed from `rental-billing`, U4), one `step.run` per invoice; plus an event-triggered function for the two ERP buttons. Both call one `automateSalesInvoice` | Steps give per-invoice isolation and memoized retries (one failure never stops the run). Sharing one function keeps the button and the cron identical |
diff --git a/apps/erp/app/components/Empty.tsx b/apps/erp/app/components/Empty.tsx
index 127d5299be..ed2b3da90f 100644
--- a/apps/erp/app/components/Empty.tsx
+++ b/apps/erp/app/components/Empty.tsx
@@ -3,7 +3,6 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { cn, VStack } from "@carbon/react";
-import { EmptyCabinet } from "@carbon/viewer/empty-cabinet";
import { Trans } from "@lingui/react/macro";
import type { ComponentProps } from "react";
@@ -20,7 +19,21 @@ export default function Empty({
)}
{...props}
>
- <EmptyCabinet className="shrink-0 mb-4" />
+ <svg
+ aria-hidden="true"
+ viewBox="0 0 64 64"
+ className="size-16 shrink-0 mb-4 text-muted-foreground/40"
+ >
+ <circle
+ cx="32"
+ cy="32"
+ r="30"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeDasharray="4 4"
+ />
+ </svg>
<h3 className="text-lg font-medium tracking-tight text-foreground max-md:text-[17px] max-md:font-semibold">
<Trans>No data yet</Trans>
</h3>
diff --git a/apps/erp/app/components/Form/Customer.tsx b/apps/erp/app/components/Form/Customer.tsx
index 3af2a3cf62..3e05792d80 100644
--- a/apps/erp/app/components/Form/Customer.tsx
+++ b/apps/erp/app/components/Form/Customer.tsx
@@ -36,7 +36,11 @@ const Customer = (props: CustomerSelectProps) => {
const triggerRef = useRef<HTMLButtonElement>(null);
const options = useMemo(() => {
- const all = customers.map((c) => ({ value: c.id, label: c.name }));
+ const all = customers.map((c) => ({
+ value: c.id,
+ label: <CustomerAvatar customerId={c.id} />,
+ keywords: c.name
+ }));
return props.exclude?.length
? all.filter((o) => !props.exclude!.includes(o.value))
: all;
diff --git a/apps/erp/app/components/Form/Customers.tsx b/apps/erp/app/components/Form/Customers.tsx
index 857ca56407..d434672233 100644
--- a/apps/erp/app/components/Form/Customers.tsx
+++ b/apps/erp/app/components/Form/Customers.tsx
@@ -9,6 +9,7 @@ import { useMemo, useRef, useState } from "react";
import { useUser } from "~/hooks";
import CustomerForm from "~/modules/sales/ui/Customer/CustomerForm";
import { useCustomers } from "~/stores";
+import CustomerAvatar from "../CustomerAvatar";
import { useEmptyState } from "./emptyStates";
type CustomerSelectProps = Omit<CreatableMultiSelectProps, "options">;
@@ -26,7 +27,8 @@ const Customers = (props: CustomerSelectProps) => {
() =>
customers.map((c) => ({
value: c.id,
- label: c.name
+ label: <CustomerAvatar customerId={c.id} />,
+ keywords: c.name
})) ?? [],
[customers]
);
diff --git a/apps/erp/app/components/Form/Supplier.tsx b/apps/erp/app/components/Form/Supplier.tsx
index 147ba9a51c..fb411d1a0c 100644
--- a/apps/erp/app/components/Form/Supplier.tsx
+++ b/apps/erp/app/components/Form/Supplier.tsx
@@ -49,7 +49,8 @@ const Supplier = ({
.filter((s) => !onlyApproved || s.supplierStatus === "Active")
.map((c) => ({
value: c.id,
- label: c.name
+ label: <SupplierAvatar supplierId={c.id} />,
+ keywords: c.name
})) ?? [],
[suppliers, allowedSuppliers, onlyApproved]
);
diff --git a/apps/erp/app/components/Form/Suppliers.tsx b/apps/erp/app/components/Form/Suppliers.tsx
index 278e5c0231..2cc39dcb4c 100644
--- a/apps/erp/app/components/Form/Suppliers.tsx
+++ b/apps/erp/app/components/Form/Suppliers.tsx
@@ -8,6 +8,7 @@ import { useDisclosure } from "@carbon/react";
import { useMemo, useRef, useState } from "react";
import { SupplierForm } from "~/modules/purchasing/ui/Supplier";
import { useSuppliers } from "~/stores";
+import SupplierAvatar from "../SupplierAvatar";
import { useEmptyState } from "./emptyStates";
type SupplierSelectProps = Omit<CreatableMultiSelectProps, "options"> & {
@@ -25,7 +26,8 @@ const Suppliers = (props: SupplierSelectProps) => {
return (
suppliers.map((c) => ({
value: c.id,
- label: c.name
+ label: <SupplierAvatar supplierId={c.id} />,
+ keywords: c.name
})) ?? []
);
}, [suppliers]);
diff --git a/apps/erp/app/components/Form/Tags.tsx b/apps/erp/app/components/Form/Tags.tsx
index bf510a79b0..dc1525f7b2 100644
--- a/apps/erp/app/components/Form/Tags.tsx
+++ b/apps/erp/app/components/Form/Tags.tsx
@@ -22,7 +22,7 @@ type TagsSelectProps = Omit<
const TagsPreview = (
value: string[],
- options: { value: string; label: string; helper?: string }[],
+ options: { value: string; label: string | JSX.Element; helper?: string }[],
maxPreview?: number
) => {
return (
diff --git a/apps/erp/app/modules/accounting/AGENTS.md b/apps/erp/app/modules/accounting/AGENTS.md
index ebd5562457..5d045300ac 100644
--- a/apps/erp/app/modules/accounting/AGENTS.md
+++ b/apps/erp/app/modules/accounting/AGENTS.md
@@ -12,7 +12,7 @@ The **Executive P&L** (`executive-pnl.tsx`) shares the income statement's loader
- **Chart of Accounts** — hierarchical account tree. Accounts have `class` (Asset/Liability/Equity/Revenue/Expense), `incomeBalance` (Balance Sheet/Income Statement), and `accountType`. Group accounts contain children; leaf accounts post transactions. Scoped by `companyGroupId`.
- **Journal Entries** — double-entry bookkeeping in the `journal` table. `amount` uses natural balances: positive Asset/Expense is debit; positive Liability/Equity/Revenue is credit. Convert by account class before summing debit-signed amounts. Lines carry dimensions and cost center allocations. Statuses (`journalEntryStatus`): a manual entry is Draft → Posted → Reversed; an automatic posting is born `Provisional` before the company's accounting cutover and `Posted` after it; the enable turns a Provisional journal into `Posted` (dated on or after the cutover) or `Superseded` (dated before it). `JournalEntryStatus` labels Superseded "Before cutover". `getJournalEntries` leaves Superseded journals out unless a status filter asks for them.
-- **The accounting cutover** (`.ai/specs/implemented/2026-10-08-accounting-cutover.md`) — every posting path writes its journal and its sub-ledger rows (cost layers, finished-goods and asset cost, deferral schedules, contract entries, intercompany rows) for every company. `companySettings.accountingCutoverDate` decides only the journal status; `hasAccountingCutover(settings)` (`accounting.utils.ts`) is the ERP's one test for it. `companySettings.accountingEnabled` still exists, but no code reads it. `accountingActivatedAt` / `accountingActivatedBy` record the enable; the `check_accounting_config_locked` trigger then refuses any change to the three cutover columns, to `company.baseCurrencyCode` and to `fiscalYearSettings.startMonth`. A new company gets a cutover from `seed-company` (the first day of the current month) and never sees the wizard. A company with no cutover sees the wizard instead of the gated pages: `AccountingBetaGate` overlays Reports, Intercompany, Journals, Periods, Fixed Assets and Depreciation Runs with a "Set up accounting" link, and `x+/accounting+/_index.tsx` redirects to the wizard. A Provisional journal has no accounting period, so it never locks the fiscal calendar (`getFiscalCalendarCommitted` counts Posted and Reversed only) and never blocks a period delete.
+- **The accounting cutover** (`.ai/specs/implemented/2026-10-08-accounting-cutover.md`) — every posting path writes its journal and its sub-ledger rows (cost layers, finished-goods and asset cost, deferral schedules, contract entries, intercompany rows) for every company. `companySettings.accountingCutoverDate` decides only the journal status; `hasAccountingCutover(settings)` (`accounting.utils.ts`) is the ERP's one test for it. `companySettings.accountingEnabled` still exists, but no code reads it. `accountingActivatedAt` / `accountingActivatedBy` record the enable; the `check_accounting_config_locked` trigger then refuses any change to the three cutover columns, to `company.baseCurrencyCode` and to `fiscalYearSettings.startMonth`. A new company gets a cutover from `seed-company` (the first day of the current month) and never sees the wizard. A company with no cutover sees the wizard instead of the gated pages: `AccountingBetaGate` overlays Reports, Intercompany, Journals, Periods and Depreciation Runs with a "Set up accounting" link (Fixed Assets and rental agreements stay open — a depreciation run or disposal is refused on the server instead), and `x+/accounting+/_index.tsx` redirects to the wizard. A Provisional journal has no accounting period, so it never locks the fiscal calendar (`getFiscalCalendarCommitted` counts Posted and Reversed only) and never blocks a period delete.
- **Journal status lists** (`@carbon/database/accounting-posting`) — every journal reader filters by one of three lists. `GL_JOURNAL_STATUSES` (Posted, Reversed): balances, trial balance, reports, period snapshots, tie-outs, provider sync. `DOCUMENT_JOURNAL_STATUSES` (Provisional, Posted, Reversed): a reader that follows one document's chain — void builders, GR/IR, WIP sums, intercompany lookups. `OPEN_ITEM_JOURNAL_STATUSES` (Provisional, Posted): payment control lookups and the memo, charge and reimbursement void checks. Superseded is in none. The `journal-status-filter` check (`@carbon/checks`) fails a `status <> 'Draft'` journal filter in TS and in migrations from `20261009005144`. The AR/AP readers (`get_ar_open_by_customer`, `get_ap_open_by_supplier`, `get_ar_tie_out`, `get_ap_tie_out`) keep `= 'Posted'` and also accept `sourceType 'Opening Balance'` (`20261009014620`).
- **Stand-in lines** — before the cutover, a posting that needs an empty nullable account default posts the line to `retainedEarningsAccount` and names the default it wanted in `journalLine.accountDefaultRole` (`resolveDefaultAccount`, `@carbon/database/journal-posting-status`). A Provisional journal counts nowhere, so the stand-in moves no balance. The enable re-points every stand-in line dated on or after the cutover to its default and clears the role. After the cutover an empty default fails the posting. See `packages/server-functions/AGENTS.md` → Journals and the accounting cutover.
- **Manual accounting work is refused before the cutover** with `ACCOUNTING_NOT_STARTED` ("Set up accounting before you post journals, runs or period closes."): `requireAccountingCutover` (`accounting.service.ts`) in `postJournalEntry`, `reverseJournalEntry`, `lockAccountingPeriod`, `closeAccountingPeriod` and `createDepreciationRun`; `requireGroupAccountingCutover` (every company of the group) in `runIntercompanyMatching` and `generateEliminations`; a `readAccountingCutoverDate` test (`@carbon/database/journal-posting-status`) at the top of `postDepreciationRun`, `postDisposal` and `postRevenueRecognitionRun` (`accounting.server.ts`); and `assertAccountingCutover` (`packages/server-functions/src/lib/require-accounting-cutover.ts`, the same read) in the `propose-revenue-recognition-run` and `recalculate-revenue-recognition-run` server functions.
diff --git a/apps/erp/app/modules/accounting/ui/AccountingBetaGate.tsx b/apps/erp/app/modules/accounting/ui/AccountingBetaGate.tsx
index ea13f08ee9..26da7dbd43 100644
--- a/apps/erp/app/modules/accounting/ui/AccountingBetaGate.tsx
+++ b/apps/erp/app/modules/accounting/ui/AccountingBetaGate.tsx
@@ -18,12 +18,14 @@ import { useSettings } from "~/hooks";
import { path } from "~/utils/path";
import { hasAccountingCutover } from "../accounting.utils";
+// Fixed assets stay open: the register (and the rental fleet built on it) is
+// usable before accounting is set up; posting a run or a disposal is what
+// waits for the cutover, and the server refuses those on its own.
const gatedRoutes = [
path.to.reports,
path.to.intercompany,
path.to.accountingJournals,
path.to.accountingPeriods,
- path.to.fixedAssets,
path.to.depreciationRuns
];
@@ -55,7 +57,7 @@ export default function AccountingBetaGate() {
<UpgradeOverlayDescription>
<Trans>
Set up accounting to use reports, journal entries, accounting
- periods, fixed assets and more.
+ periods, depreciation runs and more.
</Trans>
</UpgradeOverlayDescription>
</UpgradeOverlayContent>
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
index a5d3006ba3..91d90e9fea 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
@@ -300,31 +300,9 @@ const SalesInvoiceHeader = () => {
</Status>
))}
{showNotSent && (
- <>
- <Status color="red" tooltip={salesInvoice.sendError}>
- <Trans>Not sent</Trans>
- </Status>
- <Button
- variant="secondary"
- leftIcon={<LuSend />}
- isLoading={sendFetcher.state !== "idle"}
- isDisabled={
- sendFetcher.state !== "idle" ||
- !permissions.can("update", "invoicing")
- }
- onClick={() =>
- sendFetcher.submit(
- {},
- {
- method: "post",
- action: path.to.salesInvoiceSend(invoiceId)
- }
- )
- }
- >
- <Trans>Send</Trans>
- </Button>
- </>
+ <Status color="red" tooltip={salesInvoice.sendError}>
+ <Trans>Not sent</Trans>
+ </Status>
)}
{routeData?.stripeInvoiceUrl && isPosted && (
<a
@@ -439,6 +417,30 @@ const SalesInvoiceHeader = () => {
</DropdownMenu>
</RecordAction>
)}
+ {showNotSent && (
+ <RecordAction slot="overflow">
+ <Button
+ variant="secondary"
+ leftIcon={<LuSend />}
+ isLoading={sendFetcher.state !== "idle"}
+ isDisabled={
+ sendFetcher.state !== "idle" ||
+ !permissions.can("update", "invoicing")
+ }
+ onClick={() =>
+ sendFetcher.submit(
+ {},
+ {
+ method: "post",
+ action: path.to.salesInvoiceSend(invoiceId)
+ }
+ )
+ }
+ >
+ <Trans>Send</Trans>
+ </Button>
+ </RecordAction>
+ )}
<RecordAction slot="overflow">
<DropdownMenu>
<DropdownMenuTrigger asChild>
diff --git a/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQProperties.tsx b/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQProperties.tsx
index 1d488cabdc..754c9fda8f 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQProperties.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQProperties.tsx
@@ -6,10 +6,6 @@ import type { Json } from "@carbon/database";
import { CreatableMultiSelect, DatePicker, ValidatedForm } from "@carbon/form";
import { useAction } from "@carbon/query";
import {
- Avatar,
- AvatarGroup,
- AvatarGroupList,
- AvatarOverflowIndicator,
Button,
Copy,
HStack,
@@ -27,7 +23,11 @@ import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";
import { useParams } from "react-router";
import { z } from "zod";
import { zfd } from "zod-form-data";
-import { Assignee, useOptimisticAssignment } from "~/components";
+import {
+ Assignee,
+ SupplierAvatarGroup,
+ useOptimisticAssignment
+} from "~/components";
import { Employee, Location } from "~/components/Form";
import CustomFormInlineFields from "~/components/Form/CustomFormInlineFields";
import { usePermissions, useRouteData } from "~/hooks";
@@ -64,21 +64,11 @@ const PurchasingRFQProperties = () => {
const renderSuppliersInlinePreview = useCallback(
(value: string[], _options: unknown, maxPreview = 5) => (
- <AvatarGroup limit={maxPreview} className="relative z-10">
- <AvatarGroupList>
- {value.map((supplier, index: number) => (
- <Avatar
- key={index}
- name={
- allSuppliers.find((s) => s.id === supplier)?.name ?? supplier
- }
- />
- ))}
- </AvatarGroupList>
- <AvatarOverflowIndicator />
- </AvatarGroup>
+ <div className="relative z-10">
+ <SupplierAvatarGroup supplierIds={value} size="sm" limit={maxPreview} />
+ </div>
),
- [allSuppliers]
+ []
);
// Get current supplier IDs from the RFQ
diff --git a/apps/erp/app/modules/sales/AGENTS.md b/apps/erp/app/modules/sales/AGENTS.md
index a26b8e5e6e..6e4d27238d 100644
--- a/apps/erp/app/modules/sales/AGENTS.md
+++ b/apps/erp/app/modules/sales/AGENTS.md
@@ -130,7 +130,7 @@ Rental of serialized fleet units (fixed assets with an `itemId`), each line's ac
| `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` + `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) |
+| `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`, `invoiceSeparately` (default false; a `Charge` with it set is drafted on the held charges invoice instead of the rent invoice — ignored on a `Purchase Option`, which is always separate), `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 |
@@ -141,7 +141,7 @@ RLS on all seven: `sales_view` to read, `sales_create/update/delete` to write
- **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.
+- **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 the rent and every `Charge` go on one rent invoice (a charge alone, unheld, when no rent is due) and charges marked `invoiceSeparately` plus every `Purchase Option` go on a separate charges invoice (`planRentalInvoices`, `@carbon/utils`); holds are stamped on `salesInvoice.automationHoldReason` — the charges invoice always, a rent invoice with an early-return credit, and a re-bill of a voided invoice (wins over the credit; checked across every line of the rent invoice, charges included). 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'`.
diff --git a/apps/erp/app/modules/sales/sales.models.test.ts b/apps/erp/app/modules/sales/sales.models.test.ts
index 2ce5e98d0a..6c898e52c3 100644
--- a/apps/erp/app/modules/sales/sales.models.test.ts
+++ b/apps/erp/app/modules/sales/sales.models.test.ts
@@ -148,6 +148,23 @@ describe("rentalAgreementChargeValidator", () => {
expect(result.success).toBe(true);
expect(result.data).not.toHaveProperty("chargeType");
});
+
+ it("reads invoiceSeparately from a checkbox, off when unchecked", () => {
+ const base = {
+ rentalAgreementLineId: "ral_1",
+ chargeDate: "2026-09-23",
+ description: "Damage",
+ amount: "500",
+ taxPercent: "0"
+ };
+ expect(rentalAgreementChargeValidator.parse(base).invoiceSeparately).toBe(
+ false
+ );
+ expect(
+ rentalAgreementChargeValidator.parse({ ...base, invoiceSeparately: "on" })
+ .invoiceSeparately
+ ).toBe(true);
+ });
});
describe("salesOrderLineValidator priceTrace", () => {
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index 2ad36c627f..138bfe3076 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -1518,7 +1518,9 @@ export const rentalAgreementChargeValidator = z.object({
amount: zfd.numeric(z.number()),
taxPercent: zfd.numeric(
z.number().min(0).max(1, { message: "Tax percent must be between 0 and 1" })
- )
+ ),
+ /** Drafted on its own invoice, held for review, instead of with the rent. */
+ invoiceSeparately: zfd.checkbox()
});
/** Where a Sale unit's closing net investment goes when it comes back
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 43b443a343..e3c7f63c5a 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -9174,7 +9174,8 @@ export async function upsertRentalAgreementCharge(
chargeDate: charge.chargeDate,
description: charge.description,
amount: charge.amount,
- taxPercent: charge.taxPercent
+ taxPercent: charge.taxPercent,
+ invoiceSeparately: charge.invoiceSeparately
};
// The agreement is the line's own, read under the caller's company.
diff --git a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementChargeForm.tsx b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementChargeForm.tsx
index 21c3f2740f..74a24d8899 100644
--- a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementChargeForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementChargeForm.tsx
@@ -19,7 +19,14 @@ import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useFetcher } from "react-router";
import type { z } from "zod";
-import { DatePicker, Input, Number, Select, Submit } from "~/components/Form";
+import {
+ Boolean,
+ DatePicker,
+ Input,
+ Number,
+ Select,
+ Submit
+} from "~/components/Form";
import { useCurrencyDecimals, usePermissions } from "~/hooks";
import { rentalAgreementChargeValidator } from "../../sales.models";
@@ -101,6 +108,11 @@ const RentalAgreementChargeForm = ({
step={INPUT_STEP.percent}
formatOptions={INPUT_FORMAT.percent}
/>
+ <Boolean
+ name="invoiceSeparately"
+ label={t`Invoice Separately`}
+ description={t`Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice.`}
+ />
</VStack>
</ModalDrawerBody>
<ModalDrawerFooter>
diff --git a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementCharges.tsx b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementCharges.tsx
index 671662cc8d..e64e671d45 100644
--- a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementCharges.tsx
+++ b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementCharges.tsx
@@ -130,7 +130,16 @@ const RentalAgreementCharges = ({
{charge.rentalAgreementLine?.fixedAsset?.fixedAssetId ??
"—"}
</Td>
- <Td>{charge.description}</Td>
+ <Td>
+ <HStack spacing={2}>
+ <span>{charge.description}</span>
+ {charge.invoiceSeparately && (
+ <Badge variant="secondary">
+ <Trans>Invoiced separately</Trans>
+ </Badge>
+ )}
+ </HStack>
+ </Td>
<Td className="text-right">
<RentalMoney
value={charge.amount}
@@ -212,7 +221,8 @@ const RentalAgreementCharges = ({
chargeDate: companyToday,
description: "",
amount: 0,
- taxPercent: rentalAgreement.taxPercent ?? 0
+ taxPercent: rentalAgreement.taxPercent ?? 0,
+ invoiceSeparately: false
}}
currencyCode={rentalAgreement.currencyCode ?? ""}
lineOptions={lineOptions}
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 2b78e7aefe..7e9e26a677 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
@@ -1278,7 +1278,7 @@
{"name":"sales_getRelatedPricesForQuoteLine","classification":"READ","paramCount":2,"schema":"71f31780bb98","response":"935691b285a7","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getRentableFleetAssets","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"18707409983d","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getRentalAgreement","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"bab51585fc7b","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getRentalAgreementCharges","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"d6ae207a52d1","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getRentalAgreementCharges","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"49b56d3a2f77","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"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},
@@ -1388,7 +1388,7 @@
{"name":"sales_upsertQuoteOperationTool","classification":"WRITE","paramCount":5,"schema":"59266e6a790e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},
{"name":"sales_upsertQuotePayment","classification":"WRITE","paramCount":6,"schema":"36ca53e35fa3","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertQuoteShipment","classification":"WRITE","paramCount":7,"schema":"b67f297e5398","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:create+update","paginates":false},
- {"name":"sales_upsertRentalAgreementCharge","classification":"WRITE","paramCount":6,"schema":"7d7b644d1260","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},
+ {"name":"sales_upsertRentalAgreementCharge","classification":"WRITE","paramCount":7,"schema":"a914e37d74f4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},
{"name":"sales_upsertRentalAgreementLine","classification":"WRITE","paramCount":9,"schema":"cb7e4d4579e2","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},
{"name":"sales_upsertReturnReason","classification":"WRITE","paramCount":4,"schema":"85bdd818fbab","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},
{"name":"sales_upsertSalesOrder","classification":"WRITE","paramCount":19,"schema":"9d987dd63daf","response":"5cc20a44d4fe","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 8235c8cfd8..75bb18d03c 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -38496,6 +38496,9 @@ export default {
{
$ref: "#/parameters/rowFilter.rentalAgreementCharge.voidedSalesInvoiceId"
},
+ {
+ $ref: "#/parameters/rowFilter.rentalAgreementCharge.invoiceSeparately"
+ },
{
$ref: "#/parameters/select"
},
@@ -38597,6 +38600,9 @@ export default {
{
$ref: "#/parameters/rowFilter.rentalAgreementCharge.voidedSalesInvoiceId"
},
+ {
+ $ref: "#/parameters/rowFilter.rentalAgreementCharge.invoiceSeparately"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -38652,6 +38658,9 @@ export default {
{
$ref: "#/parameters/rowFilter.rentalAgreementCharge.voidedSalesInvoiceId"
},
+ {
+ $ref: "#/parameters/rowFilter.rentalAgreementCharge.invoiceSeparately"
+ },
{
$ref: "#/parameters/body.rentalAgreementCharge"
},
@@ -113800,6 +113809,51 @@ export default {
tags: ["(rpc) update_receipt_line_batch_tracking"]
}
},
+ "/rpc/sync_advance_document_sequence": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_new: {
+ format: "jsonb"
+ },
+ p_old: {
+ format: "jsonb"
+ },
+ p_operation: {
+ format: "text",
+ type: "string"
+ },
+ p_table: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: ["p_table", "p_operation", "p_new", "p_old"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) sync_advance_document_sequence"]
+ }
+ },
"/rpc/sync_update_stock_transfer_status": {
post: {
parameters: [
@@ -133077,7 +133131,8 @@ export default {
"amount",
"taxPercent",
"createdBy",
- "createdAt"
+ "createdAt",
+ "invoiceSeparately"
],
properties: {
id: {
@@ -133147,6 +133202,11 @@ export default {
voidedSalesInvoiceId: {
format: "text",
type: "string"
+ },
+ invoiceSeparately: {
+ default: false,
+ format: "boolean",
+ type: "boolean"
}
},
type: "object"
@@ -183895,6 +183955,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.rentalAgreementCharge.invoiceSeparately": {
+ name: "invoiceSeparately",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.journalEntries": {
name: "journalEntries",
description: "journalEntries",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index dab2a35580..4823b35886 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -54030,6 +54030,7 @@ export type Database = {
createdBy: string
description: string
id: string
+ invoiceSeparately: boolean
rentalAgreementLineId: string
salesInvoiceLineId: string | null
taxPercent: number
@@ -54046,6 +54047,7 @@ export type Database = {
createdBy: string
description: string
id?: string
+ invoiceSeparately?: boolean
rentalAgreementLineId: string
salesInvoiceLineId?: string | null
taxPercent?: number
@@ -54062,6 +54064,7 @@ export type Database = {
createdBy?: string
description?: string
id?: string
+ invoiceSeparately?: boolean
rentalAgreementLineId?: string
salesInvoiceLineId?: string | null
taxPercent?: number
diff --git a/packages/database/supabase/migrations/20261012181937_rental-charge-invoice-separately.sql b/packages/database/supabase/migrations/20261012181937_rental-charge-invoice-separately.sql
new file mode 100644
index 0000000000..e50e73240d
--- /dev/null
+++ b/packages/database/supabase/migrations/20261012181937_rental-charge-invoice-separately.sql
@@ -0,0 +1,7 @@
+-- A rental charge goes on the agreement's regular invoice with the rent
+-- unless it is marked to be invoiced separately — then it is drafted on its
+-- own invoice and held for review (damage, disputes). A Purchase Option is
+-- always invoiced separately, whatever this says.
+
+ALTER TABLE "rentalAgreementCharge"
+ ADD COLUMN IF NOT EXISTS "invoiceSeparately" BOOLEAN NOT NULL DEFAULT false;
diff --git a/packages/form/src/components/CreatableMultiSelect.tsx b/packages/form/src/components/CreatableMultiSelect.tsx
index e87ce2f0e3..543e7c7828 100644
--- a/packages/form/src/components/CreatableMultiSelect.tsx
+++ b/packages/form/src/components/CreatableMultiSelect.tsx
@@ -10,7 +10,8 @@ import {
FormErrorMessage,
FormHelperText,
FormLabel,
- LabelWithHelp
+ LabelWithHelp,
+ optionLabelText
} from "@carbon/react";
import type { ReactNode } from "react";
import { forwardRef, useEffect, useMemo } from "react";
@@ -77,7 +78,7 @@ const CreatableMultiSelect = forwardRef<
// Sort unselected options alphabetically by label
const sortedUnselected = [...unselectedOptions].sort((a, b) =>
- a.label.localeCompare(b.label)
+ optionLabelText(a).localeCompare(optionLabelText(b))
);
// Combine selected options first, followed by sorted unselected options
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index afbe36783f..a2e645321d 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20261012111443",
+ "schemaVersion": "20261012181937",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-10-12T12:00:40.103Z",
+ "exportedAt": "2026-10-12T15:30:14.722Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
@@ -4322,7 +4322,8 @@
"createdAt",
"updatedBy",
"updatedAt",
- "voidedSalesInvoiceId"
+ "voidedSalesInvoiceId",
+ "invoiceSeparately"
]
},
{
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 9c5e7f5afb..0e45be4abb 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -11193,6 +11193,9 @@ msgstr "Wechselkurs der Rechnung"
msgid "Invoice schedule"
msgstr "Rechnungsplan"
+msgid "Invoice Separately"
+msgstr ""
+
msgid "Invoice settlement"
msgstr "Rechnungsabrechnung"
@@ -11223,6 +11226,9 @@ msgstr "Fakturiert"
msgid "Invoiced Amount:"
msgstr "Fakturierter Betrag:"
+msgid "Invoiced separately"
+msgstr ""
+
msgid "Invoiced Statuses"
msgstr "Fakturierte Status"
@@ -16564,6 +16570,9 @@ msgstr "Den Buchungssatz ohne die Dimension verbuchen"
msgid "Push to accounting"
msgstr "Zur Buchhaltung senden"
+msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+msgstr ""
+
msgid "Putting your data back"
msgstr "Ihre Daten werden wiederhergestellt"
@@ -19360,8 +19369,8 @@ msgstr "Buchhaltung einrichten"
msgid "Set Up Accounting"
msgstr "Buchhaltung einrichten"
-msgid "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
-msgstr "Richten Sie die Buchhaltung ein, um Berichte, Buchungssätze, Buchungsperioden, Anlagegüter und weitere Funktionen nutzen zu können."
+msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
+msgstr ""
msgid "Set up authenticator app"
msgstr "Authentifizierungs-App einrichten"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 68038dbb44..a610a44db5 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -11193,6 +11193,9 @@ msgstr "Invoice Rate"
msgid "Invoice schedule"
msgstr "Invoice schedule"
+msgid "Invoice Separately"
+msgstr "Invoice Separately"
+
msgid "Invoice settlement"
msgstr "Invoice settlement"
@@ -11223,6 +11226,9 @@ msgstr "Invoiced"
msgid "Invoiced Amount:"
msgstr "Invoiced Amount:"
+msgid "Invoiced separately"
+msgstr "Invoiced separately"
+
msgid "Invoiced Statuses"
msgstr "Invoiced Statuses"
@@ -16564,6 +16570,9 @@ msgstr "Push the journal without the dimension"
msgid "Push to accounting"
msgstr "Push to accounting"
+msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+msgstr "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+
msgid "Putting your data back"
msgstr "Putting your data back"
@@ -19360,8 +19369,8 @@ msgstr "Set up accounting"
msgid "Set Up Accounting"
msgstr "Set Up Accounting"
-msgid "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
-msgstr "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
+msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
+msgstr "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
msgid "Set up authenticator app"
msgstr "Set up authenticator app"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index eb3b8d3e6b..b3d1814f19 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -11193,6 +11193,9 @@ msgstr "Tipo de cambio de la factura"
msgid "Invoice schedule"
msgstr "Programa de facturación"
+msgid "Invoice Separately"
+msgstr ""
+
msgid "Invoice settlement"
msgstr "Liquidación de facturas"
@@ -11223,6 +11226,9 @@ msgstr "Facturado"
msgid "Invoiced Amount:"
msgstr "Monto Facturado:"
+msgid "Invoiced separately"
+msgstr ""
+
msgid "Invoiced Statuses"
msgstr "Estados Facturados"
@@ -16564,6 +16570,9 @@ msgstr "Enviar el asiento sin la dimensión"
msgid "Push to accounting"
msgstr "Enviar a contabilidad"
+msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+msgstr ""
+
msgid "Putting your data back"
msgstr "Restaurando tus datos"
@@ -19360,8 +19369,8 @@ msgstr "Configurar contabilidad"
msgid "Set Up Accounting"
msgstr "Configurar Contabilidad"
-msgid "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
-msgstr "Configure la contabilidad para usar reportes, asientos, períodos contables, activos fijos y más."
+msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
+msgstr ""
msgid "Set up authenticator app"
msgstr "Configurar aplicación autenticadora"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 5894f3361d..e67f5b49ba 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -11193,6 +11193,9 @@ msgstr "Taux de change de la facture"
msgid "Invoice schedule"
msgstr "Planning de facturation"
+msgid "Invoice Separately"
+msgstr ""
+
msgid "Invoice settlement"
msgstr "Règlement de facture"
@@ -11223,6 +11226,9 @@ msgstr "Facturé"
msgid "Invoiced Amount:"
msgstr "Montant facturé :"
+msgid "Invoiced separately"
+msgstr ""
+
msgid "Invoiced Statuses"
msgstr "Statuts facturés"
@@ -16564,6 +16570,9 @@ msgstr "Envoyer l'écriture sans l'axe analytique"
msgid "Push to accounting"
msgstr "Envoyer vers la comptabilité"
+msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+msgstr ""
+
msgid "Putting your data back"
msgstr "Restauration de vos données"
@@ -19360,8 +19369,8 @@ msgstr "Configurer la comptabilité"
msgid "Set Up Accounting"
msgstr "Configurer la comptabilité"
-msgid "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
-msgstr "Configurez la comptabilité pour utiliser des rapports, des écritures, des périodes comptables, des immobilisations et plus."
+msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
+msgstr ""
msgid "Set up authenticator app"
msgstr "Configurer l'application d'authentification"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index a3f79cb516..dc66cb2aa9 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -11193,6 +11193,9 @@ msgstr "चालान विनिमय दर"
msgid "Invoice schedule"
msgstr "चालान शेड्यूल"
+msgid "Invoice Separately"
+msgstr ""
+
msgid "Invoice settlement"
msgstr "चालान निपटान"
@@ -11223,6 +11226,9 @@ msgstr "चालान किया गया"
msgid "Invoiced Amount:"
msgstr "चालान की गई राशि:"
+msgid "Invoiced separately"
+msgstr ""
+
msgid "Invoiced Statuses"
msgstr "चालान की गई स्थितियां"
@@ -16564,6 +16570,9 @@ msgstr "आयाम के बिना जर्नल पुश करें"
msgid "Push to accounting"
msgstr "लेखांकन को धकेलें"
+msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+msgstr ""
+
msgid "Putting your data back"
msgstr "आपका डेटा वापस डाल रहे हैं"
@@ -19360,8 +19369,8 @@ msgstr "लेखांकन स्थापित करें"
msgid "Set Up Accounting"
msgstr "लेखांकन स्थापित करें"
-msgid "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
-msgstr "रिपोर्ट, जर्नल प्रविष्टियाँ, लेखा अवधि, अचल संपत्ति और बहुत कुछ उपयोग करने के लिए लेखांकन स्थापित करें।"
+msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
+msgstr ""
msgid "Set up authenticator app"
msgstr "प्रमाणकर्ता ऐप सेटअप करें"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index a24353e5ff..5f247da47c 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -11193,6 +11193,9 @@ msgstr "Tasso di cambio della fattura"
msgid "Invoice schedule"
msgstr "Programma di fatturazione"
+msgid "Invoice Separately"
+msgstr ""
+
msgid "Invoice settlement"
msgstr "Regolamento della fattura"
@@ -11223,6 +11226,9 @@ msgstr "Fatturato"
msgid "Invoiced Amount:"
msgstr "Importo Fatturato:"
+msgid "Invoiced separately"
+msgstr ""
+
msgid "Invoiced Statuses"
msgstr "Stati Fatturati"
@@ -16564,6 +16570,9 @@ msgstr "Registra la prima nota senza la dimensione"
msgid "Push to accounting"
msgstr "Invia alla contabilità"
+msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+msgstr ""
+
msgid "Putting your data back"
msgstr "Ripristino dei dati"
@@ -19360,8 +19369,8 @@ msgstr "Configura la contabilità"
msgid "Set Up Accounting"
msgstr "Configura la contabilità"
-msgid "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
-msgstr "Configura la contabilità per utilizzare report, prime note, periodi contabili, cespiti e altro."
+msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
+msgstr ""
msgid "Set up authenticator app"
msgstr "Configura app autenticatore"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index ef1c7dd51c..4aa0ea691a 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -11193,6 +11193,9 @@ msgstr "請求書の為替レート"
msgid "Invoice schedule"
msgstr "請求スケジュール"
+msgid "Invoice Separately"
+msgstr ""
+
msgid "Invoice settlement"
msgstr "請求書決済"
@@ -11223,6 +11226,9 @@ msgstr "請求済み"
msgid "Invoiced Amount:"
msgstr "請求済み金額:"
+msgid "Invoiced separately"
+msgstr ""
+
msgid "Invoiced Statuses"
msgstr "請求済みステータス"
@@ -16564,6 +16570,9 @@ msgstr "ディメンションなしで仕訳を転記する"
msgid "Push to accounting"
msgstr "会計にプッシュ"
+msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+msgstr ""
+
msgid "Putting your data back"
msgstr "データを復元中"
@@ -19360,8 +19369,8 @@ msgstr "会計を設定"
msgid "Set Up Accounting"
msgstr "会計を設定"
-msgid "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
-msgstr "レポート、仕訳、会計期間、固定資産などを使用するために会計を設定します。"
+msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
+msgstr ""
msgid "Set up authenticator app"
msgstr "認証アプリをセットアップ"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 8fd3d07bdf..f94beeb27f 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -11193,6 +11193,9 @@ msgstr "송장 환율"
msgid "Invoice schedule"
msgstr "송장 일정"
+msgid "Invoice Separately"
+msgstr ""
+
msgid "Invoice settlement"
msgstr "송장 결제"
@@ -11223,6 +11226,9 @@ msgstr "송장 발행됨"
msgid "Invoiced Amount:"
msgstr "송장 발행 금액:"
+msgid "Invoiced separately"
+msgstr ""
+
msgid "Invoiced Statuses"
msgstr "송장 발행됨 상태"
@@ -16564,6 +16570,9 @@ msgstr "차원 없이 전표를 전기하세요"
msgid "Push to accounting"
msgstr "회계로 푸시"
+msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+msgstr ""
+
msgid "Putting your data back"
msgstr "데이터 복원 중"
@@ -19360,8 +19369,8 @@ msgstr "회계 설정"
msgid "Set Up Accounting"
msgstr "회계 설정"
-msgid "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
-msgstr "보고서, 전표, 회계 기간, 고정자산 등을 사용하기 위해 회계를 설정하십시오."
+msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
+msgstr ""
msgid "Set up authenticator app"
msgstr "인증자 앱 설정"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index af15cb1eb1..dc2dd73c80 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -11193,6 +11193,9 @@ msgstr "Kurs wymiany faktury"
msgid "Invoice schedule"
msgstr "Harmonogram fakturowania"
+msgid "Invoice Separately"
+msgstr ""
+
msgid "Invoice settlement"
msgstr "Rozliczenie faktury"
@@ -11223,6 +11226,9 @@ msgstr "Zafakturowane"
msgid "Invoiced Amount:"
msgstr "Kwota zafakturowana:"
+msgid "Invoiced separately"
+msgstr ""
+
msgid "Invoiced Statuses"
msgstr "Statusy Zafakturowane"
@@ -16564,6 +16570,9 @@ msgstr "Wyślij dowód księgowy bez wymiaru"
msgid "Push to accounting"
msgstr "Wyślij do systemu księgowego"
+msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+msgstr ""
+
msgid "Putting your data back"
msgstr "Przywracanie twoich danych"
@@ -19360,8 +19369,8 @@ msgstr "Skonfiguruj Księgowość"
msgid "Set Up Accounting"
msgstr "Skonfiguruj Księgowość"
-msgid "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
-msgstr "Skonfiguruj Księgowość, aby korzystać z raportów, wpisów dziennika, okresów księgowych, środków trwałych i innych."
+msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
+msgstr ""
msgid "Set up authenticator app"
msgstr "Skonfiguruj aplikację authenticator"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index ec6b21d7ff..1ae1b45977 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -11193,6 +11193,9 @@ msgstr "Taxa de câmbio da fatura"
msgid "Invoice schedule"
msgstr "Cronograma de faturamento"
+msgid "Invoice Separately"
+msgstr ""
+
msgid "Invoice settlement"
msgstr "Liquidação de fatura"
@@ -11223,6 +11226,9 @@ msgstr "Faturado"
msgid "Invoiced Amount:"
msgstr "Valor Faturado:"
+msgid "Invoiced separately"
+msgstr ""
+
msgid "Invoiced Statuses"
msgstr "Status Faturados"
@@ -16564,6 +16570,9 @@ msgstr "Enviar o diário sem a dimensão"
msgid "Push to accounting"
msgstr "Enviar para contabilidade"
+msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+msgstr ""
+
msgid "Putting your data back"
msgstr "Colocando seus dados de volta"
@@ -19360,8 +19369,8 @@ msgstr "Configurar contabilidade"
msgid "Set Up Accounting"
msgstr "Configurar contabilidade"
-msgid "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
-msgstr "Configure a contabilidade para usar relatórios, lançamentos de diário, períodos contábeis, ativos fixos e muito mais."
+msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
+msgstr ""
msgid "Set up authenticator app"
msgstr "Configurar aplicativo autenticador"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index be910ca562..87a21c0d4f 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -11193,6 +11193,9 @@ msgstr "Валютный курс счета-фактуры"
msgid "Invoice schedule"
msgstr "График выставления счетов"
+msgid "Invoice Separately"
+msgstr ""
+
msgid "Invoice settlement"
msgstr "Расчет по счету-фактуре"
@@ -11223,6 +11226,9 @@ msgstr "Выставлен счет"
msgid "Invoiced Amount:"
msgstr "Выставленная сумма счета-фактуры:"
+msgid "Invoiced separately"
+msgstr ""
+
msgid "Invoiced Statuses"
msgstr "Статусы выставленного счета"
@@ -16564,6 +16570,9 @@ msgstr "Провести операцию без измерения"
msgid "Push to accounting"
msgstr "Отправить в бухгалтерию"
+msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+msgstr ""
+
msgid "Putting your data back"
msgstr "Восстановление ваших данных"
@@ -19360,8 +19369,8 @@ msgstr "Установить бухгалтерию"
msgid "Set Up Accounting"
msgstr "Установка бухгалтерии"
-msgid "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
-msgstr "Установите бухгалтерию для использования отчетов, записей операций, учетных периодов, основных средств и многого другого."
+msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
+msgstr ""
msgid "Set up authenticator app"
msgstr "Установить приложение аутентификации"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 71e6a3a52f..38ba80285e 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -11193,6 +11193,9 @@ msgstr "Fatura döviz kuru"
msgid "Invoice schedule"
msgstr "Fatura çizelgesi"
+msgid "Invoice Separately"
+msgstr ""
+
msgid "Invoice settlement"
msgstr "Fatura Ödeme"
@@ -11223,6 +11226,9 @@ msgstr "Faturalandırıldı"
msgid "Invoiced Amount:"
msgstr "Faturalandı Tutarı:"
+msgid "Invoiced separately"
+msgstr ""
+
msgid "Invoiced Statuses"
msgstr "Faturalandı Durumları"
@@ -16564,6 +16570,9 @@ msgstr "Muhasebe fişini boyut olmadan gönder"
msgid "Push to accounting"
msgstr "Muhasebede gönder"
+msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+msgstr ""
+
msgid "Putting your data back"
msgstr "Verileriniz geri konuluyor"
@@ -19360,8 +19369,8 @@ msgstr "Muhasebeyi ayarlayın"
msgid "Set Up Accounting"
msgstr "Muhasebeyi Ayarlayın"
-msgid "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
-msgstr "Raporlar, muhasebe fişleri, muhasebe dönemleri, sabit kıymetler ve daha fazlasını kullanmak için muhasebeyi ayarlayın."
+msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
+msgstr ""
msgid "Set up authenticator app"
msgstr "Doğrulayıcı uygulamayı ayarla"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index ba9fa9f3a9..1b3fbdbe0e 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -11193,6 +11193,9 @@ msgstr "发票汇率"
msgid "Invoice schedule"
msgstr "发票日程表"
+msgid "Invoice Separately"
+msgstr ""
+
msgid "Invoice settlement"
msgstr "发票结算"
@@ -11223,6 +11226,9 @@ msgstr "已开票"
msgid "Invoiced Amount:"
msgstr "已开票金额:"
+msgid "Invoiced separately"
+msgstr ""
+
msgid "Invoiced Statuses"
msgstr "已开票状态"
@@ -16564,6 +16570,9 @@ msgstr "发布不包含维度的凭证"
msgid "Push to accounting"
msgstr "推送到会计系统"
+msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."
+msgstr ""
+
msgid "Putting your data back"
msgstr "正在恢复您的数据"
@@ -19360,8 +19369,8 @@ msgstr "设置会计"
msgid "Set Up Accounting"
msgstr "设置会计"
-msgid "Set up accounting to use reports, journal entries, accounting periods, fixed assets and more."
-msgstr "设置会计以使用报告、凭证、会计期间、固定资产等。"
+msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."
+msgstr ""
msgid "Set up authenticator app"
msgstr "设置身份验证器应用"
diff --git a/packages/react/src/CreateableCombobox.tsx b/packages/react/src/CreateableCombobox.tsx
index e9e904f59f..c7c0e27020 100644
--- a/packages/react/src/CreateableCombobox.tsx
+++ b/packages/react/src/CreateableCombobox.tsx
@@ -14,7 +14,7 @@ import { PickerList } from "./PickerList";
import { Popover, PopoverContent, PopoverTrigger } from "./Popover";
import { TruncatedTooltipText } from "./TruncatedTooltipText";
import { cn } from "./utils/cn";
-import { reactNodeToString, withDistinctHelpers } from "./utils/react";
+import { optionLabelText, withDistinctHelpers } from "./utils/react";
import { usePhoneOpenAutoFocus } from "./Viewport";
export type CreatableComboboxProps = Omit<
@@ -28,6 +28,8 @@ export type CreatableComboboxProps = Omit<
value: string;
helper?: string;
helperRight?: string;
+ /** Extra search text, matched but never rendered. */
+ keywords?: string;
}[];
selected?: string[];
isClearable?: boolean;
@@ -93,21 +95,18 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
);
const selectedOptionText = useMemo(() => {
if (!selectedOption) return undefined;
- const labelText =
- typeof selectedOption.label === "string"
- ? selectedOption.label
- : reactNodeToString(selectedOption.label);
-
- return [labelText, selectedOption.helper].filter(Boolean).join(" - ");
+ return [optionLabelText(selectedOption), selectedOption.helper]
+ .filter(Boolean)
+ .join(" - ");
}, [selectedOption]);
// Real-text sizer instead of a ch estimate — see Combobox.tsx.
const longestOptionText = useMemo(() => {
return options.reduce((longest, option) => {
- const labelText =
- typeof option.label === "string"
- ? option.label
- : reactNodeToString(option.label);
- const combined = [labelText, option.helper, option.helperRight]
+ const combined = [
+ optionLabelText(option),
+ option.helper,
+ option.helperRight
+ ]
.filter(Boolean)
.join(" ");
@@ -260,10 +259,9 @@ const filterCreatableComboboxOptions = (
) =>
search
? options.filter((option) => {
- const value =
- typeof option.label === "string"
- ? `${option.label} ${option.helper ?? ""}`
- : reactNodeToString(option.label);
+ const value = [optionLabelText(option), option.helper, option.keywords]
+ .filter(Boolean)
+ .join(" ");
return value.toLowerCase().includes(search.toLowerCase());
})
diff --git a/packages/react/src/CreateableMultiSelect.tsx b/packages/react/src/CreateableMultiSelect.tsx
index e3ac8cceda..aac7d9b662 100644
--- a/packages/react/src/CreateableMultiSelect.tsx
+++ b/packages/react/src/CreateableMultiSelect.tsx
@@ -14,7 +14,7 @@ import { PickerList } from "./PickerList";
import { Popover, PopoverContent, PopoverTrigger } from "./Popover";
import { TruncatedTooltipText } from "./TruncatedTooltipText";
import { cn } from "./utils/cn";
-import { reactNodeToString } from "./utils/react";
+import { optionLabelText } from "./utils/react";
import { usePhoneOpenAutoFocus } from "./Viewport";
export type CreatableMultiSelectProps = Omit<
@@ -24,9 +24,11 @@ export type CreatableMultiSelectProps = Omit<
size?: "sm" | "md" | "lg";
value: string[];
options: {
- label: string;
+ label: string | JSX.Element;
value: string;
helper?: string;
+ /** Extra search text, matched but never rendered. */
+ keywords?: string;
}[];
selected?: string[];
isReadOnly?: boolean;
@@ -39,7 +41,7 @@ export type CreatableMultiSelectProps = Omit<
showCreateOptionOnEmpty?: boolean;
inline?: (
value: string[],
- options: { value: string; label: string; helper?: string }[],
+ options: { value: string; label: string | JSX.Element; helper?: string }[],
maxPreview?: number
) => React.ReactNode;
inlineIcon?: React.ReactElement;
@@ -89,13 +91,15 @@ const CreatableMultiSelect = forwardRef<
const isInlinePreview = !!inline;
const selectedLabels = value
- .map((item) => options.find((option) => option.value === item)?.label)
- .filter((label): label is string => Boolean(label));
+ .map((item) => options.find((option) => option.value === item))
+ .filter((option) => option !== undefined)
+ .map(optionLabelText)
+ .filter(Boolean);
const selectedLabelText = selectedLabels.join(", ");
// Real-text sizer instead of a ch estimate — see Combobox.tsx.
const longestOptionText = useMemo(() => {
return options.reduce((longest, option) => {
- const combined = [option.label, option.helper]
+ const combined = [optionLabelText(option), option.helper]
.filter(Boolean)
.join(" ");
@@ -235,10 +239,9 @@ const filterCreatableMultiSelectOptions = (
) =>
search
? options.filter((option) => {
- const value =
- typeof option.label === "string"
- ? `${option.label} ${option.helper ?? ""}`
- : reactNodeToString(option.label);
+ const value = [optionLabelText(option), option.helper, option.keywords]
+ .filter(Boolean)
+ .join(" ");
return value.toLowerCase().includes(search.toLowerCase());
})
diff --git a/packages/react/src/PickerList.tsx b/packages/react/src/PickerList.tsx
index 037e39d8db..c9d9d235ae 100644
--- a/packages/react/src/PickerList.tsx
+++ b/packages/react/src/PickerList.tsx
@@ -18,7 +18,7 @@ import {
} from "./Command";
import { TruncatedTooltipText } from "./TruncatedTooltipText";
import { cn } from "./utils/cn";
-import { reactNodeToString } from "./utils/react";
+import { optionLabelText } from "./utils/react";
import { useViewport } from "./Viewport";
export type PickerListOption = {
@@ -80,11 +80,6 @@ export type PickerListProps = {
const COMPACT_ITEM_HEIGHT = 44;
-const labelOf = (option: PickerListOption) =>
- typeof option.label === "string"
- ? option.label
- : reactNodeToString(option.label);
-
/**
* The searchable, virtualized option list shared by Combobox,
* CreatableCombobox, MultiSelect and CreatableMultiSelect.
@@ -125,9 +120,10 @@ function PickerList({
if (!creatable) return filtered;
const isExactMatch = options.some((option) =>
- [labelOf(option).toLowerCase(), option.helper?.toLowerCase()].includes(
- search.toLowerCase()
- )
+ [
+ optionLabelText(option).toLowerCase(),
+ option.helper?.toLowerCase()
+ ].includes(search.toLowerCase())
);
if (isExactMatch || (search.trim() === "" && !showCreateOptionOnEmpty)) {
@@ -178,7 +174,7 @@ function PickerList({
const item = filteredOptions[virtualRow.index]!;
const itemValue = getItemValue(item);
const isCreateOption = creatable && item.value === "create";
- const itemHoverText = [labelOf(item), item.helper]
+ const itemHoverText = [optionLabelText(item), item.helper]
.filter(Boolean)
.join(" - ");
const checked =
diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx
index 8d82c82a64..4c5d2a25f3 100644
--- a/packages/react/src/index.tsx
+++ b/packages/react/src/index.tsx
@@ -398,7 +398,11 @@ import { cn } from "./utils/cn";
import { hasOpenDialog, isInsideTopmostDialog } from "./utils/dialog";
import { copyToClipboard } from "./utils/dom";
import { isEditableTarget } from "./utils/keyboard";
-import { getValidChildren, reactNodeToString } from "./utils/react";
+import {
+ getValidChildren,
+ optionLabelText,
+ reactNodeToString
+} from "./utils/react";
import { useViewport, ViewportProvider } from "./Viewport";
import { VStack } from "./VStack";
@@ -737,6 +741,7 @@ export {
isRichTextEmpty,
getValidChildren,
multiSelectTriggerVariants,
+ optionLabelText,
reactNodeToString,
shortcutKeyVariants,
toast,
diff --git a/packages/react/src/utils/react.ts b/packages/react/src/utils/react.ts
index ad2d48db6f..4cd6748672 100644
--- a/packages/react/src/utils/react.ts
+++ b/packages/react/src/utils/react.ts
@@ -49,6 +49,19 @@ export const reactNodeToString = function (reactNode: ReactNode): string {
return string;
};
+/**
+ * The plain text of a picker option. A JSX label whose text lives in a
+ * component's props (an avatar that looks up its own name) has none to
+ * extract, so it falls back to the option's `keywords`.
+ */
+export function optionLabelText(option: {
+ label: ReactNode;
+ keywords?: string;
+}): string {
+ if (typeof option.label === "string") return option.label;
+ return reactNodeToString(option.label) || (option.keywords ?? "");
+}
+
export type Merge<T, P> = P & Omit<T, keyof P>;
export type MaybeRenderProp<P> = ReactNode | ((props: P) => ReactNode);
diff --git a/packages/server-functions/src/create-rental-invoices/create-rental-invoices.test.ts b/packages/server-functions/src/create-rental-invoices/create-rental-invoices.test.ts
index 9a01f4f1c7..673a024134 100644
--- a/packages/server-functions/src/create-rental-invoices/create-rental-invoices.test.ts
+++ b/packages/server-functions/src/create-rental-invoices/create-rental-invoices.test.ts
@@ -5,8 +5,10 @@
// The rental invoice generator against the live database: a Closed agreement
// whose invoice was voided still bills the rows the void returned to
// unbilled, and amounts priced in the agreement's currency land on the
-// invoice line in base currency.
+// invoice line in base currency. A charge shares the rent's invoice unless it
+// is invoiced separately, which drafts it on its own held invoice.
+import { RENTAL_HOLD_CHARGES } from "@carbon/utils";
import { sql } from "kysely";
import { expect } from "vitest";
import {
@@ -18,7 +20,7 @@ import createRentalInvoices from "./index";
const USER = "system";
-async function closedAgreementFixture() {
+async function closedAgreementFixture({ invoiceSeparately = false } = {}) {
const db = await connectLocalTestDatabase();
const prefix = `rentest-${crypto
.randomUUID()
@@ -156,6 +158,7 @@ async function closedAgreementFixture() {
description: "Delivery",
amount: 50,
chargeDate: "2026-09-01",
+ invoiceSeparately,
companyId,
createdBy: USER
})
@@ -236,3 +239,60 @@ databaseTest(
}
}
);
+
+databaseTest("a charge lands on the rent invoice, unheld", async () => {
+ const f = await closedAgreementFixture();
+ try {
+ const result = await createRentalInvoices(f.ctx, { asOf: "2026-10-05" });
+ expect(result.error).toBeNull();
+ expect(result.data!.failures).toEqual([]);
+ expect(result.data!.invoices).toHaveLength(1);
+ expect(result.data!.invoices[0]?.holdReason).toBeNull();
+
+ const byLine = await invoiceIdsByLine(f);
+ expect(byLine.rent).toBeDefined();
+ expect(byLine.charge).toBe(byLine.rent);
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest(
+ "a separately invoiced charge gets its own held invoice",
+ async () => {
+ const f = await closedAgreementFixture({ invoiceSeparately: true });
+ try {
+ const result = await createRentalInvoices(f.ctx, { asOf: "2026-10-05" });
+ expect(result.error).toBeNull();
+ expect(result.data!.failures).toEqual([]);
+ expect(result.data!.invoices).toHaveLength(2);
+
+ const byLine = await invoiceIdsByLine(f);
+ expect(byLine.charge).toBeDefined();
+ expect(byLine.charge).not.toBe(byLine.rent);
+ const held = result.data!.invoices.find(
+ (invoice) => invoice.invoiceId === byLine.charge
+ );
+ expect(held?.holdReason).toBe(RENTAL_HOLD_CHARGES);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+/** The invoice each of the fixture's two rows was billed on. */
+async function invoiceIdsByLine(
+ f: Awaited<ReturnType<typeof closedAgreementFixture>>
+) {
+ const lines = await f.db
+ .selectFrom("salesInvoiceLine")
+ .select(["invoiceId", "rentalBillingPeriodId", "rentalAgreementChargeId"])
+ .where("companyId", "=", f.companyId)
+ .where("rentalAgreementId", "=", f.agreementId)
+ .execute();
+ return {
+ rent: lines.find((l) => l.rentalBillingPeriodId === f.periodId)?.invoiceId,
+ charge: lines.find((l) => l.rentalAgreementChargeId === f.chargeId)
+ ?.invoiceId
+ };
+}
diff --git a/packages/server-functions/src/create-rental-invoices/index.ts b/packages/server-functions/src/create-rental-invoices/index.ts
index b38820889d..8a373adf5e 100644
--- a/packages/server-functions/src/create-rental-invoices/index.ts
+++ b/packages/server-functions/src/create-rental-invoices/index.ts
@@ -322,6 +322,7 @@ async function draftAgreementInvoices(
"c.description",
"c.amount",
"c.taxPercent",
+ "c.invoiceSeparately",
"c.voidedSalesInvoiceId"
])
.where("l.rentalAgreementId", "=", agreement.id)
@@ -385,6 +386,7 @@ async function draftAgreementInvoices(
const lines: {
values: LineValues;
isAdjustment: boolean;
+ invoiceSeparately: boolean;
voidedInvoiceReadableId: string | null;
}[] = [
...billable.map((period) => ({
@@ -403,6 +405,7 @@ async function draftAgreementInvoices(
serviceEndDate: period.periodEnd
},
isAdjustment: period.isAdjustment ?? false,
+ invoiceSeparately: false,
voidedInvoiceReadableId: voidedReadableId(period.voidedSalesInvoiceId)
})),
...charges.map((charge) => ({
@@ -418,6 +421,7 @@ async function draftAgreementInvoices(
serviceEndDate: null
},
isAdjustment: false,
+ invoiceSeparately: charge.invoiceSeparately,
voidedInvoiceReadableId: voidedReadableId(charge.voidedSalesInvoiceId)
}))
];
@@ -428,6 +432,7 @@ async function draftAgreementInvoices(
item: line.values,
lineType: line.values.rentalLineType,
isAdjustment: line.isAdjustment,
+ invoiceSeparately: line.invoiceSeparately,
voidedInvoiceReadableId: line.voidedInvoiceReadableId
}))
);
diff --git a/packages/utils/src/rental-invoice-plan.test.ts b/packages/utils/src/rental-invoice-plan.test.ts
index d8736be113..7d23065cc7 100644
--- a/packages/utils/src/rental-invoice-plan.test.ts
+++ b/packages/utils/src/rental-invoice-plan.test.ts
@@ -20,6 +20,7 @@ const line = (
item,
lineType,
isAdjustment: false,
+ invoiceSeparately: false,
voidedInvoiceReadableId: null,
...overrides
});
@@ -42,11 +43,11 @@ describe("planRentalInvoices", () => {
]);
});
- it("Post splits rent from charges and holds the charges", () => {
+ it("Post splits off separately invoiced charges and holds them", () => {
expect(
planRentalInvoices("Post", [
line("rent", "Rent"),
- line("damage", "Charge"),
+ line("damage", "Charge", { invoiceSeparately: true }),
line("buyout", "Purchase Option")
])
).toEqual([
@@ -59,6 +60,52 @@ describe("planRentalInvoices", () => {
]);
});
+ it("puts a charge on the unheld rent invoice by default", () => {
+ expect(
+ planRentalInvoices("Post and Email", [
+ line("rent", "Rent"),
+ line("insurance", "Charge"),
+ line("damage", "Charge", { invoiceSeparately: true })
+ ])
+ ).toEqual([
+ { lines: ["rent", "insurance"], holdReason: null, role: "rent" },
+ { lines: ["damage"], holdReason: RENTAL_HOLD_CHARGES, role: "charges" }
+ ]);
+ });
+
+ it("drafts a charge unheld when no rent is due", () => {
+ expect(planRentalInvoices("Post", [line("insurance", "Charge")])).toEqual([
+ { lines: ["insurance"], holdReason: null, role: "rent" }
+ ]);
+ });
+
+ it("always invoices a Purchase Option separately", () => {
+ expect(
+ planRentalInvoices("Post", [
+ line("rent", "Rent"),
+ line("buyout", "Purchase Option")
+ ])
+ ).toEqual([
+ { lines: ["rent"], holdReason: null, role: "rent" },
+ { lines: ["buyout"], holdReason: RENTAL_HOLD_CHARGES, role: "charges" }
+ ]);
+ });
+
+ it("holds a rent invoice re-billing a voided charge", () => {
+ expect(
+ planRentalInvoices("Post", [
+ line("rent", "Rent"),
+ line("insurance", "Charge", { voidedInvoiceReadableId: "INV-7" })
+ ])
+ ).toEqual([
+ {
+ lines: ["rent", "insurance"],
+ holdReason: rentalHoldRebill(["INV-7"]),
+ role: "rent"
+ }
+ ]);
+ });
+
it("holds a rent invoice carrying an early-return adjustment", () => {
expect(
planRentalInvoices("Post and Email", [
@@ -74,8 +121,12 @@ describe("planRentalInvoices", () => {
]);
});
- it("Post with charges only drafts one held charges invoice", () => {
- expect(planRentalInvoices("Post", [line("damage", "Charge")])).toEqual([
+ it("Post with separate charges only drafts one held charges invoice", () => {
+ expect(
+ planRentalInvoices("Post", [
+ line("damage", "Charge", { invoiceSeparately: true })
+ ])
+ ).toEqual([
{ lines: ["damage"], holdReason: RENTAL_HOLD_CHARGES, role: "charges" }
]);
});
diff --git a/packages/utils/src/rental-invoice-plan.ts b/packages/utils/src/rental-invoice-plan.ts
index 414fb87ccb..b220e9d031 100644
--- a/packages/utils/src/rental-invoice-plan.ts
+++ b/packages/utils/src/rental-invoice-plan.ts
@@ -24,6 +24,8 @@ export type PlannableLine<T> = {
item: T;
lineType: "Rent" | "Charge" | "Purchase Option";
isAdjustment: boolean;
+ /** A Charge drafted on its own held invoice instead of with the rent. */
+ invoiceSeparately: boolean;
/** Readable id of a voided invoice this row was previously billed on, else null. */
voidedInvoiceReadableId: string | null;
};
@@ -37,9 +39,12 @@ export type PlannedInvoice<T> = {
/**
* Splits one agreement's due lines into the invoices to draft.
* - Draft Only → one combined invoice, no hold (nothing is automated).
- * - Otherwise → a rent invoice and a charges invoice (Charge + Purchase
- * Option, always held: a person confirms damage and buy-outs).
+ * - Otherwise → a rent invoice, unheld, carrying the rent and every Charge
+ * (alone when no rent is due), and a charges invoice, always held, for
+ * the Charges marked `invoiceSeparately` and every Purchase Option — a
+ * person confirms damage and buy-outs.
* Rent hold precedence: re-bill of a voided invoice > early-return adjustment.
+ * The re-bill check covers every line of the rent invoice, charges included.
* Empty invoices are omitted. Line order inside each invoice is the input order.
*/
export function planRentalInvoices<T>(
@@ -54,8 +59,10 @@ export function planRentalInvoices<T>(
];
}
- const rent = lines.filter((l) => l.lineType === "Rent");
- const charges = lines.filter((l) => l.lineType !== "Rent");
+ const withRent = (l: PlannableLine<T>) =>
+ l.lineType === "Rent" || (l.lineType === "Charge" && !l.invoiceSeparately);
+ const rent = lines.filter(withRent);
+ const charges = lines.filter((l) => !withRent(l));
const planned: PlannedInvoice<T>[] = [];
if (rent.length > 0) {
diff --git a/packages/viewer/AGENTS.md b/packages/viewer/AGENTS.md
index dc5e0ac1d2..e7500fdfa0 100644
--- a/packages/viewer/AGENTS.md
+++ b/packages/viewer/AGENTS.md
@@ -46,7 +46,6 @@ pnpm --filter @carbon/viewer typecheck # tsgo --noEmit
| `.` | `AssemblyPlayer` (+ `AssemblyPlayerHandle`/`Props`), `AssemblyViewer`, `ModelCanvas`, all plan/motion/graph/camera/describe/visibility helpers and types |
| `./steps` | Three-free plan→steps logic for server code: `buildAssemblyStepGroups`, `assignStepPhases`, `indexAssemblyGraph`, `CURRENT_PLAN_VERSION` |
| `./canvas` | `ModelCanvas` — standalone static GLB viewer (orbit + view, no steps) |
-| `./empty-cabinet` | `EmptyCabinet` — the rendered filing cabinet on ERP empty states (`~/components/Empty`). Lazy-imports `empty-cabinet/scene.ts`, which builds the cabinet procedurally and renders every instance on ONE shared `WebGLRenderer`, copied into a per-instance 2D canvas (browsers cap live WebGL contexts at ~16). Colours come from the theme's CSS variables |
| `./model-preview` | `ModelPreview` — progressive multi-tier preview (LOD → optimised → raw WASM), lazy-loads three.js on scroll-into-view |
| `./optimize-progress` | `OptimizeProgress` — optimise-status chip |
| `./use-optimized-model` | `useOptimizedModel` — TanStack Query polling of the model optimise lifecycle (shared by ERP `CadModel` + MES model tab) |
diff --git a/packages/viewer/package.json b/packages/viewer/package.json
index 70f6042bf0..d052504675 100644
--- a/packages/viewer/package.json
+++ b/packages/viewer/package.json
@@ -28,7 +28,6 @@
".": "./src/index.ts",
"./steps": "./src/steps.ts",
"./canvas": "./src/ModelCanvas.tsx",
- "./empty-cabinet": "./src/EmptyCabinet.tsx",
"./model-preview": "./src/ModelPreview.tsx",
"./optimize-progress": "./src/OptimizeProgress.tsx",
"./use-optimized-model": "./src/useOptimizedModel.ts"
diff --git a/packages/viewer/src/EmptyCabinet.tsx b/packages/viewer/src/EmptyCabinet.tsx
deleted file mode 100644
index c4e9ba62c1..0000000000
--- a/packages/viewer/src/EmptyCabinet.tsx
+++ /dev/null
@@ -1,70 +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 { useEffect, useRef, useState } from "react";
-import { cn } from "./utils";
-
-type EmptyCabinetProps = {
- className?: string;
- width?: number;
- height?: number;
-};
-
-/**
- * A rendered filing cabinet whose bottom drawer slides open, empty — the
- * illustration on empty states. three.js is imported on mount, so a page that
- * shows one ships none of it in its own bundle; until it arrives (or when
- * WebGL is unavailable) the canvas simply stays transparent. Dragging turns
- * the cabinet; on touch only a sideways drag does, so a vertical swipe still
- * scrolls the page.
- */
-export function EmptyCabinet({
- className,
- width = 152,
- height = 170
-}: EmptyCabinetProps) {
- const ref = useRef<HTMLCanvasElement>(null);
- const [ready, setReady] = useState(false);
-
- useEffect(() => {
- const canvas = ref.current;
- if (!canvas) return;
- // At least 2× so the downsample antialiases the outlines on 1× screens.
- const scale = Math.min(3, Math.max(2, window.devicePixelRatio || 1));
- canvas.width = Math.round(width * scale);
- canvas.height = Math.round(height * scale);
-
- let cancelled = false;
- let dispose: (() => void) | null = null;
- import("./empty-cabinet/scene")
- .then(({ playCabinet }) => {
- if (cancelled) return;
- dispose = playCabinet(canvas, {
- animate: !window.matchMedia("(prefers-reduced-motion: reduce)")
- .matches
- });
- if (dispose) setReady(true);
- })
- .catch(() => {
- // Decoration only: a failed chunk load leaves the canvas empty.
- });
- return () => {
- cancelled = true;
- dispose?.();
- };
- }, [width, height]);
-
- return (
- <canvas
- ref={ref}
- aria-hidden="true"
- style={{ width, height }}
- className={cn(
- "transition-opacity duration-300 touch-pan-y",
- ready ? "opacity-100 cursor-grab active:cursor-grabbing" : "opacity-0",
- className
- )}
- />
- );
-}
diff --git a/packages/viewer/src/empty-cabinet/scene.ts b/packages/viewer/src/empty-cabinet/scene.ts
deleted file mode 100644
index 98bb1e2205..0000000000
--- a/packages/viewer/src/empty-cabinet/scene.ts
+++ /dev/null
@@ -1,804 +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 {
- AmbientLight,
- BoxGeometry,
- CapsuleGeometry,
- Color,
- CylinderGeometry,
- DirectionalLight,
- EdgesGeometry,
- Group,
- LineBasicMaterial,
- LineSegments,
- type Material,
- Mesh,
- MeshBasicMaterial,
- MeshDepthMaterial,
- MeshStandardMaterial,
- NoToneMapping,
- type Object3D,
- OrthographicCamera,
- PCFSoftShadowMap,
- PlaneGeometry,
- PointLight,
- Scene,
- ShaderMaterial,
- SRGBColorSpace,
- Vector3,
- WebGLRenderer,
- WebGLRenderTarget
-} from "three";
-import {
- HorizontalBlurShader,
- RoundedBoxGeometry,
- VerticalBlurShader
-} from "three-stdlib";
-
-// A two-drawer steel filing cabinet whose bottom drawer slides open, empty.
-//
-// Every empty state on a page shares ONE WebGL renderer: browsers cap live
-// WebGL contexts at ~16 and a list page can show more empty states than that.
-// Each instance owns a plain 2D canvas, and a frame is rendered on the shared
-// renderer and copied across with `drawImage` in the same task, before the
-// drawing buffer is discarded. An instance renders only while its drawer is
-// moving or someone is turning it; otherwise it costs nothing until the theme
-// changes.
-
-// Proportions follow the line drawing this replaces: a narrow, tall cabinet,
-// about as deep as it is wide, standing on four feet.
-const W = 0.8;
-const D = 0.85;
-const H = 1.32;
-const FOOT = 0.045;
-const SIDE = 0.022;
-const PLINTH = 0.07;
-const RAIL = 0.03;
-const CAP = 0.045;
-const GAP = 0.008;
-const OPENING = (H - PLINTH - RAIL - CAP) / 2;
-const FRONT_Z = D / 2;
-const FRONT_DEPTH = 0.03;
-const TRAVEL = 0.62;
-
-const BOX_WIDTH = W - 2 * SIDE - 0.07;
-const BOX_DEPTH = D - 0.13;
-const BOX_HEIGHT = OPENING - 0.12;
-const SHEET = 0.012;
-
-// The drawer is pulled, runs out on its slides, and knocks against the stop:
-// it decelerates into the end of travel, then rebounds a few millimetres.
-const DELAY = 0.35;
-const PULL = 0.95;
-const REBOUND = 0.24;
-const REBOUND_DEPTH = 0.018;
-
-function drawerTravel(seconds: number) {
- const t = seconds - DELAY;
- if (t <= 0) return 0;
- if (t < PULL) {
- const u = t / PULL;
- // Ease in over the first few frames (the pull starts from rest), then
- // decelerate on the slides' friction into the stop.
- const pull = 1 - (1 - u) ** 3;
- const start = Math.min(1, u * 6);
- return pull * (start * start * (3 - 2 * start) * 0.15 + 0.85);
- }
- const r = t - PULL;
- if (r < REBOUND) return 1 - REBOUND_DEPTH * Math.sin((Math.PI * r) / REBOUND);
- return 1;
-}
-
-const DURATION = DELAY + PULL + REBOUND;
-
-// Turntable. The cabinet spins about the middle of its footprint with the
-// drawer out, and the camera tilts between near eye level and a steep view; at
-// rest it looks at the cabinet from a little above eye level, so the fronts
-// read and the top is a sliver.
-const PIVOT_Z = TRAVEL / 2;
-const REACH = Math.hypot(W / 2, (D + TRAVEL) / 2);
-const FLOOR_REACH = REACH + 0.12;
-const HEIGHT = FOOT + H;
-const REST_PITCH = (13 * Math.PI) / 180;
-const MIN_PITCH = (4 * Math.PI) / 180;
-const MAX_PITCH = (55 * Math.PI) / 180;
-const DRAG_SPEED = 0.012;
-const SPIN_DAMPING = 4;
-
-// Contact shadow: the floor's view of the cabinet from below, darker the
-// closer a surface is to the floor, blurred. Height-aware, so the drawer —
-// riding higher than the feet — throws a softer, fainter shadow than the
-// carcass, and it follows any rotation for free.
-const CONTACT_SIZE = 2 * (REACH + 0.35);
-const CONTACT_HEIGHT = 0.8;
-const CONTACT_RESOLUTION = 256;
-const CONTACT_BLUR = 3;
-
-type Palette = {
- steel: Color;
- card: Color;
- handle: Color;
- ink: Color;
- foot: Color;
- edge: Color;
- dark: boolean;
-};
-
-type View = { travel: number; yaw: number; pitch: number };
-
-type ContactShadow = {
- render: (renderer: WebGLRenderer, scene: Scene) => void;
- material: MeshBasicMaterial;
-};
-
-type Shared = {
- renderer: WebGLRenderer;
- scene: Scene;
- camera: OrthographicCamera;
- target: Vector3;
- pivot: Group;
- drawer: Group;
- slide: Group;
- contact: ContactShadow;
- outlines: LineSegments[];
- ambient: AmbientLight;
- key: DirectionalLight;
- fill: DirectionalLight;
- glow: PointLight;
- materials: {
- steel: MeshStandardMaterial;
- card: MeshStandardMaterial;
- foot: MeshStandardMaterial;
- handle: MeshStandardMaterial;
- rail: MeshStandardMaterial;
- ink: MeshBasicMaterial;
- edge: LineBasicMaterial;
- };
-};
-
-let shared: Shared | null | undefined;
-
-function getShared(): Shared | null {
- if (shared !== undefined) return shared;
- try {
- shared = createScene();
- } catch {
- shared = null;
- }
- return shared;
-}
-
-function createScene(): Shared {
- const renderer = new WebGLRenderer({
- antialias: true,
- alpha: true,
- powerPreference: "low-power"
- });
- renderer.setClearColor(0x000000, 0);
- renderer.outputColorSpace = SRGBColorSpace;
- renderer.toneMapping = NoToneMapping;
- renderer.shadowMap.enabled = true;
- renderer.shadowMap.type = PCFSoftShadowMap;
-
- const materials = {
- steel: new MeshStandardMaterial({
- roughness: 0.62,
- metalness: 0.05,
- polygonOffset: true,
- polygonOffsetFactor: 1,
- polygonOffsetUnits: 1
- }),
- card: new MeshStandardMaterial({ roughness: 0.9, metalness: 0 }),
- foot: new MeshStandardMaterial({ roughness: 0.8, metalness: 0 }),
- handle: new MeshStandardMaterial({ roughness: 0.38, metalness: 0.15 }),
- rail: new MeshStandardMaterial({ roughness: 0.32, metalness: 0.35 }),
- ink: new MeshBasicMaterial(),
- edge: new LineBasicMaterial({ transparent: true })
- };
-
- const scene = new Scene();
- const pivot = new Group();
- scene.add(pivot);
- const cabinet = new Group();
- cabinet.position.z = -PIVOT_Z;
- pivot.add(cabinet);
- const outlines: LineSegments[] = [];
-
- const part = (
- parent: Object3D,
- size: [number, number, number],
- center: [number, number, number],
- material: Material = materials.steel,
- { edges = true, radius = 0.006 } = {}
- ) => {
- const [w, h, d] = size;
- const geometry =
- radius > 0 && Math.min(w, h, d) > radius * 2.5
- ? new RoundedBoxGeometry(w, h, d, 2, radius)
- : new BoxGeometry(w, h, d);
- const mesh = new Mesh(geometry, material);
- mesh.position.set(...center);
- mesh.castShadow = true;
- mesh.receiveShadow = true;
- parent.add(mesh);
- if (edges) {
- // Outlines come from the sharp box, not the rounded one: a rounded box's
- // bevel facets would each draw a line. The offset is under a pixel.
- const lines = new LineSegments(
- new EdgesGeometry(new BoxGeometry(w, h, d)),
- materials.edge
- );
- lines.position.set(...center);
- parent.add(lines);
- outlines.push(lines);
- }
- return mesh;
- };
-
- // Carcass. The front of the cabinet faces +z.
- const yb = FOOT;
- const innerW = W - 2 * SIDE;
- part(cabinet, [W, PLINTH, D], [0, yb + PLINTH / 2, 0]);
- for (const side of [-1, 1]) {
- part(
- cabinet,
- [SIDE, H - CAP, D],
- [side * (W / 2 - SIDE / 2), yb + (H - CAP) / 2, 0]
- );
- }
- part(
- cabinet,
- [innerW, H - CAP - PLINTH, SIDE],
- [0, yb + PLINTH + (H - CAP - PLINTH) / 2, -D / 2 + SIDE / 2],
- materials.steel,
- { edges: false }
- );
- part(
- cabinet,
- [innerW, RAIL, 0.05],
- [0, yb + PLINTH + OPENING + RAIL / 2, FRONT_Z - 0.025]
- );
- part(
- cabinet,
- [W + 0.016, CAP, D + 0.016],
- [0, yb + H - CAP / 2, 0],
- materials.steel,
- { radius: 0.01 }
- );
- // Ceiling of the bottom bay, seen when looking up into the open drawer's slot.
- part(
- cabinet,
- [innerW, SHEET, D - 0.06],
- [0, yb + PLINTH + OPENING + RAIL / 2, -0.03],
- materials.steel,
- { edges: false }
- );
-
- // Lock cylinder in the top rail.
- const lock = new Mesh(
- new CylinderGeometry(0.018, 0.018, 0.012, 20),
- materials.handle
- );
- lock.rotation.x = Math.PI / 2;
- lock.position.set(W / 2 - 0.08, yb + H - CAP / 2, FRONT_Z + 0.014);
- cabinet.add(lock);
- const keyway = new Mesh(new BoxGeometry(0.004, 0.018, 0.004), materials.foot);
- keyway.position.set(W / 2 - 0.08, yb + H - CAP / 2, FRONT_Z + 0.02);
- cabinet.add(keyway);
-
- for (const x of [-1, 1]) {
- for (const z of [-1, 1]) {
- part(
- cabinet,
- [0.07, FOOT, 0.07],
- [x * (W / 2 - 0.06), FOOT / 2, z * (D / 2 - 0.06)],
- materials.foot,
- { radius: 0 }
- );
- }
- }
-
- // A drawer front: the panel, a card holder, and a pull handle.
- const front = (parent: Object3D, centerY: number) => {
- const fw = innerW - 2 * GAP;
- const fh = OPENING - 2 * GAP;
- const z = FRONT_Z - FRONT_DEPTH / 2 + 0.004;
- part(parent, [fw, fh, FRONT_DEPTH], [0, centerY, z], materials.steel, {
- radius: 0.008
- });
- const face = z + FRONT_DEPTH / 2;
- // Card holder and pull in a contrasting finish (dark on a light cabinet,
- // bright on a dark one) so they read at empty-state size. Neither casts a
- // shadow: under a near-overhead light a handle drops a streak down the
- // whole drawer front.
- const labelY = centerY + fh * 0.13;
- part(
- parent,
- [0.18, 0.092, 0.008],
- [0, labelY, face + 0.004],
- materials.handle,
- { edges: false, radius: 0.003 }
- );
- part(
- parent,
- [0.154, 0.066, 0.004],
- [0, labelY, face + 0.009],
- materials.card,
- { edges: false, radius: 0 }
- );
- part(
- parent,
- [0.09, 0.012, 0.002],
- [-0.016, labelY + 0.008, face + 0.0115],
- materials.ink,
- { edges: false, radius: 0 }
- );
- part(
- parent,
- [0.06, 0.012, 0.002],
- [-0.031, labelY - 0.014, face + 0.0115],
- materials.ink,
- { edges: false, radius: 0 }
- );
-
- const handleY = centerY - fh * 0.06;
- const bar = new Mesh(
- new CapsuleGeometry(0.016, 0.22, 6, 16),
- materials.handle
- );
- bar.rotation.z = Math.PI / 2;
- bar.position.set(0, handleY, face + 0.052);
- parent.add(bar);
- for (const x of [-0.11, 0.11]) {
- const post = new Mesh(
- new CylinderGeometry(0.012, 0.013, 0.052, 12),
- materials.handle
- );
- post.rotation.x = Math.PI / 2;
- post.position.set(x, handleY, face + 0.026);
- parent.add(post);
- }
- };
-
- const bottomCenter = yb + PLINTH + OPENING / 2;
- const topCenter = yb + PLINTH + OPENING + RAIL + OPENING / 2;
- front(cabinet, topCenter);
-
- // The bottom drawer: a front and an open steel box with hanging-file rails.
- const drawer = new Group();
- cabinet.add(drawer);
- front(drawer, bottomCenter);
- const boxBack = FRONT_Z - FRONT_DEPTH - BOX_DEPTH;
- const boxZ = boxBack + BOX_DEPTH / 2;
- const floorY = yb + PLINTH + 0.035;
- part(drawer, [BOX_WIDTH, SHEET, BOX_DEPTH], [0, floorY, boxZ]);
- for (const side of [-1, 1]) {
- const x = side * (BOX_WIDTH / 2 - SHEET / 2);
- part(
- drawer,
- [SHEET, BOX_HEIGHT, BOX_DEPTH],
- [x, floorY + BOX_HEIGHT / 2, boxZ]
- );
- // Hanging-file lip folded outward along the top of each side.
- part(
- drawer,
- [0.024, 0.008, BOX_DEPTH],
- [x + side * 0.006, floorY + BOX_HEIGHT, boxZ],
- materials.steel,
- { radius: 0 }
- );
- // The drawer's own slide member.
- part(
- drawer,
- [0.01, 0.034, BOX_DEPTH * 0.94],
- [side * (BOX_WIDTH / 2 + 0.007), floorY + BOX_HEIGHT * 0.45, boxZ],
- materials.rail,
- { edges: false, radius: 0 }
- );
- }
- part(
- drawer,
- [BOX_WIDTH, BOX_HEIGHT, SHEET],
- [0, floorY + BOX_HEIGHT / 2, boxBack + SHEET / 2]
- );
-
- // The telescoping intermediate member runs out half as far as the drawer, and
- // the cabinet member stays put — what a full-extension slide actually does.
- const slide = new Group();
- cabinet.add(slide);
- for (const side of [-1, 1]) {
- part(
- slide,
- [0.008, 0.044, BOX_DEPTH * 0.94],
- [side * (BOX_WIDTH / 2 + 0.016), floorY + BOX_HEIGHT * 0.45, boxZ],
- materials.rail,
- { edges: false, radius: 0 }
- );
- part(
- cabinet,
- [0.007, 0.054, D - 0.08],
- [side * (innerW / 2 - 0.004), floorY + BOX_HEIGHT * 0.45, -0.01],
- materials.rail,
- { edges: false, radius: 0 }
- );
- }
-
- const contact = createContactShadow(scene, [...outlines]);
-
- // Light from above, in front and to the left: the top is brightest, the front
- // next, and the right side falls into shade — the same reading as the line
- // drawing, where the front was light and the side was muted. The key light
- // shadows the cabinet onto itself (the drawer's walls onto its floor); the
- // floor takes only the contact shadow.
- const ambient = new AmbientLight(0xffffff);
- scene.add(ambient);
- const key = new DirectionalLight(0xffffff);
- key.position.set(-0.4, 6, 1);
- key.castShadow = true;
- key.shadow.mapSize.set(2048, 2048);
- key.shadow.camera.left = -1.1;
- key.shadow.camera.right = 1.1;
- key.shadow.camera.top = 1.1;
- key.shadow.camera.bottom = -1.1;
- key.shadow.camera.near = 3;
- key.shadow.camera.far = 8;
- key.shadow.bias = -0.0003;
- key.shadow.normalBias = 0.015;
- key.target.position.set(0, H / 2, 0);
- scene.add(key, key.target);
- const fill = new DirectionalLight(0xffffff);
- fill.position.set(3, 1.2, -0.6);
- scene.add(fill);
- // A near light above the front so each face brightens toward the top, as a
- // room light falls off — flat directional light alone reads as a diagram.
- const glow = new PointLight(0xffffff, 0, 0, 2);
- glow.position.set(-1.1, H + 0.6, D + 0.9);
- scene.add(glow);
-
- const camera = new OrthographicCamera(-1, 1, 1, -1, 0.1, 20);
- const target = new Vector3(0, HEIGHT / 2, 0);
-
- return {
- renderer,
- scene,
- camera,
- target,
- pivot,
- drawer,
- slide,
- contact,
- outlines,
- ambient,
- key,
- fill,
- glow,
- materials
- };
-}
-
-const FULLSCREEN_VERTEX = /* glsl */ `
- varying vec2 vUv;
- void main() {
- vUv = uv;
- gl_Position = vec4(position.xy, 0.0, 1.0);
- }
-`;
-
-function createContactShadow(scene: Scene, hidden: Object3D[]): ContactShadow {
- const options = { depthBuffer: true, generateMipmaps: false };
- const target = new WebGLRenderTarget(
- CONTACT_RESOLUTION,
- CONTACT_RESOLUTION,
- options
- );
- const blurTarget = new WebGLRenderTarget(
- CONTACT_RESOLUTION,
- CONTACT_RESOLUTION,
- options
- );
-
- // Looks straight up from the floor; its image's up is +z, right is +x.
- const half = CONTACT_SIZE / 2;
- const camera = new OrthographicCamera(
- -half,
- half,
- half,
- -half,
- 0,
- CONTACT_HEIGHT
- );
- camera.rotation.x = Math.PI / 2;
- scene.add(camera);
-
- // Black, with alpha falling off by height above the floor. The power curve
- // keeps a surface a hand's width up from casting as dark as the feet.
- const depth = new MeshDepthMaterial();
- depth.onBeforeCompile = (shader) => {
- shader.fragmentShader = shader.fragmentShader.replace(
- "vec4( vec3( 1.0 - fragCoordZ ), opacity );",
- "vec4( vec3( 0.0 ), pow( 1.0 - fragCoordZ, 2.5 ) );"
- );
- };
-
- const blurMaterial = (fragmentShader: string, direction: "h" | "v") =>
- new ShaderMaterial({
- uniforms: { tDiffuse: { value: null }, [direction]: { value: 0 } },
- vertexShader: FULLSCREEN_VERTEX,
- fragmentShader,
- depthTest: false,
- depthWrite: false
- });
- const horizontal = blurMaterial(HorizontalBlurShader.fragmentShader, "h");
- const vertical = blurMaterial(VerticalBlurShader.fragmentShader, "v");
- const quad = new Mesh(new PlaneGeometry(2, 2), horizontal);
- quad.frustumCulled = false;
-
- const blur = (renderer: WebGLRenderer, amount: number) => {
- quad.material = horizontal;
- horizontal.uniforms.tDiffuse!.value = target.texture;
- horizontal.uniforms.h!.value = amount / CONTACT_RESOLUTION;
- renderer.setRenderTarget(blurTarget);
- renderer.render(quad, camera);
- quad.material = vertical;
- vertical.uniforms.tDiffuse!.value = blurTarget.texture;
- vertical.uniforms.v!.value = amount / CONTACT_RESOLUTION;
- renderer.setRenderTarget(target);
- renderer.render(quad, camera);
- };
-
- const material = new MeshBasicMaterial({
- map: target.texture,
- transparent: true,
- depthWrite: false
- });
- const floor = new Mesh(
- new PlaneGeometry(CONTACT_SIZE, CONTACT_SIZE),
- material
- );
- floor.rotation.x = -Math.PI / 2;
- // The camera sees the floor mirrored; flipping v puts each shadow under its
- // own part.
- floor.scale.y = -1;
- floor.position.y = 0.001;
- floor.renderOrder = -1;
- scene.add(floor);
-
- const shadowCasters = [...hidden, floor];
-
- return {
- material,
- render(renderer, renderScene) {
- const visible = shadowCasters.map((object) => object.visible);
- for (const object of shadowCasters) object.visible = false;
- renderScene.overrideMaterial = depth;
- renderer.setRenderTarget(target);
- renderer.clear();
- renderer.render(renderScene, camera);
- renderScene.overrideMaterial = null;
- shadowCasters.forEach((object, i) => {
- object.visible = visible[i]!;
- });
- blur(renderer, CONTACT_BLUR);
- blur(renderer, CONTACT_BLUR * 0.4);
- renderer.setRenderTarget(null);
- }
- };
-}
-
-let probe: CanvasRenderingContext2D | null = null;
-
-function cssColor(element: Element, name: string, fallback: string) {
- const value = getComputedStyle(element).getPropertyValue(name).trim();
- if (!value) return new Color(fallback);
- probe ??= document.createElement("canvas").getContext("2d");
- if (!probe) return new Color(fallback);
- probe.fillStyle = fallback;
- probe.fillStyle = value;
- return new Color().setStyle(probe.fillStyle);
-}
-
-function readPalette(element: Element): Palette {
- const background = cssColor(element, "--color-background", "#ffffff");
- const foreground = cssColor(element, "--color-foreground", "#09090b");
- const dark = background.getHSL({ h: 0, s: 0, l: 0 }).l < 0.5;
- const mix = (amount: number) => background.clone().lerp(foreground, amount);
- return {
- steel: mix(dark ? 0.12 : 0.09),
- card: mix(dark ? 0.82 : 0),
- handle: mix(dark ? 0.78 : 0.72),
- ink: mix(dark ? 0.25 : 0.5),
- foot: mix(dark ? 0.04 : 0.55),
- edge: mix(dark ? 0.42 : 0.62),
- dark
- };
-}
-
-function applyPalette(s: Shared, palette: Palette) {
- s.materials.steel.color.copy(palette.steel);
- s.materials.card.color.copy(palette.card);
- s.materials.foot.color.copy(palette.foot);
- s.materials.handle.color.copy(palette.handle);
- s.materials.rail.color
- .copy(palette.steel)
- .multiplyScalar(palette.dark ? 1.4 : 0.92);
- s.materials.ink.color.copy(palette.ink);
- s.materials.edge.color.copy(palette.edge);
- s.materials.edge.opacity = palette.dark ? 0.5 : 0.42;
- s.contact.material.opacity = palette.dark ? 0.7 : 0.36;
- // Physically based lights: an intensity of π returns a surface's own colour.
- const boost = palette.dark ? 1.25 : 1;
- s.ambient.intensity = Math.PI * 0.42 * boost;
- s.key.intensity = Math.PI * 0.55 * boost;
- s.fill.intensity = Math.PI * 0.07 * boost;
- s.glow.intensity = Math.PI * 1.3 * boost;
-}
-
-function draw(
- s: Shared,
- context: CanvasRenderingContext2D,
- palette: Palette,
- view: View
-) {
- const { width, height } = context.canvas;
- if (
- s.renderer.domElement.width !== width ||
- s.renderer.domElement.height !== height
- ) {
- s.renderer.setSize(width, height, false);
- }
- // Orthographic camera on a sphere around the middle of the cabinet, framed
- // so no yaw clips the cabinet or its shadow: the cabinet sweeps a cylinder
- // (wider at the floor, where the shadow spreads), and on screen a cylinder's
- // rim reaches its radius across and half its height × cos(pitch) + radius ×
- // sin(pitch) up and down. Spinning never zooms; tilting steeply zooms out
- // only as far as the taller silhouette needs.
- const pad = 0.03;
- const halfWidth = FLOOR_REACH + pad;
- const halfHeight =
- (HEIGHT / 2) * Math.cos(view.pitch) +
- FLOOR_REACH * Math.sin(view.pitch) +
- pad;
- const scale = Math.max((2 * halfWidth) / width, (2 * halfHeight) / height);
- s.camera.left = -(width * scale) / 2;
- s.camera.right = (width * scale) / 2;
- s.camera.top = (height * scale) / 2;
- s.camera.bottom = -(height * scale) / 2;
- s.camera.updateProjectionMatrix();
- s.camera.position.set(
- s.target.x + 6 * Math.cos(view.pitch) * Math.SQRT1_2,
- s.target.y + 6 * Math.sin(view.pitch),
- s.target.z + 6 * Math.cos(view.pitch) * Math.SQRT1_2
- );
- s.camera.lookAt(s.target);
-
- applyPalette(s, palette);
- s.pivot.rotation.y = view.yaw;
- s.drawer.position.z = view.travel * TRAVEL;
- s.slide.position.z = (view.travel * TRAVEL) / 2;
- s.scene.updateMatrixWorld();
- s.contact.render(s.renderer, s.scene);
- s.renderer.render(s.scene, s.camera);
- context.clearRect(0, 0, width, height);
- context.drawImage(s.renderer.domElement, 0, 0, width, height);
-}
-
-/**
- * Plays the drawer opening on `canvas` (sized by the caller in device pixels),
- * lets the pointer turn the cabinet, and keeps the frame in step with the
- * theme. Returns a disposer, or `null` when WebGL is unavailable.
- */
-export function playCabinet(
- canvas: HTMLCanvasElement,
- { animate = true }: { animate?: boolean } = {}
-): (() => void) | null {
- const s = getShared();
- const context = canvas.getContext("2d");
- if (!s || !context) return null;
-
- let palette = readPalette(canvas);
- const view: View = {
- travel: animate ? 0 : 1,
- yaw: 0,
- pitch: REST_PITCH
- };
- let opening = animate;
- let start: number | undefined;
- let last: number | undefined;
- let frame = 0;
-
- // Drag turns it; let go and it keeps spinning, slowing to a stop.
- let pointer: { id: number; x: number; y: number; time: number } | null = null;
- let spin = 0;
-
- const tick = (now: number) => {
- frame = 0;
- const dt = last === undefined ? 0 : Math.min(0.05, (now - last) / 1000);
- last = now;
- let moving = false;
- if (opening) {
- start ??= now;
- const elapsed = (now - start) / 1000;
- view.travel = drawerTravel(elapsed);
- opening = elapsed < DURATION;
- moving ||= opening;
- }
- if (!pointer && spin !== 0) {
- view.yaw += spin * dt;
- spin *= Math.exp(-SPIN_DAMPING * dt);
- if (Math.abs(spin) < 0.05) spin = 0;
- moving ||= spin !== 0;
- }
- draw(s, context, palette, view);
- if (moving) frame = requestAnimationFrame(tick);
- else last = undefined;
- };
- const schedule = () => {
- if (!frame) frame = requestAnimationFrame(tick);
- };
-
- const onPointerDown = (event: PointerEvent) => {
- if (event.button !== 0) return;
- canvas.setPointerCapture(event.pointerId);
- pointer = {
- id: event.pointerId,
- x: event.clientX,
- y: event.clientY,
- time: event.timeStamp
- };
- spin = 0;
- };
- const onPointerMove = (event: PointerEvent) => {
- if (!pointer || event.pointerId !== pointer.id) return;
- const dx = event.clientX - pointer.x;
- const dy = event.clientY - pointer.y;
- const dt = Math.max(1, event.timeStamp - pointer.time) / 1000;
- view.yaw += dx * DRAG_SPEED;
- view.pitch = Math.min(
- MAX_PITCH,
- Math.max(MIN_PITCH, view.pitch + dy * DRAG_SPEED)
- );
- // Smoothed, so the release speed is the gesture's and not its last event's.
- spin = spin * 0.6 + ((dx * DRAG_SPEED) / dt) * 0.4;
- pointer = {
- ...pointer,
- x: event.clientX,
- y: event.clientY,
- time: event.timeStamp
- };
- schedule();
- };
- const onPointerUp = (event: PointerEvent) => {
- if (!pointer || event.pointerId !== pointer.id) return;
- // A pause before letting go means no fling.
- if (event.timeStamp - pointer.time > 80) spin = 0;
- pointer = null;
- schedule();
- };
- canvas.addEventListener("pointerdown", onPointerDown);
- canvas.addEventListener("pointermove", onPointerMove);
- canvas.addEventListener("pointerup", onPointerUp);
- canvas.addEventListener("pointercancel", onPointerUp);
-
- if (animate) draw(s, context, palette, view);
- schedule();
-
- const observer = new MutationObserver(() => {
- palette = readPalette(canvas);
- schedule();
- });
- observer.observe(document.documentElement, {
- attributes: true,
- attributeFilter: ["class", "style", "data-theme"]
- });
-
- return () => {
- observer.disconnect();
- canvas.removeEventListener("pointerdown", onPointerDown);
- canvas.removeEventListener("pointermove", onPointerMove);
- canvas.removeEventListener("pointerup", onPointerUp);
- canvas.removeEventListener("pointercancel", onPointerUp);
- if (frame) cancelAnimationFrame(frame);
- };
-}