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(quality): ship rejected units on supplier returns; NCR supplier and links (#1982)

Brad Barbin48f81e60264d
diff --git a/.claude/rules/inspection-system.md b/.claude/rules/inspection-system.md
index 17df11ffd3..49ec51ddd0 100644
--- a/.claude/rules/inspection-system.md
+++ b/.claude/rules/inspection-system.md
@@ -62,7 +62,10 @@ full-screen execution UI at `/x/inspection/{id}` (`InspectionView` +
(The pre-unification "fallback" samples table and the scanner's `mode="record"`
pass/fail path were removed 2026-07-25; scanning is always identify.)
-Disposition is always a human decision; Reject/Partial can auto-create an NCR
+Disposition is always a human decision. The ERP's **Reject Lot** is available on any open
+receipt lot: with no statistical failure, `RejectLotModal` requires a reason (a suspected
+counterfeit, the wrong part, transit damage), which `rejectInspection` passes to the engine
+as `reason`. Reject/Partial can auto-create an NCR
whose description includes the failed features (documentation only — never
required, and the NCR does not drive the physical outcome). The **ERP receipt
UI** exposes **Accept** and **Reject** (its `$id.partial.tsx` route exists but
@@ -382,8 +385,11 @@ GL/cost posting and `.ai/plans/2026-07-25-inspection-disposition-gl-posting.md`.
- `changeInspectionDocument` — swap/clear guarded to unmeasured non-terminal lots; wipes
plan rows for re-resolution.
- `dispositionInspection` — per-feature gating when the lot has features (Accept: every
- feature `recorded >= n && failed <= Ac`; Reject: some feature `failed >= Re` or a failed
- sample); Accept releases every non-failed lot entity to Available (un-sampled AND
+ feature `recorded >= n && failed <= Ac`; Reject: the pure `isRejectableWithoutReason`
+ (some feature `failed >= Re` or a failed sample; with no features, failed samples > Ac —
+ the rule both apps' Reject buttons apply, pinned by `packages/database/src/quality.test.ts`)
+ or a `reason`, so a lot can be rejected with nothing failed, e.g. a suspected counterfeit,
+ and the reason is stored as the lot's `notes`); Accept releases every non-failed lot entity to Available (un-sampled AND
partially-inspected Pending samples included); Reject flips all lot entities to
Rejected (and for a non-tracked Inventory item posts an `itemLedger` `Inbound Inspection`
negative adjustment); Partial leaves entities; always writes `inspectionHistory`.
@@ -396,7 +402,14 @@ GL/cost posting and `.ai/plans/2026-07-25-inspection-disposition-gl-posting.md`.
semantics.
- NCR auto-creation lives in the **`rejectInspection` operation** (`quality.server.ts`,
called by `x+/inspection+/$id.reject.tsx`), optional via `createNcr`, linking through `nonConformanceInspection`; the description
- includes a "Failed features" block built from the lot's measurements.
+ includes the `reason` and a "Failed features" block built from the lot's measurements,
+ and the lot's
+ `supplierId` is written as the issue's `nonConformanceSupplier` (`insertIssue`'s
+ `supplierId`). The `$id` loader reads the lot's issues (`getInspectionIssues`) and the
+ header links them (one: a button with the issue's readable id; several: an Issues
+ menu). The header's **Create Issue** button passes the failed entities and the lot's
+ `supplierId`, never the inspection: an inspection link tells `closeIssue` the lot was
+ written off at reject, which is only true for a rejected lot.
- **Service** `quality.service.ts`: `getInspections` (list), `getInspection`,
`getInspectionTrackedEntities`, `getInspectionSamplingPlans` (embeds
`inspectionFeature(...)` by table name), `getInspectionMeasurements`,
diff --git a/.claude/rules/issue-module.md b/.claude/rules/issue-module.md
index d560b3105b..fe04d50cee 100644
--- a/.claude/rules/issue-module.md
+++ b/.claude/rules/issue-module.md
@@ -91,7 +91,11 @@ in the migrations — **newest wins**; core tables created in
failure aborts the close). Movement rules: tracked Scrap/Return → `-link.qty` per
entity; non-tracked `Inventory` **non-inspection** Scrap → `-row.qty` write-off;
non-tracked `Inventory` **inspection-originated** Use-As-Is/Rework → `+row.qty` restore
- (undoing the reject write-off); tracked Use-As-Is/Rework and any `Non-Inventory` move
+ (undoing the reject write-off); inspection-originated Return to Supplier → nothing, because
+ the supplier return shipment puts those units back before it ships them
+ (`getReturnLineWriteOffs` in `postShipment`, at the write-off's own cost, Dr Inventory /
+ Cr Scrap; voiding the shipment writes them off again) — without it the shipment relieved
+ units the reject had already written off; tracked Use-As-Is/Rework and any `Non-Inventory` move
no value. Origin detected via the `nonConformanceInspection` link. Reopen is blocked
once a `Non-Conformance` `itemLedger` row exists (`setIssueStatus`). See
`.claude/rules/inspection-system.md` and `.ai/plans/2026-07-25-inspection-disposition-gl-posting.md`.
diff --git a/.claude/rules/shipments-receipts-ui-patterns.md b/.claude/rules/shipments-receipts-ui-patterns.md
index 31e6a6e685..17f99be494 100644
--- a/.claude/rules/shipments-receipts-ui-patterns.md
+++ b/.claude/rules/shipments-receipts-ui-patterns.md
@@ -52,8 +52,11 @@ run the same checks. The route only parses the form, and takes the document id f
- `lines.tracking.tsx` (`assignShipmentLineEntity`; receipt: `setReceiptLineBatch` /
`setReceiptLineSerial` / `assignReceiptReturnEntity` / `removeReceiptReturnEntity`, one per
`trackingType`) — writes `trackedEntity.attributes` (`"Shipment Line"`, `Shipment`, serial
- `"Shipment Line Index"`); guards entity status — `"Available"` normally, `"On Hold"` when the
- shipment's source is a Sales Return Order (returned stock ships back from hold); clears stale
+ `"Shipment Line Index"`); guards entity status with `shippableEntityStatuses`
+ (`inventory.utils.ts`) — `"Available"` normally, `"On Hold"` when the shipment's source is a
+ Sales Return Order (returned stock ships back from hold), `"Available"` or `"Rejected"` when it
+ is a Purchase Return Order (rejected units go back to the supplier — a Rejected unit only when
+ its `Receipt` attribute is a posted receipt from the shipment's supplier); clears stale
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).
@@ -128,7 +131,11 @@ Navigate via the typed `path.to.*` helpers (`shipmentDetails`, `shipment`, `ship
submissions. Batch/serial sub-forms render only when `line.requiresBatchTracking` /
`requiresSerialTracking`. **Receipt** batch/serial forms add an **expiration date** (batch date
shows only when item shelf-life mode is "Set on Receipt") and a per-line **FileDropzone**;
- shipment forms do not.
+ shipment forms do not. A receipt line that is inspected shows a small red clipboard beside the
+ item name (`ReceiptLineInspectionMark`): on an unposted Purchase Order receipt when the item has
+ a Receipt-usage inspection plan (`getReceiptInspectedItemIds`, loader `inspectedItemIds`), and
+ once posted when the line has a lot (`receiptInspections` by `sourceDocumentLineId`), which the
+ mark links to for a `quality` viewer.
- **Rental lines**: on a `'Rental Agreement'` document the loader reads `getRentalShipmentLines` /
`getRentalReceiptLines` into `rentalLines`, rendered by the siblings `ShipmentRentalLineItem` /
`ReceiptRentalLineItem` (no storage unit picker, no serial tracking). Both render the unit through
@@ -156,9 +163,9 @@ Navigate via the typed `path.to.*` helpers (`shipmentDetails`, `shipment`, `ship
`lines.tracking`'s guard or they reject what tracking accepted:
`ReceiptPostModal` counts a serial slot as filled when the entity is merely ASSIGNED on a
`Sales Return Order` receipt (returned units are picked, not typed, so they carry no
- `readableId` of their own); `ShipmentPostModal` and `ShipmentLines`' batch/serial inputs
- expect `On Hold` rather than `Available` when the shipment's source is a
- `Sales Return Order` (see `expectedEntityStatus` in `ShipmentLines.tsx`).
+ `readableId` of their own); `ShipmentPostModal`, `ShipmentLines`' batch/serial inputs and
+ `lines.tracking` all read `shippableEntityStatuses` (`inventory.utils.ts`, pinned by
+ `inventory.utils.test.ts`), so the three cannot drift.
## Posting flow (`$id.post.tsx` → `api.inventory.postShipment` / `postReceipt` → posting body)
diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.md
index 4d609844e0..232a0b10a9 100644
--- a/apps/erp/app/modules/inventory/AGENTS.md
+++ b/apps/erp/app/modules/inventory/AGENTS.md
@@ -8,7 +8,7 @@ Tracks item quantities across locations and storage units. Manages receipts, shi
- **Tracked Entity** — serial/batch/lot-tracked item instance with `readableId` (serial or batch number), `status` (Available/Reserved/On Hold/Consumed/Rejected/Scrapped), `quantity`, and `expirationDate`. `Scrapped` is terminal but recoverable via the Unscrap adjustment. Batch items have `batchProperty` definitions. A serialized unit can leave stock as a fixed asset: the storage-unit row action **Capitalize as Fixed Asset** (`ui/Inventory/InventoryStorageUnits.tsx`, rows with a `trackedEntityId`, needs `create: accounting`) opens `path.to.fixedAssetCapitalize` with `itemId`, `trackedEntityId`, `locationId` and `storageUnitId` as search params; `postAssetTransfer` (`accounting.service.ts`, ported from the `post-asset-transfer` server function) then consumes the unit (`Consumed`, `attributes["Fixed Asset"]`, a `'Capitalize'` `trackedActivity`, `itemLedger` −1 `'Asset Transfer'`) at its carrying cost, and **Return to Inventory** on the asset brings the same unit back `Available` at net book value. See `.claude/rules/fixed-asset-lifecycle.md`.
- **Item Ledger** — append-only log of every inventory movement (`itemLedger` table). Source of truth for on-hand quantities. MUST never INSERT directly — always go through service functions.
- **Receipt** — inbound inventory from POs, transfers, customer RMAs (source "Sales Return Order"), or rental units coming back (source "Rental Agreement"). Lines link to `purchaseOrderLine`, jobs, or `salesReturnOrderLine`. Posting creates ledger entries and tracked entities; RMA receipts re-enter at the original outbound cost (shipment consumption rows), current cost for blind returns, or zero when the return reason flags `inventoryValueZero`, and reactivate the SAME tracked entity On Hold (ReturnEntityForm re-tags the Consumed entity instead of minting a new serial). A rental receipt holds no `receiptLine`: each unit is a `receiptFixedAssetLine` with `rentalAgreementLineId`, and posting returns the unit on its agreement and moves its `fixedAsset.locationId` to the receipt's location, with no `itemLedger` row or journal for a `Rental` line (see sales AGENTS → Rentals → Deliver and return). A rental receipt cannot be voided.
-- **Shipment** — outbound inventory to customers, or return flows: source "Purchase Return Order" ships supplier returns (Cr Inventory / Dr GRNI at carried cost), source "Sales Return Order" ships rejected RMA claims back to the customer (On Hold entities allowed in lines.tracking for that source only), source "Rental Agreement" delivers rental units: each unit is a `shipmentFixedAssetLine` with `rentalAgreementLineId`, posting puts it On Rent and writes no `itemLedger`, `costLedger` or journal row, and its PDF prints as a "Delivery Ticket".
+- **Shipment** — outbound inventory to customers, or return flows: source "Purchase Return Order" ships supplier returns (Cr Inventory / Dr GRNI at carried cost; a line linked to an issue whose inspection reject wrote off a non-tracked lot first puts those units back — `getReturnLineWriteOffs`, a Positive Adjmt. under the shipment at the write-off's own cost, Dr Inventory / Cr Scrap — so they are relieved once, and the void writes them off again), source "Sales Return Order" ships rejected RMA claims back to the customer (On Hold entities allowed in lines.tracking for that source only), source "Rental Agreement" delivers rental units: each unit is a `shipmentFixedAssetLine` with `rentalAgreementLineId`, posting puts it On Rent and writes no `itemLedger`, `costLedger` or journal row, and its PDF prints as a "Delivery Ticket".
- **Stock Transfer** — moves inventory between storage units within the same location. A transfer with `kanbanId` set is a kanban replenishment (written by `replenishKanban` (`inventory.service.ts`, ported from the `kanban-replenish` server function)); the list shows it as Source "Kanban".
- **Warehouse Transfer** — moves inventory between locations (inter-location).
- **Picking List** — generated pick instructions with FEFO/FIFO ordering and tracked entity allocation.
@@ -71,7 +71,7 @@ Each operation is one `defineServiceFn` const in `inventory.server.ts`. A route
| `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) |
+| `assignShipmentLineEntity` | `shipment+/lines.tracking.tsx` | The line's item, in a status `shippableEntityStatuses` (`inventory.utils.ts`) allows: Available; On Hold, received on this return order, for a return-to-customer shipment; Available, or Rejected and received on a posted receipt from the return's supplier, for a return-to-supplier shipment |
| `createStockTransfer` / `setStockTransferStatus` | `stock-transfer+/new.tsx`, `$id.status.tsx` | Storage rules on `stockTransfer`; reopening a Completed transfer needs `delete: inventory` |
| `pickStockTransferLine` / `unpickStockTransferLine` / `pickStockTransferLineEntity`, `updateStockTransferLines` | `$id.line.quantity.tsx` (0 unpicks), `$id.scan.$lineId.tsx`, `lines.update.tsx` | `postStockTransfer` (`inventory.service.ts`, ported from `post-stock-transfer`); a Completed transfer is refused; a scanned pick never exceeds what is left |
| `setWarehouseTransferStatus`, `createWarehouseTransferLine` / `updateWarehouseTransferLine` / `removeWarehouseTransferLine` | `$transferId.status.tsx`, `$transferId.details.new.tsx`, `$transferId.details.$id.tsx` | Storage rules on `warehouseTransfer`; lines change only on a Draft transfer |
diff --git a/apps/erp/app/modules/inventory/inventory.server.ts b/apps/erp/app/modules/inventory/inventory.server.ts
index a9464324e6..bc77898af3 100644
--- a/apps/erp/app/modules/inventory/inventory.server.ts
+++ b/apps/erp/app/modules/inventory/inventory.server.ts
@@ -2036,7 +2036,7 @@ export const assignShipmentLineEntity = defineServiceFn({
.single(),
client
.from("shipment")
- .select("sourceDocument, sourceDocumentId, status")
+ .select("sourceDocument, sourceDocumentId, status, supplierId")
.eq("id", shipmentId)
.eq("companyId", companyId)
.single(),
@@ -2073,12 +2073,16 @@ export const assignShipmentLineEntity = defineServiceFn({
);
}
- // A return-to-customer shipment ships returned stock, On Hold until it
- // is dispositioned; everything else ships Available stock only. On Hold
- // alone is not provenance: the entity must have COME BACK on a receipt
- // of this return order.
+ // The statuses this source may ship (`shippableEntityStatuses`): a
+ // return-to-customer ships returned stock, On Hold until it is
+ // dispositioned; a return-to-supplier also ships rejected units;
+ // everything else ships Available stock only. On Hold alone is not
+ // provenance: the entity must have COME BACK on a receipt of this
+ // return order.
const isReturn = shipment.data.sourceDocument === "Sales Return Order";
- const allowedStatus = isReturn ? "On Hold" : "Available";
+ const allowedStatuses = utils.shippableEntityStatuses(
+ shipment.data.sourceDocument
+ );
const attributes = (entity.data.attributes ?? {}) as Record<
string,
unknown
@@ -2111,13 +2115,47 @@ export const assignShipmentLineEntity = defineServiceFn({
}
}
- if (entity.data.status !== allowedStatus) {
+ if (!allowedStatuses.includes(entity.data.status)) {
return ctx.error(
"rule",
`Tracked entity is not available. Current status: ${entity.data.status}`
);
}
+ // Rejected alone is not provenance either: a rejected unit goes back only
+ // to the supplier it came from, i.e. it was received on a posted receipt
+ // from this return's supplier (the rule the return-line picker applies).
+ if (
+ shipment.data.sourceDocument === "Purchase Return Order" &&
+ entity.data.status === "Rejected"
+ ) {
+ const receiptId = attributes.Receipt;
+ const provenance =
+ typeof receiptId === "string" && shipment.data.supplierId
+ ? await client
+ .from("receipt")
+ .select("id")
+ .eq("id", receiptId)
+ .eq("supplierId", shipment.data.supplierId)
+ .eq("status", "Posted")
+ .eq("companyId", companyId)
+ .maybeSingle()
+ : { data: null, error: null };
+ if (provenance.error) {
+ return ctx.error(
+ "internal",
+ "Failed to verify the entity's provenance",
+ provenance.error
+ );
+ }
+ if (!provenance.data) {
+ return ctx.error(
+ "rule",
+ "Rejected tracked entity was not received from this supplier and cannot be returned to it"
+ );
+ }
+ }
+
// Rounded: a lot left holding 0.020000000000000018 by an earlier split
// has enough for a 0.02 assignment.
if (
@@ -2143,7 +2181,7 @@ export const assignShipmentLineEntity = defineServiceFn({
.eq("id", trackedEntityId)
.eq("companyId", companyId)
// Guards a concurrent status change: no row matched is a conflict.
- .eq("status", allowedStatus)
+ .eq("status", entity.data.status)
.select("id");
if (updated.error) {
return ctx.error(
@@ -2155,7 +2193,7 @@ export const assignShipmentLineEntity = defineServiceFn({
if (!updated.data?.length) {
return ctx.error(
"conflict",
- `Tracked entity is no longer ${allowedStatus}`
+ `Tracked entity is no longer ${entity.data.status}`
);
}
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 30c8caa062..9c7969eacb 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -137,9 +137,11 @@ import {
} from "~/modules/sales/sales.service";
import * as settingsService from "~/modules/settings/settings.service";
import {
+ type AdjustmentItemCost,
assertCompanyRecords,
assertPostable,
attributesContain,
+ type BookAdjustmentArgs,
bookAdjustment,
buildCostLedgerRow,
buildJournalLineDimensions,
@@ -220,7 +222,7 @@ import {
reconcileReceiptLineSerials,
shippingCarrierType
} from "./inventory.models";
-import { clampDepth } from "./inventory.utils";
+import { clampDepth, writeOffRestoreQuantity } from "./inventory.utils";
import { renderPackingSlip } from "./packing-slip.pdf";
import {
effectiveSuccessorId,
@@ -13401,6 +13403,214 @@ async function lockRentalUnits(
return { linesById, assetsById };
}
+/** Units of a supplier return line an inspection reject already wrote off. */
+type ReturnLineWriteOff = {
+ quantity: number;
+ // The write-off's own unit cost, so restoring at it nets scrap to zero.
+ unitCost: number | null;
+ // Where the write-off was booked (the receipt's location, no bin).
+ locationId: string | null;
+};
+
+/**
+ * A non-tracked lot is written off when its inspection rejects it: it has no
+ * Rejected status to keep it out of on-hand. Shipping those units back to the
+ * supplier would relieve them a second time, so the return shipment first puts
+ * them back. This finds, per return line, how many of its units that applies
+ * to: the quantity the line covers for an issue whose inspection posted a
+ * write-off of the line's item, capped at what was written off.
+ */
+async function getReturnLineWriteOffs(
+ db: Kysely<KyselyDatabase> | Transaction<KyselyDatabase>,
+ companyId: string,
+ lines: { id: string; itemId: string | null }[]
+): Promise<Map<string, ReturnLineWriteOff>> {
+ const result = new Map<string, ReturnLineWriteOff>();
+ const lineIds = lines.filter((line) => line.itemId).map((line) => line.id);
+ if (lineIds.length === 0) return result;
+
+ const links = await db
+ .selectFrom("nonConformancePurchaseReturnOrderLine")
+ .select(["nonConformanceId", "purchaseReturnOrderLineId", "quantity"])
+ .where("companyId", "=", companyId)
+ .where("purchaseReturnOrderLineId", "in", lineIds)
+ .execute();
+ if (links.length === 0) return result;
+
+ const inspectionLinks = await db
+ .selectFrom("nonConformanceInspection")
+ .select(["nonConformanceId", "inspectionId"])
+ .where("companyId", "=", companyId)
+ .where("nonConformanceId", "in", [
+ ...new Set(links.map((link) => link.nonConformanceId))
+ ])
+ .execute();
+ const inspectionIds = [
+ ...new Set(inspectionLinks.map((link) => link.inspectionId))
+ ];
+ if (inspectionIds.length === 0) return result;
+
+ // The reject's write-off: the Inbound Inspection movement and the cost it
+ // relieved, both keyed by the inspection.
+ const [writeOffLedger, writeOffCosts] = await Promise.all([
+ db
+ .selectFrom("itemLedger")
+ .select(["documentId", "itemId", "quantity", "locationId"])
+ .where("companyId", "=", companyId)
+ .where("documentType", "=", "Inbound Inspection")
+ .where("documentId", "in", inspectionIds)
+ .where("quantity", "<", 0)
+ .execute(),
+ db
+ .selectFrom("costLedger")
+ .select(["documentId", "itemId", "quantity", "cost"])
+ .where("companyId", "=", companyId)
+ .where("documentId", "in", inspectionIds)
+ .where("quantity", "<", 0)
+ .execute()
+ ]);
+
+ for (const line of lines) {
+ if (!line.itemId) continue;
+ const lineLinks = links.filter(
+ (link) => link.purchaseReturnOrderLineId === line.id
+ );
+ const lineInspectionIds = new Set(
+ inspectionLinks
+ .filter((link) =>
+ lineLinks.some((l) => l.nonConformanceId === link.nonConformanceId)
+ )
+ .map((link) => link.inspectionId)
+ );
+ const ledger = writeOffLedger.filter(
+ (row) =>
+ row.itemId === line.itemId &&
+ lineInspectionIds.has(row.documentId as string)
+ );
+ if (ledger.length === 0) continue;
+ const writtenOff = ledger.reduce(
+ (sum, row) => sum + Math.abs(Number(row.quantity)),
+ 0
+ );
+ // Only links to an issue that wrote this item off count toward the line.
+ const writtenOffIssueIds = new Set(
+ inspectionLinks
+ .filter((link) =>
+ ledger.some((row) => row.documentId === link.inspectionId)
+ )
+ .map((link) => link.nonConformanceId)
+ );
+ const covered = lineLinks
+ .filter((link) => writtenOffIssueIds.has(link.nonConformanceId))
+ .reduce((sum, link) => sum + Number(link.quantity ?? 0), 0);
+ const quantity = Math.min(covered, writtenOff);
+ if (quantity <= 0) continue;
+ result.set(line.id, {
+ quantity,
+ unitCost: resolveUnscrapUnitCost(
+ writeOffCosts
+ .filter(
+ (row) =>
+ row.itemId === line.itemId &&
+ lineInspectionIds.has(row.documentId as string)
+ )
+ .map((row) => ({
+ quantity: Number(row.quantity),
+ cost: Number(row.cost)
+ }))
+ ),
+ locationId: ledger[0]?.locationId ?? null
+ });
+ }
+ return result;
+}
+
+/**
+ * The journal side of an inspection write-off that a supplier return puts back
+ * (or, on void, writes off again): inventory against the scrap account, as the
+ * reject booked it.
+ */
+async function returnWriteOffAccounting(
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ args: {
+ postingStatus: AutomaticJournalStatus;
+ accountingPeriodId: string | null;
+ description: string;
+ userId: string;
+ }
+): Promise<NonNullable<BookAdjustmentArgs["accounting"]>> {
+ const [accountDefaults, company] = await Promise.all([
+ getDefaultPostingGroup(db, companyId),
+ single(db, "company", { id: companyId }, { columns: ["companyGroupId"] })
+ ]);
+ if (accountDefaults.error || !accountDefaults.data) {
+ throw new Error("Error getting account defaults");
+ }
+ // The Item / ItemPostingGroup / Location tags every adjustment carries.
+ const dimensions: Record<string, string> = {};
+ if (company.data?.companyGroupId) {
+ const active = await many(
+ db,
+ "dimension",
+ {
+ companyGroupId: company.data.companyGroupId,
+ active: true,
+ entityType: ["Item", "ItemPostingGroup", "Location"]
+ },
+ { columns: ["id", "entityType"] }
+ );
+ for (const dim of active.data ?? []) {
+ if (dim.entityType) dimensions[dim.entityType] = dim.id;
+ }
+ }
+ return {
+ postingStatus: args.postingStatus,
+ accountingPeriodId: args.accountingPeriodId,
+ accountDefaults: {
+ rawMaterialsAccount: accountDefaults.data.rawMaterialsAccount,
+ finishedGoodsAccount: accountDefaults.data.finishedGoodsAccount,
+ inventoryAdjustmentVarianceAccount:
+ accountDefaults.data.inventoryAdjustmentVarianceAccount
+ },
+ offsetAccount: resolveDefaultAccount(
+ accountDefaults.data,
+ "scrapAccount",
+ args.postingStatus
+ ).accountId,
+ offsetDescription: "Scrap / Cost of Quality",
+ sourceType: "Purchase Return Shipment",
+ description: args.description,
+ userId: args.userId,
+ dimensions
+ };
+}
+
+/** Costing inputs for valuing a restore when its write-off cost is unknown. */
+async function adjustmentItemCosts(
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ itemIds: string[]
+): Promise<Map<string, AdjustmentItemCost>> {
+ if (itemIds.length === 0) return new Map();
+ const rows = await db
+ .selectFrom("itemCost")
+ .select(["itemId", "costingMethod", "unitCost", "standardCost"])
+ .where("companyId", "=", companyId)
+ .where("itemId", "in", itemIds)
+ .execute();
+ return new Map(
+ rows.map((row) => [
+ row.itemId,
+ {
+ costingMethod: row.costingMethod,
+ unitCost: row.unitCost == null ? null : Number(row.unitCost),
+ standardCost: row.standardCost == null ? null : Number(row.standardCost)
+ }
+ ])
+ );
+}
+
export const postShipmentInput = z.object({
type: z.enum(["post", "void"]),
shipmentId: z.string(),
@@ -15529,6 +15739,19 @@ export async function postShipment(
ledgerIndex: number;
}[] = [];
const splitChildEdges: { childId: string; quantity: number }[] = [];
+ // Units an inspection reject already wrote off: put back before
+ // they ship, so the shipment relieves them once, not twice.
+ const returnLineWriteOffs = await getReturnLineWriteOffs(
+ db,
+ companyId,
+ purchaseReturnOrderLines.data ?? []
+ );
+ const writeOffRestores: {
+ itemId: string;
+ quantity: number;
+ locationId: string | null;
+ unitCost: number | null;
+ }[] = [];
for (const shipmentLine of shipmentLines.data) {
if (!shipmentLine.itemId || !shipmentLine.lineId) continue;
@@ -15570,6 +15793,30 @@ export async function postShipment(
);
if (itemTrackingType === "Inventory") {
+ // The first units the line ships are the written-off ones;
+ // earlier shipments of the line already put theirs back.
+ const writeOff = returnLineWriteOffs.get(returnLine.id);
+ if (writeOff) {
+ const shippedBefore =
+ existingUpdate?.quantityShipped ??
+ Number(returnLine.quantityShipped ?? 0);
+ const restore = round(
+ writeOffRestoreQuantity({
+ shipped: shippedQuantity,
+ writtenOff: writeOff.quantity,
+ shippedBefore
+ })
+ );
+ if (restore > 0) {
+ writeOffRestores.push({
+ itemId: shipmentLine.itemId,
+ quantity: restore,
+ locationId:
+ writeOff.locationId ?? shipmentLine.locationId,
+ unitCost: writeOff.unitCost
+ });
+ }
+ }
itemShipmentQuantities[shipmentLine.itemId] =
(itemShipmentQuantities[shipmentLine.itemId] ?? 0) +
shippedQuantity;
@@ -15651,6 +15898,19 @@ export async function postShipment(
? await getCurrentAccountingPeriod(companyId, db, today)
: null;
+ const restoreAccounting =
+ writeOffRestores.length > 0
+ ? await returnWriteOffAccounting(db, companyId, {
+ postingStatus,
+ accountingPeriodId,
+ description: `Inspection write-off put back for return shipment ${shipmentHeader.shipmentId}`,
+ userId
+ })
+ : null;
+ const restoreItemCosts = await adjustmentItemCosts(db, companyId, [
+ ...new Set(writeOffRestores.map((restore) => restore.itemId))
+ ]);
+
await db.transaction().execute(async (trx) => {
// Double-post guard: serialize on the shipment row — a second
// concurrent post waits here, then sees Posted and aborts, so
@@ -15685,6 +15945,45 @@ export async function postShipment(
);
}
+ // Put back what the inspection reject wrote off, at the write-off's
+ // own cost (Dr Inventory / Cr Scrap) and where it was written off,
+ // so the shipment below relieves those units once. The value rows
+ // stay under this shipment: a void reverses the restore with it.
+ for (const restore of writeOffRestores) {
+ const item = items.data.find((i) => i.id === restore.itemId);
+ await bookAdjustment(trx, {
+ ledger: {
+ postingDate: today,
+ itemId: restore.itemId,
+ quantity: restore.quantity,
+ locationId: restore.locationId,
+ storageUnitId: null,
+ trackedEntityId: null,
+ entryType: "Positive Adjmt.",
+ documentType: "Purchase Return Shipment",
+ documentId: shipmentId,
+ comment:
+ "Inspection write-off put back to ship to the supplier",
+ companyId,
+ createdBy: userId
+ },
+ item: {
+ itemTrackingType: item?.itemTrackingType ?? "Inventory",
+ replenishmentSystem: item?.replenishmentSystem ?? null,
+ itemPostingGroupId:
+ itemCosts.data.find((c) => c.itemId === restore.itemId)
+ ?.itemPostingGroupId ?? null
+ },
+ itemCost: restoreItemCosts.get(restore.itemId) ?? {
+ costingMethod: "Average",
+ unitCost: 0,
+ standardCost: 0
+ },
+ accounting: restoreAccounting,
+ fixedUnitCost: restore.unitCost ?? undefined
+ });
+ }
+
// Split any batch returned in part: keep the shelf entity's id
// (decremented), depart the shipped portion as a new Consumed
// child, and retarget the negative Purchase Return Shipment
@@ -17371,16 +17670,47 @@ export async function postShipment(
);
}
+ // The posting put back units an inspection reject had written off
+ // (a positive row of the shipment's own). Voiding writes them off
+ // again, against scrap, rather than reversing them like the
+ // shipment's other rows.
+ const isWriteOffRestore = (entry: {
+ entryType: string;
+ quantity: number;
+ }) =>
+ entry.entryType === "Positive Adjmt." &&
+ Number(entry.quantity) > 0;
+ const writeOffRestores = (originalItemLedger.data ?? []).filter(
+ isWriteOffRestore
+ );
+
// A Provisional journal has no accounting period.
const accountingPeriodId =
- postingStatus === "Posted" && originalJournalLines.length > 0
+ postingStatus === "Posted" &&
+ (originalJournalLines.length > 0 || writeOffRestores.length > 0)
? await getCurrentAccountingPeriod(companyId, db, today)
: null;
+ const rewriteOffAccounting =
+ writeOffRestores.length > 0
+ ? await returnWriteOffAccounting(db, companyId, {
+ postingStatus,
+ accountingPeriodId,
+ description: `VOID: inspection write-off put back for return shipment ${shipmentHeader.shipmentId}`,
+ userId
+ })
+ : null;
+ const rewriteOffItemCosts = await adjustmentItemCosts(
+ db,
+ companyId,
+ [...new Set(writeOffRestores.map((entry) => entry.itemId))]
+ );
+
await db.transaction().execute(async (trx) => {
await assertPostingStatusUnchanged(trx, companyId, postingStatus);
- const reversingItemLedger = (originalItemLedger.data ?? []).map(
- (entry) => ({
+ const reversingItemLedger = (originalItemLedger.data ?? [])
+ .filter((entry) => !isWriteOffRestore(entry))
+ .map((entry) => ({
postingDate: today,
itemId: entry.itemId,
quantity: -entry.quantity,
@@ -17393,8 +17723,7 @@ export async function postShipment(
trackedEntityId: entry.trackedEntityId,
createdBy: userId,
companyId
- })
- );
+ }));
if (reversingItemLedger.length > 0) {
await trx
.insertInto("itemLedger")
@@ -17402,6 +17731,39 @@ export async function postShipment(
.execute();
}
+ for (const entry of writeOffRestores) {
+ const item = items.data.find((i) => i.id === entry.itemId);
+ await bookAdjustment(trx, {
+ ledger: {
+ postingDate: today,
+ itemId: entry.itemId,
+ quantity: -Number(entry.quantity),
+ locationId: entry.locationId,
+ storageUnitId: entry.storageUnitId,
+ trackedEntityId: null,
+ entryType: "Negative Adjmt.",
+ documentType: "Purchase Return Shipment",
+ documentId: shipmentId,
+ comment: "Inspection write-off restored by the void",
+ companyId,
+ createdBy: userId
+ },
+ item: {
+ itemTrackingType: item?.itemTrackingType ?? "Inventory",
+ replenishmentSystem: item?.replenishmentSystem ?? null,
+ itemPostingGroupId:
+ itemCosts.data.find((c) => c.itemId === entry.itemId)
+ ?.itemPostingGroupId ?? null
+ },
+ itemCost: rewriteOffItemCosts.get(entry.itemId) ?? {
+ costingMethod: "Average",
+ unitCost: 0,
+ standardCost: 0
+ },
+ accounting: rewriteOffAccounting
+ });
+ }
+
// Restore inventory VALUE, not just quantity: posting consumed
// FIFO layers via calculateCOGS; without an offsetting layer
// the voided stock re-enters at zero value and inventory is
diff --git a/apps/erp/app/modules/inventory/inventory.utils.test.ts b/apps/erp/app/modules/inventory/inventory.utils.test.ts
new file mode 100644
index 0000000000..f112969a40
--- /dev/null
+++ b/apps/erp/app/modules/inventory/inventory.utils.test.ts
@@ -0,0 +1,74 @@
+// 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 {
+ isShippableEntityStatus,
+ shippableEntityStatuses,
+ writeOffRestoreQuantity
+} from "./inventory.utils";
+
+// Shipment tracking, the shipment page and the post modal all read this one
+// rule, so a status one accepts the others never refuse.
+describe("shippableEntityStatuses", () => {
+ it("ships rejected units back to the supplier on a supplier return", () => {
+ expect(shippableEntityStatuses("Purchase Return Order")).toEqual([
+ "Available",
+ "Rejected"
+ ]);
+ expect(isShippableEntityStatus("Purchase Return Order", "Rejected")).toBe(
+ true
+ );
+ // Units still awaiting inspection stay in the warehouse.
+ expect(isShippableEntityStatus("Purchase Return Order", "On Hold")).toBe(
+ false
+ );
+ });
+
+ it("ships returned stock, On Hold, back to the customer on a sales return", () => {
+ expect(shippableEntityStatuses("Sales Return Order")).toEqual(["On Hold"]);
+ expect(isShippableEntityStatus("Sales Return Order", "Available")).toBe(
+ false
+ );
+ });
+
+ it("ships only Available stock on every other source", () => {
+ for (const source of ["Sales Order", "Purchase Order", null, undefined]) {
+ expect(shippableEntityStatuses(source)).toEqual(["Available"]);
+ expect(isShippableEntityStatus(source, "Rejected")).toBe(false);
+ }
+ expect(isShippableEntityStatus("Sales Order", null)).toBe(false);
+ });
+});
+
+// A non-tracked lot an inspection rejected is written off at the reject, so a
+// return shipment puts those units back before shipping them — once.
+describe("writeOffRestoreQuantity", () => {
+ it("puts back every written-off unit the shipment ships", () => {
+ expect(
+ writeOffRestoreQuantity({ shipped: 2, writtenOff: 2, shippedBefore: 0 })
+ ).toBe(2);
+ });
+
+ it("puts back no more than the shipment ships", () => {
+ expect(
+ writeOffRestoreQuantity({ shipped: 1, writtenOff: 3, shippedBefore: 0 })
+ ).toBe(1);
+ });
+
+ it("leaves out units the line's earlier shipments already put back", () => {
+ expect(
+ writeOffRestoreQuantity({ shipped: 3, writtenOff: 3, shippedBefore: 1 })
+ ).toBe(2);
+ expect(
+ writeOffRestoreQuantity({ shipped: 2, writtenOff: 3, shippedBefore: 3 })
+ ).toBe(0);
+ });
+
+ it("puts back only written-off units when the line also returns good stock", () => {
+ expect(
+ writeOffRestoreQuantity({ shipped: 5, writtenOff: 2, shippedBefore: 0 })
+ ).toBe(2);
+ });
+});
diff --git a/apps/erp/app/modules/inventory/inventory.utils.ts b/apps/erp/app/modules/inventory/inventory.utils.ts
index 6847107673..fb23db9546 100644
--- a/apps/erp/app/modules/inventory/inventory.utils.ts
+++ b/apps/erp/app/modules/inventory/inventory.utils.ts
@@ -11,6 +11,53 @@ export function clampDepth(n: number): number {
return Math.min(Math.max(1, n), 5);
}
+type TrackedEntityStatus = Database["public"]["Enums"]["trackedEntityStatus"];
+
+/**
+ * The tracked-entity statuses a shipment of this source may ship. A return to
+ * a customer ships returned stock, On Hold until it leaves. A return to a
+ * supplier ships good stock or the units an inspection or issue rejected —
+ * sending rejects back is the point of the return. Everything else ships
+ * Available stock only. `assignShipmentLineEntity`, `ShipmentLines` and
+ * `ShipmentPostModal` all read this, so tracking and posting never disagree.
+ */
+export function shippableEntityStatuses(
+ sourceDocument: string | null | undefined
+): TrackedEntityStatus[] {
+ if (sourceDocument === "Sales Return Order") return ["On Hold"];
+ if (sourceDocument === "Purchase Return Order") {
+ return ["Available", "Rejected"];
+ }
+ return ["Available"];
+}
+
+/**
+ * How many units a supplier return shipment line puts back before shipping
+ * them: the line's units an inspection reject already wrote off, less what
+ * the line's earlier shipments already put back. The written-off units are
+ * the first the line ships.
+ */
+export function writeOffRestoreQuantity({
+ shipped,
+ writtenOff,
+ shippedBefore
+}: {
+ shipped: number;
+ writtenOff: number;
+ shippedBefore: number;
+}): number {
+ return Math.max(0, Math.min(shipped, writtenOff - shippedBefore));
+}
+
+export function isShippableEntityStatus(
+ sourceDocument: string | null | undefined,
+ status: string | null | undefined
+): boolean {
+ return (shippableEntityStatuses(sourceDocument) as string[]).includes(
+ status ?? ""
+ );
+}
+
export async function getReceiptTracking(
client: SupabaseClient<Database>,
receiptId: string,
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
index efdff3d0b5..e9f392befd 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
@@ -109,11 +109,19 @@ const getActivityText = (
: ""
}`;
case "Purchase Return Shipment":
- return `returned ${ledgerRecord.quantity} units to supplier${
- ledgerRecord.storageUnit?.name
- ? ` from ${ledgerRecord.storageUnit.name}`
- : ""
- }`;
+ // A return shipment's own positive rows put stock back: units an
+ // inspection reject wrote off (restored to ship them), or a void.
+ return ledgerRecord.quantity < 0
+ ? `returned ${-1 * ledgerRecord.quantity} units to supplier${
+ ledgerRecord.storageUnit?.name
+ ? ` from ${ledgerRecord.storageUnit.name}`
+ : ""
+ }`
+ : `added back ${ledgerRecord.quantity} units for a supplier return${
+ ledgerRecord.storageUnit?.name
+ ? ` to ${ledgerRecord.storageUnit.name}`
+ : ""
+ }`;
case "Sales Credit Memo":
return `credited ${ledgerRecord.quantity} units for sale${
ledgerRecord.storageUnit?.name
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index 24fceffa0c..0d8f388ef8 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -56,13 +56,21 @@ import { Suspense, useCallback, useEffect, useState } from "react";
import {
LuCalendar,
LuCircleAlert,
+ LuClipboardCheck,
LuEllipsisVertical,
LuGroup,
LuSplit,
LuTrash,
LuX
} from "react-icons/lu";
-import { Await, Outlet, useFetchers, useParams, useSubmit } from "react-router";
+import {
+ Await,
+ Link,
+ Outlet,
+ useFetchers,
+ useParams,
+ useSubmit
+} from "react-router";
import { z } from "zod";
import {
DocumentPreview,
@@ -76,7 +84,7 @@ import FileDropzone from "~/components/FileDropzone";
import StorageUnit from "~/components/Form/StorageUnit";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { ConfirmDelete } from "~/components/Modals";
-import { useRouteData, useUser } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { splitValidator } from "~/modules/inventory/inventory.models";
import type {
BatchProperty,
@@ -116,6 +124,8 @@ const ReceiptLines = () => {
serialNumber: string | null;
}[];
rentalLines: RentalReceiptLine[];
+ receiptInspections: ReceiptLineInspection[];
+ inspectedItemIds: string[];
receiptFiles: PostgrestResponse<StorageItem>;
receiptLineTracking: ItemTracking[];
batchProperties: PostgrestResponse<BatchProperty>;
@@ -274,11 +284,20 @@ const ReceiptLines = () => {
const tracking =
trackingCandidates.find((t) => t.expirationDate) ??
trackingCandidates[0];
+ const inspection = routeData?.receiptInspections?.find(
+ (i) => i.sourceDocumentLineId === line.id
+ );
return (
<ReceiptLineItem
key={line.id}
line={line}
receipt={routeData?.receipt}
+ inspection={inspection}
+ requiresInspection={
+ !!inspection ||
+ (!!line.itemId &&
+ !!routeData?.inspectedItemIds?.includes(line.itemId))
+ }
isReadOnly={isPosted}
onUpdate={onUpdateReceiptLine}
files={routeData?.receiptFiles}
@@ -586,9 +605,64 @@ function ReceiptRentalLineItem({
);
}
+/** An inspection lot posting the receipt opened for one of its lines. */
+type ReceiptLineInspection = {
+ id: string;
+ inspectionId: string;
+ sourceDocumentLineId: string | null;
+ status: string;
+};
+
+/**
+ * A small red mark beside a line whose item is inspected at receipt: before
+ * posting, the item has a Receipt-usage inspection plan; after, the lot posting
+ * opened, which the mark links to.
+ */
+function ReceiptLineInspectionMark({
+ inspection
+}: {
+ inspection?: ReceiptLineInspection;
+}) {
+ const { t } = useLingui();
+ const permissions = usePermissions();
+ const icon = <LuClipboardCheck className="size-4 shrink-0 text-red-500" />;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ {inspection && permissions.can("view", "quality") ? (
+ <Link
+ to={path.to.inspection(inspection.id)}
+ aria-label={t`Inspection ${inspection.inspectionId}`}
+ >
+ {icon}
+ </Link>
+ ) : (
+ <span role="img" aria-label={t`Requires inspection`}>
+ {icon}
+ </span>
+ )}
+ </TooltipTrigger>
+ <TooltipContent>
+ {inspection ? (
+ <Trans>
+ Inspection {inspection.inspectionId} · {inspection.status}
+ </Trans>
+ ) : (
+ <Trans>
+ Requires inspection. A lot opens when the receipt posts.
+ </Trans>
+ )}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
function ReceiptLineItem({
line,
receipt,
+ inspection,
+ requiresInspection,
className,
isReadOnly,
onUpdate,
@@ -604,6 +678,8 @@ function ReceiptLineItem({
}: {
line: ReceiptLine;
receipt?: Receipt;
+ inspection?: ReceiptLineInspection;
+ requiresInspection: boolean;
className?: string;
isReadOnly: boolean;
files?: PostgrestResponse<StorageItem>;
@@ -698,12 +774,17 @@ function ReceiptLineItem({
type={(item?.type as "Part") ?? "Part"}
/>
<VStack spacing={0} className="flex-1 min-w-0">
- <span
- className="text-sm font-medium truncate block w-full"
- title={item?.name}
- >
- {item?.name}
- </span>
+ <HStack spacing={1} className="w-full min-w-0">
+ <span
+ className="text-sm font-medium truncate block min-w-0"
+ title={item?.name}
+ >
+ {item?.name}
+ </span>
+ {requiresInspection && (
+ <ReceiptLineInspectionMark inspection={inspection} />
+ )}
+ </HStack>
<span className="text-xs text-muted-foreground line-clamp-2">
{item?.readableIdWithRevision}
</span>
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
index f29908f227..289f03fdfb 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
@@ -67,6 +67,7 @@ import type {
getBatchNumbersForItem,
getSerialNumbersForItem
} from "~/modules/inventory/inventory.service";
+import { isShippableEntityStatus } from "~/modules/inventory/inventory.utils";
import type {
ItemTracking,
RentalShipmentLine,
@@ -753,13 +754,11 @@ function ShipmentLineItem({
);
}
-// Sales-return shipments (source "Sales Return Order") ship returned stock,
-// which is deliberately On Hold until it leaves — mirror the status
-// lines.tracking accepts when validating entities for this source.
-function expectedEntityStatus(shipment?: Shipment) {
- return shipment?.sourceDocument === "Sales Return Order"
- ? "On Hold"
- : "Available";
+// The statuses lines.tracking accepts for this shipment's source: On Hold
+// returned stock on a sales return, Available or Rejected units on a supplier
+// return, Available stock otherwise.
+function isShippable(shipment: Shipment | undefined, status: unknown) {
+ return isShippableEntityStatus(shipment?.sourceDocument, status as string);
}
function BatchForm({
@@ -827,7 +826,7 @@ function BatchForm({
: null;
const isBatchNumberValid =
// @ts-expect-error TS2339 - TODO: fix type
- resolvedBatch?.status === expectedEntityStatus(shipment);
+ isShippable(shipment, resolvedBatch?.status);
// Verify batch quantity is sufficient for the shipped quantity
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
@@ -845,7 +844,7 @@ function BatchForm({
if (
batchNumber &&
// @ts-expect-error TS2339 - TODO: fix type
- batchNumber.status === expectedEntityStatus(shipment) &&
+ isShippable(shipment, batchNumber.status) &&
// @ts-expect-error TS2339 - TODO: fix type
(line.shippedQuantity || 0) > batchNumber.quantity
) {
@@ -920,7 +919,7 @@ function BatchForm({
);
// @ts-expect-error TS2339 - TODO: fix type
- if (batchNumber && batchNumber.status !== expectedEntityStatus(shipment)) {
+ if (batchNumber && !isShippable(shipment, batchNumber.status)) {
// @ts-expect-error TS2339 - TODO: fix type
setError(`Batch number is ${batchNumber.status}`);
setValues({
@@ -987,8 +986,8 @@ function BatchForm({
// scanners, and the QR affordance opens the list of batches this line accepts.
// Quantity is shown alongside each one because a batch smaller than the
// shipped quantity is split on posting, which is worth seeing before picking.
- const selectableBatches = (batchNumbers?.data ?? []).filter(
- (entity) => entity.status === expectedEntityStatus(shipment)
+ const selectableBatches = (batchNumbers?.data ?? []).filter((entity) =>
+ isShippable(shipment, entity.status)
);
return (
@@ -1174,7 +1173,7 @@ function SerialForm({
}
// @ts-expect-error TS2339 - TODO: fix type
- if (serialNumber.status !== expectedEntityStatus(shipment)) {
+ if (!isShippable(shipment, serialNumber.status)) {
// @ts-expect-error TS2339 - TODO: fix type
return `Serial number is ${serialNumber.status}`;
}
@@ -1296,7 +1295,7 @@ function SerialForm({
// this off the same data `validateSerialNumber` checks keeps them in step.
const unassignedSerialNumbers = (serialNumbersData?.data ?? []).filter(
(entity) =>
- entity.status === expectedEntityStatus(shipment) &&
+ isShippable(shipment, entity.status) &&
!serialNumbers.some((assigned) => {
if (!assigned.id) return false;
const resolved = resolveTrackedEntity(
@@ -1344,7 +1343,7 @@ function SerialForm({
: null;
const isSerialNumberValid =
// @ts-expect-error TS2339 - TODO: fix type
- resolvedSerial?.status === expectedEntityStatus(shipment);
+ isShippable(shipment, resolvedSerial?.status);
return (
<div
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
index 2f95d2b96e..f6cd9756c0 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
@@ -35,7 +35,10 @@ import { DateTime } from "~/components";
import { useCompanyToday, useSettings, useUser } from "~/hooks";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
-import { getShipmentTracking } from "../../inventory.utils";
+import {
+ getShipmentTracking,
+ isShippableEntityStatus
+} from "../../inventory.utils";
import type { Shipment, ShipmentLine } from "../../types";
type ExpiredEntityPolicy = "Warn" | "Block" | "BlockWithOverride";
@@ -60,13 +63,11 @@ const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {
const companyToday = useCompanyToday();
const [postingDate, setPostingDate] = useState(companyToday);
- // Return-to-customer shipments (source "Sales Return Order") ship returned
- // stock, which is deliberately On Hold until shipped back — mirror the
- // status lines.tracking required when the entity was assigned.
- const expectedEntityStatus =
- routeData?.shipment?.sourceDocument === "Sales Return Order"
- ? "On Hold"
- : "Available";
+ // Mirror the statuses lines.tracking accepted when the entity was assigned:
+ // On Hold on a return to a customer, Available or Rejected on a return to a
+ // supplier, Available otherwise.
+ const isShippable = (status: string | null | undefined) =>
+ isShippableEntityStatus(routeData?.shipment?.sourceDocument, status);
const navigation = useNavigation();
@@ -171,7 +172,7 @@ const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {
return attributes["Shipment Line"] === line.id;
});
- if (trackedEntity?.status !== expectedEntityStatus) {
+ if (!isShippable(trackedEntity?.status)) {
errors.push({
itemReadableId: getItemReadableId(items, line.itemId) ?? null,
shippedQuantity: line.shippedQuantity ?? 0,
@@ -209,10 +210,7 @@ const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {
const quantityAvailable = trackedEntities?.reduce((acc, tracking) => {
const trackingQuantity = Number(tracking.quantity);
- return (
- acc +
- (tracking.status === expectedEntityStatus ? trackingQuantity : 0)
- );
+ return acc + (isShippable(tracking.status) ? trackingQuantity : 0);
}, 0);
if (quantityAvailable !== line.shippedQuantity) {
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index 5a46f499bf..de80e1994c 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -10068,6 +10068,10 @@ export async function supplierReturnCarriedCosts(
.select(["documentId", "itemId", "quantity", "cost"])
.where("documentType", "=", "Purchase Return Shipment")
.where("documentId", "in", shipmentIds)
+ // What the shipment relieved. A shipment that ships units an inspection
+ // reject wrote off first puts them back (a positive row at the
+ // write-off's cost), which is not carried cost the return took out.
+ .where("quantity", "<", 0)
.where("companyId", "=", companyId)
.execute(),
trx
diff --git a/apps/erp/app/modules/purchasing/AGENTS.md b/apps/erp/app/modules/purchasing/AGENTS.md
index be5ff4e486..6dd37306b4 100644
--- a/apps/erp/app/modules/purchasing/AGENTS.md
+++ b/apps/erp/app/modules/purchasing/AGENTS.md
@@ -56,7 +56,7 @@ cd apps/erp && pnpm exec vitest run app/modules/purchasing
| `purchasingRfq` / `purchasingRfqLine` / `purchasingRfqSupplier` | RFQ header, lines, and invited suppliers |
| `terms` | Payment/delivery terms reference data |
| `purchaseReturnOrder` / `purchaseReturnOrderLine` / `purchaseReturnOrders` (view) | Supplier returns: authorize → ship (via shipments, source "Purchase Return Order") → credit. Statuses Draft → Confirmed → Partially Shipped → Shipped → Completed/Cancelled; `supplierReference` carries the supplier's own RMA number; line quantities/prices are ALWAYS inventory-UOM (converted once at authoring) |
-| `purchaseReturnOrderLineTrackedEntity` / `purchaseReturnOrderCreditLine` | Entities to send back (picked from Available stock from that supplier) — the `create` posting (`shipmentFromPurchaseReturnOrder`) stamps these onto the shipment's tracked entities (`attributes ->> Shipment`/`Shipment Line`) so the batch/serial flows through; `post-shipment` **splits** a batch when the returned quantity is less than the entity's (mirrors the Sales Order path, `buildBatchSplitRecords`). Per-line credit breakdown behind the AP `memo` (`memo.purchaseReturnOrderId`, reason account = GRNI). The memo is a **Debit** memo (`DR-` sequence): direction alone picks the control side, so Credit would INCREASE AP and re-debit GRNI — a vendor return must DR AP / CR GRNI |
+| `purchaseReturnOrderLineTrackedEntity` / `purchaseReturnOrderCreditLine` | Entities to send back (picked from that supplier's Available or Rejected stock — rejected units are what a return usually sends back) — the `create` posting (`shipmentFromPurchaseReturnOrder`) stamps these onto the shipment's tracked entities (`attributes ->> Shipment`/`Shipment Line`/`Shipment Line Index`, so each serial lands in its own box) so the batch/serial flows through; `post-shipment` **splits** a batch when the returned quantity is less than the entity's (mirrors the Sales Order path, `buildBatchSplitRecords`). Per-line credit breakdown behind the AP `memo` (`memo.purchaseReturnOrderId`, reason account = GRNI). The memo is a **Debit** memo (`DR-` sequence): direction alone picks the control side, so Credit would INCREASE AP and re-debit GRNI — a vendor return must DR AP / CR GRNI |
## Key Service Functions
@@ -77,7 +77,7 @@ cd apps/erp && pnpm exec vitest run app/modules/purchasing
- `getSupplierQuotesForComparison` — side-by-side quote comparison
- `getDefaultAttachmentsForPO` — default document attachments for PO creation
- `getPurchaseReturnOrders` / `insertPurchaseReturnOrder` / `upsertPurchaseReturnOrderLine` — supplier-return CRUD; `confirmPurchaseReturnOrder` (Kysely row-locked caps: receiptLine received → PO line received×factor → invoice line×factor), `cancelPurchaseReturnOrder` / `shortClosePurchaseReturnOrderLine` (the header status follows the lines through `getPurchaseReturnOrderStatus`, `@carbon/utils`; there is no complete function)
-- `getReturnableLinesForSupplier` (posted receipt lines minus already-authorized) — thin wrapper over the `get_returnable_receipt_lines` RPC, which does the `received − authorized > 0` filter, the search (receipt #, PO #, item readable id, item name), recency ordering, and limit/offset paging in SQL and returns `totalCount` on each row. Scales to thousands of receipt lines; the "Add lines from receipt" modal (`ReturnableReceiptLinesModal`) shows the 5 most recent and searches for the rest. / `getReturnableEntitiesForSupplier` (Available entities whose `attributes ->> Receipt` resolves to a posted receipt from the supplier) / `getReturnableEntitiesForReceiptLine` (Available entities from ONE receipt line, via `attributes ->> Receipt Line`) — the `$id.new` action uses it to auto-select the single entity when a tracked line is added from a specific receipt, persisting it at creation so it flows onto the shipment
+- `getReturnableLinesForSupplier` (posted receipt lines minus already-authorized) — thin wrapper over the `get_returnable_receipt_lines` RPC, which does the `received − authorized > 0` filter, the search (receipt #, PO #, item readable id, item name), recency ordering, and limit/offset paging in SQL and returns `totalCount` on each row. Scales to thousands of receipt lines; the "Add lines from receipt" modal (`ReturnableReceiptLinesModal`) shows the 5 most recent and searches for the rest. / `getReturnableEntitiesForSupplier` (Available or Rejected entities whose `attributes ->> Receipt` resolves to a posted receipt from the supplier) / `getReturnableEntitiesForReceiptLine` (Available or Rejected entities from ONE receipt line, via `attributes ->> Receipt Line`) — the `$id.new` action uses it to auto-select the single entity when a tracked line is added from a specific receipt, persisting it at creation so it flows onto the shipment
- `createPurchaseReturnOrderCredit` (Kysely, shipped-minus-credited cap) / `getCreditableQuantitiesForPurchaseReturn` / `createReplacementPurchaseOrder` (linked-PO-line / supplierPart pricing)
- `createSupplierInteractionDocumentUploadUrl` / `createSupplierInteractionLineDocumentUploadUrl` — MCP file upload (step 1): presigned URLs for supplier-interaction (`supplier-interaction/{interactionId}`) and interaction-line documents; pair with `documents_insertUploadedDocument`. See `.claude/rules/mcp-tools-reference.md` → "File uploads"
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 15adba42f7..627dace4a5 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -112,6 +112,7 @@ import {
createDocumentUploadUrl,
upsertDocument
} from "~/modules/documents/documents.service";
+import { shippableEntityStatuses } from "~/modules/inventory/inventory.utils";
import { getEmployeeJob } from "~/modules/people/people.service";
import {
getCompany,
@@ -4469,11 +4470,18 @@ export async function getReturnableLinesForSupplier(
});
}
+/** The statuses a supplier return ships (`shippableEntityStatuses`). */
+const RETURNABLE_ENTITY_STATUSES = shippableEntityStatuses(
+ "Purchase Return Order"
+);
+
/**
* Entity picker source for supplier return lines: serials/batches on hand
- * that were received from this supplier. Provenance is the Receipt attribute
- * (written by the receipt tracking route) resolved to the receipt's supplier
- * — no code writes a Supplier attribute onto tracked entities.
+ * that were received from this supplier, Available or Rejected (by an
+ * inspection or an issue — the units most worth sending back). Provenance is
+ * the Receipt attribute (written by the receipt tracking route) resolved to
+ * the receipt's supplier — no code writes a Supplier attribute onto tracked
+ * entities.
*/
export async function getReturnableEntitiesForSupplier(
client: SupabaseClient<Database>,
@@ -4499,12 +4507,12 @@ export async function getReturnableEntitiesForSupplier(
.select("id, readableId, quantity, status, attributes")
.eq("companyId", companyId)
.eq("itemId", itemId)
- .eq("status", "Available")
+ .in("status", RETURNABLE_ENTITY_STATUSES)
.in("attributes ->> Receipt", receiptIds);
}
/**
- * The Available tracked entities that came in on ONE receipt line, for the item.
+ * The Available or Rejected tracked entities that came in on ONE receipt line, for the item.
* Used to pre-select the batch/serial when a return line is added from a specific
* receipt — provenance is the `Receipt Line` attribute stamped at receipt.
*/
@@ -4519,7 +4527,7 @@ export async function getReturnableEntitiesForReceiptLine(
.select("id, readableId, quantity, status")
.eq("companyId", companyId)
.eq("itemId", itemId)
- .eq("status", "Available")
+ .in("status", RETURNABLE_ENTITY_STATUSES)
.eq("attributes ->> Receipt Line", receiptLineId);
}
diff --git a/apps/erp/app/modules/quality/AGENTS.md b/apps/erp/app/modules/quality/AGENTS.md
index cb600efe76..5b37cd223f 100644
--- a/apps/erp/app/modules/quality/AGENTS.md
+++ b/apps/erp/app/modules/quality/AGENTS.md
@@ -63,14 +63,14 @@ Each operation is one `defineServiceFn` const in `quality.server.ts`. A route ca
| Operation | Route | What it holds |
|---|---|---|
-| `createIssue` | `x+/issue+/new.tsx` | Every referenced record must be the company's; tracked entities from the query string are linked; a job-operation issue links the operation's lot to its disposition row; tasks are created (a failure deletes the issue); integrations are told; `changeOrderId` links the issue onto the change notice (a failed link is `warning`) |
+| `createIssue` | `x+/issue+/new.tsx` | Every referenced record (a `supplierId` included, written as the issue's `nonConformanceSupplier`) must be the company's; tracked entities from the query string are linked; a job-operation issue links the operation's lot to its disposition row; tasks are created (a failure deletes the issue); integrations are told; `changeOrderId` links the issue onto the change notice (a failed link is `warning`) |
| `updateIssueField` | `x+/issue+/update.tsx` | Refused on a closed issue; `requiredActionIds` / `approvalRequirements` reconcile the tasks |
| `setIssueStatus` / `completeIssue` | `$id.status.tsx`, `$id.close.tsx` | Start and reopen only (reopen refused once the dispositions posted inventory); the issue must be the company's, and the write is scoped to it; close is `closeIssue`, which posts the dispositions |
| `draftIssueSupplierReturn` | `$id.supplier-return.tsx` | `purchasing` create; idempotent per covered quantity, deletes the draft on a part-way failure |
| `createIssueAssociation` | `$id.association.new.tsx` | Refused on a closed issue or one of another company; an item, customer, supplier or tracked entity must be the company's; an inspection links its whole lot under the issue lock |
| `updateIssueItemField` | `item+/update.tsx` | Disposition from the picker's subset; quantity is a compare-and-set |
| `setIssueTaskStatus` / `setIssueTaskSupplier`, `setIssueActionDueDate` / `reorderIssueActionTasks` | `task.$id.status.tsx`, `task.supplier.tsx`, `action.$id.due-date.tsx`, `action-tasks.order.tsx` | The supplier must be the company's; a reorder takes the tasks of one issue and writes them with `updateSortOrder` |
-| `rejectInspection` | `x+/inspection+/$id.reject.tsx` | Receipt lots only; the non-tracked write-off posts before any issue opens; the issue's disposition row takes the lot as Scrap |
+| `rejectInspection` | `x+/inspection+/$id.reject.tsx` | Receipt lots only; the non-tracked write-off posts before any issue opens; the issue's disposition row takes the lot as Scrap; the lot's `supplierId` becomes the issue's supplier |
| `saveInspectionDocument` / `setInspectionDocumentDrawingNumber` | `x+/inspection-document+/$id.save.tsx`, `$id.update-name.tsx` | Legacy balloons need anchors; `pdfUrl` must be a safe key in the company's folder (its `/file/preview/private/` form or the bare key); the default sampling rule is saved before the atomic RPC |
| `updateQualityDocumentField` / `decideQualityDocumentApproval` / `seedQualityDocuments` | `x+/quality-document+/update.tsx`, `$id.tsx`, `api+/quality.documents.seed.ts` | Activating opens approval requests when a rule applies; Archived / Draft withdraw a pending one |
| `createRisk` / `updateRisk` | `x+/quality+/risks.new.tsx`, `risks.$id.tsx` | The assignee is notified; create is gated on company membership (the table's RLS limits it to employees) and is not published |
@@ -85,7 +85,7 @@ The building blocks they call (`updateIssueStatus`, `updateIssueTaskStatus`, `up
- `getIssueAssociations` / `getIssueItems` / `getIssueReviewers` — NCR details and associations
- `getIssueWorkflow` / `getIssueActionTasks` / `getIssueApprovalTasks` — workflow state
- `updateIssueStatus` / `updateIssueTaskStatus` — the bare status writes under `setIssueStatus` / `setIssueTaskStatus`
-- `closeIssue` (`quality.service.ts`) — blocked while a linked supplier return is open; the 'Return to Supplier' write-off is reduced by shipped-via-return coverage, and return-shipped entities stay Consumed (not flipped Rejected). `draftIssueSupplierReturn` drafts the linked `purchaseReturnOrder` (idempotent, supplier auto-resolution)
+- `closeIssue` (`quality.service.ts`) — blocked while a linked supplier return is open; the 'Return to Supplier' write-off is reduced by shipped-via-return coverage (an inspection-rejected non-tracked lot was written off at the reject; its return shipment puts the units back before shipping them, so close posts nothing for it), and return-shipped entities stay Consumed (not flipped Rejected). `draftIssueSupplierReturn` drafts the linked `purchaseReturnOrder` (idempotent, supplier auto-resolution)
- `getInspectionDocument` / `getBalloons` / `getInspectionFeatures` / `getInspectionPlan` — drawing-inspection reads (plan authoring: `getInspectionDocuments`, `upsertInspectionDocument`, `deleteInspectionDocument`, `saveInspectionDocumentAtomic`; editor UI in `ui/InspectionDocument/`, list at `/x/quality/inspection-plans`; the editor autosaves — merge logic in `ui/InspectionDocument/autosave.ts`)
- `getInspection` / `getInspections` (status + source filters) / `getInspectionTrackedEntities` — inspections
- `getInspectionSamplingPlans` / `getInspectionMeasurements` — per-inspection feature plans and grid readings
diff --git a/apps/erp/app/modules/quality/quality.models.ts b/apps/erp/app/modules/quality/quality.models.ts
index 5f182be7b9..6880fb5b74 100644
--- a/apps/erp/app/modules/quality/quality.models.ts
+++ b/apps/erp/app/modules/quality/quality.models.ts
@@ -219,6 +219,7 @@ export const issueValidator = z.object({
items: z.array(z.string()).optional(),
jobOperationId: z.string().optional(),
customerId: z.string().optional(),
+ supplierId: z.string().optional(),
salesOrderLineId: z.string().optional(),
operationSupplierProcessId: z.string().optional()
});
diff --git a/apps/erp/app/modules/quality/quality.server.ts b/apps/erp/app/modules/quality/quality.server.ts
index 0069628e5e..43717ee5ad 100644
--- a/apps/erp/app/modules/quality/quality.server.ts
+++ b/apps/erp/app/modules/quality/quality.server.ts
@@ -78,7 +78,7 @@ const customFieldValues = z.record(
*
* @remarks
* Every record the issue names (location, type, workflow, required actions,
- * items, customer, `trackedEntityIds`) must be the company's, or nothing is
+ * items, customer, supplier, `trackedEntityIds`) must be the company's, or nothing is
* created. The issue is inserted, the tracked entities are linked to it, and
* an issue filed against a job operation links the lot that operation's make
* method produced onto the item's disposition row. Its action and approval
@@ -122,6 +122,7 @@ export const createIssue = defineServiceFn({
],
["item", [...new Set(input.items ?? [])]],
["customer", input.customerId ? [input.customerId] : []],
+ ["supplier", input.supplierId ? [input.supplierId] : []],
["trackedEntity", trackedEntityIds]
];
const owned = await Promise.all(
@@ -161,6 +162,7 @@ export const createIssue = defineServiceFn({
items: input.items,
jobOperationId: input.jobOperationId,
customerId: input.customerId,
+ supplierId: input.supplierId,
salesOrderLineId: input.salesOrderLineId,
operationSupplierProcessId: input.operationSupplierProcessId,
companyId,
@@ -1290,8 +1292,13 @@ export const draftIssueSupplierReturn = defineServiceFn({
* first issue type, at the caller's default location: its item's disposition
* row takes the lot quantity and Scrap, the lot's entities and receipt line
* are linked to it, and its tasks are created. The failed features, with
- * their measured values against spec, go in its description. A failure after
- * the issue was inserted deletes it again; the lot stays rejected.
+ * their measured values against spec, and the `reason` go in its description.
+ * A failure after the issue was inserted deletes it again; the lot stays
+ * rejected.
+ *
+ * @param reason - Why the lot is rejected. Required when no characteristic
+ * reached its rejection number and no sample failed (a suspected counterfeit,
+ * the wrong part, transit damage); stored as the lot's notes.
*
* @mcp
*/
@@ -1299,11 +1306,12 @@ export const rejectInspection = defineServiceFn({
input: z.object({
id: z.string(),
nonConformanceTypeId: z.string().nullish(),
- createNcr: z.boolean().default(true)
+ createNcr: z.boolean().default(true),
+ reason: z.string().trim().max(2000).nullish()
}),
permission: { update: "quality" },
- async run(ctx, { id, nonConformanceTypeId, createNcr }) {
+ async run(ctx, { id, nonConformanceTypeId, createNcr, reason }) {
const client = ctx.asCaller.supabase;
const serviceRole = ctx.asSystem.supabase;
const companyId = ctx.company.id;
@@ -1312,6 +1320,7 @@ export const rejectInspection = defineServiceFn({
const rejected = await engine.dispositionInspection(ctx.asSystem.pg, {
id,
decision: "Reject",
+ reason: reason || undefined,
companyId,
dispositionedBy: userId,
// The ERP reject does receipt-specific NCR / write-off work.
@@ -1400,7 +1409,7 @@ export const rejectInspection = defineServiceFn({
const created = await service.insertIssue(serviceRole, {
name: issueTitle,
- description: `Auto-created from inbound inspection ${inspectionReadableId}. Lot size ${insp.lotSize}, sample ${insp.sampleSize}, Ac ${insp.acceptanceNumber} / Re ${insp.rejectionNumber}. Supplier: ${supplierName}.${failedFeaturesBlock}`,
+ description: `Auto-created from inbound inspection ${inspectionReadableId}. Lot size ${insp.lotSize}, sample ${insp.sampleSize}, Ac ${insp.acceptanceNumber} / Re ${insp.rejectionNumber}. Supplier: ${supplierName}.${reason ? `\n\nReason: ${reason}` : ""}${failedFeaturesBlock}`,
priority: "Medium",
source: "Internal",
locationId,
@@ -1410,6 +1419,9 @@ export const rejectInspection = defineServiceFn({
.toString(),
quantity: Number(insp.lotSize ?? 0),
items: insp.itemId ? [insp.itemId] : [],
+ // The lot's supplier, stamped from the PO at receipt: it drives the
+ // SCAR report, the action-task supplier picker and the explorer.
+ supplierId: insp.supplierId ?? undefined,
companyId,
createdBy: userId
});
diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.ts
index 92f7df9534..cc2f330889 100644
--- a/apps/erp/app/modules/quality/quality.service.ts
+++ b/apps/erp/app/modules/quality/quality.service.ts
@@ -1646,6 +1646,7 @@ export async function insertIssue(
items?: string[];
jobOperationId?: string;
customerId?: string;
+ supplierId?: string;
salesOrderLineId?: string;
operationSupplierProcessId?: string;
customFields?: Json;
@@ -1679,6 +1680,7 @@ export async function insertIssue(
items,
jobOperationId,
customerId,
+ supplierId,
salesOrderLineId,
operationSupplierProcessId,
...data
@@ -1789,6 +1791,24 @@ export async function insertIssue(
}
}
+ // The outside-processing operation's supplier (below) is skipped when it is
+ // this one, so the issue never lists a supplier twice.
+ if (supplierId) {
+ const supplierInsert = await client.from("nonConformanceSupplier").insert([
+ {
+ companyId: input.companyId,
+ createdBy: input.createdBy,
+ supplierId,
+ nonConformanceId: ncrId
+ }
+ ]);
+ if (supplierInsert.error) {
+ logger.error("Failed to insert non-conformance supplier", {
+ error: supplierInsert.error
+ });
+ }
+ }
+
if (salesOrderLineId) {
const salesOrderLine = await client
.from("salesOrderLine")
@@ -1825,7 +1845,10 @@ export async function insertIssue(
.eq("companyId", input.companyId)
.single();
- if (operationSupplierProcess.data) {
+ if (
+ operationSupplierProcess.data &&
+ operationSupplierProcess.data.supplierId !== supplierId
+ ) {
const nonConformanceSupplierInsert = await client
.from("nonConformanceSupplier")
.insert([
@@ -2196,13 +2219,39 @@ export async function getReceiptInspections(
) {
return client
.from("inspection")
- .select("id, inspectionId, itemId, itemReadableId, status")
+ .select(
+ "id, inspectionId, itemId, itemReadableId, sourceDocumentLineId, status"
+ )
.eq("sourceDocument", "Receipt")
.eq("sourceDocumentId", receiptId)
.eq("companyId", companyId)
.order("createdAt", { ascending: true });
}
+/**
+ * The items, of those given, that are inspected at receipt: each has a
+ * Receipt-usage inspection document assigned, which is what makes posting a
+ * purchase receipt open an inspection lot for the line.
+ */
+export async function getReceiptInspectedItemIds(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ itemIds: string[]
+) {
+ if (itemIds.length === 0) return { data: [] as string[], error: null };
+ const assignments = await client
+ .from("itemInspectionDocumentAssignment")
+ .select("itemId")
+ .eq("usage", "Receipt")
+ .eq("companyId", companyId)
+ .in("itemId", itemIds);
+ if (assignments.error) return { data: null, error: assignments.error };
+ return {
+ data: [...new Set(assignments.data.map((a) => a.itemId))],
+ error: null
+ };
+}
+
// Receipt-sourced lots only: the received tracked entities are linked to the
// receipt line through their attributes.
export async function getInspectionTrackedEntities(
@@ -2217,6 +2266,20 @@ export async function getInspectionTrackedEntities(
.eq("companyId", companyId);
}
+/** The issues an inspection is linked to (a rejected lot's NCR, or a manual link). */
+export async function getInspectionIssues(
+ client: SupabaseClient<Database>,
+ inspectionId: string,
+ companyId: string
+) {
+ return client
+ .from("nonConformanceInspection")
+ .select("id, nonConformance(id, nonConformanceId, name, status)")
+ .eq("inspectionId", inspectionId)
+ .eq("companyId", companyId)
+ .order("createdAt", { ascending: true });
+}
+
export async function getInspectionSamplingPlans(
client: SupabaseClient<Database>,
inspectionId: string,
diff --git a/apps/erp/app/modules/quality/types.ts b/apps/erp/app/modules/quality/types.ts
index 87fb1a8a23..edbbe849a7 100644
--- a/apps/erp/app/modules/quality/types.ts
+++ b/apps/erp/app/modules/quality/types.ts
@@ -12,6 +12,7 @@ import type {
getInspection,
getInspectionDocuments,
getInspectionGauges,
+ getInspectionIssues,
getInspectionMeasurements,
getInspectionSamplingPlans,
getInspections,
@@ -189,6 +190,12 @@ export type ItemInspectionDocumentAssignment =
export type InspectionMeasurementRow =
Database["public"]["Tables"]["inspectionMeasurement"]["Row"];
+export type InspectionIssue = NonNullable<
+ NonNullable<
+ Awaited<ReturnType<typeof getInspectionIssues>>["data"]
+ >[number]["nonConformance"]
+>;
+
export type InspectionSamplingPlan = NonNullable<
Awaited<ReturnType<typeof getInspectionSamplingPlans>>["data"]
>[number];
diff --git a/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx b/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx
index 73e05b9a35..d75b40ef16 100644
--- a/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx
+++ b/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx
@@ -10,6 +10,10 @@ import {
Badge,
Button,
ClientOnly,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
HStack,
IconButton,
Modal,
@@ -45,9 +49,10 @@ import {
LuFileText,
LuScan,
LuShieldAlert,
+ LuShieldX,
LuTriangleAlert
} from "react-icons/lu";
-import { useFetcher } from "react-router";
+import { Link, useFetcher } from "react-router";
import {
RecordAction,
RecordHero,
@@ -57,6 +62,7 @@ import { Confirm } from "~/components/Modals";
import { usePermissions } from "~/hooks";
import type {
InspectionGauge,
+ InspectionIssue,
InspectionMeasurement,
InspectionRow,
InspectionSample,
@@ -126,6 +132,8 @@ export type InspectionViewProps = {
pdfUrl: string | null;
lotEntities: InspectionTrackedEntity[];
issueTypes: IssueTypeListItem[];
+ /** The issues linked to this lot (a rejected lot's NCR, or a manual link). */
+ issues: InspectionIssue[];
currentUserId: string;
enforceFourEyes: boolean;
};
@@ -153,6 +161,7 @@ const InspectionView = ({
pdfUrl,
lotEntities,
issueTypes,
+ issues,
currentUserId,
enforceFourEyes
}: InspectionViewProps) => {
@@ -391,8 +400,10 @@ const InspectionView = ({
// Gating. Feature-driven lots gate per feature (mirrors the
// server-side disposition guards); lots without features gate at the lot
// level on the "Overall result" pass/fail counts.
+ // A lot can be rejected for any reason (a suspected counterfeit, the wrong
+ // part); without a statistical failure the inspector must give one.
let canAccept: boolean;
- let canReject: boolean;
+ let failedStatistically: boolean;
if (hasFeatures) {
const allFeaturesSatisfied = liveFeatures.every((feature) => {
const counts = featureCounts.get(feature.inspectionFeatureId) ?? {
@@ -409,17 +420,16 @@ const InspectionView = ({
return counts != null && counts.failed >= feature.rejectionNumber;
});
canAccept = isReceiptSource && !lotClosed && allFeaturesSatisfied;
- canReject =
- isReceiptSource && !lotClosed && (anyFeatureRejectable || fails > 0);
+ failedStatistically = anyFeatureRejectable || fails > 0;
} else {
canAccept =
isReceiptSource &&
!lotClosed &&
inspected >= inspection.sampleSize &&
fails <= inspection.acceptanceNumber;
- canReject =
- isReceiptSource && !lotClosed && fails > inspection.acceptanceNumber;
+ failedStatistically = fails > inspection.acceptanceNumber;
}
+ const canReject = isReceiptSource && !lotClosed;
const failedFeatureSummary = useMemo<FailedFeatureSummary[]>(() => {
if (!hasFeatures) return [];
@@ -452,7 +462,7 @@ const InspectionView = ({
.map((s) => s.trackedEntityId)
.filter(Boolean) as string[];
- const newIssueHref = `/x/issue/new?itemId=${encodeURIComponent(inspection.itemId)}&trackedEntityIds=${encodeURIComponent(failedTrackedEntityIds.join(","))}&sourceInspectionId=${encodeURIComponent(inspection.id)}`;
+ const newIssueHref = `/x/issue/new?itemId=${encodeURIComponent(inspection.itemId)}&trackedEntityIds=${encodeURIComponent(failedTrackedEntityIds.join(","))}${inspection.supplierId ? `&supplierId=${encodeURIComponent(inspection.supplierId)}` : ""}`;
const drawingBalloons = useMemo<DrawingBalloon[]>(() => {
const labelByFeatureId = new Map(
@@ -528,6 +538,35 @@ const InspectionView = ({
<p className="truncate text-xs text-muted-foreground">{metaLine}</p>
</div>
<HStack spacing={2} className="flex-shrink-0 flex-wrap justify-end">
+ {issues.length === 1 && (
+ <RecordAction slot="overflow">
+ <Button variant="secondary" leftIcon={<LuShieldX />} asChild>
+ <Link to={path.to.issue(issues[0].id)}>
+ {issues[0].nonConformanceId}
+ </Link>
+ </Button>
+ </RecordAction>
+ )}
+ {issues.length > 1 && (
+ <RecordAction slot="overflow">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary" leftIcon={<LuShieldX />}>
+ <Trans>Issues</Trans>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ {issues.map((issue) => (
+ <DropdownMenuItem key={issue.id} asChild>
+ <Link to={path.to.issue(issue.id)}>
+ {issue.nonConformanceId}
+ </Link>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </RecordAction>
+ )}
<RecordAction slot="overflow">
<Button
variant="secondary"
@@ -787,10 +826,15 @@ const InspectionView = ({
<RejectLotModal
action={path.to.inspectionReject(inspection.id)}
issueTypes={issueTypes}
+ requiresReason={!failedStatistically}
summary={
- isSerial
- ? t`Statistical acceptance failed, so the entire lot is considered non-conforming (ISO 9001:2015 §8.7). All ${lotEntities.length} entities — ${passes} sampled pass(es), ${fails} failure(s), and ${Math.max(0, lotEntities.length - inspected)} un-inspected — will be marked Rejected.`
- : t`Statistical acceptance failed, so the entire lot of ${inspection.lotSize} is considered non-conforming (ISO 9001:2015 §8.7) — ${passes} sampled pass(es) and ${fails} failure(s).`
+ failedStatistically
+ ? isSerial
+ ? t`Statistical acceptance failed, so the entire lot is considered non-conforming (ISO 9001:2015 §8.7). All ${lotEntities.length} entities — ${passes} sampled pass(es), ${fails} failure(s), and ${Math.max(0, lotEntities.length - inspected)} un-inspected — will be marked Rejected.`
+ : t`Statistical acceptance failed, so the entire lot of ${inspection.lotSize} is considered non-conforming (ISO 9001:2015 §8.7) — ${passes} sampled pass(es) and ${fails} failure(s).`
+ : isSerial
+ ? t`No characteristic has failed, so say why the lot is rejected. All ${lotEntities.length} entities will be marked Rejected.`
+ : t`No characteristic has failed, so say why the lot is rejected. The entire lot of ${inspection.lotSize} will be rejected.`
}
failedFeatureSummary={failedFeatureSummary}
onCancel={rejectConfirmDisclosure.onClose}
diff --git a/apps/erp/app/modules/quality/ui/Inspections/RejectLotModal.tsx b/apps/erp/app/modules/quality/ui/Inspections/RejectLotModal.tsx
index 25297d2f97..6138c77e68 100644
--- a/apps/erp/app/modules/quality/ui/Inspections/RejectLotModal.tsx
+++ b/apps/erp/app/modules/quality/ui/Inspections/RejectLotModal.tsx
@@ -22,6 +22,7 @@ import {
SelectItem,
SelectTrigger,
SelectValue,
+ Textarea,
VStack
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
@@ -42,6 +43,9 @@ type RejectLotModalProps = {
// Document-driven lots: the features that failed, previewed here and
// written into the NCR description by the reject action.
failedFeatureSummary?: FailedFeatureSummary[];
+ // Nothing failed statistically: the lot is rejected for another reason (a
+ // suspected counterfeit, the wrong part), which the inspector must give.
+ requiresReason?: boolean;
onCancel: () => void;
onSubmit: () => void;
};
@@ -51,6 +55,7 @@ const RejectLotModal = ({
issueTypes,
summary,
failedFeatureSummary,
+ requiresReason = false,
onCancel,
onSubmit
}: RejectLotModalProps) => {
@@ -65,6 +70,7 @@ const RejectLotModal = ({
});
const submitted = useRef(false);
const [createNcr, setCreateNcr] = useState(true);
+ const [reason, setReason] = useState("");
const [issueTypeId, setIssueTypeId] = useState<string>(
issueTypes[0]?.id ?? ""
);
@@ -109,6 +115,23 @@ const RejectLotModal = ({
</ul>
</div>
)}
+ <div className="flex flex-col gap-2 w-full">
+ <Label htmlFor="rejectReason">
+ {requiresReason ? (
+ <Trans>Reason</Trans>
+ ) : (
+ <Trans>Reason (optional)</Trans>
+ )}
+ </Label>
+ <Textarea
+ id="rejectReason"
+ value={reason}
+ // rejectInspection takes at most 2,000 characters.
+ maxLength={2000}
+ onChange={(event) => setReason(event.target.value)}
+ placeholder={t`e.g. Suspected counterfeit, wrong part, damaged in transit`}
+ />
+ </div>
<label className="flex items-center gap-2 w-full cursor-pointer">
<Checkbox
isChecked={createNcr}
@@ -172,12 +195,14 @@ const RejectLotModal = ({
name="nonConformanceTypeId"
value={createNcr ? issueTypeId : ""}
/>
+ <input type="hidden" name="reason" value={reason.trim()} />
<Button
variant="destructive"
type="submit"
isLoading={fetcher.state !== "idle"}
isDisabled={
fetcher.state !== "idle" ||
+ (requiresReason && !reason.trim()) ||
(createNcr && hasIssueTypes && !issueTypeId)
}
>
diff --git a/apps/erp/app/modules/quality/ui/Issue/ReviewersList.tsx b/apps/erp/app/modules/quality/ui/Issue/ReviewersList.tsx
index 19c4ecf0ac..5449eeed68 100644
--- a/apps/erp/app/modules/quality/ui/Issue/ReviewersList.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/ReviewersList.tsx
@@ -42,6 +42,9 @@ export function ReviewersList({
reviewers: IssueReviewer[];
isDisabled: boolean;
}) {
+ const { id } = useParams();
+ if (!id) throw new Error("id not found");
+
const disclosure = useDisclosure();
const { isPhone } = useViewport();
@@ -95,6 +98,7 @@ export function ReviewersList({
<Button
variant="secondary"
leftIcon={<LuCirclePlus />}
+ isDisabled={isDisabled}
onClick={disclosure.onOpen}
>
<Trans>Add</Trans>
@@ -126,6 +130,7 @@ export function ReviewersList({
<ModalContent>
<ValidatedForm
method="post"
+ action={path.to.issueReview(id)}
validator={nonConformanceReviewerValidator}
fetcher={fetcher}
onSubmit={() => {
@@ -166,7 +171,11 @@ export function ReviewersList({
<Trans>Cancel</Trans>
</Button>
) : (
- <Button leftIcon={<LuCirclePlus />} onClick={disclosure.onOpen}>
+ <Button
+ leftIcon={<LuCirclePlus />}
+ isDisabled={isDisabled}
+ onClick={disclosure.onOpen}
+ >
<Trans>Add Requirement</Trans>
</Button>
)}
diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.ts
index 27db7d5d8b..e2ba86fa44 100644
--- a/apps/erp/app/modules/shared/shared.service.ts
+++ b/apps/erp/app/modules/shared/shared.service.ts
@@ -13218,15 +13218,18 @@ export async function createDocument(
// Stamp each return line's picked entities onto its shipment line, so
// the batch/serial flows through to posting. post-shipment splits a
// batch when the shipped quantity is less than the entity's quantity.
+ // The index puts each serial in its own box on the shipment page,
+ // which shows a serial only at the index it was assigned to.
for (const shipmentLine of insertedLines) {
const entities = shipmentLine.lineId
? entitiesByReturnLine.get(shipmentLine.lineId)
: undefined;
- for (const entity of entities ?? []) {
+ for (const [index, entity] of (entities ?? []).entries()) {
const attrs = {
...(entity.attributes ?? {}),
Shipment: id,
- "Shipment Line": shipmentLine.id
+ "Shipment Line": shipmentLine.id,
+ "Shipment Line Index": index
};
await trx
.updateTable("trackedEntity")
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 93646700c1..5cdaa1e35f 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1056,7 +1056,7 @@
{"name":"quality_completeIssue","classification":"WRITE","schema":"3797626bd17e","response":"3797626bd17e","permission":"quality:update","paginates":false},
{"name":"quality_createGaugeCalibrationRecord","classification":"WRITE","schema":"9fd203fd91da","response":"3797626bd17e","permission":"quality:create","paginates":false},
{"name":"quality_createGaugeType","classification":"WRITE","schema":"f51d093840b8","response":"8394fbabd845","permission":"quality:create","paginates":false},
- {"name":"quality_createIssue","classification":"WRITE","schema":"98e94090cc53","response":"67030fdab724","permission":"quality:create","paginates":false},
+ {"name":"quality_createIssue","classification":"WRITE","schema":"8f4e29a0f4cf","response":"67030fdab724","permission":"quality:create","paginates":false},
{"name":"quality_createIssueAssociation","classification":"WRITE","schema":"6abd32611fef","response":"f16bdda80515","permission":"quality:update","paginates":false},
{"name":"quality_createIssueType","classification":"WRITE","schema":"f51d093840b8","response":"8394fbabd845","permission":"quality:create","paginates":false},
{"name":"quality_createIssueWorkflow","classification":"WRITE","schema":"2ee341acc3e0","response":"3797626bd17e","permission":"quality:create","paginates":false},
@@ -1119,7 +1119,7 @@
{"name":"quality_getQualityDocuments","classification":"READ","schema":"cd40ae40fad5","response":"4afca05d1d27","permission":"quality:view","paginates":true},
{"name":"quality_getQualityDocumentVersions","classification":"READ","schema":"b6064496c216","response":"81dd83c56231","permission":"quality:view","paginates":false},
{"name":"quality_getQualityFiles","classification":"READ","schema":"7f8214d1083f","response":"6351756c9816","permission":"quality:view","paginates":false},
- {"name":"quality_getReceiptInspections","classification":"READ","schema":"85cf4fd2917f","response":"83d5d10abb6a","permission":"quality:view","paginates":false},
+ {"name":"quality_getReceiptInspections","classification":"READ","schema":"85cf4fd2917f","response":"06f8ced90cfa","permission":"quality:view","paginates":false},
{"name":"quality_getRequiredAction","classification":"READ","schema":"d65e071deff9","response":"58c7a89fdc1f","permission":"quality:view","paginates":false},
{"name":"quality_getRequiredActions","classification":"READ","schema":"cd40ae40fad5","response":"bb4170f94792","permission":"quality:view","paginates":true},
{"name":"quality_getRequiredActionsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"quality:view","paginates":false},
@@ -1128,7 +1128,7 @@
{"name":"quality_insertGauge","classification":"WRITE","schema":"8d2ada8f5f52","response":"3269d4609ad2","permission":"quality:create","paginates":false},
{"name":"quality_insertIssue","classification":"WRITE","schema":"ea632d40582e","response":"bf12cbd0f560","permission":"quality:create","paginates":false},
{"name":"quality_insertIssueReviewer","classification":"WRITE","schema":"83d8aaae61eb","response":"bcde375ebd4c","permission":"quality:create","paginates":false},
- {"name":"quality_rejectInspection","classification":"WRITE","schema":"d7fc4d660b91","response":"c1beaadbde90","permission":"quality:update","paginates":false},
+ {"name":"quality_rejectInspection","classification":"WRITE","schema":"9cd95b44e07a","response":"c1beaadbde90","permission":"quality:update","paginates":false},
{"name":"quality_reorderIssueActionTasks","classification":"WRITE","schema":"e27ca9c14dfd","response":"0eb0c2be01ed","permission":"quality:update","paginates":false},
{"name":"quality_saveInspectionDocument","classification":"WRITE","schema":"ce666421c179","response":"f67a43378af0","permission":"quality:update","paginates":false},
{"name":"quality_saveInspectionDocumentAtomic","classification":"WRITE","schema":"7a3138ccf220","response":"none","permission":"quality:update","paginates":false},
diff --git a/apps/erp/app/routes/x+/inspection+/$id.reject.tsx b/apps/erp/app/routes/x+/inspection+/$id.reject.tsx
index 21194b42ad..4945bfb3b8 100644
--- a/apps/erp/app/routes/x+/inspection+/$id.reject.tsx
+++ b/apps/erp/app/routes/x+/inspection+/$id.reject.tsx
@@ -12,7 +12,8 @@ import { path } from "~/utils/path";
// Opening an issue is optional: the inspector may reject without one.
const reject = z.object({
nonConformanceTypeId: zfd.text(z.string().optional()),
- createNcr: zfd.text(z.string().optional())
+ createNcr: zfd.text(z.string().optional()),
+ reason: zfd.text(z.string().optional())
});
export async function action(args: ActionFunctionArgs) {
@@ -23,7 +24,8 @@ export async function action(args: ActionFunctionArgs) {
const result = await api.quality.rejectInspection({
id,
nonConformanceTypeId: input.data.nonConformanceTypeId,
- createNcr: input.data.createNcr !== "false"
+ createNcr: input.data.createNcr !== "false",
+ reason: input.data.reason
});
if (result.error || !result.data.issueId) {
return respond(args.request, result).redirect(path.to.inspection(id), {
diff --git a/apps/erp/app/routes/x+/inspection+/$id.tsx b/apps/erp/app/routes/x+/inspection+/$id.tsx
index 827bb49262..76a8e4d59e 100644
--- a/apps/erp/app/routes/x+/inspection+/$id.tsx
+++ b/apps/erp/app/routes/x+/inspection+/$id.tsx
@@ -16,6 +16,7 @@ import {
getInspection,
getInspectionDocument,
getInspectionGauges,
+ getInspectionIssues,
getInspectionMeasurements,
getInspectionSamplingPlans,
getInspectionTrackedEntities,
@@ -25,6 +26,7 @@ import {
} from "~/modules/quality/quality.service";
import type {
InspectionGauge,
+ InspectionIssue,
InspectionMeasurement,
InspectionRow,
InspectionSample,
@@ -102,7 +104,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
lotEntities,
document,
balloons,
- receipt
+ receipt,
+ issues
] = await Promise.all([
getInspectionSamplingPlans(client, id, companyId),
getInspectionMeasurements(client, id, companyId),
@@ -132,7 +135,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
.select("createdBy, status")
.eq("id", insp.sourceDocumentId)
.maybeSingle()
- : Promise.resolve({ data: null, error: null })
+ : Promise.resolve({ data: null, error: null }),
+ getInspectionIssues(client, id, companyId)
]);
const doc = document.data as {
@@ -168,6 +172,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
pdfUrl: doc?.content?.pdfUrl ?? null,
lotEntities: (lotEntities.data ?? []) as InspectionTrackedEntity[],
issueTypes: (issueTypes.data ?? []) as IssueTypeListItem[],
+ issues: (issues.data ?? [])
+ .map((link) => link.nonConformance)
+ .filter((issue): issue is InspectionIssue => Boolean(issue)),
enforceFourEyes:
((settings.data as any)?.enforceInspectionFourEyes as boolean) ?? false,
currentUserId: userId
@@ -196,6 +203,7 @@ export default function InspectionExecutionRoute() {
pdfUrl={loaderData.pdfUrl}
lotEntities={loaderData.lotEntities as InspectionTrackedEntity[]}
issueTypes={loaderData.issueTypes as IssueTypeListItem[]}
+ issues={loaderData.issues}
currentUserId={loaderData.currentUserId}
enforceFourEyes={loaderData.enforceFourEyes}
/>
diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
index 71defa8354..84e634a1e8 100644
--- a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
@@ -6,6 +6,7 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
+import { getLogger } from "@carbon/logger";
import { RecordOutlet } from "@carbon/react";
import { redirect } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
@@ -27,11 +28,16 @@ import {
ReceiptDocuments,
ReceiptHeader
} from "~/modules/inventory/ui/Receipts";
-import { getReceiptInspections } from "~/modules/quality/quality.service";
+import {
+ getReceiptInspectedItemIds,
+ getReceiptInspections
+} from "~/modules/quality/quality.service";
import { getCompanySettings } from "~/modules/settings/settings.service";
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "receipt");
+
export const handle: Handle = {
realtime: [
{ table: "receipt", column: "id", param: "receiptId" },
@@ -134,6 +140,30 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
});
}
+ // Only a purchase receipt opens inspection lots, for the lines whose item
+ // has a Receipt-usage inspection plan. Once posted, the lots themselves
+ // (receiptInspections) say which lines were inspected.
+ const inspectedItemIds =
+ receipt.data.sourceDocument === "Purchase Order" &&
+ receipt.data.status !== "Posted"
+ ? await getReceiptInspectedItemIds(serviceRole, companyId, [
+ ...new Set(
+ (receiptLines.data ?? [])
+ .map((line) => line.itemId)
+ .filter((itemId): itemId is string => Boolean(itemId))
+ )
+ ])
+ : { data: [] as string[], error: null };
+ // The marks only inform: a failed lookup leaves them off rather than
+ // failing the receipt, but it must not pass silently for "none needed".
+ if (inspectedItemIds.error) {
+ logger.error("Failed to load the receipt's inspected items", {
+ companyId,
+ receiptId,
+ error: inspectedItemIds.error
+ });
+ }
+
let rentalLines: RentalReceiptLine[] = [];
if (receipt.data.sourceDocument === "Rental Agreement") {
@@ -192,6 +222,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
receipt: receipt.data,
receiptLines: receiptLines.data ?? [],
receiptInspections: receiptInspections.data ?? [],
+ inspectedItemIds: inspectedItemIds.data ?? [],
fixedAssetLines,
rentalLines,
receiptFiles: getReceiptFiles(serviceRole, companyId, receiptLineIds) ?? [],
diff --git a/packages/database/src/quality.test.ts b/packages/database/src/quality.test.ts
new file mode 100644
index 0000000000..ca33648864
--- /dev/null
+++ b/packages/database/src/quality.test.ts
@@ -0,0 +1,72 @@
+// 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 { isRejectableWithoutReason } from "./quality";
+
+// A lot can always be rejected with a reason (a suspected counterfeit, the
+// wrong part). Without one, it must have failed inspection.
+describe("isRejectableWithoutReason", () => {
+ const feature = (rejectionNumber: number, failed: number) => ({
+ rejectionNumber,
+ failed
+ });
+
+ it("rejects a document-driven lot once a characteristic reaches its rejection number", () => {
+ expect(
+ isRejectableWithoutReason({
+ features: [feature(2, 0), feature(2, 2)],
+ failedSamples: 0,
+ acceptanceNumber: 1
+ })
+ ).toBe(true);
+ });
+
+ it("rejects a document-driven lot with a failed sample", () => {
+ expect(
+ isRejectableWithoutReason({
+ features: [feature(3, 1)],
+ failedSamples: 1,
+ acceptanceNumber: 2
+ })
+ ).toBe(true);
+ });
+
+ it("needs a reason for a document-driven lot that has not failed", () => {
+ expect(
+ isRejectableWithoutReason({
+ features: [feature(2, 1), feature(3, 0)],
+ failedSamples: 0,
+ acceptanceNumber: 1
+ })
+ ).toBe(false);
+ });
+
+ it("rejects a lot with no characteristics once its failures pass the acceptance number", () => {
+ expect(
+ isRejectableWithoutReason({
+ features: [],
+ failedSamples: 2,
+ acceptanceNumber: 1
+ })
+ ).toBe(true);
+ });
+
+ it("needs a reason for a lot with no characteristics within its acceptance number", () => {
+ expect(
+ isRejectableWithoutReason({
+ features: [],
+ failedSamples: 1,
+ acceptanceNumber: 1
+ })
+ ).toBe(false);
+ expect(
+ isRejectableWithoutReason({
+ features: [],
+ failedSamples: 0,
+ acceptanceNumber: 0
+ })
+ ).toBe(false);
+ });
+});
diff --git a/packages/database/src/quality.ts b/packages/database/src/quality.ts
index d87a3aff65..860bcd6928 100644
--- a/packages/database/src/quality.ts
+++ b/packages/database/src/quality.ts
@@ -57,6 +57,11 @@ export type InspectionDispositionInput = {
id: string;
decision: "Accept" | "Reject" | "Partial";
notes?: string;
+ // Why a lot is rejected when no characteristic reached its rejection number
+ // and no sample failed — a suspected counterfeit, the wrong part, transit
+ // damage. A Reject with a reason needs no failure; it is stored as the lot's
+ // notes when `notes` is empty.
+ reason?: string;
companyId: string;
dispositionedBy: string;
// One-shot mode: refuse to disposition a lot that is already terminal
@@ -387,6 +392,28 @@ export async function upsertInspectionSample(
// - inspection (status, dispositionedBy/At, notes)
// - inspectionHistory (1 row for future plan auto-switching)
+/**
+ * Whether a lot has failed inspection, so it can be rejected with no reason
+ * given. A document-driven lot fails when a characteristic reaches its
+ * rejection number or a sample fails; a lot with no characteristics when its
+ * failed samples pass the acceptance number. Anything else — a suspected
+ * counterfeit, the wrong part — needs a reason. The ERP and MES Reject
+ * buttons apply the same rule.
+ */
+export function isRejectableWithoutReason(lot: {
+ features: { rejectionNumber: number; failed: number }[];
+ failedSamples: number;
+ acceptanceNumber: number;
+}): boolean {
+ if (lot.features.length > 0) {
+ return (
+ lot.features.some((f) => f.failed >= f.rejectionNumber) ||
+ lot.failedSamples > 0
+ );
+ }
+ return lot.failedSamples > lot.acceptanceNumber;
+}
+
export async function dispositionInspection(
db: Kysely<KyselyDatabase>,
args: InspectionDispositionInput
@@ -423,7 +450,8 @@ export async function dispositionInspection(
"inspectionLevel",
"aql",
"lotSize",
- "sampleSize"
+ "sampleSize",
+ "acceptanceNumber"
])
.where("id", "=", args.id)
.where("companyId", "=", args.companyId)
@@ -509,16 +537,16 @@ export async function dispositionInspection(
.where("inspectionId", "=", args.id)
.execute();
+ const countsByFeature = new Map<
+ string,
+ { recorded: number; failed: number }
+ >();
if (lotFeatures.length > 0) {
const measurements = await trx
.selectFrom("inspectionMeasurement")
.select(["inspectionFeatureId", "status"])
.where("inspectionId", "=", args.id)
.execute();
- const countsByFeature = new Map<
- string,
- { recorded: number; failed: number }
- >();
for (const m of measurements) {
const counts = countsByFeature.get(m.inspectionFeatureId) ?? {
recorded: 0,
@@ -546,19 +574,23 @@ export async function dispositionInspection(
);
}
}
+ }
- if (args.decision === "Reject") {
- const rejectable =
- lotFeatures.some((f) => {
- const counts = countsByFeature.get(f.inspectionFeatureId);
- return counts != null && counts.failed >= f.rejectionNumber;
- }) || existingSamples.some((s) => s.status === "Failed");
- if (!rejectable) {
- throw new Error(
- "Cannot reject: no feature has reached its rejection number and no sample has failed"
- );
- }
- }
+ if (
+ args.decision === "Reject" &&
+ !args.reason?.trim() &&
+ !isRejectableWithoutReason({
+ features: lotFeatures.map((f) => ({
+ rejectionNumber: f.rejectionNumber,
+ failed: countsByFeature.get(f.inspectionFeatureId)?.failed ?? 0
+ })),
+ failedSamples: failures,
+ acceptanceNumber: inspection.acceptanceNumber
+ })
+ ) {
+ throw new Error(
+ "Cannot reject: the lot has not failed inspection. Give a reason to reject it anyway."
+ );
}
// Reject = entire lot non-conforming (ISO 9001:2015 §8.7). Accept
@@ -621,7 +653,7 @@ export async function dispositionInspection(
.updateTable("inspection")
.set({
status: lotStatus,
- notes: args.notes ?? null,
+ notes: args.notes || args.reason?.trim() || null,
dispositionedBy: args.dispositionedBy,
dispositionedAt: nowIso,
updatedBy: args.dispositionedBy,
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 154ca145af..bfd31df7bf 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -8429,6 +8429,9 @@ msgstr "z.B. MI"
msgid "e.g. Suite 200"
msgstr "z.B. Suite 200"
+msgid "e.g. Suspected counterfeit, wrong part, damaged in transit"
+msgstr "z. B. Verdacht auf Fälschung, falsches Teil, Transportschaden"
+
msgid "e.g. the first 3 to 4 weeks"
msgstr "z.B. die ersten 3 bis 4 Wochen"
@@ -11695,6 +11698,15 @@ msgstr "Prüfung"
msgid "Inspection · {itemReadableId}"
msgstr "Prüfung · {itemReadableId}"
+#. placeholder {0}: inspection.inspectionId
+msgid "Inspection {0}"
+msgstr "Prüfung {0}"
+
+#. placeholder {0}: inspection.inspectionId
+#. placeholder {1}: inspection.status
+msgid "Inspection {0} · {1}"
+msgstr "Prüfung {0} · {1}"
+
msgid "Inspection document"
msgstr "Prüfungsdokument"
@@ -14739,6 +14751,14 @@ msgstr "Noch keine Änderungen."
msgid "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
msgstr "Keine Änderungen vorhanden. Sobald der Mietvertrag aktiv ist, befindet sich Ändern im Header und Beenden und Kaufen auf der Seite jedes Vermögenswerts."
+#. placeholder {0}: lotEntities.length
+msgid "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+msgstr "Kein Merkmal ist fehlgeschlagen, geben Sie daher an, warum das Los abgelehnt wird. Alle {0} Einheiten werden als abgelehnt markiert."
+
+#. placeholder {0}: inspection.lotSize
+msgid "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+msgstr "Kein Merkmal ist fehlgeschlagen, geben Sie daher an, warum das Los abgelehnt wird. Das gesamte Los von {0} wird abgelehnt."
+
msgid "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
msgstr "Keine Gebühren. Kilometer-, Schaden-, Liefer- und Reinigungsgebühren werden der nächsten Rechnung hinzugefügt."
@@ -18303,6 +18323,9 @@ msgstr "Realisierter Wechselkursverlust"
msgid "Reason"
msgstr "Grund"
+msgid "Reason (optional)"
+msgstr "Grund (optional)"
+
msgid "Reason Account"
msgstr "Grund-Konto"
@@ -19195,6 +19218,12 @@ msgstr "Erfordert Maßnahmen"
msgid "Requires Adjustment"
msgstr "Erfordert Korrektur"
+msgid "Requires inspection"
+msgstr "Erfordert Prüfung"
+
+msgid "Requires inspection. A lot opens when the receipt posts."
+msgstr "Erfordert Prüfung. Beim Buchen des Belegs wird ein Los eröffnet."
+
msgid "Requires Repair"
msgstr "Reparatur erforderlich"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 2fbdebd198..8e8fd854eb 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -8429,6 +8429,9 @@ msgstr "e.g. MI"
msgid "e.g. Suite 200"
msgstr "e.g. Suite 200"
+msgid "e.g. Suspected counterfeit, wrong part, damaged in transit"
+msgstr "e.g. Suspected counterfeit, wrong part, damaged in transit"
+
msgid "e.g. the first 3 to 4 weeks"
msgstr "e.g. the first 3 to 4 weeks"
@@ -11695,6 +11698,15 @@ msgstr "Inspection"
msgid "Inspection · {itemReadableId}"
msgstr "Inspection · {itemReadableId}"
+#. placeholder {0}: inspection.inspectionId
+msgid "Inspection {0}"
+msgstr "Inspection {0}"
+
+#. placeholder {0}: inspection.inspectionId
+#. placeholder {1}: inspection.status
+msgid "Inspection {0} · {1}"
+msgstr "Inspection {0} · {1}"
+
msgid "Inspection document"
msgstr "Inspection document"
@@ -14739,6 +14751,14 @@ msgstr "No changes yet."
msgid "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
msgstr "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
+#. placeholder {0}: lotEntities.length
+msgid "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+msgstr "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+
+#. placeholder {0}: inspection.lotSize
+msgid "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+msgstr "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+
msgid "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
msgstr "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
@@ -18303,6 +18323,9 @@ msgstr "Realized Exchange Loss"
msgid "Reason"
msgstr "Reason"
+msgid "Reason (optional)"
+msgstr "Reason (optional)"
+
msgid "Reason Account"
msgstr "Reason Account"
@@ -19195,6 +19218,12 @@ msgstr "Requires Action"
msgid "Requires Adjustment"
msgstr "Requires Adjustment"
+msgid "Requires inspection"
+msgstr "Requires inspection"
+
+msgid "Requires inspection. A lot opens when the receipt posts."
+msgstr "Requires inspection. A lot opens when the receipt posts."
+
msgid "Requires Repair"
msgstr "Requires Repair"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 65c29fe927..7ae6b37f72 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -8429,6 +8429,9 @@ msgstr "p. ej. MI"
msgid "e.g. Suite 200"
msgstr "p. ej. Suite 200"
+msgid "e.g. Suspected counterfeit, wrong part, damaged in transit"
+msgstr "p. ej. Sospecha de falsificación, pieza incorrecta, dañado en tránsito"
+
msgid "e.g. the first 3 to 4 weeks"
msgstr "p. ej. las primeras 3 a 4 semanas"
@@ -11695,6 +11698,15 @@ msgstr "Inspección"
msgid "Inspection · {itemReadableId}"
msgstr "Inspección · {itemReadableId}"
+#. placeholder {0}: inspection.inspectionId
+msgid "Inspection {0}"
+msgstr "Inspección {0}"
+
+#. placeholder {0}: inspection.inspectionId
+#. placeholder {1}: inspection.status
+msgid "Inspection {0} · {1}"
+msgstr "Inspección {0} · {1}"
+
msgid "Inspection document"
msgstr "Documento de inspección"
@@ -14739,6 +14751,14 @@ msgstr "Sin cambios aún."
msgid "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
msgstr "Sin cambios aún. Una vez que el arrendamiento es activo, Modificar se encuentra en el encabezado y Terminar y Comprar se encuentran en la página de cada activo."
+#. placeholder {0}: lotEntities.length
+msgid "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+msgstr "Ninguna característica ha fallado, así que indique por qué se rechaza el lote. Las {0} entidades se marcarán como rechazadas."
+
+#. placeholder {0}: inspection.lotSize
+msgid "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+msgstr "Ninguna característica ha fallado, así que indique por qué se rechaza el lote. Se rechazará el lote completo de {0}."
+
msgid "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
msgstr "Sin cargos. Los cargos por kilometraje, daños, entrega o limpieza se incluyen en la siguiente factura."
@@ -18303,6 +18323,9 @@ msgstr "Pérdida por Cambio de Divisas Realizada"
msgid "Reason"
msgstr "Razón"
+msgid "Reason (optional)"
+msgstr "Razón (opcional)"
+
msgid "Reason Account"
msgstr "Cuenta de Razón"
@@ -19195,6 +19218,12 @@ msgstr "Requiere Acción"
msgid "Requires Adjustment"
msgstr "Requiere Ajuste"
+msgid "Requires inspection"
+msgstr "Requiere inspección"
+
+msgid "Requires inspection. A lot opens when the receipt posts."
+msgstr "Requiere inspección. Se abre un lote al registrar la recepción."
+
msgid "Requires Repair"
msgstr "Requiere Reparación"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 585289829a..3eaa9b9b1f 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -8429,6 +8429,9 @@ msgstr "p. ex. MI"
msgid "e.g. Suite 200"
msgstr "p. ex. Suite 200"
+msgid "e.g. Suspected counterfeit, wrong part, damaged in transit"
+msgstr "p. ex. Contrefaçon suspectée, mauvaise pièce, endommagé pendant le transport"
+
msgid "e.g. the first 3 to 4 weeks"
msgstr "par exemple les 3 à 4 premières semaines"
@@ -11695,6 +11698,15 @@ msgstr "Contrôle"
msgid "Inspection · {itemReadableId}"
msgstr "Contrôle · {itemReadableId}"
+#. placeholder {0}: inspection.inspectionId
+msgid "Inspection {0}"
+msgstr "Contrôle {0}"
+
+#. placeholder {0}: inspection.inspectionId
+#. placeholder {1}: inspection.status
+msgid "Inspection {0} · {1}"
+msgstr "Contrôle {0} · {1}"
+
msgid "Inspection document"
msgstr "Document de contrôle"
@@ -14739,6 +14751,14 @@ msgstr "Aucune modification pour le moment."
msgid "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
msgstr "Aucun changement pour le moment. Une fois le bail actif, Modifier est dans l'en-tête et Résilier et Acheter se trouvent sur la page de chaque actif."
+#. placeholder {0}: lotEntities.length
+msgid "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+msgstr "Aucune caractéristique n'a échoué : indiquez pourquoi le lot est rejeté. Les {0} entités seront marquées comme rejetées."
+
+#. placeholder {0}: inspection.lotSize
+msgid "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+msgstr "Aucune caractéristique n'a échoué : indiquez pourquoi le lot est rejeté. L'ensemble du lot de {0} sera rejeté."
+
msgid "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
msgstr "Aucun frais. Les frais de kilométrage, dommages, livraison ou nettoyage seront reportés sur la facture suivante."
@@ -18303,6 +18323,9 @@ msgstr "Perte de change réalisée"
msgid "Reason"
msgstr "Raison"
+msgid "Reason (optional)"
+msgstr "Raison (facultatif)"
+
msgid "Reason Account"
msgstr "Compte de raison"
@@ -19195,6 +19218,12 @@ msgstr "Nécessite une action"
msgid "Requires Adjustment"
msgstr "Nécessite un ajustement"
+msgid "Requires inspection"
+msgstr "Nécessite un contrôle"
+
+msgid "Requires inspection. A lot opens when the receipt posts."
+msgstr "Nécessite un contrôle. Un lot est ouvert à la validation du reçu."
+
msgid "Requires Repair"
msgstr "Nécessite une réparation"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index d19d2f0454..bd428aa8d7 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -8429,6 +8429,9 @@ msgstr "उदा. MI"
msgid "e.g. Suite 200"
msgstr "उदा. Suite 200"
+msgid "e.g. Suspected counterfeit, wrong part, damaged in transit"
+msgstr "उदा. संदिग्ध नकली, गलत पार्ट, परिवहन में क्षतिग्रस्त"
+
msgid "e.g. the first 3 to 4 weeks"
msgstr "उदाहरण के लिए पहले 3 से 4 सप्ताह"
@@ -11695,6 +11698,15 @@ msgstr "निरीक्षण"
msgid "Inspection · {itemReadableId}"
msgstr "निरीक्षण · {itemReadableId}"
+#. placeholder {0}: inspection.inspectionId
+msgid "Inspection {0}"
+msgstr "निरीक्षण {0}"
+
+#. placeholder {0}: inspection.inspectionId
+#. placeholder {1}: inspection.status
+msgid "Inspection {0} · {1}"
+msgstr "निरीक्षण {0} · {1}"
+
msgid "Inspection document"
msgstr "निरीक्षण दस्तावेज़"
@@ -14739,6 +14751,14 @@ msgstr "अभी तक कोई परिवर्तन नहीं।"
msgid "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
msgstr "अभी कोई परिवर्तन नहीं है। एक बार लीज सक्रिय हो जाए, तो संशोधन शीर्षलेख में है और समाप्त तथा खरीद प्रत्येक संपत्ति पृष्ठ पर हैं।"
+#. placeholder {0}: lotEntities.length
+msgid "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+msgstr "कोई विशेषता विफल नहीं हुई है, इसलिए बताएं कि लॉट क्यों अस्वीकार किया जा रहा है। सभी {0} इकाइयाँ अस्वीकृत चिह्नित की जाएंगी।"
+
+#. placeholder {0}: inspection.lotSize
+msgid "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+msgstr "कोई विशेषता विफल नहीं हुई है, इसलिए बताएं कि लॉट क्यों अस्वीकार किया जा रहा है। {0} का पूरा लॉट अस्वीकार किया जाएगा।"
+
msgid "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
msgstr "कोई शुल्क नहीं। माइलेज, क्षति, डिलीवरी या सफाई शुल्क अगले चालान में शामिल होंगे।"
@@ -18303,6 +18323,9 @@ msgstr "वास्तविक विनिमय हानि"
msgid "Reason"
msgstr "कारण"
+msgid "Reason (optional)"
+msgstr "कारण (वैकल्पिक)"
+
msgid "Reason Account"
msgstr "कारण खाता"
@@ -19195,6 +19218,12 @@ msgstr "कार्रवाई आवश्यक है"
msgid "Requires Adjustment"
msgstr "समायोजन आवश्यक है"
+msgid "Requires inspection"
+msgstr "निरीक्षण आवश्यक है"
+
+msgid "Requires inspection. A lot opens when the receipt posts."
+msgstr "निरीक्षण आवश्यक है। रसीद पोस्ट होने पर एक लॉट खुलता है।"
+
msgid "Requires Repair"
msgstr "मरम्मत की आवश्यकता है"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index f0470f9196..bbafba9328 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -8429,6 +8429,9 @@ msgstr "ad es. MI"
msgid "e.g. Suite 200"
msgstr "ad es. Suite 200"
+msgid "e.g. Suspected counterfeit, wrong part, damaged in transit"
+msgstr "es. Sospetta contraffazione, parte errata, danneggiato durante il trasporto"
+
msgid "e.g. the first 3 to 4 weeks"
msgstr "ad es. le prime 3-4 settimane"
@@ -11695,6 +11698,15 @@ msgstr "Controllo"
msgid "Inspection · {itemReadableId}"
msgstr "Controllo · {itemReadableId}"
+#. placeholder {0}: inspection.inspectionId
+msgid "Inspection {0}"
+msgstr "Controllo {0}"
+
+#. placeholder {0}: inspection.inspectionId
+#. placeholder {1}: inspection.status
+msgid "Inspection {0} · {1}"
+msgstr "Controllo {0} · {1}"
+
msgid "Inspection document"
msgstr "Documento di controllo"
@@ -14739,6 +14751,14 @@ msgstr "Nessuna modifica ancora."
msgid "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
msgstr "Nessuna modifica al momento. Una volta che il contratto di leasing è attivo, Modifica si trova nell'intestazione e Termina e Acquista si trovano sulla pagina di ogni asset."
+#. placeholder {0}: lotEntities.length
+msgid "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+msgstr "Nessuna caratteristica è fallita, quindi indica perché il lotto viene rifiutato. Tutte le {0} entità saranno contrassegnate come rifiutate."
+
+#. placeholder {0}: inspection.lotSize
+msgid "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+msgstr "Nessuna caratteristica è fallita, quindi indica perché il lotto viene rifiutato. L'intero lotto di {0} sarà rifiutato."
+
msgid "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
msgstr "Nessun addebito. Gli addebiti per chilometraggio, danni, consegna o pulizia verranno addebitati sulla fattura successiva."
@@ -18303,6 +18323,9 @@ msgstr "Perdita di cambio realizzata"
msgid "Reason"
msgstr "Motivo"
+msgid "Reason (optional)"
+msgstr "Motivo (facoltativo)"
+
msgid "Reason Account"
msgstr "Conto Motivo"
@@ -19195,6 +19218,12 @@ msgstr "Richiede Azione"
msgid "Requires Adjustment"
msgstr "Richiede rettifica"
+msgid "Requires inspection"
+msgstr "Richiede controllo"
+
+msgid "Requires inspection. A lot opens when the receipt posts."
+msgstr "Richiede controllo. Alla registrazione della ricevuta si apre un lotto."
+
msgid "Requires Repair"
msgstr "Richiede Riparazione"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index d1761af7f5..05e7ae3380 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -8429,6 +8429,9 @@ msgstr "例:MI"
msgid "e.g. Suite 200"
msgstr "例:Suite 200"
+msgid "e.g. Suspected counterfeit, wrong part, damaged in transit"
+msgstr "例: 偽造品の疑い、部品違い、輸送中の破損"
+
msgid "e.g. the first 3 to 4 weeks"
msgstr "例:最初の3~4週間"
@@ -11695,6 +11698,15 @@ msgstr "検査"
msgid "Inspection · {itemReadableId}"
msgstr "検査·{itemReadableId}"
+#. placeholder {0}: inspection.inspectionId
+msgid "Inspection {0}"
+msgstr "検査 {0}"
+
+#. placeholder {0}: inspection.inspectionId
+#. placeholder {1}: inspection.status
+msgid "Inspection {0} · {1}"
+msgstr "検査 {0} · {1}"
+
msgid "Inspection document"
msgstr "検査文書"
@@ -14739,6 +14751,14 @@ msgstr "まだ変更がありません。"
msgid "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
msgstr "変更がまだありません。リースが有効になると、「修正」はヘッダーに、「終了」と「購入」は各資産のページにあります。"
+#. placeholder {0}: lotEntities.length
+msgid "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+msgstr "不合格の特性がないため、ロットを却下する理由を入力してください。{0}件のエンティティすべてが却下済みになります。"
+
+#. placeholder {0}: inspection.lotSize
+msgid "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+msgstr "不合格の特性がないため、ロットを却下する理由を入力してください。{0}のロット全体が却下されます。"
+
msgid "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
msgstr "請求がありません。走行距離、損傷、配送、クリーニング料金は次の請求書に含まれます。"
@@ -18303,6 +18323,9 @@ msgstr "実現為替損失"
msgid "Reason"
msgstr "理由"
+msgid "Reason (optional)"
+msgstr "理由(任意)"
+
msgid "Reason Account"
msgstr "理由アカウント"
@@ -19195,6 +19218,12 @@ msgstr "対応が必要"
msgid "Requires Adjustment"
msgstr "調整が必要"
+msgid "Requires inspection"
+msgstr "検査が必要"
+
+msgid "Requires inspection. A lot opens when the receipt posts."
+msgstr "検査が必要です。領収書の転記時にロットが作成されます。"
+
msgid "Requires Repair"
msgstr "修理が必要"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 0b5367ca61..30f5f26f00 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -8429,6 +8429,9 @@ msgstr "예: MI"
msgid "e.g. Suite 200"
msgstr "예: Suite 200"
+msgid "e.g. Suspected counterfeit, wrong part, damaged in transit"
+msgstr "예: 위조품 의심, 잘못된 부품, 운송 중 파손"
+
msgid "e.g. the first 3 to 4 weeks"
msgstr "예: 처음 3~4주"
@@ -11695,6 +11698,15 @@ msgstr "검사"
msgid "Inspection · {itemReadableId}"
msgstr "검사 · {itemReadableId}"
+#. placeholder {0}: inspection.inspectionId
+msgid "Inspection {0}"
+msgstr "검사 {0}"
+
+#. placeholder {0}: inspection.inspectionId
+#. placeholder {1}: inspection.status
+msgid "Inspection {0} · {1}"
+msgstr "검사 {0} · {1}"
+
msgid "Inspection document"
msgstr "검사 문서"
@@ -14739,6 +14751,14 @@ msgstr "아직 변경사항이 없습니다."
msgid "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
msgstr "변경 사항이 없습니다. 리스가 활성화되면 수정은 헤더에 있고 종료와 구매는 각 자산 페이지에 있습니다."
+#. placeholder {0}: lotEntities.length
+msgid "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+msgstr "불합격된 특성이 없으므로 로트를 거부하는 사유를 입력하세요. {0}개 엔터티가 모두 거부됨으로 표시됩니다."
+
+#. placeholder {0}: inspection.lotSize
+msgid "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+msgstr "불합격된 특성이 없으므로 로트를 거부하는 사유를 입력하세요. {0}개 로트 전체가 거부됩니다."
+
msgid "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
msgstr "요금이 없습니다. 주행 거리, 손상, 배송 또는 청소 요금은 다음 송장에 포함됩니다."
@@ -18303,6 +18323,9 @@ msgstr "실현 환차손"
msgid "Reason"
msgstr "사유"
+msgid "Reason (optional)"
+msgstr "사유(선택)"
+
msgid "Reason Account"
msgstr "사유 계정"
@@ -19195,6 +19218,12 @@ msgstr "조치 필요"
msgid "Requires Adjustment"
msgstr "조정 필요"
+msgid "Requires inspection"
+msgstr "검사 필요"
+
+msgid "Requires inspection. A lot opens when the receipt posts."
+msgstr "검사가 필요합니다. 입고를 전기하면 로트가 생성됩니다."
+
msgid "Requires Repair"
msgstr "수리 필요"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index cbb874e80b..86193d08b8 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -8429,6 +8429,9 @@ msgstr "np. mazowieckie"
msgid "e.g. Suite 200"
msgstr "np. lok. 200"
+msgid "e.g. Suspected counterfeit, wrong part, damaged in transit"
+msgstr "np. Podejrzenie podróbki, niewłaściwa część, uszkodzenie w transporcie"
+
msgid "e.g. the first 3 to 4 weeks"
msgstr "np. pierwsze 3 do 4 tygodnie"
@@ -11695,6 +11698,15 @@ msgstr "Kontrola"
msgid "Inspection · {itemReadableId}"
msgstr "Kontrola · {itemReadableId}"
+#. placeholder {0}: inspection.inspectionId
+msgid "Inspection {0}"
+msgstr "Kontrola {0}"
+
+#. placeholder {0}: inspection.inspectionId
+#. placeholder {1}: inspection.status
+msgid "Inspection {0} · {1}"
+msgstr "Kontrola {0} · {1}"
+
msgid "Inspection document"
msgstr "Dokument kontroli"
@@ -14739,6 +14751,14 @@ msgstr "Brak zmian."
msgid "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
msgstr "Brak zmian. Gdy leasing będzie aktywny, Modyfikuj znajduje się w nagłówku, a Zakończ i Kup znajdują się na stronie każdego zasobu."
+#. placeholder {0}: lotEntities.length
+msgid "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+msgstr "Żadna cecha nie została odrzucona, więc podaj, dlaczego partia jest odrzucana. Wszystkie {0} jednostki zostaną oznaczone jako odrzucone."
+
+#. placeholder {0}: inspection.lotSize
+msgid "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+msgstr "Żadna cecha nie została odrzucona, więc podaj, dlaczego partia jest odrzucana. Cała partia {0} zostanie odrzucona."
+
msgid "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
msgstr "Brak opłat. Opłaty za przebieg, uszkodzenie, dostawę lub czyszczenie pojawią się na następnej fakturze."
@@ -18303,6 +18323,9 @@ msgstr "Zrealizowana strata walutowa"
msgid "Reason"
msgstr "Powód"
+msgid "Reason (optional)"
+msgstr "Powód (opcjonalnie)"
+
msgid "Reason Account"
msgstr "Konto przyczyny"
@@ -19195,6 +19218,12 @@ msgstr "Wymaga działania"
msgid "Requires Adjustment"
msgstr "Wymaga Korekty"
+msgid "Requires inspection"
+msgstr "Wymaga kontroli"
+
+msgid "Requires inspection. A lot opens when the receipt posts."
+msgstr "Wymaga kontroli. Partia zostanie otwarta po zaksięgowaniu paragonu."
+
msgid "Requires Repair"
msgstr "Wymaga naprawy"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 0cf8392660..f27c1507f6 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -8429,6 +8429,9 @@ msgstr "p. ex. MI"
msgid "e.g. Suite 200"
msgstr "p. ex. Suite 200"
+msgid "e.g. Suspected counterfeit, wrong part, damaged in transit"
+msgstr "ex.: Suspeita de falsificação, peça errada, danificado no transporte"
+
msgid "e.g. the first 3 to 4 weeks"
msgstr "p.ex. as primeiras 3 a 4 semanas"
@@ -11695,6 +11698,15 @@ msgstr "Inspeção"
msgid "Inspection · {itemReadableId}"
msgstr "Inspeção · {itemReadableId}"
+#. placeholder {0}: inspection.inspectionId
+msgid "Inspection {0}"
+msgstr "Inspeção {0}"
+
+#. placeholder {0}: inspection.inspectionId
+#. placeholder {1}: inspection.status
+msgid "Inspection {0} · {1}"
+msgstr "Inspeção {0} · {1}"
+
msgid "Inspection document"
msgstr "Documento de inspeção"
@@ -14739,6 +14751,14 @@ msgstr "Nenhuma mudança ainda."
msgid "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
msgstr "Sem alterações ainda. Assim que o arrendamento estiver ativo, Modificar está no cabeçalho e Encerrar e Comprar estão na página de cada ativo."
+#. placeholder {0}: lotEntities.length
+msgid "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+msgstr "Nenhuma característica falhou, então informe por que o lote está sendo rejeitado. Todas as {0} entidades serão marcadas como rejeitadas."
+
+#. placeholder {0}: inspection.lotSize
+msgid "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+msgstr "Nenhuma característica falhou, então informe por que o lote está sendo rejeitado. O lote inteiro de {0} será rejeitado."
+
msgid "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
msgstr "Sem cobranças. Cobranças de quilometragem, dano, entrega ou limpeza serão incluídas na próxima fatura."
@@ -18303,6 +18323,9 @@ msgstr "Perda Cambial Realizada"
msgid "Reason"
msgstr "Motivo"
+msgid "Reason (optional)"
+msgstr "Motivo (opcional)"
+
msgid "Reason Account"
msgstr "Conta de Motivo"
@@ -19195,6 +19218,12 @@ msgstr "Requer Ação"
msgid "Requires Adjustment"
msgstr "Requer Ajuste"
+msgid "Requires inspection"
+msgstr "Requer inspeção"
+
+msgid "Requires inspection. A lot opens when the receipt posts."
+msgstr "Requer inspeção. Um lote é aberto ao lançar o recebimento."
+
msgid "Requires Repair"
msgstr "Requer Reparo"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 8ca604ea27..0582af5ea8 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -8429,6 +8429,9 @@ msgstr "например MI"
msgid "e.g. Suite 200"
msgstr "например Suite 200"
+msgid "e.g. Suspected counterfeit, wrong part, damaged in transit"
+msgstr "например: подозрение на подделку, не та деталь, повреждено при транспортировке"
+
msgid "e.g. the first 3 to 4 weeks"
msgstr "например, первые 3-4 недели"
@@ -11695,6 +11698,15 @@ msgstr "Контроль"
msgid "Inspection · {itemReadableId}"
msgstr "Контроль · {itemReadableId}"
+#. placeholder {0}: inspection.inspectionId
+msgid "Inspection {0}"
+msgstr "Контроль {0}"
+
+#. placeholder {0}: inspection.inspectionId
+#. placeholder {1}: inspection.status
+msgid "Inspection {0} · {1}"
+msgstr "Контроль {0} · {1}"
+
msgid "Inspection document"
msgstr "Документ контроля"
@@ -14739,6 +14751,14 @@ msgstr "Пока нет изменений."
msgid "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
msgstr "Изменений еще нет. Когда аренда активна, кнопка \"Изменить\" находится в заголовке, а кнопки \"Завершить\" и \"Приобрести\" находятся на странице каждого актива."
+#. placeholder {0}: lotEntities.length
+msgid "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+msgstr "Ни одна характеристика не забракована, поэтому укажите, почему партия отклоняется. Все {0} единиц будут отмечены как отклонённые."
+
+#. placeholder {0}: inspection.lotSize
+msgid "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+msgstr "Ни одна характеристика не забракована, поэтому укажите, почему партия отклоняется. Вся партия из {0} будет отклонена."
+
msgid "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
msgstr "Нет начислений. Плата за пробег, повреждения, доставку или уборку будет перенесена на следующий счет-фактуру."
@@ -18303,6 +18323,9 @@ msgstr "Реализованный убыток от обмена валют"
msgid "Reason"
msgstr "Причина"
+msgid "Reason (optional)"
+msgstr "Причина (необязательно)"
+
msgid "Reason Account"
msgstr "Счет причины"
@@ -19195,6 +19218,12 @@ msgstr "Требует действия"
msgid "Requires Adjustment"
msgstr "Требует корректировки"
+msgid "Requires inspection"
+msgstr "Требует контроля"
+
+msgid "Requires inspection. A lot opens when the receipt posts."
+msgstr "Требует контроля. Партия открывается при проведении квитанции."
+
msgid "Requires Repair"
msgstr "Требует ремонта"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 39ec50ea25..2c809b04c1 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -8429,6 +8429,9 @@ msgstr "örn. MI"
msgid "e.g. Suite 200"
msgstr "örn. Daire 200"
+msgid "e.g. Suspected counterfeit, wrong part, damaged in transit"
+msgstr "örn. Sahte olduğundan şüpheleniliyor, yanlış parça, taşımada hasar görmüş"
+
msgid "e.g. the first 3 to 4 weeks"
msgstr "örn. ilk 3 ila 4 hafta"
@@ -11695,6 +11698,15 @@ msgstr "Muayene"
msgid "Inspection · {itemReadableId}"
msgstr "Muayene · {itemReadableId}"
+#. placeholder {0}: inspection.inspectionId
+msgid "Inspection {0}"
+msgstr "Muayene {0}"
+
+#. placeholder {0}: inspection.inspectionId
+#. placeholder {1}: inspection.status
+msgid "Inspection {0} · {1}"
+msgstr "Muayene {0} · {1}"
+
msgid "Inspection document"
msgstr "Muayene belgesi"
@@ -14739,6 +14751,14 @@ msgstr "Henüz değişiklik yok."
msgid "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
msgstr "Henüz değişiklik yok. Kiralama aktif olduktan sonra, Değiştir başlık kısmında ve Sonlandır ile Satın Al her varlığın sayfasında yer alır."
+#. placeholder {0}: lotEntities.length
+msgid "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+msgstr "Başarısız olan bir özellik yok, bu yüzden lotun neden reddedildiğini belirtin. {0} varlığın tamamı Reddedildi olarak işaretlenecek."
+
+#. placeholder {0}: inspection.lotSize
+msgid "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+msgstr "Başarısız olan bir özellik yok, bu yüzden lotun neden reddedildiğini belirtin. {0} adetlik lotun tamamı reddedilecek."
+
msgid "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
msgstr "Herhangi bir ücret yok. Kilometre, hasar, teslimat veya temizlik ücretleri sonraki faturaya dahil edilir."
@@ -18303,6 +18323,9 @@ msgstr "Gerçekleşen Döviz Kaybı"
msgid "Reason"
msgstr "Neden"
+msgid "Reason (optional)"
+msgstr "Neden (isteğe bağlı)"
+
msgid "Reason Account"
msgstr "Neden Hesabı"
@@ -19195,6 +19218,12 @@ msgstr "Eylem Gerektirir"
msgid "Requires Adjustment"
msgstr "Düzeltme gerekli"
+msgid "Requires inspection"
+msgstr "Muayene gerekli"
+
+msgid "Requires inspection. A lot opens when the receipt posts."
+msgstr "Muayene gerekli. Makbuz kaydedildiğinde bir lot açılır."
+
msgid "Requires Repair"
msgstr "Onarım Gerektirir"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 4e27d6ff52..c23428b833 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -8429,6 +8429,9 @@ msgstr "例:MI"
msgid "e.g. Suite 200"
msgstr "例:Suite 200"
+msgid "e.g. Suspected counterfeit, wrong part, damaged in transit"
+msgstr "例如:疑似假冒、零件错误、运输中损坏"
+
msgid "e.g. the first 3 to 4 weeks"
msgstr "例如前3到4周"
@@ -11695,6 +11698,15 @@ msgstr "检验"
msgid "Inspection · {itemReadableId}"
msgstr "检验 · {itemReadableId}"
+#. placeholder {0}: inspection.inspectionId
+msgid "Inspection {0}"
+msgstr "检验 {0}"
+
+#. placeholder {0}: inspection.inspectionId
+#. placeholder {1}: inspection.status
+msgid "Inspection {0} · {1}"
+msgstr "检验 {0} · {1}"
+
msgid "Inspection document"
msgstr "检验文件"
@@ -14739,6 +14751,14 @@ msgstr "还没有变更。"
msgid "No changes yet. Once the lease is active, Modify is in the header and Terminate and Purchase are on each asset's page."
msgstr "暂无更改。租赁启用后,修改在页眉中,终止和购买在每个资产的页面上。"
+#. placeholder {0}: lotEntities.length
+msgid "No characteristic has failed, so say why the lot is rejected. All {0} entities will be marked Rejected."
+msgstr "没有特性不合格,请说明拒绝该批次的原因。全部 {0} 个实体将被标记为已拒绝。"
+
+#. placeholder {0}: inspection.lotSize
+msgid "No characteristic has failed, so say why the lot is rejected. The entire lot of {0} will be rejected."
+msgstr "没有特性不合格,请说明拒绝该批次的原因。整个批次 {0} 将被拒绝。"
+
msgid "No charges. Mileage, damage, delivery or cleaning charges ride the next invoice."
msgstr "无费用。里程、损毁、交付或清洁费用计入下一张发票。"
@@ -18303,6 +18323,9 @@ msgstr "已实现汇兑损失"
msgid "Reason"
msgstr "原因"
+msgid "Reason (optional)"
+msgstr "原因(可选)"
+
msgid "Reason Account"
msgstr "原因账户"
@@ -19195,6 +19218,12 @@ msgstr "需要采取行动"
msgid "Requires Adjustment"
msgstr "需要调整"
+msgid "Requires inspection"
+msgstr "需要检验"
+
+msgid "Requires inspection. A lot opens when the receipt posts."
+msgstr "需要检验。过账收据时将创建一个批次。"
+
msgid "Requires Repair"
msgstr "需要维修"