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
feat(oee): post sensor machine time to the GL when it ends (#1921)
Brad Barbin6dc74654c3bf
diff --git a/.ai/specs/2026-10-12-oee-provider-integration.md b/.ai/specs/2026-10-12-oee-provider-integration.mdindex 9ff3f5cf92..2f757a485f 100644--- a/.ai/specs/2026-10-12-oee-provider-integration.md+++ b/.ai/specs/2026-10-12-oee-provider-integration.md@@ -493,18 +493,17 @@ events and posts them.`OeeProviderUnavailableError` (network failure, timeout, 5xx) stops therun, because every device would fail the same way.-The job never posts to the GL. Carbon has no scheduled sweep that posts-production events. An event posts at one of 3 moments:--1. At a press: the MES routes post every event that the press ended, except- batch events.-2. At operation finish: `finishJobOperation` (MES) and `completeOperation`- (ERP) post the operation's ended, unposted events.-3. At job completion: `complete_job_to_inventory` posts every ended, unposted- event of the job.--A sensor event that the sync closes posts at operation finish or job-completion. Until it posts, a supervisor can edit it on the job's Events tab.+A Machine event posts to the GL when it ends. After each device's+transaction commits, the job posts the Machine events that its sync ended+(`postEndedMachineEvents`, which invokes `post-production-event`). The other+writers that end sensor time also post what they end: an assignment of+unattributed time, an unmap or remap, the Sense uninstall, a press and a Down+maintenance dispatch. A posting failure is logged and does not stop the sync.+Operation finish (`finishJobOperation`, `completeOperation`) and job+completion (`complete_job_to_inventory`) post any ended event that is still+unposted. Carbon has no scheduled sweep that posts production events. A+supervisor can still edit a posted event on the job's Events tab: the edit+reverses the posted amount and posts the new one.When a user uninstalls Sense, its `onUninstall` hook (`senseOnUninstall`) endsthe open sensor time of every Sense device of the company. The mappings stay.@@ -576,7 +575,7 @@ its filters.| How an operation is loaded | Any open `productionEvent` insert on the work center | Setup, Labor, Machine and the QR start already insert one. Shops change nothing. || Unattributed time | Its own table, cleared from an ERP list | User decision (Q3). `productionEvent.jobOperationId` is NOT NULL, so unattributed time cannot be a production event. || Manual Machine timer | Kept on every work center. A press ends every open Machine event on the work center. The time after a press in the same run goes to the queue. Pause keeps the operation loaded. | User decision (Q4, Q4b, Q4c). A work center has one machine time, so time is never counted twice. |-| GL posting | Sensor events post at operation finish or job completion. Events that a press ends post at the press. There is no posting sweep. | User decision (Q5). A wrong sensor attribution stays editable until the operation is done. |+| GL posting | A sensor event posts when it ends: at the sync that ends it, at an assignment, an unmap or uninstall, or a press. Operation finish and job completion post what a failure left. There is no posting sweep. | User decision (Q5, revised 2026-10-14). Machine cost reaches WIP in the period the machine ran, not when the operation finishes. A posted event stays editable: an edit reposts the difference. || License boundary | Provider, sync, mapping and the unattributed list are commercial (`packages/ee`, `.ee.tsx`), gated by `INTEGRATIONS`. The loaded operation, the MES button rules and the display are AGPL. | User decision (Q6). Matches every other integration. || Timezone | Store UTC instants. Use the work center's `location.timezone` for local time. Warn on a site/location mismatch. | User decision (Q7). || Polling | Inngest cron every 2 minutes, 10-minute overlap, idempotent insert | Sense has no webhooks. A 2-minute delay keeps the work center display useful. The overlap plus the unique key makes a re-read safe. |@@ -718,10 +717,10 @@ a company with no OEE integration does not see it.- [ ] Activating Sense while another `oee` integration is active succeeds. The single-active trigger still refuses a second active `accounting` integration.- [ ] An operator starts Setup on operation A at W1 and stops it. The open `workCenterLoad` row of W1 names A.- [ ] An event that starts before the newest `loadedAt` or `unloadedAt` of W1 loads nothing.-- [ ] Sense reports Active at T1 and Idle at T2 for the mapped station. Within 2 sync runs, a Machine `productionEvent` on A exists with `startTime` = T1, `endTime` = T2, `employeeId` null and `postedToGL` false.-- [ ] After operation A is finished, that event has `postedToGL` = true. Its cost is (T2 − T1) × W1's machine rate plus overhead.+- [ ] Sense reports Active at T1 and Idle at T2 for the mapped station. Within 2 sync runs, a Machine `productionEvent` on A exists with `startTime` = T1, `endTime` = T2, `employeeId` null and `postedToGL` true.+- [ ] That event has a `Production Event` journal. Its cost is (T2 − T1) × W1's machine rate plus overhead.- [ ] With nothing loaded on W1, an Active change creates an open `unattributedMachineTime` row. The row appears on Production → Unattributed Time.-- [ ] Assigning a stopped row to operation B creates a Machine event on B with the row's start and end, and deletes the row.+- [ ] Assigning a stopped row to operation B creates a Machine event on B with the row's start and end, posts it, and deletes the row.- [ ] Dismissing a stopped row deletes it, and no event exists. Dismissing a running row fails.- [ ] The machine is Active and the operator presses Pause at 10:03. The event ends at 10:03. The time after 10:03 until the machine stops goes to an unattributed row. The next Idle→Active change opens a new event on the same operation.- [ ] A sensor event runs on A, and the operator presses Machine Start on operation C. A's event ends at the press time. C's event starts at the press time. C is loaded.@@ -758,12 +757,13 @@ a company with no OEE integration does not see it.- [x] Where is unattributed time resolved in v1? — **Answer:** An ERP supervisor list only. Assign to a job operation, or dismiss. The MES prompt is later work. (Shipped: dismiss takes no reason and deletes the row.)- [x] What happens to the manual MES Machine timer on a mapped work center? — **Answer:** It stays visible and in sync with the sensor. There is one Machine event at a time, so no duplicates.- [x] What does the Machine button do when the sensor drives the timer? — **Answer:** It overrides the sensor for the operator's time. Pause keeps the operation loaded. (Shipped as the owner rule: the time after a press in the same run goes to the queue.)-- [x] When does sensor machine time post to the GL? — **Answer:** At operation finish or job completion. (Shipped: there is no posting sweep; section 7 lists the 3 moments an event posts.)+- [x] When does sensor machine time post to the GL? — **Answer:** At operation finish or job completion. **Revised 2026-10-14:** when the event ends (section 7); operation finish and job completion are the catch-up.- [x] Which parts are commercial? — **Answer:** The provider, the sync, the mapping and the unattributed list are in `packages/ee`, gated by `INTEGRATIONS`. The loaded operation and its MES display are AGPL.- [x] Which timezone wins for local time? — **Answer:** The work center's location timezone. Store UTC. Warn when the Sense site timezone differs.## Changelog+- 2026-10-14: Sensor time posts when it ends (Q5 revised). The sync, assign, unmap/remap, the Sense uninstall and a Down maintenance dispatch post the Machine events they end. `post-production-event` locks the event row, and `complete_job_to_inventory` locks the unposted events it posts (migration `20261014135003`), so two callers never post one event twice.- 2026-10-14: Fixes from the strict self-review (`.ai/plans/2026-10-14-oee-review-fixes.md`). The open `workCenterLoad` row is the load: the migration drops `workCenter.loadedJobOperationId` and `loadedAt`. A load older than the newest boundary in the history writes nothing. An unload ends the open row at `GREATEST(NOW(), loadedAt)`. The engine applies one owner rule to every piece of a run. Open sensor time follows its owner across load, block and press edges. A late stop trims the closed queue rows. A press takes its time under the locks and records `unplannedPressAt`. A Machine start writes the press, the event and the tracked activity in one transaction. The routes check permission before any write and post every event a press ends. Uninstalling Sense ends its open sensor time. The ERP review keeps the list filters and spans the days of the row.- 2026-10-13: Build changes. Unattributed time became a queue with no status. Maintenance blocks became periods. The load gained its history table, `workCenterLoad`. The OEE tables became read-only through the API, with composite foreign keys to `workCenter`. The MES press rules apply on every work center.- 2026-10-12: Planning pass. Corrected the secret path, the interceptor timing, the view recreation and the indexes. Added the engine's inputs, applied state (`appliedThrough`) and first-sync rules. The steady-state rule now reopens time on the loaded operation when the rules allow it.diff --git a/.claude/rules/oee-provider.md b/.claude/rules/oee-provider.mdindex a34464c925..9b6b1f5a79 100644--- a/.claude/rules/oee-provider.md+++ b/.claude/rules/oee-provider.md@@ -37,14 +37,14 @@ checks it first ("Work center not found"). `machineStateChange` and| `packages/ee/src/oee/engine.ts` | `planMachineTime`: the pure attribution engine. No database, no env. Pinned by `engine.test.ts` || `packages/ee/src/oee/assignable.ts` | `machineTimeRefusal(operationStatus, jobStatus)`: `"Done"`, `"Canceled"`, `"Locked"` or null. The one rule for "can this operation take machine time", used by the sync (a load's `assignable`), `assignUnattributedMachineTime` and the review's suggestion cards. Built on `isJobLocked` / `JOB_LOCKED_STATUSES` (`packages/utils/src/job-status.ts`, re-exported by the ERP's `production.models.ts`) || `packages/ee/src/oee/registry.ts` | `OEE_PROVIDERS` (keyed by `OeeProviderId`): provider id → factory, the one place a provider is named. `isOeeProviderId`, and `createOeeProvider(integrationId, metadata)`: the one resolution (id check, "No API key", the `DEFAULT_MINIMUM_STATE_SECONDS` default, the factory) behind `getOeeProvider` and the Sense healthcheck |-| `packages/ee/src/oee/service.server.ts` | `getOeeProvider` (runtime, degrades through `companyHasFeature("INTEGRATIONS")`), and 4 authoring writes that embed `requireEntitlement("INTEGRATIONS")`: `upsertWorkCenterDevice`, `deleteWorkCenterDevice`, `assignUnattributedMachineTime`, `dismissUnattributedMachineTime` |+| `packages/ee/src/oee/service.server.ts` | `getOeeProvider` (runtime, degrades through `companyHasFeature("INTEGRATIONS")`), `postEndedMachineEvents` (runtime: posts ended Machine events through `post-production-event`, logs failures, never throws), and 4 authoring writes that embed `requireEntitlement("INTEGRATIONS")`: `upsertWorkCenterDevice`, `deleteWorkCenterDevice`, `assignUnattributedMachineTime`, `dismissUnattributedMachineTime` || `packages/ee/src/sense/provider.ts` | `SenseProvider`, the Sense HTTP adapter. Pinned by `provider.test.ts` || `packages/ee/src/sense/config.tsx` | The descriptor: `apiKey` (secret), `environment`, `minimumStateSeconds` (default 60) || `packages/ee/src/sense/hooks.server.ts` | `senseHealthcheck` (calls `provider.validate()`) and `senseOnUninstall` (registered in `packages/ee/src/hooks.server.ts`; see "Uninstalling Sense") || `packages/jobs/src/inngest/functions/integrations/oee-sweep.ts` | Cron `*/2 * * * *`. Sends one `carbon/oee-sync` per (company, OEE integration) that is active and has at least 1 mapped device || `packages/jobs/src/inngest/functions/integrations/oee-sync.ts` | `carbon/oee-sync`, concurrency 1 per company, `singleton` (skip) per company and integration. Syncs every device of the integration in ONE `step.run` || `packages/jobs/src/inngest/functions/integrations/oee-sync-device.ts` | `syncOeeDevice`: read, store, then plan and apply under the device lock. Pinned by `oee-sync-device.database.test.ts` (needs `SUPABASE_DB_URL`) |-| `packages/database/src/machine-time.ts` | `lockWorkCenterDevice` (`FOR UPDATE` on the device row), `lockMachinePress` (the device lock, then a transaction advisory lock per work center), `recordManualMachinePress` and `endSensorMachineTime`. Shared by the sync, the MES, the device mapping writes and the Sense uninstall hook. Pinned by `machine-time.test.ts` (needs `SUPABASE_DB_URL`) |+| `packages/database/src/machine-time.ts` | `lockWorkCenterDevice` (`FOR UPDATE` on the device row), `lockMachinePress` (the device lock, then a transaction advisory lock per work center), `recordManualMachinePress` and `endSensorMachineTime` (both return the ended event ids for the caller to post after commit). Shared by the sync, the MES, the device mapping writes and the Sense uninstall hook. Pinned by `machine-time.test.ts` (needs `SUPABASE_DB_URL`) || `apps/mes/app/services/operations.service.ts` | `startMachineProductionEvent` (press, event and tracked activity in one Kysely transaction), `endMachineProductionEvent` (press locks, then the open event's row lock), `postEndedProductionEvents` (posts the events a press ended), `endProductionEvent` (ends an open event, scoped by `companyId`) || `packages/database/src/event-system/handlers/sync_load_work_center_operation.sql` | `productionEvent` AFTER INSERT: writes a load into `workCenterLoad` (see "The loaded operation") || `packages/database/src/event-system/handlers/sync_unload_work_center_operation.sql` | `jobOperation` AFTER UPDATE / DELETE: ends the operation's open `workCenterLoad` row when it becomes Done or Canceled, is deleted, or moves to another work center |@@ -225,14 +225,15 @@ has left. So `deleteWorkCenterDevice` and the remap path of`upsertWorkCenterDevice` first call `endSensorMachineTime` on the OLD workcenter, under the device row lock: it ends, at now, the open Machine eventscreated by `system` and the unattributed rows with no `endTime`. An-operator's own open Machine event stays open.+operator's own open Machine event stays open. The ended events post once the+transaction commits (`postEndedMachineEvents`).**Uninstalling Sense.** The integration card's **Uninstall** posts to`x+/settings+/integrations.deactivate.$id.tsx`, which deactivates theintegration and runs its `onUninstall` hook.`senseOnUninstall` ends the sensor time of every Sense device of the companyat one instant: per device, `lockWorkCenterDevice` then-`endSensorMachineTime` (`userId` `system`). The mappings stay, so a+`endSensorMachineTime` (`userId` `system`), then posts the ended events. The mappings stay, so areconnect resumes each device from its cursor.**Steady state.** After the changes, if the device is `Running`, nothing is@@ -264,7 +265,8 @@ more cases:`Running` change, else to the last press): `deleteUnattributed` whennothing is left, `updateUnattributed` (plus an `insertUnattributed` for thepart after the idle stretch) otherwise. Queue rows are not posted, so this- is safe. The engine never trims a Machine event.+ is safe. The engine never trims a Machine event: a closed one may already+ be posted.**Running past a press.** A machine that is `Running` at the press(`currentStateAt <= lastManualChangeAt`) and runs on after it: the press, a@@ -390,19 +392,36 @@ After a Pause on a running machine, the time until it stops goes to the queueKysely returns `timestamptz` as a JS `Date`. `syncOeeDevice` normalizes everyinstant with `toInstant` before the engine compares it.-**GL posting.** The sync never posts. There is no scheduled sweep that posts-production events. An event posts at one of three moments:--1. At a press: the MES routes post every event the press ended- (`postEndedProductionEvents`, skipping batch events).-2. At operation finish: MES `finishJobOperation` and ERP `completeOperation`- post the operation's ended, unposted events.-3. At job completion: `complete_job_to_inventory` posts every ended,- unposted event of the job with a duration.--A sensor event that the sync closes is an ordinary Machine event with no-employee: it posts at operation finish or job completion. An assigned-unattributed row also does not post at assign time.+**GL posting.** A Machine event posts when it ends (Dr WIP, Cr labor/machine+and overhead absorption, `post-production-event`). There is no scheduled+sweep. The writers that end sensor time post what they ended, after their+transaction commits:++1. The sync: `syncOeeDevice` returns `endedEventIds` (a `closeMachineEvent`+ that matched, or an `insertMachineEvent` with an `endTime`), and+ `oee-sync` passes them to `postEndedMachineEvents` (`userId` `system`).+2. Assign: `assignUnattributedMachineTime` posts the event it inserted.+3. Unmap, remap and uninstall: `deleteWorkCenterDevice`,+ `upsertWorkCenterDevice` and `senseOnUninstall` post what+ `endSensorMachineTime` ended.+4. A press: the MES routes post every event the press ended+ (`postEndedProductionEvents`, skipping batch events). So does a Down+ maintenance dispatch (`dispatch.new.tsx`), which ends every event on the+ work center.++`postEndedMachineEvents` logs a failure and never throws, so the cursor+still moves. Two catch-ups post what a failure left: operation finish (MES+`finishJobOperation`, ERP `completeOperation`) and job completion+(`complete_job_to_inventory`). Two callers can post one event at once (the+sync and an operation finish): `post-production-event` locks the event row in+its transaction and refuses with 409 (`PRODUCTION_EVENT_POSTED_CONCURRENTLY_ERROR`)+when `postedToGL` changed since it read the event, or, for a repost, when the+net already posted for the event (`readPostedNet`, re-read under the lock)+changed: the flag stays true across reposts, so it alone cannot tell two+concurrent edit reposts apart. `complete_job_to_inventory`+selects its unposted events `FOR UPDATE OF pe` (migration `20261014135003`),+so it waits for a concurrent post and skips an event that one posted. An edit on the job's+Events tab reposts the difference (reversal, then the new amount).## Unattributed machine timediff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex cb651145d0..223be5668c 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -20,7 +20,7 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced### Job completion-`complete_job_to_inventory` (SQL, newest `20261006221601_complete-job-to-asset.sql`, forked from the guarded definition in `20260925121735_rpc-function-guards.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.+`complete_job_to_inventory` (SQL, newest `20261014135003_lock-production-events-at-job-completion.sql` (locks the unposted events it posts), before it `20261009010412_job-costing-always-post.sql` and `20261006221601_complete-job-to-asset.sql`, forked from the guarded definition in `20260925121735_rpc-function-guards.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.@@ -31,7 +31,7 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced### Loaded operation and unattributed machine time- **Loaded operation** (community) — the open `workCenterLoad` row (`unloadedAt` null) IS the load; there is no pointer column on `workCenter` (migration `20261014024119` dropped `loadedJobOperationId`/`loadedAt`). The `productionEvent` interceptor `sync_load_work_center_operation` loads the operation of any event inserted with `endTime` null and a `workCenterId` (Setup, Labor, Machine, the MES QR start): it ends the open row at the event's `startTime` and opens a new one. An event inserted with an `endTime` never loads; a start earlier than the newest `loadedAt`/`unloadedAt` in the work center's history writes nothing, and a reload of the loaded operation writes nothing. `sync_unload_work_center_operation` (on `jobOperation`) ends the open row (`unloadedAt` = `GREATEST(NOW(), loadedAt)`) when the operation becomes `Done` or `Canceled`, is deleted, or moves to another work center; a Pause does not unload. An event loads only its own company's operation onto its own company's work center. A CHECK refuses `unloadedAt < loadedAt`, and a partial unique index allows one open row per work center. `jobOperationId` has no foreign key on purpose: a second `jobOperation`↔`workCenter` relationship makes PostgREST refuse embeds like `jobOperation` → `workCenter(name)` (PGRST201). The MES work center display shows it as "Loaded: …", read from `workCentersWithBlockingStatus.loadedJobOperationId`. It exists on every work center, with or without a device. Rows are deleted 7 days after the unload, unless a device on the work center has not planned past it. The OEE sync reads this history to give each piece of a run to the operation loaded when it ran.-- **Machine time from an OEE device** — when a `workCenterDevice` (Settings → Integrations → Sense → Devices) maps a machine to the work center, the `oee-sync` job records its Running time as Machine `productionEvent` rows on the loaded operation: `employeeId` null, `createdBy` `system`. The sensor's open event follows the load: a Setup or Labor start on another operation moves the time to it. Those events post to the GL only when the operation finishes (MES `finishJobOperation`, ERP `completeOperation`) or the job completes (`complete_job_to_inventory`) — never at sync or assign time. There is no posting sweep.+- **Machine time from an OEE device** — when a `workCenterDevice` (Settings → Integrations → Sense → Devices) maps a machine to the work center, the `oee-sync` job records its Running time as Machine `productionEvent` rows on the loaded operation: `employeeId` null, `createdBy` `system`. The sensor's open event follows the load: a Setup or Labor start on another operation moves the time to it. Those events post to the GL as soon as they end, through `postEndedMachineEvents` (`@carbon/ee/oee.server`, which invokes `post-production-event`): after the sync that ends them, after an Unattributed Time assignment, after an unmap/remap or the Sense uninstall, and at an operator's press or a Down maintenance dispatch (`postEndedProductionEvents`). Operation finish and job completion stay the catch-up for anything a failure left unposted. There is no posting sweep.- **Unattributed machine time** — `unattributedMachineTime` is a review queue of Running time that no operation can take: nothing is loaded; the work center is blocked by maintenance (a `Down` dispatch from its `createdAt` until Completed or Cancelled, a `Planned` one from its actual start while `In Progress`); the loaded operation is Done or Canceled or its job is locked (`machineTimeRefusal`); or the machine ran on after an operator's Machine press in the same run (a Pause). It has no status: assigning (`assignUnattributedMachineTime`, inserts a Machine event for the interval) or dismissing (`dismissUnattributedMachineTime`) deletes the row, and pg_cron deletes rows 30 days after their `endTime`. Production → "Unattributed Time" (shown in the nav only while an `oee` integration is active; `x+/production+/machine-time.tsx`, `ui/MachineTime/*.ee.tsx`). The drawer (`machine-time.$id.tsx`) is a one-at-a-time review: suggestion cards from `getWorkCenterDayEvents` over the days the row touches, ranked by `suggestMachineTimeOperations` (`ui/MachineTime/machine-time-suggestions.ee.ts`), a search card over `getMachineTimeOperationCandidates` (open operations at the work center's location, including ones with no work center), "Not job time", Skip, and j/k; each answer redirects to the next row (`getUnattributedMachineTimeNeighbors`, keyset from `machineTimeQueueKeyset`). A row link and the drawer's close keep the list's filters; a queue move replaces the history entry; a failed read shows in the drawer (`loadErrors`). Both writes are `@carbon/ee/oee.server` behind `requireEntitlement("INTEGRATIONS")`; both refuse a row with no `endTime`, and assign refuses a locked job or a Done/Canceled operation. The list has 5 filters (work center, location, start date, end date, state Running in blue / Stopped in green): `parseMachineTimeListFilters` (`ui/MachineTime/machine-time-filters.ee.ts`, pure, inclusive `YYYY-MM-DD` days) and `applyMachineTimeListFilters` (service), shared by the list and the review queue; both read the view `unattributedMachineTimes`, whose `startDate`/`endDate` are the row's days in its location's timezone, the timezone the list shows (a `''` timezone counts as none). The list has no sort. The list renders `MachineTimeUpgradeOverlay` when gated.Engine, sync and press rules: `.claude/rules/oee-provider.md`.diff --git a/apps/mes/app/routes/x+/dispatch.new.tsx b/apps/mes/app/routes/x+/dispatch.new.tsxindex ef77a2898c..602c483385 100644--- a/apps/mes/app/routes/x+/dispatch.new.tsx+++ b/apps/mes/app/routes/x+/dispatch.new.tsx@@ -13,8 +13,12 @@ import { NotificationEvent } from "@carbon/notifications";import { datetime, redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";+import { getDatabaseClient } from "~/services/database.server";import { maintenanceDispatchValidator } from "~/services/models";-import { endProductionEventsByWorkCenter } from "~/services/operations.service";+import {+ endProductionEventsByWorkCenter,+ postEndedProductionEvents+} from "~/services/operations.service";import { path } from "~/utils/path";const log = getLogger("mes");@@ -145,13 +149,27 @@ export async function action({ request }: ActionFunctionArgs) {);}- // End all production events for the work center if oeeImpact is Down+ // End all production events for the work center if oeeImpact is Down,+ // and post them as any ended event posts.if (validation.data.oeeImpact === "Down") {- await endProductionEventsByWorkCenter(serviceRole, {+ const ended = await endProductionEventsByWorkCenter(serviceRole, {workCenterId: validation.data.workCenterId,companyId,endTime: datetime.timestamp()});+ if (ended.error) {+ log.error("Failed to end the work center's production events", {+ companyId,+ workCenterId: validation.data.workCenterId,+ error: ended.error+ });+ } else {+ await postEndedProductionEvents(serviceRole, getDatabaseClient(), {+ companyId,+ userId,+ ids: ended.data.map((event) => event.id)+ });+ }}// Send notification based on failure mode typediff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 19a1df597a..398676b16c 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -2599,6 +2599,7 @@ export async function endProductionEvents(.eq("companyId", args.companyId);}+/** Ends every open event on the work center; returns the ended ids to post. */export async function endProductionEventsByWorkCenter(client: SupabaseClient<Database>,args: { workCenterId: string; companyId: string; endTime: string }@@ -2610,7 +2611,8 @@ export async function endProductionEventsByWorkCenter(}).is("endTime", null).eq("workCenterId", args.workCenterId)- .eq("companyId", args.companyId);+ .eq("companyId", args.companyId)+ .select("id");}// Phase 3 (auto-start): when an operator starts a production event, flip a not-yet-starteddiff --git a/docs/content/docs/integrations/oee.mdx b/docs/content/docs/integrations/oee.mdxindex dfc85eb8ac..ca930393d7 100644--- a/docs/content/docs/integrations/oee.mdx+++ b/docs/content/docs/integrations/oee.mdx@@ -79,8 +79,8 @@ When a station reports Running, Carbon opens a Machine production event on the lIf an operator starts Setup or Labor on operation B while the machine runs on operation A, B becomes the loaded operation. The sensor's machine time moves to B from that moment: the event on A ends there, and a new event on B starts. If the operator starts a Machine timer on B, the press ends the running event on A instead (see below). An operator's own Machine timer stays on its operation when another operation loads.-<Callout type="note" title="Sensor time posts when the operation finishes">-Carbon posts a sensor event to the general ledger when its operation finishes or the job completes. If an operator's Machine press ends the event first, it posts at the press. Until it posts, you can correct the event in the job's **Production Events** view.+<Callout type="note" title="Sensor time posts when it ends">+Carbon posts a sensor event to the general ledger as soon as the event ends: its machine and overhead cost goes to the job's work in progress, at the work center's machine and overhead rates. That is at the sync that ends it, at an operator's press, when the operation finishes, or when you unmap the station or uninstall Sense. You can still correct a posted event in the job's **Production Events** view; Carbon posts the difference.</Callout>### One machine time per work center@@ -117,7 +117,7 @@ Select **Review**, or open a row, to work through the rows the list shows, one a- **Not job time** dismisses the time, for example warm-up, prove-out or maintenance.- **Skip**, or <kbd>J</kbd> and <kbd>K</kbd>, move to the next and previous row.-Each answer takes you to the next row. Closing the review returns you to the list with your filters. Assigning creates a Machine production event for the row's interval and removes the row. Dismissing removes the row. A row that nobody answers is removed 30 days after the machine stopped.+Each answer takes you to the next row. Closing the review returns you to the list with your filters. Assigning creates a Machine production event for the row's interval, posts it to the general ledger, and removes the row. Dismissing removes the row and posts nothing. A row that nobody answers is removed 30 days after the machine stopped.You cannot answer a row while the machine still runs. You cannot assign time to a Done or Canceled operation, or to a locked job. Answering needs the `production` update permission.diff --git a/packages/database/src/machine-time.test.ts b/packages/database/src/machine-time.test.tsindex 6612f39bcb..dae98d087a 100644--- a/packages/database/src/machine-time.test.ts+++ b/packages/database/src/machine-time.test.ts@@ -271,7 +271,7 @@ describe.skipIf(!url)("machine time against a migrated database", () => {await unattributed("running");await unattributed("stopped", { endTime: before });- await db.transaction().execute((trx) =>+ const result = await db.transaction().execute((trx) =>endSensorMachineTime(trx, {workCenterId,companyId,@@ -280,6 +280,8 @@ describe.skipIf(!url)("machine time against a migrated database", () => {}));+ // The caller posts exactly the events it ended.+ expect(result.endedEventIds).toEqual([id("sensor")]);expect(await endedAt("productionEvent", "sensor")).toBe(true);expect(await endedAt("productionEvent", "operator")).toBeNull();expect(await endedAt("productionEvent", "other-wc")).toBeNull();diff --git a/packages/database/src/machine-time.ts b/packages/database/src/machine-time.tsindex 9144a7bdaf..cbf9975e53 100644--- a/packages/database/src/machine-time.ts+++ b/packages/database/src/machine-time.ts@@ -45,9 +45,14 @@ async function endOpenUnattributedTime(trx: KyselyTx, args: CloseArgs) {* sensor opened there — Machine events created by `system` and running* unattributed time — because no later sync of that device will close it. An operator's* own Machine event stays open. Call it under `lockWorkCenterDevice`.+ * Returns the ended event ids: the caller posts them once its transaction+ * commits.*/-export async function endSensorMachineTime(trx: KyselyTx, args: CloseArgs) {- await trx+export async function endSensorMachineTime(+ trx: KyselyTx,+ args: CloseArgs+): Promise<{ endedEventIds: string[] }> {+ const ended = await trx.updateTable("productionEvent").set({ endTime: args.at, updatedBy: args.userId, updatedAt: args.at }).where("workCenterId", "=", args.workCenterId)@@ -56,8 +61,10 @@ export async function endSensorMachineTime(trx: KyselyTx, args: CloseArgs) {.where("createdBy", "=", "system").where("endTime", "is", null).where("startTime", "<=", args.at)+ .returning("id").execute();await endOpenUnattributedTime(trx, args);+ return { endedEventIds: ended.map((row) => row.id) };}/**diff --git a/packages/database/supabase/migrations/20261014135003_lock-production-events-at-job-completion.sql b/packages/database/supabase/migrations/20261014135003_lock-production-events-at-job-completion.sqlnew file mode 100644index 0000000000..6f73d292a8--- /dev/null+++ b/packages/database/supabase/migrations/20261014135003_lock-production-events-at-job-completion.sql@@ -0,0 +1,1134 @@+-- Lock each unposted production event before job completion posts it.+--+-- Several callers post a production event: the OEE sync and the MES as the+-- event ends, an operation finish, and this function at job completion.+-- `post-production-event` locks the event row and refuses when `postedToGL`+-- changed since it read the event. This loop read the events without a lock,+-- so an event that the server function posted at the same moment could be+-- posted here a second time. `FOR UPDATE OF pe` waits for that transaction;+-- READ COMMITTED then re-checks `postedToGL = false` on the committed row and+-- skips an event that is already posted.+--+-- The body is 20261009010412_job-costing-always-post.sql's definition with+-- only that clause added.++CREATE OR REPLACE FUNCTION public.complete_job_to_inventory(p_job_id text, p_quantity_complete numeric, p_storage_unit_id text DEFAULT NULL::text, p_location_id text DEFAULT NULL::text, p_company_id text DEFAULT NULL::text, p_user_id text DEFAULT NULL::text)+ RETURNS void+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+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_posting_status "journalEntryStatus";+ 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);+ v_job_asset_class_id TEXT;+ v_job_asset_id TEXT;+ v_asset_target TEXT;+ v_target_class RECORD;+ v_asset_ids TEXT[] := '{}';+ v_transfer_ids TEXT[] := '{}';+ v_asset_unit_ids TEXT[];+ v_new_asset_id TEXT;+ v_transfer_id TEXT;+ v_per_unit_cost NUMERIC;+ v_activity_id TEXT;+ v_asset_class_id TEXT;+ v_journal_source_type "journalEntrySourceType" := 'Job Receipt';+ v_journal_document_type "journalLineDocumentType" := 'Job Receipt';+ v_journal_description TEXT;+ v_dimension_fixed_asset_class TEXT;+ i INTEGER;+BEGIN+ PERFORM assert_company_access(p_company_id);++ -- 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",+ "fixedAssetClassId", "fixedAssetId"+ 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,+ v_job_asset_class_id, v_job_asset_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;++ -- Make to Asset: a job that targets a fixed asset class completes into one+ -- new asset per unit; a job attached to a Construction in Progress asset+ -- sweeps its cost onto that asset. Either way the units never enter stock.+ v_asset_target := CASE+ WHEN v_job_asset_id IS NOT NULL THEN 'asset'+ WHEN v_job_asset_class_id IS NOT NULL THEN 'class'+ END;++ IF v_asset_target IS NOT NULL AND v_sales_order_line_id IS NOT NULL THEN+ RAISE EXCEPTION 'A job linked to a sales order line cannot complete to a fixed asset';+ 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 job that targets a class makes new assets, and every one of them is a+ -- fleet unit that rental, return to inventory and capitalization follow by+ -- its serial. So the item must be serialized, whatever the quantity.+ IF v_asset_target = 'class'+ AND v_item_tracking_type IS DISTINCT FROM 'Serial' THEN+ RAISE EXCEPTION 'A job that completes to a fixed asset class needs a serialized item';+ END IF;++ -- A sweep onto an asset under construction makes no new unit, so an+ -- unserialized item is fine there, but only as a single unit: an untracked+ -- or batch quantity cannot be told apart.+ IF v_asset_target = 'asset'+ AND v_item_tracking_type IS DISTINCT FROM 'Serial'+ AND COALESCE(p_quantity_complete, 0) <> 1 THEN+ RAISE EXCEPTION 'Make to Asset needs a serialized item or a quantity of one';+ END IF;++ -- 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;++ -- Make to Asset: the newly completed units leave the job as fixed assets+ -- instead of stock. Assets and their transfers are created at cost 0 here and+ -- priced once the WIP journal exists below; with accounting disabled they stay+ -- at 0, the same posture as registering an asset with accounting off.+ IF v_asset_target IS NOT NULL AND v_quantity_received_to_inventory > 0 THEN+ IF v_asset_target = 'class' THEN+ SELECT fac.*+ INTO STRICT v_target_class+ FROM "fixedAssetClass" fac+ WHERE fac.id = v_job_asset_class_id+ AND fac."companyId" = p_company_id;+ ELSE+ SELECT fac.*+ INTO STRICT v_target_class+ FROM "fixedAsset" fa+ JOIN "fixedAssetClass" fac ON fac.id = fa."fixedAssetClassId"+ WHERE fa.id = v_job_asset_id+ AND fa."companyId" = p_company_id;++ -- Only a Construction in Progress asset accumulates cost; sweeping WIP+ -- onto a live, depreciating asset would restate its basis.+ IF NOT v_target_class."isConstructionInProgress" THEN+ RAISE EXCEPTION 'Job % targets fixed asset % which is not in a Construction in Progress class',+ v_job_id_readable, v_job_asset_id;+ END IF;+ END IF;+ v_asset_class_id := v_target_class.id;++ IF v_job_make_method."requiresSerialTracking" THEN+ -- The same unit order as a receipt: shop-floor-finished units first, then+ -- by serial number. A unit already turned into an asset is never taken+ -- twice (it is Consumed and carries the asset id).+ v_asset_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 (te.attributes ? 'Fixed Asset')+ 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_asset_unit_ids, 1), 0) < v_quantity_received_to_inventory THEN+ RAISE EXCEPTION 'Job % has % serial unit(s) left to capitalize, fewer than the % being completed',+ v_job_id_readable, COALESCE(array_length(v_asset_unit_ids, 1), 0), v_quantity_received_to_inventory;+ END IF;++ v_asset_unit_ids := v_asset_unit_ids[1:v_quantity_received_to_inventory::INTEGER];+ ELSE+ -- A class target makes one asset per serial unit. A job created before+ -- its item was serialized has no units to follow, and would otherwise+ -- make ONE asset for the whole quantity.+ IF v_asset_target = 'class' THEN+ RAISE EXCEPTION 'Job % does not track serial numbers, so it cannot complete to a fixed asset class',+ v_job_id_readable;+ END IF;+ -- One untracked or batch unit swept onto an asset under construction; the+ -- guard above holds the quantity at 1.+ v_asset_unit_ids := ARRAY[NULL::TEXT];+ END IF;++ FOR i IN 1..array_length(v_asset_unit_ids, 1) LOOP+ IF v_asset_target = 'class' THEN+ INSERT INTO "fixedAsset" (+ "fixedAssetId", "fixedAssetClassId", name, "serialNumber",+ "itemId", "trackedEntityId", quantity, status,+ "depreciationMethod", "usefulLifeMonths", "residualValuePercent",+ "acquisitionCost", "acquisitionDate", "depreciationStartDate",+ "locationId", "companyId", "createdBy"+ )+ SELECT+ get_next_sequence('fixedAsset', p_company_id), v_job_asset_class_id,+ it.name || ' ' || COALESCE(te."readableId", v_job_id_readable), te."readableId",+ v_item_id, v_asset_unit_ids[i], 1,+ CASE WHEN v_target_class."isConstructionInProgress" THEN 'Under Construction' ELSE 'Active' END::"fixedAssetStatus",+ v_target_class."depreciationMethod", v_target_class."usefulLifeMonths", v_target_class."residualValuePercent",+ 0, v_company_today, v_company_today,+ v_job_location_id, p_company_id, p_user_id+ FROM "item" it+ LEFT JOIN "trackedEntity" te ON te.id = v_asset_unit_ids[i]+ WHERE it.id = v_item_id+ RETURNING id INTO v_new_asset_id;++ INSERT INTO "fixedAssetTransfer" (+ "transferId", type, "sourceType", "fixedAssetId", "itemId", "trackedEntityId",+ "jobId", "locationId", quantity, "transferDate", amount, status,+ "postedAt", "postedBy", "companyId", "createdBy"+ ) VALUES (+ get_next_sequence('fixedAssetTransfer', p_company_id), 'Capitalization', 'Job',+ v_new_asset_id, v_item_id, v_asset_unit_ids[i],+ p_job_id, v_job_location_id, 1, v_company_today, 0, 'Posted',+ NOW(), p_user_id, p_company_id, p_user_id+ )+ RETURNING id INTO v_transfer_id;++ v_asset_ids := v_asset_ids || v_new_asset_id;+ v_transfer_ids := v_transfer_ids || v_transfer_id;+ ELSE+ v_new_asset_id := v_job_asset_id;+ END IF;++ -- The unit is consumed into the asset: it is no longer stock, and the+ -- asset id on its attributes is how the fleet finds it again.+ IF v_asset_unit_ids[i] IS NOT NULL THEN+ UPDATE "trackedEntity"+ SET status = 'Consumed',+ attributes = COALESCE(attributes, '{}'::jsonb) || jsonb_build_object('Fixed Asset', v_new_asset_id)+ WHERE id = v_asset_unit_ids[i];++ INSERT INTO "trackedActivity" (+ type, "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",+ attributes, "companyId", "createdBy"+ )+ SELECT+ 'Capitalize', 'Fixed Asset', fa.id, fa."fixedAssetId",+ jsonb_build_object('Fixed Asset', fa.id, 'Job', p_job_id), p_company_id, p_user_id+ FROM "fixedAsset" fa+ WHERE fa.id = v_new_asset_id+ RETURNING id INTO v_activity_id;++ INSERT INTO "trackedActivityInput" (+ "trackedActivityId", "trackedEntityId", quantity, "companyId", "createdBy"+ ) VALUES (+ v_activity_id, v_asset_unit_ids[i], 1, p_company_id, p_user_id+ );+ END IF;+ END LOOP;+ END IF;++ -- Complete the quantities behind the status: raise the terminal operations so+ -- the routing agrees with a Completed job, and refuse a serial job whose units+ -- still need serial numbers.+ --+ -- AFTER the status flip, never before. Closing an operation fires+ -- sync_finish_job_operation, which re-enters this function for a job in+ -- Ready/In Progress/Paused. Being a BEFORE row trigger it runs mid-statement,+ -- so it reads the operation's OLD quantityComplete (still 0 on a desk+ -- completion), falls back to the job's planned quantity and receives a second+ -- time — while this call's own receipt delta was computed further up, before+ -- any of it happened. With the job already Completed the interceptor's status+ -- gate returns early, so the operations close without a second receipt.+ PERFORM complete_job_remaining_quantities(p_job_id, p_quantity_complete, p_user_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_asset_target IS NULL+ 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;++ -- The job's own lot can already be Consumed by a lot MERGE: the batch+ -- completion prompt offers the merge before member jobs are received,+ -- and the merge is identity-only (it moves no unreceived stock). This+ -- job's receipt must then land on the merge's output lot — walk Merge+ -- activities from the job's lot to the terminal, still-live output.+ IF v_tracked_entity.id IS NULL THEN+ WITH RECURSIVE merge_walk(id) AS (+ SELECT te.id+ FROM "trackedEntity" te+ WHERE te.attributes->>'Job Make Method' = v_job_make_method.id+ AND te."companyId" = p_company_id+ UNION+ SELECT tao."trackedEntityId"+ FROM merge_walk+ JOIN "trackedActivityInput" tai+ ON tai."trackedEntityId" = merge_walk.id+ AND tai."companyId" = p_company_id+ JOIN "trackedActivity" ta+ ON ta.id = tai."trackedActivityId"+ AND ta."companyId" = p_company_id+ AND ta.type = 'Merge'+ JOIN "trackedActivityOutput" tao+ ON tao."trackedActivityId" = ta.id+ AND tao."companyId" = p_company_id+ )+ SELECT te.*+ INTO v_tracked_entity+ FROM merge_walk+ JOIN "trackedEntity" te ON te.id = merge_walk.id+ WHERE te.status != 'Consumed'+ ORDER BY te."createdAt" DESC+ LIMIT 1;+ END IF;++ 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 v_asset_target IS NULL 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);++ -- Every company posts; the accounting cutover decides the status+ -- (.ai/specs/2026-10-08-accounting-cutover.md section 1).+ v_posting_status := journal_posting_status(p_company_id);++ -- 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),+ MAX(CASE WHEN "entityType" = 'FixedAssetClass' THEN id END)+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location,+ v_dimension_cost_center, v_dimension_employee, v_dimension_fixed_asset_class+ FROM dimension+ WHERE "companyGroupId" = v_company_group_id+ AND active = true+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location', 'CostCenter', 'Employee', 'FixedAssetClass');++ -- 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+ ORDER BY pe.id+ -- Waits for a concurrent post-production-event, then skips the event if+ -- it posted it (the WHERE is re-checked on the committed row).+ FOR UPDATE OF pe+ 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 AND v_posting_status = 'Posted' 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;++ -- A Provisional journal has no accounting period (spec section 1).+ IF v_posting_status <> 'Posted' THEN+ v_labor_accounting_period_id := NULL;+ 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', v_posting_status,+ 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+ AND j."status" IN ('Provisional', 'Posted', 'Reversed');++ 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;++ -- Make to Asset: the swept WIP lands on the target class's asset account as+ -- an Asset Transfer journal. Both lines stay documented against the job so+ -- the WIP credit still nets this job's WIP to zero for a re-completion.+ IF v_asset_target IS NOT NULL THEN+ v_item_inventory_account := v_target_class."assetAccountId";+ v_item_inventory_description := 'Fixed Asset';+ v_journal_source_type := 'Asset Transfer';+ v_journal_document_type := 'Asset Transfer';+ v_journal_description := 'Job Completion to Fixed Asset ' || v_job_id_readable;+ ELSE+ v_journal_description := 'Job Completion ' || v_job_id_readable;+ 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 AND v_posting_status = 'Posted' 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;++ -- A Provisional journal has no accounting period (spec section 1).+ IF v_posting_status <> 'Posted' THEN+ v_accounting_period_id := NULL;+ 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,+ v_journal_description,+ v_today, p_company_id, v_journal_source_type, v_posting_status,+ 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,+ v_journal_document_type, 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,+ v_journal_document_type, 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' AND v_asset_target IS NULL 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' AND v_asset_target IS NULL 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;++ -- Make to Asset: price the assets created above from the swept WIP and link+ -- their transfers to the journal. A Construction in Progress target takes the+ -- whole cost as one CIP cost row and one transfer.+ IF v_asset_target = 'class' THEN+ -- Rounded at persist; the last asset takes the residual so the assets add+ -- up to exactly the WIP the journal debits to the asset account.+ v_per_unit_cost := ROUND(v_accumulated_wip_cost / array_length(v_asset_ids, 1), 5);++ UPDATE "fixedAsset"+ SET "acquisitionCost" = CASE+ WHEN id = v_asset_ids[array_length(v_asset_ids, 1)]+ THEN v_accumulated_wip_cost - v_per_unit_cost * (array_length(v_asset_ids, 1) - 1)+ ELSE v_per_unit_cost+ END,+ "updatedAt" = NOW(),+ "updatedBy" = p_user_id+ WHERE id = ANY(v_asset_ids);++ UPDATE "fixedAssetTransfer"+ SET amount = CASE+ WHEN id = v_transfer_ids[array_length(v_transfer_ids, 1)]+ THEN v_accumulated_wip_cost - v_per_unit_cost * (array_length(v_transfer_ids, 1) - 1)+ ELSE v_per_unit_cost+ END,+ "journalId" = v_journal_id,+ "updatedAt" = NOW(),+ "updatedBy" = p_user_id+ WHERE id = ANY(v_transfer_ids);+ ELSIF v_asset_target = 'asset' THEN+ INSERT INTO "fixedAssetCipCost" (+ "fixedAssetId", "sourceType", "jobId", amount, "costDate", "journalId", "companyId", "createdBy"+ ) VALUES (+ v_job_asset_id, 'Job', p_job_id, v_accumulated_wip_cost, v_company_today, v_journal_id, p_company_id, p_user_id+ );++ UPDATE "fixedAsset"+ SET "acquisitionCost" = "acquisitionCost" + v_accumulated_wip_cost,+ status = 'Under Construction',+ "updatedAt" = NOW(),+ "updatedBy" = p_user_id+ WHERE id = v_job_asset_id;++ INSERT INTO "fixedAssetTransfer" (+ "transferId", type, "sourceType", "fixedAssetId", "itemId", "jobId",+ "locationId", quantity, "transferDate", amount, "journalId", status,+ "postedAt", "postedBy", "companyId", "createdBy"+ ) VALUES (+ get_next_sequence('fixedAssetTransfer', p_company_id), 'Capitalization', 'Job',+ v_job_asset_id, v_item_id, p_job_id,+ v_job_location_id, v_quantity_received_to_inventory, v_company_today, v_accumulated_wip_cost, v_journal_id, 'Posted',+ NOW(), p_user_id, p_company_id, p_user_id+ );+ 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;++ IF v_asset_class_id IS NOT NULL AND v_dimension_fixed_asset_class IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_jl_ids[i], v_dimension_fixed_asset_class, v_asset_class_id, p_company_id+ );+ END IF;+ END LOOP;+ END IF;+END;+$function$;diff --git a/packages/ee/src/oee/service.server.ts b/packages/ee/src/oee/service.server.tsindex b4693f5da7..f9d25adec8 100644--- a/packages/ee/src/oee/service.server.ts+++ b/packages/ee/src/oee/service.server.ts@@ -5,6 +5,8 @@import type { Database } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";import { endSensorMachineTime } from "@carbon/database/machine-time";+import { getLogger } from "@carbon/logger";+import { serverFns } from "@carbon/server-functions";import { datetime } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { EntitlementError, requireEntitlement } from "../entitlements.server";@@ -21,6 +23,8 @@ import type { OeeProvider } from "./types";* and degrades through `companyHasFeature` instead of throwing.*/+const logger = getLogger("ee", "oee");+type Result<T> = { data: T; error: null } | { data: null; error: string };const fail = (error: unknown): { data: null; error: string } => {@@ -67,6 +71,38 @@ export async function getOeeProvider(}}+/**+ * Posts the Machine events that sensor time ended (machine and overhead cost+ * to WIP), as an operator's press posts the events it ends. Call it after the+ * transaction that ended them commits. A failure is logged, never thrown: the+ * operation-finish and job-completion catch-ups post what is still unposted.+ */+export async function postEndedMachineEvents(+ db: Kysely<KyselyDatabase>,+ args: { companyId: string; userId: string; productionEventIds: string[] }+) {+ if (args.productionEventIds.length === 0) return;+ const functions = serverFns.system({+ db,+ companyId: args.companyId,+ userId: args.userId+ });+ for (const productionEventId of args.productionEventIds) {+ const posted = await functions.invoke("post-production-event", {+ productionEventId+ });+ // `success: false` is an event with nothing to post yet (no duration):+ // the catch-ups take it once it has one.+ if (posted.error) {+ logger.error("Failed to post a Machine event", {+ companyId: args.companyId,+ productionEventId,+ error: posted.error.message+ });+ }+ }+}+export async function upsertWorkCenterDevice(client: SupabaseClient<Database>,db: Kysely<KyselyDatabase>,@@ -92,7 +128,8 @@ export async function upsertWorkCenterDevice(error: `${args.integration} is not an OEE provider`};}- return await db.transaction().execute(async (trx) => {+ let endedEventIds: string[] = [];+ const result = await db.transaction().execute(async (trx) => {const integration = await trx.selectFrom("companyIntegration").select("active")@@ -154,12 +191,12 @@ export async function upsertWorkCenterDevice(// time the device opened on its old work center ends now; no later// sync of the old mapping will close it.if (current) {- await endSensorMachineTime(trx, {+ ({ endedEventIds } = await endSensorMachineTime(trx, {workCenterId: current.workCenterId,companyId: args.companyId,userId: args.userId,at: datetime.timestamp()- });+ }));await trx.deleteFrom("workCenterDevice").where("id", "=", current.id)@@ -183,6 +220,12 @@ export async function upsertWorkCenterDevice(.executeTakeFirstOrThrow();return { data: { id: inserted.id }, error: null };});+ await postEndedMachineEvents(db, {+ companyId: args.companyId,+ userId: args.userId,+ productionEventIds: endedEventIds+ });+ return result;} catch (error) {return fail(error);}@@ -200,7 +243,7 @@ export async function deleteWorkCenterDevice(): Promise<Result<null>> {await requireEntitlement(client, args.companyId, "INTEGRATIONS");try {- await db.transaction().execute(async (trx) => {+ const endedEventIds = await db.transaction().execute(async (trx) => {const device = await trx.selectFrom("workCenterDevice").select(["id", "workCenterId"])@@ -209,11 +252,11 @@ export async function deleteWorkCenterDevice(.where("companyId", "=", args.companyId).forUpdate().executeTakeFirst();- if (!device) return;+ if (!device) return [];// Nothing syncs this work center after the delete, so the time its// sensor opened ends now instead of staying open forever.- await endSensorMachineTime(trx, {+ const ended = await endSensorMachineTime(trx, {workCenterId: device.workCenterId,companyId: args.companyId,userId: args.userId,@@ -224,6 +267,12 @@ export async function deleteWorkCenterDevice(.where("id", "=", device.id).where("companyId", "=", args.companyId).execute();+ return ended.endedEventIds;+ });+ await postEndedMachineEvents(db, {+ companyId: args.companyId,+ userId: args.userId,+ productionEventIds: endedEventIds});return { data: null, error: null };} catch (error) {@@ -233,8 +282,8 @@ export async function deleteWorkCenterDevice(/*** Assign unattributed time to an operation: insert a Machine event for its- * interval and delete the row. The event is the record; the row was only a- * question waiting for an answer.+ * interval and delete the row, then post the event. The event is the record;+ * the row was only a question waiting for an answer.*/export async function assignUnattributedMachineTime(client: SupabaseClient<Database>,@@ -248,7 +297,7 @@ export async function assignUnattributedMachineTime(): Promise<Result<{ productionEventId: string }>> {await requireEntitlement(client, args.companyId, "INTEGRATIONS");try {- return await db.transaction().execute(async (trx) => {+ const result = await db.transaction().execute(async (trx) => {const row = await trx.selectFrom("unattributedMachineTime").select(["workCenterId", "startTime", "endTime"])@@ -308,6 +357,14 @@ export async function assignUnattributedMachineTime(return { data: { productionEventId: event.id }, error: null };});+ if (result.data) {+ await postEndedMachineEvents(db, {+ companyId: args.companyId,+ userId: args.userId,+ productionEventIds: [result.data.productionEventId]+ });+ }+ return result;} catch (error) {return fail(error);}diff --git a/packages/ee/src/sense/hooks.server.ts b/packages/ee/src/sense/hooks.server.tsindex 0f3538f7b5..8812cf6eb4 100644--- a/packages/ee/src/sense/hooks.server.ts+++ b/packages/ee/src/sense/hooks.server.ts@@ -11,6 +11,7 @@ import {import { datetime } from "@carbon/utils";import { PostgresDriver } from "kysely";import { createOeeProvider } from "../oee/registry";+import { postEndedMachineEvents } from "../oee/service.server";import type { IntegrationHealthcheckResult } from "../types";/** `metadata` arrives with the vaulted `apiKey` already resolved. */@@ -34,8 +35,9 @@ export async function senseHealthcheck(/*** Disconnecting Sense stops its sync, so nothing would ever close the time its* sensors opened: each device's open sensor Machine event and running- * unattributed time end now, under the device lock. The device mappings stay,- * so reconnecting resumes from where each device left off.+ * unattributed time end now, under the device lock, and the ended events+ * post. The device mappings stay, so reconnecting resumes from where each+ * device left off.*/export async function senseOnUninstall(companyId: string) {const db = getPostgresClient<KyselyDatabase>(@@ -50,14 +52,19 @@ export async function senseOnUninstall(companyId: string) {.execute();const at = datetime.timestamp();for (const { workCenterId } of devices) {- await db.transaction().execute(async (trx) => {+ const { endedEventIds } = await db.transaction().execute(async (trx) => {await lockWorkCenterDevice(trx, { workCenterId, companyId });- await endSensorMachineTime(trx, {+ return endSensorMachineTime(trx, {workCenterId,companyId,userId: "system",at});});+ await postEndedMachineEvents(db, {+ companyId,+ userId: "system",+ productionEventIds: endedEventIds+ });}}diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.mdindex 578d672aca..4c28fd4ab0 100644--- a/packages/jobs/AGENTS.md+++ b/packages/jobs/AGENTS.md@@ -58,7 +58,7 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +| `ramp-sync` | `carbon/ramp-sync` | Company-serialized Ramp family sync || `ramp-sweep` | `0 * * * *` | Dispatch Ramp sync for every active install || `oee-sweep` | `*/2 * * * *` | Sends one `carbon/oee-sync` per (company, OEE integration) that is active and has at least 1 `workCenterDevice`. OEE providers have no webhooks, so this poll is the only input |-| `oee-sync` | `carbon/oee-sync` (concurrency 1 per company; `singleton` with `mode: "skip"` per company and integration, so an event that arrives while a run is live is dropped) | Syncs every mapped device of one OEE integration in ONE `step.run` (`syncOeeDevice`, `oee-sync-device.ts`): reads the provider's state changes from `lastEventAt − 10 minutes` (24 hours before the mapping on a first sync), stores them in `machineStateChange`, then under `lockWorkCenterDevice` reads the loads (`workCenterLoad`), maintenance block periods and recorded machine time in a bounded window, runs `planMachineTime` and writes Machine `productionEvent` / `unattributedMachineTime` rows; it clears `workCenterDevice.unplannedPressAt` and deletes closed unattributed rows shorter than `minimumStateSeconds`. A failed device gets `lastSyncError` and keeps its cursor; the others continue, except on `OeeProviderUnavailableError` (network failure, timeout, 5xx), which stops the run. Skipped (no error) when the company is not entitled, the integration is inactive or the key is empty. Never posts to the GL. See `.claude/rules/oee-provider.md` |+| `oee-sync` | `carbon/oee-sync` (concurrency 1 per company; `singleton` with `mode: "skip"` per company and integration, so an event that arrives while a run is live is dropped) | Syncs every mapped device of one OEE integration in ONE `step.run` (`syncOeeDevice`, `oee-sync-device.ts`): reads the provider's state changes from `lastEventAt − 10 minutes` (24 hours before the mapping on a first sync), stores them in `machineStateChange`, then under `lockWorkCenterDevice` reads the loads (`workCenterLoad`), maintenance block periods and recorded machine time in a bounded window, runs `planMachineTime` and writes Machine `productionEvent` / `unattributedMachineTime` rows; it clears `workCenterDevice.unplannedPressAt` and deletes closed unattributed rows shorter than `minimumStateSeconds`. A failed device gets `lastSyncError` and keeps its cursor; the others continue, except on `OeeProviderUnavailableError` (network failure, timeout, 5xx), which stops the run. Skipped (no error) when the company is not entitled, the integration is inactive or the key is empty. After each device commits, posts the Machine events its sync ended (`endedEventIds` → `postEndedMachineEvents`, `post-production-event` as `userId "system"`); a posting failure is logged, never fails the device. See `.claude/rules/oee-provider.md` || `mount-publish` | `carbon/mount-publish` | One company's push to Mount: a step per batch of 200 until nothing is stale, a batch publishes nothing, or 50 batches; progress and outcome in `companyIntegration.metadata.lastPublish.{entityType}`, which the integration page reads || `mount-sweep` | `30 2 * * *` | Dispatch a scheduled `mount-publish` for every active Mount install || `workflow-run` | `carbon/workflow-run.queued` | Execute one owner-scoped workflow graph |diff --git a/packages/jobs/src/inngest/functions/integrations/oee-sync-device.database.test.ts b/packages/jobs/src/inngest/functions/integrations/oee-sync-device.database.test.tsindex ae274defd7..acab472f1f 100644--- a/packages/jobs/src/inngest/functions/integrations/oee-sync-device.database.test.ts+++ b/packages/jobs/src/inngest/functions/integrations/oee-sync-device.database.test.ts@@ -293,7 +293,7 @@ describe.skipIf(!hasLocalDatabase)(}]);- await sync(provider);+ const result = await sync(provider);expect(await machineEvents()).toEqual([{@@ -304,6 +304,8 @@ describe.skipIf(!hasLocalDatabase)(endTime: null}]);+ // An open event has nothing to post yet.+ expect(result.endedEventIds).toEqual([]);expect(await unattributedTime()).toEqual([]);expect(await deviceState()).toEqual({currentState: "Running",@@ -435,7 +437,7 @@ describe.skipIf(!hasLocalDatabase)();const { provider } = fakeProvider([]);- await sync(provider);+ const result = await sync(provider);expect(await machineEvents()).toEqual([{@@ -446,6 +448,8 @@ describe.skipIf(!hasLocalDatabase)(endTime: "2026-10-13T10:45:00.000Z"}]);+ // The event it ended goes to the caller to post.+ expect(result.endedEventIds).toEqual([id("running")]);// The machine still runs with nothing loaded: the rest is unattributed.expect(await unattributedTime()).toEqual([{ startTime: "2026-10-13T10:45:00.000Z", endTime: null }diff --git a/packages/jobs/src/inngest/functions/integrations/oee-sync-device.ts b/packages/jobs/src/inngest/functions/integrations/oee-sync-device.tsindex 2a59823756..2a0b20ebee 100644--- a/packages/jobs/src/inngest/functions/integrations/oee-sync-device.ts+++ b/packages/jobs/src/inngest/functions/integrations/oee-sync-device.ts@@ -137,6 +137,10 @@ export async function syncOeeDevice({// the next sync's 10-minute overlap. With nothing stored it stays put.const lastEventAt = inserted.reduce(later, toInstant(device.lastEventAt));+ // The Machine events this sync ended (closed, or inserted closed). The+ // caller posts them to the GL once the transaction commits.+ const endedEventIds: string[] = [];+await db.transaction().execute(async (trx) => {const locked = await lockWorkCenterDevice(trx, {workCenterId: device.workCenterId,@@ -371,8 +375,8 @@ export async function syncOeeDevice({for (const write of plan.writes) {switch (write.kind) {- case "insertMachineEvent":- await trx+ case "insertMachineEvent": {+ const inserted = await trx.insertInto("productionEvent").values({type: "Machine",@@ -384,10 +388,15 @@ export async function syncOeeDevice({companyId: device.companyId,createdBy: "system"})- .execute();+ .returning("id")+ .executeTakeFirstOrThrow();+ if (write.endTime !== null) endedEventIds.push(inserted.id);break;- case "closeMachineEvent":- await trx+ }+ case "closeMachineEvent": {+ // Matches only while open: an event a press ended meanwhile is the+ // press's to post.+ const closed = await trx.updateTable("productionEvent").set({endTime: write.endTime,@@ -397,8 +406,11 @@ export async function syncOeeDevice({.where("id", "=", write.productionEventId).where("companyId", "=", device.companyId).where("endTime", "is", null)- .execute();+ .returning("id")+ .executeTakeFirst();+ if (closed) endedEventIds.push(closed.id);break;+ }case "insertUnattributed":await trx.insertInto("unattributedMachineTime")@@ -478,5 +490,5 @@ export async function syncOeeDevice({.execute();});- return { changes: changes.length };+ return { changes: changes.length, endedEventIds };}diff --git a/packages/jobs/src/inngest/functions/integrations/oee-sync.ts b/packages/jobs/src/inngest/functions/integrations/oee-sync.tsindex 1dcd87bc38..fda0b45400 100644--- a/packages/jobs/src/inngest/functions/integrations/oee-sync.ts+++ b/packages/jobs/src/inngest/functions/integrations/oee-sync.ts@@ -5,14 +5,15 @@/*** Syncs every mapped device of one company's OEE integration. All devices run* in ONE step: a step per device would multiply the Inngest cost by the device- * count every 2 minutes. Each device is isolated — a failure is recorded on+ * count every 2 minutes. The Machine events a device's sync ends post to the+ * GL right after it commits. Each device is isolated — a failure is recorded on* that device (`lastSyncError`) and keeps its cursor; the others continue.* An `OeeProviderUnavailableError` stops the run instead: every remaining* device would fail the same way.*/import { getCarbonServiceRole } from "@carbon/auth/client.server";import { OeeProviderUnavailableError } from "@carbon/ee/oee";-import { getOeeProvider } from "@carbon/ee/oee.server";+import { getOeeProvider, postEndedMachineEvents } from "@carbon/ee/oee.server";import { getJobDatabaseClient } from "../../../db";import { inngest } from "../../client";import { syncOeeDevice } from "./oee-sync-device";@@ -72,7 +73,18 @@ export const oeeSyncFunction = inngest.createFunction(let stopped: string | undefined;for (const device of devices) {try {- await syncOeeDevice({ db, provider, device, minimumStateSeconds });+ const { endedEventIds } = await syncOeeDevice({+ db,+ provider,+ device,+ minimumStateSeconds+ });+ // Sensor time posts when it ends, as an operator's press does.+ await postEndedMachineEvents(db, {+ companyId,+ userId: "system",+ productionEventIds: endedEventIds+ });} catch (error) {const message =error instanceof Error ? error.message : String(error);diff --git a/packages/server-functions/src/always-post-production.test.ts b/packages/server-functions/src/always-post-production.test.tsindex 17a41be393..e85f7f4615 100644--- a/packages/server-functions/src/always-post-production.test.ts+++ b/packages/server-functions/src/always-post-production.test.ts@@ -276,6 +276,83 @@ databaseTest(});+databaseTest(+ "two posts of one production event at once absorb its cost once",+ async () => {+ const f = await alwaysPostFixture();+ try {+ const workCenterId = await workCenterFixture(f);+ const job = await jobFixture(f, "1");+ const eventId = await laborEvent(f, job.operationId, workCenterId);++ // The OEE sync posts a sensor event as it ends it while an operation+ // finish posts the same event: the second must not add it again.+ const results: Awaited<ReturnType<typeof postProductionEvent>>[] = [];+ const journals = await newJournals(f, async () => {+ results.push(+ ...(await Promise.all([+ postProductionEvent(f.ctx, { productionEventId: eventId }),+ postProductionEvent(f.ctx, { productionEventId: eventId })+ ]))+ );+ });++ const wip = (await journalLinesOf(f, journals))+ .filter((line) => line.accountId === f.account("wip"))+ .reduce((sum, line) => sum + line.amount, 0);+ expect(wip).toBe(60);+ for (const result of results) {+ if (result.error) expect(result.error.status).toBe(409);+ }+ } finally {+ await f.cleanup();+ }+ }+);++databaseTest(+ "two reposts of one edited production event at once adjust it once",+ async () => {+ const f = await alwaysPostFixture();+ try {+ const workCenterId = await workCenterFixture(f);+ const job = await jobFixture(f, "1");+ const eventId = await laborEvent(f, job.operationId, workCenterId);+ const posted = await newJournals(f, async () =>+ unwrap(await postProductionEvent(f.ctx, { productionEventId: eventId }))+ );++ // Edited to two hours, then reposted by two callers at once. Both read+ // the same prior lines: the second must not reverse 60 and add 120+ // on top of the first's adjustment.+ await f.db+ .updateTable("productionEvent")+ .set({ startTime: sql<string>`now() - interval '2 hours'` })+ .where("id", "=", eventId)+ .execute();+ const results: Awaited<ReturnType<typeof postProductionEvent>>[] = [];+ const adjustments = await newJournals(f, async () => {+ results.push(+ ...(await Promise.all([+ postProductionEvent(f.ctx, { productionEventId: eventId }),+ postProductionEvent(f.ctx, { productionEventId: eventId })+ ]))+ );+ });++ const wip = (await journalLinesOf(f, [...posted, ...adjustments]))+ .filter((line) => line.accountId === f.account("wip"))+ .reduce((sum, line) => sum + line.amount, 0);+ expect(wip).toBe(120);+ for (const result of results) {+ if (result.error) expect(result.error.status).toBe(409);+ }+ } finally {+ await f.cleanup();+ }+ }+);+databaseTest("a maintenance event posts a labor absorption stand-in before the cutover and refuses an empty default after it",async () => {diff --git a/packages/server-functions/src/post-production-event/index.ts b/packages/server-functions/src/post-production-event/index.tsindex ba82a82a68..06e1b25daf 100644--- a/packages/server-functions/src/post-production-event/index.ts+++ b/packages/server-functions/src/post-production-event/index.ts@@ -4,6 +4,7 @@import { getCompanyTimeZone, journalReference } from "@carbon/database";import { DOCUMENT_JOURNAL_STATUSES } from "@carbon/database/accounting-posting";+import type { Kysely, KyselyDatabase } from "@carbon/database/client";import {assertPostingStatusUnchanged,journalPostingStatus,@@ -24,7 +25,7 @@ import { credit, datetime, debit, round } from "@carbon/utils";import { nanoid } from "nanoid";import { z } from "zod";import { defineServerFn } from "../define-server-fn";-import { InvalidInputError, NotFoundError } from "../errors";+import { InvalidInputError, NotFoundError, ServerFnError } from "../errors";import { TIME_ENTRY_BEFORE_CUTOVER_ERROR } from "../lib/cutover-void";import { getCurrentAccountingPeriod } from "../lib/get-accounting-period";import { getDefaultPostingGroup } from "../lib/get-posting-group";@@ -44,6 +45,45 @@ export const postProductionEventInput = z.object({*/export type PostProductionEventResult = { success: boolean; reason?: string };+export const PRODUCTION_EVENT_POSTED_CONCURRENTLY_ERROR =+ "This production event was just posted by another process.";++/** The net amount posted for one event so far, per account. */+async function readPostedNet(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ eventReference: string+) {+ const lines = await db+ .selectFrom("journalLine")+ .innerJoin("journal", (join) =>+ join+ .onRef("journal.id", "=", "journalLine.journalId")+ .onRef("journal.companyId", "=", "journalLine.companyId")+ )+ .select([+ "journalLine.accountId",+ "journalLine.accountDefaultRole",+ (eb) => eb.fn.sum("journalLine.amount").as("amount")+ ])+ .where("journalLine.documentLineReference", "=", eventReference)+ .where("journalLine.companyId", "=", companyId)+ .where("journal.status", "in", [...DOCUMENT_JOURNAL_STATUSES])+ .groupBy(["journalLine.accountId", "journalLine.accountDefaultRole"])+ .execute();+ return lines.filter((line) => Math.abs(Number(line.amount)) >= 0.000001);+}++/** A posted net as one comparable value, independent of row order. */+const postedNetKey = (lines: Awaited<ReturnType<typeof readPostedNet>>) =>+ lines+ .map(+ (line) =>+ `${line.accountId}|${line.accountDefaultRole ?? ""}|${round(Number(line.amount))}`+ )+ .sort()+ .join(";");+/** Posts (or reverses) a production event's labor/machine and overhead cost to WIP. */const postProductionEvent = defineServerFn({name: "post-production-event",@@ -224,28 +264,9 @@ const postProductionEvent = defineServerFn({throw new InvalidInputError(TIME_ENTRY_BEFORE_CUTOVER_ERROR);}}- const priorLines = event.postedToGL- ? await db- .selectFrom("journalLine")- .innerJoin("journal", (join) =>- join- .onRef("journal.id", "=", "journalLine.journalId")- .onRef("journal.companyId", "=", "journalLine.companyId")- )- .select([- "journalLine.accountId",- "journalLine.accountDefaultRole",- (eb) => eb.fn.sum("journalLine.amount").as("amount")- ])- .where("journalLine.documentLineReference", "=", eventReference)- .where("journalLine.companyId", "=", companyId)- .where("journal.status", "in", [...DOCUMENT_JOURNAL_STATUSES])- .groupBy(["journalLine.accountId", "journalLine.accountDefaultRole"])- .execute()+ const reversalLines = event.postedToGL+ ? await readPostedNet(db, companyId, eventReference): [];- const reversalLines = priorLines.filter(- (line) => Math.abs(Number(line.amount)) >= 0.000001- );// Did this event's job post any production-event lines under the old// job-tagged scheme (documentLineReference = job:...)? Those can't be@@ -437,6 +458,32 @@ const postProductionEvent = defineServerFn({await db.transaction().execute(async (trx) => {await assertPostingStatusUnchanged(trx, companyId, postingStatus);+ // Several callers post an event as it ends: a press, the OEE sync, an+ // operation finish, an edit's repost. Under the row lock, a second+ // caller that read the event before the first committed sees what the+ // first wrote and stops, instead of posting the cost or the adjustment+ // twice: the flag for a first post, the net already posted for a+ // repost (the flag stays true across reposts).+ const locked = await trx+ .selectFrom("productionEvent")+ .select("postedToGL")+ .where("id", "=", productionEventId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (+ !locked ||+ locked.postedToGL !== event.postedToGL ||+ (locked.postedToGL &&+ postedNetKey(await readPostedNet(trx, companyId, eventReference)) !==+ postedNetKey(reversalLines))+ ) {+ throw new ServerFnError(+ PRODUCTION_EVENT_POSTED_CONCURRENTLY_ERROR,+ 409+ );+ }+const journalEntryId = await getNextSequence(trx,"journalEntry",