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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(production): receive exactly the completed quantity when completing serial jobs (#1626)
BettrCallRaul3108f7707edb
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 5f0cc32fe1..c2da31130c 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -1542,6 +1542,15 @@ full-screen ERP route.**Applies to:** PaymentForm, PaymentApplyTable, and other forms using derived presentation choices.+## A RAISE in a completion RPC aborts the UPDATE that triggered it++**Context:** `complete_job_to_inventory` gained guards refusing a completion it could not satisfy (zero quantity, a fractional serial quantity, fewer receivable units than completed).++**Problem:** That function is not only called from the ERP complete route — `sync_finish_job_operation` calls it from a BEFORE trigger interceptor, and `dispatch_event_interceptors` has no `EXCEPTION` block. So a serial item with no serial sequence (whose job keeps one whole-quantity seed entity, because `assign-serial-numbers` returns early with no sequence) made the raise propagate out and abort the `jobOperation` UPDATE itself: the operator could not mark the operation Done at all.++**Rule:** Before adding a `RAISE` to a SQL function, grep for trigger interceptors that call it. A refusal that is a useful error on a request path is a hard block on a trigger path. Either handle the case rather than refusing it, or make the trigger caller skip the call.++**Applies to:** `complete_job_to_inventory`, `sync_finish_job_operation`, and any function registered through `attach_event_trigger`.## A nullable column added by migration needs a reader that tolerates NULL**Context:** The accounting corrections release added `invoiceSettlement.sourceAmount` (document-currency principal) without backfilling rows written before it, and the migration comment explicitly declared legacy NULLs valid.diff --git a/.ai/plans/2026-09-14-job-completion-tracked-quantity.md b/.ai/plans/2026-09-14-job-completion-tracked-quantity.mdnew file mode 100644index 0000000000..03fdc969ba--- /dev/null+++ b/.ai/plans/2026-09-14-job-completion-tracked-quantity.md@@ -0,0 +1,140 @@+# Job completion: received quantity must equal completed quantity++Branch `fix/job-completion-tracked-quantity`. Bug fix, no schema change.++## Problem++Completing a job whose made item is serial-tracked, from the ERP, when no unit was+finished on the shop floor app:++- `JobCompleteModal` (`apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx`) locks+ Quantity Completed to the sum of `Available` job serials. None are `Available`, so it+ submits 0.+- `complete_job_to_inventory` (newest body: `20260805023439_company-timezone-sql-functions.sql`)+ receives one unit per unconsumed, unrejected job serial regardless of the quantity passed,+ and flips them all `Available`.+- `backflush_job_materials` prorates by `quantity / job.quantity`, so 0 consumes nothing.++Result: the finished unit is in stock, its materials never leave stock, `job.quantityComplete`+is 0. Completing again receives the same serial a second time.++The lock dates from 2025-03-12 (`bce810a17`), when job serials were one unnumbered placeholder+and got an identity only when finished on the shop floor app. Per-item serial sequences now+split and number job serials at creation (`assign-serial-numbers`), so the units exist before+any shop floor activity. The receipt code still carries the original author's TODO about which+units go into inventory.++Reproduced locally (rolled back) on the seeded serial job J000002: completing at 0 received+serial J000002-01 and issued 0 of 30 materials; completing at 1 twice received it twice.++## Change++1. **Receipt receives exactly the completed quantity (SQL, new migration).**+ Recreate `complete_job_to_inventory` verbatim from the newest body; change only the serial+ branch:+ - receivable units = job make-method serials not `Consumed`/`Rejected` and with no existing+ `Assembly Output` / `Job Receipt` ledger row for this job;+ - receive `p_quantity_complete - prior received` of them, ordering `Available` first (finished+ on the shop floor app), then by `readableId`, then `createdAt`;+ - flip only the received units to `Available`;+ - never receive the same unit twice, so re-completion is safe;+ - lock the job row first, so concurrent completions cannot compute the same delta;+ - refuse when fewer single-unit serials are left than the units being completed, and+ when the cumulative quantity would drop below what was already received.+ The auto-complete path (`sync_finish_job_operation`) calls the same function and is fixed+ with it.+2. **Refuse completion at quantity ≤ 0** in `complete_job_to_inventory` (and therefore every+ caller: ERP route, MCP tool, auto-complete) except Non-Inventory items, which keep current+ behavior. The fully-scrapped auto-complete branch never calls the function and is untouched.+3. **Dialog.** For a serial job whose serials are already split into quantity-1 units, unlock+ Quantity Completed. The quantity is cumulative, like the database: units the job already+ received are excluded, the default is what was received plus the unreceived `Available`+ units (else the rest of the job quantity), the field runs from the received quantity to+ received + receivable, and the preview lists only the units this completion adds. Keep the lock when the job+ still has an unsplit placeholder (no serial sequence) — receiving those needs serial numbers,+ which is out of scope. Complete Job is disabled at quantity ≤ 0 for stocked items; the+ validator is unchanged, since Non-Inventory completions may still submit 0.++## Out of scope++- Unsplit serial placeholders (items without a serial sequence).+- Batch-tracked made items: same lock; batch receipt already follows quantity; status handling+ not yet checked.+- Serial- or batch-tracked components: backflush skips them and only the shop floor app issues+ them.+- Repairing jobs already completed at 0 (Complete is disabled on completed jobs).+- Interaction with the parked serial-number timing work (numbers assigned at production).++## Verification++- [x] SQL, rolled back, on the seeded serial job: complete at 0 refused; complete at 1 receives+ one serial and backflushes 27 of 30 lines (the 3 tracked lines are skipped by design);+ completing again receives nothing new.+- [x] Multi-unit serial job: complete 2 of 3 receives 2, leaves 1 `Reserved`; complete 3 receives+ the third.+- [x] Mixed (SQL, unit marked `Available` directly): the finished unit is the one received first.+- [x] Mixed, through the shop floor app: 2-unit job with serial-sequence units SAT-0002/SAT-0003;+ logged SAT-0003 complete on the final operation (operation stays open at 1 of 2); ERP dialog+ defaulted to 1 listing SAT-0003; completing received SAT-0003, left SAT-0002 `Reserved`,+ backflushed for one unit.+- [x] Shop floor only: 2-unit job, both units (SAT-0004, SAT-0005) logged complete on the final+ operation; operation flipped Done, job auto-completed at 2, both units received once,+ backflushed for two units (27 of 30 lines).+- [x] Auto-complete when the last operation goes Done still receives 1 and backflushes.+- [x] Inventory-tracked completion at 1 unchanged and refused at 0; Non-Inventory at 0 allowed.+- [x] Browser: J000002 dialog unlocked at 1 with serial J000002-01, Complete disabled at 0,+ capped at 1, completed (1 received, 27 lines consumed). J000001 with an unsplit placeholder+ stays locked at 0 with Complete disabled. J000001 split into 3 numbered units: dialog+ defaults to 3, completed at 2, received -01 and -02, -03 left `Reserved`.+- [x] Whole units: `complete_job_to_inventory` refuses a fractional quantity for serial-tracked+ jobs (SQL, rolled back: 1.5 refused, 2 accepted with no double receipt, inventory item at+ 1.5 still accepted). Dialog: at 0.5 shows "Serial-tracked jobs must be completed in whole+ units." and disables Complete; back at 1 lists the serial and re-enables it.+- [x] Locked tracked job with nothing finished on the shop floor: dialog shows a warning+ ("Nothing completed in MES yet") explaining how to proceed, Complete disabled.+- [x] New strings translated in all 13 erp catalogs (hand-filled using the glossary terms).+- [x] Typecheck (`erp`), lint, `pnpm db:check:datasets`, `@carbon/checks` clobbers + tests.++## Review follow-up (2026-09-15)++Second-round review plus the open CodeRabbit comment on the migration.++- [x] **Decrease refused for every stocked item**, not only serial. A lower cumulative quantity+ posted a negative receipt, cost layer and WIP journal for batch and untracked jobs.+- [x] **Zero-delta re-completion.** No receipt row is posted, and when catch-up production events+ add WIP the function returns before the WIP discharge instead of dividing by a zero quantity.+ That WIP stays in WIP and is discharged with the next receipt.+- [x] **`sync_finish_job_operation`** asks for at least the quantity already received, so marking+ the last operation Done on a reopened job is not refused by the decrease guard.+- [x] **Dialog warning.** A serial job still holding a multi-unit placeholder no longer suggests+ marking every operation Done: that path raises. Batch jobs and single-unit serial jobs keep+ the original text.+- [x] **Received units read past RLS** (`getJobReceiptSnapshot`). The browser query returned nothing+ for users without inventory or accounting view, so already-received units looked receivable+ again. The dialog fetches them, with the job's received quantity, from+ `api+/production.job.$jobId.receipts` each time it opens, so a receipt made while the job page+ is open is not missed (CodeRabbit, second round; the first version read them in the job route+ loader). Quantity and units come from one Kysely statement, so a receipt committing between two+ reads cannot pair a new quantity with old units (CodeRabbit, third round).+- [x] **No stale fallback.** When the receipt read fails, the dialog shows an error with Retry instead+ of opening the form on the route's job and an empty received set (CodeRabbit, third round).+- [x] **Dialog minimum** is the received quantity for every stocked job, matching the database.+- [x] Comment in `getReceivableSerialUnits` on why the dialog locks an unnumbered single unit that+ the database would receive.+- Not changed: `Number.isFinite` in `isFractionalSerialQuantity` (it keeps an emptied input from+ reading as fractional). The auto-complete quantity still sums every last operation, so parallel+ "With Previous" last operations double-count for all item types; that predates this branch.++Verification:++- [x] Unit tests: `job-complete-logic.test.ts` (22 passing, including `hasUnsplitSerialPlaceholder`).+- [x] SQL test re-run with the new cases (inventory lower/re-completion, reopened last operation,+ accounting zero-delta with catch-up WIP): all pass. Against the previously pushed functions the+ new cases fail, the accounting one with `division by zero`.+- [x] Browser: a Ready serial job with an unsplit 2-unit placeholder shows the new warning with+ Complete disabled. Reopened J000001 (2 of 3 received) defaults to 3, lists only J000001-03 from the+ loader-provided received ids, and clamps a typed 1 to 2. Not run as a production-only user; the+ receipts read bypasses RLS, so the result does not depend on the viewer's permissions.+- [x] Browser, stale page: opened a 3-serial job, received JCQ-STALE-01 by SQL without reloading, then+ opened Complete. The dialog listed only -02 and -03 and clamped a typed 0 to the fresh received+ quantity of 1.diff --git a/.claude/rules/inspection-system.md b/.claude/rules/inspection-system.mdindex 2d75933ec2..43c8f71a3a 100644--- a/.claude/rules/inspection-system.md+++ b/.claude/rules/inspection-system.md@@ -111,8 +111,12 @@ strings (cosmetic).`sync_finish_job_operation` (the zero-completions fallback to the full jobquantity now applies ONLY when the job recorded no scrap/rework — a fullyscrapped job closes with `quantityComplete = 0` and receives nothing) and- `complete_job_to_inventory` (the serial branch excludes `Rejected` entities- from the Assembly Output ledger loop AND the Available release).+ `complete_job_to_inventory` (the serial branch excludes `Rejected` entities).+ `20260914095239_complete-job-received-quantity.sql` then rewrote that branch:+ it no longer loops every entity and no longer releases them all to `Available`+ — it receives only the delta between the cumulative completed quantity and+ what the job already received, oldest-numbered first, skipping `Consumed`,+ `Rejected` and `Scrapped`, and flips only the units it received.Execution-layer tables (`20260722040401_inbound-inspection-execution.sql`):diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex 5d201bd6a7..d6cf1e4b04 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -17,6 +17,15 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced- **Scheduling** — forecast-first finite scheduling run **IN-PROCESS in Node** via `runLocationSchedule` / `runExpediteWhatIf` from `@carbon/ee/planning` (the ERP app and `@carbon/jobs` call it directly — no edge cold-start/HTTP hop; the `schedule` Deno edge function was DELETED, and the engine now lives in `packages/ee/src/planning/scheduling/`). It regenerates a **whole LOCATION** in one deterministic FORWARD-ASAP pass (no backward JIT pass in placement, no `initial`/`reschedule` modes). Machine availability comes from a per-work-center ladder: `workCenter.alwaysOn` = 24×7 lights-out → explicit `workCenterShift` rows → the location's `shift` rows → a stock Mon–Fri 8h week; open maintenance dispatches flagged `takesWorkCenterOffline` subtract downtime from those windows. Work centers are finite (capacity 1 — one op at a time) AND, for ability-gated processes, qualified PEOPLE are finite: work only accumulates while a qualified employee is on shift (`employeeShift` ⋈ `shift`; no shift assignment = the job location's calendar) and not reserved elsewhere. Started ops net **remaining work** only — labor+machine scaled by `(1 − quantityComplete/operationQuantity)`, setup done once any `productionEvent` exists. Placements persist as `capacityReservation` rows (a materialized output: delete-by-job + bulk insert per run, `scenarioId IS NULL`; `WorkCenter` + `Employee` kinds — `OperatorPool` is read-tolerated legacy, never written); the run also writes `job.projectedCompletionAt` (forecast finish) and clears the job's schedule-outdated stamps. **Dual dates** (`20260818031629_dual-dates.sql`, spec `.ai/specs/2026-08-15-dual-dates-due-vs-projected.md`): every regen writes each op's forward projection — `startDate` (projected start day) + `jobOperation.projectedCompletionAt` (projected finish instant) — and DIFF-writes `jobOperation.dueDate` from a backward demand-anchored need-by pass (`computeNeedByDates`, `packages/ee/src/planning/scheduling/need-by-calculator.ts` — a pure pre-placement step: reverse-topo from `job.dueDate`, `operationLeadTime` + assembly lead times, day lengths from the work centers' real calendars). Targets NEVER floor placement; `manuallyScheduled` = a human owns the need-by (the pin is taken as-is, propagates upstream, and is never overwritten — pinned ops still place normally; the old frozen-window branch is gone). An op projected past its need-by gets an informational amber behind-target state (BOP rows, ops-board `ItemCard`, MES operation detail) — never per-op `hasConflict`; when the job is late, the cause sentence appends "First behind target: {op} (due X, projected Y)". `jobOperation.priority` = the per-work-center placement order (reservation start ascending) — one source of truth for dispatch order (there is no configurable dispatch-sequencing policy). **People assignments** (manning board, `peopleAssignment`) make a staffed station a TEAM: the station still runs ONE op at a time, but the whole team present is booked on that op together — labor is parallelized across the present people (two people halve the labor wall-clock; setup and machine time are never compressed). Gated ops team-book people∩qualified on their assigned dates, falling back to an any-qualified single-person relay — but the board is a COMMITMENT, not a soft preference: the fallback may only draw on true FLOATERS (people with NO board assignment anywhere in the horizon, via `assignmentsByEmployee.has(id)`). A person you have manned anywhere is spoken for and is never pulled to a station they weren't assigned to — so moving your only welder off a station makes that station's op an unschedulable placeholder (visible on the Forecast) rather than silently double-booking the welder or shoving the op onto an unmanned weekend. A blank board leaves every qualified person a floater ⇒ classic any-qualified fallback, unchanged. Ungated ops at a staffed station are manned the same way with machine-only fallback. **Require-staffing policy** (`location.requiresStaffing`, per-location, default off, edited on the Production settings page (Settings → Production → Scheduling)): when ON, the scheduler places work ONLY where an operator is manned — the gated floater fallback and the ungated machine-only fallback are both removed, EXCEPT lights-out (`workCenter.alwaysOn`) stations keep running unattended. An op with no manned coverage (and not lights-out) becomes an unschedulable placeholder, so work routes to the staffed work centers and unstaffed ones get nothing. Threaded through `provider.getLocationRequiresStaffing` + `getAlwaysOnWorkCenterIds` → `FiniteSchedulingContext.requiresStaffing` + `capacity.workCenter.alwaysOn`. `peopleAbsence` subtracts the person's availability for that date everywhere; `peopleAssignment.overtimeHours` lengthens the person's day (window extension) and `peopleAssignment.hours` splits deal the day out per station sequentially — all as pure window edits before allocation. A blank board changes nothing. To reschedule, call `notifyScheduleInputsChanged` (stamps jobs; the debounced wave regenerates the whole location) — never direct date writes. An expedite what-if (`expediteJobId`) re-runs the sim with one job first, simulate-only, and returns its projected completion.- **Ability requirements** — resolved through the operation's PROCESS: `process.requiresAbility` → the ability linked 1:1 to the process (`ability.processId`) → **presence-based** `employeeAbility` qualification (a row exists ∧ not expired; no `active`/`trainingCompleted` gate). Gates both the scheduler's operator pools and MES operation start. There are no operation-level ability tables.+### Job completion++`complete_job_to_inventory` (SQL, `20260914095239_complete-job-received-quantity.sql`) is the single choke point: the ERP complete route, the API/MCP `completeJob` tool and the `sync_finish_job_operation` trigger interceptor all go through it.++- `p_quantity_complete` is **CUMULATIVE**, not this completion's delta. The function receives `p_quantity_complete - job.quantityReceivedToInventory` and stores the cumulative value back, because `get_inventory_quantities` computes on-production supply as production + scrap − received − shipped. `backflush_job_materials` takes the same cumulative number and is idempotent, so a re-completion at the received quantity receives nothing and consumes nothing.+- It **refuses** a quantity ≤ 0 or below what was already received (stocked items), and a fractional quantity on a serial job. Those raises reach the `jobOperation` UPDATE when they happen under the trigger — `sync_finish_job_operation` therefore clamps with `GREATEST(computed, received)` before calling.+- The serial branch receives the delta one numbered unit at a time — shop-floor-finished (`Available`) first, then by `readableId` — skipping `Consumed`/`Rejected`/`Scrapped` and any unit with a `Job Receipt` ledger row for this job, so re-completion never double-receives. An item with **no serial sequence** never reaches `assign-serial-numbers`, so its job keeps one whole-quantity seed entity and the delta is received against that seed instead.+- Dialog logic lives in `ui/Jobs/job-complete-logic.ts` (pure, no JSX/lingui, unit-tested by `apps/erp/test/job-complete-logic.test.ts`); the SQL is covered by `packages/database/supabase/tests/job-completion-received-quantity.test.sql`, hand-run like its siblings (nothing in CI runs `supabase/tests/`).+## Safety### Always@@ -82,6 +91,7 @@ pnpm --filter @carbon/erp test- `getJobPromiseDate` — promise date = `job.projectedCompletionAt` (forward-ASAP forecast finish), null before the first regen (no operation-date fallback — `jobOperation.dueDate` is the backward need-by target, so max(op.dueDate) would just echo the job due date); returns the §7 `{ promiseDate, basis: "schedule", confidence }` contract (`confidence` "low" when the job has a conflicted op or a `scheduleOutdatedReason`, else "scheduled")- `runMRP(client, db, params)` — triggers Material Requirements Planning **in-process** via `runMrp` from `@carbon/ee/planning`; the route action passes the Kysely handle (`getDatabaseClient()` from `~/services/database.server`) — it is NEVER constructed in this service file (which is bundled for the browser via the module barrel; enforced by the `no-db-client-in-service` conformance check). `recalculateJobOperationDependencies(client, db, params)` and `getJobExpediteForecast(client, db, …)` take the handle the same way. Formerly the `mrp` Deno edge function; preserves the `{ data, error }` shape- `calculateJobPriority` — computes priority from deadline type and due date+- `getJobReceiptSnapshot(db, jobId, companyId)` — a job's `quantityReceivedToInventory` plus the `trackedEntity` ids its `Job Receipt` ledger rows already posted, in ONE statement so the two can never come from different moments. Kysely because `itemLedger` is RLS-hidden from users without inventory/accounting view. Served by `api/production/job/:jobId/receipts`, read when the Complete dialog opens- `getActiveJobOperationsByLocation` — schedule board data (RPC `get_active_job_operations_by_location`, now also returns `processBatchable`/`jobOperationBatchId`/`batchReadableId`)- `getBatchableOperations` / `getBatchableProcesses` — batch builder candidate data (RPC `get_batchable_operations` with per-op BOM material properties), served via `api/production/batchable-operations`. `getBatchableProcesses` also selects `batchRules` so the builder can resolve per-process compatibility rules- `createJobOperationBatch` / `updateJobOperationBatch` — operation batch mutations (invoke the `batch-operations` edge function: create/add/remove/update/dissolve)diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 14247102e2..bab1f450db 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -2508,6 +2508,40 @@ export async function getTrackedEntitiesByJobId(.is("attributes ->> Split From Entity ID", null);}+/**+ * What a job has already received to inventory: its received quantity and the+ * tracked entities its receipts posted. One statement, so both come from the+ * same snapshot and a receipt committing mid-read cannot pair a new quantity+ * with old units. Kysely because itemLedger is readable only with inventory or+ * accounting view, and production users need the answer; the route authorizes.+ */+export async function getJobReceiptSnapshot(+ db: Kysely<KyselyDatabase>,+ jobId: string,+ companyId: string+) {+ return db+ .selectFrom("job")+ .leftJoin("itemLedger", (join) =>+ join+ .onRef("itemLedger.documentId", "=", "job.id")+ .onRef("itemLedger.companyId", "=", "job.companyId")+ .on("itemLedger.documentType", "=", "Job Receipt")+ )+ .select([+ "job.quantityReceivedToInventory",+ sql<+ string[]+ >`COALESCE(array_agg("itemLedger"."trackedEntityId") FILTER (WHERE "itemLedger"."trackedEntityId" IS NOT NULL), '{}')`.as(+ "trackedEntityIds"+ )+ ])+ .where("job.id", "=", jobId)+ .where("job.companyId", "=", companyId)+ .groupBy(["job.id", "job.companyId"])+ .executeTakeFirst();+}+/*** Reschedule a job using the unified scheduling engine.* This recalculates dates, work centers, and priorities for all operations.diff --git a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsxindex fb4c17fbc9..959ac93207 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx@@ -88,6 +88,12 @@ import { isJobLocked, jobCompleteValidator } from "../../production.models";import { getJobMethodTree } from "../../production.service";import type { Job } from "../../types";import JobStatus from "./JobStatus";+import {+ getDefaultSerialCompleteQuantity,+ getFinishedUnreceivedQuantity,+ getReceivableSerialUnits,+ type JobReceiptSnapshot+} from "./job-complete-logic";const JobHeader = () => {const navigate = useNavigate();@@ -1114,6 +1120,24 @@ function JobExpediteModal({);}+// What the job has received as of now, from api+/production.job.$jobId.receipts.+// Null when it cannot be read; the dialog then keeps the quantity locked rather+// than offering units it cannot prove are unreceived.+async function getJobReceipts(+ jobId: string+): Promise<JobReceiptSnapshot | null> {+ try {+ const response = await fetch(path.to.api.jobReceipts(jobId));+ if (!response.ok) return null;+ const body = (await response.json()) as {+ receipts: JobReceiptSnapshot | null;+ };+ return body.receipts;+ } catch {+ return null;+ }+}+function JobCompleteModal({job,onClose,@@ -1134,6 +1158,20 @@ function JobCompleteModal({job?.quantityComplete ?? 0);const [hasTrackedQuantity, setHasTrackedQuantity] = useState<boolean>(false);+ // Serial units the completion can still receive, in the order+ // complete_job_to_inventory receives them. Null when the quantity is not+ // chosen per serial unit.+ const [receivableSerials, setReceivableSerials] = useState<string[] | null>(+ null+ );+ // The completed quantity is cumulative; this much was already received.+ // Refreshed when the dialog opens, since the route's job may be stale.+ const [priorReceivedQuantity, setPriorReceivedQuantity] = useState<number>(+ job?.quantityReceivedToInventory ?? 0+ );+ // complete_job_to_inventory refuses a stocked job below what it received.+ const minimumQuantityComplete =+ job?.itemTrackingType !== "Non-Inventory" ? priorReceivedQuantity : 0;// Leftover handling stateconst [leftoverAction, setLeftoverAction] = useState<@@ -1146,11 +1184,16 @@ function JobCompleteModal({const makeToOrder = !!job?.salesOrderId && !!job?.salesOrderLineId;const leftoverQuantity = Math.max(0, quantityComplete - (job?.quantity ?? 0));const hasLeftover = leftoverQuantity > 0;+ // Serial units are received one at a time; the database refuses a fraction.+ const hasFractionalSerialQuantity =+ receivableSerials !== null &&+ Number.isFinite(quantityComplete) &&+ !Number.isInteger(quantityComplete);const getJobData = async () => {if (!carbon) return;- const [pickMethod, makeMethod] = await Promise.all([+ const [pickMethod, makeMethod, receipts] = await Promise.all([carbon.from("pickMethod").select("*")@@ -1162,9 +1205,20 @@ function JobCompleteModal({.select("*").eq("jobId", job?.id!).is("parentMaterialId", null)- .single()+ .single(),+ getJobReceipts(job?.id!)]);+ // Read now rather than from the job route: a receipt may have been made+ // since the page loaded. When the read fails, fall back to the route's job+ // and leave the quantity locked below — offering units that may already be+ // received is the one thing this must not do. complete_job_to_inventory+ // enforces both regardless.+ const currentReceivedQuantity =+ receipts?.quantityReceivedToInventory ??+ job?.quantityReceivedToInventory ??+ 0;+if (makeMethod.data?.requiresSerialTracking ||makeMethod.data?.requiresBatchTracking@@ -1183,11 +1237,39 @@ function JobCompleteModal({return acc;}, 0);- setQuantityComplete(availableQuantity);- setHasTrackedQuantity(true);+ const receivedEntityIds = new Set(receipts?.trackedEntityIds ?? []);+ // Only unlock per-serial entry when the receipts are known: without them+ // the list could offer a unit the job already received.+ const serialUnits =+ receipts && makeMethod.data?.requiresSerialTracking+ ? getReceivableSerialUnits(trackedEntities.data, receivedEntityIds)+ : null;++ if (serialUnits) {+ // Every unit already exists as a numbered serial, so the quantity can+ // be chosen here even when nothing was finished on the shop floor.+ setReceivableSerials(serialUnits);+ setHasTrackedQuantity(false);+ setQuantityComplete(+ getDefaultSerialCompleteQuantity({+ finishedUnreceivedQuantity: getFinishedUnreceivedQuantity(+ trackedEntities.data,+ receivedEntityIds+ ),+ jobQuantity: job?.quantity ?? 0,+ priorReceivedQuantity: currentReceivedQuantity,+ receivableSerialCount: serialUnits.length+ })+ );+ } else {+ setQuantityComplete(availableQuantity);+ setHasTrackedQuantity(true);+ }}}+ setPriorReceivedQuantity(currentReceivedQuantity);+flushSync(() => {setDefaultStorageUnitId(pickMethod.data?.defaultStorageUnitId ?? undefined@@ -1302,13 +1384,58 @@ function JobCompleteModal({value={quantityComplete}onChange={(value) => setQuantityComplete(value)}isDisabled={hasTrackedQuantity}+ minValue={minimumQuantityComplete}+ maxValue={+ receivableSerials+ ? priorReceivedQuantity + receivableSerials.length+ : undefined+ }helperText={hasTrackedQuantity? t`Quantity is derived from completed serials/batches in MES and cannot be edited.`- : undefined+ : hasFractionalSerialQuantity+ ? t`Serial-tracked jobs must be completed in whole units.`+ : undefined}/>+ {hasTrackedQuantity && !(quantityComplete > 0) && (+ <Alert variant="warning">+ <LuTriangleAlert />+ <AlertTitle>+ <Trans>Nothing completed in MES yet</Trans>+ </AlertTitle>+ <AlertDescription>+ <Trans>+ Complete serials/batches in MES before completing this+ job, or mark every operation Done to complete it+ automatically.+ </Trans>+ </AlertDescription>+ </Alert>+ )}++ {receivableSerials &&+ quantityComplete > priorReceivedQuantity &&+ !hasFractionalSerialQuantity && (+ <VStack spacing={1} className="w-full">+ <span className="text-xs text-muted-foreground">+ <Trans>Serial numbers received</Trans>+ </span>+ <span className="text-sm">+ {receivableSerials+ .slice(+ 0,+ Math.max(+ quantityComplete - priorReceivedQuantity,+ 0+ )+ )+ .join(", ")}+ </span>+ </VStack>+ )}+{hasLeftover && (<><Alert>@@ -1447,7 +1574,17 @@ function JobCompleteModal({<Trans>Cancel</Trans></Button>- <Button type="submit" isDisabled={hasLeftover && !leftoverAction}>+ <Button+ type="submit"+ isDisabled={+ (hasLeftover && !leftoverAction) ||+ // Completing a stocked item at zero receives nothing and+ // consumes nothing; the database refuses it as well.+ (job.itemTrackingType !== "Non-Inventory" &&+ !(quantityComplete > 0)) ||+ hasFractionalSerialQuantity+ }+ ><Trans>Complete Job</Trans></Button></ModalFooter>diff --git a/apps/erp/app/modules/production/ui/Jobs/job-complete-logic.ts b/apps/erp/app/modules/production/ui/Jobs/job-complete-logic.tsnew file mode 100644index 0000000000..c12d8b9a0e--- /dev/null+++ b/apps/erp/app/modules/production/ui/Jobs/job-complete-logic.ts@@ -0,0 +1,109 @@+// Pure logic for the job Complete dialog. No JSX or lingui, so it can be unit+// tested directly (apps/erp/test/job-complete-logic.test.ts).+//+// The completed quantity is CUMULATIVE: complete_job_to_inventory receives the+// difference between it and what the job has already received. Everything here+// works on the units the job has not received yet, so the dialog and the+// database always agree on which units a completion takes.++export type JobSerialUnit = {+ id: string;+ status: string;+ quantity: number;+ readableId: string | null;+ createdAt: string;+};++/** What a job has received to inventory, from api+/production.job.$jobId.receipts. */+export type JobReceiptSnapshot = {+ quantityReceivedToInventory: number;+ trackedEntityIds: string[];+};++const NON_RECEIVABLE_SERIAL_STATUSES = ["Consumed", "Rejected", "Scrapped"];++function isUnreceived(+ entity: JobSerialUnit,+ receivedEntityIds: ReadonlySet<string>+) {+ return (+ !NON_RECEIVABLE_SERIAL_STATUSES.includes(entity.status) &&+ !receivedEntityIds.has(entity.id)+ );+}++/**+ * The serial numbers a job completion can still receive, in the order+ * complete_job_to_inventory receives them: units finished on the shop floor+ * (Available) first, then reserved units, each by serial number. Units the job+ * already received are excluded.+ *+ * Returns null unless every unit left to receive is a numbered, single-unit+ * serial. A job still holding an unsplit seed entity has no serial numbers to+ * receive yet, so its quantity stays locked to what the shop floor finished.+ */+export function getReceivableSerialUnits(+ trackedEntities: JobSerialUnit[],+ receivedEntityIds: ReadonlySet<string> = new Set()+): string[] | null {+ const receivable = trackedEntities.filter((entity) =>+ isUnreceived(entity, receivedEntityIds)+ );++ // Stricter than complete_job_to_inventory on purpose: the database also+ // receives a single-unit serial with no serial number (a one-unit job with no+ // serial sequence), but the dialog only unlocks when it can name every unit it+ // lists. Such a job still completes through the locked path or by marking its+ // operations Done.+ if (+ receivable.length === 0 ||+ receivable.some((entity) => entity.quantity !== 1 || !entity.readableId)+ ) {+ return null;+ }++ const statusRank = (status: string) =>+ status === "Available" ? 0 : status === "Reserved" ? 1 : 2;++ return [...receivable]+ .sort(+ (a, b) =>+ statusRank(a.status) - statusRank(b.status) ||+ a.readableId!.localeCompare(b.readableId!)+ )+ .map((entity) => entity.readableId as string);+}++/** Units finished on the shop floor that the job has not received yet. */+export function getFinishedUnreceivedQuantity(+ trackedEntities: JobSerialUnit[],+ receivedEntityIds: ReadonlySet<string> = new Set()+): number {+ return trackedEntities.filter(+ (entity) =>+ entity.status === "Available" && !receivedEntityIds.has(entity.id)+ ).length;+}++/**+ * The cumulative quantity the dialog opens at for a job whose serial units are+ * numbered: what the job already received, plus the units finished on the shop+ * floor, or else the rest of the job quantity, never more than can be received.+ */+export function getDefaultSerialCompleteQuantity({+ finishedUnreceivedQuantity,+ jobQuantity,+ priorReceivedQuantity,+ receivableSerialCount+}: {+ finishedUnreceivedQuantity: number;+ jobQuantity: number;+ priorReceivedQuantity: number;+ receivableSerialCount: number;+}): number {+ const newUnits =+ finishedUnreceivedQuantity > 0+ ? finishedUnreceivedQuantity+ : Math.max(jobQuantity - priorReceivedQuantity, 0);+ return priorReceivedQuantity + Math.min(newUnits, receivableSerialCount);+}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.jsonindex 7449644bc6..0ac8e9e515 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -1,5 +1,5 @@{- "totalTools": 1553,+ "totalTools": 1554,"modules": 15,"tools": [{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},@@ -717,6 +717,7 @@{"name":"production_getJobOrderStatusMap","classification":"READ","paramCount":4,"schema":"ff6a888f05b8","response":"3f77244fd820","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getJobPromiseDate","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"f6521bc077a4","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getJobPurchaseOrderLines","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"309dea2a265c","injectAuth":"companyId","permission":"production:view","paginates":false},+ {"name":"production_getJobReceiptSnapshot","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"af63ddd51939","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getJobs","classification":"READ","paramCount":1,"schema":"75e0e9e0be40","response":"630059095fdc","injectAuth":"companyId","permission":"production:view","paginates":true},{"name":"production_getJobsByDateRange","classification":"READ","paramCount":3,"schema":"00794c516592","response":"737259a0d747","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getJobsBySalesOrderLine","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"630059095fdc","injectAuth":"companyId","permission":"production:view","paginates":false},diff --git a/apps/erp/app/routes/api+/production.job.$jobId.receipts.ts b/apps/erp/app/routes/api+/production.job.$jobId.receipts.tsnew file mode 100644index 0000000000..dd14528962--- /dev/null+++ b/apps/erp/app/routes/api+/production.job.$jobId.receipts.ts@@ -0,0 +1,39 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import type { LoaderFunctionArgs } from "react-router";+import { getJobReceiptSnapshot } from "~/modules/production";+import { getDatabaseClient } from "~/services/database.server";++/**+ * What a job has already received to inventory, read when the Complete dialog+ * opens so a receipt made while the job page was open is not missed. The+ * quantity and the received units come from one statement, so the dialog never+ * pairs values from different moments. Read past RLS: itemLedger is hidden from+ * users without inventory or accounting view, and the dialog would otherwise+ * offer received units again.+ *+ * A query failure throws rather than answering `null`: the dialog's fallback is+ * to lock the quantity, and a permanent failure that looks like a transient one+ * is the harder bug to find.+ */+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { companyId } = await requirePermissions(request, {+ view: "production"+ });++ const { jobId } = params;+ if (!jobId) throw new Error("Could not find jobId");++ const job = await getJobReceiptSnapshot(+ getDatabaseClient(),+ jobId,+ companyId+ );+ if (!job) return { receipts: null };++ return {+ receipts: {+ quantityReceivedToInventory: job.quantityReceivedToInventory ?? 0,+ trackedEntityIds: job.trackedEntityIds+ }+ };+}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex cd6a51862b..60e9489e35 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -156,6 +156,8 @@ export const path = {generatePath(`${api}/production/methods/${id}/bom.csv?withOperations=${withOperations}`),+ jobReceipts: (jobId: string) =>+ generatePath(`${api}/production/job/${jobId}/receipts`),jobSalesOrderLines: (jobId: string) =>generatePath(`${api}/production/job/${jobId}/sales-order-lines`),jobs: `${api}/production/jobs`,diff --git a/apps/erp/test/job-complete-logic.test.ts b/apps/erp/test/job-complete-logic.test.tsnew file mode 100644index 0000000000..233dc4bc59--- /dev/null+++ b/apps/erp/test/job-complete-logic.test.ts@@ -0,0 +1,163 @@+import { describe, expect, it } from "vitest";+// Import the logic module directly — the ERP barrels drag lingui macros vitest+// does not transform (see batching-migration-guards.test.ts).+import {+ getDefaultSerialCompleteQuantity,+ getFinishedUnreceivedQuantity,+ getReceivableSerialUnits,+ type JobSerialUnit+} from "../app/modules/production/ui/Jobs/job-complete-logic";++const unit = (overrides: Partial<JobSerialUnit>): JobSerialUnit => ({+ id: overrides.readableId ?? "unit",+ status: "Reserved",+ quantity: 1,+ readableId: null,+ createdAt: "2026-09-14T09:00:00.000Z",+ ...overrides+});++describe("getReceivableSerialUnits", () => {+ it("lists numbered units by serial number", () => {+ expect(+ getReceivableSerialUnits([+ unit({ readableId: "SN-0003" }),+ unit({ readableId: "SN-0001" }),+ unit({ readableId: "SN-0002" })+ ])+ ).toEqual(["SN-0001", "SN-0002", "SN-0003"]);+ });++ it("puts units finished on the shop floor first", () => {+ expect(+ getReceivableSerialUnits([+ unit({ readableId: "SN-0001" }),+ unit({ readableId: "SN-0002" }),+ unit({ readableId: "SN-0003", status: "Available" })+ ])+ ).toEqual(["SN-0003", "SN-0001", "SN-0002"]);+ });++ it("never offers consumed, rejected or scrapped units", () => {+ expect(+ getReceivableSerialUnits([+ unit({ readableId: "SN-0001", status: "Consumed" }),+ unit({ readableId: "SN-0002", status: "Rejected" }),+ unit({ readableId: "SN-0003", status: "Scrapped" }),+ unit({ readableId: "SN-0004" })+ ])+ ).toEqual(["SN-0004"]);+ });++ it("never offers units the job already received", () => {+ expect(+ getReceivableSerialUnits(+ [+ unit({ readableId: "SN-0001", status: "Available" }),+ unit({ readableId: "SN-0002", status: "Available" }),+ unit({ readableId: "SN-0003" })+ ],+ new Set(["SN-0001"])+ )+ ).toEqual(["SN-0002", "SN-0003"]);+ });++ it("keeps the quantity locked when a unit has no serial number yet", () => {+ expect(+ getReceivableSerialUnits([+ unit({ readableId: "SN-0001" }),+ unit({ readableId: null })+ ])+ ).toBeNull();+ });++ it("keeps the quantity locked for an unsplit seed entity", () => {+ expect(+ getReceivableSerialUnits([unit({ readableId: "SN-0001", quantity: 3 })])+ ).toBeNull();+ });++ it("returns null when nothing is left to receive", () => {+ expect(+ getReceivableSerialUnits([unit({ readableId: "SN-0001", status: "Consumed" })])+ ).toBeNull();+ expect(+ getReceivableSerialUnits(+ [unit({ readableId: "SN-0001", status: "Available" })],+ new Set(["SN-0001"])+ )+ ).toBeNull();+ });+});++describe("getFinishedUnreceivedQuantity", () => {+ it("counts units finished on the shop floor that were not received", () => {+ expect(+ getFinishedUnreceivedQuantity(+ [+ unit({ readableId: "SN-0001", status: "Available" }),+ unit({ readableId: "SN-0002", status: "Available" }),+ unit({ readableId: "SN-0003" })+ ],+ new Set(["SN-0001"])+ )+ ).toBe(1);+ });+});++describe("getDefaultSerialCompleteQuantity", () => {+ it("defaults to the units finished on the shop floor", () => {+ expect(+ getDefaultSerialCompleteQuantity({+ finishedUnreceivedQuantity: 1,+ jobQuantity: 3,+ priorReceivedQuantity: 0,+ receivableSerialCount: 3+ })+ ).toBe(1);+ });++ it("defaults to the job quantity when nothing was finished on the shop floor", () => {+ expect(+ getDefaultSerialCompleteQuantity({+ finishedUnreceivedQuantity: 0,+ jobQuantity: 3,+ priorReceivedQuantity: 0,+ receivableSerialCount: 3+ })+ ).toBe(3);+ });++ it("never defaults above the units that can be received", () => {+ expect(+ getDefaultSerialCompleteQuantity({+ finishedUnreceivedQuantity: 0,+ jobQuantity: 5,+ priorReceivedQuantity: 0,+ receivableSerialCount: 2+ })+ ).toBe(2);+ });++ it("adds new units on top of what a partial completion already received", () => {+ expect(+ getDefaultSerialCompleteQuantity({+ finishedUnreceivedQuantity: 0,+ jobQuantity: 3,+ priorReceivedQuantity: 2,+ receivableSerialCount: 1+ })+ ).toBe(3);+ });++ it("adds newly finished units on top of what was already received", () => {+ expect(+ getDefaultSerialCompleteQuantity({+ finishedUnreceivedQuantity: 1,+ jobQuantity: 3,+ priorReceivedQuantity: 2,+ receivableSerialCount: 1+ })+ ).toBe(3);+ });+});diff --git a/packages/database/supabase/migrations/20260914095239_complete-job-received-quantity.sql b/packages/database/supabase/migrations/20260914095239_complete-job-received-quantity.sqlnew file mode 100644index 0000000000..8a2936d667--- /dev/null+++ b/packages/database/supabase/migrations/20260914095239_complete-job-received-quantity.sql@@ -0,0 +1,971 @@+-- Job completion receives exactly the completed quantity of a serial-tracked item.+--+-- Bug: for a serial-tracked made item, complete_job_to_inventory received one unit+-- per unconsumed job serial REGARDLESS of p_quantity_complete, and flipped every one+-- of them Available. Completing at 0 therefore put the unit in stock while+-- backflush_job_materials (prorated by the same quantity) consumed nothing, and+-- completing twice received the same serial twice.+--+-- Fix, serial branch only:+-- * receive exactly the newly completed units (p_quantity_complete minus what the+-- job already received), never a unit this job has already received;+-- * take units already finished on the shop floor (Available) first, then by+-- serial number; never a Consumed, Rejected or Scrapped unit;+-- * flip only the received units to Available;+-- * fall back to the whole-quantity seed entity when the item has no serial+-- sequence and its units were never split into numbered serials;+-- * refuse the completion when fewer units are left than are being completed.+-- The job row is locked first so two concurrent completions cannot compute the+-- same receipt delta.+-- Refuse a fractional completion quantity for serial-tracked items.+-- And refuse a completion quantity <= 0 for stocked items: receiving nothing while+-- marking the job Completed is how the unit/material mismatch arose. Non-Inventory+-- (service) completions keep their existing behavior. The fully-scrapped branch of+-- sync_finish_job_operation never calls this function and is unaffected.+--+-- Every stocked item, not only serial:+-- * refuse a cumulative quantity below what the job already received; the+-- negative delta otherwise posted a negative receipt, cost layer and WIP journal;+-- * a re-completion at the received quantity (zero delta) receives nothing and+-- leaves WIP posted since the last receipt in WIP for the next one, instead of+-- dividing that WIP by a zero quantity.+--+-- Recreated VERBATIM from its newest committed definition+-- (20260805023439_company-timezone-sql-functions.sql) apart from the guards, the+-- zero-delta skips and the serial branch.+--+-- sync_finish_job_operation is recreated from 20260727031247 so that marking the+-- last operation Done on a reopened job never asks for less than the job already+-- received.++CREATE OR REPLACE FUNCTION complete_job_to_inventory(+ p_job_id TEXT,+ p_quantity_complete NUMERIC,+ p_storage_unit_id TEXT DEFAULT NULL,+ p_location_id TEXT DEFAULT NULL,+ p_company_id TEXT DEFAULT NULL,+ p_user_id TEXT DEFAULT NULL+)+RETURNS VOID+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public+AS $$+DECLARE+ v_item_id TEXT;+ v_item_tracking_type "itemTrackingType";+ v_cogs_account TEXT;+ v_sales_order_line_id TEXT;+ v_line_quantity_complete NUMERIC;+ v_job_company_id TEXT;+ v_prior_quantity_received NUMERIC;+ v_quantity_received_to_inventory NUMERIC;+ v_job_id_readable TEXT;+ v_job_make_method RECORD;+ v_tracked_entity RECORD;+ v_accounting_enabled BOOLEAN;+ v_company_group_id TEXT;+ v_raw_materials_account TEXT;+ v_finished_goods_account TEXT;+ v_item_inventory_account TEXT;+ v_item_inventory_description TEXT;+ v_wip_account TEXT;+ v_labor_absorption_account TEXT;+ v_overhead_absorption_account TEXT;+ v_dimension_item_posting_group TEXT;+ v_dimension_item TEXT;+ v_dimension_location TEXT;+ v_dimension_cost_center TEXT;+ v_dimension_employee TEXT;+ v_event RECORD;+ v_duration_hours NUMERIC;+ v_rate NUMERIC;+ v_labor_cost NUMERIC;+ v_overhead_cost NUMERIC;+ v_event_reference TEXT;+ v_labor_journal_line_reference TEXT;+ v_labor_accounting_period_id TEXT;+ v_labor_journal_entry_id TEXT;+ v_labor_journal_id TEXT;+ v_labor_jl_id TEXT;+ v_accumulated_wip_cost NUMERIC;+ v_today DATE;+ v_journal_line_reference TEXT;+ v_accounting_period_id TEXT;+ v_journal_entry_id TEXT;+ v_journal_id TEXT;+ v_jl_ids TEXT[];+ v_new_per_unit_cost NUMERIC;+ v_costing_method TEXT;+ v_existing_unit_cost NUMERIC;+ v_item_posting_group_id TEXT;+ v_job_location_id TEXT;+ v_total_qty_on_hand NUMERIC;+ v_prior_qty NUMERIC;+ v_prior_value NUMERIC;+ v_new_unit_cost NUMERIC;+ v_serial_unit_ids TEXT[];+ v_company_today DATE := company_today(p_company_id);+BEGIN+ -- Never let a NULL user reach NOT NULL audit columns; fall back to the job creator+ p_user_id := COALESCE(p_user_id, (SELECT "createdBy" FROM "job" WHERE id = p_job_id));++ -- Fetch job details. The row lock makes a concurrent completion wait and then+ -- read this completion's cumulative quantity, so both cannot compute the same+ -- receipt delta.+ SELECT "itemId", "quantityReceivedToInventory", "jobId", "locationId", "salesOrderLineId", "companyId"+ INTO STRICT v_item_id, v_prior_quantity_received, v_job_id_readable, v_job_location_id, v_sales_order_line_id, v_job_company_id+ FROM "job"+ WHERE id = p_job_id+ FOR UPDATE;++ -- SECURITY DEFINER bypasses RLS: bind the call to the job's own company so a+ -- caller can never complete another tenant's job or post into a mismatched+ -- company's ledger/journal.+ IF p_company_id IS NULL OR v_job_company_id IS DISTINCT FROM p_company_id THEN+ RAISE EXCEPTION 'Job % does not belong to company %', p_job_id, COALESCE(p_company_id, '<null>');+ END IF;++ -- Non-Inventory items (services) never enter inventory+ SELECT "itemTrackingType"+ INTO v_item_tracking_type+ FROM "item"+ WHERE id = v_item_id+ AND "companyId" = p_company_id;++ -- A stocked item completed at zero marks the job Completed, receives nothing+ -- and backflushes nothing. Refuse it at the one function every completion path+ -- crosses (ERP complete route, API/MCP, sync_finish_job_operation).+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'+ AND COALESCE(p_quantity_complete, 0) <= 0 THEN+ RAISE EXCEPTION 'Quantity completed must be greater than 0 for job %', v_job_id_readable;+ END IF;++ -- Delta for this completion: drives the itemLedger/costLedger quantities and+ -- the WIP-discharge journal. The job column itself stores the CUMULATIVE+ -- quantity (get_inventory_quantities computes on-production supply as+ -- production + scrap - received - shipped, which requires cumulative).+ v_quantity_received_to_inventory := p_quantity_complete - COALESCE(v_prior_quantity_received, 0);++ -- Fetch jobMakeMethod for the top-level (no parentMaterialId)+ SELECT *+ INTO STRICT v_job_make_method+ FROM "jobMakeMethod"+ WHERE "jobId" = p_job_id+ AND "parentMaterialId" IS NULL;++ -- Serial units are received one tracked entity at a time, so a fractional+ -- quantity cannot be honoured; it would be stored on the job and rounded by+ -- the receipt.+ IF v_job_make_method."requiresSerialTracking"+ AND p_quantity_complete <> trunc(p_quantity_complete) THEN+ RAISE EXCEPTION 'Quantity completed must be a whole number for serial-tracked job %', v_job_id_readable;+ END IF;++ -- The quantity is cumulative, so a stocked job cannot be completed at less than+ -- it has already received: the negative delta would post a negative receipt,+ -- cost layer and WIP journal. Received stock is corrected through inventory+ -- adjustments, not by re-completing the job. Non-Inventory jobs never receive.+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'+ AND p_quantity_complete < COALESCE(v_prior_quantity_received, 0) THEN+ RAISE EXCEPTION 'Quantity completed cannot be lower than the % already received for job %',+ COALESCE(v_prior_quantity_received, 0), v_job_id_readable;+ END IF;++ -- Update job status. quantityReceivedToInventory is CUMULATIVE (not the+ -- delta): re-completions previously overwrote it with the delta, corrupting+ -- get_inventory_quantities' on-production supply math. Non-Inventory items+ -- never receive to inventory, so their value is left unchanged.+ UPDATE "job"+ SET status = 'Completed',+ "completedDate" = NOW(),+ "quantityComplete" = p_quantity_complete,+ "quantityReceivedToInventory" = CASE+ WHEN v_item_tracking_type = 'Non-Inventory' THEN v_prior_quantity_received+ ELSE p_quantity_complete+ END,+ "updatedAt" = NOW(),+ "updatedBy" = p_user_id+ WHERE id = p_job_id;++ -- Services never ship, so job completion is the fulfillment event: advance+ -- the linked sales-order line the way post-shipment does for physical lines.+ -- Lives HERE (not in app code) because completion has multiple entry points —+ -- the ERP complete route AND the sync_finish_job_operation interceptor that+ -- auto-completes when the last operation finishes. Recomputed from ALL jobs+ -- on the line, so it is idempotent and lot-split safe. Runs before the+ -- accounting-enabled / zero-WIP early returns.+ -- NARROWED: only genuine Service lines (salesOrderLineType = 'Service') fulfill+ -- by completion. They never receive a shipment line (the `create` edge fn skips+ -- salesOrderLineType='Service'), so completion is their only fulfillment event.+ -- A Non-Inventory *Part* (or Material/Tool/etc.) still ships via post-shipment and+ -- must NOT be auto-fulfilled here — that was marking SO lines "Shipped" with no shipment.+ IF v_item_tracking_type = 'Non-Inventory' AND v_sales_order_line_id IS NOT NULL+ AND EXISTS (+ SELECT 1 FROM "salesOrderLine" sol+ WHERE sol.id = v_sales_order_line_id+ AND sol."companyId" = p_company_id+ AND sol."salesOrderLineType" = 'Service'+ ) THEN+ SELECT COALESCE(SUM("quantityComplete"), 0)+ INTO v_line_quantity_complete+ FROM "job"+ WHERE "salesOrderLineId" = v_sales_order_line_id+ AND "companyId" = p_company_id+ AND status != 'Cancelled';++ UPDATE "salesOrderLine" sol+ SET "quantitySent" = v_line_quantity_complete,+ "sentComplete" = (COALESCE(sol."saleQuantity", 0) > 0 AND v_line_quantity_complete >= sol."saleQuantity"),+ "sentDate" = CASE+ WHEN COALESCE(sol."saleQuantity", 0) > 0+ AND v_line_quantity_complete >= sol."saleQuantity"+ AND sol."sentDate" IS NULL+ THEN v_company_today+ ELSE sol."sentDate"+ END,+ "updatedBy" = p_user_id,+ "updatedAt" = NOW()+ WHERE sol.id = v_sales_order_line_id+ AND sol."companyId" = p_company_id;+ END IF;++ -- Insert itemLedger entries based on tracking type.+ -- Non-Inventory items (services) never enter inventory, and a re-completion at+ -- the quantity already received has nothing new to receive.+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'+ AND v_quantity_received_to_inventory > 0 THEN+ IF v_job_make_method."requiresBatchTracking" THEN+ SELECT *+ INTO v_tracked_entity+ FROM "trackedEntity"+ WHERE attributes->>'Job Make Method' = v_job_make_method.id+ AND "companyId" = p_company_id+ AND status != 'Consumed'+ ORDER BY "createdAt" DESC+ LIMIT 1;++ IF v_tracked_entity.id IS NULL THEN+ RAISE EXCEPTION 'Tracked entity not found';+ END IF;++ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId",+ "trackedEntityId", "createdBy"+ ) VALUES (+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,+ v_tracked_entity.id, p_user_id+ );++ ELSIF v_job_make_method."requiresSerialTracking" THEN+ -- Receive exactly the newly completed units: units finished on the shop floor+ -- (Available) first, then by serial number. A unit this job already received+ -- is never received again, so re-completion cannot double-count. Rejected+ -- (failed inspection) and Scrapped units never enter stock. The candidates+ -- are locked so a concurrent completion cannot take the same units.+ v_serial_unit_ids := ARRAY(+ SELECT te.id+ FROM "trackedEntity" te+ WHERE te.attributes->>'Job Make Method' = v_job_make_method.id+ AND te."companyId" = p_company_id+ AND te.status NOT IN ('Consumed', 'Rejected', 'Scrapped')+ AND te.quantity = 1+ AND NOT EXISTS (+ SELECT 1+ FROM "itemLedger" il+ WHERE il."trackedEntityId" = te.id+ AND il."documentType" = 'Job Receipt'+ AND il."documentId" = p_job_id+ )+ ORDER BY+ CASE te.status WHEN 'Available' THEN 0 WHEN 'Reserved' THEN 1 ELSE 2 END,+ te."readableId" NULLS LAST,+ te."createdAt",+ te.id+ FOR UPDATE OF te+ );++ IF COALESCE(array_length(v_serial_unit_ids, 1), 0) >= v_quantity_received_to_inventory THEN+ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId",+ "trackedEntityId", "createdBy"+ )+ SELECT+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,+ v_item_id, 1, p_location_id, p_storage_unit_id,+ unit_id, p_user_id+ FROM unnest(v_serial_unit_ids[1:v_quantity_received_to_inventory::INTEGER]) AS unit_id;++ UPDATE "trackedEntity"+ SET status = 'Available'+ WHERE id = ANY(v_serial_unit_ids[1:v_quantity_received_to_inventory::INTEGER]);++ ELSE+ -- An item with no serial sequence never reaches assign-serial-numbers, so+ -- the job still holds ONE seed entity covering every unit and there is+ -- nothing to receive one at a time. Receive the delta against that seed,+ -- the way the batch branch does. Raising here instead would abort the+ -- jobOperation UPDATE itself: completion also runs inside+ -- sync_finish_job_operation, a BEFORE trigger interceptor.+ SELECT *+ INTO v_tracked_entity+ FROM "trackedEntity" te+ WHERE te.attributes->>'Job Make Method' = v_job_make_method.id+ AND te."companyId" = p_company_id+ AND te.status NOT IN ('Consumed', 'Rejected', 'Scrapped')+ AND te.quantity > 1+ ORDER BY te."createdAt"+ LIMIT 1+ FOR UPDATE;++ -- Genuinely short of units (some scrapped, some already received) rather+ -- than un-numbered: receiving fewer than completed would leave the job's+ -- received quantity ahead of the ledger.+ IF v_tracked_entity.id IS NULL THEN+ RAISE EXCEPTION 'Job % has % serial unit(s) left to receive, fewer than the % being completed',+ v_job_id_readable, COALESCE(array_length(v_serial_unit_ids, 1), 0), v_quantity_received_to_inventory;+ END IF;++ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId",+ "trackedEntityId", "createdBy"+ ) VALUES (+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,+ v_tracked_entity.id, p_user_id+ );++ UPDATE "trackedEntity"+ SET status = 'Available'+ WHERE id = v_tracked_entity.id;+ END IF;++ ELSE+ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"+ ) VALUES (+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,+ p_user_id+ );+ END IF;+ END IF;++ -- Update pickMethod defaultStorageUnitId if needed+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' AND p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN+ IF NOT EXISTS (+ SELECT 1 FROM "itemLedger"+ WHERE "itemId" = v_item_id+ AND "locationId" = p_location_id+ AND "storageUnitId" IS NOT NULL+ AND "storageUnitId" != p_storage_unit_id+ LIMIT 1+ ) THEN+ IF EXISTS (+ SELECT 1 FROM "pickMethod"+ WHERE "itemId" = v_item_id AND "locationId" = p_location_id+ ) THEN+ UPDATE "pickMethod"+ SET "defaultStorageUnitId" = p_storage_unit_id,+ "updatedBy" = p_user_id,+ "updatedAt" = NOW()+ WHERE "itemId" = v_item_id+ AND "locationId" = p_location_id;+ ELSE+ INSERT INTO "pickMethod" (+ "itemId", "locationId", "defaultStorageUnitId",+ "companyId", "createdBy", "createdAt"+ ) VALUES (+ v_item_id, p_location_id, p_storage_unit_id,+ p_company_id, p_user_id, NOW()+ );+ END IF;+ END IF;+ END IF;++ -- Backflush unissued materials (delegated to shared function)+ PERFORM backflush_job_materials(p_job_id, p_quantity_complete, p_company_id, p_user_id);++ -- Check if accounting is enabled+ SELECT "accountingEnabled"+ INTO v_accounting_enabled+ FROM "companySettings"+ WHERE id = p_company_id;++ v_accounting_enabled := COALESCE(v_accounting_enabled, false);++ IF NOT v_accounting_enabled THEN+ RETURN;+ END IF;++ -- Fetch company group+ SELECT "companyGroupId"+ INTO STRICT v_company_group_id+ FROM company+ WHERE id = p_company_id;++ -- Fetch account defaults+ SELECT "rawMaterialsAccount", "finishedGoodsAccount", "workInProgressAccount", "laborAbsorptionAccount", "overheadAbsorptionAccount", "costOfGoodsSoldAccount"+ INTO STRICT v_raw_materials_account, v_finished_goods_account, v_wip_account, v_labor_absorption_account, v_overhead_absorption_account, v_cogs_account+ FROM "accountDefault"+ WHERE "companyId" = p_company_id;++ -- Resolve Raw Materials vs Finished Goods from the produced item:+ -- Buy → Raw Materials; Make / Buy and Make → Finished Goods.+ SELECT+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN v_raw_materials_account ELSE v_finished_goods_account END,+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN 'Raw Materials Account' ELSE 'Finished Goods Account' END+ INTO v_item_inventory_account, v_item_inventory_description+ FROM "item" i+ WHERE i."id" = v_item_id+ AND i."companyId" = p_company_id;++ -- Non-Inventory (Service): the produced output is never stocked, so completion+ -- relieves WIP straight to Cost of Goods Sold (Epicor "Make Direct" pattern).+ -- >>> REV-REC SEAM (spec .ai/specs/2026-07-04-revenue-recognition.md, issue #1048):+ -- when revenue recognition lands, Percent-of-Completion elements will gate THIS+ -- branch off and post COGS as-incurred in the recognition run instead. <<<+ IF v_item_tracking_type = 'Non-Inventory' THEN+ v_item_inventory_account := v_cogs_account;+ v_item_inventory_description := 'Cost of Goods Sold';+ END IF;++ -- Fetch dimension IDs+ SELECT+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),+ MAX(CASE WHEN "entityType" = 'Location' THEN id END),+ MAX(CASE WHEN "entityType" = 'CostCenter' THEN id END),+ MAX(CASE WHEN "entityType" = 'Employee' THEN id END)+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location,+ v_dimension_cost_center, v_dimension_employee+ FROM dimension+ WHERE "companyGroupId" = v_company_group_id+ AND active = true+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location', 'CostCenter', 'Employee');++ -- Post unposted production events as labor/machine + overhead absorption JEs+ -- (mirrors post-production-event; this is the catch-up path for events that+ -- were never posted individually)+ FOR v_event IN+ SELECT+ pe.id,+ pe.duration,+ pe.type,+ pe."employeeId",+ wc."laborRate",+ wc."machineRate",+ wc."overheadRate"+ FROM "productionEvent" pe+ INNER JOIN "jobOperation" jo ON jo.id = pe."jobOperationId"+ INNER JOIN "workCenter" wc ON wc.id = pe."workCenterId"+ WHERE jo."jobId" = p_job_id+ AND pe."endTime" IS NOT NULL+ AND pe."postedToGL" = false+ AND pe.duration > 0+ LOOP+ v_duration_hours := v_event.duration::NUMERIC / 3600;+ v_rate := CASE+ WHEN v_event.type = 'Machine' THEN COALESCE(v_event."machineRate", 0)+ ELSE COALESCE(v_event."laborRate", 0)+ END;+ v_labor_cost := v_duration_hours * v_rate;+ v_overhead_cost := v_duration_hours * COALESCE(v_event."overheadRate", 0);+ v_event_reference := 'production-event:' || v_event.id;++ IF (v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL)+ OR (v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL) THEN+ v_labor_journal_line_reference := nanoid();++ -- Get current accounting period+ SELECT id INTO v_labor_accounting_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = p_company_id+ AND "startDate" <= v_company_today+ AND "endDate" >= v_company_today+ AND status = 'Active'+ LIMIT 1;++ IF v_labor_accounting_period_id IS NULL THEN+ UPDATE "accountingPeriod"+ SET status = 'Inactive'+ WHERE status = 'Active' AND "companyId" = p_company_id;++ UPDATE "accountingPeriod"+ SET status = 'Active'+ WHERE "companyId" = p_company_id+ AND "startDate" <= v_company_today+ AND "endDate" >= v_company_today+ RETURNING id INTO v_labor_accounting_period_id;++ IF v_labor_accounting_period_id IS NULL THEN+ INSERT INTO "accountingPeriod" (+ "startDate", "endDate", "companyId", status, "createdBy"+ ) VALUES (+ date_trunc('month', v_company_today)::DATE,+ (date_trunc('month', v_company_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,+ p_company_id, 'Active', 'system'+ )+ RETURNING id INTO v_labor_accounting_period_id;+ END IF;+ END IF;++ v_labor_journal_entry_id := get_next_sequence('journalEntry', p_company_id);++ INSERT INTO journal (+ "journalEntryId", "accountingPeriodId", description,+ "postingDate", "companyId", "sourceType", status,+ "postedAt", "postedBy", "createdBy"+ ) VALUES (+ v_labor_journal_entry_id, v_labor_accounting_period_id,+ v_event.type || ' Time — Job ' || v_job_id_readable,+ v_company_today, p_company_id, 'Production Event', 'Posted',+ NOW(), p_user_id, p_user_id+ )+ RETURNING id INTO v_labor_journal_id;++ IF v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL THEN+ -- DR WIP (labor/machine)+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_labor_journal_id, v_wip_account, 'WIP Account',+ v_labor_cost, 1,+ 'Production Event', p_job_id, v_event_reference,+ v_labor_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ -- Employee dimension on WIP line+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id+ );+ END IF;++ -- Item dimension on WIP line (the finished good this labor rolls into)+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id+ );+ END IF;++ -- CR Labor/Machine Absorption+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_labor_journal_id, v_labor_absorption_account, 'Labor/Machine Absorption',+ -v_labor_cost, 1,+ 'Production Event', p_job_id, v_event_reference,+ v_labor_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ -- Employee dimension on absorption line+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id+ );+ END IF;++ -- Item dimension on absorption line+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id+ );+ END IF;+ END IF;++ IF v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL THEN+ -- DR WIP (overhead)+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_labor_journal_id, v_wip_account, 'WIP Account (Overhead)',+ v_overhead_cost, 1,+ 'Production Event', p_job_id, v_event_reference,+ v_labor_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ -- Employee dimension on WIP overhead line+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id+ );+ END IF;++ -- Item dimension on WIP overhead line+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id+ );+ END IF;++ -- CR Overhead Absorption+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_labor_journal_id, v_overhead_absorption_account, 'Overhead Absorption',+ -v_overhead_cost, 1,+ 'Production Event', p_job_id, v_event_reference,+ v_labor_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ -- Employee dimension on overhead absorption line+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id+ );+ END IF;++ -- Item dimension on overhead absorption line+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id+ );+ END IF;+ END IF;+ END IF;++ UPDATE "productionEvent"+ SET "postedToGL" = true+ WHERE id = v_event.id;+ END LOOP;++ -- Calculate accumulated WIP cost for this job+ SELECT COALESCE(ABS(SUM(jl.amount)), 0)+ INTO v_accumulated_wip_cost+ FROM "journalLine" jl+ INNER JOIN journal j ON j.id = jl."journalId"+ WHERE jl."accountId" = v_wip_account+ AND jl."documentId" = p_job_id+ AND j."companyId" = p_company_id;++ IF v_accumulated_wip_cost <= 0 THEN+ RETURN;+ END IF;++ -- A stocked re-completion at the quantity already received has no units to+ -- carry this cost. The catch-up WIP above stays in WIP and is discharged with+ -- the next receipt; the per-unit cost below would otherwise divide by zero.+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'+ AND v_quantity_received_to_inventory <= 0 THEN+ RETURN;+ END IF;++ v_today := v_company_today;+ v_journal_line_reference := nanoid();++ -- Get accounting period for WIP discharge+ SELECT id INTO v_accounting_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = p_company_id+ AND "startDate" <= v_today+ AND "endDate" >= v_today+ AND status = 'Active'+ LIMIT 1;++ IF v_accounting_period_id IS NULL THEN+ UPDATE "accountingPeriod"+ SET status = 'Inactive'+ WHERE status = 'Active' AND "companyId" = p_company_id;++ UPDATE "accountingPeriod"+ SET status = 'Active'+ WHERE "companyId" = p_company_id+ AND "startDate" <= v_today+ AND "endDate" >= v_today+ RETURNING id INTO v_accounting_period_id;++ IF v_accounting_period_id IS NULL THEN+ INSERT INTO "accountingPeriod" (+ "startDate", "endDate", "companyId", status, "createdBy"+ ) VALUES (+ date_trunc('month', v_today)::DATE,+ (date_trunc('month', v_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,+ p_company_id, 'Active', 'system'+ )+ RETURNING id INTO v_accounting_period_id;+ END IF;+ END IF;++ v_journal_entry_id := get_next_sequence('journalEntry', p_company_id);++ INSERT INTO journal (+ "journalEntryId", "accountingPeriodId", description,+ "postingDate", "companyId", "sourceType", status,+ "postedAt", "postedBy", "createdBy"+ ) VALUES (+ v_journal_entry_id, v_accounting_period_id,+ 'Job Completion ' || v_job_id_readable,+ v_today, p_company_id, 'Job Receipt', 'Posted',+ NOW(), p_user_id, p_user_id+ )+ RETURNING id INTO v_journal_id;++ -- DR Inventory (Raw Materials or Finished Goods by item)+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_journal_id, v_item_inventory_account, v_item_inventory_description,+ v_accumulated_wip_cost, v_quantity_received_to_inventory,+ 'Job Receipt', p_job_id, 'job:' || p_job_id,+ v_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ v_jl_ids := ARRAY[v_labor_jl_id];++ -- CR WIP+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_journal_id, v_wip_account, 'WIP Account',+ -v_accumulated_wip_cost, v_quantity_received_to_inventory,+ 'Job Receipt', p_job_id, 'job:' || p_job_id,+ v_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ v_jl_ids := v_jl_ids || v_labor_jl_id;++ -- Write costLedger entry for finished good (skipped for Non-Inventory: no+ -- output layer exists for a service — its cost went straight to COGS above)+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN+ INSERT INTO "costLedger" (+ "itemLedgerType", "costLedgerType", adjustment,+ "documentType", "documentId", "itemId",+ quantity, cost, "remainingQuantity", "companyId"+ ) VALUES (+ 'Output', 'Direct Cost', false,+ 'Job Receipt', p_job_id, v_item_id,+ v_quantity_received_to_inventory, v_accumulated_wip_cost,+ v_quantity_received_to_inventory, p_company_id+ );+ END IF;++ -- Update item cost+ SELECT "costingMethod", "unitCost", "itemPostingGroupId"+ INTO v_costing_method, v_existing_unit_cost, v_item_posting_group_id+ FROM "itemCost"+ WHERE "itemId" = v_item_id+ AND "companyId" = p_company_id;++ -- Update itemCost.unitCost (skipped for Non-Inventory: a service has no+ -- stocked unit cost; the read above still feeds the dimension inserts below)+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN+ v_new_per_unit_cost := v_accumulated_wip_cost / v_quantity_received_to_inventory;++ IF v_costing_method = 'Average' THEN+ SELECT COALESCE(SUM(quantity), 0)+ INTO v_total_qty_on_hand+ FROM "itemLedger"+ WHERE "itemId" = v_item_id+ AND "companyId" = p_company_id;++ v_prior_qty := v_total_qty_on_hand - v_quantity_received_to_inventory;+ v_prior_value := v_prior_qty * COALESCE(v_existing_unit_cost, 0);++ IF v_total_qty_on_hand > 0 THEN+ v_new_unit_cost := (v_prior_value + v_accumulated_wip_cost) / v_total_qty_on_hand;+ UPDATE "itemCost"+ SET "unitCost" = v_new_unit_cost+ WHERE "itemId" = v_item_id+ AND "companyId" = p_company_id;+ END IF;++ ELSIF v_costing_method IN ('FIFO', 'LIFO') THEN+ UPDATE "itemCost"+ SET "unitCost" = v_new_per_unit_cost+ WHERE "itemId" = v_item_id+ AND "companyId" = p_company_id;+ END IF;+ END IF;++ -- Insert dimensions on WIP discharge journal lines+ IF v_jl_ids IS NOT NULL AND array_length(v_jl_ids, 1) > 0 THEN+ FOR i IN 1..array_length(v_jl_ids, 1)+ LOOP+ IF v_item_posting_group_id IS NOT NULL AND v_dimension_item_posting_group IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_jl_ids[i], v_dimension_item_posting_group, v_item_posting_group_id, p_company_id+ );+ END IF;++ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_jl_ids[i], v_dimension_item, v_item_id, p_company_id+ );+ END IF;++ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id+ );+ END IF;+ END LOOP;+ END IF;+END;+$$;+++-- sync_finish_job_operation (fork of 20260727031247): never asks+-- complete_job_to_inventory for less than the job already received.+CREATE OR REPLACE FUNCTION sync_finish_job_operation(+ p_table TEXT,+ p_operation TEXT,+ p_new JSONB,+ p_old JSONB+)+RETURNS VOID+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public+AS $$+DECLARE+ v_job_location_id TEXT;+ v_job_storage_unit_id TEXT;+ v_job_quantity NUMERIC;+ v_sales_order_id TEXT;+ v_quantity_complete NUMERIC;+ v_quantity_lost NUMERIC;+ v_quantity_received NUMERIC;+ v_job_status TEXT;+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF (p_new->>'status') != 'Done' OR (p_old->>'status') = 'Done' THEN RETURN; END IF;++ UPDATE "productionEvent"+ SET "endTime" = NOW()+ WHERE "jobOperationId" = p_new->>'id'+ AND "endTime" IS NULL;++ UPDATE "jobOperation" op+ SET status = 'Ready'+ WHERE EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ WHERE dep."operationId" = op.id+ AND dep."dependsOnId" = p_new->>'id'+ AND op.status = 'Waiting'+ )+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep2+ JOIN "jobOperation" jo2 ON jo2.id = dep2."dependsOnId"+ WHERE dep2."operationId" = op.id+ AND jo2.status != 'Done'+ AND jo2.id != p_new->>'id'+ );++ SELECT status INTO v_job_status FROM "job" WHERE id = p_new->>'jobId';+ IF v_job_status NOT IN ('Ready', 'In Progress', 'Paused') THEN+ RETURN;+ END IF;++ IF is_last_job_operation(p_new->>'id') THEN+ SELECT "locationId", "storageUnitId", quantity, "salesOrderId", "quantityReceivedToInventory"+ INTO v_job_location_id, v_job_storage_unit_id, v_job_quantity, v_sales_order_id, v_quantity_received+ FROM "job"+ WHERE id = p_new->>'jobId';++ v_quantity_complete := (+ SELECT COALESCE(SUM(terminal_jo."quantityComplete"), 0)+ FROM "jobOperation" terminal_jo+ INNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"+ WHERE terminal_jo."jobId" = p_new->>'jobId'+ AND terminal_jmm."parentMaterialId" IS NULL+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"+ WHERE dep."dependsOnId" = terminal_jo.id+ AND child_jmm."parentMaterialId" IS NULL+ )+ );++ IF COALESCE(v_quantity_complete, 0) = 0 THEN+ -- The zero fallback exists for the quantity-less Finish flow (no+ -- productionQuantity ever recorded). When the job DID record scrap or+ -- rework, zero completions is a real outcome (e.g. a fully-scrapped+ -- lot) — falling back would receive scrapped units into stock.+ SELECT COALESCE(SUM(COALESCE("quantityScrapped", 0) + COALESCE("quantityReworked", 0)), 0)+ INTO v_quantity_lost+ FROM "jobOperation"+ WHERE "jobId" = p_new->>'jobId';++ IF v_quantity_lost = 0 THEN+ v_quantity_complete := v_job_quantity;+ ELSE+ -- Nothing to receive: close the job without posting Assembly Output.+ -- Materials were already consumed by the scrap/complete flows; WIP+ -- cost disposition for fully-scrapped jobs is a costing follow-up.+ UPDATE "job"+ SET status = 'Completed',+ "completedDate" = NOW(),+ "quantityComplete" = 0,+ "updatedBy" = COALESCE(p_new->>'updatedBy', p_new->>'createdBy'),+ "updatedAt" = NOW()+ WHERE id = p_new->>'jobId';+ RETURN;+ END IF;+ END IF;++ -- A reopened job may already have received more than its operations now+ -- report. complete_job_to_inventory refuses a quantity below what was+ -- received, and refusing here would block the Done update itself.+ v_quantity_complete := GREATEST(v_quantity_complete, COALESCE(v_quantity_received, 0));++ PERFORM complete_job_to_inventory(+ p_job_id := p_new->>'jobId',+ p_quantity_complete := v_quantity_complete,+ p_storage_unit_id := v_job_storage_unit_id,+ p_location_id := v_job_location_id,+ p_company_id := p_new->>'companyId',+ p_user_id := COALESCE(p_new->>'updatedBy', p_new->>'createdBy')+ );+ END IF;+END;+$$;diff --git a/packages/database/supabase/tests/job-completion-received-quantity.test.sql b/packages/database/supabase/tests/job-completion-received-quantity.test.sqlnew file mode 100644index 0000000000..1fcc8c6735--- /dev/null+++ b/packages/database/supabase/tests/job-completion-received-quantity.test.sql@@ -0,0 +1,297 @@+-- Job completion receives exactly the completed quantity (complete_job_to_inventory).+-- Isolated fixture company; no existing business data is read or edited. Always rolls back.+-- Run: pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -f packages/database/supabase/tests/job-completion-received-quantity.test.sql+\set ON_ERROR_STOP on+BEGIN;+SET LOCAL statement_timeout = '60s';++-- A job for p_item_id with p_quantity units. For a serial item, p_split splits+-- the job's serial placeholder into numbered single units (<job>-01, -02, ...),+-- as the item serial sequence does at job creation; otherwise the placeholder is+-- left as created. Every job consumes 2 of p_part_id per unit, pulled from+-- inventory.+CREATE FUNCTION pg_temp.make_job(+ p_company_id text, p_location_id text, p_item_id text, p_part_id text,+ p_readable_id text, p_quantity numeric, p_split boolean DEFAULT true+) RETURNS text LANGUAGE plpgsql AS $fn$+DECLARE+ v_job_id text;+ v_make_method_id text;+ v_seed record;+BEGIN+ INSERT INTO job ("jobId", "itemId", quantity, "locationId", "companyId", "createdBy", "unitOfMeasureCode")+ VALUES (p_readable_id, p_item_id, p_quantity, p_location_id, p_company_id, 'system', 'EA')+ RETURNING id INTO v_job_id;++ SELECT id INTO STRICT v_make_method_id+ FROM "jobMakeMethod" WHERE "jobId" = v_job_id AND "parentMaterialId" IS NULL;++ INSERT INTO "jobMaterial" ("jobId", "jobMakeMethodId", "itemId", description, "methodType",+ "itemType", quantity, "estimatedQuantity", "companyId", "createdBy")+ VALUES (v_job_id, v_make_method_id, p_part_id, 'Stocked part', 'Pull from Inventory',+ 'Part', 2, 2 * p_quantity, p_company_id, 'system');++ SELECT * INTO v_seed FROM "trackedEntity" WHERE attributes->>'Job Make Method' = v_make_method_id;+ IF v_seed.id IS NOT NULL AND p_split THEN+ UPDATE "trackedEntity" SET quantity = 1, "readableId" = p_readable_id || '-01' WHERE id = v_seed.id;+ FOR n IN 2..p_quantity::int LOOP+ INSERT INTO "trackedEntity" ("sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",+ quantity, status, "companyId", "createdBy", attributes, "itemId", "readableId")+ VALUES (v_seed."sourceDocument", v_seed."sourceDocumentId", v_seed."sourceDocumentReadableId",+ 1, 'Reserved', p_company_id, 'system', v_seed.attributes, v_seed."itemId",+ p_readable_id || '-' || lpad(n::text, 2, '0'));+ END LOOP;+ END IF;++ RETURN v_job_id;+END;+$fn$;++-- Completes the job; returns the error message, or NULL when it succeeded.+-- The exception block rolls a refused completion back, so state is unchanged.+CREATE FUNCTION pg_temp.try_complete(p_job_id text, p_quantity numeric) RETURNS text+LANGUAGE plpgsql AS $fn$+DECLARE v_job record;+BEGIN+ SELECT * INTO STRICT v_job FROM job WHERE id = p_job_id;+ PERFORM complete_job_to_inventory(p_job_id, p_quantity, NULL, v_job."locationId", v_job."companyId", 'system');+ RETURN NULL;+EXCEPTION WHEN OTHERS THEN+ RETURN SQLERRM;+END;+$fn$;++-- "<serial>:<status>:<units received>" for every serial on the job, by serial number.+CREATE FUNCTION pg_temp.serials(p_job_id text) RETURNS text LANGUAGE sql AS $fn$+ SELECT string_agg(COALESCE(te."readableId", 'unnumbered') || ':' || te.status || ':' ||+ COALESCE((SELECT sum(il.quantity) FROM "itemLedger" il+ WHERE il."trackedEntityId" = te.id AND il."documentType" = 'Job Receipt'+ AND il."documentId" = p_job_id), 0)::int,+ ',' ORDER BY te."readableId")+ FROM "trackedEntity" te+ JOIN "jobMakeMethod" m ON m.id = te.attributes->>'Job Make Method' AND m."parentMaterialId" IS NULL+ WHERE m."jobId" = p_job_id;+$fn$;++-- Rounded to the internal quantity scale: backflush prorates by a ratio such as+-- 2/3, which leaves float noise far below it.+CREATE FUNCTION pg_temp.issued(p_job_id text) RETURNS numeric LANGUAGE sql AS $fn$+ SELECT round(sum("quantityIssued"), 5) FROM "jobMaterial" WHERE "jobId" = p_job_id;+$fn$;++-- Marks a job operation Done; returns the error message, or NULL when it+-- succeeded. The Done update runs the sync_finish_job_operation interceptor.+CREATE FUNCTION pg_temp.try_finish_operation(p_operation_id text) RETURNS text+LANGUAGE plpgsql AS $fn$+BEGIN+ UPDATE "jobOperation" SET status = 'Done' WHERE id = p_operation_id;+ RETURN NULL;+EXCEPTION WHEN OTHERS THEN+ RETURN SQLERRM;+END;+$fn$;++-- Net WIP posted against a job.+CREATE FUNCTION pg_temp.wip(p_job_id text, p_wip_account text) RETURNS numeric LANGUAGE sql AS $fn$+ SELECT round(COALESCE(sum(amount), 0), 5) FROM "journalLine"+ WHERE "documentId" = p_job_id AND "accountId" = p_wip_account;+$fn$;++DO $cases$+DECLARE+ v_group_id text; v_company_id text; v_location_id text;+ v_serial_item text; v_stocked_item text; v_service_item text; v_part text;+ v_job text; v_error text; v_row record;+ v_process text; v_work_center text; v_operation text; v_defaults jsonb;+ v_wip_account text; v_finished_account text; v_labor_account text; v_other_account text;+ v_receipt_journals int; v_cost_layers int;+BEGIN+ INSERT INTO "companyGroup" (name, "createdBy") VALUES ('Job completion test', 'system') RETURNING id INTO v_group_id;+ INSERT INTO company (name, "companyGroupId", "baseCurrencyCode", timezone)+ VALUES ('Job completion test', v_group_id, 'USD', 'UTC') RETURNING id INTO v_company_id;+ INSERT INTO location (name, "addressLine1", city, "postalCode", "companyId", "createdBy", timezone)+ VALUES ('Plant', '1 Test Way', 'Testville', '00000', v_company_id, 'system', 'UTC') RETURNING id INTO v_location_id;+ INSERT INTO "unitOfMeasure" (code, name, "companyId", "createdBy")+ VALUES ('EA', 'Each', v_company_id, 'system') ON CONFLICT DO NOTHING;+ INSERT INTO item ("readableId", name, type, "replenishmentSystem", "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")+ VALUES ('T-SERIAL', 'Serial machine', 'Part', 'Make', 'Serial', 'EA', v_company_id, 'system') RETURNING id INTO v_serial_item;+ INSERT INTO item ("readableId", name, type, "replenishmentSystem", "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")+ VALUES ('T-STOCKED', 'Stocked assembly', 'Part', 'Make', 'Inventory', 'EA', v_company_id, 'system') RETURNING id INTO v_stocked_item;+ INSERT INTO item ("readableId", name, type, "replenishmentSystem", "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")+ VALUES ('T-SERVICE', 'Service', 'Part', 'Make', 'Non-Inventory', 'EA', v_company_id, 'system') RETURNING id INTO v_service_item;+ INSERT INTO item ("readableId", name, type, "replenishmentSystem", "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")+ VALUES ('T-PART', 'Stocked part', 'Part', 'Buy', 'Inventory', 'EA', v_company_id, 'system') RETURNING id INTO v_part;++ -- Serial job: refusals leave the job untouched.+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_serial_item, v_part, 'SJ', 3);+ v_error := pg_temp.try_complete(v_job, 0);+ ASSERT v_error LIKE 'Quantity completed must be greater than 0%', 'Serial job at 0 must be refused, got: ' || COALESCE(v_error, 'success');+ v_error := pg_temp.try_complete(v_job, 1.5);+ ASSERT v_error LIKE 'Quantity completed must be a whole number%', 'Serial job at 1.5 must be refused, got: ' || COALESCE(v_error, 'success');+ ASSERT pg_temp.serials(v_job) = 'SJ-01:Reserved:0,SJ-02:Reserved:0,SJ-03:Reserved:0', 'Refusals must not receive units: ' || pg_temp.serials(v_job);+ ASSERT (SELECT status FROM job WHERE id = v_job) <> 'Completed', 'Refusals must not complete the job';++ -- Completing 2 of 3 receives exactly 2 units and consumes for 2 units.+ v_error := pg_temp.try_complete(v_job, 2);+ ASSERT v_error IS NULL, 'Serial job at 2 failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.serials(v_job) = 'SJ-01:Available:1,SJ-02:Available:1,SJ-03:Reserved:0', 'Completing 2 must receive exactly 2 units: ' || pg_temp.serials(v_job);+ SELECT status, "quantityComplete", "quantityReceivedToInventory" INTO v_row FROM job WHERE id = v_job;+ ASSERT v_row.status = 'Completed' AND v_row."quantityComplete" = 2 AND v_row."quantityReceivedToInventory" = 2, 'Job must record 2 completed and received';+ ASSERT pg_temp.issued(v_job) = 4, 'Backflush must consume for 2 units: ' || pg_temp.issued(v_job);++ -- Completing the rest receives only the remaining unit.+ v_error := pg_temp.try_complete(v_job, 3);+ ASSERT v_error IS NULL, 'Serial job at 3 failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.serials(v_job) = 'SJ-01:Available:1,SJ-02:Available:1,SJ-03:Available:1', 'Completing 3 must receive the third unit once: ' || pg_temp.serials(v_job);+ ASSERT pg_temp.issued(v_job) = 6, 'Backflush must consume for 3 units: ' || pg_temp.issued(v_job);++ -- Completing again at the same quantity receives and consumes nothing more.+ v_error := pg_temp.try_complete(v_job, 3);+ ASSERT v_error IS NULL, 'Re-completion failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.serials(v_job) = 'SJ-01:Available:1,SJ-02:Available:1,SJ-03:Available:1', 'Re-completion must not receive a unit twice: ' || pg_temp.serials(v_job);+ ASSERT pg_temp.issued(v_job) = 6, 'Re-completion must not consume again: ' || pg_temp.issued(v_job);++ -- The quantity is cumulative: it cannot drop below what was already received.+ v_error := pg_temp.try_complete(v_job, 2);+ ASSERT v_error LIKE 'Quantity completed cannot be lower than the 3 already received%', 'Lowering a serial job below its receipts must be refused, got: ' || COALESCE(v_error, 'success');+ SELECT "quantityComplete", "quantityReceivedToInventory" INTO v_row FROM job WHERE id = v_job;+ ASSERT v_row."quantityComplete" = 3 AND v_row."quantityReceivedToInventory" = 3, 'A refused lower quantity must leave the job at 3';++ -- A unit finished on the shop floor is received ahead of lower serial numbers.+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_serial_item, v_part, 'MJ', 3);+ UPDATE "trackedEntity" SET status = 'Available' WHERE "readableId" = 'MJ-03' AND "companyId" = v_company_id;+ v_error := pg_temp.try_complete(v_job, 1);+ ASSERT v_error IS NULL, 'Mixed job at 1 failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.serials(v_job) = 'MJ-01:Reserved:0,MJ-02:Reserved:0,MJ-03:Available:1', 'The shop-floor unit must be received first: ' || pg_temp.serials(v_job);++ -- A scrapped unit is never received, and completing more units than are left+ -- is refused rather than recording units the ledger never received.+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_serial_item, v_part, 'XJ', 2);+ UPDATE "trackedEntity" SET status = 'Scrapped' WHERE "readableId" = 'XJ-01' AND "companyId" = v_company_id;+ v_error := pg_temp.try_complete(v_job, 2);+ ASSERT v_error LIKE 'Job XJ has 1 serial unit(s) left to receive, fewer than the 2 being completed%', 'Completing more units than are left must be refused, got: ' || COALESCE(v_error, 'success');+ ASSERT pg_temp.serials(v_job) = 'XJ-01:Scrapped:0,XJ-02:Reserved:0', 'A refused completion must not receive units: ' || pg_temp.serials(v_job);+ v_error := pg_temp.try_complete(v_job, 1);+ ASSERT v_error IS NULL, 'Scrap job at 1 failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.serials(v_job) = 'XJ-01:Scrapped:0,XJ-02:Available:1', 'A scrapped unit must not be received: ' || pg_temp.serials(v_job);++ -- An item with no serial sequence keeps one seed entity covering every unit.+ -- It is received as a whole, so marking the last operation Done never raises+ -- out of sync_finish_job_operation's BEFORE trigger.+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_serial_item, v_part, 'UJ', 2, false);+ v_error := pg_temp.try_complete(v_job, 1);+ ASSERT v_error IS NULL, 'Unsplit seed job at 1 failed: ' || COALESCE(v_error, '');+ ASSERT (SELECT sum(quantity) FROM "itemLedger" WHERE "documentId" = v_job AND "documentType" = 'Job Receipt') = 1,+ 'The seed entity must receive exactly 1';+ ASSERT pg_temp.issued(v_job) = 2, 'Backflush must consume for 1 unit: ' || pg_temp.issued(v_job);+ v_error := pg_temp.try_complete(v_job, 2);+ ASSERT v_error IS NULL, 'Unsplit seed job at 2 failed: ' || COALESCE(v_error, '');+ ASSERT (SELECT sum(quantity) FROM "itemLedger" WHERE "documentId" = v_job AND "documentType" = 'Job Receipt') = 2,+ 'The second completion must receive only the delta';+ ASSERT pg_temp.issued(v_job) = 4, 'Backflush must consume for 2 units: ' || pg_temp.issued(v_job);++ -- A single-unit job without a serial sequence still completes (e.g. every+ -- operation marked Done), receiving its one unnumbered unit.+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_serial_item, v_part, 'OJ', 1, false);+ v_error := pg_temp.try_complete(v_job, 1);+ ASSERT v_error IS NULL, 'Single-unit unsplit job at 1 failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.serials(v_job) = 'unnumbered:Available:1', 'The single unnumbered unit must be received once: ' || pg_temp.serials(v_job);++ -- Inventory-tracked job: fractions are allowed, zero is refused.+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_stocked_item, v_part, 'IJ', 2);+ v_error := pg_temp.try_complete(v_job, 0);+ ASSERT v_error LIKE 'Quantity completed must be greater than 0%', 'Inventory job at 0 must be refused, got: ' || COALESCE(v_error, 'success');+ v_error := pg_temp.try_complete(v_job, 1.5);+ ASSERT v_error IS NULL, 'Inventory job at 1.5 failed: ' || COALESCE(v_error, '');+ ASSERT (SELECT sum(quantity) FROM "itemLedger" WHERE "documentId" = v_job AND "documentType" = 'Job Receipt') = 1.5, 'Inventory job must receive 1.5';+ ASSERT pg_temp.issued(v_job) = 3, 'Inventory job must consume for 1.5 units: ' || pg_temp.issued(v_job);++ -- Every stocked job, not only serial: the cumulative quantity cannot drop below+ -- what was received, and re-completing at it posts no zero-quantity receipt.+ v_error := pg_temp.try_complete(v_job, 1);+ ASSERT v_error LIKE 'Quantity completed cannot be lower than the 1.5 already received%', 'Lowering an inventory job below its receipts must be refused, got: ' || COALESCE(v_error, 'success');+ v_error := pg_temp.try_complete(v_job, 1.5);+ ASSERT v_error IS NULL, 'Inventory re-completion failed: ' || COALESCE(v_error, '');+ ASSERT (SELECT count(*) FROM "itemLedger" WHERE "documentId" = v_job AND "documentType" = 'Job Receipt') = 1, 'Re-completion must not post another receipt';++ -- Reopened job: marking its last operation Done with fewer completions than+ -- were received completes it at the received quantity instead of being refused.+ INSERT INTO process (name, "processType", "defaultStandardFactor", "companyId", "createdBy")+ VALUES ('Assembly', 'Process', 'Hours/Piece', v_company_id, 'system') RETURNING id INTO v_process;+ INSERT INTO "workCenter" (name, "locationId", "laborRate", "machineRate", "overheadRate", "defaultStandardFactor", "companyId", "createdBy")+ VALUES ('Bench', v_location_id, 50, 0, 0, 'Hours/Piece', v_company_id, 'system') RETURNING id INTO v_work_center;+ UPDATE job SET status = 'In Progress' WHERE id = v_job;+ INSERT INTO "jobOperation" ("jobId", "jobMakeMethodId", "processId", "workCenterId", "operationQuantity", "quantityComplete", status, "companyId", "createdBy")+ SELECT v_job, m.id, v_process, v_work_center, 2, 1, 'In Progress', v_company_id, 'system'+ FROM "jobMakeMethod" m WHERE m."jobId" = v_job AND m."parentMaterialId" IS NULL+ RETURNING id INTO v_operation;+ v_error := pg_temp.try_finish_operation(v_operation);+ ASSERT v_error IS NULL, 'Finishing the last operation of a reopened job failed: ' || COALESCE(v_error, '');+ SELECT status, "quantityComplete", "quantityReceivedToInventory" INTO v_row FROM job WHERE id = v_job;+ ASSERT v_row.status = 'Completed' AND v_row."quantityComplete" = 1.5 AND v_row."quantityReceivedToInventory" = 1.5, 'The reopened job must complete at the 1.5 already received';+ ASSERT (SELECT sum(quantity) FROM "itemLedger" WHERE "documentId" = v_job AND "documentType" = 'Job Receipt') = 1.5, 'Finishing the reopened job must not change its receipts';++ -- Non-Inventory (service) job may still complete at zero.+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_service_item, v_part, 'NJ', 1);+ v_error := pg_temp.try_complete(v_job, 0);+ ASSERT v_error IS NULL, 'Non-Inventory job at 0 must be allowed, got: ' || COALESCE(v_error, '');+ ASSERT (SELECT status FROM job WHERE id = v_job) = 'Completed', 'Non-Inventory job must complete';++ -- Accounting enabled: labor logged after a completion stays in WIP when the job+ -- is re-completed at the received quantity, and is discharged with the next+ -- receipt. Before, the zero-quantity re-completion divided that WIP by zero.+ UPDATE "companySettings" SET "accountingEnabled" = true WHERE id = v_company_id;+ IF NOT FOUND THEN+ INSERT INTO "companySettings" (id, "accountingEnabled") VALUES (v_company_id, true);+ END IF;+ INSERT INTO "sequence" ("table", name, prefix, "companyId", "updatedBy")+ VALUES ('journalEntry', 'Journal entries', 'JE-', v_company_id, 'system') ON CONFLICT DO NOTHING;+ INSERT INTO account (name, class, "accountType", "incomeBalance", "companyGroupId", "createdBy")+ VALUES ('WIP', 'Asset', 'Bank', 'Balance Sheet', v_group_id, 'system') RETURNING id INTO v_wip_account;+ INSERT INTO account (name, class, "accountType", "incomeBalance", "companyGroupId", "createdBy")+ VALUES ('Finished goods', 'Asset', 'Bank', 'Balance Sheet', v_group_id, 'system') RETURNING id INTO v_finished_account;+ INSERT INTO account (name, class, "accountType", "incomeBalance", "companyGroupId", "createdBy")+ VALUES ('Labor absorption', 'Expense', 'Expense', 'Income Statement', v_group_id, 'system') RETURNING id INTO v_labor_account;+ INSERT INTO account (name, class, "accountType", "incomeBalance", "companyGroupId", "createdBy")+ VALUES ('Other', 'Expense', 'Expense', 'Income Statement', v_group_id, 'system') RETURNING id INTO v_other_account;+ SELECT jsonb_object_agg(attname, to_jsonb(v_other_account)) INTO v_defaults+ FROM pg_attribute WHERE attrelid = '"accountDefault"'::regclass AND attnum > 0 AND NOT attisdropped AND attnotnull AND attname <> 'companyId';+ INSERT INTO "accountDefault" SELECT (jsonb_populate_record(NULL::"accountDefault", v_defaults || jsonb_build_object(+ 'companyId', v_company_id, 'workInProgressAccount', v_wip_account, 'finishedGoodsAccount', v_finished_account,+ 'laborAbsorptionAccount', v_labor_account))).*;++ v_job := pg_temp.make_job(v_company_id, v_location_id, v_stocked_item, v_part, 'AJ', 2);+ INSERT INTO "jobOperation" ("jobId", "jobMakeMethodId", "processId", "workCenterId", "operationQuantity", status, "companyId", "createdBy")+ SELECT v_job, m.id, v_process, v_work_center, 2, 'In Progress', v_company_id, 'system'+ FROM "jobMakeMethod" m WHERE m."jobId" = v_job AND m."parentMaterialId" IS NULL+ RETURNING id INTO v_operation;+ v_error := pg_temp.try_complete(v_job, 2);+ ASSERT v_error IS NULL, 'Accounting job at 2 failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.wip(v_job, v_wip_account) = 0, 'No WIP before labor is logged: ' || pg_temp.wip(v_job, v_wip_account);++ -- One hour of labor at 50, logged after the completion and not yet posted.+ INSERT INTO "productionEvent" ("jobOperationId", "workCenterId", type, "startTime", "endTime", "companyId", "createdBy")+ VALUES (v_operation, v_work_center, 'Labor', now() - interval '1 hour', now(), v_company_id, 'system');+ SELECT count(*) INTO v_receipt_journals FROM journal WHERE "companyId" = v_company_id AND "sourceType" = 'Job Receipt';+ SELECT count(*) INTO v_cost_layers FROM "costLedger" WHERE "documentId" = v_job;++ v_error := pg_temp.try_complete(v_job, 2);+ ASSERT v_error IS NULL, 'Zero-delta re-completion with catch-up WIP failed: ' || COALESCE(v_error, '');+ ASSERT NOT EXISTS (SELECT 1 FROM "productionEvent" WHERE "jobOperationId" = v_operation AND "postedToGL" = false), 'The catch-up labor must be posted';+ ASSERT pg_temp.wip(v_job, v_wip_account) = 50, 'The catch-up labor must stay in WIP: ' || pg_temp.wip(v_job, v_wip_account);+ ASSERT (SELECT count(*) FROM journal WHERE "companyId" = v_company_id AND "sourceType" = 'Job Receipt') = v_receipt_journals, 'A zero-delta re-completion must not post a receipt journal';+ ASSERT (SELECT count(*) FROM "costLedger" WHERE "documentId" = v_job) = v_cost_layers, 'A zero-delta re-completion must not add a cost layer';++ v_error := pg_temp.try_complete(v_job, 1);+ ASSERT v_error LIKE 'Quantity completed cannot be lower than the 2 already received%', 'Lowering an accounting job must be refused, got: ' || COALESCE(v_error, 'success');+ ASSERT pg_temp.wip(v_job, v_wip_account) = 50, 'A refused completion must not move WIP';++ v_error := pg_temp.try_complete(v_job, 3);+ ASSERT v_error IS NULL, 'Accounting job at 3 failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.wip(v_job, v_wip_account) = 0, 'The next receipt must discharge the WIP: ' || pg_temp.wip(v_job, v_wip_account);+ ASSERT (SELECT count(*) FROM "costLedger" WHERE "documentId" = v_job AND quantity = 1 AND cost = 50) = 1, 'The next receipt must carry the WIP into one cost layer';++ RAISE NOTICE 'ALL JOB COMPLETION CASES PASSED (zero/fraction/lower refusal, partial and full serial receipt, re-completion, shop-floor-first, scrapped, too few units, unsplit placeholders, inventory lower/re-completion, reopened last operation, non-inventory, accounting zero-delta with catch-up WIP)';+END;+$cases$;+ROLLBACK;diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 36a33e8112..4f9dc9b641 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -3722,6 +3722,9 @@ msgstr "Alle Mengen beim Kanban-Abschluss-Scan abschließen"msgid "Complete Job"msgstr "Auftrag abschließen"+msgid "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgstr "Schließen Sie Seriennummern/Chargen in MES ab, bevor Sie diesen Fertigungsauftrag abschließen, oder markieren Sie jeden Arbeitsgang als Erledigt, um ihn automatisch abzuschließen."+msgid "Complete Stock Transfer"msgstr "Lagerbestandsübertragung abschließen"@@ -11418,6 +11421,9 @@ msgstr "Nichts"msgid "Nothing at this location matches \"{0}\"."msgstr "Nichts an diesem Ort stimmt mit \"{0}\" überein."+msgid "Nothing completed in MES yet"+msgstr "In MES noch nichts abgeschlossen"+msgid "Nothing else at this location has stock to pull from."msgstr "Keine anderen Artikel an diesem Ort haben Bestand zum Entnehmen."@@ -15188,6 +15194,9 @@ msgstr "Seriennummern"msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Seriennummern werden nur für Artikel mit Serien- oder Chargenverfolgung generiert."+msgid "Serial numbers received"+msgstr "Eingelagerte Seriennummern"+msgid "Serial numbers to return"msgstr ""@@ -15200,6 +15209,9 @@ msgstr "Seriennummernverfolgung"msgid "Serial Tracking"msgstr "Seriennummernverfolgung"+msgid "Serial-tracked jobs must be completed in whole units."+msgstr "Seriennummerngeführte Fertigungsaufträge müssen in ganzen Einheiten abgeschlossen werden."+msgid "Serial/Batch #"msgstr "Seriennummer/Chargennummer #"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex a334a1a307..48ae936592 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -3722,6 +3722,9 @@ msgstr "Complete all quantities on kanban complete scan"msgid "Complete Job"msgstr "Complete Job"+msgid "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgstr "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgid "Complete Stock Transfer"msgstr "Complete Stock Transfer"@@ -11418,6 +11421,9 @@ msgstr "Nothing"msgid "Nothing at this location matches \"{0}\"."msgstr "Nothing at this location matches \"{0}\"."+msgid "Nothing completed in MES yet"+msgstr "Nothing completed in MES yet"+msgid "Nothing else at this location has stock to pull from."msgstr "Nothing else at this location has stock to pull from."@@ -15188,6 +15194,9 @@ msgstr "Serial Numbers"msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Serial numbers are only generated for serial- or batch-tracked items."+msgid "Serial numbers received"+msgstr "Serial numbers received"+msgid "Serial numbers to return"msgstr "Serial numbers to return"@@ -15200,6 +15209,9 @@ msgstr "Serial tracking"msgid "Serial Tracking"msgstr "Serial Tracking"+msgid "Serial-tracked jobs must be completed in whole units."+msgstr "Serial-tracked jobs must be completed in whole units."+msgid "Serial/Batch #"msgstr "Serial/Batch #"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 87f66d7ba8..f26bed0dd1 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -3722,6 +3722,9 @@ msgstr "Completar todas las cantidades al escanear Kanban completado"msgid "Complete Job"msgstr "Completar Trabajo"+msgid "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgstr "Complete los seriales/lotes en MES antes de completar esta orden de trabajo, o marque cada operación como hecha para completarla automáticamente."+msgid "Complete Stock Transfer"msgstr "Completar Transferencia de Inventario"@@ -11418,6 +11421,9 @@ msgstr "Nada"msgid "Nothing at this location matches \"{0}\"."msgstr "Nada en esta ubicación coincide con \"{0}\"."+msgid "Nothing completed in MES yet"+msgstr "Aún no se ha completado nada en MES"+msgid "Nothing else at this location has stock to pull from."msgstr "Nada más en esta ubicación tiene stock para extraer."@@ -15188,6 +15194,9 @@ msgstr "Números de Serie"msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Los números de serie se generan solo para artículos con seguimiento de serie o lote."+msgid "Serial numbers received"+msgstr "Números de serie recibidos"+msgid "Serial numbers to return"msgstr ""@@ -15200,6 +15209,9 @@ msgstr "Seguimiento de números de serie"msgid "Serial Tracking"msgstr "Seguimiento en Serie"+msgid "Serial-tracked jobs must be completed in whole units."+msgstr "Las órdenes de trabajo con número de serie deben completarse en unidades enteras."+msgid "Serial/Batch #"msgstr "Serial/Lote #"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex a5fd205a38..5819501a5e 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -3722,6 +3722,9 @@ msgstr "Terminer toutes les quantités lors du scan de clôture du kanban"msgid "Complete Job"msgstr "Terminer le travail"+msgid "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgstr "Terminez les numéros de série/lots dans MES avant de terminer cet ordre de fabrication, ou marquez chaque opération comme terminée pour le terminer automatiquement."+msgid "Complete Stock Transfer"msgstr "Terminer le transfert de stock"@@ -11418,6 +11421,9 @@ msgstr "Rien"msgid "Nothing at this location matches \"{0}\"."msgstr "Rien à cet emplacement ne correspond à \"{0}\"."+msgid "Nothing completed in MES yet"+msgstr "Rien n'a encore été terminé dans MES"+msgid "Nothing else at this location has stock to pull from."msgstr "Aucun autre article à cet endroit n'a de stock à prélever."@@ -15188,6 +15194,9 @@ msgstr "Numéros de série"msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Les numéros de série ne sont générés que pour les articles suivis en série ou en lot."+msgid "Serial numbers received"+msgstr "Numéros de série réceptionnés"+msgid "Serial numbers to return"msgstr ""@@ -15200,6 +15209,9 @@ msgstr "Suivi des numéros de série"msgid "Serial Tracking"msgstr "Suivi en série"+msgid "Serial-tracked jobs must be completed in whole units."+msgstr "Les ordres de fabrication suivis par numéro de série doivent être terminés en unités entières."+msgid "Serial/Batch #"msgstr "Numéro de série/lot"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex aa12fff150..a4bdd2bd09 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -3722,6 +3722,9 @@ msgstr "कानबान पूर्ण स्कैन पर सभी मmsgid "Complete Job"msgstr "नौकरी पूरी करें"+msgid "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgstr "इस जॉब को पूर्ण करने से पहले MES में सीरियल नंबर/बैच पूर्ण करें, या इसे स्वचालित रूप से पूर्ण करने के लिए हर ऑपरेशन को हो गया के रूप में चिह्नित करें।"+msgid "Complete Stock Transfer"msgstr "स्टॉक ट्रांसफर पूरा करें"@@ -11418,6 +11421,9 @@ msgstr "कुछ नहीं"msgid "Nothing at this location matches \"{0}\"."msgstr "इस स्थान पर कुछ भी \"{0}\" से मेल नहीं खाता।"+msgid "Nothing completed in MES yet"+msgstr "MES में अभी तक कुछ भी पूर्ण नहीं हुआ"+msgid "Nothing else at this location has stock to pull from."msgstr "इस स्थान पर कोई अन्य स्टॉक नहीं है जहां से खींचा जा सकता है।"@@ -15188,6 +15194,9 @@ msgstr "सीरियल नंबर"msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "सीरियल नंबर केवल सीरियल या बैच-ट्रैक किए गए आइटम के लिए उत्पन्न होते हैं।"+msgid "Serial numbers received"+msgstr "प्राप्त सीरियल नंबर"+msgid "Serial numbers to return"msgstr ""@@ -15200,6 +15209,9 @@ msgstr "सीरियल ट्रैकिंग"msgid "Serial Tracking"msgstr "सीरियल ट्रैकिंग"+msgid "Serial-tracked jobs must be completed in whole units."+msgstr "सीरियल नंबर से ट्रैक किए गए जॉब पूरी इकाइयों में पूरे किए जाने चाहिए।"+msgid "Serial/Batch #"msgstr "सीरीज़/बैच #"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex bd9cfaef7c..4d31741b28 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -3722,6 +3722,9 @@ msgstr "Completa tutte le quantità alla scansione di completamento kanban"msgid "Complete Job"msgstr "Completa Lavoro"+msgid "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgstr "Completa i seriali/lotti in MES prima di completare questo ordine di produzione, oppure contrassegna ogni operazione come completata per completarlo automaticamente."+msgid "Complete Stock Transfer"msgstr "Completa Trasferimento Magazzino"@@ -11418,6 +11421,9 @@ msgstr "Niente"msgid "Nothing at this location matches \"{0}\"."msgstr "Nulla in questa posizione corrisponde a \"{0}\"."+msgid "Nothing completed in MES yet"+msgstr "Nulla ancora completato in MES"+msgid "Nothing else at this location has stock to pull from."msgstr "Niente altro in questa posizione ha stock da cui prelevare."@@ -15188,6 +15194,9 @@ msgstr "Numeri di Serie"msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "I numeri di serie vengono generati solo per articoli tracciati in serie o per lotto."+msgid "Serial numbers received"+msgstr "Numeri di serie ricevuti"+msgid "Serial numbers to return"msgstr ""@@ -15200,6 +15209,9 @@ msgstr "Tracciamento dei numeri di serie"msgid "Serial Tracking"msgstr "Tracciamento Seriale"+msgid "Serial-tracked jobs must be completed in whole units."+msgstr "Gli ordini di produzione tracciati per numero di serie devono essere completati in unità intere."+msgid "Serial/Batch #"msgstr "Seriale/Lotto #"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 9c5de68592..2d7f92743f 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -3722,6 +3722,9 @@ msgstr "かんばんスキャン完了時にすべての数量を完了する"msgid "Complete Job"msgstr "ジョブを完了"+msgid "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgstr "この製造指図を完了する前にMESでシリアル/バッチを完了するか、すべての工程を完了にして自動的に完了させてください。"+msgid "Complete Stock Transfer"msgstr "在庫移動を完了"@@ -11418,6 +11421,9 @@ msgstr "なし"msgid "Nothing at this location matches \"{0}\"."msgstr "この場所には\"{0}\"に一致するものはありません。"+msgid "Nothing completed in MES yet"+msgstr "MESでまだ何も完了していません"+msgid "Nothing else at this location has stock to pull from."msgstr "この場所には他に引き出す在庫がありません。"@@ -15188,6 +15194,9 @@ msgstr "シリアル番号"msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "シリアル番号は、シリアルまたはバッチ追跡アイテムに対してのみ生成されます。"+msgid "Serial numbers received"+msgstr "受け入れたシリアル番号"+msgid "Serial numbers to return"msgstr ""@@ -15200,6 +15209,9 @@ msgstr "シリアルトラッキング"msgid "Serial Tracking"msgstr "シリアル追跡"+msgid "Serial-tracked jobs must be completed in whole units."+msgstr "シリアル番号で管理される製造指図は、整数単位で完了する必要があります。"+msgid "Serial/Batch #"msgstr "シリアル/バッチ #"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 5713a21ceb..82ab2fe7ed 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -3722,6 +3722,9 @@ msgstr "칸반 완료 스캔에서 모든 수량을 완료 처리"msgid "Complete Job"msgstr "작업 완료"+msgid "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgstr "이 작업 지시를 완료하기 전에 MES에서 일련번호/배치를 완료하거나, 모든 공정을 완료로 표시하여 자동으로 완료되도록 하세요."+msgid "Complete Stock Transfer"msgstr "재고 이동 완료"@@ -11418,6 +11421,9 @@ msgstr "없음"msgid "Nothing at this location matches \"{0}\"."msgstr "이 위치에서 \"{0}\"와 일치하는 항목이 없습니다."+msgid "Nothing completed in MES yet"+msgstr "MES에서 아직 완료된 항목이 없습니다"+msgid "Nothing else at this location has stock to pull from."msgstr "이 위치에는 더 이상 가져올 재고가 없습니다."@@ -15188,6 +15194,9 @@ msgstr "시리얼 번호"msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "시리얼 번호는 시리얼 또는 배치 추적 항목에만 생성됩니다."+msgid "Serial numbers received"+msgstr "입고된 시리얼 번호"+msgid "Serial numbers to return"msgstr ""@@ -15200,6 +15209,9 @@ msgstr "일련번호 추적"msgid "Serial Tracking"msgstr "일련번호 추적"+msgid "Serial-tracked jobs must be completed in whole units."+msgstr "시리얼 번호로 추적되는 작업 지시는 정수 단위로 완료해야 합니다."+msgid "Serial/Batch #"msgstr "일련번호/배치 #"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 47ae37a8a3..18668228f6 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -3722,6 +3722,9 @@ msgstr "Zakończ wszystkie ilości podczas skanowania zakończenia kanban"msgid "Complete Job"msgstr "Ukończ zadanie"+msgid "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgstr "Zakończ produkcję sztuk z numerami seryjnymi/partii w MES przed zakończeniem tego zlecenia produkcyjnego lub oznacz każdą operację jako zakończoną, aby zakończyć je automatycznie."+msgid "Complete Stock Transfer"msgstr "Ukończ Transfer Zapasów"@@ -11418,6 +11421,9 @@ msgstr "Nic"msgid "Nothing at this location matches \"{0}\"."msgstr "Nic w tej lokalizacji nie pasuje do \"{0}\"."+msgid "Nothing completed in MES yet"+msgstr "W MES nic jeszcze nie ukończono"+msgid "Nothing else at this location has stock to pull from."msgstr "W tym miejscu nic innego nie ma zapasów do pobrania."@@ -15188,6 +15194,9 @@ msgstr "Numery seryjne"msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Numery seryjne są generowane tylko dla elementów śledzonych numerem seryjnym lub partią."+msgid "Serial numbers received"+msgstr "Przyjęte numery seryjne"+msgid "Serial numbers to return"msgstr ""@@ -15200,6 +15209,9 @@ msgstr "Śledzenie numerów seryjnych"msgid "Serial Tracking"msgstr "Śledzenie seryjne"+msgid "Serial-tracked jobs must be completed in whole units."+msgstr "Zlecenia produkcyjne śledzone numerem seryjnym muszą być realizowane w pełnych jednostkach."+msgid "Serial/Batch #"msgstr "Numer seryjny/partii #"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 45a6fb0e35..19360ce423 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -3722,6 +3722,9 @@ msgstr "Concluir todas as quantidades ao escanear a conclusão do kanban"msgid "Complete Job"msgstr "Concluir Trabalho"+msgid "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgstr "Conclua os seriais/lotes no MES antes de concluir esta ordem de produção, ou marque cada operação como concluída para concluí-la automaticamente."+msgid "Complete Stock Transfer"msgstr "Concluir Transferência de Estoque"@@ -11418,6 +11421,9 @@ msgstr "Nada"msgid "Nothing at this location matches \"{0}\"."msgstr "Nada neste local corresponde a \"{0}\"."+msgid "Nothing completed in MES yet"+msgstr "Nada concluído no MES ainda"+msgid "Nothing else at this location has stock to pull from."msgstr "Nada mais neste local tem estoque para puxar."@@ -15188,6 +15194,9 @@ msgstr "Números de Série"msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Números de série são gerados apenas para itens rastreados por série ou lote."+msgid "Serial numbers received"+msgstr "Números de série recebidos"+msgid "Serial numbers to return"msgstr ""@@ -15200,6 +15209,9 @@ msgstr "Rastreamento de série"msgid "Serial Tracking"msgstr "Rastreamento em Série"+msgid "Serial-tracked jobs must be completed in whole units."+msgstr "Ordens de produção rastreadas por número de série devem ser concluídas em unidades inteiras."+msgid "Serial/Batch #"msgstr "Série/Lote #"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 9f29e5bc69..27dffc50d9 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -3722,6 +3722,9 @@ msgstr "Завершить все количества при сканироваmsgid "Complete Job"msgstr "Завершить работу"+msgid "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgstr "Завершите серийные номера/партии в MES перед завершением этого производственного заказа или отметьте каждую операцию как выполненную, чтобы он завершился автоматически."+msgid "Complete Stock Transfer"msgstr "Завершить передачу запасов"@@ -11418,6 +11421,9 @@ msgstr "Ничего"msgid "Nothing at this location matches \"{0}\"."msgstr "В этом месте нет ничего, соответствующего \"{0}\"."+msgid "Nothing completed in MES yet"+msgstr "В MES пока ничего не завершено"+msgid "Nothing else at this location has stock to pull from."msgstr "На этом месте больше нечего извлекать из запаса."@@ -15188,6 +15194,9 @@ msgstr "Серийные номера"msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Серийные номера генерируются только для серийных или партионно отслеживаемых товаров."+msgid "Serial numbers received"+msgstr "Принятые серийные номера"+msgid "Serial numbers to return"msgstr ""@@ -15200,6 +15209,9 @@ msgstr "Отслеживание серийных номеров"msgid "Serial Tracking"msgstr "Отслеживание по серийным номерам"+msgid "Serial-tracked jobs must be completed in whole units."+msgstr "Производственные заказы с учётом по серийным номерам должны завершаться целыми единицами."+msgid "Serial/Batch #"msgstr "Серийный номер/Партия №"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex dd8d505ab5..e03003f69d 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -3722,6 +3722,9 @@ msgstr "Kanban tamamlama taramasında tüm miktarları tamamla"msgid "Complete Job"msgstr "İşi Tamamla"+msgid "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgstr "Bu iş emrini tamamlamadan önce MES'te seri numaralarını/partileri tamamlayın veya otomatik olarak tamamlanması için her operasyonu Bitti olarak işaretleyin."+msgid "Complete Stock Transfer"msgstr "Stok Transferini Tamamla"@@ -11418,6 +11421,9 @@ msgstr "Hiçbir şey"msgid "Nothing at this location matches \"{0}\"."msgstr "Bu konumda \"{0}\" ile eşleşen hiçbir şey yok."+msgid "Nothing completed in MES yet"+msgstr "MES'te henüz hiçbir şey tamamlanmadı"+msgid "Nothing else at this location has stock to pull from."msgstr "Bu konumda çekilecek başka hiçbir stok yok."@@ -15188,6 +15194,9 @@ msgstr "Seri Numaraları"msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Seri numaraları yalnızca seri- veya batch-izlenen öğeler için oluşturulur."+msgid "Serial numbers received"+msgstr "Teslim alınan seri numaraları"+msgid "Serial numbers to return"msgstr ""@@ -15200,6 +15209,9 @@ msgstr "Seri numarası takibi"msgid "Serial Tracking"msgstr "Seri Takibi"+msgid "Serial-tracked jobs must be completed in whole units."+msgstr "Seri numarasıyla izlenen iş emirleri tam birimler halinde tamamlanmalıdır."+msgid "Serial/Batch #"msgstr "Seri/Parti No"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 096bb4f19f..9c3a6237dc 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -3722,6 +3722,9 @@ msgstr "完成看板扫码时完成所有数量"msgid "Complete Job"msgstr "完成工作"+msgid "Complete serials/batches in MES before completing this job, or mark every operation Done to complete it automatically."+msgstr "请先在MES中完成序列号/批次再完成此工单,或将每道工序标记为完成以自动完成该工单。"+msgid "Complete Stock Transfer"msgstr "完成库存转移"@@ -11418,6 +11421,9 @@ msgstr "无"msgid "Nothing at this location matches \"{0}\"."msgstr "此位置处没有与\"{0}\"匹配的内容。"+msgid "Nothing completed in MES yet"+msgstr "MES中尚未完成任何内容"+msgid "Nothing else at this location has stock to pull from."msgstr "此位置没有其他可提取的库存。"@@ -15188,6 +15194,9 @@ msgstr "序列号"msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "序列号仅为序列号或批次跟踪的物料生成。"+msgid "Serial numbers received"+msgstr "已接收的序列号"+msgid "Serial numbers to return"msgstr ""@@ -15200,6 +15209,9 @@ msgstr "序列号追踪"msgid "Serial Tracking"msgstr "序列追踪"+msgid "Serial-tracked jobs must be completed in whole units."+msgstr "按序列号跟踪的工单必须以整数单位完成。"+msgid "Serial/Batch #"msgstr "序列号/批次 #"