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.

fix(inventory): serial entry and voids on serial- and batch-tracked receipts (#1936)

Naveen Kashyap7d1cbb2d175e
diff --git a/.ai/lessons.md b/.ai/lessons.md
index a2342be0e4..57e35837a0 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -3703,6 +3703,36 @@ The write was then removed (nothing reads it), so the rail always starts collaps
**Applies to:** `membership` and its interceptors in `packages/database/src/event-system/handlers/`, and any unique key with a nullable column.
+## A flash on a fetcher's redirect back to the same page is never shown
+
+**Context:** Refusing a receipt post that still misses serial numbers (2026-10-16). The Post dialog submits through `useRuleViolations`, a fetcher.
+
+**Problem:** The action threw `redirect(path.to.receipt(id), await flash(...))`. The redirect lands on the pathname already on screen, so the root's `shouldRevalidate` (`isSearchParamOnlyNavigation`) skips the root loader, and the root is what reads the flash and shows the toast. The post was refused correctly, but the user saw nothing happen. The route's older flash errors ("Failed to post receipt") have the same gap.
+
+**Rule:** An action submitted through a fetcher returns its error as data (`{ error: { message } }`, which `useRuleViolations` toasts), not as a flash on a redirect to the current page. A flash is for a redirect that navigates somewhere else.
+
+**Applies to:** Post / void / approve actions behind a modal or `useRuleViolations` (`receipt+/$receiptId.post.tsx` and its siblings).
+
+## What a document posts must be what its form shows
+
+**Context:** Receipt serial entry (2026-10-16). Each serial box saved on blur, keyed on the serial number.
+
+**Problem:** A box emptied, refused (a duplicate) or pushed out of range by a lower received quantity kept its saved serial. The post check reads what is saved, so the receipt posted a serial the user could no longer see.
+
+**Rule:** Key a per-field save on the field's position (here the box: receipt line + index), not on its value. An empty value, a refused value and a removed field each clear what is saved for it. And a removal never deletes a record with stock history: a sales return re-tags real shipped units, so those only lose their receipt link (`planReceiptSerialRelease`).
+
+**Applies to:** `setReceiptLineSerial` / `saveReceiptSerialBox`, `updateReceiptLines`, `ReceiptLines` `SerialForm`, the receipt line split (`receiptLineSplit` in `shared.service.ts`), and any autosaved list of tracked values (shipment serials, batch numbers).
+
+## A void reverses only what is still where the posting put it
+
+**Context:** Voiding a posted purchase receipt with serials and batches (2026-10-16).
+
+**Problem:** The void set every tracked entity back to Available at its received quantity, so a lot that was never received stayed pickable. It also reversed each ledger row at the receipt's bin with only a cost-layer check. A serial moved to another bin, picked to lineside or shipped (Standard and Average cost never draw a layer down) passed that check, so the receipt bin went negative while the unit stayed counted where it went. And the receipt's inspection lot stayed open: Accept made the voided batch Available again, and Reject wrote the reversed stock off a second time.
+
+**Rule:** A reversal checks, inside its transaction, that the stock it removes is still at the position the posting wrote: per serial or batch for tracked rows. It closes every record that hangs off the document (here the inspection lot) or refuses while one has acted. It drains the document's tracked entities to quantity 0. To keep `Rejected` at zero, write the status directly: `settleQuantity` only preserves `Scrapped` and turns `Rejected` into `Consumed`.
+
+**Applies to:** the `postReceipt` void (`lockPostedReceipt`, `assertReceivedStockOnHand`, `assertNoRejectedUntrackedLot` in `inventory.service.ts`), and any other void that reverses item ledger rows (shipments, stock transfers, adjustments).
+
## A text replace on a function name also renames its prefix siblings
**Context:** The service-function migration (2026-10-16) renamed thousands of call sites with scripts.
@@ -3929,3 +3959,13 @@ The write was then removed (nothing reads it), so the rail always starts collaps
**Rule:** A request a timer or event sends on its own (not one the user started) must not be able to fail into a boundary: skip it while `navigator.onLine` is false and retry on `online`. Both error boundaries treat `isNetworkError` as a lost connection and revalidate when the connection or the tab comes back; a successful revalidation clears `state.errors`.
**Applies to:** every `useFetcher` used from a layout or provider, every background timer that submits or loads, `packages/react/src/ErrorBoundary/`.
+
+## A posting's refusal only reaches the dialog when it is thrown as a 4xx
+
+**Context:** A refused receipt void showed "Failed to void receipt" with no reason. The guards inside the `post-receipt` posting said exactly why ("stock received on this receipt was moved, picked or shipped since it was received").
+
+**Problem:** `invokePosting` reads a plain `Error` as status 500 (the posting's default), and the operation passed every failure to `serverFnFailure` with a fixed message. So every refusal, and every new guard, was reported with the same generic text.
+
+**Rule:** Throw an authored refusal from a posting as `InvalidInputError` (or another `ServerFnError` below 500), never a plain `Error`. In the operation, below 500 return the error's own message (`error.message || <fallback>`); keep the generic message for 500, whose detail `toError` already withholds.
+
+**Applies to:** every operation that calls `invokePosting` and every posting body (`voidReceipt` / `postReceipt` in `inventory.server.ts`, `adjustInventory` follows the same shape).
diff --git a/.ai/playbooks/receipt-serial-entry.md b/.ai/playbooks/receipt-serial-entry.md
new file mode 100644
index 0000000000..7c7f8683a0
--- /dev/null
+++ b/.ai/playbooks/receipt-serial-entry.md
@@ -0,0 +1,62 @@
+# Receipt Serial Entry (clear / edit / post refusal)
+
+Last tested: 2026-10-16
+Route: /x/receipt/<id>/details
+
+## Prerequisites
+- A Serial-tracked part. Create at /x/part/new: Part ID + Name, "Tracking Type"
+ combobox (second combobox after Replenishment) → "Serial", requestSubmit Save.
+- A finalized PO for that part (see create-purchase-order.md). Then on the PO,
+ click "Receive" → lands on the receipt with one "Serial N" textbox per unit.
+- Satellite seed data has storage/sales rules that raise a "Rule Violation"
+ dialog on post — click "Acknowledge & continue". When POSTing the post route
+ directly, send `acknowledged=true` or the rule warnings stop it first.
+
+## Steps
+### 1. Clear a saved serial (the original bug)
+- Click "Serial 1", type `123`, click the "Receipt Lines" heading (blur saves).
+- Click back in, press End, Backspace until empty (Ctrl+A does NOT select on
+ macOS), click the heading again.
+- Verify DB: no trackedEntity left at `Receipt Line Index` 0.
+### 2. Edit a serial
+- Change a saved value and blur → the same trackedEntity id is renamed (one row).
+### 3. Post with a box empty
+- Click "Post" → dialog shows "Missing Information … Serial numbers are missing",
+ Post Receipt disabled.
+### 4. Server refusal (stale dialog)
+- Fill all boxes, open the Post dialog, then clear one box out of band
+ (fetch POST /x/receipt/lines/tracking with serialNumber=''), click Post Receipt,
+ acknowledge rules → toast "Serial numbers are missing", receipt stays Draft.
+### 5. Quantity change
+- Received 3 → 2 → 3: box 3 comes back empty AND its saved serial is gone.
+### 6. Happy path
+- Fill all boxes, Post → receipt Posted, entities Available, inputs disabled.
+
+## Selector Notes
+- Serial inputs: `input[placeholder="Serial N"]`. Received quantity: the
+ textbox just under the "Receipt Lines" heading.
+- Read-only DB check:
+ `select "readableId", status, attributes->>'Receipt Line Index' from "trackedEntity" where attributes->>'Receipt' = '<receipt id>'`
+
+### 7. Refused values empty the box
+- A duplicate within the form, a serial on another receipt's box, a job's
+ reserved serial, or the serial of an existing unit with stock history (e.g.
+ one shipped to a customer: "already belongs to an existing unit") shows an
+ error AND leaves nothing saved for the box; the Post dialog then blocks.
+### 8. Enter
+- Enter moves focus to the next box (one save via blur); on the last box it blurs.
+### 9. Line split and sales returns
+- Split a serial PO line: its unposted serials are deleted, boxes show empty.
+- Split / lower the quantity on a sales-return line with picked units: the units
+ are kept (stock history) and only lose their receipt link.
+
+## Browser session
+- Other agents may drive the shared default agent-browser session. Use
+ `export AGENT_BROWSER_SESSION=<name>` in every command (and log in again in it).
+
+## Common Failures
+- A flash from a redirect is never shown after the post dialog submits (fetcher
+ redirect to the same page does not reload root) — the post route returns
+ `{ error: { message } }` instead.
+- Sales returns: RMA "Add Line Item" → "Add from shipment"; the customer needs a
+ US Customer Location on the SO header or the ITAR rule blocks the SO line.
diff --git a/.ai/playbooks/receipt-void-tracked-entities.md b/.ai/playbooks/receipt-void-tracked-entities.md
new file mode 100644
index 0000000000..aafa201018
--- /dev/null
+++ b/.ai/playbooks/receipt-void-tracked-entities.md
@@ -0,0 +1,51 @@
+# Receipt Void — Tracked Entities
+
+Last tested: 2026-10-16
+Route: /x/receipt/<id>/details → More options → Void
+
+## Prerequisites
+- A Batch part and a Serial part. Create at /x/part/new: Part ID (1st textbox),
+ Revision (2nd, keep "0"), Name (3rd), "Tracking Type" combobox (the one
+ showing "Inventory") → Batch / Serial, requestSubmit Save.
+- A finalized PO for them (see create-purchase-order.md). The supplier picker
+ hides a just-created Pending supplier; pick a seeded one (satellite:
+ "AstroMill Machining").
+- For the On Hold case: the part's Quality tab → Inspection Plans "New"
+ (drawing number only) → Inspection Plan Assignments, Receipt slot → the
+ new plan → requestSubmit the form holding `inspectionDocumentId`.
+
+## Steps
+### 1. Receive
+- PO → "Receive" (or "Receipts" menu → "New Receipt" once one exists).
+- "Batch number" textbox, "Serial N" textboxes; click the "Receipt Lines"
+ heading to blur after each (blur saves). Draft entities are On Hold.
+### 2. Post
+- "Post" → "Post Receipt" → satellite rules raise "Rule Violation" →
+ "Acknowledge & continue". Entities: Available (On Hold when inspected).
+### 3. Void
+- "More options" (header) → menuitem "Void" → "Void Receipt".
+### 4. Verify
+- Inventory → Tracked Entities (`/x/inventory/tracked-entities?search=...`):
+ every entity of the receipt is quantity 0, Consumed (Rejected/Scrapped kept).
+- Read-only DB check:
+ `select "readableId", status, quantity from "trackedEntity" where attributes->>'Receipt' = '<receipt id>'`
+- Picker RPC returns nothing:
+ `select count(*) from get_available_tracked_entities(p_item_id=>'<item>', p_company_id=>'<co>', p_location_id=>'<loc>')`
+
+## Edge cases (expected behaviour)
+- Partial receipt (2 of 3) void: PO line back to 0, entities Consumed/0.
+- The inspection of a voided receipt shows a "Receipt voided" badge and every
+ action is off; a direct POST is refused "The receipt of this inspection was voided".
+- An untracked lot rejected (written off) before the void: the void is refused
+ in the modal, naming the inspection.
+- A serial or batch moved to another bin (stock transfer), picked, shipped or
+ adjusted out before the void: the void is refused in the modal ("moved, picked
+ or shipped"). Every refusal shows its own reason, never "Failed to void receipt".
+- A serial from a voided receipt can be entered on a new receipt: on the draft
+ it is On Hold/1 again, and after posting it is the same tracked entity, Available/1.
+
+## Common Failures
+- Session lands on /login with "User record not found": the stack's kong/gotrue
+ containers died. `docker start <project>-kong-1 <project>-gotrue-1`, log in again.
+- `agent-browser screenshot` with a relative path does not land in the repo;
+ pass an absolute path.
diff --git a/.claude/rules/inspection-system.md b/.claude/rules/inspection-system.md
index 7a2bafd656..17df11ffd3 100644
--- a/.claude/rules/inspection-system.md
+++ b/.claude/rules/inspection-system.md
@@ -349,6 +349,13 @@ GL/cost posting and `.ai/plans/2026-07-25-inspection-disposition-gl-posting.md`.
call `runInspectionBalloonRegionVisionAnalysis`). `packages/database/src/sampling.ts`
is the pure resolver; the engine and `post-receipt` both consume it, so they share ONE resolver copy
(ERP's `samplingStandards.ts` client copy remains for UI previews).
+ - **Voided receipt (2026-10-16):** a Receipt lot whose receipt is `Voided` is
+ closed too. `assertReceiptNotVoided` (reads the receipt `FOR SHARE`, so it waits
+ for a void in progress) refuses samples, measurements, gauges, document swaps and
+ dispositions with "The receipt of this inspection was voided", and the `$id` loader
+ passes `receiptVoided` so `InspectionView` treats the lot as closed and shows a
+ "Receipt voided" badge. The lot keeps its Pending status: there is no cancelled
+ inspection status.
- **Closed guards + linked-sample locks (2026-07-27):** all three terminal
statuses (Passed/Failed/**Partial**) block `upsertInspectionSample` (guard
is NEW — it had none) and `upsertInspectionMeasurement` ("Inspection is
diff --git a/.claude/rules/shipments-receipts-ui-patterns.md b/.claude/rules/shipments-receipts-ui-patterns.md
index 6aa0670d7c..d4ae6a3f0d 100644
--- a/.claude/rules/shipments-receipts-ui-patterns.md
+++ b/.claude/rules/shipments-receipts-ui-patterns.md
@@ -53,8 +53,39 @@ run the same checks. The route only parses the form, and takes the document id f
attrs off prior entities. Receipt tracking additionally has a `returnEntity` type for
sales-return receipts (same-serial re-entry, guarded by provenance: the entity must be the
return line's item and shipped to that return's customer on a posted shipment).
+ A receipt serial write is keyed by its box (`Receipt Line` + `Receipt Line Index`), not by the
+ serial number, and planned by the pure `planSerialBoxWrite` (`inventory.models.ts`): an empty
+ value clears the box, a new value renames the box's unposted entity, and a refused value (a
+ serial of a unit with `itemLedger` history, checked first; a serial held by another box or by
+ any other record, such as a job's reserved serial; or a failed write) empties the box, so a box
+ showing an error never posts its previous serial. Only this box's record, or one from a voided
+ receipt, is ever taken over. Typed serials only
+ exist on purchase receipts of new units (outside-processing lines ask for none, inbound
+ transfers never touch serials), so writing into an existing unit is never right: it wiped a
+ shipped unit's `Shipment` link, which the RMA provenance check reads. `ReceiptLines` sends every
+ blur as typed, an empty value included, and shows the server's error: the server, not the page,
+ decides a duplicate, so a box is never cleared because another box holds the same text. Enter
+ only moves focus (`data-serial-boxes`) so the blur is the one save. `setReceiptLineSerial`
+ runs `saveReceiptSerialBox` (`inventory.service.ts`): the reads, the write
+ (`update_receipt_line_serial_tracking`, called through Kysely) and the release in one
+ transaction, holding the receipt line `FOR UPDATE` so two saves of one line run one after the
+ other; a failed write empties the box in a second one (`clearReceiptSerialBox`). Refused
+ unless the receipt is Draft.
+ The `postReceipt` operation refuses a Posted or Voided receipt before any write, and refuses
+ the post (back to Draft) when `reconcileReceiptSerialEntities` reports a line still missing
+ serials ("Serial numbers are missing").
+ Lowering `receivedQuantity` (`updateReceiptLines`) runs the same cleanup on a Draft receipt, in
+ one Kysely transaction with the quantity update, and refuses a non-numeric quantity. Every
+ removal goes through `releaseReceiptSerialEntities` (`@carbon/database/receipt-serials`, Kysely,
+ set-based; the line split uses it too): an entity with no
+ `itemLedger` history is deleted, one with history only loses its receipt attributes — a sales
+ return re-tags real shipped units. `lines.return-entities` reports a failed read as an error,
+ and `ReturnEntityForm` shows it instead of falling back to typed serials (whose empty save
+ would unlink an assigned unit).
- `lines.split.tsx` (`splitShipmentLine` / `splitReceiptLine`) — invokes `create` with
`type: "shipmentLineSplit"` / `receiptLineSplit`.
+ A serial `receiptLineSplit` drops the line's serials, deleting only entities with no
+ `itemLedger` history; a unit with history (a sales return) only loses its receipt link.
- `lines.$id.delete.tsx` — `deleteShipmentLine` / `deleteReceiptLine`.
- `fixed-asset-lines.update.tsx` (`updateShipmentFixedAssetLine` / `updateReceiptFixedAssetLine`) — update one field of a `shipmentFixedAssetLine` / `receiptFixedAssetLine`,
parsed by `shipmentFixedAssetLineUpdateValidator` / `receiptFixedAssetLineUpdateValidator`
@@ -191,7 +222,24 @@ applies.
- **`void`** (post fn, `type: "void"`): requires `status === "Posted"`; receipt also blocks if
`invoiced` (and only PO-sourced receipts can void). Posts reversing `itemLedger` + `journalLine`s,
- rolls back source-document quantities, restores tracked entities to `Available`, sets `status: "Voided"`.
+ rolls back source-document quantities, sets `status: "Voided"`. A purchase receipt's void drains
+ its tracked entities to quantity 0 / `Consumed` (`Scrapped`/`Rejected` kept) — they were never
+ received, so no picker may offer them; a sales-return receipt's void flips the returned units
+ back to `Consumed`. Inside the transaction (`lockPostedReceipt`, `assertReceivedStockOnHand`,
+ `assertNoRejectedUntrackedLot` in `inventory.service.ts`) the void locks the
+ receipt and re-checks `Posted` (two voids at once cannot both reverse it), refuses when the
+ reversal would take a bin below zero — a serial or batch is checked on its own, so a unit that
+ was moved, picked or shipped after posting is caught even when the bin holds other stock — and
+ refuses a purchase receipt whose untracked inspection lot was rejected (the reject route already
+ wrote that stock off). `ReceiptVoidModal` shows a refused `voidReceipt` in place and stays
+ open. A serial from a voided receipt can be entered on a new receipt: `saveReceiptSerialBox`
+ reuses the same tracked entity (`idsWithLiveStockHistory` ignores the ledger rows of voided
+ receipts, `onVoidedReceipt` lifts the "taken by another box" refusal), so one unit keeps one
+ history. The function's update keeps quantity and status, so the save resets that record to
+ 1 / On Hold, as a new draft serial starts.
+ `voidReceipt` and `postReceipt` show a posting refusal (status below 500) in the posting's own
+ words; the refusals in `postReceipt` are `InvalidInputError`, never a plain `Error` (which the
+ posting reads as a 500 and the dialog would show as "Failed to void receipt").
A rental shipment voids while every unit is still On Rent and no `Accrual` row of its lines is
Posted or held by a Draft run: the units go back to Pending. `post-receipt` refuses a rental
receipt void ("A rental return cannot be voided. Correct the unit by hand.").
diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.md
index 005d613d8b..688cfabcf7 100644
--- a/apps/erp/app/modules/inventory/AGENTS.md
+++ b/apps/erp/app/modules/inventory/AGENTS.md
@@ -68,7 +68,7 @@ Each operation is one `defineServiceFn` const in `inventory.server.ts`. A route
| `createReceipt` / `createShipment` | `receipt+/new.tsx`, `shipment+/new.tsx` | The `create` posting for the source document; a return order or rental agreement with a Draft document returns that one. A sales or purchase order shipment needs the caller's default location |
| `updateReceipt` / `updateShipment` | `$receiptId.details.tsx`, `$shipmentId.details.tsx` | A changed source or location rebuilds the lines; a rental document keeps its agreement |
| `postReceipt` / `postShipment` | `$receiptId.post.tsx`, `$shipmentId.post.tsx` | Storage rules (and over-receipt, and the order's sales rules), Pending, the posting, back to Draft on failure, labels, lead times, the workflow moment. A shipment also applies the expired-batch policy and saves the packing slip (`packing-slip.pdf.tsx`, shared with `file+/shipment+/$id[.]pdf.tsx`) |
-| `voidReceipt` / `voidShipment` | `$receiptId.void.tsx`, `$shipmentId.void.tsx` | Posted only; not a receipt a purchase invoice created |
+| `voidReceipt` / `voidShipment` | `$receiptId.void.tsx`, `$shipmentId.void.tsx` | Posted only; not a receipt a purchase invoice created. A receipt void also refuses stock that has left its bin since posting and an untracked lot an inspection rejected; the refusal reaches the caller in its own words |
| `splitReceiptLine`, `updateReceiptLines`, `updateReceiptFixedAssetLine` (and the shipment twins) | `lines.split.tsx`, `lines.update.tsx`, `fixed-asset-lines.update.tsx` | A fixed-asset line changes only on a Draft document |
| `setReceiptLineBatch` / `setReceiptLineSerial` / `assignReceiptReturnEntity` / `removeReceiptReturnEntity` | `receipt+/lines.tracking.tsx` (one per `trackingType` / `intent`) | Batch and serial numbers; a sales return re-tags the Consumed entity the customer sent back |
| `assignShipmentLineEntity` | `shipment+/lines.tracking.tsx` | The line's item, Available (On Hold, received on this return order, for a return-to-customer shipment) |
@@ -104,7 +104,8 @@ A blocking rule is data, not an error: `post`, `create`, `setStatus` and `adjust
- `correctStockMovement` — the operation settles `postStockMovementCorrection` (`inventory.service.ts`, ported from the `correct-stock-movement` server function) directly, so its refusal keeps its message: 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
-- `getReceipts` / `getReceiptLines` / `reconcileReceiptSerialEntities` — receipt management
+- `getReceipts` / `getReceiptLines` / `reconcileReceiptSerialEntities` — receipt management. `reconcileReceiptSerialEntities` (Kysely, its own transaction; `reconcileReceiptSerialsInTransaction` inside a caller's) drops serials beyond the received quantity (run on post, and in the same transaction as a quantity change in `updateReceiptLines`) and returns the lines still missing serials, which the post refuses
+- `releaseReceiptSerialEntities` (`@carbon/database/receipt-serials`, shared with the receipt line split, `receiptLineSplit` in `shared.service.ts`) — the one way a receipt serial is removed, run inside a Kysely transaction: an entity with no `itemLedger` history is deleted, one with history only loses its receipt link in one set-based update. A serial box save is planned by the pure `planSerialBoxWrite` (`inventory.models.ts`)
- `getShipments` / `getShipmentLines` / `getShipmentRelatedItems` — shipment management
- `getRentalShipmentLines` / `getRentalReceiptLines` — a rental document's asset lines with their rental line, fleet asset, item and tracked entity; the `$shipmentId.tsx` / `$receiptId.tsx` loaders call them for the `'Rental Agreement'` source and pass them as `rentalLines` (sorted by asset id, else unit name) to `ShipmentRentalLineItem` / `ReceiptRentalLineItem`. Both readers order by `createdAt, id`: a document's units are inserted in one statement and share a `createdAt`
- `getReceiptRelatedItems` / `getWarehouseTransferRelatedItems` / `getPickingListRelatedItems` — the `DocumentPage` Documents panels (receipt invoices + a sales return's customer; a transfer's shipments and receipts; a picking list's jobs). Query errors are logged and degrade to empty lists
diff --git a/apps/erp/app/modules/inventory/inventory.models.test.ts b/apps/erp/app/modules/inventory/inventory.models.test.ts
index 84c1aa0d4a..4ceb2f3cdb 100644
--- a/apps/erp/app/modules/inventory/inventory.models.test.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.test.ts
@@ -6,7 +6,9 @@ import { describe, expect, it } from "vitest";
import {
finishPickingList,
kanbanValidator,
+ planSerialBoxWrite,
receiptFixedAssetLineUpdateValidator,
+ reconcileReceiptLineSerials,
resolveStockTransferPickForward,
shipmentFixedAssetLineUpdateValidator,
storageTypeValidator,
@@ -238,6 +240,209 @@ describe("kanbanValidator replenishmentLevel", () => {
});
});
+describe("planSerialBoxWrite", () => {
+ const box = (line: string, index: number) => ({
+ "Receipt Line": line,
+ "Receipt Line Index": index,
+ Receipt: "rec1"
+ });
+
+ it("clears the box when the serial is emptied", () => {
+ expect(
+ planSerialBoxWrite({
+ receiptLineId: "line1",
+ index: 0,
+ serialNumber: " ",
+ box: [{ id: "e1", hasHistory: false }],
+ withSerial: []
+ })
+ ).toEqual({ kind: "clear", releaseIds: ["e1"] });
+ });
+
+ it("renames the box's own entity when the serial is edited", () => {
+ expect(
+ planSerialBoxWrite({
+ receiptLineId: "line1",
+ index: 0,
+ serialNumber: "NEW",
+ box: [{ id: "e1", hasHistory: false }],
+ withSerial: []
+ })
+ ).toEqual({ kind: "write", targetId: "e1", releaseIds: [] });
+ });
+
+ it("refuses a serial held by another box and empties this one", () => {
+ expect(
+ planSerialBoxWrite({
+ receiptLineId: "line1",
+ index: 1,
+ serialNumber: "SN-A",
+ box: [{ id: "e2", hasHistory: false }],
+ withSerial: [
+ { id: "e1", hasHistory: false, attributes: box("line1", 0) }
+ ]
+ })
+ ).toEqual({ kind: "taken", reason: "box", releaseIds: ["e2"] });
+ });
+
+ it("refuses a serial held by a box on another receipt line", () => {
+ expect(
+ planSerialBoxWrite({
+ receiptLineId: "line1",
+ index: 0,
+ serialNumber: "SN-A",
+ box: [],
+ withSerial: [
+ { id: "e9", hasHistory: false, attributes: box("line2", 0) }
+ ]
+ }).kind
+ ).toBe("taken");
+ });
+
+ it("keeps one copy when a racing save left two in the box", () => {
+ expect(
+ planSerialBoxWrite({
+ receiptLineId: "line1",
+ index: 0,
+ serialNumber: "SN-A",
+ box: [
+ { id: "e1", hasHistory: false },
+ { id: "e2", hasHistory: false }
+ ],
+ withSerial: [
+ { id: "e1", hasHistory: false, attributes: box("line1", 0) },
+ { id: "e2", hasHistory: false, attributes: box("line1", 0) }
+ ]
+ })
+ ).toEqual({ kind: "write", targetId: "e1", releaseIds: ["e2"] });
+ });
+
+ it("never renames a box entity that has stock history", () => {
+ expect(
+ planSerialBoxWrite({
+ receiptLineId: "line1",
+ index: 0,
+ serialNumber: "NEW",
+ box: [{ id: "unit", hasHistory: true }],
+ withSerial: []
+ })
+ ).toEqual({ kind: "write", targetId: undefined, releaseIds: ["unit"] });
+ });
+
+ it("refuses the serial of a unit with stock history", () => {
+ expect(
+ planSerialBoxWrite({
+ receiptLineId: "line1",
+ index: 0,
+ serialNumber: "SN-B",
+ box: [{ id: "e1", hasHistory: false }],
+ withSerial: [
+ { id: "shipped", hasHistory: true, attributes: { Shipment: "sh1" } }
+ ]
+ })
+ ).toEqual({ kind: "taken", reason: "unit", releaseIds: ["e1"] });
+ });
+
+ it("refuses a unit with stock history even when it already sits in the box", () => {
+ expect(
+ planSerialBoxWrite({
+ receiptLineId: "line1",
+ index: 0,
+ serialNumber: "SN-B",
+ box: [{ id: "shipped", hasHistory: true }],
+ withSerial: [
+ { id: "shipped", hasHistory: true, attributes: box("line1", 0) }
+ ]
+ })
+ ).toEqual({ kind: "taken", reason: "unit", releaseIds: ["shipped"] });
+ });
+
+ it("takes back the serial of a voided receipt as the same unit", () => {
+ expect(
+ planSerialBoxWrite({
+ receiptLineId: "line1",
+ index: 0,
+ serialNumber: "SN-A",
+ box: [],
+ withSerial: [
+ {
+ id: "voided",
+ hasHistory: false,
+ attributes: { ...box("lineOld", 0), Receipt: "recVoided" },
+ onVoidedReceipt: true
+ }
+ ]
+ })
+ ).toEqual({ kind: "write", targetId: "voided", releaseIds: [] });
+ });
+
+ it("refuses the serial of a record no receipt box holds (a job's reserved serial)", () => {
+ expect(
+ planSerialBoxWrite({
+ receiptLineId: "line1",
+ index: 0,
+ serialNumber: "SN-A",
+ box: [{ id: "e1", hasHistory: false }],
+ withSerial: [
+ { id: "reserved", hasHistory: false, attributes: { Job: "job1" } }
+ ]
+ })
+ ).toEqual({ kind: "taken", reason: "unit", releaseIds: ["e1"] });
+ });
+
+ it("names a received unit in another box as an existing unit", () => {
+ expect(
+ planSerialBoxWrite({
+ receiptLineId: "line1",
+ index: 0,
+ serialNumber: "SN-B",
+ box: [],
+ withSerial: [
+ { id: "received", hasHistory: true, attributes: box("line2", 0) }
+ ]
+ })
+ ).toEqual({ kind: "taken", reason: "unit", releaseIds: [] });
+ });
+});
+
+describe("reconcileReceiptLineSerials", () => {
+ it("reports an index with no serial as missing", () => {
+ expect(
+ reconcileReceiptLineSerials(
+ [
+ { id: "a", index: 0, hasSerial: true },
+ { id: "c", index: 2, hasSerial: true }
+ ],
+ 3
+ ).missingIndexes
+ ).toEqual([1]);
+ });
+
+ it("marks the boxes beyond the received quantity as surplus", () => {
+ expect(
+ reconcileReceiptLineSerials(
+ [
+ { id: "a", index: 0, hasSerial: true },
+ { id: "c", index: 2, hasSerial: true }
+ ],
+ 2
+ ).surplusEntityIds
+ ).toEqual(["c"]);
+ });
+
+ it("keeps the serial-bearing entity over an older blank one", () => {
+ expect(
+ reconcileReceiptLineSerials(
+ [
+ { id: "blank", index: 0, hasSerial: false, createdAt: "1" },
+ { id: "serial", index: 0, hasSerial: true, createdAt: "2" }
+ ],
+ 1
+ )
+ ).toEqual({ missingIndexes: [], surplusEntityIds: ["blank"] });
+ });
+});
+
describe("finishPickingList", () => {
const finish = (
unresolvedItemNames: string[],
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.ts
index 72d1bbb381..5fb88f9fd0 100644
--- a/apps/erp/app/modules/inventory/inventory.models.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.ts
@@ -530,7 +530,8 @@ export type ReceiptSerialEntity = {
* can never disagree on which serials count:
* - `missingIndexes` — required indices with no serial yet (post validation)
* - `surplusEntityIds` — orphan/duplicate entities to delete before posting,
- * keeping the earliest-created entity for each in-range index.
+ * keeping, for each in-range index, a serial-bearing entity over a blank
+ * one, then the earliest-created.
*/
export function reconcileReceiptLineSerials(
entities: ReceiptSerialEntity[],
@@ -548,8 +549,10 @@ export function reconcileReceiptLineSerials(
const keptIndexes = new Set<number>();
const surplusEntityIds: string[] = [];
- const ordered = [...entities].sort((a, b) =>
- (a.createdAt ?? "").localeCompare(b.createdAt ?? "")
+ const ordered = [...entities].sort(
+ (a, b) =>
+ Number(b.hasSerial) - Number(a.hasSerial) ||
+ (a.createdAt ?? "").localeCompare(b.createdAt ?? "")
);
for (const entity of ordered) {
const index = entity.index;
@@ -564,6 +567,66 @@ export function reconcileReceiptLineSerials(
return { missingIndexes, surplusEntityIds };
}
+export type SerialBoxEntity = { id: string; hasHistory: boolean };
+
+export type SerialBoxWrite =
+ | { kind: "clear"; releaseIds: string[] }
+ | { kind: "taken"; reason: "box" | "unit"; releaseIds: string[] }
+ | { kind: "write"; targetId: string | undefined; releaseIds: string[] };
+
+export function planSerialBoxWrite(args: {
+ receiptLineId: string;
+ index: number;
+ serialNumber: string;
+ box: SerialBoxEntity[];
+ withSerial: (SerialBoxEntity & {
+ attributes: Record<string, unknown>;
+ /** Its `Receipt` is voided: the box it names no longer holds it. */
+ onVoidedReceipt?: boolean;
+ })[];
+}): SerialBoxWrite {
+ const boxIds = args.box.map((entity) => entity.id);
+ if (!args.serialNumber.trim()) return { kind: "clear", releaseIds: boxIds };
+
+ const isInThisBox = (attributes: Record<string, unknown>) =>
+ attributes["Receipt Line"] === args.receiptLineId &&
+ attributes["Receipt Line Index"] === args.index;
+
+ if (args.withSerial.some((entity) => entity.hasHistory)) {
+ return { kind: "taken", reason: "unit", releaseIds: boxIds };
+ }
+
+ // Only this box's record or one from a voided receipt can be taken over;
+ // any other record with the serial belongs to another box or document (a
+ // job's reserved serial).
+ const elsewhere = args.withSerial.filter(
+ (entity) => !entity.onVoidedReceipt && !isInThisBox(entity.attributes)
+ );
+ if (elsewhere.length > 0) {
+ return {
+ kind: "taken",
+ reason: elsewhere.some(
+ (entity) => "Receipt Line Index" in entity.attributes
+ )
+ ? "box"
+ : "unit",
+ releaseIds: boxIds
+ };
+ }
+
+ const targetId =
+ (
+ args.withSerial.find((entity) => isInThisBox(entity.attributes)) ??
+ args.withSerial[0]
+ )?.id ?? args.box.find((entity) => !entity.hasHistory)?.id;
+
+ return {
+ kind: "write",
+ targetId,
+ releaseIds: boxIds.filter((id) => id !== targetId)
+ };
+}
+
export const warehouseTransferValidator = z
.object({
id: zfd.text(z.string().optional()),
diff --git a/apps/erp/app/modules/inventory/inventory.server.ts b/apps/erp/app/modules/inventory/inventory.server.ts
index 6e85b32d80..5665aaf36b 100644
--- a/apps/erp/app/modules/inventory/inventory.server.ts
+++ b/apps/erp/app/modules/inventory/inventory.server.ts
@@ -461,11 +461,17 @@ export const postReceipt = defineServiceFn({
let failure: CarbonError | null = null;
try {
- await service.reconcileReceiptSerialEntities(serviceRole, {
- receiptId,
- companyId,
- lines: lines.data ?? []
- });
+ const { linesMissingSerials } =
+ await service.reconcileReceiptSerialEntities(ctx.asSystem.pg, {
+ receiptId,
+ companyId,
+ isSalesReturn: receipt.data.sourceDocument === "Sales Return Order",
+ lines: lines.data ?? []
+ });
+ if (linesMissingSerials.length > 0) {
+ await backToDraft();
+ return ctx.error("rule", "Serial numbers are missing");
+ }
const posted = await invokePosting(
ctx,
"post-receipt",
@@ -477,11 +483,14 @@ export const postReceipt = defineServiceFn({
);
if (posted.error) {
await backToDraft();
- return service.serverFnFailure(
- ctx,
- posted.error,
- "Failed to post receipt"
- );
+ // Below 500 the posting refused the receipt, in words for the person.
+ return posted.error.status < 500
+ ? service.serverFnFailure(
+ ctx,
+ posted.error,
+ posted.error.message || "Failed to post receipt"
+ )
+ : ctx.error("internal", "Failed to post receipt", posted.error);
}
} catch (thrown) {
await backToDraft();
@@ -591,11 +600,14 @@ export const voidReceipt = defineServiceFn({
service.postReceipt
);
if (voided.error) {
- return service.serverFnFailure(
- ctx,
- voided.error,
- "Failed to void receipt"
- );
+ // Below 500 the posting refused the void, in words for the person.
+ return voided.error.status < 500
+ ? service.serverFnFailure(
+ ctx,
+ voided.error,
+ voided.error.message || "Failed to void receipt"
+ )
+ : ctx.error("internal", "Failed to void receipt", voided.error);
}
return { receiptId };
}
@@ -685,12 +697,58 @@ export const updateReceiptLines = defineServiceFn({
return ctx.error("rule", RECEIPT_LOCKED);
}
+ if (field === "receivedQuantity") {
+ const receivedQuantity = Number(value || 0);
+ if (!Number.isFinite(receivedQuantity)) {
+ return ctx.error("validation", "Received quantity must be a number");
+ }
+ // Drop serials beyond the new quantity in the same transaction.
+ try {
+ await ctx.asSystem.pg.transaction().execute(async (trx) => {
+ const updated = await trx
+ .updateTable("receiptLine")
+ .set({
+ receivedQuantity,
+ updatedBy: ctx.auditUserId,
+ updatedAt: datetime.timestamp()
+ })
+ .where("id", "in", ids)
+ .where("companyId", "=", ctx.company.id)
+ .returning([
+ "id",
+ "receiptId",
+ "receivedQuantity",
+ "requiresSerialTracking"
+ ])
+ .execute();
+ if (updated.length === 0) return;
+
+ const receipts = await trx
+ .selectFrom("receipt")
+ .select(["id", "sourceDocument"])
+ .where("id", "in", [...new Set(updated.map((l) => l.receiptId))])
+ .where("companyId", "=", ctx.company.id)
+ .where("status", "=", "Draft")
+ .execute();
+ for (const receipt of receipts) {
+ await service.reconcileReceiptSerialsInTransaction(trx, {
+ receiptId: receipt.id,
+ companyId: ctx.company.id,
+ isSalesReturn: receipt.sourceDocument === "Sales Return Order",
+ lines: updated.filter((l) => l.receiptId === receipt.id)
+ });
+ }
+ });
+ } catch (error) {
+ return ctx.error("internal", "Failed to update receipt lines", error);
+ }
+ return { ids };
+ }
+
const update = await ctx.asCaller.supabase
.from("receiptLine")
.update({
- ...(field === "storageUnitId"
- ? { storageUnitId: value || null }
- : { receivedQuantity: Number(value || 0) }),
+ storageUnitId: value || null,
updatedBy: ctx.auditUserId,
updatedAt: datetime.timestamp()
})
@@ -855,8 +913,10 @@ export const setReceiptLineBatch = defineServiceFn({
* Set one serial number of a serial-tracked receipt line.
*
* @remarks
- * `index` is the unit's position on the line, from 0. A serial number the
- * line's item already uses at another receipt line or position is refused.
+ * `index` is the unit's position on the line, from 0. An empty serial number
+ * clears the position. A serial number the line's item already uses at another
+ * position, or that belongs to an existing unit with stock movements, is
+ * refused and the position is cleared.
*
* @mcp
*/
@@ -871,76 +931,60 @@ export const setReceiptLineSerial = defineServiceFn({
permission: { create: "inventory" },
async run(ctx, input) {
- const [line, receipt] = await Promise.all([
- service.receiptLineOf(ctx, input),
- ctx.asSystem.supabase
- .from("receipt")
- .select("status")
- .eq("id", input.receiptId)
- .eq("companyId", ctx.company.id)
- .maybeSingle()
- ]);
+ const line = await service.receiptLineOf(ctx, input);
if (line instanceof Error) return line;
- if (receipt.error) {
- return ctx.error("internal", "Failed to load receipt", receipt.error);
- }
- if (receipt.data?.status !== "Draft") {
- return ctx.error("rule", RECEIPT_LOCKED);
- }
-
- const existing = await ctx.asCaller.supabase
- .from("trackedEntity")
- .select("id, attributes")
- .eq("sourceDocumentId", line.itemId ?? "")
- .eq("readableId", input.serialNumber)
- .eq("companyId", ctx.company.id)
- .maybeSingle();
- if (existing.error) {
- return ctx.error(
- "internal",
- "Failed to check serial number index",
- existing.error
- );
- }
- // Only a serial entity (one with a receipt line index) at a different
- // line or position conflicts.
- if (existing.data) {
- const attributes = (existing.data.attributes ?? {}) as Record<
- string,
- unknown
- >;
- if (
- "Receipt Line Index" in attributes &&
- (attributes["Receipt Line"] !== input.receiptLineId ||
- attributes["Receipt Line Index"] !== input.index)
- ) {
+ const box = {
+ companyId: ctx.company.id,
+ receiptLineId: input.receiptLineId,
+ index: input.index
+ };
+ let saved: service.ReceiptSerialBoxResult;
+ try {
+ saved = await service.saveReceiptSerialBox(ctx.asSystem.pg, {
+ ...box,
+ receiptId: input.receiptId,
+ itemId: line.itemId ?? "",
+ serialNumber: input.serialNumber.trim(),
+ expiryDate: input.expiryDate
+ });
+ } catch (error) {
+ // The position shows a value that did not save; empty it so its
+ // previous serial cannot post in its place.
+ await service
+ .clearReceiptSerialBox(ctx.asSystem.pg, box)
+ .catch((clearError) =>
+ logger.error("Failed to clear the serial box", {
+ ...box,
+ error: clearError
+ })
+ );
+ if (isUniqueViolation(error)) {
return ctx.error(
"conflict",
- "Serial number is already used for a different item or position"
+ "Serial number already exists for this item"
);
}
+ return ctx.error("internal", "Failed to update tracking", error);
}
- const updated = await ctx.asSystem.supabase.rpc(
- "update_receipt_line_serial_tracking",
- {
- p_tracked_entity_id: existing.data?.id,
- p_receipt_line_id: input.receiptLineId,
- p_receipt_id: input.receiptId,
- p_serial_number: input.serialNumber,
- p_index: input.index,
- p_expiry_date: input.expiryDate || undefined
- }
- );
- if (updated.error) {
- if (isUniqueViolation(updated.error)) {
- return ctx.error(
- "conflict",
- "Serial number already exists for this item"
- );
+ if (!saved.ok) {
+ switch (saved.reason) {
+ case "notFound":
+ return ctx.error("notFound", RECEIPT_NOT_FOUND);
+ case "locked":
+ return ctx.error("rule", RECEIPT_LOCKED);
+ case "unit":
+ return ctx.error(
+ "conflict",
+ "Serial number already belongs to an existing unit"
+ );
+ case "box":
+ return ctx.error(
+ "conflict",
+ "Serial number is already used for a different item or position"
+ );
}
- return ctx.error("internal", "Failed to update tracking", updated.error);
}
return { receiptLineId: input.receiptLineId, index: input.index };
}
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index ade57e1f15..75bfbdbe56 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -50,6 +50,11 @@ import {
type SharedTakes,
splitTakeByBin
} from "@carbon/database/picked-consumption";
+import {
+ idsWithLiveStockHistory,
+ releaseReceiptSerialEntities,
+ voidedReceiptIds
+} from "@carbon/database/receipt-serials";
import {
contains,
deleteRows,
@@ -201,6 +206,7 @@ import {
isPickingListLocked,
isStockTransferLocked,
isWarehouseTransferLocked,
+ planSerialBoxWrite,
type receiptFixedAssetLineUpdateValidator,
reconcileReceiptLineSerials,
shippingCarrierType
@@ -913,63 +919,234 @@ export async function getReceiptLineTracking(
.eq("companyId", companyId);
}
+function selectReceiptSerialBox(
+ db: Kysely<KyselyDatabase>,
+ args: { companyId: string; receiptLineId: string; index: number }
+) {
+ return db
+ .selectFrom("trackedEntity")
+ .select("id")
+ .where("companyId", "=", args.companyId)
+ .where(sql<string>`attributes->>'Receipt Line'`, "=", args.receiptLineId)
+ .where(
+ sql<string>`attributes->>'Receipt Line Index'`,
+ "=",
+ String(args.index)
+ )
+ .execute();
+}
+
+/** One serial save of a line at a time: two saves into an empty box would each insert a record. */
+async function lockReceiptLine(
+ trx: Kysely<KyselyDatabase>,
+ companyId: string,
+ receiptLineId: string
+) {
+ await trx
+ .selectFrom("receiptLine")
+ .select("id")
+ .where("id", "=", receiptLineId)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .execute();
+}
+
+export type ReceiptSerialBoxResult =
+ | { ok: true }
+ | { ok: false; reason: "notFound" | "locked" | "box" | "unit" };
+
/**
- * Deletes stale serial tracked entities for a receipt's serial-tracked lines
- * before posting. Post-receipt flips one serial per index in
- * [0, receivedQuantity) to Available; orphaned (reduced quantity) or duplicate
- * (edited serial) entities would otherwise become phantom Available serials.
- * The keep/delete decision is owned by `reconcileReceiptLineSerials` so it
- * stays in lockstep with the post-time validation in ReceiptPostModal.
+ * Saves one serial box of a receipt line (`planSerialBoxWrite`) in one
+ * transaction: an empty serial clears it, a refused one empties it.
*/
-export async function reconcileReceiptSerialEntities(
- client: SupabaseClient<Database>,
+export async function saveReceiptSerialBox(
+ db: Kysely<KyselyDatabase>,
args: {
- receiptId: string;
companyId: string;
- lines: {
- id: string;
- receivedQuantity: number | null;
- requiresSerialTracking?: boolean | null;
- }[];
+ receiptId: string;
+ receiptLineId: string;
+ itemId: string;
+ index: number;
+ serialNumber: string;
+ expiryDate?: string | null;
}
-) {
+): Promise<ReceiptSerialBoxResult> {
+ const { companyId, receiptId, receiptLineId, itemId, index, serialNumber } =
+ args;
+ return db.transaction().execute(async (trx) => {
+ await lockReceiptLine(trx, companyId, receiptLineId);
+ const receipt = await trx
+ .selectFrom("receipt")
+ .select("status")
+ .where("id", "=", receiptId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!receipt) return { ok: false, reason: "notFound" };
+ if (receipt.status !== "Draft") return { ok: false, reason: "locked" };
+
+ const box = await selectReceiptSerialBox(trx, {
+ companyId,
+ receiptLineId,
+ index
+ });
+
+ const withSerial = serialNumber
+ ? await trx
+ .selectFrom("trackedEntity")
+ .select(["id", "attributes"])
+ .where("sourceDocumentId", "=", itemId)
+ .where("readableId", "=", serialNumber)
+ .where("companyId", "=", companyId)
+ .execute()
+ : [];
+
+ // A serial from a voided receipt was never received: its movements are
+ // the receipt and its void, and the box it names is gone. The new box
+ // takes the same entity, so one unit keeps one history.
+ const history = await idsWithLiveStockHistory(trx, companyId, [
+ ...box.map((entity) => entity.id),
+ ...withSerial.map((entity) => entity.id)
+ ]);
+ const voided = await voidedReceiptIds(
+ trx,
+ companyId,
+ withSerial.flatMap((entity) => {
+ const receiptOfEntity = (entity.attributes as Record<string, unknown>)
+ ?.Receipt;
+ return typeof receiptOfEntity === "string" ? [receiptOfEntity] : [];
+ })
+ );
+
+ const candidates = withSerial.map((entity) => {
+ const attributes = (entity.attributes ?? {}) as Record<string, unknown>;
+ return {
+ id: entity.id,
+ hasHistory: history.has(entity.id),
+ attributes,
+ onVoidedReceipt:
+ typeof attributes.Receipt === "string" &&
+ voided.has(attributes.Receipt)
+ };
+ });
+ const plan = planSerialBoxWrite({
+ receiptLineId,
+ index,
+ serialNumber,
+ box: box.map((entity) => ({
+ id: entity.id,
+ hasHistory: history.has(entity.id)
+ })),
+ withSerial: candidates
+ });
+
+ if (plan.kind === "write") {
+ await sql`SELECT update_receipt_line_serial_tracking(
+ p_receipt_line_id => ${receiptLineId},
+ p_receipt_id => ${receiptId},
+ p_serial_number => ${serialNumber},
+ p_index => ${index}::int,
+ p_tracked_entity_id => ${plan.targetId ?? null}::text,
+ p_expiry_date => ${args.expiryDate || null}::text
+ )`.execute(trx);
+
+ // The void drained the record to 0 / Consumed, and the function's
+ // update keeps both: start it again as a new draft serial starts.
+ const reusedFromVoid = candidates.some(
+ (entity) => entity.id === plan.targetId && entity.onVoidedReceipt
+ );
+ if (reusedFromVoid && plan.targetId) {
+ await trx
+ .updateTable("trackedEntity")
+ .set({ quantity: 1, status: "On Hold" })
+ .where("id", "=", plan.targetId)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+ }
+
+ await releaseReceiptSerialEntities(trx, companyId, plan.releaseIds);
+
+ return plan.kind === "taken"
+ ? { ok: false, reason: plan.reason }
+ : { ok: true };
+ });
+}
+
+/** Empties one serial box of a receipt line. */
+export async function clearReceiptSerialBox(
+ db: Kysely<KyselyDatabase>,
+ args: { companyId: string; receiptLineId: string; index: number }
+): Promise<void> {
+ await db.transaction().execute(async (trx) => {
+ await lockReceiptLine(trx, args.companyId, args.receiptLineId);
+ const box = await selectReceiptSerialBox(trx, args);
+ await releaseReceiptSerialEntities(
+ trx,
+ args.companyId,
+ box.map((entity) => entity.id)
+ );
+ });
+}
+
+export async function reconcileReceiptSerialEntities(
+ db: Kysely<KyselyDatabase>,
+ args: ReconcileReceiptSerialsArgs
+): Promise<{ linesMissingSerials: string[] }> {
+ return db
+ .transaction()
+ .execute((trx) => reconcileReceiptSerialsInTransaction(trx, args));
+}
+
+type ReconcileReceiptSerialsArgs = {
+ receiptId: string;
+ companyId: string;
+ isSalesReturn: boolean;
+ lines: {
+ id: string;
+ receivedQuantity: number | null;
+ requiresSerialTracking?: boolean | null;
+ }[];
+};
+
+export async function reconcileReceiptSerialsInTransaction(
+ trx: Kysely<KyselyDatabase>,
+ args: ReconcileReceiptSerialsArgs
+): Promise<{ linesMissingSerials: string[] }> {
const serialLines = args.lines.filter((line) => line.requiresSerialTracking);
- if (serialLines.length === 0) return;
+ if (serialLines.length === 0) return { linesMissingSerials: [] };
- const { data: serialEntities } = await client
- .from("trackedEntity")
- .select("id, attributes, createdAt, readableId")
- .eq("attributes ->> Receipt", args.receiptId)
- .eq("companyId", args.companyId);
+ const entities = await trx
+ .selectFrom("trackedEntity")
+ .select([
+ "id",
+ "readableId",
+ sql<string | null>`attributes->>'Receipt Line'`.as("receiptLineId"),
+ sql<number | null>`(attributes->>'Receipt Line Index')::int`.as("index"),
+ sql<string>`"createdAt"::text`.as("createdAt")
+ ])
+ .where("companyId", "=", args.companyId)
+ .where(sql<string>`attributes->>'Receipt'`, "=", args.receiptId)
+ .execute();
- const idsToDelete = serialLines.flatMap((line) => {
- const entities = (serialEntities ?? [])
- .filter(
- (e) =>
- (e.attributes as TrackedEntityAttributes)?.["Receipt Line"] ===
- line.id
- )
- .map((e) => ({
- id: e.id,
- index: (e.attributes as TrackedEntityAttributes)?.[
- "Receipt Line Index"
- ],
- hasSerial: !!e.readableId,
- createdAt: e.createdAt
- }));
- return reconcileReceiptLineSerials(
- entities,
+ const linesMissingSerials: string[] = [];
+ const surplusIds = serialLines.flatMap((line) => {
+ const { missingIndexes, surplusEntityIds } = reconcileReceiptLineSerials(
+ entities
+ .filter((e) => e.receiptLineId === line.id)
+ .map((e) => ({
+ id: e.id,
+ index: e.index ?? undefined,
+ hasSerial: args.isSalesReturn || !!e.readableId,
+ createdAt: e.createdAt
+ })),
Number(line.receivedQuantity ?? 0)
- ).surplusEntityIds;
+ );
+ if (missingIndexes.length > 0) linesMissingSerials.push(line.id);
+ return surplusEntityIds;
});
- if (idsToDelete.length > 0) {
- await client
- .from("trackedEntity")
- .delete()
- .in("id", idsToDelete)
- .eq("companyId", args.companyId);
- }
+ await releaseReceiptSerialEntities(trx, args.companyId, surplusIds);
+ return { linesMissingSerials };
}
export async function getReceiptFiles(
@@ -9093,6 +9270,181 @@ export function planReceiptVoidCostLedger(
};
}
+type VoidGuardDb = Kysely<KyselyDatabase> | Transaction<KyselyDatabase>;
+
+export type StockPosition = {
+ itemId: string;
+ locationId: string | null;
+ storageUnitId: string | null;
+ trackedEntityId: string | null;
+};
+
+export type ReversingRow = StockPosition & { quantity: number };
+
+const positionKey = (row: StockPosition) =>
+ [
+ row.itemId,
+ row.locationId ?? "",
+ row.storageUnitId ?? "",
+ row.trackedEntityId ?? ""
+ ].join("|");
+
+/**
+ * The positions the reversal would drive below zero. A tracked row is checked
+ * per serial or batch, so a unit that left its bin is caught even when the bin
+ * holds other stock of the item. Reversal rows that add stock (a negative
+ * receipt line) need nothing.
+ */
+export function findVoidShortfalls(
+ reversingRows: ReversingRow[],
+ onHand: ReadonlyMap<string, number>
+): (StockPosition & { required: number; onHand: number })[] {
+ const required = new Map<string, StockPosition & { required: number }>();
+ for (const row of reversingRows) {
+ if (row.quantity >= 0) continue;
+ const key = positionKey(row);
+ const entry = required.get(key) ?? { ...row, required: 0 };
+ entry.required += -row.quantity;
+ required.set(key, entry);
+ }
+
+ return [...required.entries()].flatMap(([key, entry]) => {
+ const available = onHand.get(key) ?? 0;
+ return available + EPSILON < entry.required
+ ? [
+ {
+ itemId: entry.itemId,
+ locationId: entry.locationId,
+ storageUnitId: entry.storageUnitId,
+ trackedEntityId: entry.trackedEntityId,
+ required: entry.required,
+ onHand: available
+ }
+ ]
+ : [];
+ });
+}
+
+/** Refuses the void when the received stock is no longer where it was received. */
+export async function assertReceivedStockOnHand(
+ trx: VoidGuardDb,
+ companyId: string,
+ reversingRows: ReversingRow[]
+): Promise<void> {
+ const removing = reversingRows.filter((row) => row.quantity < 0);
+ if (removing.length === 0) return;
+
+ const itemIds = [...new Set(removing.map((row) => row.itemId))];
+ const locationIds = [
+ ...new Set(removing.flatMap((row) => row.locationId ?? []))
+ ];
+ const withoutLocation = removing.some((row) => row.locationId === null);
+ const rows = await trx
+ .selectFrom("itemLedger")
+ .select([
+ "itemId",
+ "locationId",
+ "storageUnitId",
+ "trackedEntityId",
+ (eb) => eb.fn.sum<number>("quantity").as("quantity")
+ ])
+ .where("companyId", "=", companyId)
+ .where("itemId", "in", itemIds)
+ .where((eb) =>
+ eb.or([
+ ...(locationIds.length > 0
+ ? [eb("locationId", "in", locationIds)]
+ : []),
+ ...(withoutLocation ? [eb("locationId", "is", null)] : [])
+ ])
+ )
+ .groupBy(["itemId", "locationId", "storageUnitId", "trackedEntityId"])
+ .execute();
+
+ // Untracked rows are compared with the bin's untracked stock; tracked rows
+ // with that serial or batch alone.
+ const onHand = new Map<string, number>();
+ for (const row of rows) {
+ onHand.set(positionKey(row), Number(row.quantity ?? 0));
+ }
+
+ if (findVoidShortfalls(removing, onHand).length > 0) {
+ throw new InvalidInputError(
+ "Cannot void: stock received on this receipt was moved, picked or shipped since it was received. Correct the remainder with an inventory adjustment instead."
+ );
+ }
+}
+
+/**
+ * Locks the receipt and re-reads its status inside the void's transaction, so
+ * two voids sent at once cannot both reverse it. Inspection writes read the
+ * receipt FOR SHARE, so they also wait for the void to commit.
+ */
+export async function lockPostedReceipt(
+ trx: VoidGuardDb,
+ companyId: string,
+ receiptId: string
+): Promise<void> {
+ const receipt = await trx
+ .selectFrom("receipt")
+ .select("status")
+ .where("id", "=", receiptId)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ if (receipt?.status !== "Posted") {
+ throw new InvalidInputError("Can only void posted receipts");
+ }
+}
+
+/**
+ * Refuses the void when an inspection of the receipt rejected an untracked
+ * lot. The reject route writes that lot off; the void would then take the same
+ * stock out a second time.
+ */
+export async function assertNoRejectedUntrackedLot(
+ trx: VoidGuardDb,
+ companyId: string,
+ receiptId: string
+): Promise<void> {
+ const rejected = await trx
+ .selectFrom("inspection")
+ .innerJoin("item", (join) =>
+ join
+ .onRef("item.id", "=", "inspection.itemId")
+ .onRef("item.companyId", "=", "inspection.companyId")
+ )
+ .select("inspection.inspectionId")
+ .where("inspection.companyId", "=", companyId)
+ .where("inspection.sourceDocument", "=", "Receipt")
+ .where("inspection.sourceDocumentId", "=", receiptId)
+ .where("inspection.status", "=", "Failed")
+ .where("item.itemTrackingType", "=", "Inventory")
+ .executeTakeFirst();
+ if (rejected) {
+ throw new InvalidInputError(
+ `Cannot void: inspection ${rejected.inspectionId} rejected this stock and wrote it off. Correct the remainder with an inventory adjustment instead.`
+ );
+ }
+}
+
+/** An item ledger row the void is about to insert, as a stock position. */
+export function toReversingRow(row: {
+ itemId: string;
+ locationId?: string | null;
+ storageUnitId?: string | null;
+ trackedEntityId?: string | null;
+ quantity: number | string;
+}): ReversingRow {
+ return {
+ itemId: row.itemId,
+ locationId: row.locationId ?? null,
+ storageUnitId: row.storageUnitId ?? null,
+ trackedEntityId: row.trackedEntityId ?? null,
+ quantity: Number(row.quantity)
+ };
+}
+
export const postReceiptInput = z.object({
type: z.enum(["post", "void"]).default("post"),
receiptId: z.string(),
@@ -9312,7 +9664,7 @@ export async function postReceipt(
if (type === "void") {
if (receiptHeader.status !== "Posted") {
- throw new Error("Can only void posted receipts");
+ throw new InvalidInputError("Can only void posted receipts");
}
// The enable reset the cost layers this receipt created.
@@ -9324,7 +9676,7 @@ export async function postReceipt(
);
if (receiptHeader.invoiced) {
- throw new Error(
+ throw new InvalidInputError(
"Cannot void a receipt created by a purchase invoice. Void the invoice instead."
);
}
@@ -9339,7 +9691,7 @@ export async function postReceipt(
receiptHeader.sourceDocument !== "Purchase Order" &&
receiptHeader.sourceDocument !== "Sales Return Order"
) {
- throw new Error(
+ throw new InvalidInputError(
`Void is only supported for receipts with source document "Purchase Order" or "Sales Return Order"`
);
}
@@ -9368,7 +9720,7 @@ export async function postReceipt(
if (creditMemos.error)
throw new Error("Failed to check for credit memos");
if ((creditMemos.data ?? []).length > 0) {
- throw new Error(
+ throw new InvalidInputError(
"Cannot void: a credit memo exists for this return order. Void it first."
);
}
@@ -9447,7 +9799,13 @@ export async function postReceipt(
: null;
await db.transaction().execute(async (trx) => {
+ await lockPostedReceipt(trx, companyId, receiptId);
await assertPostingStatusUnchanged(trx, companyId, postingStatus);
+ await assertReceivedStockOnHand(
+ trx,
+ companyId,
+ reversingItemLedger.map(toReversingRow)
+ );
// Refuse to void when this receipt's cost layers were already
// (partially) consumed — the returned stock moved on (dispositioned,
// sold, scrapped), so reversing the full receipt would drive stock
@@ -9467,7 +9825,7 @@ export async function postReceipt(
Number(layer.remainingQuantity) < Number(layer.quantity)
);
if (consumed) {
- throw new Error(
+ throw new InvalidInputError(
"Cannot void: stock received on this return was already consumed. Correct the remainder with an inventory adjustment instead."
);
}
@@ -9834,7 +10192,7 @@ export async function postReceipt(
Boolean(asset.fixedAssetClass?.isConstructionInProgress);
if (isConstructionInProgress) {
if (asset.status !== "Under Construction") {
- throw new Error(
+ throw new InvalidInputError(
"Asset was capitalized; reverse the capitalization first"
);
}
@@ -9917,28 +10275,29 @@ export async function postReceipt(
purchaseOrderStatusVoid = "To Invoice";
}
- const trackedEntityUpdatesVoid =
- receiptLineTracking.data?.reduce<
- Record<
- string,
- Database["public"]["Tables"]["trackedEntity"]["Update"]
- >
- >((acc, trackedEntity) => {
- // Voiding restores the lot, but a lot with nothing in it must not
- // come back Available — that is the zero-quantity husk the drain
- // rule forbids. Scrapped/Rejected are terminal quality states and
- // must survive a void, so keep them; everything else returns to
- // Available (the helper then drains a zero-quantity lot to Consumed).
- acc[trackedEntity.id] = settleQuantity({
- quantity: Number(trackedEntity.quantity ?? 0),
+ // The receipt's serials and batches were never received, so the void
+ // drains them to zero: they leave every on-hand list and no picker
+ // offers them. Leaving them at their received quantity made them
+ // Available again (even one On Hold for inspection), pickable on a
+ // shipment or job with no stock behind them. Scrapped/Rejected are
+ // quality markers, already off on-hand, and survive the void at zero
+ // (as update_receipt_line_batch_tracking keeps them); everything else
+ // is Consumed. Not settleQuantity: its drain turns Rejected into
+ // Consumed.
+ const trackedEntitiesVoid = (receiptLineTracking.data ?? []).map(
+ (trackedEntity) => ({
+ id: trackedEntity.id,
+ voidedQuantity: Number(trackedEntity.quantity ?? 0),
+ update: {
+ quantity: 0,
status:
trackedEntity.status === "Scrapped" ||
trackedEntity.status === "Rejected"
? trackedEntity.status
- : ("Available" as const)
- });
- return acc;
- }, {}) ?? {};
+ : ("Consumed" as const)
+ }
+ })
+ );
// A Provisional journal has no accounting period.
const accountingPeriodId =
@@ -9947,7 +10306,14 @@ export async function postReceipt(
: null;
await db.transaction().execute(async (trx) => {
+ await lockPostedReceipt(trx, companyId, receiptId);
await assertPostingStatusUnchanged(trx, companyId, postingStatus);
+ await assertNoRejectedUntrackedLot(trx, companyId, receiptId);
+ await assertReceivedStockOnHand(
+ trx,
+ companyId,
+ reversingItemLedger.map(toReversingRow)
+ );
// The cost layers this receipt wrote. Without this, a voided
// receipt's layer stayed open and later issues consumed stock that
// was never there.
@@ -9977,7 +10343,7 @@ export async function postReceipt(
}))
);
if (costLedgerPlan.consumed) {
- throw new Error(
+ throw new InvalidInputError(
"Cannot void: stock received on this receipt was already consumed. Correct the remainder with an inventory adjustment instead."
);
}
@@ -10093,7 +10459,7 @@ export async function postReceipt(
.execute();
}
- if (Object.keys(trackedEntityUpdatesVoid).length > 0) {
+ if (trackedEntitiesVoid.length > 0) {
const voidActivity = await trx
.insertInto("trackedActivity")
.values({
@@ -10115,9 +10481,11 @@ export async function postReceipt(
const voidActivityId = voidActivity[0]!.id;
- for await (const [id, update] of Object.entries(
- trackedEntityUpdatesVoid
- )) {
+ for await (const {
+ id,
+ voidedQuantity,
+ update
+ } of trackedEntitiesVoid) {
await trx
.updateTable("trackedEntity")
.set(update)
@@ -10131,7 +10499,7 @@ export async function postReceipt(
.values({
trackedActivityId: voidActivityId,
trackedEntityId: id,
- quantity: update.quantity ?? 0,
+ quantity: voidedQuantity,
companyId,
createdBy: userId,
createdAt: today
@@ -10157,7 +10525,7 @@ export async function postReceipt(
}
if (receiptHeader.status === "Voided") {
- throw new Error("Cannot post a voided receipt");
+ throw new InvalidInputError("Cannot post a voided receipt");
}
switch (receiptHeader.sourceDocument) {
@@ -11482,7 +11850,7 @@ export async function postReceipt(
// its caps validated, so it must be confirmed (To Receive) before
// receiving.
if (salesReturnOrder.data.status !== "To Receive") {
- throw new Error(
+ throw new InvalidInputError(
`Cannot post a receipt against a return order in ${salesReturnOrder.data.status} status`
);
}
@@ -11813,7 +12181,9 @@ export async function postReceipt(
lockedReceipt.status === "Posted" ||
lockedReceipt.status === "Voided"
) {
- throw new Error(`Receipt is already ${lockedReceipt.status}`);
+ throw new InvalidInputError(
+ `Receipt is already ${lockedReceipt.status}`
+ );
}
// cancelSalesReturnOrder locks this same order row — re-check the
@@ -11827,7 +12197,7 @@ export async function postReceipt(
.forUpdate()
.executeTakeFirstOrThrow();
if (lockedOrder.status !== "To Receive") {
- throw new Error(
+ throw new InvalidInputError(
`Cannot post a receipt against a return order in ${lockedOrder.status} status`
);
}
diff --git a/apps/erp/app/modules/inventory/inventory.void-guards.test.ts b/apps/erp/app/modules/inventory/inventory.void-guards.test.ts
new file mode 100644
index 0000000000..3b1aae5d7d
--- /dev/null
+++ b/apps/erp/app/modules/inventory/inventory.void-guards.test.ts
@@ -0,0 +1,70 @@
+// 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 { findVoidShortfalls } from "./inventory.service";
+
+const at = (
+ storageUnitId: string | null,
+ trackedEntityId: string | null = null
+) => ({ itemId: "item", locationId: "loc", storageUnitId, trackedEntityId });
+
+const key = (
+ storageUnitId: string | null,
+ trackedEntityId: string | null = null
+) => ["item", "loc", storageUnitId ?? "", trackedEntityId ?? ""].join("|");
+
+describe("findVoidShortfalls", () => {
+ it("passes when the received stock is still in its bin", () => {
+ expect(
+ findVoidShortfalls(
+ [{ ...at("A1", "lot"), quantity: -4 }],
+ new Map([[key("A1", "lot"), 4]])
+ )
+ ).toEqual([]);
+ });
+
+ it("refuses a lot that moved to another bin", () => {
+ expect(
+ findVoidShortfalls(
+ [{ ...at("A1", "lot"), quantity: -4 }],
+ new Map([
+ [key("A1", "lot"), 0],
+ [key("B2", "lot"), 4]
+ ])
+ )
+ ).toEqual([{ ...at("A1", "lot"), required: 4, onHand: 0 }]);
+ });
+
+ it("checks a serial on its own, whatever else the bin holds", () => {
+ expect(
+ findVoidShortfalls(
+ [{ ...at("A1", "sn-1"), quantity: -1 }],
+ new Map([
+ [key("A1", "sn-1"), 0],
+ [key("A1", "sn-2"), 1],
+ [key("A1"), 30]
+ ])
+ )
+ ).toHaveLength(1);
+ });
+
+ it("adds up two lines of one item that went into the same bin", () => {
+ expect(
+ findVoidShortfalls(
+ [
+ { ...at("A1"), quantity: -3 },
+ { ...at("A1"), quantity: -3 }
+ ],
+ new Map([[key("A1"), 5]])
+ )
+ ).toEqual([{ ...at("A1"), required: 6, onHand: 5 }]);
+ });
+
+ it("needs nothing for a row that puts stock back", () => {
+ expect(
+ findVoidShortfalls([{ ...at(null), quantity: 2 }], new Map())
+ ).toEqual([]);
+ });
+});
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
index 261a2891bb..8b12cb7578 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
@@ -192,7 +192,12 @@ const ReceiptHeader = () => {
/>
{postModal.isOpen && <ReceiptPostModal onClose={postModal.onClose} />}
- {voidModal.isOpen && <ReceiptVoidModal onClose={voidModal.onClose} />}
+ {voidModal.isOpen && (
+ <ReceiptVoidModal
+ isSalesReturn={receipt.sourceDocument === "Sales Return Order"}
+ onClose={voidModal.onClose}
+ />
+ )}
{deleteDisclosure.isOpen && (
<ConfirmDelete
action={path.to.deleteReceipt(receiptId)}
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index a0c1fecb47..24fceffa0c 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -1262,26 +1262,17 @@ function SerialForm({
[serialNumbers]
);
- const updateSerialNumber = useCallback(
- async (serialNumber: { index: number; number: string }) => {
- if (!receipt?.id || !serialNumber.number.trim()) return;
-
- const error = validateSerialNumber(
- serialNumber.number,
- serialNumber.index
- );
- if (error) {
- setErrors((prev) => ({ ...prev, [serialNumber.index]: error }));
- return;
- }
+ const saveSerialNumber = useCallback(
+ async (index: number, value: string) => {
+ if (!receipt?.id) return { ok: true, error: null };
const formData = new FormData();
formData.append("itemId", line.itemId!);
formData.append("receiptId", receipt.id);
formData.append("receiptLineId", line.id!);
formData.append("trackingType", "serial");
- formData.append("index", serialNumber.index.toString());
- formData.append("serialNumber", serialNumber.number.trim());
+ formData.append("index", index.toString());
+ formData.append("serialNumber", value);
if (expiryDate) {
formData.append("expiryDate", expiryDate);
}
@@ -1295,31 +1286,30 @@ function SerialForm({
const result: { error: { message: string } | null } | null = response.ok
? await response.json()
: null;
-
- if (result && !result.error) {
- // Clear error if submission was successful
- setErrors((prev) => {
- const newErrors = { ...prev };
- delete newErrors[serialNumber.index];
- return newErrors;
- });
- } else {
- setErrors((prev) => ({
- ...prev,
- [serialNumber.index]:
- result?.error?.message ?? "Serial number already exists"
- }));
- }
- } catch (error) {
- if (error instanceof Error && error.message.includes("duplicate")) {
- setErrors((prev) => ({
- ...prev,
- [serialNumber.index]: "Serial number already exists for this item"
- }));
- }
+ if (result && !result.error) return { ok: true, error: null };
+ return {
+ ok: false,
+ error: result?.error?.message ?? "Failed to save the serial number"
+ };
+ } catch {
+ return { ok: false, error: "Failed to save the serial number" };
}
},
- [line.id, line.itemId, receipt?.id, validateSerialNumber, expiryDate]
+ [line.id, line.itemId, receipt?.id, expiryDate]
+ );
+
+ const updateSerialNumber = useCallback(
+ async (serialNumber: { index: number; number: string }) => {
+ const { index } = serialNumber;
+ const saved = await saveSerialNumber(index, serialNumber.number.trim());
+ setErrors((prev) => {
+ const next = { ...prev };
+ if (saved.error) next[index] = saved.error;
+ else delete next[index];
+ return next;
+ });
+ },
+ [saveSerialNumber]
);
const propertiesDisclosure = useDisclosure();
@@ -1364,7 +1354,10 @@ function SerialForm({
</div>
)}
- <div className="grid grid-cols-1 @min-[42rem]:grid-cols-3 gap-x-4 gap-y-3">
+ <div
+ data-serial-boxes
+ className="grid grid-cols-1 @min-[42rem]:grid-cols-3 gap-x-4 gap-y-3"
+ >
{serialNumbers.map((serialNumber, index) => (
<div
key={`${line.id}-${index}-serial`}
@@ -1396,22 +1389,18 @@ function SerialForm({
onSerialNumbersChange(newSerialNumbers);
}}
onBlur={() => {
- if (serialNumber.number.trim()) {
- updateSerialNumber(serialNumber);
- }
+ updateSerialNumber(serialNumber);
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
- if (serialNumber.number.trim()) {
- updateSerialNumber(serialNumber);
- }
const nextInput = e.currentTarget
- .closest("div")
- ?.querySelector(`input[placeholder="Serial ${index + 2}"]`);
- if (nextInput) {
- (nextInput as HTMLElement).focus();
- }
+ .closest("[data-serial-boxes]")
+ ?.querySelector<HTMLInputElement>(
+ `input[placeholder="Serial ${index + 2}"]`
+ );
+ if (nextInput) nextInput.focus();
+ else e.currentTarget.blur();
}
}}
className={cn(errors[index] && "border-destructive")}
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptVoidModal.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptVoidModal.tsx
index e90669eafd..55fe273966 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptVoidModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptVoidModal.tsx
@@ -25,21 +25,32 @@ import { useNavigation, useParams } from "react-router";
import type { action as voidAction } from "~/routes/x+/receipt+/$receiptId.void";
import { path } from "~/utils/path";
-const ReceiptVoidModal = ({ onClose }: { onClose: () => void }) => {
+const ReceiptVoidModal = ({
+ isSalesReturn,
+ onClose
+}: {
+ isSalesReturn: boolean;
+ onClose: () => void;
+}) => {
const { receiptId } = useParams();
if (!receiptId) throw new Error("receiptId not found");
const { t } = useLingui();
const navigation = useNavigation();
const fetcher = useAction<typeof voidAction>({
- onSuccess: () => toast.success(t`Receipt voided`),
- onSettled: () => {
- if (submitted.current) {
- onClose();
- }
+ onSuccess: () => {
+ toast.success(t`Receipt voided`);
+ if (submitted.current) onClose();
+ },
+ onError: () => {
+ // No toast: a refused void keeps the modal open and shows the reason in place.
}
});
const submitted = useRef(false);
+ const refusal =
+ fetcher.state === "idle" && fetcher.data && "error" in fetcher.data
+ ? (fetcher.data.error?.message ?? null)
+ : null;
return (
<Modal
@@ -77,14 +88,29 @@ const ReceiptVoidModal = ({ onClose }: { onClose: () => void }) => {
<Trans>Reverse the related journal entries</Trans>
</li>
<li>
- <Trans>Restore tracked entities to available</Trans>
+ <Trans>
+ Remove the received serial and batch numbers from stock
+ </Trans>
</li>
<li>
- <Trans>Update the purchase order quantities</Trans>
+ {isSalesReturn ? (
+ <Trans>Update the return order quantities</Trans>
+ ) : (
+ <Trans>Update the purchase order quantities</Trans>
+ )}
</li>
</ul>
</AlertDescription>
</Alert>
+ {refusal && (
+ <Alert variant="destructive" className="mt-4">
+ <LuTriangleAlert className="h-4 w-4" />
+ <AlertTitle>
+ <Trans>The receipt was not voided</Trans>
+ </AlertTitle>
+ <AlertDescription>{refusal}</AlertDescription>
+ </Alert>
+ )}
</ModalBody>
<ModalFooter>
<HStack>
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReturnEntityForm.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReturnEntityForm.tsx
index 181f3516f9..eda2f948f1 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReturnEntityForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReturnEntityForm.tsx
@@ -53,6 +53,7 @@ export function ReturnEntityForm({
const candidatesFetcher = useFetcher<{
candidates: CandidateEntity[];
assigned: AssignedRow[];
+ error: string | null;
}>();
const assignFetcher = useAction<typeof trackingAction>({
onError: () => {
@@ -98,7 +99,18 @@ export function ReturnEntityForm({
return map;
}, [candidatesFetcher.data?.assigned]);
- if (!line.lineId || (candidates && candidates.length === 0)) {
+ if (candidatesFetcher.data?.error) {
+ return (
+ <span className="text-xs text-destructive">
+ {candidatesFetcher.data.error}
+ </span>
+ );
+ }
+
+ if (
+ !line.lineId ||
+ (candidates && candidates.length === 0 && assignedByEntityId.size === 0)
+ ) {
// Blind return: nothing shipped on record — standard serial/batch entry
return <>{children}</>;
}
diff --git a/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx b/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx
index 751327b5e4..73e05b9a35 100644
--- a/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx
+++ b/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx
@@ -99,6 +99,8 @@ export type InspectionViewProps = {
inspection: InspectionRow;
sourceDocumentReadableId: string | null;
receiverId: string | null;
+ /** The receipt was voided: its stock was never received, so the lot is closed. */
+ receiptVoided: boolean;
itemName: string;
itemTrackingType: string | null;
supplierName: string | null;
@@ -137,6 +139,7 @@ const InspectionView = ({
inspection,
sourceDocumentReadableId,
receiverId,
+ receiptVoided,
itemName,
itemTrackingType,
supplierName,
@@ -363,8 +366,9 @@ const InspectionView = ({
enforceFourEyes && !!receiverId && receiverId === currentUserId;
const lotClosed =
- inspection.dispositionedAt != null &&
- (inspection.status === "Passed" || inspection.status === "Failed");
+ receiptVoided ||
+ (inspection.dispositionedAt != null &&
+ (inspection.status === "Passed" || inspection.status === "Failed"));
// Serial lots build their sample columns by scanning tracked entities. The
// header "Add Sample" button stays primary until the plan's sample size is
@@ -498,7 +502,14 @@ const InspectionView = ({
.join(" · ");
const statusBadge = (
- <Badge variant={statusBadgeVariant}>{inspection.status}</Badge>
+ <HStack spacing={1}>
+ <Badge variant={statusBadgeVariant}>{inspection.status}</Badge>
+ {receiptVoided && (
+ <Badge variant="red">
+ <Trans>Receipt voided</Trans>
+ </Badge>
+ )}
+ </HStack>
);
return (
diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.ts
index a1d660c224..1770723dfb 100644
--- a/apps/erp/app/modules/shared/shared.service.ts
+++ b/apps/erp/app/modules/shared/shared.service.ts
@@ -72,6 +72,7 @@ import type { AccountType } from "@carbon/database/ledger";
import { accountTypeFromClass, isAccountClass } from "@carbon/database/ledger";
import { equals } from "@carbon/database/precision";
import { quoteToOrderPriceTrace } from "@carbon/database/price-trace";
+import { releaseReceiptSerialEntities } from "@carbon/database/receipt-serials";
import type * as rows from "@carbon/database/rows";
import type * as rowsModule from "@carbon/database/rows";
import {
@@ -11565,11 +11566,11 @@ export async function createDocument(
trackedEntities.data?.length
) {
// TODO: update the Receipt Line and Index attributes to point to the new line
- await trx
- .deleteFrom("trackedEntity")
- .where("id", "in", trackedEntities.data?.map((d) => d.id) ?? [])
- .where("companyId", "=", companyId)
- .execute();
+ await releaseReceiptSerialEntities(
+ trx,
+ companyId,
+ trackedEntities.data.map((d) => d.id)
+ );
}
const newReceiptLineRows = await trx
diff --git a/apps/erp/app/routes/x+/inspection+/$id.tsx b/apps/erp/app/routes/x+/inspection+/$id.tsx
index 0d967796f0..827bb49262 100644
--- a/apps/erp/app/routes/x+/inspection+/$id.tsx
+++ b/apps/erp/app/routes/x+/inspection+/$id.tsx
@@ -129,7 +129,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
isReceiptSource
? client
.from("receipt")
- .select("createdBy")
+ .select("createdBy, status")
.eq("id", insp.sourceDocumentId)
.maybeSingle()
: Promise.resolve({ data: null, error: null })
@@ -144,6 +144,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
inspection: insp,
sourceDocumentReadableId: insp.sourceDocumentReadableId ?? null,
receiverId: receipt.data?.createdBy ?? null,
+ receiptVoided: receipt.data?.status === "Voided",
itemName: insp.item?.name ?? "",
itemTrackingType: insp.item?.itemTrackingType ?? null,
supplierName: insp.supplier?.name ?? null,
@@ -181,6 +182,7 @@ export default function InspectionExecutionRoute() {
inspection={loaderData.inspection as InspectionRow}
sourceDocumentReadableId={loaderData.sourceDocumentReadableId}
receiverId={loaderData.receiverId}
+ receiptVoided={loaderData.receiptVoided}
itemName={loaderData.itemName}
itemTrackingType={loaderData.itemTrackingType}
supplierName={loaderData.supplierName}
diff --git a/apps/erp/app/routes/x+/receipt+/lines.return-entities.tsx b/apps/erp/app/routes/x+/receipt+/lines.return-entities.tsx
index c139d06dc4..9681c0ee1e 100644
--- a/apps/erp/app/routes/x+/receipt+/lines.return-entities.tsx
+++ b/apps/erp/app/routes/x+/receipt+/lines.return-entities.tsx
@@ -3,9 +3,12 @@
// 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 type { LoaderFunctionArgs } from "react-router";
import { getShippedTrackedEntitiesForCustomer } from "~/modules/sales/sales.service";
+const logger = getLogger("erp", "receipt", "return-entities");
+
// Candidate serials/batches for a sales-return receipt line — the picker
// source for return-receipt tracking (ReturnEntityForm). "Which serial is it"
// lives entirely on the receipt: candidates are every entity of the line's
@@ -22,7 +25,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
const lineId = url.searchParams.get("lineId");
const receiptLineId = url.searchParams.get("receiptLineId");
if (!lineId) {
- return { candidates: [], assigned: [] };
+ return { candidates: [], assigned: [], error: null };
}
const line = await client
@@ -62,8 +65,28 @@ export async function loader({ request }: LoaderFunctionArgs) {
: Promise.resolve({ data: [] })
]);
+ const error =
+ line.error ??
+ ("error" in order ? order.error : null) ??
+ candidates.error ??
+ ("error" in assigned ? assigned.error : null);
+ if (error) {
+ logger.error("Failed to load return entities", {
+ companyId,
+ lineId,
+ receiptLineId,
+ error
+ });
+ return {
+ candidates: [],
+ assigned: [],
+ error: "The returned units could not be loaded"
+ };
+ }
+
return {
candidates: candidates.data ?? [],
- assigned: assigned.data ?? []
+ assigned: assigned.data ?? [],
+ error: null
};
}
diff --git a/apps/erp/test/database/post-receipt/void-tracked-entities.test.ts b/apps/erp/test/database/post-receipt/void-tracked-entities.test.ts
new file mode 100644
index 0000000000..f98f64ccec
--- /dev/null
+++ b/apps/erp/test/database/post-receipt/void-tracked-entities.test.ts
@@ -0,0 +1,489 @@
+// 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.
+
+// Voiding a purchase receipt un-receives its serials and batches. The void
+// reversed the stock but set every tracked entity back to Available at its
+// received quantity, so a lot that was never received (one On Hold for
+// inspection included) stayed pickable on shipments and jobs.
+
+import {
+ dispositionInspection,
+ upsertInspectionSample
+} from "@carbon/database/quality";
+import {
+ idsWithLiveStockHistory,
+ idsWithStockHistory
+} from "@carbon/database/receipt-serials";
+import { sql } from "kysely";
+import { afterAll, beforeAll, describe, expect } from "vitest";
+import { postReceipt } from "../../../app/modules/inventory/inventory.service";
+import {
+ invokeCreate,
+ invokePosting
+} from "../../../app/modules/shared/shared.service";
+import {
+ alwaysPostFixture,
+ type Fixture,
+ seed,
+ USER,
+ unwrap
+} from "../fixtures/always-post";
+import { handlesOf } from "../fixtures/handles";
+import { databaseTest, hasLocalDatabase } from "../fixtures/local-database";
+
+describe.skipIf(!hasLocalDatabase)("voiding a receipt", () => {
+ let f: Fixture;
+ let batchItemId: string;
+ let serialItemId: string;
+ let inspectedItemId: string;
+ let otherBin: string;
+
+ beforeAll(async () => {
+ f = await alwaysPostFixture();
+ batchItemId = `${f.prefix}-batch`;
+ serialItemId = `${f.prefix}-serial`;
+ inspectedItemId = `${f.prefix}-tank`;
+ otherBin = `${f.prefix}-other-bin`;
+ await seed(f, async (trx) => {
+ await trx
+ .insertInto("item")
+ .values([
+ {
+ id: batchItemId,
+ readableId: `${f.prefix}-OIL`,
+ name: "Oil",
+ type: "Part",
+ itemTrackingType: "Batch",
+ replenishmentSystem: "Buy",
+ companyId: f.companyId,
+ createdBy: USER
+ },
+ {
+ id: serialItemId,
+ readableId: `${f.prefix}-VEH`,
+ name: "Vehicle",
+ type: "Part",
+ itemTrackingType: "Serial",
+ replenishmentSystem: "Buy",
+ companyId: f.companyId,
+ createdBy: USER
+ }
+ ])
+ .execute();
+ await trx
+ .insertInto("item")
+ .values({
+ id: inspectedItemId,
+ readableId: `${f.prefix}-TANK`,
+ name: "Tank",
+ type: "Part",
+ itemTrackingType: "Inventory",
+ replenishmentSystem: "Buy",
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+ await trx
+ .updateTable("itemCost")
+ .set({ costingMethod: "FIFO", unitCost: 10 })
+ .where("itemId", "in", [batchItemId, serialItemId, inspectedItemId])
+ .where("companyId", "=", f.companyId)
+ .execute();
+ // A Receipt-usage inspection plan: posting creates a lot for the tank.
+ await trx
+ .insertInto("sequence")
+ .values({
+ table: "inspection",
+ name: "Inspection",
+ prefix: "INS",
+ companyId: f.companyId
+ })
+ .execute();
+ const document = await trx
+ .insertInto("inspectionDocument")
+ .values({
+ partId: inspectedItemId,
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ await trx
+ .insertInto("itemInspectionDocumentAssignment")
+ .values({
+ itemId: inspectedItemId,
+ usage: "Receipt",
+ inspectionDocumentId: document.id,
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+ await trx
+ .insertInto("storageUnit")
+ .values({
+ id: otherBin,
+ name: "Other bin",
+ locationId: f.locationId,
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+ });
+ });
+
+ afterAll(async () => {
+ await f?.cleanup();
+ });
+
+ /** A draft receipt for `quantity` of `itemId` on a new purchase order. */
+ async function draftReceipt(key: string, itemId: string, quantity: number) {
+ const purchaseOrderId = `${f.prefix}-po-${key}`;
+ await seed(f, async (trx) => {
+ const interaction = await trx
+ .insertInto("supplierInteraction")
+ .values({ supplierId: f.supplierId, companyId: f.companyId })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ await trx
+ .insertInto("purchaseOrder")
+ .values({
+ id: purchaseOrderId,
+ purchaseOrderId: `PO-${key}`,
+ supplierId: f.supplierId,
+ supplierInteractionId: interaction.id,
+ currencyCode: "USD",
+ exchangeRate: 1,
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+ await trx
+ .insertInto("purchaseOrderDelivery")
+ .values({
+ id: purchaseOrderId,
+ locationId: f.locationId,
+ companyId: f.companyId
+ })
+ .execute();
+ await trx
+ .insertInto("purchaseOrderLine")
+ .values({
+ purchaseOrderId,
+ purchaseOrderLineType: "Part",
+ itemId,
+ purchaseQuantity: quantity,
+ supplierUnitPrice: 10,
+ exchangeRate: 1,
+ conversionFactor: 1,
+ inventoryUnitOfMeasureCode: "EA",
+ locationId: f.locationId,
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+ });
+ const receipt = unwrap(
+ await invokeCreate(handlesOf(f.ctx), {
+ type: "receiptFromPurchaseOrder",
+ purchaseOrderId,
+ locationId: f.locationId
+ })
+ );
+ const line = await f.db
+ .selectFrom("receiptLine")
+ .where("receiptId", "=", receipt.id)
+ .where("companyId", "=", f.companyId)
+ .select("id")
+ .executeTakeFirstOrThrow();
+ return { receiptId: receipt.id, receiptLineId: line.id };
+ }
+
+ async function entitiesOf(receiptId: string) {
+ return f.db
+ .selectFrom("trackedEntity")
+ .where(sql<boolean>`attributes ->> 'Receipt' = ${receiptId}`)
+ .where("companyId", "=", f.companyId)
+ .select(["id", "status", "quantity"])
+ .orderBy("readableId")
+ .execute();
+ }
+
+ databaseTest(
+ "a voided batch receipt leaves its batch at zero, not Available",
+ async () => {
+ const { receiptId, receiptLineId } = await draftReceipt(
+ "batch",
+ batchItemId,
+ 5
+ );
+ await sql`SELECT update_receipt_line_batch_tracking(
+ ${receiptLineId}, ${receiptId}, ${"LOT-1"}, ${5}
+ )`.execute(f.db);
+
+ unwrap(await invokePosting(handlesOf(f.ctx), "post-receipt", { type: "post", receiptId }, postReceipt));
+ expect(
+ (await entitiesOf(receiptId)).map(({ status, quantity }) => ({
+ status,
+ quantity: Number(quantity)
+ }))
+ ).toEqual([{ status: "Available", quantity: 5 }]);
+
+ unwrap(await invokePosting(handlesOf(f.ctx), "post-receipt", { type: "void", receiptId }, postReceipt));
+ const [lot] = await entitiesOf(receiptId);
+ expect({ status: lot!.status, quantity: Number(lot!.quantity) }).toEqual({
+ status: "Consumed",
+ quantity: 0
+ });
+
+ // The void activity records what was un-received, not the zero left.
+ const input = await f.db
+ .selectFrom("trackedActivityInput")
+ .innerJoin(
+ "trackedActivity",
+ "trackedActivity.id",
+ "trackedActivityInput.trackedActivityId"
+ )
+ .where("trackedActivityInput.trackedEntityId", "=", lot!.id)
+ .where("trackedActivity.type", "=", "Void Receipt")
+ .select("trackedActivityInput.quantity")
+ .executeTakeFirstOrThrow();
+ expect(Number(input.quantity)).toBe(5);
+ }
+ );
+
+ databaseTest(
+ "a voided serial receipt does not release a unit On Hold for inspection",
+ async () => {
+ const { receiptId, receiptLineId } = await draftReceipt(
+ "serial",
+ serialItemId,
+ 2
+ );
+ for (const [index, serial] of ["SN-1", "SN-2"].entries()) {
+ await sql`SELECT update_receipt_line_serial_tracking(
+ ${receiptLineId}, ${receiptId}, ${serial}, ${index}
+ )`.execute(f.db);
+ }
+
+ unwrap(await invokePosting(handlesOf(f.ctx), "post-receipt", { type: "post", receiptId }, postReceipt));
+ // One unit waits on a receipt inspection, the other was rejected by it.
+ const [held, rejected] = await entitiesOf(receiptId);
+ await seed(f, async (trx) => {
+ await trx
+ .updateTable("trackedEntity")
+ .set({ status: "On Hold" })
+ .where("id", "=", held!.id)
+ .execute();
+ await trx
+ .updateTable("trackedEntity")
+ .set({ status: "Rejected" })
+ .where("id", "=", rejected!.id)
+ .execute();
+ });
+
+ unwrap(await invokePosting(handlesOf(f.ctx), "post-receipt", { type: "void", receiptId }, postReceipt));
+ expect(
+ (await entitiesOf(receiptId)).map(({ status, quantity }) => ({
+ status,
+ quantity: Number(quantity)
+ }))
+ ).toEqual([
+ { status: "Consumed", quantity: 0 },
+ { status: "Rejected", quantity: 0 }
+ ]);
+ }
+ );
+
+ async function onHand(itemId: string) {
+ const rows = await f.db
+ .selectFrom("itemLedger")
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", f.companyId)
+ .groupBy(["storageUnitId", "trackedEntityId"])
+ .select([
+ "storageUnitId",
+ (eb) => eb.fn.sum<number>("quantity").as("quantity")
+ ])
+ .execute();
+ return rows
+ .map((row) => ({
+ bin: row.storageUnitId,
+ quantity: Number(row.quantity)
+ }))
+ .filter((row) => row.quantity !== 0);
+ }
+
+ async function receiptStatus(receiptId: string) {
+ const receipt = await f.db
+ .selectFrom("receipt")
+ .select("status")
+ .where("id", "=", receiptId)
+ .executeTakeFirstOrThrow();
+ return receipt.status;
+ }
+
+ databaseTest(
+ "refuses a void after the received batch moved to another bin",
+ async () => {
+ const { receiptId, receiptLineId } = await draftReceipt(
+ "moved",
+ batchItemId,
+ 4
+ );
+ await sql`SELECT update_receipt_line_batch_tracking(
+ ${receiptLineId}, ${receiptId}, ${"LOT-MOVED"}, ${4}
+ )`.execute(f.db);
+ unwrap(await invokePosting(handlesOf(f.ctx), "post-receipt", { type: "post", receiptId }, postReceipt));
+ const [lot] = await entitiesOf(receiptId);
+ const before = await onHand(batchItemId);
+ const receivedBin = before[0]!.bin;
+
+ // A stock transfer moves the whole batch to another bin.
+ await seed(f, (trx) =>
+ trx
+ .insertInto("itemLedger")
+ .values(
+ [
+ { storageUnitId: receivedBin, quantity: -4 },
+ { storageUnitId: otherBin, quantity: 4 }
+ ].map((move) => ({
+ ...move,
+ itemId: batchItemId,
+ trackedEntityId: lot!.id,
+ locationId: f.locationId,
+ entryType: "Transfer" as const,
+ documentType: "Direct Transfer" as const,
+ companyId: f.companyId,
+ createdBy: USER
+ }))
+ )
+ .execute()
+ );
+ const moved = await onHand(batchItemId);
+
+ const result = await invokePosting(handlesOf(f.ctx), "post-receipt", { type: "void", receiptId }, postReceipt);
+ expect(result.error?.message).toMatch(/moved, picked or shipped/);
+ expect(await receiptStatus(receiptId)).toBe("Posted");
+ expect(await onHand(batchItemId)).toEqual(moved);
+ const [after] = await entitiesOf(receiptId);
+ expect(after!.status).toBe("Available");
+ }
+ );
+
+ databaseTest(
+ "a serial from a voided receipt can be received again as the same unit",
+ async () => {
+ const first = await draftReceipt("again-1", serialItemId, 1);
+ await sql`SELECT update_receipt_line_serial_tracking(
+ ${first.receiptLineId}, ${first.receiptId}, ${"SN-AGAIN"}, ${0}
+ )`.execute(f.db);
+ unwrap(
+ await invokePosting(handlesOf(f.ctx), "post-receipt", { type: "post", receiptId: first.receiptId }, postReceipt)
+ );
+ unwrap(
+ await invokePosting(handlesOf(f.ctx), "post-receipt", { type: "void", receiptId: first.receiptId }, postReceipt)
+ );
+ const [unit] = await entitiesOf(first.receiptId);
+
+ // Its movements are the receipt and its void, so it is free to receive.
+ expect(await idsWithStockHistory(f.db, f.companyId, [unit!.id])).toEqual(
+ new Set([unit!.id])
+ );
+ expect(
+ await idsWithLiveStockHistory(f.db, f.companyId, [unit!.id])
+ ).toEqual(new Set());
+
+ const second = await draftReceipt("again-2", serialItemId, 1);
+ await sql`SELECT update_receipt_line_serial_tracking(
+ p_receipt_line_id => ${second.receiptLineId},
+ p_receipt_id => ${second.receiptId},
+ p_serial_number => ${"SN-AGAIN"},
+ p_index => ${0}::int,
+ p_tracked_entity_id => ${unit!.id}::text
+ )`.execute(f.db);
+ unwrap(
+ await invokePosting(handlesOf(f.ctx), "post-receipt", { type: "post", receiptId: second.receiptId }, postReceipt)
+ );
+
+ const [received] = await entitiesOf(second.receiptId);
+ expect(received!.id).toBe(unit!.id);
+ expect({
+ status: received!.status,
+ quantity: Number(received!.quantity)
+ }).toEqual({ status: "Available", quantity: 1 });
+ expect(
+ await idsWithLiveStockHistory(f.db, f.companyId, [unit!.id])
+ ).toEqual(new Set([unit!.id]));
+ }
+ );
+
+ databaseTest(
+ "the inspection of a voided receipt can no longer be dispositioned",
+ async () => {
+ const { receiptId } = await draftReceipt("inspect", inspectedItemId, 2);
+ unwrap(await invokePosting(handlesOf(f.ctx), "post-receipt", { type: "post", receiptId }, postReceipt));
+ unwrap(await invokePosting(handlesOf(f.ctx), "post-receipt", { type: "void", receiptId }, postReceipt));
+ const lot = await f.db
+ .selectFrom("inspection")
+ .select("id")
+ .where("sourceDocumentId", "=", receiptId)
+ .executeTakeFirstOrThrow();
+
+ const sample = await upsertInspectionSample(f.db, {
+ inspectionId: lot.id,
+ status: "Failed",
+ companyId: f.companyId,
+ inspectedBy: USER
+ });
+ expect(sample.error?.message).toBe(
+ "The receipt of this inspection was voided"
+ );
+ const reject = await dispositionInspection(f.db, {
+ id: lot.id,
+ decision: "Reject",
+ companyId: f.companyId,
+ dispositionedBy: USER
+ });
+ expect(reject.error?.message).toBe(
+ "The receipt of this inspection was voided"
+ );
+ }
+ );
+
+ databaseTest(
+ "refuses a void after an inspection rejected and wrote off untracked stock",
+ async () => {
+ const { receiptId } = await draftReceipt("rejected", inspectedItemId, 2);
+ unwrap(await invokePosting(handlesOf(f.ctx), "post-receipt", { type: "post", receiptId }, postReceipt));
+ const lot = await f.db
+ .selectFrom("inspection")
+ .select(["id", "inspectionId"])
+ .where("sourceDocumentId", "=", receiptId)
+ .executeTakeFirstOrThrow();
+ expect(
+ (
+ await upsertInspectionSample(f.db, {
+ inspectionId: lot.id,
+ status: "Failed",
+ companyId: f.companyId,
+ inspectedBy: USER
+ })
+ ).error
+ ).toBeNull();
+ const reject = await dispositionInspection(f.db, {
+ id: lot.id,
+ decision: "Reject",
+ companyId: f.companyId,
+ dispositionedBy: USER
+ });
+ expect(reject.data?.writeOff?.quantity).toBe(-2);
+
+ const result = await invokePosting(handlesOf(f.ctx), "post-receipt", { type: "void", receiptId }, postReceipt);
+ expect(result.error?.message).toBe(
+ `Cannot void: inspection ${lot.inspectionId} rejected this stock and wrote it off. Correct the remainder with an inventory adjustment instead.`
+ );
+ expect(await receiptStatus(receiptId)).toBe("Posted");
+ }
+ );
+});
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index 11edfc9817..6a7f74fc54 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -98,6 +98,7 @@ pnpm --filter @carbon/database authz migration <name> # ship unshipped rules/h
| `./legacy-documents` | Server-only. The one detection of legacy documents (`.ai/specs/implemented/2026-10-08-accounting-cutover.md` section 5a): posted, dated on or after the cutover, with no journal. Each function (`legacySalesInvoices`, `legacyPayments`, `legacyShipments`, `legacyAdjustmentCostRows`, `legacyJobMovements`, `legacyDepreciationRunLines`, …) returns a Kysely query, not rows: `activateAccounting` (`accounting.service.ts`, ported from the `activate-accounting` server function) executes it, and `getLegacyDocumentCounts` (`./accounting-cutover-reads`) counts the same rows for the wizard. Also `LEGACY_DOCUMENT_FAMILIES` (the families in the order the enable writes them), `LegacyDocumentCounts`, `assetsLeavingWithoutJournal` and `REBUILT_DISPOSAL_METHOD` |
| `./deposit-scope` | `loadSalesInvoiceDocumentIds` (the rental agreements / sales orders each sales invoice bills, one query) and `loadDepositScope` (a deposit payment's document + readable id) — the reads behind "a customer deposit funds only its own document", shared by `replaceInvoiceSettlements` and `post-payment` |
| `./sequence` | `getNextSequences` (`count` numbers in one statement; `getNextSequence` is its count-of-one) / `getNextRevisionSequence` / `getNextSerialNumbers` — the one allocator for document and serial numbers (date tokens in the company timezone) |
+| `./receipt-serials` | `releaseReceiptSerialEntities(db, companyId, ids)` — the one way a receipt serial is taken off a receipt, inside the caller's Kysely transaction: an entity with no `itemLedger` history is deleted, one with history only loses its `Receipt` / `Receipt Line` / `Receipt Line Index` attributes. Shared by the ERP's receipt serial routes and the receipt line split (`receiptLineSplit` in `shared.service.ts`). `planReceiptSerialRelease` is the pure split; `idsWithStockHistory` is the one "has stock movements" test. `idsWithLiveStockHistory` is the same test without the rows of voided receipts (a void writes its reversal under the receipt's `documentId`), and `voidedReceiptIds` filters receipt ids to the voided ones — together they let a serial from a voided receipt be received again as the same entity |
| `./stock-transfer` | `expandSerialTrackedLines`, `isBelowReplenishmentLevel`, `levelReplenishmentQuantity` (the fewest whole kanban quantities that reach a level), `kanbanReplenishmentNote` — the stock-transfer line and kanban-note rules shared by the ERP's `insertStockTransfer` and `replenishKanban` (`inventory.service.ts`, ported from the `kanban-replenish` server function) |
| `./seed-data` | The company seed data (accounts, sequences, groups + `getGroupId`, …) used by `seedCompany` (`settings.service.ts`, ported from the `seed-company` server function) and the dataset tooling |
| *(no subpath)* | `src/sql-effects.ts` — `sqlFunctionEffects(sources)` / `loadSqlFunctionEffects()`: whether a SQL function writes, reads or cannot be told, read off its current definition with `libpg-query` (every migration, then the managed function files). The API generator imports it by path to refuse a `read` tool that calls a writing function. An extension function it meets must be added to `EXTERNAL_READS` or `EXTERNAL_WRITES`; reviewed dynamic SQL to `REVIEWED_DYNAMIC_READS` |
diff --git a/packages/database/package.json b/packages/database/package.json
index 57f890f6bb..ec149417de 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -50,6 +50,7 @@
"./sampling": "./src/sampling.ts",
"./sequence": "./src/sequence.ts",
"./stock-transfer": "./src/stock-transfer.ts",
+ "./receipt-serials": "./src/receipt-serials.ts",
"./storage-objects": "./src/storage-objects.ts",
"./seed-data": "./src/seed-data.ts",
"./seed-workflows": "./src/datasets/tiers/workflow-definitions.ts",
diff --git a/packages/database/src/quality.ts b/packages/database/src/quality.ts
index 83ea41e1a5..d87a3aff65 100644
--- a/packages/database/src/quality.ts
+++ b/packages/database/src/quality.ts
@@ -124,6 +124,29 @@ function isInspectionClosed(status: string): boolean {
return (INSPECTION_CLOSED_STATUSES as readonly string[]).includes(status);
}
+// A receipt lot is closed once its receipt is voided: the stock it inspects was
+// never received. Accepting it made the voided serials and batches Available
+// again, and rejecting an untracked lot wrote the reversed stock off a second
+// time. FOR SHARE waits for a void that is running, which locks the receipt.
+async function assertReceiptNotVoided(
+ trx: Transaction<KyselyDatabase>,
+ companyId: string,
+ inspection: { sourceDocument: string; sourceDocumentId: string | null }
+): Promise<void> {
+ if (inspection.sourceDocument !== "Receipt" || !inspection.sourceDocumentId)
+ return;
+ const receipt = await trx
+ .selectFrom("receipt")
+ .select("status")
+ .where("id", "=", inspection.sourceDocumentId)
+ .where("companyId", "=", companyId)
+ .forShare()
+ .executeTakeFirst();
+ if (receipt?.status === "Voided") {
+ throw new Error("The receipt of this inspection was voided");
+ }
+}
+
// A sample whose verdict already drove a production posting (MES verdict-driven
// completion links productionQuantity.inspectionSampleId) is locked — changing
// it would desync the posted quantity. Deleting the productionQuantity row in
@@ -239,6 +262,7 @@ export async function upsertInspectionSample(
if (isInspectionClosed(inspection.status)) {
throw new Error("Inspection is closed");
}
+ await assertReceiptNotVoided(trx, sample.companyId, inspection);
// Serial parts carry a tracked entity that may only be sampled once, so we
// upsert by it. Anonymous (batch / inventory / non-inventory) columns have
@@ -416,6 +440,7 @@ export async function dispositionInspection(
if (args.requireOpen && isInspectionClosed(inspection.status)) {
throw new Error("Inspection is already dispositioned");
}
+ await assertReceiptNotVoided(trx, args.companyId, inspection);
const isReceiptSource = inspection.sourceDocument === "Receipt";
const item = await trx
@@ -686,6 +711,7 @@ export async function upsertInspectionMeasurement(
if (isInspectionClosed(inspection.status)) {
throw new Error("Inspection is closed");
}
+ await assertReceiptNotVoided(trx, args.companyId, inspection);
const feature = await trx
.selectFrom("inspectionFeature")
@@ -1013,7 +1039,7 @@ export async function changeInspectionDocument(
const result = await db.transaction().execute(async (trx) => {
const inspection = await trx
.selectFrom("inspection")
- .select(["id", "status"])
+ .select(["id", "status", "sourceDocument", "sourceDocumentId"])
.where("id", "=", args.inspectionId)
.where("companyId", "=", args.companyId)
.executeTakeFirst();
@@ -1021,6 +1047,7 @@ export async function changeInspectionDocument(
if (isInspectionClosed(inspection.status)) {
throw new Error("Inspection is closed");
}
+ await assertReceiptNotVoided(trx, args.companyId, inspection);
const measurement = await trx
.selectFrom("inspectionMeasurement")
@@ -1083,7 +1110,7 @@ export async function recordInspectionGauge(
const result = await db.transaction().execute(async (trx) => {
const inspection = await trx
.selectFrom("inspection")
- .select(["id", "status"])
+ .select(["id", "status", "sourceDocument", "sourceDocumentId"])
.where("id", "=", args.inspectionId)
.where("companyId", "=", args.companyId)
.executeTakeFirst();
@@ -1091,6 +1118,7 @@ export async function recordInspectionGauge(
if (isInspectionClosed(inspection.status)) {
throw new Error("Inspection is closed");
}
+ await assertReceiptNotVoided(trx, args.companyId, inspection);
const plan = await trx
.selectFrom("inspectionSamplingPlan")
diff --git a/packages/database/src/receipt-serials.test.ts b/packages/database/src/receipt-serials.test.ts
new file mode 100644
index 0000000000..7c8b11dc13
--- /dev/null
+++ b/packages/database/src/receipt-serials.test.ts
@@ -0,0 +1,16 @@
+// 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 { planReceiptSerialRelease } from "./receipt-serials.ts";
+
+describe("planReceiptSerialRelease", () => {
+ it("deletes entities without history and only unlinks the rest", () => {
+ const placeholder = { id: "new" };
+ const shipped = { id: "unit" };
+ expect(
+ planReceiptSerialRelease([placeholder, shipped], new Set(["unit"]))
+ ).toEqual({ deleteIds: ["new"], unlink: [shipped] });
+ });
+});
diff --git a/packages/database/src/receipt-serials.ts b/packages/database/src/receipt-serials.ts
new file mode 100644
index 0000000000..dbb1f1db8b
--- /dev/null
+++ b/packages/database/src/receipt-serials.ts
@@ -0,0 +1,126 @@
+// 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 Kysely, sql } from "kysely";
+import type { KyselyDatabase } from "./client.ts";
+
+export function planReceiptSerialRelease<T extends { id: string }>(
+ entities: T[],
+ idsWithHistory: ReadonlySet<string>
+): { deleteIds: string[]; unlink: T[] } {
+ return {
+ deleteIds: entities
+ .filter((entity) => !idsWithHistory.has(entity.id))
+ .map((entity) => entity.id),
+ unlink: entities.filter((entity) => idsWithHistory.has(entity.id))
+ };
+}
+
+/** The tracked entities among `entityIds` that have stock movements. */
+export async function idsWithStockHistory(
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ entityIds: string[]
+): Promise<Set<string>> {
+ if (entityIds.length === 0) return new Set();
+ const rows = await db
+ .selectFrom("itemLedger")
+ .select("trackedEntityId")
+ .distinct()
+ .where("trackedEntityId", "in", entityIds)
+ .where("companyId", "=", companyId)
+ .execute();
+ return new Set(rows.flatMap((row) => row.trackedEntityId ?? []));
+}
+
+/**
+ * The tracked entities among `entityIds` with stock movements outside voided
+ * receipts. A serial whose only movements are a receipt and that receipt's void
+ * was never received, so a new receipt can take it again; a void writes its
+ * reversal under the receipt's own `documentId`.
+ */
+export async function idsWithLiveStockHistory(
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ entityIds: string[]
+): Promise<Set<string>> {
+ if (entityIds.length === 0) return new Set();
+ const rows = await db
+ .selectFrom("itemLedger")
+ .select("itemLedger.trackedEntityId")
+ .distinct()
+ .where("itemLedger.trackedEntityId", "in", entityIds)
+ .where("itemLedger.companyId", "=", companyId)
+ .where(({ not, exists, selectFrom }) =>
+ not(
+ exists(
+ selectFrom("receipt")
+ .select("receipt.id")
+ .whereRef("receipt.id", "=", "itemLedger.documentId")
+ .whereRef("receipt.companyId", "=", "itemLedger.companyId")
+ .where("receipt.status", "=", "Voided")
+ )
+ )
+ )
+ .execute();
+ return new Set(rows.flatMap((row) => row.trackedEntityId ?? []));
+}
+
+/** The receipts among `receiptIds` that are voided. */
+export async function voidedReceiptIds(
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ receiptIds: string[]
+): Promise<Set<string>> {
+ if (receiptIds.length === 0) return new Set();
+ const rows = await db
+ .selectFrom("receipt")
+ .select("id")
+ .where("id", "in", receiptIds)
+ .where("companyId", "=", companyId)
+ .where("status", "=", "Voided")
+ .execute();
+ return new Set(rows.map((row) => row.id));
+}
+
+/**
+ * Takes serial tracked entities off a receipt: one with no stock history is
+ * deleted, one with history only loses its receipt link. Run it inside a
+ * transaction.
+ */
+export async function releaseReceiptSerialEntities(
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ entityIds: string[]
+): Promise<void> {
+ if (entityIds.length === 0) return;
+
+ const { deleteIds, unlink } = planReceiptSerialRelease(
+ entityIds.map((id) => ({ id })),
+ await idsWithStockHistory(db, companyId, entityIds)
+ );
+
+ if (deleteIds.length > 0) {
+ await db
+ .deleteFrom("trackedEntity")
+ .where("id", "in", deleteIds)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+
+ if (unlink.length > 0) {
+ await db
+ .updateTable("trackedEntity")
+ .set({
+ attributes: sql`attributes - 'Receipt' - 'Receipt Line' - 'Receipt Line Index'`
+ })
+ .where(
+ "id",
+ "in",
+ unlink.map((entity) => entity.id)
+ )
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+}
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index aeaddd6609..3bee56942e 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -18717,6 +18717,9 @@ msgstr "Sortierung nach Spalte entfernen"
msgid "Remove station"
msgstr "Station entfernen"
+msgid "Remove the received serial and batch numbers from stock"
+msgstr "Entfernen Sie die empfangenen Seriennummern und Chargennummern aus dem Bestand"
+
msgid "Remove this item"
msgstr "Diesen Artikel entfernen"
@@ -19147,9 +19150,6 @@ msgstr "Stellen Sie dieses Unternehmen aus einer Sicherung wieder her"
msgid "Restore this entity to available stock at the bin and cost it was scrapped from."
msgstr "Stellen Sie diese Entität als verfügbaren Bestand zum Lagerplatz und zu den Kosten wieder her, von denen sie verschrottet wurde."
-msgid "Restore tracked entities to available"
-msgstr "Nachverfolgter Entitäten als verfügbar wiederherstellen"
-
msgid "Restore…"
msgstr "Wiederherstellen…"
@@ -23375,6 +23375,9 @@ msgstr "Die Gründe, die Sie aufzeichnen, wenn Teile verschrottet werden"
msgid "The reasons you record when you decline an RFQ"
msgstr "Die Gründe, die Sie aufzeichnen, wenn Sie eine Anfrage ablehnen"
+msgid "The receipt was not voided"
+msgstr "Der Wareneingang wurde nicht storniert"
+
msgid "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
msgstr "Der Datensatz, auf den eine Workflow-Benachrichtigung verweist, benannt als eine ID plus seine Art; lassen Sie sie leer und die Benachrichtigung verweist auf den Workflow-Ausführungsdatensatz selbst."
@@ -25127,6 +25130,9 @@ msgstr "Aktualisieren Sie die Kanban-Informationen für die scanbasierte Auffül
msgid "Update the purchase order quantities"
msgstr "Bestellmengen aktualisieren"
+msgid "Update the return order quantities"
+msgstr "Aktualisieren Sie die Mengen der Rückgabebestellung"
+
msgid "Updated"
msgstr "Aktualisiert"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 9e97bb1ee4..a068ee1ace 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -18717,6 +18717,9 @@ msgstr "Remove sort by column"
msgid "Remove station"
msgstr "Remove station"
+msgid "Remove the received serial and batch numbers from stock"
+msgstr "Remove the received serial and batch numbers from stock"
+
msgid "Remove this item"
msgstr "Remove this item"
@@ -19147,9 +19150,6 @@ msgstr "Restore this company from a backup"
msgid "Restore this entity to available stock at the bin and cost it was scrapped from."
msgstr "Restore this entity to available stock at the bin and cost it was scrapped from."
-msgid "Restore tracked entities to available"
-msgstr "Restore tracked entities to available"
-
msgid "Restore…"
msgstr "Restore…"
@@ -23375,6 +23375,9 @@ msgstr "The reasons you record when parts get scrapped"
msgid "The reasons you record when you decline an RFQ"
msgstr "The reasons you record when you decline an RFQ"
+msgid "The receipt was not voided"
+msgstr "The receipt was not voided"
+
msgid "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
msgstr "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
@@ -25127,6 +25130,9 @@ msgstr "Update the kanban information for scan-based replenishment."
msgid "Update the purchase order quantities"
msgstr "Update the purchase order quantities"
+msgid "Update the return order quantities"
+msgstr "Update the return order quantities"
+
msgid "Updated"
msgstr "Updated"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 4a4384e0a3..864e2f7c6b 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -18717,6 +18717,9 @@ msgstr "Quitar ordenamiento por columna"
msgid "Remove station"
msgstr "Eliminar estación"
+msgid "Remove the received serial and batch numbers from stock"
+msgstr "Quitar los números de serie y de lote de producción recibidos de las existencias"
+
msgid "Remove this item"
msgstr "Quitar este artículo"
@@ -19147,9 +19150,6 @@ msgstr "Restaure esta empresa desde una copia de seguridad"
msgid "Restore this entity to available stock at the bin and cost it was scrapped from."
msgstr "Restaurar esta entidad al stock disponible en el contenedor al costo desde el cual fue descartado."
-msgid "Restore tracked entities to available"
-msgstr "Restaurar entidades rastreadas a disponibles"
-
msgid "Restore…"
msgstr "Restaurar…"
@@ -23375,6 +23375,9 @@ msgstr "Las razones que registra cuando se descartan piezas"
msgid "The reasons you record when you decline an RFQ"
msgstr "Las razones que registra cuando rechaza una solicitud de cotización"
+msgid "The receipt was not voided"
+msgstr "La recepción no fue anulada"
+
msgid "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
msgstr "El registro al que apunta una notificación de flujo de trabajo, nombrado como un id más su tipo; déjalo vacío y la notificación se vincula a la ejecución del flujo de trabajo en sí."
@@ -25127,6 +25130,9 @@ msgstr "Actualizar la información del kanban para reabastecimiento basado en es
msgid "Update the purchase order quantities"
msgstr "Actualizar las cantidades de la orden de compra"
+msgid "Update the return order quantities"
+msgstr "Actualizar las cantidades de la orden de devolución"
+
msgid "Updated"
msgstr "Actualizado"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index d7227a3646..f4fdb888cd 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -18717,6 +18717,9 @@ msgstr "Retirer le tri par colonne"
msgid "Remove station"
msgstr "Supprimer la station"
+msgid "Remove the received serial and batch numbers from stock"
+msgstr "Retirer les numéros de série et de lot reçus du stock"
+
msgid "Remove this item"
msgstr "Retirer cet article"
@@ -19147,9 +19150,6 @@ msgstr "Restaurer cette société à partir d'une sauvegarde"
msgid "Restore this entity to available stock at the bin and cost it was scrapped from."
msgstr "Restaurer cette entité au stock disponible au casier et au coût à partir duquel elle a été mise au rebut."
-msgid "Restore tracked entities to available"
-msgstr "Restaurer les entités suivies en disponibles"
-
msgid "Restore…"
msgstr "Restaurer…"
@@ -23375,6 +23375,9 @@ msgstr "Les raisons que vous enregistrez lorsque des pièces sont mises au rebut
msgid "The reasons you record when you decline an RFQ"
msgstr "Les raisons que vous enregistrez lorsque vous refusez une demande de devis"
+msgid "The receipt was not voided"
+msgstr "La réception n'a pas été invalidée"
+
msgid "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
msgstr "L'enregistrement vers lequel une notification de flux de travail pointe, nommé comme un id plus son type ; laissez-le vide et la notification lien vers l'exécution du flux de travail elle-même."
@@ -25127,6 +25130,9 @@ msgstr "Mettez à jour les informations du kanban pour le réapprovisionnement b
msgid "Update the purchase order quantities"
msgstr "Mettre à jour les quantités du bon de commande"
+msgid "Update the return order quantities"
+msgstr "Mettre à jour les quantités du bon de retour"
+
msgid "Updated"
msgstr "Mis à jour"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index f5eba58477..40636b33dc 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -18717,6 +18717,9 @@ msgstr "कॉलम के अनुसार क्रमबद्धता
msgid "Remove station"
msgstr "स्टेशन हटाएं"
+msgid "Remove the received serial and batch numbers from stock"
+msgstr "प्राप्त सीरियल और बैच नंबर को स्टॉक से निकालें"
+
msgid "Remove this item"
msgstr "इस आइटम को निकालें"
@@ -19147,9 +19150,6 @@ msgstr "बैकअप से इस कंपनी को पुनः स्
msgid "Restore this entity to available stock at the bin and cost it was scrapped from."
msgstr "इस इकाई को उसी बिन और लागत पर उपलब्ध स्टॉक में पुनः स्थापित करें जहां से इसे स्क्रैप किया गया था।"
-msgid "Restore tracked entities to available"
-msgstr "ट्रैक किए गए इकाइयों को उपलब्ध में पुनः स्थापित करें"
-
msgid "Restore…"
msgstr "पुनः स्थापित करें…"
@@ -23375,6 +23375,9 @@ msgstr "वह कारण जो आप रिकॉर्ड करते ह
msgid "The reasons you record when you decline an RFQ"
msgstr "वह कारण जो आप RFQ को अस्वीकार करते समय दर्ज करते हैं"
+msgid "The receipt was not voided"
+msgstr "प्राप्ति अमान्य नहीं की गई"
+
msgid "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
msgstr "रिकॉर्ड जिस पर एक वर्कफ़्लो सूचना इंगित करती है, एक आईडी प्लस इसकी तरह के रूप में नामित; इसे खाली छोड़ दें और सूचना वर्कफ़्लो रन को स्वयं जोड़ती है।"
@@ -25127,6 +25130,9 @@ msgstr "स्कैन-आधारित पुनः भरण के लि
msgid "Update the purchase order quantities"
msgstr "क्रय आदेश मात्रा अपडेट करें"
+msgid "Update the return order quantities"
+msgstr "रिटर्न ऑर्डर की मात्रा अपडेट करें"
+
msgid "Updated"
msgstr "अपडेट किया गया"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 77e806e34e..84e9feaf74 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -18717,6 +18717,9 @@ msgstr "Rimuovi ordinamento per colonna"
msgid "Remove station"
msgstr "Rimuovi stazione"
+msgid "Remove the received serial and batch numbers from stock"
+msgstr "Rimuovi i numeri di serie e di lotto di produzione ricevuti dalla giacenza"
+
msgid "Remove this item"
msgstr "Rimuovi questo articolo"
@@ -19147,9 +19150,6 @@ msgstr "Ripristina questa azienda da un backup"
msgid "Restore this entity to available stock at the bin and cost it was scrapped from."
msgstr "Ripristina questa entità alle giacenze disponibili nel contenitore e al costo da cui è stata scartata."
-msgid "Restore tracked entities to available"
-msgstr "Ripristina le entità tracciate come disponibili"
-
msgid "Restore…"
msgstr "Ripristina…"
@@ -23375,6 +23375,9 @@ msgstr "I motivi che registri quando i componenti vengono scartati"
msgid "The reasons you record when you decline an RFQ"
msgstr "I motivi che registri quando rifiuti una richiesta di offerta"
+msgid "The receipt was not voided"
+msgstr "L'entrata merci non è stata stornata"
+
msgid "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
msgstr "Il record a cui una notifica del flusso di lavoro punta, denominato come un ID più il suo tipo; lasciarlo vuoto e la notifica si collega all'esecuzione del flusso di lavoro stesso."
@@ -25127,6 +25130,9 @@ msgstr "Aggiorna le informazioni del kanban per il rifornimento basato su scansi
msgid "Update the purchase order quantities"
msgstr "Aggiorna le quantità dell'ordine di acquisto"
+msgid "Update the return order quantities"
+msgstr "Aggiorna le quantità dell'ordine di reso"
+
msgid "Updated"
msgstr "Aggiornato"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index c0b64b99dd..d0929d4139 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -18717,6 +18717,9 @@ msgstr "列でのソートを除去"
msgid "Remove station"
msgstr "ステーションを削除"
+msgid "Remove the received serial and batch numbers from stock"
+msgstr "受け入れたシリアル番号とバッチ番号を在庫から除去する"
+
msgid "Remove this item"
msgstr "このアイテムを除去"
@@ -19147,9 +19150,6 @@ msgstr "バックアップからこの会社を復元する"
msgid "Restore this entity to available stock at the bin and cost it was scrapped from."
msgstr "このエンティティを、スクラップされた元のビンと原価で利用可能な在庫に復元します。"
-msgid "Restore tracked entities to available"
-msgstr "追跡対象エンティティを利用可能に復元"
-
msgid "Restore…"
msgstr "復元…"
@@ -23375,6 +23375,9 @@ msgstr "部品がスクラップされたときに記録する理由"
msgid "The reasons you record when you decline an RFQ"
msgstr "RFQを辞退した理由を記録する"
+msgid "The receipt was not voided"
+msgstr "入荷が取消されませんでした"
+
msgid "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
msgstr "ワークフロー通知が指す レコード。ID とそのタイプで名前が付けられます。空のままにすると、通知はワークフロー実行そのものにリンクします。"
@@ -25127,6 +25130,9 @@ msgstr "スキャンベースの補充用かんばん情報を更新します。
msgid "Update the purchase order quantities"
msgstr "発注書の数量を更新"
+msgid "Update the return order quantities"
+msgstr "返品注文の数量を更新する"
+
msgid "Updated"
msgstr "更新済み"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index d14369daac..aaf2e27131 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -18717,6 +18717,9 @@ msgstr "열 정렬 제거"
msgid "Remove station"
msgstr "스테이션 제거"
+msgid "Remove the received serial and batch numbers from stock"
+msgstr "수령한 일련번호 및 배치 번호를 재고에서 제거"
+
msgid "Remove this item"
msgstr "이 항목 제거"
@@ -19147,9 +19150,6 @@ msgstr "백업에서 이 회사 복원"
msgid "Restore this entity to available stock at the bin and cost it was scrapped from."
msgstr "이 엔티티를 스크랩 전의 빈과 원가로 가용 재고에 복원합니다."
-msgid "Restore tracked entities to available"
-msgstr "추적된 엔티티를 가용으로 복원"
-
msgid "Restore…"
msgstr "복원…"
@@ -23375,6 +23375,9 @@ msgstr "부품이 스크랩될 때 기록하는 사유"
msgid "The reasons you record when you decline an RFQ"
msgstr "RFQ를 거절할 때 기록하는 사유"
+msgid "The receipt was not voided"
+msgstr "입고가 무효 처리되지 않았습니다"
+
msgid "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
msgstr "워크플로우 알림이 가리키는 기록이며, id와 종류로 이름이 지어집니다. 비워두면 알림이 워크플로우 실행 자체에 연결됩니다."
@@ -25127,6 +25130,9 @@ msgstr "스캔 기반 보충을 위한 칸반 정보를 업데이트합니다."
msgid "Update the purchase order quantities"
msgstr "발주서 수량 업데이트"
+msgid "Update the return order quantities"
+msgstr "반품 주문 수량 업데이트"
+
msgid "Updated"
msgstr "업데이트됨"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index e32806f7ef..e66f7e5fb0 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -18717,6 +18717,9 @@ msgstr "Usuń z listy sortowanie po kolumnie"
msgid "Remove station"
msgstr "Usuń stanowisko"
+msgid "Remove the received serial and batch numbers from stock"
+msgstr "Usuń z listy otrzymane numery seryjne i partie produktów ze zapasu"
+
msgid "Remove this item"
msgstr "Usuń ten artykuł"
@@ -19147,9 +19150,6 @@ msgstr "Przywróć tę firmę z kopii zapasowej"
msgid "Restore this entity to available stock at the bin and cost it was scrapped from."
msgstr "Przywróć tę jednostkę do dostępnych zapasów w pojemniku i po koszcie, z których została złomowana."
-msgid "Restore tracked entities to available"
-msgstr "Przywróć śledzone jednostki do dostępnych"
-
msgid "Restore…"
msgstr "Przywróć…"
@@ -23375,6 +23375,9 @@ msgstr "Powody, które rejestrujesz, gdy części są złomowane"
msgid "The reasons you record when you decline an RFQ"
msgstr "Powody, które rejestrujesz, gdy odrzucisz zapytanie ofertowe"
+msgid "The receipt was not voided"
+msgstr "Przyjęcie nie zostało unieważnione"
+
msgid "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
msgstr "Rekord wskazywany przez powiadomienie przepływu pracy, nazwany jako identyfikator plus jego rodzaj; pozostaw puste, a powiadomienie będzie odsyłać do samego uruchomienia przepływu pracy."
@@ -25127,6 +25130,9 @@ msgstr "Zaktualizuj informacje kanban dla uzupełniania opartego na skanowaniu."
msgid "Update the purchase order quantities"
msgstr "Zaktualizuj ilości zamówienia zakupu"
+msgid "Update the return order quantities"
+msgstr "Aktualizuj ilości zamówienia zwrotnego"
+
msgid "Updated"
msgstr "Zaktualizowano"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 935faf76ad..cf8b6c073d 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -18717,6 +18717,9 @@ msgstr "Remover ordenação por coluna"
msgid "Remove station"
msgstr "Remover estação"
+msgid "Remove the received serial and batch numbers from stock"
+msgstr "Remover os números de série e lote recebidos do estoque"
+
msgid "Remove this item"
msgstr "Remover este item"
@@ -19147,9 +19150,6 @@ msgstr "Restaure esta empresa a partir de um backup"
msgid "Restore this entity to available stock at the bin and cost it was scrapped from."
msgstr "Restaure esta entidade ao estoque disponível no compartimento e custo de onde foi sucateada."
-msgid "Restore tracked entities to available"
-msgstr "Restaurar entidades rastreadas para disponível"
-
msgid "Restore…"
msgstr "Restaurar…"
@@ -23375,6 +23375,9 @@ msgstr "Os motivos que você registra quando peças são descartadas"
msgid "The reasons you record when you decline an RFQ"
msgstr "Os motivos que você registra quando recusa uma RFQ"
+msgid "The receipt was not voided"
+msgstr "O recebimento não foi anulado"
+
msgid "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
msgstr "O registro para o qual uma notificação de fluxo de trabalho aponta, nomeado como um id mais seu tipo; deixe-o vazio e a notificação será vinculada à execução do fluxo de trabalho em si."
@@ -25127,6 +25130,9 @@ msgstr "Atualize as informações do kanban para reabastecimento baseado em varr
msgid "Update the purchase order quantities"
msgstr "Atualizar as quantidades do pedido de compra"
+msgid "Update the return order quantities"
+msgstr "Atualizar as quantidades da ordem de devolução"
+
msgid "Updated"
msgstr "Atualizado"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 9a41b231f2..6ca35dd282 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -18717,6 +18717,9 @@ msgstr "Убрать сортировку по столбцу"
msgid "Remove station"
msgstr "Удалить рабочее место"
+msgid "Remove the received serial and batch numbers from stock"
+msgstr "Убрать полученные серийные номера и номера серий из запаса"
+
msgid "Remove this item"
msgstr "Убрать этот элемент"
@@ -19147,9 +19150,6 @@ msgstr "Восстановить эту организацию из резерв
msgid "Restore this entity to available stock at the bin and cost it was scrapped from."
msgstr "Восстановить эту сущность в доступный запас по ячейке и себестоимости, откуда она была выбракована."
-msgid "Restore tracked entities to available"
-msgstr "Восстановить отслеживаемые объекты в доступные"
-
msgid "Restore…"
msgstr "Восстановить…"
@@ -23375,6 +23375,9 @@ msgstr "Причины, которые вы записываете, когда
msgid "The reasons you record when you decline an RFQ"
msgstr "Причины, которые вы записываете, когда отклоняете РФП"
+msgid "The receipt was not voided"
+msgstr "Поступление не было аннулировано"
+
msgid "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
msgstr "Запись, на которую указывает уведомление рабочего процесса, названная как id и её тип; оставьте пустым, и уведомление будет указывать на сам прогон рабочего процесса."
@@ -25127,6 +25130,9 @@ msgstr "Обновите информацию канбана для пополн
msgid "Update the purchase order quantities"
msgstr "Обновить количества Заказа поставщику"
+msgid "Update the return order quantities"
+msgstr "Обновить количества возвратного заказа"
+
msgid "Updated"
msgstr "Обновлено"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 8461494533..44b39126b4 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -18717,6 +18717,9 @@ msgstr "Sıralamayı kaldır"
msgid "Remove station"
msgstr "İstasyonu kaldır"
+msgid "Remove the received serial and batch numbers from stock"
+msgstr "Alınan seri numaraları ve parti numaralarını stoktan kaldır"
+
msgid "Remove this item"
msgstr "Bu stok kartını kaldır"
@@ -19147,9 +19150,6 @@ msgstr "Bu şirketi bir yedekten geri yükle"
msgid "Restore this entity to available stock at the bin and cost it was scrapped from."
msgstr "Bu varlığı, hurdaya çıkarıldığı gözde ve maliyette kullanılabilir stoka geri yükle."
-msgid "Restore tracked entities to available"
-msgstr "Takip edilen varlıkları kullanılabilir hale getir"
-
msgid "Restore…"
msgstr "Geri yükle…"
@@ -23375,6 +23375,9 @@ msgstr "Parçalar hurdaya çıkarıldığında kaydettiğiniz nedenler"
msgid "The reasons you record when you decline an RFQ"
msgstr "Bir RFQ'yu reddettiğinizde kaydettiğiniz nedenler"
+msgid "The receipt was not voided"
+msgstr "Mal kabul hükümsüz kılınmadı"
+
msgid "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
msgstr "İş akışı bildiriminin işaret ettiği kayıt, bir kimlik ve türü olarak adlandırılır; boş bırakırsanız bildirim iş akışı çalıştırmasının kendisine bağlanır."
@@ -25127,6 +25130,9 @@ msgstr "Tarama tabanlı ikmal için kanban bilgilerini güncelleyin."
msgid "Update the purchase order quantities"
msgstr "Satın alma siparişi miktarlarını güncelle"
+msgid "Update the return order quantities"
+msgstr "İade siparişi miktarlarını güncelle"
+
msgid "Updated"
msgstr "Güncellendi"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index ccb2010425..60ee3a0858 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -18717,6 +18717,9 @@ msgstr "移除按列排序"
msgid "Remove station"
msgstr "删除工位"
+msgid "Remove the received serial and batch numbers from stock"
+msgstr "从库存中移除已收货的序列号和批次号"
+
msgid "Remove this item"
msgstr "移除此物料"
@@ -19147,9 +19150,6 @@ msgstr "从备份中恢复此公司"
msgid "Restore this entity to available stock at the bin and cost it was scrapped from."
msgstr "将此实体恢复到来自其被报废的料箱和成本的可用库存。"
-msgid "Restore tracked entities to available"
-msgstr "将跟踪的实体恢复为可用"
-
msgid "Restore…"
msgstr "恢复…"
@@ -23375,6 +23375,9 @@ msgstr "零件报废时记录的原因"
msgid "The reasons you record when you decline an RFQ"
msgstr "您拒绝询价单时记录的原因"
+msgid "The receipt was not voided"
+msgstr "该收货单未被作废"
+
msgid "The record a workflow notification points at, named as an id plus its kind; leave it empty and the notification links to the workflow run itself."
msgstr "工作流通知指向的记录,命名为 id 及其类型;将其留空,通知链接到工作流运行本身。"
@@ -25127,6 +25130,9 @@ msgstr "更新看板信息以进行扫描式补货。"
msgid "Update the purchase order quantities"
msgstr "更新采购订单数量"
+msgid "Update the return order quantities"
+msgstr "更新退货单数量"
+
msgid "Updated"
msgstr "已更新"