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.

feat(accounting): capitalize zero-cost units, adjust asset cost, recost serials (#1873)

Brad Barbin8024a6330824
diff --git a/.ai/plans/2026-10-08-fixed-asset-cost-adjustment.md b/.ai/plans/2026-10-08-fixed-asset-cost-adjustment.md
new file mode 100644
index 0000000000..4cd83a410c
--- /dev/null
+++ b/.ai/plans/2026-10-08-fixed-asset-cost-adjustment.md
@@ -0,0 +1,33 @@
+# Fixed asset cost adjustment (zero-cost capitalization)
+
+A serialized unit made by a job with no production events or material issues,
+or issued into stock at no cost, carries 0 in inventory. Capitalizing it from
+stock is refused ("has no cost in inventory"), and Make to Asset creates the
+asset at 0 with nothing to correct it. Decisions (user, 2026-10-08):
+
+- Offset account: user picks, defaults to Retained Earnings.
+- Entry points: both — the capitalize form takes a cost when the unit carries
+ none, and the asset page gets **Adjust Cost**.
+- Direction: raise only.
+- Depreciation: missed Straight Line months catch up in the next run.
+
+## Tasks
+
+- [x] Migration `20261008163615_fixed-asset-cost-adjustment.sql`: enum values
+ `fixedAssetTransferType 'Cost Adjustment'`, `fixedAssetTransferSourceType 'Manual'`;
+ `pnpm db:migrate` + `pnpm run generate:types`.
+- [x] `post-asset-transfer/validators.ts`: `capitalize` gains `cost?` +
+ `offsetAccountId?`; new `adjustCost` variant; pure helpers
+ `resolveCapitalizationCost`, `statusAfterCostAdjustment`; tests.
+- [x] `post-asset-transfer/index.ts`: entered cost on capitalize (only when the
+ unit carries 0; Cr offset account); `adjustCost` (Active / Fully
+ Depreciated; Dr class asset / Cr offset; Fully Depreciated → Active when
+ NBV is above residual); DB tests.
+- [x] Depreciation: `buildDepreciationLines` adds the Straight Line shortfall
+ (book and tax) to the first month of an asset with a posted Cost
+ Adjustment; `buildDepreciationRunLines` passes the flag; utils tests.
+- [x] ERP: validators, capitalize route/form (cost + offset account when cost
+ is 0), `$fixedAssetId.adjust-cost.tsx` + `FixedAssetAdjustCostForm`, path,
+ header menu item.
+- [x] Docs: `.claude/rules/fixed-asset-lifecycle.md`, docs reference page.
+- [x] Verify: server-functions + erp typecheck, tests, Biome.
diff --git a/.ai/playbooks/serial-recost-and-zero-cost-capitalize.md b/.ai/playbooks/serial-recost-and-zero-cost-capitalize.md
new file mode 100644
index 0000000000..7e28661291
--- /dev/null
+++ b/.ai/playbooks/serial-recost-and-zero-cost-capitalize.md
@@ -0,0 +1,45 @@
+# Serial unit cost, Recost, zero-cost Capitalize, Adjust Cost
+
+Last tested: 2026-10-08
+Routes: /x/part/<itemId>/inventory (Storage Units card), /x/fixed-asset/capitalize?…, /x/fixed-asset/<id>/adjust-cost
+
+## Prerequisites
+- A Serial-tracked FIFO part (satellite dataset: `RW-010`, Buy). To get a zero-cost unit,
+ set its `itemCost.unitCost = 0` (FIFO with no open layers values a positive adjustment at the unit cost).
+- Accounting enabled; user with accounting view + update (the bypass user `[email protected]` has both).
+- Seeding: `pnpm db:seed:dev` reads `.env` (port 54322), not the worktree's `.env.local` —
+ pass `SUPABASE_DB_URL=postgresql://postgres:postgres@localhost:<db port>/postgres`. On 2026-10-08 the
+ dataset wipe failed (`customerContractInvoiceLine_parent_check`), but `crbn up` had already seeded the company.
+
+## Steps
+### 1. Add zero-cost serials
+- Part → Inventory → "Update Inventory" (click it via `eval` — a fixed toast region covers it).
+- Positive Adjustment, Serial Number textbox (the one before "What is Expiration Date?") → `RW-TEST-1`; quantity defaults to 1.
+- requestSubmit the dialog form with the "Save" button. Repeat for `RW-TEST-2`.
+- Verify: each serial row shows "No cost" (amber). Row actions sit behind a vertical-ellipsis
+ trigger (`button[aria-label=Actions]`, revealed on hover): Copy ID, Print Label, Update Quantity,
+ Recost, Capitalize as Fixed Asset. Open it with a `pointerdown` event (Radix), not `.click()`.
+
+### 2. Recost
+- Open RW-TEST-1's Actions menu → menuitem "Recost". Modal "Recost RW-TEST-1": Unit Cost (react-aria),
+ Offset Account prefilled "3100 Retained Earnings", Posting Date = today.
+- fill Unit Cost "500", blur (click a date spinbutton), verify `input[name=unitCost]` = "500".
+- requestSubmit the dialog form with the "Recost" button.
+- Verify: row shows "$500.00". DB: journal "Recost RW-010 RW-TEST-1": 1210 Raw Materials +500, 3100 Retained Earnings +500;
+ costLedger two 'Revaluation' rows (−1 @ 0, +1 @ 500 stamped).
+
+### 3. Capitalize a zero-cost unit
+- Actions menu → "Capitalize as Fixed Asset" (a link item; `a[href*="fixed-asset/capitalize"]` exists only while the menu is open).
+- Alert "This unit has no cost in inventory", Acquisition Cost field, Offset Account (Retained Earnings).
+- fill Acquisition Cost "4200", blur, verify `input[name=cost]`; requestSubmit with "Capitalize".
+- Verify: redirect to /x/fixed-asset/<id>, Acquisition Cost $4,200.00. Journal: 1370 +4200 / 3100 +4200.
+
+### 4. Adjust Cost
+- Asset header "More options" → menuitem "Adjust Cost". fill Increase "800", blur, requestSubmit with "Adjust Cost".
+- Verify: Acquisition Cost $5,000.00; Transfers table has a "Cost Adjustment" row. Journal: 1370 +800 / 3100 +800.
+
+## Selector Notes
+- Read committed values from `[role=dialog] input[name=…]`, never the visible formatted text.
+
+## Common Failures
+- A plain click on Save/Recost does nothing — requestSubmit the form.
diff --git a/.claude/rules/fixed-asset-lifecycle.md b/.claude/rules/fixed-asset-lifecycle.md
index 53ecc1859c..f96fa65f5c 100644
--- a/.claude/rules/fixed-asset-lifecycle.md
+++ b/.claude/rules/fixed-asset-lifecycle.md
@@ -39,7 +39,9 @@ Schema lives in these migrations (newest wins):
`20260717031529_split-asset-gain-loss-disposal-accounts.sql`,
`20261006220301_fleet-rental-lease-enums.sql`, `20261006220401_fleet-bridge.sql`,
`20261006220501_rental-agreements.sql` (rentals, the sales-type lease schedule and the
-`fleetAssets` view) and `20261006221601_complete-job-to-asset.sql`. Design:
+`fleetAssets` view), `20261006221601_complete-job-to-asset.sql` and
+`20261008163615_fixed-asset-cost-adjustment.sql` (the `Cost Adjustment` / `Manual`
+transfer enum values). Design:
`.ai/specs/implemented/2026-09-22-revenue-recognition-rentals-and-contracts.md` Part I §2 and §4.
## Tables (current schema)
@@ -139,8 +141,8 @@ the job → asset branch inside `complete_job_to_inventory` (Make to Asset).
- `disposalMethod`: `Sale`, `Scrapping`, `Transfer to Inventory`
(`20261006220301`; only `post-asset-transfer` writes the third — the UI
`disposalMethods` array still lists the first two)
-- `fixedAssetTransferType`: `Capitalization`, `Return to Inventory`
-- `fixedAssetTransferSourceType`: `Inventory`, `Job`, `Construction in Progress`
+- `fixedAssetTransferType`: `Capitalization`, `Return to Inventory`, `Cost Adjustment`
+- `fixedAssetTransferSourceType`: `Inventory`, `Job`, `Construction in Progress`, `Manual`
- `journalEntrySourceType`, `journalLineDocumentType`, `itemLedgerDocumentType`
each gained `Asset Transfer`
- `macrsPropertyClass`: `3`,`5`,`7`,`10`,`15`,`20`,`27.5`,`39`
@@ -167,7 +169,10 @@ enum value (CHECK: only Fixed Asset lines have non-NULL `assetId`). The
`fixedAssetReturnToInventoryValidator` (transferDate, locationId,
storageUnitId?), `fixedAssetAttachJobValidator` (jobId),
`fixedAssetCapitalizeCipValidator` (toClassId, inServiceDate),
- `fixedAssetOutOfServiceValidator` (reason).
+ `fixedAssetOutOfServiceValidator` (reason). `fixedAssetCapitalizeValidator`
+ also takes `cost?` + `offsetAccountId?` (a unit carried at zero), and
+ `fixedAssetAdjustCostValidator` (amount, offsetAccountId?, locationId,
+ transferDate) backs Adjust Cost.
- Service: `accounting.service.ts` — `getFixedAsset(s)`, `insert/update/deleteFixedAsset`,
`getFixedAssetsListForSale` (status Active/Fully Depreciated), class CRUD,
`insert/getDepreciationRun(s)`, `getDepreciationRunLines`,
@@ -231,7 +236,7 @@ enum value (CHECK: only Fixed Asset lines have non-NULL `assetId`). The
- UI: `accounting/ui/FixedAssets/` — `FixedAssetForm` (has a **Work Center**
picker, `workCenterId`), `AssetClassForm`, `FixedAssetRegisterForm`,
`FixedAssetDisposalForm`, `FixedAssetCapitalizeForm`,
- `FixedAssetReturnToInventoryForm`, `FixedAssetAttachJobForm`,
+ `FixedAssetReturnToInventoryForm`, `FixedAssetAdjustCostForm`, `FixedAssetAttachJobForm`,
`FixedAssetCapitalizeCipForm`, `FixedAssetOutOfServiceForm`,
`FixedAssetCipCosts` (the "Construction in Progress" card on the asset page,
rendered for a CIP-class asset), `FleetAssetsTable`, `FleetStatus` (its own
@@ -239,7 +244,7 @@ enum value (CHECK: only Fixed Asset lines have non-NULL `assetId`). The
`FIXED_ASSET_STATUS_COLOR_MAP` does include `Under Construction`), tables,
status badges. The asset page also lists the asset's transfers and shows
`Work Center` / `Out of Service Since` detail rows.
-- Routes: `routes/x+/fixed-asset+/$fixedAssetId.{tsx,register,dispose,sell,purchase,details,delete,capitalize,return-to-inventory,attach-job,out-of-service}`,
+- Routes: `routes/x+/fixed-asset+/$fixedAssetId.{tsx,register,dispose,sell,purchase,details,delete,capitalize,return-to-inventory,adjust-cost,attach-job,out-of-service}`,
`routes/x+/fixed-asset+/capitalize.tsx` (no id: capitalize a stock unit);
`routes/x+/depreciation-run+/$depreciationRunId.{tsx,post,repeat,recalculate,reverse,delete}`;
list/new at `routes/x+/accounting+/{fixed-assets,asset-classes,depreciation-runs}*`;
@@ -300,7 +305,15 @@ enum value (CHECK: only Fixed Asset lines have non-NULL `assetId`). The
asset per unit; see **Make to Asset** below.
4. Capitalize from stock: `post-asset-transfer` `capitalize` consumes an
`Available` serialized unit into a new (or a Draft) asset at its carrying
- cost; see **post-asset-transfer** below.
+ cost — or, for a unit carried at zero, at the cost the user enters; see
+ **post-asset-transfer** below.
+
+**Adjust Cost (post-capitalization).** An asset that came onto the books for
+less than it cost — a Make to Asset job with no WIP creates it at 0 — is raised
+by `post-asset-transfer` `adjustCost` (asset menu → **Adjust Cost**,
+`$fixedAssetId.adjust-cost.tsx`). Raise only; lowering is a write-down. The
+next depreciation run catches a Straight Line asset up on the months it took
+at the old cost (see **Depreciate**).
**Make to Asset.** The branch lives inside `complete_job_to_inventory`
(`20261006221601_complete-job-to-asset.sql`, forked from the guarded definition in
@@ -373,8 +386,11 @@ Closed; `$fixedAssetId.capitalize` offers only non-CIP classes.
**post-asset-transfer** (`packages/server-functions/src/post-asset-transfer/index.ts`,
`validators.ts` = the zod contract + pure helpers). One `fixedAssetTransfer`
-document per call, created and Posted in ONE transaction; the function declares
-`permissions: { create: "accounting" }`; business failures are 400
+document per call, created and Posted in ONE transaction; the function's permissions are keyed by
+`type`: `create: accounting` for capitalize / return / attachJob /
+capitalizeCip, `update: accounting` for `adjustCost`, and a `capitalize`
+that carries an entered `cost` additionally `authorize`s `update:
+accounting` (recosting puts a number of the user's own on the books); business failures are 400
`InvalidInputError`s with the message the app shows, a record the
caller's company does not own is a 404. With `accountingEnabled = false` every
ledger, entity and asset write is identical and no journal is created. Journals
@@ -382,7 +398,7 @@ are `sourceType 'Asset Transfer'`, lines `documentType 'Asset Transfer'`, with
Location / FixedAssetClass / Item dimensions. Four payload variants:
- `capitalize` (`fixedAssetClassId`, `itemId`, `trackedEntityId`, `locationId`,
`storageUnitId?`, `transferDate`, `name?`, `fixedAssetId?` = a Draft asset to
- fill): the unit must belong to the item, be `Available`, have no live asset
+ fill, `cost?` + `offsetAccountId?` for a unit carried at zero): the unit must belong to the item, be `Available`, have no live asset
and net on-hand at the location (`resolveCapitalizationStock`: the bin with
the highest positive net wins; a picked unit has rows in more than one bin).
Creates the asset (or fills the Draft under the same `status = 'Draft'` race
@@ -392,17 +408,27 @@ Location / FixedAssetClass / Item dimensions. Four payload variants:
for a CIP class); relieves the unit through the shared adjustment path
(`itemLedger` −1, `entryType 'Negative Adjmt.'`, cost-layer consumption at
carrying cost, no variance journal); posts Dr class asset / Cr the
- replenishment inventory account for that cost (a unit whose carrying cost
- rounds to 0 is REFUSED — "<serial> has no cost in inventory…" — and the
- transaction rolls back, rather than creating a worthless asset with no
- journal; the cost is never typed by the user, since the transfer can only
- move the value inventory holds); writes a `'Manual'` CIP row for
+ replenishment inventory account for that cost. The cost is decided by the
+ pure `resolveCapitalizationCost` (`validators.ts`): a unit that carries a
+ cost moves at it, and an entered `cost` is refused ("<serial> is carried in
+ inventory at a cost…"); a unit whose carrying cost rounds to 0 takes the
+ entered `cost` instead and the journal credits `offsetAccountId` (description
+ `Capitalized Cost`; required with accounting on, an active non-group account
+ of the company group — `getOffsetAccount`, `lib/offset-account.ts`, which
+ returns the account's class so `buildCapitalizationLines` signs the credit
+ by it: Retained Earnings is Equity, credited +x); with neither it is REFUSED —
+ "<serial> has no cost in inventory… Enter what it cost, or set a unit
+ cost…" — and the transaction rolls back. The entered value never touches
+ the cost ledger: inventory relieved the unit at 0, and the value comes from
+ the offset account, not from stock; writes a `'Manual'` CIP row for
a CIP class; sets the entity `Consumed` with `attributes['Fixed Asset']` and a
`'Capitalize'` activity. Transfer: `type 'Capitalization'`, `sourceType
'Inventory'`. Entry points: the inventory storage-unit row action and
`x+/fixed-asset+/capitalize.tsx` (defaults the class to the one named
`Rental Fleet`, hides CIP classes, shows the exact cost the transfer will
- book and disables Capitalize when it is 0). That cost comes from the
+ book; when it is 0 the form asks for an Acquisition Cost and, with
+ accounting on, an Offset Account defaulting to
+ `accountDefault.retainedEarningsAccount`). That cost comes from the
`preview-asset-capitalization` server function (`{ trackedEntityId }`,
`view: accounting`; ERP wrapper `getCapitalizationCost`): the same
`calculateCOGS` relief in a transaction that always rolls back, so it
@@ -440,6 +466,18 @@ Location / FixedAssetClass / Item dimensions. Four payload variants:
`status = 'Under Construction'`). Transfer: `type 'Capitalization'`,
`sourceType 'Construction in Progress'`, `fromClassId`, `inServiceDate`.
+- `adjustCost` (`fixedAssetId`, `amount` > 0, `offsetAccountId?`,
+ `locationId`, `transferDate`): asset must be `Active` or `Fully
+ Depreciated` (`ADJUSTABLE_ASSET_STATUSES`, re-checked under `FOR UPDATE`
+ in the transaction). Posts Dr class `assetAccountId` / Cr `offsetAccountId`
+ (description `Capitalized Cost`; required and validated when accounting is
+ on, ignored when off), `acquisitionCost += amount`, and the status from
+ `statusAfterCostAdjustment` (Fully Depreciated → Active when NBV is above
+ residual again). Fills an unset asset location from `locationId` (the
+ route asks for one only when the asset has none). Transfer: `type 'Cost
+ Adjustment'`, `sourceType 'Manual'`, `accumulatedDepreciation` recorded.
+ The route defaults the offset account to Retained Earnings.
+
**Fleet register.** `x+/accounting+/fleet.tsx` renders `getFleetAssets` with
the derived status (see the view); **Build for Fleet** (needs
`create: production`) opens `path.to.newJob?fixedAssetClassId=<the class named
@@ -551,6 +589,18 @@ Cost** panel (asset id → NBV, per-asset monthly depreciation for Straight Line
assets, totals). Machine rates are still typed by hand.
**Depreciate.** Manual, in two steps — **no scheduled/cron job exists**:
+**Cost adjustment catch-up.** `buildDepreciationRunLines` passes
+`costAdjusted` (the asset has a Posted `Cost Adjustment` transfer) to
+`buildDepreciationLines`, which adds `straightLineShortfall` — what the CURRENT
+cost would have accumulated on a straight line from the start through the
+month before the run, less what was accumulated, never negative — to the
+asset's first month (book, and tax when the tax method is Straight Line),
+capped at what is left. It is stateless: once posted the shortfall is zero,
+and Reverse Run brings it back. Declining Balance and table MACRS correct
+themselves (remaining value over remaining life / cumulative minus taken);
+Units of Production does not catch up. Gated on the adjustment so a mid-life
+registration with an opening accumulated balance is never re-derived.
+
1. `depreciation-runs.new` action calls `createDepreciationRun()`, which
builds the lines with `buildDepreciationRunLines()` and inserts a
`depreciationRun` (Draft) + one `depreciationRunLine` per asset per month.
diff --git a/.claude/rules/inventory-system.md b/.claude/rules/inventory-system.md
index 79b70c0de5..a4ea52a3ba 100644
--- a/.claude/rules/inventory-system.md
+++ b/.claude/rules/inventory-system.md
@@ -47,7 +47,27 @@ Key service functions (verified):
shipment's ledger rows) and `issue`'s `createMaterialWipEntries`. Receipt and job-output
layers cover many units and stay unstamped, so a received serial is still FIFO-costed.
Pinned by `lib/cost-layer-order.test.ts` and the database test
- `lib/calculate-cogs.test.ts`. The valuation
+ `lib/calculate-cogs.test.ts`.
+ **Serial unit cost and Recost.** `preview-serial-unit-costs` (`{ itemId,
+ locationId? }`, `view: accounting`) values every on-hand serial of an item
+ with the pure `serialUnitCost` (`lib/serial-unit-cost.ts`): calculateCOGS's
+ arithmetic for a quantity of one (own layer, then unstamped, with price
+ correction children; Standard / Average at the item cost), from one read of
+ the item's layers. ERP: `getSerialUnitCosts` → cached `api+/items.$itemId.serial-costs.ts`
+ (also returns `costingMethod` and `retainedEarningsAccountId`), read by
+ `InventoryStorageUnits` only when the user can view accounting; a zero
+ cost reads "No cost". **Recost** (row action, `update: accounting`, FIFO /
+ LIFO only) → `x+/inventory+/quantities+/$itemId.recost.tsx` →
+ `recostSerialUnit` → `recost-serial-unit` (`{ trackedEntityId, unitCost,
+ offsetAccountId?, postingDate }`, `update: accounting`): exactly one unit on
+ hand at one location; relieves it via `calculateCOGS` (its own layer first)
+ and books −1 at the old cost / +1 stamped at the new, both
+ `costLedgerType 'Revaluation'` (the only writer of that type; no
+ `itemLedger` row — nothing moves); with accounting on posts an `'Inventory
+ Adjustment'` journal of the difference, inventory account vs the offset
+ account (`getOffsetAccount`, `lib/offset-account.ts`, signed by the offset
+ account's own class via `buildOffsetLines`). The valuation report's FIFO /
+ LIFO layer average moves by exactly the difference, so the tie-out holds. The valuation
workbench tie-out offers a **Reconcile** action (`createInventoryReconciliationJournal`) that
drafts an adjusting journal for any residual pre-feature variance.
**Scrap** = a `Negative Adjmt.` movement with `documentType='Scrap'` +
diff --git a/apps/erp/app/modules/accounting/AGENTS.md b/apps/erp/app/modules/accounting/AGENTS.md
index 3dfea13675..c5707de197 100644
--- a/apps/erp/app/modules/accounting/AGENTS.md
+++ b/apps/erp/app/modules/accounting/AGENTS.md
@@ -83,7 +83,7 @@ pnpm --dir apps/erp exec vitest run app/modules/accounting
| `costCenter` | Hierarchical cost allocation units |
| `dimension` / `dimensionValue` | Analytical dimensions and custom values |
| `fixedAsset` / `fixedAssetClass` | Capital assets with depreciation configuration. Asset: `itemId`, `trackedEntityId` (unique per company while not Disposed), `quantity` (CHECK = 1), `workCenterId`, `outOfServiceSince` / `outOfServiceReason` (both or neither). Class: `isConstructionInProgress`, `gainOnDisposalAccountId` / `lossOnDisposalAccountId` |
-| `fixedAssetTransfer` | Inventory ↔ asset transfer document (`transferId` sequence `FAT`; `type` Capitalization / Return to Inventory; `sourceType` Inventory / Job / Construction in Progress; `amount`, `accumulatedDepreciation`, `journalId`; created and Posted in one step) |
+| `fixedAssetTransfer` | Inventory ↔ asset transfer document (`transferId` sequence `FAT`; `type` Capitalization / Return to Inventory / Cost Adjustment; `sourceType` Inventory / Job / Construction in Progress / Manual; `amount`, `accumulatedDepreciation`, `journalId`; created and Posted in one step) |
| `fixedAssetCipCost` | Append-only cost ledger of an asset under construction (`sourceType` Purchase Invoice / Receipt / Job / Manual, document + line ids, `jobId`, `amount`, `costDate`, `journalId`); capitalization sums these rows |
| `fleetAssets` (view) | `fixedAsset` with an `itemId`, joined to item, class, tracked entity and work center; `netBookValue` and the derived `fleetStatus` (Returned to Stock / Sold / Under Construction / On Rent / In Maintenance / Reserved / Available, in that precedence; On Rent / Reserved come from the live `rentalAgreementLine`), plus `rentalAgreementId`, `customerId`, `customerLocationId` of that line |
| `depreciationRun` / `depreciationRunLine` | Batch depreciation processing |
@@ -120,7 +120,7 @@ pnpm --dir apps/erp exec vitest run app/modules/accounting
- `getDimensions` / `getActiveDimensionsWithValues` / `saveJournalLineDimensions` — dimension management
- `getCostCenters` / `getCostCentersTree` — cost center hierarchy
- `getFixedAssets` / `insertFixedAsset` / `insertDepreciationRun` — fixed asset lifecycle. `buildDepreciationRunLines` is what a depreciation run for a period should hold; `createDepreciationRun` creates the Draft from it and refuses "Nothing to depreciate for this period" rather than leave an empty run, and refuses any period a later posted run already covers (`laterPostedRunId`). `postDepreciationRun` (`accounting.server.ts`) locks the run, refuses anything but a Draft whose lines are the ones the route checked, reads the lines and locks the assets inside its transaction, and adds to `accumulatedDepreciation` in SQL; a month with no book amount posts no journal
-- `getFleetAssets` (the `fleetAssets` view, search + `fleetStatus` filter) / `getUnderConstructionAssets` / `getFixedAssetTransfers` / `getFixedAssetCipCosts` / `getWorkCenterCapitalCost` (non-Disposed assets of a work center with NBV and straight-line monthly depreciation) / `setFixedAssetOutOfService` / `returnFixedAssetToService` / `getCapitalizationCost` (the `preview-asset-capitalization` server function: the cost `capitalize` would book, rolled back) / `invokeAssetTransfer` (`serverFns.as(...).invoke("post-asset-transfer")`, run as the caller: `capitalize`, `return`, `attachJob`, `capitalizeCip`) — the fleet bridge (`// -- Fleet --` in `accounting.service.ts`); `postAssetRegistration` (`accounting.server.ts`) takes an optional `status` and writes a `fixedAssetCipCost` row for a registration into a CIP class; `posting: null` (accounting off) writes the same rows with no journal, in the same one transaction
+- `getFleetAssets` (the `fleetAssets` view, search + `fleetStatus` filter) / `getUnderConstructionAssets` / `getFixedAssetTransfers` / `getFixedAssetCipCosts` / `getWorkCenterCapitalCost` (non-Disposed assets of a work center with NBV and straight-line monthly depreciation) / `setFixedAssetOutOfService` / `returnFixedAssetToService` / `getCapitalizationCost` (the `preview-asset-capitalization` server function: the cost `capitalize` would book, rolled back) / `invokeAssetTransfer` (`serverFns.as(...).invoke("post-asset-transfer")`, run as the caller: `capitalize` (a unit carried at zero takes an entered cost from an offset account), `return`, `attachJob`, `capitalizeCip`, `adjustCost` — raise an Active / Fully Depreciated asset's cost from an offset account, and the next depreciation run catches a Straight Line asset up) — the fleet bridge (`// -- Fleet --` in `accounting.service.ts`); `postAssetRegistration` (`accounting.server.ts`) takes an optional `status` and writes a `fixedAssetCipCost` row for a registration into a CIP class; `posting: null` (accounting off) writes the same rows with no journal, in the same one transaction
- `getRevenueRecognitionRuns` / `getRevenueRecognitionRun` / `getRevenueRecognitionRunLines` / `getRevenueSchedules` / `getDeferredRevenueWaterfall` (service) and `postRevenueRecognitionRun` / `reverseRevenueRecognitionRun` / `deleteRevenueRecognitionRun` (`accounting.server.ts`, Kysely) — recognition runs; `resolveRunPostingPeriods` / `resolveReversalPeriods` / `reverseRunJournals` are shared with depreciation runs; the proposal builder is the `propose-revenue-recognition-run` server function, and `recalculate-revenue-recognition-run` rebuilds a Draft through the same `selectDueScheduleRows` / `claimScheduleRows`
- `getRentalUtilization` — the rental utilization report (above)
- `getLeaseNetInvestment` — the net investment in leases report (above)
diff --git a/apps/erp/app/modules/accounting/accounting.models.ts b/apps/erp/app/modules/accounting/accounting.models.ts
index cfc692be2d..cd5045e9e2 100644
--- a/apps/erp/app/modules/accounting/accounting.models.ts
+++ b/apps/erp/app/modules/accounting/accounting.models.ts
@@ -1098,7 +1098,22 @@ export const fixedAssetCapitalizeValidator = z.object({
locationId: z.string().min(1, { message: "Location is required" }),
storageUnitId: zfd.text(z.string().optional()),
transferDate: z.string().min(1, { message: "Transfer date is required" }),
- name: zfd.text(z.string().optional())
+ name: zfd.text(z.string().optional()),
+ // Only for a unit inventory carries at nothing: what it cost, and the
+ // account that value was booked to when it was spent.
+ cost: zfd.numeric(
+ z.number().positive({ message: "Cost must be more than zero" }).optional()
+ ),
+ offsetAccountId: zfd.text(z.string().optional())
+});
+
+export const fixedAssetAdjustCostValidator = z.object({
+ amount: zfd.numeric(
+ z.number().positive({ message: "The increase must be more than zero" })
+ ),
+ offsetAccountId: zfd.text(z.string().optional()),
+ locationId: z.string().min(1, { message: "Location is required" }),
+ transferDate: z.string().min(1, { message: "Transfer date is required" })
});
export const fixedAssetReturnToInventoryValidator = z.object({
diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.ts
index e6a0aa4b03..30d938525e 100644
--- a/apps/erp/app/modules/accounting/accounting.service.ts
+++ b/apps/erp/app/modules/accounting/accounting.service.ts
@@ -7229,46 +7229,69 @@ export async function buildDepreciationRunLines(
}
);
- const [settings, lastPosted, laterPosted, coveredLines, assets, decimals] =
- await Promise.all([
- client
- .from("companySettings")
- .select("assetTaxDepreciationEnabled")
- .eq("id", companyId)
- .single(),
- client
- .from("depreciationRun")
- .select("periodEnd")
- .eq("companyId", companyId)
- .eq("status", "Posted")
- .lt("periodEnd", periodEnd)
- .order("periodEnd", { ascending: false })
- .limit(1)
- .maybeSingle(),
- client
- .from("depreciationRun")
- .select("depreciationRunId")
- .eq("companyId", companyId)
- .eq("status", "Posted")
- .gt("periodEnd", periodEnd)
- .order("periodEnd")
- .limit(1)
- .maybeSingle(),
- covered,
- fetchAllFromTable<Database["public"]["Tables"]["fixedAsset"]["Row"]>(
- client,
- "fixedAsset",
- "*",
- (query: any) =>
- query
- .eq("companyId", companyId)
- .eq("status", "Active")
- .order("id", { ascending: true })
- ),
- getBaseCurrencyDecimalPlaces(client, companyId, companyGroupId)
- ]);
+ const [
+ settings,
+ lastPosted,
+ laterPosted,
+ coveredLines,
+ assets,
+ decimals,
+ costAdjustments
+ ] = await Promise.all([
+ client
+ .from("companySettings")
+ .select("assetTaxDepreciationEnabled")
+ .eq("id", companyId)
+ .single(),
+ client
+ .from("depreciationRun")
+ .select("periodEnd")
+ .eq("companyId", companyId)
+ .eq("status", "Posted")
+ .lt("periodEnd", periodEnd)
+ .order("periodEnd", { ascending: false })
+ .limit(1)
+ .maybeSingle(),
+ client
+ .from("depreciationRun")
+ .select("depreciationRunId")
+ .eq("companyId", companyId)
+ .eq("status", "Posted")
+ .gt("periodEnd", periodEnd)
+ .order("periodEnd")
+ .limit(1)
+ .maybeSingle(),
+ covered,
+ fetchAllFromTable<Database["public"]["Tables"]["fixedAsset"]["Row"]>(
+ client,
+ "fixedAsset",
+ "*",
+ (query: any) =>
+ query
+ .eq("companyId", companyId)
+ .eq("status", "Active")
+ .order("id", { ascending: true })
+ ),
+ getBaseCurrencyDecimalPlaces(client, companyId, companyGroupId),
+ // Assets whose cost was raised after capitalization: a Straight Line
+ // one catches up the months it took at the old cost.
+ fetchAllFromTable<{ fixedAssetId: string }>(
+ client,
+ "fixedAssetTransfer",
+ "id, fixedAssetId",
+ (query: any) =>
+ query
+ .eq("companyId", companyId)
+ .eq("type", "Cost Adjustment")
+ .eq("status", "Posted")
+ .order("id", { ascending: true })
+ )
+ ]);
if (lastPosted.error) return { data: null, error: lastPosted.error };
+ if (costAdjustments.error || !costAdjustments.data) {
+ return { data: null, error: costAdjustments.error };
+ }
if (laterPosted.error) return { data: null, error: laterPosted.error };
if (coveredLines.error || !coveredLines.data) {
return { data: null, error: coveredLines.error };
@@ -7308,6 +7331,9 @@ export async function buildDepreciationRunLines(
const coveredAssetIds = new Set(
coveredLines.data.map((line) => line.fixedAssetId)
);
+ const costAdjustedAssetIds = new Set(
+ costAdjustments.data.map((transfer) => transfer.fixedAssetId)
+ );
const lines = buildDepreciationLines(
assets.data
@@ -7316,7 +7342,8 @@ export async function buildDepreciationRunLines(
...asset,
accumulatedTaxDepreciation: Number(
asset.accumulatedTaxDepreciation ?? 0
- )
+ ),
+ costAdjusted: costAdjustedAssetIds.has(asset.id)
})),
periodEnd,
lastPostedPeriodEnd,
diff --git a/apps/erp/app/modules/accounting/accounting.utils.test.ts b/apps/erp/app/modules/accounting/accounting.utils.test.ts
index 813a6f8795..a0f0cb8f97 100644
--- a/apps/erp/app/modules/accounting/accounting.utils.test.ts
+++ b/apps/erp/app/modules/accounting/accounting.utils.test.ts
@@ -25,6 +25,7 @@ import {
isFutureRunPeriod,
monthEndOf,
runPostingTargets,
+ straightLineShortfall,
usageKey
} from "./accounting.utils";
@@ -1342,3 +1343,135 @@ describe("diffJournalLines", () => {
expect(deleteIds).toEqual(["jl_a", "jl_b"]);
});
});
+
+describe("cost adjustment catch-up", () => {
+ // Capitalized at zero on Jan 1, depreciated (at nothing) through March,
+ // then raised to 6,000: 100 a month over 60 months.
+ const adjusted = {
+ id: "asset-adjusted",
+ acquisitionCost: 6000,
+ accumulatedDepreciation: 0,
+ residualValuePercent: 0,
+ depreciationMethod: "Straight Line",
+ usefulLifeMonths: 60,
+ depreciationStartDate: "2025-01-01",
+ acquisitionDate: "2025-01-01",
+ assetLifetimeUsage: null,
+ accumulatedTaxDepreciation: 0,
+ taxDepreciationMethod: "Straight Line",
+ taxUsefulLifeMonths: 36,
+ taxResidualValuePercent: 0,
+ macrsPropertyClass: null,
+ macrsConvention: null,
+ bonusDepreciationPercent: null,
+ costAdjusted: true
+ };
+
+ it("adds the months taken at the old cost to the run's first month", () => {
+ const lines = buildDepreciationLines(
+ [adjusted],
+ "2025-05-31",
+ "2025-03-31",
+ true,
+ new Map(),
+ 2
+ );
+ expect(lines).toEqual([
+ // 100 for April + 300 for Jan–Mar; tax 6,000 / 36 = 166.67 a month.
+ {
+ fixedAssetId: "asset-adjusted",
+ periodEnd: "2025-04-30",
+ amount: 400,
+ taxAmount: 666.67
+ },
+ {
+ fixedAssetId: "asset-adjusted",
+ periodEnd: "2025-05-31",
+ amount: 100,
+ taxAmount: 166.67
+ }
+ ]);
+ });
+
+ it("catches up once: the next run is back on schedule", () => {
+ const lines = buildDepreciationLines(
+ [
+ {
+ ...adjusted,
+ accumulatedDepreciation: 500,
+ accumulatedTaxDepreciation: 833.34
+ }
+ ],
+ "2025-06-30",
+ "2025-05-31",
+ true,
+ new Map(),
+ 2
+ );
+ expect(lines.map((line) => [line.amount, line.taxAmount])).toEqual([
+ [100, 166.67]
+ ]);
+ });
+
+ it("leaves an asset without a cost adjustment on its usual schedule", () => {
+ const lines = buildDepreciationLines(
+ [{ ...adjusted, costAdjusted: false }],
+ "2025-04-30",
+ "2025-03-31",
+ false,
+ new Map(),
+ 2
+ );
+ expect(lines.map((line) => line.amount)).toEqual([100]);
+ });
+
+ it("never takes back depreciation from an asset ahead of schedule", () => {
+ expect(
+ straightLineShortfall({
+ acquisitionCost: 6000,
+ residualValuePercent: 0,
+ usefulLifeMonths: 60,
+ startDate: "2025-01-01",
+ through: "2025-03-31",
+ accumulated: 1000,
+ decimalPlaces: 2
+ })
+ ).toEqual(0);
+ });
+
+ it("is nothing before the asset's first month has been depreciated", () => {
+ expect(
+ straightLineShortfall({
+ acquisitionCost: 6000,
+ residualValuePercent: 0,
+ usefulLifeMonths: 60,
+ startDate: "2025-04-01",
+ through: "2025-03-31",
+ accumulated: 0,
+ decimalPlaces: 2
+ })
+ ).toEqual(0);
+ });
+
+ it("never catches up past the depreciable base", () => {
+ const lines = buildDepreciationLines(
+ [
+ {
+ ...adjusted,
+ residualValuePercent: 20,
+ usefulLifeMonths: 12,
+ depreciationStartDate: "2024-01-01",
+ acquisitionDate: "2024-01-01",
+ taxDepreciationMethod: null
+ }
+ ],
+ "2025-04-30",
+ "2025-03-31",
+ false,
+ new Map(),
+ 2
+ );
+ // 6,000 less a 20 % residual is 4,800 — all of it, in one line.
+ expect(lines.map((line) => line.amount)).toEqual([4800]);
+ });
+});
diff --git a/apps/erp/app/modules/accounting/accounting.utils.ts b/apps/erp/app/modules/accounting/accounting.utils.ts
index 1f663fda60..ffc349cbd9 100644
--- a/apps/erp/app/modules/accounting/accounting.utils.ts
+++ b/apps/erp/app/modules/accounting/accounting.utils.ts
@@ -706,6 +706,52 @@ export function calculateTaxDepreciation(
return null;
}
+/** Cost less residual less what is already accumulated, never negative. */
+function depreciableRemaining(
+ asset: { acquisitionCost: number; residualValuePercent: number },
+ accumulated: number,
+ decimalPlaces: number
+): number {
+ const cost = Number(asset.acquisitionCost);
+ const base = cost - cost * (Number(asset.residualValuePercent) / 100);
+ return Math.max(0, round(base - accumulated, decimalPlaces));
+}
+
+/**
+ * What a Straight Line asset is behind by after its cost was raised: the
+ * depreciation its CURRENT cost would have accumulated from its start through
+ * `through` (the last month already depreciated), less what it accumulated at
+ * the old cost. Never negative — an asset ahead of schedule (an opening
+ * balance at registration) is left alone.
+ */
+export function straightLineShortfall(args: {
+ acquisitionCost: number;
+ residualValuePercent: number;
+ usefulLifeMonths: number;
+ startDate: string;
+ through: string | null;
+ accumulated: number;
+ /** Settlement decimals from currency.decimalPlaces — data, never a literal. */
+ decimalPlaces: number;
+}): number {
+ if (!args.through || args.usefulLifeMonths <= 0) return 0;
+ const start = toCalendarDate(args.startDate);
+ const through = toCalendarDate(args.through);
+ if (start.compare(through) > 0) return 0;
+ const cost = Number(args.acquisitionCost);
+ const depreciableBase =
+ cost - cost * (Number(args.residualValuePercent) / 100);
+ const expected = Math.min(
+ round(
+ (depreciableBase / args.usefulLifeMonths) *
+ getMonthsBetween(start, through),
+ args.decimalPlaces
+ ),
+ depreciableBase
+ );
+ return Math.max(0, round(expected - args.accumulated, args.decimalPlaces));
+}
+
/**
* One line per asset per month, from the month after `lastPostedPeriodEnd` (or
* the asset's start month) through `periodEnd` — FAM's depreciation history
@@ -713,6 +759,13 @@ export function calculateTaxDepreciation(
* tax depreciation of the months before it, so a catch-up run posts each
* month in its own period at the amount a monthly run would have posted.
* `usageMap` holds Units of Production usage by `usageKey(asset, month)`.
+ *
+ * An asset whose cost was adjusted after capitalization (`costAdjusted`, a
+ * posted Cost Adjustment transfer) took its earlier months at the old cost.
+ * Straight Line — book, and tax when its method is Straight Line — adds that
+ * shortfall to the run's first month, so the asset still ends on its original
+ * schedule. Declining Balance and MACRS need nothing: both depreciate what is
+ * left over the life that is left. Units of Production does not catch up.
*/
export function buildDepreciationLines(
assets: Array<{
@@ -732,6 +785,7 @@ export function buildDepreciationLines(
macrsPropertyClass: string | null;
macrsConvention: string | null;
bonusDepreciationPercent: number | null;
+ costAdjusted?: boolean;
}>,
periodEnd: string,
lastPostedPeriodEnd: string | null,
@@ -766,6 +820,37 @@ export function buildDepreciationLines(
? endOfMonth(firstMonth.subtract({ months: 1 })).toString()
: lastPostedPeriodEnd;
+ let catchUp = 0;
+ let taxCatchUp = 0;
+ if (asset.costAdjusted && start) {
+ if (asset.depreciationMethod === "Straight Line") {
+ catchUp = straightLineShortfall({
+ acquisitionCost: Number(asset.acquisitionCost),
+ residualValuePercent: Number(asset.residualValuePercent),
+ usefulLifeMonths: asset.usefulLifeMonths,
+ startDate: start,
+ through: previous,
+ accumulated,
+ decimalPlaces
+ });
+ }
+ if (
+ taxEnabled &&
+ asset.taxDepreciationMethod === "Straight Line" &&
+ asset.taxUsefulLifeMonths
+ ) {
+ taxCatchUp = straightLineShortfall({
+ acquisitionCost: Number(asset.acquisitionCost),
+ residualValuePercent: Number(asset.taxResidualValuePercent ?? 0),
+ usefulLifeMonths: asset.taxUsefulLifeMonths,
+ startDate: start,
+ through: previous,
+ accumulated: accumulatedTax,
+ decimalPlaces
+ });
+ }
+ }
+
for (
let month = firstMonth;
month.toString() <= periodEnd;
@@ -773,7 +858,7 @@ export function buildDepreciationLines(
) {
const monthEnd = month.toString();
const units = usageMap.get(usageKey(asset.id, monthEnd)) ?? 0;
- const amount = calculateDepreciation(
+ const scheduled = calculateDepreciation(
{
acquisitionCost: Number(asset.acquisitionCost),
accumulatedDepreciation: accumulated,
@@ -791,6 +876,15 @@ export function buildDepreciationLines(
decimalPlaces,
{ unitsProduced: units }
);
+ // The catch-up lands on the first month only, within what is left.
+ const amount =
+ catchUp > 0
+ ? Math.min(
+ round(scheduled + catchUp, decimalPlaces),
+ depreciableRemaining(asset, accumulated, decimalPlaces)
+ )
+ : scheduled;
+ catchUp = 0;
let taxAmount: number | null = null;
if (taxEnabled) {
@@ -813,7 +907,20 @@ export function buildDepreciationLines(
);
if (taxAmount === null) {
taxAmount = amount;
+ } else if (taxCatchUp > 0) {
+ taxAmount = Math.min(
+ round(taxAmount + taxCatchUp, decimalPlaces),
+ depreciableRemaining(
+ {
+ acquisitionCost: asset.acquisitionCost,
+ residualValuePercent: asset.taxResidualValuePercent ?? 0
+ },
+ accumulatedTax,
+ decimalPlaces
+ )
+ );
}
+ taxCatchUp = 0;
}
if (amount > 0 || (taxAmount !== null && taxAmount > 0)) {
diff --git a/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetAdjustCostForm.tsx b/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetAdjustCostForm.tsx
new file mode 100644
index 0000000000..6db90458c7
--- /dev/null
+++ b/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetAdjustCostForm.tsx
@@ -0,0 +1,169 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
+ VStack
+} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useFetcher } from "react-router";
+import type { z } from "zod";
+import {
+ Account,
+ DatePicker,
+ Hidden,
+ Location,
+ Number,
+ Submit
+} from "~/components/Form";
+import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
+import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
+import { fixedAssetAdjustCostValidator } from "../../accounting.models";
+
+type FixedAssetAdjustCostFormProps = {
+ initialValues: z.infer<typeof fixedAssetAdjustCostValidator>;
+ acquisitionCost: number;
+ netBookValue: number;
+ // The transfer needs a location; asked for only when the asset has none.
+ hasLocation: boolean;
+ // Whether the adjustment posts a journal, and so needs an offset account.
+ accountingEnabled: boolean;
+ onClose: () => void;
+};
+
+const FixedAssetAdjustCostForm = ({
+ initialValues,
+ acquisitionCost,
+ netBookValue,
+ hasLocation,
+ accountingEnabled,
+ onClose
+}: FixedAssetAdjustCostFormProps) => {
+ const { t } = useLingui();
+ const permissions = usePermissions();
+ const fetcher = useFetcher();
+ const { company } = useUser();
+ const currencyFormatter = useCurrencyFormatter({
+ currency: company.baseCurrencyCode
+ });
+ const currencyDecimals = useCurrencyDecimals(company.baseCurrencyCode);
+
+ return (
+ <ModalDrawerProvider type="modal">
+ <ModalDrawer
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose?.();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ validator={fixedAssetAdjustCostValidator}
+ method="post"
+ fetcher={fetcher}
+ className="flex flex-col h-full"
+ defaultValues={initialValues}
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>
+ <Trans>Adjust Cost</Trans>
+ </ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <VStack spacing={4}>
+ <div className="w-full divide-y divide-border text-sm">
+ <DetailRow label={t`Acquisition Cost`}>
+ {currencyFormatter.format(acquisitionCost)}
+ </DetailRow>
+ <DetailRow label={t`Net Book Value`}>
+ {currencyFormatter.format(netBookValue)}
+ </DetailRow>
+ </div>
+ <p className="text-sm text-muted-foreground">
+ {accountingEnabled ? (
+ <Trans>
+ Adds cost the asset was never charged with, such as the
+ labor and material of a job that recorded none. The value
+ is booked to the asset from the account it was spent from:
+ Retained Earnings for an earlier year, or this year's
+ labor or material expense.
+ </Trans>
+ ) : (
+ <Trans>
+ Adds cost the asset was never charged with, such as the
+ labor and material of a job that recorded none.
+ </Trans>
+ )}
+ </p>
+ <Number
+ name="amount"
+ label={t`Increase`}
+ minValue={0}
+ formatOptions={INPUT_FORMAT.money(
+ company.baseCurrencyCode,
+ currencyDecimals
+ )}
+ />
+ {accountingEnabled && (
+ <Account name="offsetAccountId" label={t`Offset Account`} />
+ )}
+ {hasLocation ? (
+ <Hidden name="locationId" />
+ ) : (
+ <Location name="locationId" label={t`Location`} />
+ )}
+ <DatePicker name="transferDate" label={t`Date`} />
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ If depreciation has already run, the next run catches up the
+ months a Straight Line asset took at the old cost.
+ </Trans>
+ </p>
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={!permissions.can("update", "accounting")}>
+ <Trans>Adjust Cost</Trans>
+ </Submit>
+ <Button size="md" variant="solid" onClick={() => onClose?.()}>
+ <Trans>Cancel</Trans>
+ </Button>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
+ );
+};
+
+function DetailRow({
+ label,
+ children
+}: {
+ label: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="flex items-center justify-between py-2">
+ <span className="text-muted-foreground">{label}</span>
+ <span className="font-medium tabular-nums text-foreground">
+ {children}
+ </span>
+ </div>
+ );
+}
+
+export default FixedAssetAdjustCostForm;
diff --git a/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetCapitalizeForm.tsx b/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetCapitalizeForm.tsx
index e4336256cd..ccdcd937fe 100644
--- a/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetCapitalizeForm.tsx
+++ b/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetCapitalizeForm.tsx
@@ -18,12 +18,21 @@ import {
ModalDrawerTitle,
VStack
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
-import { LuTriangleAlert } from "react-icons/lu";
+import { LuInfo } from "react-icons/lu";
import { useFetcher } from "react-router";
import type { z } from "zod";
-import { Combobox, DatePicker, Hidden, Input, Submit } from "~/components/Form";
-import { usePermissions, useUser } from "~/hooks";
+import {
+ Account,
+ Combobox,
+ DatePicker,
+ Hidden,
+ Input,
+ Number,
+ Submit
+} from "~/components/Form";
+import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
import { fixedAssetCapitalizeValidator } from "../../accounting.models";
@@ -35,6 +44,8 @@ type FixedAssetCapitalizeFormProps = {
// The unit's carrying cost — what the transfer will book. null when it
// could not be read; the server function still decides on submit.
cost: number | null;
+ // Whether an entered cost posts a journal, and so needs an offset account.
+ accountingEnabled: boolean;
onClose: () => void;
};
@@ -44,6 +55,7 @@ const FixedAssetCapitalizeForm = ({
item,
serialNumber,
cost,
+ accountingEnabled,
onClose
}: FixedAssetCapitalizeFormProps) => {
const { t } = useLingui();
@@ -53,7 +65,13 @@ const FixedAssetCapitalizeForm = ({
const currencyFormatter = useCurrencyFormatter({
currency: company.baseCurrencyCode
});
+ const currencyDecimals = useCurrencyDecimals(company.baseCurrencyCode);
+ // A unit inventory carries at nothing — made by a job that recorded no
+ // production or material, or issued at no cost — takes the cost entered
+ // here instead.
const hasNoCost = cost !== null && cost <= 0;
+ // Entering a cost is recosting, which takes accounting update.
+ const canEnterCost = permissions.can("update", "accounting");
return (
<ModalDrawerProvider type="modal">
@@ -96,16 +114,27 @@ const FixedAssetCapitalizeForm = ({
</DetailRow>
</div>
{hasNoCost ? (
- <Alert variant="destructive">
- <LuTriangleAlert className="h-4 w-4" />
+ <Alert>
+ <LuInfo className="h-4 w-4" />
<AlertTitle>
<Trans>This unit has no cost in inventory</Trans>
</AlertTitle>
<AlertDescription>
- <Trans>
- The asset would be worth nothing. Set a unit cost on the
- item, then capitalize it.
- </Trans>
+ {!canEnterCost ? (
+ <Trans>
+ Someone who can update accounting has to enter what it
+ cost to make before it can be capitalized.
+ </Trans>
+ ) : accountingEnabled ? (
+ <Trans>
+ Enter what it cost to make. The value is booked to the
+ asset from the account it was spent from: Retained
+ Earnings for an earlier year, or this year's labor or
+ material expense.
+ </Trans>
+ ) : (
+ <Trans>Enter what it cost to make.</Trans>
+ )}
</AlertDescription>
</Alert>
) : (
@@ -116,6 +145,26 @@ const FixedAssetCapitalizeForm = ({
</Trans>
</p>
)}
+ {hasNoCost && canEnterCost && (
+ <>
+ <Number
+ name="cost"
+ label={t`Acquisition Cost`}
+ termId="fixed-asset-acquisition-cost"
+ minValue={0}
+ formatOptions={INPUT_FORMAT.money(
+ company.baseCurrencyCode,
+ currencyDecimals
+ )}
+ />
+ {accountingEnabled && (
+ <Account
+ name="offsetAccountId"
+ label={t`Offset Account`}
+ />
+ )}
+ </>
+ )}
<Combobox
name="fixedAssetClassId"
label={t`Asset Class`}
@@ -133,7 +182,8 @@ const FixedAssetCapitalizeForm = ({
<HStack>
<Submit
isDisabled={
- hasNoCost || !permissions.can("create", "accounting")
+ !permissions.can("create", "accounting") ||
+ (hasNoCost && !canEnterCost)
}
>
<Trans>Capitalize</Trans>
diff --git a/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetHeader.tsx b/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetHeader.tsx
index 496884069d..3328d8be06 100644
--- a/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetHeader.tsx
+++ b/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetHeader.tsx
@@ -16,6 +16,7 @@ import {
LuCircleCheck,
LuCircleX,
LuClipboardCheck,
+ LuCoins,
LuLink,
LuPackageCheck,
LuPencil,
@@ -136,6 +137,17 @@ const FixedAssetHeader = () => {
<Trans>Take Out of Service</Trans>
</DropdownMenuItem>
)}
+ {isActive && (
+ <DropdownMenuItem
+ disabled={!canUpdate}
+ onClick={() =>
+ navigate(path.to.fixedAssetAdjustCost(fixedAssetId))
+ }
+ >
+ <DropdownMenuIcon icon={<LuCoins />} />
+ <Trans>Adjust Cost</Trans>
+ </DropdownMenuItem>
+ )}
{canReturnToInventory && (
<DropdownMenuItem
disabled={!canCreate}
diff --git a/apps/erp/app/modules/accounting/ui/FixedAssets/index.ts b/apps/erp/app/modules/accounting/ui/FixedAssets/index.ts
index d6b6f77e4e..03ea98d248 100644
--- a/apps/erp/app/modules/accounting/ui/FixedAssets/index.ts
+++ b/apps/erp/app/modules/accounting/ui/FixedAssets/index.ts
@@ -8,6 +8,7 @@ import DepreciationRunDocuments from "./DepreciationRunDocuments";
import DepreciationRunHeader from "./DepreciationRunHeader";
import DepreciationRunStatus from "./DepreciationRunStatus";
import DepreciationRunTable from "./DepreciationRunTable";
+import FixedAssetAdjustCostForm from "./FixedAssetAdjustCostForm";
import FixedAssetAttachJobForm from "./FixedAssetAttachJobForm";
import FixedAssetCapitalizeCipForm from "./FixedAssetCapitalizeCipForm";
import FixedAssetCapitalizeForm from "./FixedAssetCapitalizeForm";
@@ -32,6 +33,7 @@ export {
DepreciationRunHeader,
DepreciationRunStatus,
DepreciationRunTable,
+ FixedAssetAdjustCostForm,
FixedAssetAttachJobForm,
FixedAssetCapitalizeCipForm,
FixedAssetCapitalizeForm,
diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.md
index 7005d04d1c..aeb809b1e4 100644
--- a/apps/erp/app/modules/inventory/AGENTS.md
+++ b/apps/erp/app/modules/inventory/AGENTS.md
@@ -63,6 +63,7 @@ pnpm exec turbo run typecheck --filter=erp # the app's package name is "erp",
- `getItemLedgerPage` / `getItemLedgerActivity` — paginated ledger history
- `getItemLedgerBalance` — `get_item_ledger_balance` RPC: on-hand right after one ledger entry, on the `quantityOnHand` definition (Rejected tracked stock counts zero). The item Activity feed fetches it ONCE for its newest loaded row; `withRunningBalance` (`ui/Inventory/ledgerFeed.ts`) derives every row's before → after from it as pages load, so paging adds no queries. Run it on raw rows, before `collapseTransferPairs`
- `insertManualInventoryAdjustment` — adjustments with tracked entity handling; wraps the `post-inventory-adjustment` server function, which also maintains cost layers and posts GL journals (5310 vs RM/FG) in one transaction when accounting is enabled
+- `getSerialUnitCosts` / `recostSerialUnit` — wrap `preview-serial-unit-costs` (each on-hand serial's carrying cost, `view: accounting`; read by the Storage Units card through `api+/items.$itemId.serial-costs.ts`) and `recost-serial-unit` (re-book ONE serial's FIFO / LIFO layer at a new cost, journal vs an offset account, `update: accounting`; route `x+/inventory+/quantities+/$itemId.recost.tsx`). See `.claude/rules/inventory-system.md` → Serial unit cost and Recost
- `correctStockMovement` — wraps the `correct-stock-movement` server function: fixes a posted `itemLedger` row by booking ONE opposite (delta) movement linked via `correctionOfItemLedgerId`, dated with the original's `postingDate` and posted into the original's accounting period (fails if Locked/Closed). The delta is derived against the movement's current effective quantity (original + prior corrections), so repeat corrections converge
- `getStorageUnit(s)` / `getStorageUnitTree` / `getStorageUnitsTreeForLocation` — storage hierarchy
- `getAvailableTrackedEntities` — calls `get_available_tracked_entities` RPC
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.ts
index 5ccb8dfc86..464b94f7e8 100644
--- a/apps/erp/app/modules/inventory/inventory.models.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.ts
@@ -174,6 +174,16 @@ export const inventoryCountLineValidator = z.object({
)
});
+// Put a cost of the user's own on one serial unit in stock (FIFO / LIFO).
+export const serialUnitRecostValidator = z.object({
+ trackedEntityId: z.string().min(1, { message: "Unit is required" }),
+ unitCost: zfd.numeric(
+ z.number().min(0, { message: "Unit cost cannot be negative" })
+ ),
+ offsetAccountId: zfd.text(z.string().optional()),
+ postingDate: z.string().min(1, { message: "Posting date is required" })
+});
+
export const inventoryAdjustmentValidator = z
.object({
itemId: z.string().min(1, { message: "Item ID is required" }),
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 1eb1d49441..97d2f965c4 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -1512,6 +1512,42 @@ export async function getShippingTermsList(
.order("name", { ascending: true });
}
+/** What each serial unit of an item on hand would leave stock at — the
+ * `preview-serial-unit-costs` server function, valued the way a shipment or
+ * a capitalization would relieve it. Keyed by tracked entity id. */
+export async function getSerialUnitCosts(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ args: {
+ companyId: string;
+ userId: string;
+ itemId: string;
+ locationId?: string | null;
+ }
+) {
+ const { companyId, userId, ...input } = args;
+ return serverFns
+ .as({ client, db, companyId, userId })
+ .invoke("preview-serial-unit-costs", input);
+}
+
+/** Recost one serial unit in stock — the `recost-serial-unit` server
+ * function: re-books the unit's layer at `unitCost` and posts the
+ * difference against the offset account. Requires accounting update. */
+export async function recostSerialUnit(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ args: ServerFnInput<"recost-serial-unit"> & {
+ companyId: string;
+ userId: string;
+ }
+) {
+ const { companyId, userId, ...input } = args;
+ return serverFns
+ .as({ client, db, companyId, userId })
+ .invoke("recost-serial-unit", input);
+}
+
// Merge >=2 same-item Available lots into ONE new entity (fresh id, summed
// quantity, earliest expiry) with genealogy back to every parent. The issue
// server fn owns the writes; see `buildBatchMergeRecords` (@carbon/utils).
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx
index eeb4957d12..acf0b3e910 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx
@@ -11,6 +11,7 @@ import {
ValidatedForm
} from "@carbon/form";
import { LabelDownloadModal } from "@carbon/printing/ui";
+import { useAction, useLoaderQuery } from "@carbon/query";
import {
Button,
Card,
@@ -18,8 +19,13 @@ import {
CardContent,
CardHeader,
CardTitle,
- Copy,
cn,
+ copyToClipboard,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
HStack,
IconButton,
InputGroup,
@@ -31,14 +37,11 @@ import {
ModalHeader,
ModalTitle,
Input as SearchInput,
- Tooltip,
- TooltipContent,
- TooltipTrigger,
toast,
useDisclosure,
VStack
} from "@carbon/react";
-import { groupBy, round } from "@carbon/utils";
+import { groupBy, INPUT_FORMAT, round } from "@carbon/utils";
import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { nanoid } from "nanoid";
@@ -48,6 +51,8 @@ import {
LuCheck,
LuChevronDown,
LuChevronRight,
+ LuCoins,
+ LuEllipsisVertical,
LuPencil,
LuPrinter,
LuQrCode,
@@ -56,18 +61,37 @@ import {
import { Link, Outlet, useFetcher } from "react-router";
import type { z } from "zod";
import { DateTime } from "~/components";
-import { Input, Location, Select, TextArea } from "~/components/Form";
+import {
+ Account,
+ Input,
+ Location,
+ Number as NumberInput,
+ Select,
+ TextArea
+} from "~/components/Form";
import ScrapReason from "~/components/Form/ScrapReason";
import StorageUnit from "~/components/Form/StorageUnit";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
-import { usePermissions, usePrinting, useQuantityFormatter } from "~/hooks";
+import {
+ useCompanyToday,
+ useCurrencyDecimals,
+ usePermissions,
+ usePrinting,
+ useQuantityFormatter,
+ useSettings,
+ useUser
+} from "~/hooks";
+import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
import type {
ItemStorageUnitQuantities,
itemTrackingTypes,
pickMethodValidator
} from "~/modules/items";
import { path } from "~/utils/path";
-import { inventoryAdjustmentValidator } from "../../inventory.models";
+import {
+ inventoryAdjustmentValidator,
+ serialUnitRecostValidator
+} from "../../inventory.models";
type InventoryStorageUnitsProps = {
pickMethod: z.infer<typeof pickMethodValidator>;
@@ -293,6 +317,41 @@ const InventoryStorageUnits = ({
// Goods at its carrying cost). The capitalize route reads the unit from the
// search params; the posting itself needs `create: accounting`.
const canCapitalize = permissions.can("create", "accounting");
+
+ // What each serial unit would leave stock at — the cost a shipment or a
+ // capitalization would relieve. Inventory value is accounting data, so it
+ // is only read for someone who can view accounting.
+ const canViewCost = isSerial && permissions.can("view", "accounting");
+ const { data: serialCosts } = useLoaderQuery<{
+ costs: Record<string, number>;
+ costingMethod: string | null;
+ retainedEarningsAccountId: string | null;
+ }>(
+ canViewCost
+ ? path.to.api.itemSerialCosts(pickMethod.itemId, locationId)
+ : null
+ );
+ const costFormatter = useCurrencyFormatter({ rate: true });
+
+ // Recosting one unit puts a number of the user's own on the books, so it
+ // takes accounting update; only a FIFO / LIFO unit carries its own layer.
+ const canRecost =
+ canViewCost &&
+ permissions.can("update", "accounting") &&
+ (serialCosts?.costingMethod === "FIFO" ||
+ serialCosts?.costingMethod === "LIFO");
+ const { accountingEnabled } = useSettings();
+ const { company } = useUser();
+ const currencyDecimals = useCurrencyDecimals(company.baseCurrencyCode);
+ const companyToday = useCompanyToday();
+ const retainedEarningsAccountId = serialCosts?.retainedEarningsAccountId;
+ const [recostItem, setRecostItem] =
+ useState<ItemStorageUnitQuantities | null>(null);
+ const recostFetcher = useAction({
+ onSuccess: () => setRecostItem(null)
+ });
+ const unitCostOf = (item: ItemStorageUnitQuantities) =>
+ item.trackedEntityId ? serialCosts?.costs[item.trackedEntityId] : undefined;
const capitalizeHref = (item: ItemStorageUnitQuantities) => {
const params = new URLSearchParams({
itemId: pickMethod.itemId,
@@ -353,6 +412,22 @@ const InventoryStorageUnits = ({
</span>
);
+ // A unit carried at nothing is the one to recost before it ships or is
+ // capitalized, so it reads amber.
+ const renderUnitCost = (item: ItemStorageUnitQuantities) => {
+ const cost = unitCostOf(item);
+ if (cost === undefined) return null;
+ return cost > 0 ? (
+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">
+ {costFormatter.format(cost)}
+ </span>
+ ) : (
+ <span className="shrink-0 text-xs text-amber-600 dark:text-amber-400">
+ <Trans>No cost</Trans>
+ </span>
+ );
+ };
+
const renderTracking = (
item: ItemStorageUnitQuantities,
expiration: string | null | undefined
@@ -367,6 +442,7 @@ const InventoryStorageUnits = ({
<Trans>Untracked</Trans>
</span>
)}
+ {renderUnitCost(item)}
{expiration && (
<span
className={cn("shrink-0 text-xs", expirationClassName(expiration))}
@@ -379,61 +455,73 @@ const InventoryStorageUnits = ({
</span>
);
+ // One trigger per row; the actions live in its menu.
const renderActions = (item: ItemStorageUnitQuantities) => (
<HStack
spacing={0}
- className="justify-end opacity-0 transition-opacity duration-150 ease-out group-hover/row:opacity-100 focus-within:opacity-100 [@media(hover:none)]:opacity-100"
+ className="justify-end opacity-0 transition-opacity duration-150 ease-out group-hover/row:opacity-100 focus-within:opacity-100 has-[[data-state=open]]:opacity-100 [@media(hover:none)]:opacity-100"
>
- {item.trackedEntityId && (
- <Copy
- icon={<LuQrCode />}
- text={item.trackedEntityId}
- withTextInTooltip
- />
- )}
- {item.trackedEntityId && (
- <IconButton
- aria-label={t`Print Label`}
- title={t`Print Label`}
- variant="ghost"
- size="sm"
- icon={<LuPrinter />}
- onClick={() => handlePrintLabel(item.trackedEntityId!)}
- />
- )}
- {/* A fixed asset is one serialized unit; a batch row is many. */}
- {item.trackedEntityId && isSerial && canCapitalize && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Link to={capitalizeHref(item)}>
- <IconButton
- aria-label={t`Capitalize as Fixed Asset`}
- variant="ghost"
- size="sm"
- icon={<LuBuilding2 />}
- />
- </Link>
- </TooltipTrigger>
- <TooltipContent>
- <Trans>Capitalize as Fixed Asset</Trans>
- </TooltipContent>
- </Tooltip>
- )}
- <IconButton
- aria-label={t`Update Quantity`}
- title={t`Update Quantity`}
- variant="ghost"
- size="sm"
- icon={<LuPencil />}
- onClick={() =>
- openAdjustmentModal(
- item.storageUnitId,
- item.trackedEntityId,
- item.readableId,
- item.quantity
- )
- }
- />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label={t`Actions`}
+ variant="ghost"
+ size="sm"
+ icon={<LuEllipsisVertical />}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {item.trackedEntityId && (
+ <DropdownMenuItem
+ onSelect={async () => {
+ // Only confirm a copy that happened.
+ if (await copyToClipboard(item.trackedEntityId!)) {
+ toast.success(t`Copied ID to clipboard`);
+ }
+ }}
+ >
+ <DropdownMenuIcon icon={<LuQrCode />} />
+ <Trans>Copy ID</Trans>
+ </DropdownMenuItem>
+ )}
+ {item.trackedEntityId && (
+ <DropdownMenuItem
+ onSelect={() => handlePrintLabel(item.trackedEntityId!)}
+ >
+ <DropdownMenuIcon icon={<LuPrinter />} />
+ <Trans>Print Label</Trans>
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem
+ onSelect={() =>
+ openAdjustmentModal(
+ item.storageUnitId,
+ item.trackedEntityId,
+ item.readableId,
+ item.quantity
+ )
+ }
+ >
+ <DropdownMenuIcon icon={<LuPencil />} />
+ <Trans>Update Quantity</Trans>
+ </DropdownMenuItem>
+ {item.trackedEntityId && canRecost && (
+ <DropdownMenuItem onSelect={() => setRecostItem(item)}>
+ <DropdownMenuIcon icon={<LuCoins />} />
+ <Trans>Recost</Trans>
+ </DropdownMenuItem>
+ )}
+ {/* A fixed asset is one serialized unit; a batch row is many. */}
+ {item.trackedEntityId && isSerial && canCapitalize && (
+ <DropdownMenuItem asChild>
+ <Link to={capitalizeHref(item)}>
+ <DropdownMenuIcon icon={<LuBuilding2 />} />
+ <Trans>Capitalize as Fixed Asset</Trans>
+ </Link>
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
</HStack>
);
@@ -595,6 +683,75 @@ const InventoryStorageUnits = ({
</div>
</CardContent>
</Card>
+ {recostItem?.trackedEntityId && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) setRecostItem(null);
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ validator={serialUnitRecostValidator}
+ action={path.to.inventoryItemRecost(pickMethod.itemId)}
+ fetcher={recostFetcher}
+ defaultValues={{
+ trackedEntityId: recostItem.trackedEntityId,
+ unitCost: unitCostOf(recostItem) ?? 0,
+ offsetAccountId: retainedEarningsAccountId ?? "",
+ postingDate: companyToday
+ }}
+ >
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Recost {recostItem.readableId ?? ""}</Trans>
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <Hidden name="trackedEntityId" />
+ <VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ {accountingEnabled ? (
+ <Trans>
+ Sets what this unit is carried at in inventory. The
+ difference is booked between inventory and the account
+ the cost was spent from: Retained Earnings for an
+ earlier year, or this year's labor or material expense.
+ </Trans>
+ ) : (
+ <Trans>
+ Sets what this unit is carried at in inventory.
+ </Trans>
+ )}
+ </p>
+ <NumberInput
+ name="unitCost"
+ label={t`Unit Cost`}
+ minValue={0}
+ formatOptions={INPUT_FORMAT.rate(
+ company.baseCurrencyCode,
+ currencyDecimals
+ )}
+ />
+ {accountingEnabled && (
+ <Account name="offsetAccountId" label={t`Offset Account`} />
+ )}
+ <DatePicker name="postingDate" label={t`Posting Date`} />
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={() => setRecostItem(null)}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <Submit>
+ <Trans>Recost</Trans>
+ </Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ )}
{adjustmentModal.isOpen && (
<Modal
open
diff --git a/apps/erp/app/modules/inventory/ui/StorageRules/RuleAssignmentsList.tsx b/apps/erp/app/modules/inventory/ui/StorageRules/RuleAssignmentsList.tsx
index 1cbd8ce08b..fe218d0374 100644
--- a/apps/erp/app/modules/inventory/ui/StorageRules/RuleAssignmentsList.tsx
+++ b/apps/erp/app/modules/inventory/ui/StorageRules/RuleAssignmentsList.tsx
@@ -277,23 +277,24 @@ export default function RuleAssignmentsList({
const isLocked = isBroadcast;
return (
<Tr key={a.ruleId}>
- <Td className="whitespace-nowrap">
- <HStack className="gap-2 items-center flex-wrap">
+ <Td className="whitespace-nowrap py-3">
+ <div className="flex flex-col items-start gap-1">
<Hyperlink to={path.to.storageRule(a.ruleId)}>
- <HStack className="gap-2 items-center">
- <LuShieldCheck className="text-muted-foreground shrink-0" />
+ <span className="flex items-center gap-2">
+ <LuShieldCheck className="size-4 shrink-0 text-muted-foreground" />
<span>{a.rule.name}</span>
- </HStack>
+ </span>
</Hyperlink>
+ {/* Indented past the icon so it sits under the name. */}
{isBroadcast && (
<Badge
variant="outline"
- className="text-[10px] uppercase tracking-wide"
+ className="ml-6 text-[10px] uppercase tracking-wide"
>
<Trans>Applies to all</Trans>
</Badge>
)}
- </HStack>
+ </div>
</Td>
<Td>
{a.rule.severity === "error" ? (
diff --git a/apps/erp/app/routes/api+/items.$itemId.serial-costs.ts b/apps/erp/app/routes/api+/items.$itemId.serial-costs.ts
new file mode 100644
index 0000000000..d43768b8c7
--- /dev/null
+++ b/apps/erp/app/routes/api+/items.$itemId.serial-costs.ts
@@ -0,0 +1,52 @@
+// 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 { requirePermissions } from "@carbon/auth/auth.server";
+import { getLogger } from "@carbon/logger";
+import { cachedClientLoader } from "@carbon/query/cache";
+import type { LoaderFunctionArgs } from "react-router";
+import { getDefaultAccounts } from "~/modules/accounting";
+import { getSerialUnitCosts } from "~/modules/inventory";
+import { getDatabaseClient } from "~/services/database.server";
+
+const logger = getLogger("erp", "item-serial-costs");
+
+// Each on-hand serial unit's inventory cost, for the item's Storage Units
+// card. Inventory value is accounting data, so it takes accounting view.
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "accounting"
+ });
+
+ const { itemId } = params;
+ if (!itemId) {
+ return { costs: {}, costingMethod: null, retainedEarningsAccountId: null };
+ }
+ const locationId = new URL(request.url).searchParams.get("locationId");
+
+ const [result, accountDefaults] = await Promise.all([
+ getSerialUnitCosts(client, getDatabaseClient(), {
+ companyId,
+ userId,
+ itemId,
+ locationId
+ }),
+ getDefaultAccounts(client, companyId)
+ ]);
+ // A recost's offset defaults to Retained Earnings, as on the asset side.
+ const retainedEarningsAccountId =
+ accountDefaults.data?.retainedEarningsAccount ?? null;
+ if (result.error) {
+ logger.error("Failed to value serial units", {
+ companyId,
+ itemId,
+ locationId,
+ error: result.error
+ });
+ return { costs: {}, costingMethod: null, retainedEarningsAccountId };
+ }
+ return { ...result.data, retainedEarningsAccountId };
+}
+
+export const clientLoader = cachedClientLoader<typeof loader>();
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 6681069ba4..6b15d5a129 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
@@ -39,7 +39,7 @@
{"name":"accounting_getAccountingPeriods","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"bd245bd0358c","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getAccountingSyncTieOut","classification":"READ","paramCount":3,"schema":"4feda8437359","response":"5483e69d7515","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getAccountingSyncTieOutCell","classification":"READ","paramCount":1,"schema":"1a84bfebf9e9","response":"a5febf12f4bd","injectAuth":"companyId","permission":"accounting:view","paginates":false},
- {"name":"accounting_getAccountLedger","classification":"READ","paramCount":6,"schema":"8ad7f551d78b","response":"0bbccf81d43d","injectAuth":"companyId","permission":"accounting:view","paginates":true},
+ {"name":"accounting_getAccountLedger","classification":"READ","paramCount":6,"schema":"8ad7f551d78b","response":"41b04015fdbb","injectAuth":"companyId","permission":"accounting:view","paginates":true},
{"name":"accounting_getAccountLedgerSummary","classification":"READ","paramCount":3,"schema":"aad65f7c3f63","response":"0a28a92b28ff","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getAccountPeriodSeries","classification":"READ","paramCount":2,"schema":"d5db2abee293","response":"2c75339d9fde","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getAccounts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"84821cb96b68","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},
@@ -88,15 +88,15 @@
{"name":"accounting_getFixedAssets","classification":"READ","paramCount":4,"schema":"98a82364580e","response":"1352052a4d0e","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},
{"name":"accounting_getFixedAssetsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0c62226f500a","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getFixedAssetsListForSale","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0c62226f500a","injectAuth":"companyId","permission":"accounting:view","paginates":false},
- {"name":"accounting_getFixedAssetTransfers","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"da9297e3e4b0","injectAuth":"companyId","permission":"accounting:view","paginates":false},
+ {"name":"accounting_getFixedAssetTransfers","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"e88320352e28","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getFixedAssetUsageLogs","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"517f4c28c365","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getFleetAssets","classification":"READ","paramCount":4,"schema":"e83739fdf2bc","response":"8735b01a7188","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},
{"name":"accounting_getGroupAccounts","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"a9a2c5be8164","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getIntercompanyBalance","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f2f76b33a3df","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getIntercompanyEliminationLines","classification":"READ","paramCount":1,"schema":"b9efe4d053a7","response":"eb31d414081e","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getIntercompanyTransactions","classification":"READ","paramCount":3,"schema":"db142abe3913","response":"394c314af3a6","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},
- {"name":"accounting_getJournalEntries","classification":"READ","paramCount":4,"schema":"85098b9cb044","response":"543dc8eb009c","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},
- {"name":"accounting_getJournalEntry","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"b45bf9949a8f","injectAuth":"companyId","permission":"accounting:view","paginates":false},
+ {"name":"accounting_getJournalEntries","classification":"READ","paramCount":4,"schema":"85098b9cb044","response":"c82a207efb63","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},
+ {"name":"accounting_getJournalEntry","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"b6bef001d645","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getJournalLineDimensions","classification":"READ","paramCount":1,"schema":"4a6413e2bb5a","response":"b731368c1d3c","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getJournalSyncCompleteness","classification":"READ","paramCount":3,"schema":"6eb0a36bbd4b","response":"58d45b19b00c","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getLeaseNetInvestment","classification":"READ","paramCount":1,"schema":"c860433efc00","response":"93c82b571cea","injectAuth":"companyId","permission":"accounting:view","paginates":false},
diff --git a/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.adjust-cost.tsx b/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.adjust-cost.tsx
new file mode 100644
index 0000000000..4abd5aa9f0
--- /dev/null
+++ b/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.adjust-cost.tsx
@@ -0,0 +1,153 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { assertIsPost, error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { datetime, getErrorMessage, redirect } from "@carbon/utils";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { useLoaderData, useNavigate } from "react-router";
+import {
+ fixedAssetAdjustCostValidator,
+ getDefaultAccounts,
+ getFixedAsset,
+ invokeAssetTransfer
+} from "~/modules/accounting";
+import { FixedAssetAdjustCostForm } from "~/modules/accounting/ui/FixedAssets";
+import { getCompanySettings } from "~/modules/settings";
+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
+import { getDatabaseClient } from "~/services/database.server";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "accounting"
+ });
+
+ const { fixedAssetId } = params;
+ if (!fixedAssetId) throw notFound("fixedAssetId not found");
+
+ const [asset, companySettings, accountDefaults, timeZone] = await Promise.all(
+ [
+ getFixedAsset(client, fixedAssetId, companyId),
+ getCompanySettings(client, companyId),
+ getDefaultAccounts(client, companyId),
+ getCompanyTimeZone(client, companyId)
+ ]
+ );
+ if (asset.error) {
+ throw redirect(
+ path.to.fixedAssets,
+ await flash(request, error(asset.error, "Failed to get fixed asset"))
+ );
+ }
+
+ if (
+ asset.data.status !== "Active" &&
+ asset.data.status !== "Fully Depreciated"
+ ) {
+ throw redirect(
+ path.to.fixedAsset(fixedAssetId),
+ await flash(
+ request,
+ error(
+ null,
+ "Only an Active or Fully Depreciated asset's cost can be adjusted"
+ )
+ )
+ );
+ }
+
+ const accountingEnabled =
+ (companySettings.data as { accountingEnabled?: boolean } | null)
+ ?.accountingEnabled ?? false;
+ const acquisitionCost = Number(asset.data.acquisitionCost);
+
+ return {
+ acquisitionCost,
+ netBookValue: acquisitionCost - Number(asset.data.accumulatedDepreciation),
+ hasLocation: Boolean(asset.data.locationId),
+ accountingEnabled,
+ initialValues: {
+ amount: 0,
+ // Retained Earnings unless the accountant picks the account the cost
+ // was spent from this year.
+ offsetAccountId: accountDefaults.data?.retainedEarningsAccount ?? "",
+ locationId: asset.data.locationId ?? "",
+ transferDate: datetime.today(timeZone).toString()
+ }
+ };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ // Recosting an asset puts a number of the user's own on the books.
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "accounting"
+ });
+
+ const { fixedAssetId } = params;
+ if (!fixedAssetId) throw notFound("fixedAssetId not found");
+
+ const formData = await request.formData();
+ const validation = await validator(fixedAssetAdjustCostValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { offsetAccountId, ...adjustment } = validation.data;
+
+ const result = await invokeAssetTransfer(client, getDatabaseClient(), {
+ type: "adjustCost",
+ companyId,
+ userId,
+ fixedAssetId,
+ ...adjustment,
+ offsetAccountId: offsetAccountId || null
+ });
+
+ if (result.error) {
+ throw redirect(
+ path.to.fixedAsset(fixedAssetId),
+ await flash(
+ request,
+ error(
+ result.error,
+ getErrorMessage(result.error, "Failed to adjust the asset's cost")
+ )
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.fixedAsset(fixedAssetId),
+ await flash(request, success("Asset cost adjusted"))
+ );
+}
+
+export default function AdjustFixedAssetCostRoute() {
+ const {
+ acquisitionCost,
+ netBookValue,
+ hasLocation,
+ accountingEnabled,
+ initialValues
+ } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ return (
+ <FixedAssetAdjustCostForm
+ initialValues={initialValues}
+ acquisitionCost={acquisitionCost}
+ netBookValue={netBookValue}
+ hasLocation={hasLocation}
+ accountingEnabled={accountingEnabled}
+ onClose={() => navigate(-1)}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/fixed-asset+/capitalize.tsx b/apps/erp/app/routes/x+/fixed-asset+/capitalize.tsx
index 6d4bac4066..68fb20332f 100644
--- a/apps/erp/app/routes/x+/fixed-asset+/capitalize.tsx
+++ b/apps/erp/app/routes/x+/fixed-asset+/capitalize.tsx
@@ -13,11 +13,13 @@ import { data, useLoaderData, useNavigate } from "react-router";
import {
fixedAssetCapitalizeValidator,
getCapitalizationCost,
+ getDefaultAccounts,
invokeAssetTransfer
} from "~/modules/accounting";
import { FixedAssetCapitalizeForm } from "~/modules/accounting/ui/FixedAssets";
import { getTrackedEntity } from "~/modules/inventory";
import { getItem } from "~/modules/items";
+import { getCompanySettings } from "~/modules/settings";
import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { getDatabaseClient } from "~/services/database.server";
import { path } from "~/utils/path";
@@ -52,26 +54,35 @@ export async function loader({ request }: LoaderFunctionArgs) {
);
}
- const [entity, item, capitalization, assetClasses, timeZone] =
- await Promise.all([
- getTrackedEntity(client, trackedEntityId),
- getItem(client, itemId),
- getCapitalizationCost(client, getDatabaseClient(), {
- companyId,
- userId,
- trackedEntityId
- }),
- // A CIP class is a holding account, never a capitalization target.
- // `getFixedAssetClassesList` does not select `isConstructionInProgress`,
- // so the filter is applied here (same select as `x+/job+/new.tsx`).
- client
- .from("fixedAssetClass")
- .select("id, name")
- .eq("companyId", companyId)
- .eq("isConstructionInProgress", false)
- .order("name"),
- getCompanyTimeZone(client, companyId)
- ]);
+ const [
+ entity,
+ item,
+ capitalization,
+ assetClasses,
+ timeZone,
+ companySettings,
+ accountDefaults
+ ] = await Promise.all([
+ getTrackedEntity(client, trackedEntityId),
+ getItem(client, itemId),
+ getCapitalizationCost(client, getDatabaseClient(), {
+ companyId,
+ userId,
+ trackedEntityId
+ }),
+ // A CIP class is a holding account, never a capitalization target.
+ // `getFixedAssetClassesList` does not select `isConstructionInProgress`,
+ // so the filter is applied here (same select as `x+/job+/new.tsx`).
+ client
+ .from("fixedAssetClass")
+ .select("id, name")
+ .eq("companyId", companyId)
+ .eq("isConstructionInProgress", false)
+ .order("name"),
+ getCompanyTimeZone(client, companyId),
+ getCompanySettings(client, companyId),
+ getDefaultAccounts(client, companyId)
+ ]);
if (
entity.error ||
@@ -99,6 +110,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
});
}
+ const accountingEnabled =
+ (companySettings.data as { accountingEnabled?: boolean } | null)
+ ?.accountingEnabled ?? false;
+
const classes = assetClasses.data ?? [];
const rentalFleetClassId =
classes.find((c) => c.name === RENTAL_FLEET_CLASS_NAME)?.id ?? "";
@@ -112,8 +127,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
locationId,
storageUnitId: storageUnitId ?? "",
transferDate: datetime.today(timeZone).toString(),
- name: [item.data.name, serialNumber].filter(Boolean).join(" ")
+ name: [item.data.name, serialNumber].filter(Boolean).join(" "),
+ // Used only when the unit carries no cost: the value is booked from
+ // Retained Earnings unless the accountant picks the account it was
+ // spent from this year.
+ offsetAccountId: accountDefaults.data?.retainedEarningsAccount ?? ""
},
+ accountingEnabled,
assetClasses: classes,
item: {
readableId: item.data.readableIdWithRevision ?? item.data.readableId,
@@ -141,7 +161,8 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const { storageUnitId, name, ...transfer } = validation.data;
+ const { storageUnitId, name, cost, offsetAccountId, ...transfer } =
+ validation.data;
const result = await invokeAssetTransfer(client, getDatabaseClient(), {
type: "capitalize",
@@ -149,7 +170,9 @@ export async function action({ request }: ActionFunctionArgs) {
userId,
...transfer,
storageUnitId: storageUnitId || null,
- name: name || null
+ name: name || null,
+ cost: cost ?? null,
+ offsetAccountId: cost ? offsetAccountId || null : null
});
if (result.error) {
@@ -181,8 +204,14 @@ export async function action({ request }: ActionFunctionArgs) {
}
export default function CapitalizeFixedAssetRoute() {
- const { initialValues, assetClasses, item, serialNumber, cost } =
- useLoaderData<typeof loader>();
+ const {
+ initialValues,
+ assetClasses,
+ item,
+ serialNumber,
+ cost,
+ accountingEnabled
+ } = useLoaderData<typeof loader>();
const navigate = useNavigate();
return (
@@ -192,6 +221,7 @@ export default function CapitalizeFixedAssetRoute() {
item={item}
serialNumber={serialNumber}
cost={cost}
+ accountingEnabled={accountingEnabled}
onClose={() => navigate(-1)}
/>
);
diff --git a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.recost.tsx b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.recost.tsx
new file mode 100644
index 0000000000..9af2404ffa
--- /dev/null
+++ b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.recost.tsx
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
+import { getErrorMessage } from "@carbon/utils";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ recostSerialUnit,
+ serialUnitRecostValidator
+} from "~/modules/inventory";
+import { getDatabaseClient } from "~/services/database.server";
+
+const logger = getLogger("erp", "inventory-recost");
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ // Recosting puts a number of the user's own on the books.
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "accounting"
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const formData = await request.formData();
+ const validation = await validator(serialUnitRecostValidator).validate(
+ formData
+ );
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { offsetAccountId, ...recost } = validation.data;
+ const result = await recostSerialUnit(client, getDatabaseClient(), {
+ companyId,
+ userId,
+ ...recost,
+ offsetAccountId: offsetAccountId || null
+ });
+
+ if (result.error) {
+ logger.error("Failed to recost the unit", {
+ companyId,
+ itemId,
+ trackedEntityId: recost.trackedEntityId,
+ error: result.error
+ });
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(result.error, getErrorMessage(result.error, "Failed to recost"))
+ )
+ );
+ }
+
+ return data(
+ { success: true },
+ await flash(request, success("Unit recosted"))
+ );
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 2bf6529a89..832710cf35 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -166,6 +166,10 @@ export const path = {
generatePath(`${api}/items/quantities/${locationId}`),
itemRecipeProcesses: (itemId: string) =>
generatePath(`${api}/items/${itemId}/recipe-processes`),
+ itemSerialCosts: (itemId: string, locationId: string) =>
+ `${generatePath(`${api}/items/${itemId}/serial-costs`)}?${new URLSearchParams(
+ { locationId }
+ )}`,
jiraCreateIssue: `${api}/integrations/jira/issue/create`,
jiraLinkExistingIssue: `${api}/integrations/jira/issue/link`,
jiraSyncNotes: `${api}/integrations/jira/issue/sync-notes`,
@@ -1308,6 +1312,8 @@ export const path = {
},
fiscalYears: `${x}/accounting/years`,
fixedAsset: (id: string) => generatePath(`${x}/fixed-asset/${id}`),
+ fixedAssetAdjustCost: (id: string) =>
+ generatePath(`${x}/fixed-asset/${id}/adjust-cost`),
fixedAssetAttachJob: (id: string) =>
generatePath(`${x}/fixed-asset/${id}/attach-job`),
fixedAssetCapitalize: `${x}/fixed-asset/capitalize`,
@@ -1395,6 +1401,8 @@ export const path = {
generatePath(`${x}/inventory/quantities/${id}/activity`),
inventoryItemAdjustment: (id: string) =>
generatePath(`${x}/inventory/quantities/${id}/adjustment`),
+ inventoryItemRecost: (id: string) =>
+ generatePath(`${x}/inventory/quantities/${id}/recost`),
inventoryRoot: `${x}/inventory`,
inventorySettings: `${x}/settings/inventory`,
inventoryValuation: `${x}/reports/inventory-valuation`,
diff --git a/docs/content/docs/reference/fixed-assets.mdx b/docs/content/docs/reference/fixed-assets.mdx
index 00d03b0502..8a3ea64853 100644
--- a/docs/content/docs/reference/fixed-assets.mdx
+++ b/docs/content/docs/reference/fixed-assets.mdx
@@ -21,7 +21,7 @@ An asset comes onto the books four ways. Registering and buying start from a **D
- **Register** one you already own: supply its acquisition cost and depreciation start date, and it moves to **Active**. No cash moves; with accounting enabled the entry offsets equity, since you're recording something you already have.
- **Buy** one through purchasing: a <Term id="purchase-order">purchase-order</Term> line of type *Fixed Asset* that, when the receipt posts, debits the asset account, **adds** the cost to the asset, and flips it to **Active**. A purchase invoice with no receipt does the same. The asset page's **"Purchase"** action drafts the purchase order for you, and it is offered while the asset is Draft.
- **Build** one on a job: set the job's **"Complete To"** to **"Fixed Asset Class"** and choose the class. When the job completes, each finished unit becomes its own asset priced at the <Term>WIP</Term> cost it absorbed, and the unit never enters stock. This is <Term id="make-to-asset">Make to Asset</Term>.
-- **Capitalize** a unit already in stock: on the item's inventory page, the storage-unit row action **"Capitalize as Fixed Asset"** moves one <Term id="serial">serialized</Term> unit out of stock at its carrying cost and creates the asset, or fills a Draft one, as **Active**. The form shows that cost before you confirm. The serial number travels with it. A unit with no cost in inventory can't be capitalized: give the item a unit cost first.
+- **Capitalize** a unit already in stock: on the item's inventory page, the storage-unit row action **"Capitalize as Fixed Asset"** moves one <Term id="serial">serialized</Term> unit out of stock at its carrying cost and creates the asset, or fills a Draft one, as **Active**. The form shows that cost before you confirm. The serial number travels with it. A unit inventory carries at no cost, such as one a job completed with no production or material recorded, or one issued into stock at no cost, takes the **Acquisition Cost** you enter instead. With accounting enabled you also choose the **Offset Account** the value was spent from (Retained Earnings by default). Entering a cost takes permission to update accounting. To carry the unit at that cost in inventory first, use **Recost** on its storage-unit row.
<Callout type="note" title="A job that builds assets has two rules">
A job that completes to a fixed asset class needs a serialized item, so every finished unit maps to one numbered asset that the fleet can rent, return and capitalize. And it cannot be linked to a sales order line, because that job is a sale. Carbon refuses the job when you save it, and again at release.
@@ -56,6 +56,12 @@ The seeded **<Term id="rental-fleet">Rental Fleet</Term>** class is the default
<Screenshot label="Fleet register listing assets with derived Available and In Maintenance statuses" caption="The fleet register. Status is derived from the asset's own state, never stored." />
+## Adjusting cost
+
+An Active or Fully Depreciated asset that came onto the books for less than it cost, such as a unit a job built with no labor or material recorded, takes the rest through **"Adjust Cost"** in the asset's menu. Enter the increase and, with accounting enabled, the **Offset Account** it was spent from: Retained Earnings (the default) for an earlier year, or this year's labor or material expense account. Carbon debits the class's asset account, credits the offset account, raises the acquisition cost and records a **Cost Adjustment** transfer on the asset. A Fully Depreciated asset with value above its residual again returns to **Active**. Cost can only be raised here, and adjusting it takes permission to update accounting.
+
+If depreciation already ran at the old cost, the next run catches up a straight-line asset: its first month carries the depreciation the earlier months missed, so the asset still finishes on its original schedule. Declining balance and MACRS correct themselves, since both depreciate what is left over the life that is left; units of production does not catch up.
+
## Depreciating
<Term id="depreciation">Depreciation</Term> runs as a **monthly batch you trigger**. There's no background poster. You create a run for a period, Carbon pulls every Active asset and computes each charge, you review it as a draft, then post: debit depreciation expense, credit accumulated depreciation. An asset under construction is not Active, so it is skipped until it is capitalized; a fleet unit out of service is still Active, so it keeps depreciating. Carbon keeps a separate **tax** book too, including <Term>MACRS</Term>, when tax depreciation is enabled. When an asset's net book value reaches its residual, posting flips it to **Fully Depreciated**.
@@ -131,6 +137,18 @@ Return to Inventory needs `fixedAsset.itemId`, status Active or Fully Depreciate
### "Asset … is on rent on rental agreement …; return it from the agreement first" / "Asset … is reserved on rental agreement …; return it from the agreement first"
Return to Inventory refuses a unit on a live rental agreement line (Pending or On Rent). Return the unit on the agreement, or cancel the agreement if it was never delivered.
+### "… has no cost in inventory, so the asset would be worth nothing"
+The unit is carried at zero and no cost was entered. Enter its **Acquisition Cost** on the Capitalize form, or give the item a unit cost first.
+
+### "… is carried in inventory at a cost, so it is capitalized at that cost"
+A cost was entered for a unit that inventory already values. The transfer moves the value inventory holds; capitalize it without a cost, then use **Adjust Cost** on the asset for anything more.
+
+### "Choose the account the cost was booked to when it was spent" / "The offset account must be an active posting account"
+With accounting enabled, an entered cost or a cost adjustment needs an active, non-group account to credit.
+
+### "… only an Active or Fully Depreciated asset's cost can be adjusted"
+Adjust Cost is offered for Active and Fully Depreciated assets. Register a Draft asset instead; a disposed asset is off the books.
+
### "Only an Available unit can be capitalized" / "Choose a serialized unit from the item's inventory to capitalize"
Capitalize as Fixed Asset needs an Available serialized unit with on-hand at the chosen location; the capitalize route is reached from the item's storage-unit row with `itemId`, `trackedEntityId`, `locationId` and `storageUnitId` in the URL.
@@ -151,5 +169,5 @@ Asset postings land in an accounting period like everything else. "Accounting pe
## Internals
Construction in progress (a CIP class, `Under Construction`, Attach Job, Capitalize, Complete To → Asset Under Construction) is built but HIDDEN from the app until it returns with projects: `CONSTRUCTION_IN_PROGRESS_ENABLED = false` (`accounting.models.ts`) keeps CIP classes out of every class list and picker and hides the actions, the CIP cost card and the status filters. The engines, schema and error messages below are live, so treat a CIP asset as unreachable from the UI rather than impossible.
-Tables: `fixedAssetTransfer` (sequence `FAT`; `type` Capitalization / Return to Inventory; `sourceType` Inventory / Job / Construction in Progress), `fixedAssetCipCost` (append-only; `sourceType` Purchase Invoice / Receipt / Job / Manual), view `fleetAssets` (derived `fleetStatus`; since the rental migration it joins the live `rentalAgreementLine` for Reserved / On Rent and exposes `rentalAgreementId`, `customerId`, `customerLocationId`). Serial costing: a layer `bookAdjustment` writes for a serial unit carries `costLedger.trackedEntityId`, and `calculateCOGS` relieves the leaving unit's own layer first (`shared/cost-layer-order.ts`), so Return to Inventory's NBV layer is what that serial later costs under FIFO / LIFO; Standard and Average use the item's current cost. Columns: `fixedAsset.itemId`, `trackedEntityId`, `workCenterId`, `outOfServiceSince`, `outOfServiceReason`; `fixedAssetClass.isConstructionInProgress`; `job.fixedAssetClassId` / `job.fixedAssetId`. Server function `post-asset-transfer` (`capitalize`, `return`, `attachJob`, `capitalizeCip`); journal source type `Asset Transfer`; the job branch lives in `complete_job_to_inventory`. Routes: `/x/accounting/fleet`, `/x/fixed-asset/capitalize`, `/x/fixed-asset/:id/capitalize`, `/x/fixed-asset/:id/return-to-inventory`, `/x/fixed-asset/:id/attach-job`, `/x/fixed-asset/:id/out-of-service`. Seeded accounts 1370 Rental Fleet, 1380 Accumulated Depreciation – Rental Fleet, 1390 Construction in Progress; classes Rental Fleet and Construction in Progress.
+Tables: `fixedAssetTransfer` (sequence `FAT`; `type` Capitalization / Return to Inventory / Cost Adjustment; `sourceType` Inventory / Job / Construction in Progress / Manual), `fixedAssetCipCost` (append-only; `sourceType` Purchase Invoice / Receipt / Job / Manual), view `fleetAssets` (derived `fleetStatus`; since the rental migration it joins the live `rentalAgreementLine` for Reserved / On Rent and exposes `rentalAgreementId`, `customerId`, `customerLocationId`). Serial costing: a layer `bookAdjustment` writes for a serial unit carries `costLedger.trackedEntityId`, and `calculateCOGS` relieves the leaving unit's own layer first (`shared/cost-layer-order.ts`), so Return to Inventory's NBV layer is what that serial later costs under FIFO / LIFO; Standard and Average use the item's current cost. Columns: `fixedAsset.itemId`, `trackedEntityId`, `workCenterId`, `outOfServiceSince`, `outOfServiceReason`; `fixedAssetClass.isConstructionInProgress`; `job.fixedAssetClassId` / `job.fixedAssetId`. Server function `post-asset-transfer` (`capitalize`, `return`, `attachJob`, `capitalizeCip`, `adjustCost`); journal source type `Asset Transfer`; the job branch lives in `complete_job_to_inventory`. Routes: `/x/accounting/fleet`, `/x/fixed-asset/capitalize`, `/x/fixed-asset/:id/capitalize`, `/x/fixed-asset/:id/return-to-inventory`, `/x/fixed-asset/:id/adjust-cost`, `/x/fixed-asset/:id/attach-job`, `/x/fixed-asset/:id/out-of-service`. Seeded accounts 1370 Rental Fleet, 1380 Accumulated Depreciation – Rental Fleet, 1390 Construction in Progress; classes Rental Fleet and Construction in Progress.
</AgentContext>
diff --git a/docs/content/docs/reference/inventory.mdx b/docs/content/docs/reference/inventory.mdx
index 82f7bfc1e1..3f399e27d7 100644
--- a/docs/content/docs/reference/inventory.mdx
+++ b/docs/content/docs/reference/inventory.mdx
@@ -42,6 +42,12 @@ The ledger is append-only — a posted movement is never edited or deleted. To f
Inventory value is on-hand quantity multiplied by item unit cost, aggregated by item and location. The Valuation report groups by location or item. Its **Tie-Out** panel compares subledger value with GL inventory balances. If they differ, **Reconcile** creates a draft adjusting journal for review and posting.
+### Serial unit cost
+
+On an item's **Inventory** tab, each serialized unit in **Storage Units** shows what it is carried at: the cost a shipment, a scrap or a capitalization would take out of inventory for it. A unit with its own cost layer shows that cost; any other unit shows the next layer in the item's FIFO or LIFO order. A unit carried at nothing reads **No cost**. Only users who can view accounting see these costs.
+
+To give one unit a cost of its own, for example a unit a job completed with no production or material recorded, use the row's **Recost** action. You need permission to update accounting, and the item must use FIFO or LIFO costing, since a Standard or Average item carries every unit at the item's one cost. Enter the **Unit Cost** and, with accounting enabled, the **Offset Account** the cost was spent from (Retained Earnings by default). Carbon takes the unit off the layer it was on and books it on a layer of its own at the new cost; the difference posts between the inventory account and the offset account. Nothing moves, so the unit's quantity and location are unchanged.
+
## Related
<Cards>
@@ -59,6 +65,12 @@ Inventory value is on-hand quantity multiplied by item unit cost, aggregated by
### "Insufficient quantity for negative adjustment"
The decrease (or *Set Quantity* reduction) exceeds what's on hand in that storage unit. Manual adjustments are the one movement guarded against overdraw. Check on-hand for the exact item/location/storage unit (and lot, if tracked) and adjust by no more than that.
+### "… uses Average costing, so every unit carries the item's cost; one unit cannot have its own"
+Recost works on FIFO and LIFO items only. Change the item's cost on its **Costing** tab instead.
+
+### "… must have exactly one unit on hand to be recosted" / "… is already carried at that cost"
+The unit has left stock, or the entered cost equals what it already carries.
+
### "Serial number not found"
The serial or batch number entered for a negative adjustment doesn't exist in the selected storage unit. Verify the number and the storage unit — the stock may sit in a different bin.
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 9d83f8195c..59290fbbe8 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -120359,13 +120359,13 @@ export default {
type: "string"
},
type: {
- enum: ["Capitalization", "Return to Inventory"],
+ enum: ["Capitalization", "Return to Inventory", "Cost Adjustment"],
format: 'public."fixedAssetTransferType"',
type: "string"
},
sourceType: {
default: "Inventory",
- enum: ["Inventory", "Job", "Construction in Progress"],
+ enum: ["Inventory", "Job", "Construction in Progress", "Manual"],
format: 'public."fixedAssetTransferSourceType"',
type: "string"
},
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 984387dae7..7e82fffea0 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -92442,7 +92442,11 @@ export type Database = {
| "Inventory"
| "Job"
| "Construction in Progress"
- fixedAssetTransferType: "Capitalization" | "Return to Inventory"
+ | "Manual"
+ fixedAssetTransferType:
+ | "Capitalization"
+ | "Return to Inventory"
+ | "Cost Adjustment"
fulfillmentType: "Inventory" | "Job"
gaugeCalibrationStatus:
| "Pending"
@@ -93933,8 +93937,13 @@ export const Constants = {
"Inventory",
"Job",
"Construction in Progress",
+ "Manual",
+ ],
+ fixedAssetTransferType: [
+ "Capitalization",
+ "Return to Inventory",
+ "Cost Adjustment",
],
- fixedAssetTransferType: ["Capitalization", "Return to Inventory"],
fulfillmentType: ["Inventory", "Job"],
gaugeCalibrationStatus: [
"Pending",
diff --git a/packages/database/supabase/migrations/20261008163615_fixed-asset-cost-adjustment.sql b/packages/database/supabase/migrations/20261008163615_fixed-asset-cost-adjustment.sql
new file mode 100644
index 0000000000..5b2cf5b6ae
--- /dev/null
+++ b/packages/database/supabase/migrations/20261008163615_fixed-asset-cost-adjustment.sql
@@ -0,0 +1,7 @@
+-- A fixed asset's cost can be raised after it was capitalized: a unit made by
+-- a job that recorded no production or material, or issued into stock at no
+-- cost, enters the register at zero. `post-asset-transfer` `adjustCost` books
+-- the value from an offset account the accountant chooses and records it as a
+-- 'Cost Adjustment' transfer with source 'Manual'.
+ALTER TYPE "fixedAssetTransferType" ADD VALUE IF NOT EXISTS 'Cost Adjustment';
+ALTER TYPE "fixedAssetTransferSourceType" ADD VALUE IF NOT EXISTS 'Manual';
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index 7b568f4b1a..88988a7bec 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20261007171726",
+ "schemaVersion": "20261008163615",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-10-07T18:06:45.508Z",
+ "exportedAt": "2026-10-08T18:09:13.590Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index f15be6167e..684306b028 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -1986,6 +1986,15 @@ msgstr "Adresszeile 1"
msgid "Address line2"
msgstr "Adresszeile 2"
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+msgstr "Addiert Kosten hinzu, mit denen die Anlage nie belastet wurde, wie das Personal und das Material eines Fertigungsauftrags, das nichts verzeichnet hat."
+
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Addiert Kosten hinzu, mit denen die Anlage nie belastet wurde, wie das Personal und das Material eines Fertigungsauftrags, das nichts verzeichnet hat. Der Wert wird der Anlage vom Konto verbucht, auf dem es ausgegeben wurde: Gewinnvortrag für ein früheres Jahr oder der Personal- oder Materialaufwand dieses Jahres."
+
+msgid "Adjust Cost"
+msgstr "Kosten anpassen"
+
msgid "Adjustment"
msgstr "Korrektur"
@@ -5163,6 +5172,9 @@ msgstr "Wird konvertiert …"
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Wandelt die Einkaufseinheit eines Lieferanten in Ihre Bestandseinheit auf einer Bestellung, einem Wareneingang oder einer Rechnungsposition um – Einkauf in Kartons à 12, Bestand in Einzelstücken."
+msgid "Copied ID to clipboard"
+msgstr "ID in die Zwischenablage kopiert"
+
msgid "Copied link to clipboard"
msgstr "Link in die Zwischenablage kopiert"
@@ -8312,6 +8324,12 @@ msgstr "Geben Sie die Onshape URL, Client-ID und Client Secret Ihrer privaten OA
msgid "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
msgstr "Geben Sie die Menge ein, die diese Bewegung hätte sein sollen. Eine Gegenbewegung für die Differenz wird neben dem Original in dessen Zeitraum verbucht."
+msgid "Enter what it cost to make."
+msgstr "Geben Sie ein, was die Herstellung gekostet hat."
+
+msgid "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Geben Sie ein, was die Herstellung gekostet hat. Der Wert wird der Anlage vom Konto verbucht, auf dem es ausgegeben wurde: Gewinnvortrag für ein früheres Jahr oder der Personal- oder Materialaufwand dieses Jahres."
+
msgid "Entered At Receipt"
msgstr "Bei Wareneingang erfasst"
@@ -10271,6 +10289,9 @@ msgstr "IDs und Beschreibungen werden für Rohstoffe generiert."
msgid "If"
msgstr "Wenn"
+msgid "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+msgstr "Wenn die Abschreibung bereits durchgelaufen ist, holt der nächste Durchlauf die Monate nach, in denen eine lineare Anlage zum alten Kostensatz abgeschrieben wurde."
+
msgid "If it can't wait for the next call, the leads on both sides decide."
msgstr "Wenn es nicht bis zum nächsten Anruf warten kann, entscheiden die Leiter auf beiden Seiten."
@@ -13229,6 +13250,9 @@ msgstr "Keine Bedingung darf zutreffen"
msgid "No conversion is required"
msgstr "Keine Umrechnung erforderlich"
+msgid "No cost"
+msgstr "Keine Kosten"
+
msgid "No cost has been recorded against this asset yet."
msgstr "Gegen diesen Vermögenswert wurden bisher keine Kosten verbucht."
@@ -13946,6 +13970,9 @@ msgstr "Aus — außerhalb der Synchronisierung behandelt"
msgid "Off — released revisions stay editable"
msgstr "Aus — ausgegebene Revisionen bleiben bearbeitbar"
+msgid "Offset Account"
+msgstr "Gegenkonto"
+
msgid "ok"
msgstr "ok"
@@ -16550,6 +16577,13 @@ msgstr "Aufzeichnungen"
msgid "Records and posted journals are being sent to and received from this provider."
msgstr "Datensätze und gebuchte Buchungssätze werden von diesem Anbieter gesendet und empfangen."
+msgid "Recost"
+msgstr "Neu bewerten"
+
+#. placeholder {0}: recostItem.readableId ?? ""
+msgid "Recost {0}"
+msgstr "Neu bewerten {0}"
+
msgid "Recovery Period"
msgstr "Registrieren"
@@ -18709,6 +18743,12 @@ msgstr "Version {0} als aktive Version festlegen?"
msgid "Set your default location in profile settings to pick a storage unit."
msgstr "Legen Sie Ihren Standardort in den Profileinstellungen fest, um eine Lagereinheit auszuwählen."
+msgid "Sets what this unit is carried at in inventory."
+msgstr "Bestimmt den Buchwert dieser Einheit im Lager."
+
+msgid "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Bestimmt den Buchwert dieser Einheit im Lager. Die Differenz wird zwischen dem Bestand und dem Konto verbucht, auf dem die Kosten ausgegeben wurden: Gewinnvortrag für ein früheres Jahr oder der Personal- oder Materialaufwand dieses Jahres."
+
msgid "Settings"
msgstr "Einstellungen"
@@ -19205,6 +19245,9 @@ msgstr "Einige Datensätze werden nicht zurückkommen. Geben Sie <0>{CONFIRM_WOR
msgid "Some Shifts"
msgstr "Einige Schichten"
+msgid "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+msgstr "Jemand mit Berechtigung zur Aktualisierung der Buchhaltung muss eingeben, was die Herstellung gekostet hat, bevor es aktiviert werden kann."
+
msgid "Something went wrong. Please try again."
msgstr "Etwas ist schief gelaufen. Bitte versuchen Sie es erneut."
@@ -20328,9 +20371,6 @@ msgstr "Der unveränderliche Datensatz jeder Bestandsbewegung; der verfügbare B
msgid "The asset moves into its in-service class and starts depreciating from the in-service date."
msgstr "Der Vermögenswert wechselt in seine Betriebsklasse und wird ab dem Inbetriebnahmedatum abgeschrieben."
-msgid "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-msgstr "Das Anlagevermögen hätte keinen Wert. Legen Sie die Einheitskosten für den Artikel fest, und aktivieren Sie ihn."
-
msgid "The authorization was refused in Onshape. Save the integration settings to try again."
msgstr "Die Autorisierung wurde in Onshape verweigert. Speichern Sie die Integrationseinstellungen, um es erneut zu versuchen."
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 7e89028d01..e09f9d6872 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -1986,6 +1986,15 @@ msgstr "Address line1"
msgid "Address line2"
msgstr "Address line2"
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+msgstr "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+
+msgid "Adjust Cost"
+msgstr "Adjust Cost"
+
msgid "Adjustment"
msgstr "Adjustment"
@@ -5163,6 +5172,9 @@ msgstr "Converting…"
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
+msgid "Copied ID to clipboard"
+msgstr "Copied ID to clipboard"
+
msgid "Copied link to clipboard"
msgstr "Copied link to clipboard"
@@ -8312,6 +8324,12 @@ msgstr "Enter the Onshape URL, client ID and client secret of your private OAuth
msgid "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
msgstr "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
+msgid "Enter what it cost to make."
+msgstr "Enter what it cost to make."
+
+msgid "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+
msgid "Entered At Receipt"
msgstr "Entered At Receipt"
@@ -10271,6 +10289,9 @@ msgstr "IDs and descriptions are generated for raw materials."
msgid "If"
msgstr "If"
+msgid "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+msgstr "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+
msgid "If it can't wait for the next call, the leads on both sides decide."
msgstr "If it can't wait for the next call, the leads on both sides decide."
@@ -13229,6 +13250,9 @@ msgstr "No condition may match"
msgid "No conversion is required"
msgstr "No conversion is required"
+msgid "No cost"
+msgstr "No cost"
+
msgid "No cost has been recorded against this asset yet."
msgstr "No cost has been recorded against this asset yet."
@@ -13946,6 +13970,9 @@ msgstr "Off — handled outside the sync"
msgid "Off — released revisions stay editable"
msgstr "Off — released revisions stay editable"
+msgid "Offset Account"
+msgstr "Offset Account"
+
msgid "ok"
msgstr "ok"
@@ -16550,6 +16577,13 @@ msgstr "Records"
msgid "Records and posted journals are being sent to and received from this provider."
msgstr "Records and posted journals are being sent to and received from this provider."
+msgid "Recost"
+msgstr "Recost"
+
+#. placeholder {0}: recostItem.readableId ?? ""
+msgid "Recost {0}"
+msgstr "Recost {0}"
+
msgid "Recovery Period"
msgstr "Recovery Period"
@@ -18709,6 +18743,12 @@ msgstr "Set Version {0} as Active Version?"
msgid "Set your default location in profile settings to pick a storage unit."
msgstr "Set your default location in profile settings to pick a storage unit."
+msgid "Sets what this unit is carried at in inventory."
+msgstr "Sets what this unit is carried at in inventory."
+
+msgid "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+
msgid "Settings"
msgstr "Settings"
@@ -19205,6 +19245,9 @@ msgstr "Some records won't come back. Type <0>{CONFIRM_WORD}</0> to continue."
msgid "Some Shifts"
msgstr "Some Shifts"
+msgid "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+msgstr "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+
msgid "Something went wrong. Please try again."
msgstr "Something went wrong. Please try again."
@@ -20328,9 +20371,6 @@ msgstr "The append-only record of every stock movement; on-hand is the sum of it
msgid "The asset moves into its in-service class and starts depreciating from the in-service date."
msgstr "The asset moves into its in-service class and starts depreciating from the in-service date."
-msgid "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-msgstr "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-
msgid "The authorization was refused in Onshape. Save the integration settings to try again."
msgstr "The authorization was refused in Onshape. Save the integration settings to try again."
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index a8b42cac11..f0f9d36236 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -1986,6 +1986,15 @@ msgstr "Línea de dirección 1"
msgid "Address line2"
msgstr "Línea de dirección 2"
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+msgstr "Agrega el costo al activo que nunca fue cargado, como la mano de obra y materiales de una orden de trabajo que no registró ningún costo."
+
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Agrega el costo al activo que nunca fue cargado, como la mano de obra y materiales de una orden de trabajo que no registró ningún costo. El valor se registra en el activo desde la cuenta desde la que se gastó: Resultados acumulados para un año anterior, o gasto de mano de obra o material de este año."
+
+msgid "Adjust Cost"
+msgstr "Ajustar Costo"
+
msgid "Adjustment"
msgstr "Ajuste"
@@ -5163,6 +5172,9 @@ msgstr "Convirtiendo…"
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Convierte la unidad de compra del proveedor a tu unidad de existencias en una orden de compra, recepción o línea de factura — compra en cajas de 12, existencias en unidades."
+msgid "Copied ID to clipboard"
+msgstr "Copiado ID al portapapeles"
+
msgid "Copied link to clipboard"
msgstr "Enlace copiado al portapapeles"
@@ -8312,6 +8324,12 @@ msgstr "Ingrese la URL de Onshape, el ID de cliente y el secreto de cliente de s
msgid "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
msgstr "Ingrese la cantidad que debería haber sido este movimiento. Un movimiento opuesto para la diferencia se publica junto al original, en el período de tiempo del original."
+msgid "Enter what it cost to make."
+msgstr "Ingrese el costo de fabricación."
+
+msgid "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Ingrese el costo de fabricación. El valor se registra en el activo desde la cuenta desde la que se gastó: Resultados acumulados para un año anterior, o gasto de mano de obra o material de este año."
+
msgid "Entered At Receipt"
msgstr "Ingresado en la Recepción"
@@ -10271,6 +10289,9 @@ msgstr "Los IDs y descripciones se generan para materias primas."
msgid "If"
msgstr "Si"
+msgid "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+msgstr "Si la depreciación ya se ha ejecutado, la próxima ejecución compensa los meses que un activo de Línea recta registró con el costo anterior."
+
msgid "If it can't wait for the next call, the leads on both sides decide."
msgstr "Si no puede esperar hasta la próxima llamada, los líderes de ambos lados deciden."
@@ -13229,6 +13250,9 @@ msgstr "Ninguna condición puede coincidir"
msgid "No conversion is required"
msgstr "No se requiere conversión"
+msgid "No cost"
+msgstr "Sin costo"
+
msgid "No cost has been recorded against this asset yet."
msgstr "No se ha registrado ningún costo contra este activo aún."
@@ -13946,6 +13970,9 @@ msgstr "Off — manejado fuera de la sincronización"
msgid "Off — released revisions stay editable"
msgstr "Desactivado — las revisiones lanzadas permanecen editables"
+msgid "Offset Account"
+msgstr "Cuenta de compensación"
+
msgid "ok"
msgstr "ok"
@@ -16550,6 +16577,13 @@ msgstr "Registros"
msgid "Records and posted journals are being sent to and received from this provider."
msgstr "Los registros y asientos contabilizados se están enviando y recibiendo desde este proveedor."
+msgid "Recost"
+msgstr "Recalcular costo"
+
+#. placeholder {0}: recostItem.readableId ?? ""
+msgid "Recost {0}"
+msgstr "Recalcular costo {0}"
+
msgid "Recovery Period"
msgstr "Registrar"
@@ -18709,6 +18743,12 @@ msgstr "¿Establecer la versión {0} como versión activa?"
msgid "Set your default location in profile settings to pick a storage unit."
msgstr "Establece tu ubicación predeterminada en la configuración del perfil para seleccionar una unidad de almacenamiento."
+msgid "Sets what this unit is carried at in inventory."
+msgstr "Define el costo al que esta unidad se registra en el inventario."
+
+msgid "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Define el costo al que esta unidad se registra en el inventario. La diferencia se registra entre el inventario y la cuenta desde la que se gastó el costo: Resultados acumulados para un año anterior, o gasto de mano de obra o material de este año."
+
msgid "Settings"
msgstr "Configuración"
@@ -19205,6 +19245,9 @@ msgstr "Algunos registros no volverán. Escriba <0>{CONFIRM_WORD}</0> para conti
msgid "Some Shifts"
msgstr "Algunos turnos"
+msgid "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+msgstr "Alguien que pueda actualizar Contabilidad debe ingresar el costo de fabricación antes de que pueda capitalizarse."
+
msgid "Something went wrong. Please try again."
msgstr "Algo salió mal. Por favor, inténtalo de nuevo."
@@ -20328,9 +20371,6 @@ msgstr "El registro de solo adición de cada movimiento de inventario; la cantid
msgid "The asset moves into its in-service class and starts depreciating from the in-service date."
msgstr "El activo entra en su clase en servicio y comienza a depreciarse desde la fecha de entrada en servicio."
-msgid "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-msgstr "El activo no tendría valor. Establezca un costo unitario en el artículo y luego capitalícelo."
-
msgid "The authorization was refused in Onshape. Save the integration settings to try again."
msgstr "La autorización fue rechazada en Onshape. Guarde la configuración de integración e intente de nuevo."
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 479789b103..c145ff369b 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -1986,6 +1986,15 @@ msgstr "Ligne d'adresse 1"
msgid "Address line2"
msgstr "Ligne d'adresse 2"
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+msgstr "Ajoute un coût que l'actif n'a jamais enregistré, comme la main-d'œuvre et les matériaux d'un ordre de fabrication qui n'en a enregistré aucun."
+
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Ajoute un coût que l'actif n'a jamais enregistré, comme la main-d'œuvre et les matériaux d'un ordre de fabrication qui n'en a enregistré aucun. La valeur est imputée à l'actif à partir du compte où elle a été dépensée : Report à nouveau pour un exercice antérieur, ou charge de main-d'œuvre ou de matière de cet exercice."
+
+msgid "Adjust Cost"
+msgstr "Ajuster le coût"
+
msgid "Adjustment"
msgstr "Ajustement"
@@ -5163,6 +5172,9 @@ msgstr "Conversion en cours…"
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Convertit l'unité d'achat d'un fournisseur en votre unité d'inventaire sur une ligne de commande, reçu ou facture — acheter en cartons de 12, stocker en unités."
+msgid "Copied ID to clipboard"
+msgstr "ID copié dans le presse-papiers"
+
msgid "Copied link to clipboard"
msgstr "Lien copié dans le presse-papiers"
@@ -8312,6 +8324,12 @@ msgstr "Entrez l'URL Onshape, l'ID client et le secret client de votre applicati
msgid "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
msgstr "Entrez la quantité que ce mouvement aurait dû avoir. Un mouvement opposé pour la différence est posté à côté de l'original, dans la période de l'original."
+msgid "Enter what it cost to make."
+msgstr "Entrez le coût de fabrication."
+
+msgid "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Entrez le coût de fabrication. La valeur est imputée à l'actif à partir du compte où elle a été dépensée : Report à nouveau pour un exercice antérieur, ou charge de main-d'œuvre ou de matière de cet exercice."
+
msgid "Entered At Receipt"
msgstr "Saisi à la réception"
@@ -10271,6 +10289,9 @@ msgstr "Les IDs et descriptions sont générés pour les matières premières."
msgid "If"
msgstr "Si"
+msgid "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+msgstr "Si l'amortissement a déjà été exécuté, le prochain calcul rattrape les mois qu'un actif linéaire a amortis à l'ancien coût."
+
msgid "If it can't wait for the next call, the leads on both sides decide."
msgstr "Si cela ne peut pas attendre le prochain appel, les responsables des deux côtés décident."
@@ -13229,6 +13250,9 @@ msgstr "Aucune condition ne doit correspondre"
msgid "No conversion is required"
msgstr "Aucune conversion n'est requise"
+msgid "No cost"
+msgstr "Aucun coût"
+
msgid "No cost has been recorded against this asset yet."
msgstr "Aucun coût n'a été enregistré pour cet actif pour le moment."
@@ -13946,6 +13970,9 @@ msgstr "Off — géré en dehors de la synchronisation"
msgid "Off — released revisions stay editable"
msgstr "Désactivé — les révisions publiées restent modifiables"
+msgid "Offset Account"
+msgstr "Compte de contrepartie"
+
msgid "ok"
msgstr "ok"
@@ -16550,6 +16577,13 @@ msgstr "Enregistrements"
msgid "Records and posted journals are being sent to and received from this provider."
msgstr "Les enregistrements et les écritures comptabilisées sont envoyés à et reçus de ce fournisseur."
+msgid "Recost"
+msgstr "Réévaluer le coût"
+
+#. placeholder {0}: recostItem.readableId ?? ""
+msgid "Recost {0}"
+msgstr "Réévaluer le coût {0}"
+
msgid "Recovery Period"
msgstr "Enregistrer"
@@ -18709,6 +18743,12 @@ msgstr "Définir la version {0} comme version active ?"
msgid "Set your default location in profile settings to pick a storage unit."
msgstr "Définissez votre emplacement par défaut dans les paramètres de profil pour sélectionner une unité de stockage."
+msgid "Sets what this unit is carried at in inventory."
+msgstr "Définit le coût auquel cette unité est portée en stocks."
+
+msgid "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Définit le coût auquel cette unité est portée en stocks. La différence est imputée entre les stocks et le compte dont le coût a été prélevé : Report à nouveau pour un exercice antérieur, ou charge de main-d'œuvre ou de matière de cet exercice."
+
msgid "Settings"
msgstr "Paramètres"
@@ -19205,6 +19245,9 @@ msgstr "Certains enregistrements ne reviendront pas. Tapez <0>{CONFIRM_WORD}</0>
msgid "Some Shifts"
msgstr "Certaines équipes"
+msgid "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+msgstr "Quelqu'un qui peut mettre à jour la comptabilité doit entrer le coût de fabrication avant qu'il puisse être capitalisé."
+
msgid "Something went wrong. Please try again."
msgstr "Quelque chose s'est mal passé. Veuillez réessayer."
@@ -20328,9 +20371,6 @@ msgstr "L'enregistrement d'ajout seul de tout mouvement de stock; le stock dispo
msgid "The asset moves into its in-service class and starts depreciating from the in-service date."
msgstr "L'actif passe dans sa classe en service et commence à se déprécier à partir de la date de mise en service."
-msgid "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-msgstr "L'immobilisation n'aurait aucune valeur. Définissez un coût unitaire sur l'article, puis capitalisez-la."
-
msgid "The authorization was refused in Onshape. Save the integration settings to try again."
msgstr "L'autorisation a été refusée dans Onshape. Enregistrez les paramètres d'intégration pour réessayer."
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 1336852fb6..390cd88b5d 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -1986,6 +1986,15 @@ msgstr "पता पंक्ति 1"
msgid "Address line2"
msgstr "पता पंक्ति 2"
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+msgstr "परिसंपत्ति को वह लागत जोड़ता है जो कभी चार्ज नहीं की गई थी, जैसे कि एक जॉब का श्रम और सामग्री जिसमें कुछ रिकॉर्ड नहीं किया गया था।"
+
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "परिसंपत्ति को वह लागत जोड़ता है जो कभी चार्ज नहीं की गई थी, जैसे कि एक जॉब का श्रम और सामग्री जिसमें कुछ रिकॉर्ड नहीं किया गया था। यह मान परिसंपत्ति को उस खाते से बुक किया जाता है जहाँ से खर्च किया गया था: एक पिछले वर्ष के लिए प्रतिधारित आय, या इस वर्ष का श्रम या सामग्री व्यय।"
+
+msgid "Adjust Cost"
+msgstr "लागत समायोजित करें"
+
msgid "Adjustment"
msgstr "समायोजन"
@@ -5163,6 +5172,9 @@ msgstr "परिवर्तित कर रहे हैं…"
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "एक आपूर्तिकर्ता की खरीद इकाई को PO, प्राप्ति, या बिल लाइन पर आपकी इन्वेंटरी इकाई में परिवर्तित करता है — 12 के कार्टन में खरीदें, व्यक्तिगत में स्टॉक करें।"
+msgid "Copied ID to clipboard"
+msgstr "ID क्लिपबोर्ड में कॉपी किया गया"
+
msgid "Copied link to clipboard"
msgstr "क्लिपबोर्ड में लिंक कॉपी किया गया"
@@ -8312,6 +8324,12 @@ msgstr "अपने निजी OAuth एप्लिकेशन का Onsha
msgid "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
msgstr "वह मात्रा दर्ज करें जो यह आंदोलन होना चाहिए था। अंतर के लिए एक विपरीत आंदोलन मूल के बगल में, मूल की समय अवधि में पोस्ट किया जाता है।"
+msgid "Enter what it cost to make."
+msgstr "इसे बनाने में जो लागत आई उसे दर्ज करें।"
+
+msgid "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "इसे बनाने में जो लागत आई उसे दर्ज करें। यह मान परिसंपत्ति को उस खाते से बुक किया जाता है जहाँ से खर्च किया गया था: एक पिछले वर्ष के लिए प्रतिधारित आय, या इस वर्ष का श्रम या सामग्री व्यय।"
+
msgid "Entered At Receipt"
msgstr "रसीद पर दर्ज"
@@ -10271,6 +10289,9 @@ msgstr "कच्चे माल के लिए ID और विवरण उ
msgid "If"
msgstr "यदि"
+msgid "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+msgstr "यदि मूल्यह्रास पहले ही चला है, तो अगला रन उन महीनों को पकड़ता है जो एक सीधी रेखा परिसंपत्ति को पुरानी लागत पर ले गए।"
+
msgid "If it can't wait for the next call, the leads on both sides decide."
msgstr "अगर यह अगली कॉल तक इंतज़ार नहीं कर सकता, तो दोनों तरफ के लीड फैसला लेते हैं।"
@@ -13229,6 +13250,9 @@ msgstr "कोई भी शर्त मेल नहीं खा सकती
msgid "No conversion is required"
msgstr "कोई रूपांतरण आवश्यक नहीं है"
+msgid "No cost"
+msgstr "कोई लागत नहीं"
+
msgid "No cost has been recorded against this asset yet."
msgstr "अभी तक इस संपत्ति के विरुद्ध कोई लागत दर्ज नहीं की गई है।"
@@ -13946,6 +13970,9 @@ msgstr "बंद — सिंक के बाहर संभाला गय
msgid "Off — released revisions stay editable"
msgstr "बंद — जारी किए गए रिवीजन संपादन योग्य रहते हैं"
+msgid "Offset Account"
+msgstr "ऑफसेट खाता"
+
msgid "ok"
msgstr "ठीक"
@@ -16550,6 +16577,13 @@ msgstr "रिकॉर्ड"
msgid "Records and posted journals are being sent to and received from this provider."
msgstr "रिकॉर्ड और पोस्ट किए गए जर्नल इस प्रदाता को भेजे जा रहे हैं और प्राप्त किए जा रहे हैं।"
+msgid "Recost"
+msgstr "लागत पुनः निर्धारित करें"
+
+#. placeholder {0}: recostItem.readableId ?? ""
+msgid "Recost {0}"
+msgstr "{0} की लागत पुनः निर्धारित करें"
+
msgid "Recovery Period"
msgstr "पंजीकृत करें"
@@ -18709,6 +18743,12 @@ msgstr "संस्करण {0} को सक्रिय संस्कर
msgid "Set your default location in profile settings to pick a storage unit."
msgstr "एक भंडारण इकाई चुनने के लिए प्रोफ़ाइल सेटिंग्स में अपना डिफ़ॉल्ट स्थान सेट करें।"
+msgid "Sets what this unit is carried at in inventory."
+msgstr "यह निर्धारित करता है कि यह इकाई इन्वेंटरी में किस कीमत पर ले जाई जाती है।"
+
+msgid "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "यह निर्धारित करता है कि यह इकाई इन्वेंटरी में किस कीमत पर ले जाई जाती है। अंतर इन्वेंटरी और उस खाते के बीच बुक किया जाता है जहाँ से लागत खर्च की गई थी: एक पिछले वर्ष के लिए प्रतिधारित आय, या इस वर्ष का श्रम या सामग्री व्यय।"
+
msgid "Settings"
msgstr "सेटिंग्स"
@@ -19205,6 +19245,9 @@ msgstr "कुछ रिकॉर्ड वापस नहीं आएंग
msgid "Some Shifts"
msgstr "कुछ शिफ्ट"
+msgid "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+msgstr "जो कोई भी लेखांकन को अपडेट कर सकता है, उसे इसे पूंजीकृत करने से पहले इसे बनाने की लागत दर्ज करनी होगी।"
+
msgid "Something went wrong. Please try again."
msgstr "कुछ गलत हो गया। कृपया पुनः प्रयास करें।"
@@ -20328,9 +20371,6 @@ msgstr "प्रत्येक स्टॉक आंदोलन का क
msgid "The asset moves into its in-service class and starts depreciating from the in-service date."
msgstr "संपत्ति अपनी सेवा-में कक्षा में चली जाती है और सेवा-में तारीख से मूल्यह्रास शुरू करती है।"
-msgid "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-msgstr "संपत्ति का कोई मूल्य नहीं होगा। आइटम पर इकाई लागत सेट करें, फिर इसे पूंजीकृत करें।"
-
msgid "The authorization was refused in Onshape. Save the integration settings to try again."
msgstr "Onshape में प्राधिकरण को अस्वीकार कर दिया गया था। एकीकरण सेटिंग्स को सहेजने का प्रयास करें।"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 0ec032cd90..5baf190646 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -1986,6 +1986,15 @@ msgstr "Riga indirizzo 1"
msgid "Address line2"
msgstr "Riga indirizzo 2"
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+msgstr "Aggiunge il costo che l'asset non è mai stato addebitato, come la manodopera e il materiale di un ordine di produzione che non ha registrato nulla."
+
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Aggiunge il costo che l'asset non è mai stato addebitato, come la manodopera e il materiale di un ordine di produzione che non ha registrato nulla. Il valore è registrato nell'asset dal conto da cui è stato speso: Utili non distribuiti per un anno precedente, o la spesa di manodopera o materiale di quest'anno."
+
+msgid "Adjust Cost"
+msgstr "Regola il costo"
+
msgid "Adjustment"
msgstr "Rettifica"
@@ -5163,6 +5172,9 @@ msgstr "Conversione in corso…"
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Converte l'unità di acquisto di un fornitore nella tua unità di inventario su una linea di ordine, ricevuta o fattura — acquista in scatole di 12, stoccaggio in unità singole."
+msgid "Copied ID to clipboard"
+msgstr "ID copiato negli appunti"
+
msgid "Copied link to clipboard"
msgstr "Collegamento copiato negli appunti"
@@ -8312,6 +8324,12 @@ msgstr "Immetti l'URL Onshape, l'ID client e il client secret della tua applicaz
msgid "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
msgstr "Inserisci la quantità che questo movimento avrebbe dovuto essere. Un movimento opposto per la differenza è registrato accanto all'originale, nel periodo temporale dell'originale."
+msgid "Enter what it cost to make."
+msgstr "Inserisci il costo di produzione."
+
+msgid "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Inserisci il costo di produzione. Il valore è registrato nell'asset dal conto da cui è stato speso: Utili non distribuiti per un anno precedente, o la spesa di manodopera o materiale di quest'anno."
+
msgid "Entered At Receipt"
msgstr "Inserito al Ricevimento"
@@ -10271,6 +10289,9 @@ msgstr "Gli ID e le descrizioni vengono generati per le materie prime."
msgid "If"
msgstr "Se"
+msgid "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+msgstr "Se l'ammortamento è già stato eseguito, la prossima esecuzione recupera i mesi che un asset con Quote costanti ha preso al vecchio costo."
+
msgid "If it can't wait for the next call, the leads on both sides decide."
msgstr "Se non può aspettare la prossima call, i responsabili da entrambi i lati decidono."
@@ -13229,6 +13250,9 @@ msgstr "Nessuna condizione può corrispondere"
msgid "No conversion is required"
msgstr "Nessuna conversione richiesta"
+msgid "No cost"
+msgstr "Nessun costo"
+
msgid "No cost has been recorded against this asset yet."
msgstr "Non è stato registrato alcun costo su questo asset."
@@ -13946,6 +13970,9 @@ msgstr "Disattivato — gestito al di fuori della sincronizzazione"
msgid "Off — released revisions stay editable"
msgstr "Disattivato — le revisioni rilasciate rimangono modificabili"
+msgid "Offset Account"
+msgstr "Conto di compensazione"
+
msgid "ok"
msgstr "ok"
@@ -16550,6 +16577,13 @@ msgstr "Registri"
msgid "Records and posted journals are being sent to and received from this provider."
msgstr "I record e le prime note registrate vengono inviate e ricevute da questo provider."
+msgid "Recost"
+msgstr "Ricalcola il costo"
+
+#. placeholder {0}: recostItem.readableId ?? ""
+msgid "Recost {0}"
+msgstr "Ricalcola il costo {0}"
+
msgid "Recovery Period"
msgstr "Registrare"
@@ -18709,6 +18743,12 @@ msgstr "Imposta la versione {0} come versione attiva?"
msgid "Set your default location in profile settings to pick a storage unit."
msgstr "Imposta la tua ubicazione predefinita nelle impostazioni del profilo per scegliere un'unità di stoccaggio."
+msgid "Sets what this unit is carried at in inventory."
+msgstr "Definisce il valore con cui questa unità è riportata nel magazzino."
+
+msgid "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Definisce il valore con cui questa unità è riportata nel magazzino. La differenza è registrata tra il magazzino e il conto da cui è stato speso il costo: Utili non distribuiti per un anno precedente, o la spesa di manodopera o materiale di quest'anno."
+
msgid "Settings"
msgstr "Impostazioni"
@@ -19205,6 +19245,9 @@ msgstr "Alcuni record non torneranno. Digita <0>{CONFIRM_WORD}</0> per continuar
msgid "Some Shifts"
msgstr "Alcuni turni"
+msgid "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+msgstr "Qualcuno che può aggiornare la contabilità deve inserire il costo di produzione prima che possa essere capitalizzato."
+
msgid "Something went wrong. Please try again."
msgstr "Qualcosa è andato storto. Riprova."
@@ -20328,9 +20371,6 @@ msgstr "Il record di sola aggiunta di ogni movimento di inventario; la giacenza
msgid "The asset moves into its in-service class and starts depreciating from the in-service date."
msgstr "L'asset si sposta nella sua classe in servizio e inizia l'ammortamento dalla data di messa in servizio."
-msgid "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-msgstr "L'attività non avrebbe valore. Impostare un costo unitario sull'articolo, quindi capitalizzarlo."
-
msgid "The authorization was refused in Onshape. Save the integration settings to try again."
msgstr "L'autorizzazione è stata rifiutata in Onshape. Salva le impostazioni di integrazione per riprovare."
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index bf85f5f6fd..de99c118d8 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -1986,6 +1986,15 @@ msgstr "住所 行1"
msgid "Address line2"
msgstr "住所 行2"
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+msgstr "資産に計上されなかった原価を追加します。例えば、記録されていない製造指図の労務と材料など。"
+
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "資産に計上されなかった原価を追加します。例えば、記録されていない製造指図の労務と材料などです。その価値は、支出元の勘定から資産に計上されます。前年度の利益剰余金、あるいは当年度の労務費または材料費から計上されます。"
+
+msgid "Adjust Cost"
+msgstr "原価を調整"
+
msgid "Adjustment"
msgstr "調整"
@@ -5163,6 +5172,9 @@ msgstr "変換中…"
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "仕入先の購入単位をPO、入荷、または請求書上で在庫単位に変換します — 12個のカートン単位で仕入れ、個単位で在庫する。"
+msgid "Copied ID to clipboard"
+msgstr "IDをクリップボードにコピーしました"
+
msgid "Copied link to clipboard"
msgstr "クリップボードにリンクをコピーしました"
@@ -8312,6 +8324,12 @@ msgstr "プライベートOAuthアプリケーションのOnshape URL、クラ
msgid "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
msgstr "この移動がどの数量であるべきかを入力します。差分の反対の移動は、オリジナルの横に、オリジナルの期間に投稿されます。"
+msgid "Enter what it cost to make."
+msgstr "製造にかかった原価を入力してください。"
+
+msgid "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "製造にかかった原価を入力してください。その価値は、支出元の勘定から資産に計上されます。前年度の利益剰余金、あるいは当年度の労務費または材料費から計上されます。"
+
msgid "Entered At Receipt"
msgstr "受領時に入力"
@@ -10271,6 +10289,9 @@ msgstr "IDと説明は原材料に対して生成されます。"
msgid "If"
msgstr "条件"
+msgid "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+msgstr "減価償却が既に実行されている場合、次回の減価償却実行時に定額法資産が旧原価で計上していた月分が埋め合わされます。"
+
msgid "If it can't wait for the next call, the leads on both sides decide."
msgstr "次の通話を待つことができない場合、両側のリーダーが決定します。"
@@ -13229,6 +13250,9 @@ msgstr "条件が一致しない"
msgid "No conversion is required"
msgstr "変換は不要です"
+msgid "No cost"
+msgstr "原価なし"
+
msgid "No cost has been recorded against this asset yet."
msgstr "このアセットに対してまだ原価が記録されていません。"
@@ -13946,6 +13970,9 @@ msgstr "オフ — 同期外で処理"
msgid "Off — released revisions stay editable"
msgstr "オフ - リリースされたリビジョンは編集可能なままです"
+msgid "Offset Account"
+msgstr "相殺勘定"
+
msgid "ok"
msgstr "OK"
@@ -16550,6 +16577,13 @@ msgstr "記録"
msgid "Records and posted journals are being sent to and received from this provider."
msgstr "レコードと転記済仕訳がこのプロバイダーとの間で送受信されています。"
+msgid "Recost"
+msgstr "原価を再査定"
+
+#. placeholder {0}: recostItem.readableId ?? ""
+msgid "Recost {0}"
+msgstr "{0}の原価を再査定"
+
msgid "Recovery Period"
msgstr "登録"
@@ -18709,6 +18743,12 @@ msgstr "バージョン {0} をアクティブバージョンとして設定し
msgid "Set your default location in profile settings to pick a storage unit."
msgstr "プロフィール設定でデフォルトの場所を設定して、保管ユニットを選択してください。"
+msgid "Sets what this unit is carried at in inventory."
+msgstr "この個が在庫で計上されている価値を設定します。"
+
+msgid "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "この個が在庫で計上されている価値を設定します。差額は在庫と支出元の勘定との間で計上されます。前年度の利益剰余金、あるいは当年度の労務費または材料費から計上されます。"
+
msgid "Settings"
msgstr "設定"
@@ -19205,6 +19245,9 @@ msgstr "いくつかのレコードは戻りません。続行するには<0>{CO
msgid "Some Shifts"
msgstr "一部のシフト"
+msgid "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+msgstr "会計を更新できるユーザーが製造にかかった原価を入力してからでなければ、資本化できません。"
+
msgid "Something went wrong. Please try again."
msgstr "何か問題が発生しました。もう一度お試しください。"
@@ -20328,9 +20371,6 @@ msgstr "すべての在庫移動の追加専用レコード。手持在庫はそ
msgid "The asset moves into its in-service class and starts depreciating from the in-service date."
msgstr "資産が使用中クラスに移動され、使用開始日から減価償却が開始されます。"
-msgid "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-msgstr "資産の価値がゼロになります。品目に単価を設定してから、資産化してください。"
-
msgid "The authorization was refused in Onshape. Save the integration settings to try again."
msgstr "Onshapeで認可が拒否されました。連携設定を保存して再度試してください。"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 88bb85e7ee..0be57df2c7 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -1986,6 +1986,15 @@ msgstr "주소 라인1"
msgid "Address line2"
msgstr "주소 라인2"
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+msgstr "자산이 청구되지 않은 원가를 추가합니다. 예를 들어, 비용을 기록하지 않은 작업 지시의 노무와 자재입니다."
+
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "자산이 청구되지 않은 원가를 추가합니다. 예를 들어, 비용을 기록하지 않은 작업 지시의 노무와 자재입니다. 이 금액은 지출된 계정에서 자산으로 기입됩니다: 이전 연도의 이익잉여금 또는 올해의 노무 또는 자재 비용입니다."
+
+msgid "Adjust Cost"
+msgstr "원가 조정"
+
msgid "Adjustment"
msgstr "조정"
@@ -5163,6 +5172,9 @@ msgstr "변환 중…"
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "공급업체의 구매 단위를 발주서, 입고, 송장 라인에서 귀사의 재고 단위로 전환합니다 — 12개 상자 단위로 구매하고 개별 단위로 재고에 보관합니다."
+msgid "Copied ID to clipboard"
+msgstr "ID를 클립보드에 복사했습니다"
+
msgid "Copied link to clipboard"
msgstr "링크가 클립보드에 복사됨"
@@ -8312,6 +8324,12 @@ msgstr "개인 OAuth 애플리케이션의 Onshape URL, 클라이언트 ID 및
msgid "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
msgstr "이 이동이 있었어야 할 수량을 입력하십시오. 차이에 대한 반대 이동은 원본 옆의 원본의 시간 기간에 게시됩니다."
+msgid "Enter what it cost to make."
+msgstr "사내 생산 원가를 입력하십시오."
+
+msgid "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "사내 생산 원가를 입력하십시오. 이 금액은 지출된 계정에서 자산으로 기입됩니다: 이전 연도의 이익잉여금 또는 올해의 노무 또는 자재 비용입니다."
+
msgid "Entered At Receipt"
msgstr "입고 시 입력됨"
@@ -10271,6 +10289,9 @@ msgstr "원자재에 대한 ID와 설명이 자동으로 생성됩니다."
msgid "If"
msgstr "만약"
+msgid "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+msgstr "감가상각이 이미 실행된 경우, 다음 실행 시 정액법 자산이 이전 원가로 소요한 개월 수의 감가상각을 보정합니다."
+
msgid "If it can't wait for the next call, the leads on both sides decide."
msgstr "다음 통화까지 기다릴 수 없는 경우, 양측 담당자가 결정합니다."
@@ -13229,6 +13250,9 @@ msgstr "조건이 하나도 일치하지 않을 수 있습니다"
msgid "No conversion is required"
msgstr "변환이 필요하지 않습니다"
+msgid "No cost"
+msgstr "원가 없음"
+
msgid "No cost has been recorded against this asset yet."
msgstr "이 자산에 대해 아직 기록된 원가가 없습니다."
@@ -13946,6 +13970,9 @@ msgstr "끔 — 동기화 외부에서 처리됨"
msgid "Off — released revisions stay editable"
msgstr "꺼짐 — 릴리스된 리비전은 편집 가능한 상태로 유지됨"
+msgid "Offset Account"
+msgstr "상계 계정"
+
msgid "ok"
msgstr "확인"
@@ -16550,6 +16577,13 @@ msgstr "레코드"
msgid "Records and posted journals are being sent to and received from this provider."
msgstr "기록 및 전기된 전표가 이 공급자에게 송수신되고 있습니다."
+msgid "Recost"
+msgstr "원가 재계산"
+
+#. placeholder {0}: recostItem.readableId ?? ""
+msgid "Recost {0}"
+msgstr "원가 재계산 {0}"
+
msgid "Recovery Period"
msgstr "회수 기간"
@@ -18709,6 +18743,12 @@ msgstr "버전 {0}을(를) 활성 버전으로 설정하시겠습니까?"
msgid "Set your default location in profile settings to pick a storage unit."
msgstr "프로필 설정에서 기본 사업장을 설정하여 보관 단위를 선택하세요."
+msgid "Sets what this unit is carried at in inventory."
+msgstr "이 자산의 재고 계상 금액을 설정합니다."
+
+msgid "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "이 자산의 재고 계상 금액을 설정합니다. 차이는 재고와 비용이 지출된 계정 간에 기입됩니다: 이전 연도의 이익잉여금 또는 올해의 노무 또는 자재 비용입니다."
+
msgid "Settings"
msgstr "설정"
@@ -19205,6 +19245,9 @@ msgstr "일부 레코드는 돌아오지 않습니다. 계속하려면 <0>{CONFI
msgid "Some Shifts"
msgstr "일부 교대조"
+msgid "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+msgstr "회계를 업데이트할 수 있는 사용자가 자산을 자본화하기 전에 사내 생산 원가를 입력해야 합니다."
+
msgid "Something went wrong. Please try again."
msgstr "문제가 발생했습니다. 다시 시도해 주세요."
@@ -20328,9 +20371,6 @@ msgstr "모든 재고 이동을 추가 전용으로 기록한 원장으로, 보
msgid "The asset moves into its in-service class and starts depreciating from the in-service date."
msgstr "자산이 사용 중인 분류로 이동하고 사용 개시 일자부터 감가상각을 시작합니다."
-msgid "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-msgstr "자산의 가치가 0이 될 것입니다. 품목에 단위 원가를 설정한 후 자산화하세요."
-
msgid "The authorization was refused in Onshape. Save the integration settings to try again."
msgstr "Onshape에서 인증이 거부되었습니다. 연동 설정을 저장하여 다시 시도하세요."
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index b8e0762f3c..46c798e4b1 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -1986,6 +1986,15 @@ msgstr "Linia adresu 1"
msgid "Address line2"
msgstr "Linia adresu 2"
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+msgstr "Dodaje koszt, którym składnik majątku nigdy nie został obciążony, taki jak robocizna i materiały ze zlecenia produkcyjnego, które nic nie zarejestrowały."
+
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Dodaje koszt, którym składnik majątku nigdy nie został obciążony, taki jak robocizna i materiały ze zlecenia produkcyjnego, które nic nie zarejestrowały. Wartość jest księgowana na składnik majątku z konta, z którego została wydatkowana: Zyski zatrzymane za wcześniejszy rok, lub wydatek na robocizę lub materiały za ten rok."
+
+msgid "Adjust Cost"
+msgstr "Dostosuj koszt"
+
msgid "Adjustment"
msgstr "Korekta"
@@ -5163,6 +5172,9 @@ msgstr "Konwertowanie…"
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Konwertuje jednostkę zakupu dostawcy na Twoją jednostkę zapasów na pozycji zamówienia zakupu, przyjęcia lub faktury — zakup w kartonach po 12 sztuk, zapasy w sztukach."
+msgid "Copied ID to clipboard"
+msgstr "Skopiowano ID do schowka"
+
msgid "Copied link to clipboard"
msgstr "Skopiowano link do schowka"
@@ -8312,6 +8324,12 @@ msgstr "Podaj URL Onshape, identyfikator klienta i klucz tajny prywatnej aplikac
msgid "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
msgstr "Wprowadź ilość, która powinna być dla tego ruchu. Przeciwny ruch dla różnicy jest publikowany obok oryginału w okresie czasowym oryginału."
+msgid "Enter what it cost to make."
+msgstr "Wpisz, ile kosztowało to wytworzenie."
+
+msgid "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Wpisz, ile kosztowało to wytworzenie. Wartość jest księgowana na składnik majątku z konta, z którego została wydatkowana: Zyski zatrzymane za wcześniejszy rok, lub wydatek na robocizę lub materiały za ten rok."
+
msgid "Entered At Receipt"
msgstr "Wprowadzono przy odbiorze"
@@ -10271,6 +10289,9 @@ msgstr "Identyfikatory i opisy są generowane dla surowców."
msgid "If"
msgstr "Jeśli"
+msgid "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+msgstr "Jeśli amortyzacja już się uruchomiła, następny przebieg uwzględni wyrównanie za miesiące, w których ta pozycja została amortyzowana metodą liniową przy starym koszcie."
+
msgid "If it can't wait for the next call, the leads on both sides decide."
msgstr "Jeśli nie może czekać do następnego spotkania, decydują liderzy z obu stron."
@@ -13229,6 +13250,9 @@ msgstr "Żaden warunek nie może się zgadzać"
msgid "No conversion is required"
msgstr "Konwersja nie jest wymagana"
+msgid "No cost"
+msgstr "Bez kosztu"
+
msgid "No cost has been recorded against this asset yet."
msgstr "Jeszcze nie zaksięgowano kosztu dla tego zasobu."
@@ -13946,6 +13970,9 @@ msgstr "Wyłączone — obsługiwane poza synchronizacją"
msgid "Off — released revisions stay editable"
msgstr "Wyłączone — zwolnione rewizje pozostają edytowalne"
+msgid "Offset Account"
+msgstr "Konto równoważące"
+
msgid "ok"
msgstr "ok"
@@ -16550,6 +16577,13 @@ msgstr "Rekordy"
msgid "Records and posted journals are being sent to and received from this provider."
msgstr "Rekordy i zaksięgowane dowody księgowe są wysyłane do i odbierane z tego dostawcy."
+msgid "Recost"
+msgstr "Przelicz koszt"
+
+#. placeholder {0}: recostItem.readableId ?? ""
+msgid "Recost {0}"
+msgstr "Przelicz koszt {0}"
+
msgid "Recovery Period"
msgstr "Zarejestruj"
@@ -18709,6 +18743,12 @@ msgstr "Ustawić wersję {0} jako aktywną wersję?"
msgid "Set your default location in profile settings to pick a storage unit."
msgstr "Ustaw swoją domyślną lokalizację w ustawieniach profilu, aby wybrać jednostkę magazynową."
+msgid "Sets what this unit is carried at in inventory."
+msgstr "Ustawia, za ile ta sztuka jest wyceniana w zapasach."
+
+msgid "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Ustawia, za ile ta sztuka jest wyceniana w zapasach. Różnica jest księgowana między zapasami a kontem, z którego wydatkowano koszt: Zyski zatrzymane za wcześniejszy rok, lub wydatek na robocizę lub materiały za ten rok."
+
msgid "Settings"
msgstr "Ustawienia"
@@ -19205,6 +19245,9 @@ msgstr "Niektóre rekordy nie wrócą. Wpisz <0>{CONFIRM_WORD}</0> aby kontynuow
msgid "Some Shifts"
msgstr "Niektóre zmiany"
+msgid "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+msgstr "Osoba, która może aktualizować księgowość, musi wpisać, ile kosztowało to wytworzenie, zanim będzie można to skapitalizować."
+
msgid "Something went wrong. Please try again."
msgstr "Coś poszło nie tak. Spróbuj ponownie."
@@ -20328,9 +20371,6 @@ msgstr "Rejestr tylko dołączania każdego ruchu magazynowego; dostępna iloś
msgid "The asset moves into its in-service class and starts depreciating from the in-service date."
msgstr "Zasób przechodzi do swojej klasy w użytku i zaczyna się amortyzować od daty wprowadzenia do użytku."
-msgid "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-msgstr "Zasób miałby zerową wartość. Ustaw koszt jednostkowy artykułu, a następnie go skapitalizuj."
-
msgid "The authorization was refused in Onshape. Save the integration settings to try again."
msgstr "Autoryzacja została odmówiona w Onshape. Zapisz ustawienia integracji i spróbuj ponownie."
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 69d61bcbf4..05c3da604d 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -1986,6 +1986,15 @@ msgstr "Linha de endereço 1"
msgid "Address line2"
msgstr "Linha de endereço 2"
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+msgstr "Adiciona custo que o ativo nunca teve registrado, como a mão de obra e os materiais de uma ordem de produção que não registrou nenhum custo."
+
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Adiciona custo que o ativo nunca teve registrado, como a mão de obra e os materiais de uma ordem de produção que não registrou nenhum custo. O valor é registrado no ativo da conta de onde foi gasto: Lucros acumulados para um ano anterior, ou despesa de mão de obra ou de materiais deste ano."
+
+msgid "Adjust Cost"
+msgstr "Ajustar Custo"
+
msgid "Adjustment"
msgstr "Ajuste"
@@ -5163,6 +5172,9 @@ msgstr "Convertendo…"
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Converte a unidade de compra de um fornecedor para sua unidade de inventário em uma linha de pedido, recebimento ou fatura — compre em caixas de 12, estoque em unidades."
+msgid "Copied ID to clipboard"
+msgstr "ID copiado para a área de transferência"
+
msgid "Copied link to clipboard"
msgstr "Link copiado para a área de transferência"
@@ -8312,6 +8324,12 @@ msgstr "Insira a URL do Onshape, o ID do cliente e o segredo do cliente de seu a
msgid "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
msgstr "Insira a quantidade que esse movimento deveria ter sido. Um movimento oposto para a diferença é lançado ao lado do original, no período de tempo do original."
+msgid "Enter what it cost to make."
+msgstr "Digite o custo para fabricar."
+
+msgid "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Digite o custo para fabricar. O valor é registrado no ativo da conta de onde foi gasto: Lucros acumulados para um ano anterior, ou despesa de mão de obra ou de materiais deste ano."
+
msgid "Entered At Receipt"
msgstr "Inserido no Recebimento"
@@ -10271,6 +10289,9 @@ msgstr "IDs e descrições são gerados para matérias-primas."
msgid "If"
msgstr "Se"
+msgid "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+msgstr "Se a depreciação já foi executada, a próxima execução compensa os meses em que um ativo Linear foi depreciado com o custo antigo."
+
msgid "If it can't wait for the next call, the leads on both sides decide."
msgstr "Se não puder esperar pela próxima chamada, os líderes de ambos os lados decidem."
@@ -13229,6 +13250,9 @@ msgstr "Nenhuma condição pode corresponder"
msgid "No conversion is required"
msgstr "Nenhuma conversão é necessária"
+msgid "No cost"
+msgstr "Sem custo"
+
msgid "No cost has been recorded against this asset yet."
msgstr "Nenhum custo foi registrado para este ativo ainda."
@@ -13946,6 +13970,9 @@ msgstr "Desativado — tratado fora da sincronização"
msgid "Off — released revisions stay editable"
msgstr "Desativado — revisões lançadas permanecem editáveis"
+msgid "Offset Account"
+msgstr "Conta de Compensação"
+
msgid "ok"
msgstr "ok"
@@ -16550,6 +16577,13 @@ msgstr "Registros"
msgid "Records and posted journals are being sent to and received from this provider."
msgstr "Registros e diários contabilizados estão sendo enviados e recebidos deste provedor."
+msgid "Recost"
+msgstr "Recalcular Custo"
+
+#. placeholder {0}: recostItem.readableId ?? ""
+msgid "Recost {0}"
+msgstr "Recalcular Custo de {0}"
+
msgid "Recovery Period"
msgstr "Registrar"
@@ -18709,6 +18743,12 @@ msgstr "Definir Versão {0} como Versão Ativa?"
msgid "Set your default location in profile settings to pick a storage unit."
msgstr "Defina sua localização padrão nas configurações de perfil para escolher uma unidade de armazenamento."
+msgid "Sets what this unit is carried at in inventory."
+msgstr "Define o valor pelo qual esta unidade é registrada no inventário."
+
+msgid "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Define o valor pelo qual esta unidade é registrada no inventário. A diferença é registrada entre o inventário e a conta de onde o custo foi gasto: Lucros acumulados para um ano anterior, ou despesa de mão de obra ou de materiais deste ano."
+
msgid "Settings"
msgstr "Configurações"
@@ -19205,6 +19245,9 @@ msgstr "Alguns registros não voltarão. Digite <0>{CONFIRM_WORD}</0> para conti
msgid "Some Shifts"
msgstr "Alguns Turnos"
+msgid "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+msgstr "Alguém que possa atualizar a contabilidade deve inserir o custo para fabricar antes que possa ser capitalizado."
+
msgid "Something went wrong. Please try again."
msgstr "Algo deu errado. Tente novamente."
@@ -20328,9 +20371,6 @@ msgstr "O registro de adição ao final de cada movimento de estoque; a quantida
msgid "The asset moves into its in-service class and starts depreciating from the in-service date."
msgstr "O ativo entra em sua classe de serviço e começa a ser depreciado a partir da data de entrada em serviço."
-msgid "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-msgstr "O ativo não teria valor. Defina um custo unitário no item e depois capitalizá-lo."
-
msgid "The authorization was refused in Onshape. Save the integration settings to try again."
msgstr "A autorização foi recusada no Onshape. Salve as configurações de integração para tentar novamente."
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index cab256f636..e1b40a0d50 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -1986,6 +1986,15 @@ msgstr "Адрес строка1"
msgid "Address line2"
msgstr "Адрес строка2"
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+msgstr "Добавляет себестоимость, которая не была отнесена на актив, такую как затраты труда и материалов производственного заказа, который не был зафиксирован."
+
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Добавляет себестоимость, которая не была отнесена на актив, такую как затраты труда и материалов производственного заказа, который не был зафиксирован. Стоимость проводится на актив со счета, с которого она была потрачена: Нераспределенная прибыль за предыдущий год или расходы труда и материалов текущего года."
+
+msgid "Adjust Cost"
+msgstr "Скорректировать себестоимость"
+
msgid "Adjustment"
msgstr "Корректировка"
@@ -5163,6 +5172,9 @@ msgstr "Преобразование…"
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Преобразует единицу покупки поставщика в единицу инвентаря в строке заказа на покупку, квитанции или счета — покупайте в картонах по 12 штук, запасайте в единицах."
+msgid "Copied ID to clipboard"
+msgstr "ID скопирован в буфер обмена"
+
msgid "Copied link to clipboard"
msgstr "Ссылка скопирована в буфер обмена"
@@ -8312,6 +8324,12 @@ msgstr "Введите URL Onshape, ID клиента и клиентский с
msgid "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
msgstr "Введите количество, которое должно было быть в этом движении. Противоположное движение для разницы размещается рядом с оригинальным в его временном периоде."
+msgid "Enter what it cost to make."
+msgstr "Введите себестоимость производства."
+
+msgid "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Введите себестоимость производства. Стоимость проводится на актив со счета, с которого она была потрачена: Нераспределенная прибыль за предыдущий год или расходы труда и материалов текущего года."
+
msgid "Entered At Receipt"
msgstr "Введено при получении"
@@ -10271,6 +10289,9 @@ msgstr "Идентификаторы и описания генерируютс
msgid "If"
msgstr "Если"
+msgid "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+msgstr "Если амортизация уже была рассчитана, следующий расчет выровняет периоды, в течение которых актив с линейным методом амортизации учитывался по старой себестоимости."
+
msgid "If it can't wait for the next call, the leads on both sides decide."
msgstr "Если это не может ждать до следующего звонка, решение принимают руководители с обеих сторон."
@@ -13229,6 +13250,9 @@ msgstr "Ни одно условие не должно совпадать"
msgid "No conversion is required"
msgstr "Преобразование не требуется"
+msgid "No cost"
+msgstr "Нет себестоимости"
+
msgid "No cost has been recorded against this asset yet."
msgstr "Никакие расходы еще не зафиксированы против этого актива."
@@ -13946,6 +13970,9 @@ msgstr "Отключено — обработано вне синхрониза
msgid "Off — released revisions stay editable"
msgstr "Отключено — выпущенные ревизии остаются редактируемыми"
+msgid "Offset Account"
+msgstr "Счет компенсации"
+
msgid "ok"
msgstr "хорошо"
@@ -16550,6 +16577,13 @@ msgstr "Записи"
msgid "Records and posted journals are being sent to and received from this provider."
msgstr "Записи и проведенные операции отправляются и получаются от этого поставщика."
+msgid "Recost"
+msgstr "Переоценить"
+
+#. placeholder {0}: recostItem.readableId ?? ""
+msgid "Recost {0}"
+msgstr "Переоценить {0}"
+
msgid "Recovery Period"
msgstr "Зарегистрировать"
@@ -18709,6 +18743,12 @@ msgstr "Установить версию {0} как активную верси
msgid "Set your default location in profile settings to pick a storage unit."
msgstr "Установите местоположение по умолчанию в настройках профиля, чтобы выбрать единицу хранения."
+msgid "Sets what this unit is carried at in inventory."
+msgstr "Задает себестоимость единицы в запасах."
+
+msgid "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Задает себестоимость единицы в запасах. Разница проводится между запасами и счетом, с которого была потрачена себестоимость: Нераспределенная прибыль за предыдущий год или расходы труда и материалов текущего года."
+
msgid "Settings"
msgstr "Настройки"
@@ -19205,6 +19245,9 @@ msgstr "Некоторые записи не вернутся. Введите <0
msgid "Some Shifts"
msgstr "Некоторые смены"
+msgid "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+msgstr "Пользователь, имеющий права на обновление бухгалтерии, должен ввести себестоимость производства перед тем, как она может быть капитализирована."
+
msgid "Something went wrong. Please try again."
msgstr "Что-то пошло не так. Пожалуйста, попробуйте еще раз."
@@ -20328,9 +20371,6 @@ msgstr "Журнал доступного только для добавлени
msgid "The asset moves into its in-service class and starts depreciating from the in-service date."
msgstr "Актив переходит в свой класс в эксплуатации и начинает амортизироваться с даты ввода в эксплуатацию."
-msgid "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-msgstr "Актив будет иметь нулевую стоимость. Установите себестоимость номенклатуры, затем капитализируйте ее."
-
msgid "The authorization was refused in Onshape. Save the integration settings to try again."
msgstr "Авторизация была отклонена в Onshape. Сохраните настройки интеграции и попробуйте еще раз."
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index a2db38142f..72d8f3a4a1 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -1986,6 +1986,15 @@ msgstr "Adres satırı 1"
msgid "Address line2"
msgstr "Adres satırı 2"
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+msgstr "Varlığın hiçbir zaman yüklenmediği, örneğin maliyeti kaydedilmemiş bir iş emrinin İşçiliği ve malzemeleri gibi maliyetleri ekler."
+
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Varlığın hiçbir zaman yüklenmediği, örneğin maliyeti kaydedilmemiş bir iş emrinin İşçiliği ve malzemeleri gibi maliyetleri ekler. Değer, harcanan hesaptan varlığa kaydedilir: önceki yıl için Dağıtılmamış kârlar veya bu yıl'ın İşçilik veya malzeme gideri."
+
+msgid "Adjust Cost"
+msgstr "Maliyeti Ayarla"
+
msgid "Adjustment"
msgstr "Düzeltme"
@@ -5163,6 +5172,9 @@ msgstr "Dönüştürülüyor…"
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "Bir tedarikçinin satın alma birimini bir PO, makbuz veya fatura satırında envanter biriminize dönüştürür — 12'lik kutularda satın alın, birimlerde stok yapın."
+msgid "Copied ID to clipboard"
+msgstr "ID panoya kopyalandı"
+
msgid "Copied link to clipboard"
msgstr "Bağlantı panoya kopyalandı"
@@ -8312,6 +8324,12 @@ msgstr "Özel OAuth uygulamanızın Onshape URL'sini, istemci ID'sini ve istemci
msgid "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
msgstr "Bu hareketin olması gereken miktarı girin. Farktaki ters hareket, orijinalin zaman döneminde orijinalin yanında deftere kaydedilir."
+msgid "Enter what it cost to make."
+msgstr "Üretim maliyetini girin."
+
+msgid "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Üretim maliyetini girin. Değer, harcanan hesaptan varlığa kaydedilir: önceki yıl için Dağıtılmamış kârlar veya bu yıl'ın İşçilik veya malzeme gideri."
+
msgid "Entered At Receipt"
msgstr "Alındığında Girildi"
@@ -10271,6 +10289,9 @@ msgstr "Kimlikler ve açıklamalar hammadde için oluşturulur."
msgid "If"
msgstr "Eğer"
+msgid "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+msgstr "Amortisman zaten çalıştıysa, sonraki çalıştırma Doğrusal bir varlığın eski maliyette harcadığı ayları yakalama yapar."
+
msgid "If it can't wait for the next call, the leads on both sides decide."
msgstr "Eğer bir sonraki çağrıyı bekleyemezse, her iki tarafın da liderler karar verir."
@@ -13229,6 +13250,9 @@ msgstr "Hiçbir koşul eşleşemez"
msgid "No conversion is required"
msgstr "Dönüşüm gerekmiyor"
+msgid "No cost"
+msgstr "Maliyet yok"
+
msgid "No cost has been recorded against this asset yet."
msgstr "Bu varlık için henüz maliyet kaydı yapılmamıştır."
@@ -13946,6 +13970,9 @@ msgstr "Kapalı — senkronizasyon dışında işlenir"
msgid "Off — released revisions stay editable"
msgstr "Kapalı — yayınlanan revizyonlar düzenlenebilir kalır"
+msgid "Offset Account"
+msgstr "Karşı Hesap"
+
msgid "ok"
msgstr "tamam"
@@ -16550,6 +16577,13 @@ msgstr "Kayıtlar"
msgid "Records and posted journals are being sent to and received from this provider."
msgstr "Kayıtlar ve muhasebeleştirilmiş muhasebe fişleri bu sağlayıcı ile gönderiliyor ve alınıyor."
+msgid "Recost"
+msgstr "Maliyeti Yeniden Hesapla"
+
+#. placeholder {0}: recostItem.readableId ?? ""
+msgid "Recost {0}"
+msgstr "{0} için Maliyeti Yeniden Hesapla"
+
msgid "Recovery Period"
msgstr "Kayıt Yap"
@@ -18709,6 +18743,12 @@ msgstr "Sürüm {0}\"ü Aktif Sürüm Olarak Ayarla?"
msgid "Set your default location in profile settings to pick a storage unit."
msgstr "Bir depolama birimi seçmek için varsayılan konumunuzu profil ayarlarınızda belirleyin."
+msgid "Sets what this unit is carried at in inventory."
+msgstr "Bu öğenin envanterde muhasebeleştirildiği değeri ayarlar."
+
+msgid "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "Bu öğenin envanterde muhasebeleştirildiği değeri ayarlar. Fark, envanter ile maliyetin harcandığı hesap arasında kaydedilir: önceki yıl için Dağıtılmamış kârlar veya bu yıl'ın İşçilik veya malzeme gideri."
+
msgid "Settings"
msgstr "Ayarlar"
@@ -19205,6 +19245,9 @@ msgstr "Bazı kayıtlar geri gelmeyecek. Devam etmek için <0>{CONFIRM_WORD}</0>
msgid "Some Shifts"
msgstr "Bazı Vardiyalar"
+msgid "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+msgstr "Muhasebeyi güncelleyebilen birinin, varlıklaştırılabilmesi için üretim maliyetini girmesi gerekir."
+
msgid "Something went wrong. Please try again."
msgstr "Bir şeyler ters gitti. Lütfen tekrar deneyin."
@@ -20328,9 +20371,6 @@ msgstr "Her stok hareketinin yalnızca ekleme kaydı; eldeki tutar, imzalı gird
msgid "The asset moves into its in-service class and starts depreciating from the in-service date."
msgstr "Varlık, hizmet sınıfına geçer ve hizmet tarihinden itibaren amortismana tabi olmaya başlar."
-msgid "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-msgstr "Varlık hiçbir değer taşımayacaktır. Stok kartında adet maliyeti belirleyin, ardından aktifleştirin."
-
msgid "The authorization was refused in Onshape. Save the integration settings to try again."
msgstr "Yetkilendirme Onshape'te reddedildi. Tekrar denemek için entegrasyon ayarlarını kaydedin."
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index e01b3c01e1..7819054dbf 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -1986,6 +1986,15 @@ msgstr "地址行1"
msgid "Address line2"
msgstr "地址行2"
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none."
+msgstr "为资产添加未曾计入的成本,例如未记录任何成本的工单的人工和材料。"
+
+msgid "Adds cost the asset was never charged with, such as the labor and material of a job that recorded none. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "为资产添加未曾计入的成本,例如未记录任何成本的工单的人工和材料。该成本将从其原支出账户计入资产:上年度的未分配利润或本年度的人工、材料费用。"
+
+msgid "Adjust Cost"
+msgstr "调整成本"
+
msgid "Adjustment"
msgstr "调整"
@@ -5163,6 +5172,9 @@ msgstr "转换中…"
msgid "Converts a supplier's purchase unit to your inventory unit on a PO, receipt, or bill line — buy in cartons of 12, stock in eaches."
msgstr "在采购单、收货或账单行中将供应商的采购单位转换为您的库存管理单位 — 按 12 个纸箱采购,按件库存。"
+msgid "Copied ID to clipboard"
+msgstr "已复制ID到剪贴板"
+
msgid "Copied link to clipboard"
msgstr "已复制链接到剪贴板"
@@ -8312,6 +8324,12 @@ msgstr "输入您的私有 OAuth 应用程序的 Onshape URL、客户端 ID 和
msgid "Enter the quantity this movement should have been. An opposite movement for the difference is posted next to the original, in the original's time period."
msgstr "输入此移动应该的数量。差异的相反移动在原始时期内的原始旁边过账。"
+msgid "Enter what it cost to make."
+msgstr "输入该资产的制造成本。"
+
+msgid "Enter what it cost to make. The value is booked to the asset from the account it was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "输入该资产的制造成本。该成本将从其原支出账户计入资产:上年度的未分配利润或本年度的人工、材料费用。"
+
msgid "Entered At Receipt"
msgstr "在收货时输入"
@@ -10271,6 +10289,9 @@ msgstr "ID 和描述是为原材料生成的。"
msgid "If"
msgstr "如果"
+msgid "If depreciation has already run, the next run catches up the months a Straight Line asset took at the old cost."
+msgstr "如果已执行过折旧,下次运行将补算直线法资产按原成本计提的折旧。"
+
msgid "If it can't wait for the next call, the leads on both sides decide."
msgstr "如果不能等到下次通话,双方的负责人会做出决定。"
@@ -13229,6 +13250,9 @@ msgstr "没有条件可以匹配"
msgid "No conversion is required"
msgstr "不需要转换"
+msgid "No cost"
+msgstr "无成本"
+
msgid "No cost has been recorded against this asset yet."
msgstr "尚未针对此资产记录任何成本。"
@@ -13946,6 +13970,9 @@ msgstr "关闭 — 在同步外处理"
msgid "Off — released revisions stay editable"
msgstr "关闭 — 已下达修订版保持可编辑"
+msgid "Offset Account"
+msgstr "抵消账户"
+
msgid "ok"
msgstr "确定"
@@ -16550,6 +16577,13 @@ msgstr "记录"
msgid "Records and posted journals are being sent to and received from this provider."
msgstr "记录和已过账凭证正在从此提供商发送和接收。"
+msgid "Recost"
+msgstr "重新核算成本"
+
+#. placeholder {0}: recostItem.readableId ?? ""
+msgid "Recost {0}"
+msgstr "重新核算{0}的成本"
+
msgid "Recovery Period"
msgstr "注册"
@@ -18709,6 +18743,12 @@ msgstr "将版本 {0} 设置为启用版本?"
msgid "Set your default location in profile settings to pick a storage unit."
msgstr "在个人资料设置中设置默认地点以选择存储单元。"
+msgid "Sets what this unit is carried at in inventory."
+msgstr "设置此项在库存中的账面价值。"
+
+msgid "Sets what this unit is carried at in inventory. The difference is booked between inventory and the account the cost was spent from: Retained Earnings for an earlier year, or this year's labor or material expense."
+msgstr "设置此项在库存中的账面价值。差异将在库存和原支出账户之间记账:上年度的未分配利润或本年度的人工、材料费用。"
+
msgid "Settings"
msgstr "设置"
@@ -19205,6 +19245,9 @@ msgstr "某些记录不会回来。输入 <0>{CONFIRM_WORD}</0> 继续。"
msgid "Some Shifts"
msgstr "某些班次"
+msgid "Someone who can update accounting has to enter what it cost to make before it can be capitalized."
+msgstr "能够更新会计的人员必须先输入该资产的制造成本,才能将其资本化。"
+
msgid "Something went wrong. Please try again."
msgstr "出现问题。请重试。"
@@ -20328,9 +20371,6 @@ msgstr "每个库存变动的追加专用记录;在手数量是其带符号条
msgid "The asset moves into its in-service class and starts depreciating from the in-service date."
msgstr "资产进入其在用资产类别,并从在用日期开始折旧。"
-msgid "The asset would be worth nothing. Set a unit cost on the item, then capitalize it."
-msgstr "该资产价值为零。在该物料上设置件成本,然后将其资本化。"
-
msgid "The authorization was refused in Onshape. Save the integration settings to try again."
msgstr "授权在 Onshape 中被拒绝。保存集成设置以重试。"
diff --git a/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap b/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap
index 9f484ba832..d6849c0e42 100644
--- a/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap
+++ b/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap
@@ -275,7 +275,24 @@ exports[`server function permissions > match the reviewed manifest 1`] = `
},
},
"post-asset-transfer": {
- "create": "accounting",
+ "by": "type",
+ "rules": {
+ "adjustCost": {
+ "update": "accounting",
+ },
+ "attachJob": {
+ "create": "accounting",
+ },
+ "capitalize": {
+ "create": "accounting",
+ },
+ "capitalizeCip": {
+ "create": "accounting",
+ },
+ "return": {
+ "create": "accounting",
+ },
+ },
},
"post-charge": {
"update": "invoicing",
@@ -330,6 +347,9 @@ exports[`server function permissions > match the reviewed manifest 1`] = `
"preview-revenue-recognition-run": {
"view": "accounting",
},
+ "preview-serial-unit-costs": {
+ "view": "accounting",
+ },
"propose-revenue-recognition-run": {
"create": "accounting",
},
@@ -339,6 +359,9 @@ exports[`server function permissions > match the reviewed manifest 1`] = `
"recalculate-revenue-recognition-run": {
"update": "accounting",
},
+ "recost-serial-unit": {
+ "update": "accounting",
+ },
"reschedule": {
"update": "production",
},
diff --git a/packages/server-functions/src/invoke.ts b/packages/server-functions/src/invoke.ts
index 560f6097bb..25c441b0b4 100644
--- a/packages/server-functions/src/invoke.ts
+++ b/packages/server-functions/src/invoke.ts
@@ -48,9 +48,11 @@ const registry = {
import("./preview-asset-capitalization"),
"preview-revenue-recognition-run": () =>
import("./preview-revenue-recognition-run"),
+ "preview-serial-unit-costs": () => import("./preview-serial-unit-costs"),
"propose-revenue-recognition-run": () =>
import("./propose-revenue-recognition-run"),
recalculate: () => import("./recalculate"),
+ "recost-serial-unit": () => import("./recost-serial-unit"),
"recalculate-revenue-recognition-run": () =>
import("./recalculate-revenue-recognition-run"),
reschedule: () => import("./reschedule"),
diff --git a/packages/server-functions/src/lib/asset-transfer.test.ts b/packages/server-functions/src/lib/asset-transfer.test.ts
index 2f6cac105b..dcedeb4706 100644
--- a/packages/server-functions/src/lib/asset-transfer.test.ts
+++ b/packages/server-functions/src/lib/asset-transfer.test.ts
@@ -6,6 +6,7 @@ import { expect, it } from "vitest";
import {
buildCapitalizationLines,
+ buildOffsetLines,
buildReturnToInventoryLines
} from "./asset-transfer.ts";
@@ -131,3 +132,61 @@ it("return to inventory rejects negative or non-finite inputs", () => {
)
).toThrow("finite");
});
+
+it("an entered cost credits an Equity offset as a positive natural balance", () => {
+ // Retained Earnings is Equity: a credit there is stored +x, not −x.
+ expect(
+ buildCapitalizationLines({
+ ...capitalization(4200),
+ creditAccountId: "acct_retained_earnings",
+ creditDescription: "Capitalized Cost",
+ creditAccountType: "equity"
+ })
+ ).toEqual([
+ {
+ accountId: "acct_fixed_asset",
+ description: "Fixed Asset Acquisition",
+ amount: 4200
+ },
+ {
+ accountId: "acct_retained_earnings",
+ description: "Capitalized Cost",
+ amount: 4200
+ }
+ ]);
+});
+
+it("an Expense offset is credited as a negative natural balance", () => {
+ const [, offset] = buildCapitalizationLines({
+ ...capitalization(4200),
+ creditAccountId: "acct_labor",
+ creditDescription: "Capitalized Cost",
+ creditAccountType: "expense"
+ });
+ expect(offset?.amount).toEqual(-4200);
+});
+
+it("a negative offset amount lowers the asset and debits the offset", () => {
+ expect(
+ buildOffsetLines({
+ amount: -25,
+ accountId: "acct_finished_goods",
+ description: "Finished Goods",
+ offsetAccountId: "acct_retained_earnings",
+ offsetDescription: "Recost",
+ offsetAccountType: "equity",
+ label: "Recost journal"
+ }).map((line) => line.amount)
+ ).toEqual([-25, -25]);
+ expect(() =>
+ buildOffsetLines({
+ amount: 0,
+ accountId: "a",
+ description: "a",
+ offsetAccountId: "b",
+ offsetDescription: "b",
+ offsetAccountType: "equity",
+ label: "Recost journal"
+ })
+ ).toThrow("nothing to post");
+});
diff --git a/packages/server-functions/src/lib/asset-transfer.ts b/packages/server-functions/src/lib/asset-transfer.ts
index 707b5b2223..285acec227 100644
--- a/packages/server-functions/src/lib/asset-transfer.ts
+++ b/packages/server-functions/src/lib/asset-transfer.ts
@@ -2,6 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import type { AccountType } from "@carbon/database/ledger";
import { assertBalanced, credit, debit, EPSILON, round } from "@carbon/utils";
/**
@@ -9,11 +10,12 @@ import { assertBalanced, credit, debit, EPSILON, round } from "@carbon/utils";
* asset register — capitalising stock / WIP / CIP into an asset, and returning
* an asset to stock at its net book value.
*
- * Every account these builders touch is class Asset, so a line's stored amount
- * is natural-balance-signed the way `journalLine.amount` is: `debit("asset", x)`
- * is +x and `credit("asset", x)` is −x. Each amount is rounded to the internal
- * scale before it is placed on a line, and every builder refuses to return an
- * unbalanced set of lines.
+ * A line's stored amount is natural-balance-signed the way `journalLine.amount`
+ * is: on an Asset account `debit("asset", x)` is +x and `credit("asset", x)` is
+ * −x. Every account is class Asset except the offset of `buildOffsetLines`
+ * (and an entered cost's credit), which is signed by its own class. Each
+ * amount is rounded to the internal scale before it is placed on a line, and
+ * every builder refuses to return an unbalanced set of lines.
*/
export type PostingLine = {
@@ -42,34 +44,83 @@ function assertAssetLinesBalance(lines: PostingLine[], label: string): void {
assertBalanced(signedDebitTotal, 0, EPSILON, label);
}
+/** A stored, natural-balance-signed amount as a signed debit. */
+function asSignedDebit(type: AccountType, amount: number): number {
+ return amount * debit(type, 1);
+}
+
/**
* Capitalise `cost` into a fixed asset: Dr the asset account, Cr the account
* the value came from — a stock account (Finished Goods / Raw Materials), WIP,
- * or CIP — under `creditDescription`.
+ * or CIP — under `creditDescription`. `creditAccountType` is that account's
+ * class (default asset): an entered cost is credited to whatever account it
+ * was spent from — Retained Earnings is Equity, so its credit is stored +x.
*/
export function buildCapitalizationLines(args: {
cost: number;
assetAccountId: string;
creditAccountId: string;
creditDescription: string;
+ creditAccountType?: AccountType;
}): PostingLine[] {
const cost = ledgerAmount(args.cost, "Asset cost");
// A cost that rounds to nothing at ledger precision has nothing to post.
if (cost <= 0) throw new Error("Asset cost must be positive");
+ return buildOffsetLines({
+ amount: cost,
+ accountId: args.assetAccountId,
+ description: "Fixed Asset Acquisition",
+ offsetAccountId: args.creditAccountId,
+ offsetDescription: args.creditDescription,
+ offsetAccountType: args.creditAccountType ?? "asset",
+ label: "Asset capitalization journal"
+ });
+}
+
+/**
+ * Raise (`amount` > 0) or lower (`amount` < 0) an Asset-class account against
+ * an offset account of any class: Dr asset / Cr offset to raise, the reverse
+ * to lower. Each line is signed by its own account's natural balance, and the
+ * pair is checked as debits = credits.
+ */
+export function buildOffsetLines(args: {
+ amount: number;
+ accountId: string;
+ description: string;
+ offsetAccountId: string;
+ offsetDescription: string;
+ offsetAccountType: AccountType;
+ label: string;
+}): PostingLine[] {
+ const amount = ledgerAmount(args.amount, args.label);
+ if (amount === 0) throw new Error(`${args.label} has nothing to post`);
+ const raise = amount > 0;
+ const size = Math.abs(amount);
const lines: PostingLine[] = [
{
- accountId: args.assetAccountId,
- description: "Fixed Asset Acquisition",
- amount: debit("asset", cost)
+ accountId: args.accountId,
+ description: args.description,
+ amount: raise ? debit("asset", size) : credit("asset", size)
},
{
- accountId: args.creditAccountId,
- description: args.creditDescription,
- amount: credit("asset", cost)
+ accountId: args.offsetAccountId,
+ description: args.offsetDescription,
+ amount: raise
+ ? credit(args.offsetAccountType, size)
+ : debit(args.offsetAccountType, size)
}
];
- assertAssetLinesBalance(lines, "Asset capitalization journal");
+ const [assetLine, offsetLine] = lines as [PostingLine, PostingLine];
+ assertBalanced(
+ round(
+ asSignedDebit("asset", assetLine.amount) +
+ asSignedDebit(args.offsetAccountType, offsetLine.amount)
+ ),
+ 0,
+ EPSILON,
+ args.label
+ );
return lines;
}
diff --git a/packages/server-functions/src/lib/offset-account.ts b/packages/server-functions/src/lib/offset-account.ts
new file mode 100644
index 0000000000..2db0deff8e
--- /dev/null
+++ b/packages/server-functions/src/lib/offset-account.ts
@@ -0,0 +1,43 @@
+// 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 type { KyselyDatabase as DB, Kysely } from "@carbon/database/client";
+import {
+ type AccountType,
+ accountTypeFromClass,
+ isAccountClass
+} from "@carbon/database/ledger";
+import { InvalidInputError } from "../errors";
+
+// The account an entered cost is credited to: where that value was booked
+// when it was spent (an expense this year, Retained Earnings for an earlier
+// one). Any active posting account of the company group.
+export async function getOffsetAccount(
+ db: Kysely<DB>,
+ companyId: string,
+ accountId: string | null | undefined
+): Promise<{ id: string; type: AccountType }> {
+ if (!accountId) {
+ throw new InvalidInputError(
+ "Choose the account the cost was booked to when it was spent"
+ );
+ }
+ const account = await db
+ .selectFrom("account")
+ .innerJoin("company", "company.companyGroupId", "account.companyGroupId")
+ .select(["account.id", "account.class"])
+ .where("account.id", "=", accountId)
+ .where("company.id", "=", companyId)
+ .where("account.active", "=", true)
+ .where("account.isGroup", "=", false)
+ .executeTakeFirst();
+ if (!account || !isAccountClass(account.class)) {
+ throw new InvalidInputError(
+ "The offset account must be an active posting account"
+ );
+ }
+ // The credit is signed by the account's own class (Retained Earnings is
+ // Equity), not as the inventory account it replaces.
+ return { id: account.id, type: accountTypeFromClass(account.class) };
+}
diff --git a/packages/server-functions/src/lib/serial-unit-cost.test.ts b/packages/server-functions/src/lib/serial-unit-cost.test.ts
new file mode 100644
index 0000000000..f087c35360
--- /dev/null
+++ b/packages/server-functions/src/lib/serial-unit-cost.test.ts
@@ -0,0 +1,89 @@
+// 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 { describe, expect, it } from "vitest";
+import { serialUnitCost, type UnitCostLayer } from "./serial-unit-cost";
+
+const fifo = { costingMethod: "FIFO" as const, unitCost: 100, standardCost: 0 };
+
+const layer = (
+ id: string,
+ cost: number,
+ trackedEntityId: string | null = null,
+ remainingQuantity = 1
+): UnitCostLayer => ({
+ id,
+ trackedEntityId,
+ quantity: 1,
+ cost,
+ remainingQuantity
+});
+
+describe("serialUnitCost", () => {
+ it("values a unit at its own layer before the queue", () => {
+ expect(
+ serialUnitCost({
+ itemCost: fifo,
+ layers: [layer("a", 40), layer("b", 60, "SN-1")],
+ childrenByLayer: new Map(),
+ trackedEntityId: "SN-1"
+ })
+ ).toEqual(60);
+ });
+
+ it("values an unstamped unit at the head of the queue, never another unit's layer", () => {
+ expect(
+ serialUnitCost({
+ itemCost: fifo,
+ layers: [layer("b", 60, "SN-1"), layer("a", 40)],
+ childrenByLayer: new Map(),
+ trackedEntityId: "SN-2"
+ })
+ ).toEqual(40);
+ });
+
+ it("adds the layer's price corrections", () => {
+ expect(
+ serialUnitCost({
+ itemCost: fifo,
+ layers: [layer("a", 40)],
+ childrenByLayer: new Map([
+ ["a", [{ quantity: 1, cost: 5, remainingQuantity: 1 }]]
+ ]),
+ trackedEntityId: "SN-2"
+ })
+ ).toEqual(45);
+ });
+
+ it("falls back to the item's unit cost when no layer is open", () => {
+ expect(
+ serialUnitCost({
+ itemCost: fifo,
+ layers: [layer("a", 40, null, 0)],
+ childrenByLayer: new Map(),
+ trackedEntityId: "SN-2"
+ })
+ ).toEqual(100);
+ });
+
+ it("values Standard and Average items at the item's cost", () => {
+ const args = {
+ layers: [layer("a", 40, "SN-1")],
+ childrenByLayer: new Map(),
+ trackedEntityId: "SN-1"
+ };
+ expect(
+ serialUnitCost({
+ ...args,
+ itemCost: { costingMethod: "Standard", unitCost: 7, standardCost: 9 }
+ })
+ ).toEqual(9);
+ expect(
+ serialUnitCost({
+ ...args,
+ itemCost: { costingMethod: "Average", unitCost: 7, standardCost: 9 }
+ })
+ ).toEqual(7);
+ });
+});
diff --git a/packages/server-functions/src/lib/serial-unit-cost.ts b/packages/server-functions/src/lib/serial-unit-cost.ts
new file mode 100644
index 0000000000..af26ae7618
--- /dev/null
+++ b/packages/server-functions/src/lib/serial-unit-cost.ts
@@ -0,0 +1,88 @@
+// 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 type { Database } from "@carbon/database";
+import { orderLayersForConsumption } from "./cost-layer-order";
+
+// What ONE serial unit would leave stock at right now, without consuming
+// anything: the same arithmetic calculateCOGS runs for a quantity of one —
+// Standard at the standard cost, Average at the unit cost, FIFO / LIFO from
+// the unit's own layer first (cost-layer-order.ts), then the unstamped layers,
+// each with its price-correction children, falling back to the item's unit
+// cost when no layer is left. Pure, so a whole item's units are valued from
+// one read of its layers.
+
+export type UnitCostLayer = {
+ id: string;
+ trackedEntityId: string | null;
+ quantity: number;
+ cost: number;
+ remainingQuantity: number;
+};
+
+export type UnitCostChild = {
+ quantity: number;
+ cost: number;
+ remainingQuantity: number;
+};
+
+export type UnitCostBasis = {
+ costingMethod: Database["public"]["Enums"]["itemCostingMethod"];
+ unitCost: number | null;
+ standardCost: number | null;
+};
+
+export function serialUnitCost(args: {
+ itemCost: UnitCostBasis;
+ // Open layers already in FIFO / LIFO order, as calculateCOGS reads them.
+ layers: UnitCostLayer[];
+ // Open price-correction children per layer id, oldest first.
+ childrenByLayer: ReadonlyMap<string, UnitCostChild[]>;
+ trackedEntityId: string;
+}): number {
+ const { itemCost } = args;
+ switch (itemCost.costingMethod) {
+ case "Standard":
+ return Number(itemCost.standardCost ?? 0);
+ case "Average":
+ return Number(itemCost.unitCost ?? 0);
+ case "FIFO":
+ case "LIFO": {
+ let remaining = 1;
+ let total = 0;
+ const ordered = orderLayersForConsumption(args.layers, [
+ args.trackedEntityId
+ ]);
+ for (const layer of ordered) {
+ if (remaining <= 0) break;
+ const layerRemaining = Number(layer.remainingQuantity);
+ if (layerRemaining <= 0) continue;
+ const layerUnitCost =
+ Number(layer.quantity) > 0
+ ? Number(layer.cost) / Number(layer.quantity)
+ : 0;
+ const taken = Math.min(remaining, layerRemaining);
+ total += taken * layerUnitCost;
+ remaining -= taken;
+
+ let unapplied = taken;
+ for (const child of args.childrenByLayer.get(layer.id) ?? []) {
+ if (unapplied <= 0) break;
+ const childRemaining = Number(child.remainingQuantity);
+ const perUnitBump =
+ Number(child.quantity) > 0
+ ? Number(child.cost) / Number(child.quantity)
+ : 0;
+ const applied = Math.min(childRemaining, unapplied);
+ total += applied * perUnitBump;
+ unapplied -= applied;
+ }
+ }
+ if (remaining > 0) total += remaining * Number(itemCost.unitCost ?? 0);
+ return total;
+ }
+ default:
+ throw new Error(`Unsupported costing method: ${itemCost.costingMethod}`);
+ }
+}
diff --git a/packages/server-functions/src/post-asset-transfer/index.ts b/packages/server-functions/src/post-asset-transfer/index.ts
index a703f5236d..2914d5307d 100644
--- a/packages/server-functions/src/post-asset-transfer/index.ts
+++ b/packages/server-functions/src/post-asset-transfer/index.ts
@@ -22,32 +22,42 @@ import {
getDefaultPostingGroup,
resolveInventoryAccount
} from "../lib/get-posting-group";
+import { getOffsetAccount } from "../lib/offset-account";
import {
bookAdjustment,
createAdjustmentJournal
} from "../lib/post-adjustment";
+import { authorize } from "../server-fn-context";
import {
+ ADJUSTABLE_ASSET_STATUSES,
type AssetTransferInput,
CLOSED_JOB_STATUSES,
postAssetTransferInput,
RETURNABLE_ASSET_STATUSES,
- resolveCapitalizationStock
+ resolveCapitalizationCost,
+ resolveCapitalizationStock,
+ statusAfterCostAdjustment
} from "./validators";
export { postAssetTransferInput } from "./validators";
// The single write path for moving value between inventory and the fixed
-// asset register (spec §2, "Fleet bridge"). Four actions, each creating and
+// asset register (spec §2, "Fleet bridge"). Five actions, each creating and
// posting one `fixedAssetTransfer` document in ONE transaction:
//
// capitalize stock → asset at the unit's carrying cost (the serial is
// consumed INTO the asset; Dr class asset / Cr inventory);
-// refused when that cost is zero
+// a unit carried at zero takes the cost the user enters
+// instead (Dr class asset / Cr the chosen offset account),
+// and is refused without one
// return asset → stock at net book value (Dr inventory N / Dr
// accumulated depreciation / Cr class asset at cost)
// attachJob point a job at a Construction in Progress asset and sweep
// its WIP balance there (Dr CIP / Cr WIP), SAP AuC style
// capitalizeCip CIP asset → its in-service class (Dr class / Cr CIP)
+// adjustCost raise an asset's cost after it was capitalized (Dr class
+// asset / Cr the chosen offset account), SAP
+// post-capitalization style
//
// With companySettings.accountingEnabled = false every ledger, entity and
// asset write is identical and no journal is created.
@@ -514,6 +524,12 @@ async function capitalize(
}
const accounting = await loadAccounting(db, companyId, payload.transferDate);
+ // Only read when a cost was entered; whether one may be is decided once the
+ // unit's carrying cost is known, inside the transaction.
+ const offsetAccount =
+ accounting && payload.cost != null
+ ? await getOffsetAccount(db, companyId, payload.offsetAccountId)
+ : null;
const serial = entity.readableId ?? entity.id;
const status = assetClass.isConstructionInProgress
? ("Under Construction" as const)
@@ -654,16 +670,19 @@ async function capitalize(
itemCost: item.itemCost,
accounting: null
});
- const cost = round(booked.cost);
-
- // A unit with no carrying value would become an asset worth nothing, with
- // no journal to say so. The transfer moves the value inventory already
- // holds and cannot invent one, so the unit needs a cost first.
- if (cost <= 0) {
- throw new InvalidInputError(
- `${serial} has no cost in inventory, so the asset would be worth nothing. Set a unit cost on ${item.readableId}, then capitalize it.`
- );
- }
+ // The transfer moves the value inventory already holds. A unit carried at
+ // nothing (a job that recorded no production or material, a no-cost
+ // issue) would become an asset worth nothing with no journal to say so,
+ // so it takes the cost the user entered instead — booked from the offset
+ // account that value was spent from — and is refused without one.
+ const resolved = resolveCapitalizationCost({
+ carried: round(booked.cost),
+ entered: payload.cost == null ? null : round(payload.cost),
+ serial,
+ itemReadableId: item.readableId
+ });
+ if ("error" in resolved) throw new InvalidInputError(resolved.error);
+ const cost = resolved.cost;
let journalId: string | null = null;
if (accounting) {
@@ -671,6 +690,14 @@ async function capitalize(
item.replenishmentSystem,
accounting.accountDefaults
);
+ const credit =
+ resolved.source === "entered" && offsetAccount
+ ? {
+ account: offsetAccount.id,
+ description: "Capitalized Cost",
+ type: offsetAccount.type
+ }
+ : { ...inventoryAccount, type: "asset" as const };
journalId = await postAssetJournal(trx, {
accounting,
companyId,
@@ -680,8 +707,9 @@ async function capitalize(
lines: buildCapitalizationLines({
cost,
assetAccountId: assetClass.assetAccountId,
- creditAccountId: inventoryAccount.account,
- creditDescription: inventoryAccount.description
+ creditAccountId: credit.account,
+ creditDescription: credit.description,
+ creditAccountType: credit.type
}),
documentId: transfer.id,
tags: { locationId, fixedAssetClassId: assetClass.id, itemId }
@@ -1391,6 +1419,149 @@ async function capitalizeCip(
});
}
+async function adjustCost(
+ db: Db,
+ payload: Scoped<"adjustCost">
+): Promise<AssetTransferResult> {
+ const { companyId, userId, locationId } = payload;
+
+ const asset = await getAsset(db, companyId, payload.fixedAssetId);
+ if (!ADJUSTABLE_ASSET_STATUSES.has(asset.status)) {
+ throw new InvalidInputError(
+ `Asset ${asset.fixedAssetId} is ${asset.status}; only an Active or Fully Depreciated asset's cost can be adjusted`
+ );
+ }
+ const [assetClass] = await inOrder([
+ () => getAssetClass(db, companyId, asset.fixedAssetClassId),
+ () =>
+ assertCompanyRecords(db, "location", [locationId], companyId, "Location")
+ ]);
+
+ const amount = round(payload.amount);
+ if (amount <= 0) {
+ throw new InvalidInputError("The cost adjustment must be more than zero");
+ }
+
+ const accounting = await loadAccounting(db, companyId, payload.transferDate);
+ const offsetAccount = accounting
+ ? await getOffsetAccount(db, companyId, payload.offsetAccountId)
+ : null;
+
+ return db.transaction().execute(async (trx): Promise<AssetTransferResult> => {
+ // Re-read under a row lock: a concurrent run, disposal or adjustment
+ // changes the values the new status is derived from.
+ const current = await trx
+ .selectFrom("fixedAsset")
+ .select([
+ "status",
+ "acquisitionCost",
+ "accumulatedDepreciation",
+ "residualValuePercent"
+ ])
+ .where("id", "=", asset.id)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirstOrThrow();
+ if (!ADJUSTABLE_ASSET_STATUSES.has(current.status)) {
+ throw new InvalidInputError(
+ `Asset ${asset.fixedAssetId} is ${current.status}; only an Active or Fully Depreciated asset's cost can be adjusted`
+ );
+ }
+ const acquisitionCost = round(Number(current.acquisitionCost) + amount);
+
+ const transferId = await getNextSequence(
+ trx,
+ "fixedAssetTransfer",
+ companyId
+ );
+ const transfer = await trx
+ .insertInto("fixedAssetTransfer")
+ .values({
+ transferId,
+ type: "Cost Adjustment",
+ sourceType: "Manual",
+ fixedAssetId: asset.id,
+ itemId: asset.itemId,
+ trackedEntityId: asset.trackedEntityId,
+ locationId,
+ quantity: 1,
+ transferDate: payload.transferDate,
+ amount: 0,
+ accumulatedDepreciation: Number(current.accumulatedDepreciation),
+ status: "Draft",
+ companyId,
+ createdBy: userId
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ let journalId: string | null = null;
+ if (accounting && offsetAccount) {
+ journalId = await postAssetJournal(trx, {
+ accounting,
+ companyId,
+ userId,
+ postingDate: payload.transferDate,
+ description: `Cost Adjustment ${asset.fixedAssetId}`,
+ lines: buildCapitalizationLines({
+ cost: amount,
+ assetAccountId: assetClass.assetAccountId,
+ creditAccountId: offsetAccount.id,
+ creditDescription: "Capitalized Cost",
+ creditAccountType: offsetAccount.type
+ }),
+ documentId: transfer.id,
+ tags: {
+ locationId,
+ fixedAssetClassId: assetClass.id,
+ itemId: asset.itemId
+ }
+ });
+ }
+
+ // Depreciation already taken stays; the next run catches a Straight Line
+ // asset up on the months it took at the old cost (buildDepreciationLines).
+ const adjusted = await trx
+ .updateTable("fixedAsset")
+ .set({
+ acquisitionCost,
+ status: statusAfterCostAdjustment({
+ status: current.status,
+ acquisitionCost,
+ accumulatedDepreciation: Number(current.accumulatedDepreciation),
+ residualValuePercent: Number(current.residualValuePercent)
+ }),
+ locationId: asset.locationId ?? locationId,
+ updatedAt: datetime.timestamp(),
+ updatedBy: userId
+ })
+ .where("id", "=", asset.id)
+ .where("companyId", "=", companyId)
+ .where("status", "in", [...ADJUSTABLE_ASSET_STATUSES])
+ .executeTakeFirst();
+ if (!adjusted.numUpdatedRows) {
+ throw new InvalidInputError(
+ `Asset ${asset.fixedAssetId} changed status while its cost was being adjusted`
+ );
+ }
+
+ await postTransfer(trx, {
+ id: transfer.id,
+ amount,
+ journalId,
+ companyId,
+ userId
+ });
+
+ return {
+ id: transfer.id,
+ transferId,
+ fixedAssetId: asset.id,
+ fixedAssetReadableId: asset.fixedAssetId
+ };
+ });
+}
+
/**
* Creates and posts one `fixedAssetTransfer` document between inventory and
* the fixed asset register, per `type`. Every record id in the input is
@@ -1399,11 +1570,26 @@ async function capitalizeCip(
const postAssetTransfer = defineServerFn({
name: "post-asset-transfer",
input: postAssetTransferInput,
- permissions: { create: "accounting" },
+ // Moving value the books already hold is `create`; putting a number of
+ // your own on an asset (an entered cost, a cost adjustment) is recosting,
+ // which takes `update`.
+ permissions: {
+ by: "type",
+ rules: {
+ capitalize: { create: "accounting" },
+ return: { create: "accounting" },
+ attachJob: { create: "accounting" },
+ capitalizeCip: { create: "accounting" },
+ adjustCost: { update: "accounting" }
+ }
+ },
async run(ctx, input): Promise<AssetTransferResult> {
const { db, companyId, userId } = ctx;
switch (input.type) {
case "capitalize":
+ if (input.cost != null) {
+ await authorize(ctx, { update: "accounting" });
+ }
return capitalize(db, { ...input, companyId, userId });
case "return":
return returnToInventory(db, { ...input, companyId, userId });
@@ -1411,6 +1597,8 @@ const postAssetTransfer = defineServerFn({
return attachJob(db, { ...input, companyId, userId });
case "capitalizeCip":
return capitalizeCip(db, { ...input, companyId, userId });
+ case "adjustCost":
+ return adjustCost(db, { ...input, companyId, userId });
}
}
});
diff --git a/packages/server-functions/src/post-asset-transfer/validators.test.ts b/packages/server-functions/src/post-asset-transfer/validators.test.ts
index 1d5004a1f8..6f91b35ec5 100644
--- a/packages/server-functions/src/post-asset-transfer/validators.test.ts
+++ b/packages/server-functions/src/post-asset-transfer/validators.test.ts
@@ -8,7 +8,9 @@ import {
CLOSED_JOB_STATUSES,
postAssetTransferInput,
RETURNABLE_ASSET_STATUSES,
- resolveCapitalizationStock
+ resolveCapitalizationCost,
+ resolveCapitalizationStock,
+ statusAfterCostAdjustment
} from "./validators";
it("capitalize accepts the inventory payload with its optional fields absent", () => {
@@ -183,3 +185,100 @@ it("status sets match the plan", () => {
expect(RETURNABLE_ASSET_STATUSES.has("Under Construction")).toEqual(false);
expect(CLOSED_JOB_STATUSES.has("Paused")).toEqual(false);
});
+
+it("adjustCost requires a positive amount", () => {
+ const base = {
+ type: "adjustCost",
+ fixedAssetId: "fa_1",
+ locationId: "loc_1",
+ transferDate: "2026-10-08"
+ };
+ expect(postAssetTransferInput.safeParse({ ...base, amount: 0 }).success).toBe(
+ false
+ );
+ expect(
+ postAssetTransferInput.safeParse({ ...base, amount: -5 }).success
+ ).toBe(false);
+ expect(
+ postAssetTransferInput.safeParse({
+ ...base,
+ amount: 1250,
+ offsetAccountId: "acc_re"
+ }).success
+ ).toBe(true);
+});
+
+it("capitalize takes the inventory cost when the unit carries one", () => {
+ expect(
+ resolveCapitalizationCost({
+ carried: 60,
+ entered: null,
+ serial: "SN-1",
+ itemReadableId: "RW"
+ })
+ ).toEqual({ cost: 60, source: "inventory" });
+});
+
+it("capitalize refuses an entered cost for a unit that carries one", () => {
+ const resolved = resolveCapitalizationCost({
+ carried: 60,
+ entered: 90,
+ serial: "SN-1",
+ itemReadableId: "RW"
+ });
+ expect("error" in resolved && resolved.error).toMatch(
+ /SN-1 is carried in inventory at a cost/
+ );
+});
+
+it("capitalize takes the entered cost for a unit carried at zero", () => {
+ expect(
+ resolveCapitalizationCost({
+ carried: 0,
+ entered: 4200,
+ serial: "SN-2",
+ itemReadableId: "RW"
+ })
+ ).toEqual({ cost: 4200, source: "entered" });
+});
+
+it("capitalize refuses a unit carried at zero with no entered cost", () => {
+ const resolved = resolveCapitalizationCost({
+ carried: 0,
+ entered: null,
+ serial: "SN-2",
+ itemReadableId: "RW"
+ });
+ expect("error" in resolved && resolved.error).toMatch(
+ /SN-2 has no cost in inventory/
+ );
+});
+
+it("a Fully Depreciated asset whose cost is raised above its residual returns to Active", () => {
+ // A zero-cost asset a run marked Fully Depreciated, now worth 1,000.
+ expect(
+ statusAfterCostAdjustment({
+ status: "Fully Depreciated",
+ acquisitionCost: 1000,
+ accumulatedDepreciation: 0,
+ residualValuePercent: 20
+ })
+ ).toEqual("Active");
+ // Raised, but still at or below its residual: nothing left to depreciate.
+ expect(
+ statusAfterCostAdjustment({
+ status: "Fully Depreciated",
+ acquisitionCost: 1000,
+ accumulatedDepreciation: 800,
+ residualValuePercent: 20
+ })
+ ).toEqual("Fully Depreciated");
+ expect(
+ statusAfterCostAdjustment({
+ status: "Active",
+ acquisitionCost: 1000,
+ accumulatedDepreciation: 0,
+ residualValuePercent: 0
+ })
+ ).toEqual("Active");
+});
diff --git a/packages/server-functions/src/post-asset-transfer/validators.ts b/packages/server-functions/src/post-asset-transfer/validators.ts
index ea37813ddf..94ffb8fd4b 100644
--- a/packages/server-functions/src/post-asset-transfer/validators.ts
+++ b/packages/server-functions/src/post-asset-transfer/validators.ts
@@ -3,11 +3,12 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import type { Database } from "@carbon/database";
+import { EPSILON } from "@carbon/utils";
import { z } from "zod";
/**
* Input contract and pure helpers for `post-asset-transfer`. No I/O and no
- * imports beyond zod and the generated types, so the server function's own
+ * imports beyond zod, the generated types and `@carbon/utils`, so the server function's own
* logic can be pinned without a database.
*/
@@ -29,7 +30,14 @@ export const capitalizeValidator = z.object({
transferDate: calendarDate,
name: z.string().optional().nullable(),
// An existing Draft asset to fill; otherwise the function creates one.
- fixedAssetId: z.string().optional().nullable()
+ fixedAssetId: z.string().optional().nullable(),
+ // What the unit cost to make, for a unit inventory carries at nothing (a job
+ // that recorded no production or material, a no-cost issue). Refused for a
+ // unit that carries a cost: that value moves from inventory as it is.
+ cost: z.number().positive().optional().nullable(),
+ // The other side of an entered cost: where that value was booked when it
+ // was spent. Required with `cost` when accounting is enabled.
+ offsetAccountId: z.string().optional().nullable()
});
/** Return an asset to stock at its net book value. */
@@ -56,11 +64,26 @@ export const capitalizeCipValidator = z.object({
inServiceDate: calendarDate
});
+/**
+ * Raise an asset's cost after it was capitalized (post-capitalization): Dr the
+ * class asset account / Cr `offsetAccountId`. Raise only — lowering a cost is
+ * a write-down.
+ */
+export const adjustCostValidator = z.object({
+ type: z.literal("adjustCost"),
+ fixedAssetId: z.string().min(1),
+ amount: z.number().positive(),
+ offsetAccountId: z.string().optional().nullable(),
+ locationId: z.string().min(1),
+ transferDate: calendarDate
+});
+
export const postAssetTransferInput = z.discriminatedUnion("type", [
capitalizeValidator,
returnValidator,
attachJobValidator,
- capitalizeCipValidator
+ capitalizeCipValidator,
+ adjustCostValidator
]);
export type AssetTransferInput = z.output<typeof postAssetTransferInput>;
@@ -106,3 +129,54 @@ export const CLOSED_JOB_STATUSES: ReadonlySet<
export const RETURNABLE_ASSET_STATUSES: ReadonlySet<
Database["public"]["Enums"]["fixedAssetStatus"]
> = new Set(["Active", "Fully Depreciated"] as const);
+
+/** Asset statuses whose cost can be adjusted. */
+export const ADJUSTABLE_ASSET_STATUSES: ReadonlySet<
+ Database["public"]["Enums"]["fixedAssetStatus"]
+> = new Set(["Active", "Fully Depreciated"] as const);
+
+/**
+ * The cost a unit is capitalized at: what inventory carries it at, or — only
+ * when that is nothing — the cost the user entered. Returns the refusal
+ * message instead when neither gives the asset a value, or when a cost is
+ * entered for a unit that already carries one.
+ */
+export function resolveCapitalizationCost(args: {
+ carried: number;
+ entered: number | null | undefined;
+ serial: string;
+ itemReadableId: string;
+}): { cost: number; source: "inventory" | "entered" } | { error: string } {
+ const { carried, entered, serial, itemReadableId } = args;
+ if (carried > 0) {
+ if (entered != null) {
+ return {
+ error: `${serial} is carried in inventory at a cost, so it is capitalized at that cost; clear the entered cost`
+ };
+ }
+ return { cost: carried, source: "inventory" };
+ }
+ if (entered != null && entered > 0) {
+ return { cost: entered, source: "entered" };
+ }
+ return {
+ error: `${serial} has no cost in inventory, so the asset would be worth nothing. Enter what it cost, or set a unit cost on ${itemReadableId}, then capitalize it.`
+ };
+}
+
+/**
+ * An asset's status once its cost is raised: a Fully Depreciated asset whose
+ * net book value is above its residual again has depreciation left to take,
+ * so it returns to Active and the depreciation runs pick it up.
+ */
+export function statusAfterCostAdjustment(args: {
+ status: Database["public"]["Enums"]["fixedAssetStatus"];
+ acquisitionCost: number;
+ accumulatedDepreciation: number;
+ residualValuePercent: number;
+}): Database["public"]["Enums"]["fixedAssetStatus"] {
+ if (args.status !== "Fully Depreciated") return args.status;
+ const residual = args.acquisitionCost * (args.residualValuePercent / 100);
+ const remaining = args.acquisitionCost - args.accumulatedDepreciation;
+ return remaining - residual > EPSILON ? "Active" : args.status;
+}
diff --git a/packages/server-functions/src/post-reimbursement/post-reimbursement-test-fixture.ts b/packages/server-functions/src/post-reimbursement/post-reimbursement-test-fixture.ts
index 06b8b631e3..f76b3b106a 100644
--- a/packages/server-functions/src/post-reimbursement/post-reimbursement-test-fixture.ts
+++ b/packages/server-functions/src/post-reimbursement/post-reimbursement-test-fixture.ts
@@ -11,7 +11,7 @@ import { connectLocalTestDatabase } from "../local-database-test-fixture";
// suite actually exercises. They are pointed at one filler posting account so
// the row can exist at all — the payable resolution only ever reads
// `employeeReimbursementsPayableAccount` and `payablesAccount`.
-const FILLER_ACCOUNT_DEFAULTS = [
+export const FILLER_ACCOUNT_DEFAULTS = [
"salesAccount",
"salesDiscountAccount",
"costOfGoodsSoldAccount",
diff --git a/packages/server-functions/src/preview-asset-capitalization/preview-asset-capitalization.test.ts b/packages/server-functions/src/preview-asset-capitalization/preview-asset-capitalization.test.ts
index f4308d6e02..3eda51ad99 100644
--- a/packages/server-functions/src/preview-asset-capitalization/preview-asset-capitalization.test.ts
+++ b/packages/server-functions/src/preview-asset-capitalization/preview-asset-capitalization.test.ts
@@ -2,10 +2,15 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import type { KyselyDatabase } from "@carbon/database/client";
+import { type Insertable, sql } from "kysely";
import { expect } from "vitest";
import { databaseTest } from "../local-database-test-fixture";
import postAssetTransfer from "../post-asset-transfer";
import { chargeFixture } from "../post-charge/post-charge-test-fixture";
+import { FILLER_ACCOUNT_DEFAULTS } from "../post-reimbursement/post-reimbursement-test-fixture";
+import previewSerialUnitCosts from "../preview-serial-unit-costs";
+import recostSerialUnit from "../recost-serial-unit";
import { ServerFnContext } from "../server-fn-context";
import previewAssetCapitalization from "./index";
@@ -229,3 +234,449 @@ databaseTest(
}
}
);
+
+databaseTest(
+ "a unit with no cost in inventory is capitalized at the cost entered for it",
+ async () => {
+ const f = await chargeFixture();
+ try {
+ const c = await capitalizationFixture(f, 0);
+ const serial = await c.unit("SN-3");
+
+ const posted = await postAssetTransfer(context(f), {
+ type: "capitalize",
+ fixedAssetClassId: c.assetClass.id,
+ itemId: c.itemId,
+ trackedEntityId: serial,
+ locationId: c.locationId,
+ transferDate: "2026-01-02",
+ cost: 4200
+ });
+ if (posted.error) throw posted.error;
+
+ const asset = await f.db
+ .selectFrom("fixedAsset")
+ .select(["acquisitionCost", "status"])
+ .where("id", "=", posted.data.fixedAssetId)
+ .executeTakeFirstOrThrow();
+ expect(Number(asset.acquisitionCost)).toEqual(4200);
+ expect(asset.status).toEqual("Active");
+ const transfer = await f.db
+ .selectFrom("fixedAssetTransfer")
+ .select(["amount", "type", "status"])
+ .where("fixedAssetId", "=", posted.data.fixedAssetId)
+ .executeTakeFirstOrThrow();
+ expect(Number(transfer.amount)).toEqual(4200);
+ expect(transfer.type).toEqual("Capitalization");
+ expect(transfer.status).toEqual("Posted");
+ // The unit left stock all the same.
+ const entity = await f.db
+ .selectFrom("trackedEntity")
+ .select("status")
+ .where("id", "=", serial)
+ .executeTakeFirstOrThrow();
+ expect(entity.status).toEqual("Consumed");
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "a cost entered for a unit that carries one is refused",
+ async () => {
+ const f = await chargeFixture();
+ try {
+ const c = await capitalizationFixture(f, 100);
+ const serial = await c.unit("SN-4");
+
+ const posted = await postAssetTransfer(context(f), {
+ type: "capitalize",
+ fixedAssetClassId: c.assetClass.id,
+ itemId: c.itemId,
+ trackedEntityId: serial,
+ locationId: c.locationId,
+ transferDate: "2026-01-02",
+ cost: 4200
+ });
+ expect(posted.error?.message).toMatch(
+ /SN-4 is carried in inventory at a cost/
+ );
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "adjustCost raises a zero-cost asset's cost and brings it back to Active",
+ async () => {
+ const f = await chargeFixture();
+ try {
+ const c = await capitalizationFixture(f, 0);
+ // What Make to Asset leaves behind for a job with no WIP: an asset at
+ // zero, which a depreciation run then marks Fully Depreciated.
+ const asset = await f.db
+ .insertInto("fixedAsset")
+ .values({
+ fixedAssetId: `${f.companyId}-FA`,
+ name: "Reaction Wheel SN-5",
+ fixedAssetClassId: c.assetClass.id,
+ itemId: c.itemId,
+ locationId: c.locationId,
+ depreciationMethod: "Straight Line",
+ usefulLifeMonths: 60,
+ residualValuePercent: 20,
+ acquisitionCost: 0,
+ acquisitionDate: "2026-01-02",
+ depreciationStartDate: "2026-01-02",
+ status: "Fully Depreciated",
+ quantity: 1,
+ companyId: f.companyId,
+ createdBy: "system"
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+
+ const adjust = (amount: number) =>
+ postAssetTransfer(context(f), {
+ type: "adjustCost",
+ fixedAssetId: asset.id,
+ amount,
+ locationId: c.locationId,
+ transferDate: "2026-03-01"
+ });
+
+ const first = await adjust(5000);
+ if (first.error) throw first.error;
+ const second = await adjust(250);
+ if (second.error) throw second.error;
+
+ const adjusted = await f.db
+ .selectFrom("fixedAsset")
+ .select(["acquisitionCost", "status"])
+ .where("id", "=", asset.id)
+ .executeTakeFirstOrThrow();
+ expect(Number(adjusted.acquisitionCost)).toEqual(5250);
+ expect(adjusted.status).toEqual("Active");
+
+ const transfers = await f.db
+ .selectFrom("fixedAssetTransfer")
+ .select(["amount", "type", "sourceType", "status"])
+ .where("fixedAssetId", "=", asset.id)
+ .orderBy("transferId")
+ .execute();
+ expect(
+ transfers.map((t) => [Number(t.amount), t.type, t.sourceType, t.status])
+ ).toEqual([
+ [5000, "Cost Adjustment", "Manual", "Posted"],
+ [250, "Cost Adjustment", "Manual", "Posted"]
+ ]);
+
+ // A disposed asset is off the books; its cost cannot change.
+ await f.db
+ .updateTable("fixedAsset")
+ .set({ status: "Disposed" })
+ .where("id", "=", asset.id)
+ .execute();
+ const refused = await adjust(100);
+ expect(refused.error?.message).toMatch(/is Disposed/);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "each serial's inventory cost is what capitalizing it would book",
+ async () => {
+ const f = await chargeFixture();
+ try {
+ const c = await capitalizationFixture(f, 100);
+ const own = await c.unit("SN-6");
+ const queued = await c.unit("SN-7");
+ await f.db
+ .insertInto("costLedger")
+ .values([
+ {
+ itemLedgerType: "Positive Adjmt.",
+ costLedgerType: "Direct Cost",
+ itemId: c.itemId,
+ quantity: 1,
+ cost: 60,
+ remainingQuantity: 1,
+ postingDate: "2026-01-01",
+ trackedEntityId: own,
+ companyId: f.companyId
+ },
+ {
+ itemLedgerType: "Positive Adjmt.",
+ costLedgerType: "Direct Cost",
+ itemId: c.itemId,
+ quantity: 1,
+ cost: 40,
+ remainingQuantity: 1,
+ postingDate: "2026-01-01",
+ companyId: f.companyId
+ }
+ ])
+ .execute();
+
+ const listed = await previewSerialUnitCosts(context(f), {
+ itemId: c.itemId,
+ locationId: c.locationId
+ });
+ if (listed.error) throw listed.error;
+ expect(listed.data.costs).toEqual({ [own]: 60, [queued]: 40 });
+ expect(await preview(f, own)).toEqual(60);
+ expect(await preview(f, queued)).toEqual(40);
+
+ // A unit that has left stock is not listed.
+ await f.db
+ .insertInto("itemLedger")
+ .values({
+ entryType: "Negative Adjmt.",
+ itemId: c.itemId,
+ quantity: -1,
+ locationId: c.locationId,
+ trackedEntityId: queued,
+ postingDate: "2026-01-03",
+ companyId: f.companyId
+ })
+ .execute();
+ const after = await previewSerialUnitCosts(context(f), {
+ itemId: c.itemId
+ });
+ if (after.error) throw after.error;
+ expect(Object.keys(after.data.costs)).toEqual([own]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+// Accounting on, with a Retained Earnings (Equity) account to credit: the
+// journal must sign each line by its own account's class.
+async function withAccounting(f: Fixture) {
+ const { db, companyId } = f;
+ const company = await db
+ .selectFrom("company")
+ .select("companyGroupId")
+ .where("id", "=", companyId)
+ .executeTakeFirstOrThrow();
+ const companyGroupId = company.companyGroupId;
+ if (!companyGroupId) throw new Error("Expected a company group");
+ const retainedEarnings = f.account("retained-earnings");
+ await db.transaction().execute(async (trx) => {
+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);
+ await trx
+ .insertInto("account")
+ .values({
+ id: retainedEarnings,
+ name: "Retained Earnings",
+ class: "Equity",
+ incomeBalance: "Balance Sheet",
+ companyGroupId,
+ createdBy: "system"
+ })
+ .execute();
+ await trx
+ .insertInto("accountDefault")
+ .values({
+ companyId,
+ ...Object.fromEntries(
+ FILLER_ACCOUNT_DEFAULTS.map((column) => [column, f.account("bank")])
+ ),
+ payablesAccount: f.account("bank"),
+ employeeReimbursementsPayableAccount: f.account("bank")
+ } as unknown as Insertable<KyselyDatabase["accountDefault"]>)
+ .execute();
+ await trx
+ .updateTable("companySettings")
+ .set({ accountingEnabled: true })
+ .where("id", "=", companyId)
+ .execute();
+ });
+ return { retainedEarnings };
+}
+
+async function journalLines(f: Fixture, journalId: string | null) {
+ if (!journalId) throw new Error("Expected a journal");
+ const lines = await f.db
+ .selectFrom("journalLine")
+ .select(["accountId", "amount"])
+ .where("journalId", "=", journalId)
+ .orderBy("amount", "desc")
+ .orderBy("accountId")
+ .execute();
+ return lines.map((line) => [line.accountId, Number(line.amount)]);
+}
+
+databaseTest(
+ "an entered cost and a cost adjustment credit Retained Earnings",
+ async () => {
+ const f = await chargeFixture();
+ try {
+ const c = await capitalizationFixture(f, 0);
+ const { retainedEarnings } = await withAccounting(f);
+ const serial = await c.unit("SN-8");
+
+ const posted = await postAssetTransfer(context(f), {
+ type: "capitalize",
+ fixedAssetClassId: c.assetClass.id,
+ itemId: c.itemId,
+ trackedEntityId: serial,
+ locationId: c.locationId,
+ transferDate: "2026-01-02",
+ cost: 4200,
+ offsetAccountId: retainedEarnings
+ });
+ if (posted.error) throw posted.error;
+ const capitalization = await f.db
+ .selectFrom("fixedAssetTransfer")
+ .select("journalId")
+ .where("id", "=", posted.data.id!)
+ .executeTakeFirstOrThrow();
+ // Dr the class asset account (an Expense-class account in this
+ // fixture: +4200 is a debit) / Cr Retained Earnings (Equity: +4200 is
+ // a credit).
+ expect(await journalLines(f, capitalization.journalId)).toEqual([
+ [f.account("expense"), 4200],
+ [retainedEarnings, 4200]
+ ]);
+
+ const adjusted = await postAssetTransfer(context(f), {
+ type: "adjustCost",
+ fixedAssetId: posted.data.fixedAssetId,
+ amount: 800,
+ offsetAccountId: retainedEarnings,
+ locationId: c.locationId,
+ transferDate: "2026-01-03"
+ });
+ if (adjusted.error) throw adjusted.error;
+ const adjustment = await f.db
+ .selectFrom("fixedAssetTransfer")
+ .select("journalId")
+ .where("id", "=", adjusted.data.id!)
+ .executeTakeFirstOrThrow();
+ expect(await journalLines(f, adjustment.journalId)).toEqual([
+ [f.account("expense"), 800],
+ [retainedEarnings, 800]
+ ]);
+
+ // Without an offset account there is nothing to credit.
+ const refused = await postAssetTransfer(context(f), {
+ type: "adjustCost",
+ fixedAssetId: posted.data.fixedAssetId,
+ amount: 100,
+ locationId: c.locationId,
+ transferDate: "2026-01-03"
+ });
+ expect(refused.error?.message).toMatch(/Choose the account/);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "recosting a unit carried at zero gives it a layer of its own, booked from the offset",
+ async () => {
+ const f = await chargeFixture();
+ try {
+ const c = await capitalizationFixture(f, 0);
+ const { retainedEarnings } = await withAccounting(f);
+ const serial = await c.unit("SN-9");
+ // Completed by a job that recorded nothing: a layer at zero.
+ await f.db
+ .insertInto("costLedger")
+ .values({
+ itemLedgerType: "Output",
+ costLedgerType: "Direct Cost",
+ itemId: c.itemId,
+ quantity: 1,
+ cost: 0,
+ remainingQuantity: 1,
+ postingDate: "2026-01-01",
+ companyId: f.companyId
+ })
+ .execute();
+
+ const recost = (unitCost: number) =>
+ recostSerialUnit(context(f), {
+ trackedEntityId: serial,
+ unitCost,
+ offsetAccountId: retainedEarnings,
+ postingDate: "2026-01-02"
+ });
+
+ const raised = await recost(500);
+ if (raised.error) throw raised.error;
+ expect(raised.data.previousCost).toEqual(0);
+ // Dr inventory (Raw Materials, Asset) / Cr Retained Earnings (Equity).
+ expect(await journalLines(f, raised.data.journalId)).toEqual([
+ [f.account("bank"), 500],
+ [retainedEarnings, 500]
+ ]);
+
+ const costs = await previewSerialUnitCosts(context(f), {
+ itemId: c.itemId
+ });
+ if (costs.error) throw costs.error;
+ expect(costs.data.costs).toEqual({ [serial]: 500 });
+
+ // A write-down reverses the sides.
+ const lowered = await recost(400);
+ if (lowered.error) throw lowered.error;
+ expect(lowered.data.previousCost).toEqual(500);
+ expect(await journalLines(f, lowered.data.journalId)).toEqual([
+ [f.account("bank"), -100],
+ [retainedEarnings, -100]
+ ]);
+ expect((await recost(400)).error?.message).toMatch(
+ /already carried at that cost/
+ );
+
+ // Capitalizing now moves the recosted value out of inventory.
+ expect(await preview(f, serial)).toEqual(400);
+ const posted = await postAssetTransfer(context(f), {
+ type: "capitalize",
+ fixedAssetClassId: c.assetClass.id,
+ itemId: c.itemId,
+ trackedEntityId: serial,
+ locationId: c.locationId,
+ transferDate: "2026-01-03"
+ });
+ if (posted.error) throw posted.error;
+ const asset = await f.db
+ .selectFrom("fixedAsset")
+ .select("acquisitionCost")
+ .where("id", "=", posted.data.fixedAssetId)
+ .executeTakeFirstOrThrow();
+ expect(Number(asset.acquisitionCost)).toEqual(400);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest("an Average item's unit cannot be recosted", async () => {
+ const f = await chargeFixture();
+ try {
+ const c = await capitalizationFixture(f, 0);
+ await f.db
+ .updateTable("itemCost")
+ .set({ costingMethod: "Average" })
+ .where("itemId", "=", c.itemId)
+ .execute();
+ const serial = await c.unit("SN-10");
+ const result = await recostSerialUnit(context(f), {
+ trackedEntityId: serial,
+ unitCost: 500,
+ postingDate: "2026-01-02"
+ });
+ expect(result.error?.message).toMatch(/uses Average costing/);
+ } finally {
+ await f.cleanup();
+ }
+});
diff --git a/packages/server-functions/src/preview-serial-unit-costs/index.ts b/packages/server-functions/src/preview-serial-unit-costs/index.ts
new file mode 100644
index 0000000000..2b5aef93a2
--- /dev/null
+++ b/packages/server-functions/src/preview-serial-unit-costs/index.ts
@@ -0,0 +1,172 @@
+// 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.
+
+// What each serial unit of an item on hand would leave stock at right now —
+// the cost a shipment, a scrap or a capitalization would relieve for it — so
+// the inventory page can show it per serial number. Read-only: the layers are
+// valued with `serialUnitCost`, the same arithmetic calculateCOGS runs, from
+// one read of the item's open layers.
+
+import type { Database } from "@carbon/database";
+import { inOrder } from "@carbon/database/rows";
+import { round } from "@carbon/utils";
+import { sql } from "kysely";
+import { z } from "zod";
+import { defineServerFn } from "../define-server-fn";
+import { NotFoundError } from "../errors";
+import { serialUnitCost, type UnitCostChild } from "../lib/serial-unit-cost";
+
+export const previewSerialUnitCostsInput = z.object({
+ itemId: z.string().min(1),
+ // Only the units on hand at this location; every location when absent.
+ locationId: z.string().optional().nullable()
+});
+
+export type SerialUnitCosts = {
+ costs: Record<string, number>;
+ // Only a FIFO / LIFO item's unit can be recosted on its own.
+ costingMethod: Database["public"]["Enums"]["itemCostingMethod"] | null;
+};
+
+const previewSerialUnitCosts = defineServerFn({
+ name: "preview-serial-unit-costs",
+ input: previewSerialUnitCostsInput,
+ // Inventory value is accounting data: the valuation report and the
+ // capitalization preview take the same permission.
+ permissions: { view: "accounting" },
+ async run(
+ { db, companyId },
+ { itemId, locationId }
+ ): Promise<SerialUnitCosts> {
+ const item = await db
+ .selectFrom("item")
+ .select("itemTrackingType")
+ .where("id", "=", itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!item) throw new NotFoundError("Item not found");
+ if (item.itemTrackingType !== "Serial") {
+ return { costs: {}, costingMethod: null };
+ }
+
+ let onHandQuery = db
+ .selectFrom("itemLedger")
+ .select("trackedEntityId")
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
+ .where("trackedEntityId", "is not", null)
+ .groupBy("trackedEntityId")
+ .having(sql<number>`SUM("quantity")`, ">", 0);
+ if (locationId)
+ onHandQuery = onHandQuery.where("locationId", "=", locationId);
+
+ const [onHand, itemCost] = await inOrder([
+ () => onHandQuery.execute(),
+ () =>
+ db
+ .selectFrom("itemCost")
+ .select(["costingMethod", "unitCost", "standardCost"])
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ ]);
+ if (!itemCost) throw new NotFoundError("Item cost not found");
+ const units = onHand.flatMap((row) =>
+ row.trackedEntityId ? [row.trackedEntityId] : []
+ );
+ if (units.length === 0) {
+ return { costs: {}, costingMethod: itemCost.costingMethod };
+ }
+
+ const isLayered =
+ itemCost.costingMethod === "FIFO" || itemCost.costingMethod === "LIFO";
+ const direction = itemCost.costingMethod === "LIFO" ? "desc" : "asc";
+ // The layers calculateCOGS would consume from, in its order.
+ const layers = isLayered
+ ? await db
+ .selectFrom("costLedger")
+ .select([
+ "id",
+ "trackedEntityId",
+ "quantity",
+ "cost",
+ "remainingQuantity"
+ ])
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
+ .where("remainingQuantity", ">", 0)
+ .where("adjustment", "=", false)
+ .where("appliesToCostLedgerId", "is", null)
+ .where((eb) =>
+ eb.or([
+ eb("documentType", "is", null),
+ eb("documentType", "!=", "Purchase Order")
+ ])
+ )
+ .orderBy("postingDate", direction)
+ .orderBy("createdAt", direction)
+ .execute()
+ : [];
+
+ const childrenByLayer = new Map<string, UnitCostChild[]>();
+ if (layers.length > 0) {
+ const children = await db
+ .selectFrom("costLedger")
+ .select([
+ "appliesToCostLedgerId",
+ "quantity",
+ "cost",
+ "remainingQuantity"
+ ])
+ .where(
+ "appliesToCostLedgerId",
+ "in",
+ layers.map((layer) => layer.id)
+ )
+ .where("companyId", "=", companyId)
+ .where("remainingQuantity", ">", 0)
+ .orderBy("createdAt", "asc")
+ .execute();
+ for (const child of children) {
+ if (!child.appliesToCostLedgerId) continue;
+ const list = childrenByLayer.get(child.appliesToCostLedgerId) ?? [];
+ list.push({
+ quantity: Number(child.quantity),
+ cost: Number(child.cost),
+ remainingQuantity: Number(child.remainingQuantity)
+ });
+ childrenByLayer.set(child.appliesToCostLedgerId, list);
+ }
+ }
+
+ const basis = {
+ costingMethod: itemCost.costingMethod,
+ unitCost: itemCost.unitCost == null ? null : Number(itemCost.unitCost),
+ standardCost:
+ itemCost.standardCost == null ? null : Number(itemCost.standardCost)
+ };
+ const valuedLayers = layers.map((layer) => ({
+ id: layer.id,
+ trackedEntityId: layer.trackedEntityId,
+ quantity: Number(layer.quantity),
+ cost: Number(layer.cost),
+ remainingQuantity: Number(layer.remainingQuantity)
+ }));
+
+ const costs: Record<string, number> = {};
+ for (const trackedEntityId of units) {
+ costs[trackedEntityId] = round(
+ serialUnitCost({
+ itemCost: basis,
+ layers: valuedLayers,
+ childrenByLayer,
+ trackedEntityId
+ })
+ );
+ }
+ return { costs, costingMethod: itemCost.costingMethod };
+ }
+});
+
+export default previewSerialUnitCosts;
diff --git a/packages/server-functions/src/recost-serial-unit/index.ts b/packages/server-functions/src/recost-serial-unit/index.ts
new file mode 100644
index 0000000000..36bc2a1cbc
--- /dev/null
+++ b/packages/server-functions/src/recost-serial-unit/index.ts
@@ -0,0 +1,296 @@
+// 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.
+
+// Put a cost of the user's own on ONE serial unit in stock — a unit a job
+// completed with no production or material recorded, or one issued in at no
+// cost. The unit is relieved from whatever layer it carries today
+// (calculateCOGS, its own layer first) and re-booked on a layer of its own
+// at the new cost, both rows `costLedgerType 'Revaluation'`; the difference
+// posts Dr / Cr the inventory account against the offset account the value
+// was spent from. Nothing moves: no item ledger row is written.
+//
+// FIFO / LIFO only. A Standard or Average item carries every unit at the
+// item's one cost, so a single unit cannot have its own.
+
+import type { KyselyDatabase as DB, Kysely } from "@carbon/database/client";
+import { inOrder } from "@carbon/database/rows";
+import { round } from "@carbon/utils";
+import { sql } from "kysely";
+import { nanoid } from "nanoid";
+import { z } from "zod";
+import { defineServerFn } from "../define-server-fn";
+import { InvalidInputError, NotFoundError } from "../errors";
+import { buildOffsetLines } from "../lib/asset-transfer";
+import { calculateCOGS } from "../lib/calculate-cogs";
+import { getAccountingPeriodForDate } from "../lib/get-accounting-period";
+import {
+ getDefaultPostingGroup,
+ resolveInventoryAccount
+} from "../lib/get-posting-group";
+import { getOffsetAccount } from "../lib/offset-account";
+import {
+ buildCostLedgerRow,
+ buildJournalLineDimensions
+} from "../lib/plan-adjustment";
+import { createAdjustmentJournal } from "../lib/post-adjustment";
+
+export const recostSerialUnitInput = z.object({
+ trackedEntityId: z.string().min(1),
+ // The unit's new carrying cost, in base currency.
+ unitCost: z.number().min(0),
+ offsetAccountId: z.string().optional().nullable(),
+ postingDate: z
+ .string()
+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Expected a YYYY-MM-DD date")
+});
+
+export type RecostResult = {
+ previousCost: number;
+ unitCost: number;
+ journalId: string | null;
+};
+
+const recostSerialUnit = defineServerFn({
+ name: "recost-serial-unit",
+ input: recostSerialUnitInput,
+ // Recosting puts a number of the user's own on the books.
+ permissions: { update: "accounting" },
+ async run({ db, companyId, userId }, input): Promise<RecostResult> {
+ const unitCost = round(input.unitCost);
+
+ return db.transaction().execute(async (trx): Promise<RecostResult> => {
+ // Lock the unit before reading where it is: a second recost, or an
+ // issue, pick, transfer or adjustment of it (they lock it too), waits,
+ // so the on-hand check below still holds when calculateCOGS relieves
+ // its layer (which locks the layers it reads).
+ const entity = await trx
+ .selectFrom("trackedEntity")
+ .select(["id", "itemId", "readableId", "status"])
+ .where("id", "=", input.trackedEntityId)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ if (!entity?.itemId) throw new NotFoundError("Tracked entity not found");
+ const itemId = entity.itemId;
+ const serial = entity.readableId ?? entity.id;
+
+ const [item, itemCost] = await inOrder([
+ () =>
+ trx
+ .selectFrom("item")
+ .select(["readableId", "itemTrackingType", "replenishmentSystem"])
+ .where("id", "=", itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst(),
+ () =>
+ trx
+ .selectFrom("itemCost")
+ .select(["costingMethod", "itemPostingGroupId"])
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ ]);
+ if (!item || !itemCost) throw new NotFoundError("Item not found");
+ if (item.itemTrackingType !== "Serial") {
+ throw new InvalidInputError("Only a serialized unit can be recosted");
+ }
+ if (
+ itemCost.costingMethod !== "FIFO" &&
+ itemCost.costingMethod !== "LIFO"
+ ) {
+ throw new InvalidInputError(
+ `${item.readableId} uses ${itemCost.costingMethod} costing, so every unit carries the item's cost; one unit cannot have its own`
+ );
+ }
+
+ // Where the unit is: exactly one on hand, at one location.
+ const stock = await trx
+ .selectFrom("itemLedger")
+ .select([
+ "locationId",
+ (eb) => eb.fn.sum<number>("quantity").as("onHand")
+ ])
+ .where("trackedEntityId", "=", entity.id)
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
+ .groupBy("locationId")
+ .having(sql<number>`SUM("quantity")`, ">", 0)
+ .execute();
+ const onHand = stock.reduce((sum, row) => sum + Number(row.onHand), 0);
+ if (round(onHand) !== 1 || stock.length !== 1) {
+ throw new InvalidInputError(
+ `${serial} must have exactly one unit on hand to be recosted`
+ );
+ }
+ const locationId = stock[0]?.locationId ?? null;
+
+ const settings = await trx
+ .selectFrom("companySettings")
+ .select("accountingEnabled")
+ .where("id", "=", companyId)
+ .executeTakeFirst();
+ // Fail closed: a failed settings read must not silently skip the GL.
+ if (!settings) throw new Error("Failed to fetch company settings");
+ const accounting = settings.accountingEnabled
+ ? await loadAccounting(trx, companyId, input)
+ : null;
+
+ // Relieve what the unit carries today, exactly as a shipment would.
+ const relieved = await calculateCOGS(trx, {
+ itemId,
+ quantity: 1,
+ companyId,
+ trackedEntityIds: [entity.id]
+ });
+ const previousCost = round(relieved.totalCost);
+ const delta = round(unitCost - previousCost);
+ if (delta === 0) {
+ throw new InvalidInputError(
+ `${serial} is already carried at that cost`
+ );
+ }
+
+ const ledger = {
+ documentType: null,
+ documentId: entity.id,
+ itemId,
+ postingDate: input.postingDate,
+ trackedEntityId: entity.id,
+ companyId
+ };
+ await trx
+ .insertInto("costLedger")
+ .values([
+ {
+ ...buildCostLedgerRow({
+ ...ledger,
+ entryType: "Negative Adjmt.",
+ quantity: -1,
+ cost: -previousCost
+ }),
+ costLedgerType: "Revaluation"
+ },
+ {
+ // The unit's own layer: it is relieved first when it leaves.
+ ...buildCostLedgerRow({
+ ...ledger,
+ entryType: "Positive Adjmt.",
+ quantity: 1,
+ cost: unitCost
+ }),
+ costLedgerType: "Revaluation"
+ }
+ ])
+ .execute();
+
+ let journalId: string | null = null;
+ if (accounting) {
+ const inventoryAccount = resolveInventoryAccount(
+ item.replenishmentSystem,
+ accounting.accountDefaults
+ );
+ journalId = await createAdjustmentJournal(trx, {
+ companyId,
+ accountingPeriodId: accounting.accountingPeriodId,
+ description: `Recost ${item.readableId} ${serial}`,
+ postingDate: input.postingDate,
+ userId,
+ sourceType: "Inventory Adjustment"
+ });
+ const journalLineReference = nanoid();
+ const lines = await trx
+ .insertInto("journalLine")
+ .values(
+ buildOffsetLines({
+ amount: delta,
+ accountId: inventoryAccount.account,
+ description: inventoryAccount.description,
+ offsetAccountId: accounting.offsetAccount.id,
+ offsetDescription: "Inventory Recost",
+ offsetAccountType: accounting.offsetAccount.type,
+ label: "Inventory recost journal"
+ }).map((line) => ({
+ journalId: journalId as string,
+ accountId: line.accountId,
+ description: line.description,
+ amount: line.amount,
+ quantity: 1,
+ documentType: "Inventory Adjustment" as const,
+ documentId: entity.id,
+ journalLineReference,
+ companyId
+ }))
+ )
+ .returning(["id"])
+ .execute();
+ const dimensions = buildJournalLineDimensions({
+ journalLineIds: lines.map((line) => line.id),
+ dimensions: accounting.dimensions,
+ itemId,
+ itemPostingGroupId: itemCost.itemPostingGroupId,
+ locationId,
+ companyId
+ });
+ if (dimensions.length > 0) {
+ await trx
+ .insertInto("journalLineDimension")
+ .values(dimensions)
+ .execute();
+ }
+ }
+
+ return { previousCost, unitCost, journalId };
+ });
+ }
+});
+
+// Everything the journal needs, read on the recost's transaction.
+async function loadAccounting(
+ db: Kysely<DB>,
+ companyId: string,
+ input: z.output<typeof recostSerialUnitInput>
+) {
+ const [defaults, offsetAccount, company] = await inOrder([
+ () => getDefaultPostingGroup(db, companyId),
+ () => getOffsetAccount(db, companyId, input.offsetAccountId),
+ () =>
+ db
+ .selectFrom("company")
+ .select("companyGroupId")
+ .where("id", "=", companyId)
+ .executeTakeFirst()
+ ]);
+ if (defaults.error || !defaults.data) {
+ throw new Error("Error getting account defaults");
+ }
+ if (!company) throw new Error("Failed to fetch company");
+ // Fail closed: journal lines must not silently lose dimension tags.
+ const dimensionRows = await db
+ .selectFrom("dimension")
+ .select(["id", "entityType"])
+ .where("companyGroupId", "=", company.companyGroupId)
+ .where("active", "=", true)
+ .where("entityType", "in", ["Item", "ItemPostingGroup", "Location"])
+ .execute();
+ const dimensions: Record<string, string> = {};
+ for (const row of dimensionRows) {
+ if (row.entityType) dimensions[row.entityType] = row.id;
+ }
+ const accountingPeriodId = await getAccountingPeriodForDate(
+ companyId,
+ db,
+ input.postingDate
+ );
+ return {
+ accountingPeriodId,
+ accountDefaults: {
+ rawMaterialsAccount: defaults.data.rawMaterialsAccount,
+ finishedGoodsAccount: defaults.data.finishedGoodsAccount
+ },
+ offsetAccount,
+ dimensions
+ };
+}
+
+export default recostSerialUnit;