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
Merge remote-tracking branch 'origin/main' into feat/serial-number-timing
Raul1bdcc0d488e5
diff --cc apps/erp/app/modules/production/AGENTS.mdindex 1b4031a2db,21b74e0225..30433d3646--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@@ -34,22 -34,12 +34,22 @@@ Work orders (jobs), scheduling, routing### Job completion- `complete_job_to_inventory` (SQL, newest `20261027064600_serial-number-timing-completion.sql`, before it `20261015161847_job-receipt-takes-issued-serial-units.sql`, `20261014171619_receive-consumed-serial-units.sql`, `20261014135003_lock-production-events-at-job-completion.sql` (locks the unposted events it posts), `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: `completeJob` (the ERP complete route and the API/MCP tool) and the `sync_finish_job_operation` trigger interceptor both 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: `completeJob` (the ERP complete route and the API/MCP tool) and the `sync_finish_job_operation` trigger interceptor both go through it.++`complete_job_to_inventory` (SQL, newest `20261028153518_serial-number-timing-completion.sql`, before it `20261015161847_job-receipt-takes-issued-serial-units.sql`, `20261014171619_receive-consumed-serial-units.sql`, `20261014135003_lock-production-events-at-job-completion.sql` (locks the unposted events it posts), `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: `completeJob` (the ERP complete route and the API/MCP tool) and the `sync_finish_job_operation` trigger interceptor both go through it.- `p_quantity_complete` is **CUMULATIVE**, not this completion's delta. The function receives `p_quantity_complete - job.quantityReceivedToInventory` and stores the cumulative value back, because `get_inventory_quantities` computes on-production supply as production + scrap − received − shipped. `backflush_job_materials` takes the same cumulative number and is idempotent, so a re-completion at the received quantity receives nothing and consumes nothing.- It **refuses** a quantity ≤ 0 or below what was already received (stocked items), and a fractional quantity on a serial job. Those raises reach the `jobOperation` UPDATE when they happen under the trigger — `sync_finish_job_operation` therefore clamps with `GREATEST(computed, received)` before calling.-- The serial branch receives the delta one numbered unit at a time — shop-floor-finished (`Available`) first, then by `readableId` — skipping `Consumed`/`Rejected`/`Scrapped` and any unit with a `Job Receipt` ledger row for this job, so re-completion never double-receives. An item with **no serial sequence** never reaches `assign-serial-numbers`, so its job keeps one whole-quantity seed entity and the delta is received against that seed instead.+- The serial branch receives the delta one numbered unit at a time — shop-floor-finished (`Available`) first, then by `readableId` — skipping `Consumed`/`Rejected`/`Scrapped` and any unit with a `Job Receipt` ledger row for this job, so re-completion never double-receives. When the job's rows hold too few single units, an item with a serial sequence has the rest split off the seed (`split_serial_units_for_completion`) and the units picked again; the units taken are then numbered (`number_serial_units_for_receipt`). An item with **no serial sequence** is never split: its single units are received first, then the rest of the delta against its seed (one entity holding the units the shop floor has not touched). The seed gives the units the job has not received from it, plus the units no row holds up to the job quantity (it grows by those); a completion beyond that is refused.- **Make to Asset branch.** A job with `fixedAssetClassId` completes into one new `fixedAsset` per unit (status `Active`, or `Under Construction` when the class `isConstructionInProgress`; `acquisitionCost` = swept WIP ÷ units; one Posted `fixedAssetTransfer` per asset, `type 'Capitalization'`, `sourceType 'Job'`); a job with `fixedAssetId` sweeps its WIP onto that Construction in Progress asset as one `fixedAssetCipCost` row + one transfer. The units never enter stock: no `itemLedger`, `costLedger`, `pickMethod` or `itemCost` write, and the WIP discharge posts Dr class `assetAccountId` / Cr WIP as an `'Asset Transfer'` journal (both lines still `documentId = jobId`, so the per-job WIP balance nets to zero). Each serial unit goes `Consumed` with `attributes["Fixed Asset"]` and a `'Capitalize'` `trackedActivity`; every company writes the asset cost (the journal is Provisional before the accounting cutover). Guards raise before anything moves: `'A job linked to a sales order line cannot complete to a fixed asset'`; `'A job that completes to a fixed asset class needs a serialized item'` (any quantity — every asset a class job makes is a fleet unit followed by its serial); `'Make to Asset needs a serialized item or a quantity of one'` (a job attached to an asset under construction); a job attached to a non-CIP asset is also refused (`'… is not in a Construction in Progress class'`). The item rule is `makeToAssetItemError` (`production.models.ts`), applied by `x+/job+/new.tsx` on save (a field error on the item), by `updateJobDetails` (the details form), by `setJobItem` on a property-panel item change and by `resumeJob` when a paused job goes back to `Ready`, with the sales order line gate. Covered by `packages/database/supabase/tests/job-completion-to-asset.test.sql`. Full flow: `.claude/rules/fixed-asset-lifecycle.md`.+- **Serial number timing**: when a produced unit draws its serial number.+ - Setting: `companySettings.serialNumberTiming` (Settings → Production → Serial Numbers). An item's serial sequence overrides it with `itemSerialSequence.serialNumberTiming` (NULL follows the company; Settings → Serial Numbers). Readers resolve the item's value first: `getSerialNumberTiming` / `resolveSerialNumberTiming` (`@carbon/database/sequence`). Values: `serialNumberTimings` (`@carbon/database/serial-number-timing`, client-safe).+ - `jobCreation` (default): `assignJobSerialNumbers` → the `assign-serial-numbers` posting splits and numbers every unit when the job is created. The posting takes `at` and numbers only when the item's timing is `at`.+ - `jobRelease`: the same posting runs with `at: "jobRelease"` when `releaseCheckedJobs` flips the job to Ready (`assignJobSerialNumbersAtRelease`), on every release path. A failure does not stop the release: the job is listed in the result's `warnings` (`releaseJobs` passes it on).+ - `production`: the job keeps its unnumbered seed. A unit draws its number at its first touch through `assignSerialNumberIfMissing`: the MES start (`services/serial-number.server.ts`; only a single unit of the operation's own make method, since the unit id comes from the request), the `issue` posting's serial completion and operation scrap, and the completion that receives it.+ - A Batch lot is numbered at job creation whatever the timing; batch output never numbers.+ - A unit spawned later (a serial completion's next unit, a scrap's replacement) is numbered by `getSpawnSerialNumber`, which leaves it unnumbered under `production`. When the unit touched is an unsplit seed, the next unit or the replacement carries the seed's other units and stays unnumbered, so a job with no serial sequence still has a seed to receive against. The operation scrap refuses a unit already received to stock.- - Completion: `complete_job_to_inventory` (`20261027064600_serial-number-timing-completion.sql`) picks the units, splits what the rows lack off the seed and creates units no row holds yet, up to the job quantity less the units in rows (`split_serial_units_for_completion`), picks again, then numbers the unnumbered units it took (`number_serial_units_for_receipt`). Both helpers are `SECURITY INVOKER`. It does not read the timing: a job left unnumbered by a timing that changed back to `jobCreation` is numbered too. One query picks the units, so numbering and receipt take the same ones.++ - Completion: `complete_job_to_inventory` (`20261028153518_serial-number-timing-completion.sql`) picks the units, splits what the rows lack off the seed and creates units no row holds yet, up to the job quantity less the units in rows (`split_serial_units_for_completion`), picks again, then numbers the unnumbered units it took (`number_serial_units_for_receipt`). Both helpers are `SECURITY INVOKER`. It does not read the timing: a job left unnumbered by a timing that changed back to `jobCreation` is numbered too. One query picks the units, so numbering and receipt take the same ones.+ - Every serial is formatted by the SQL `get_next_serial_numbers`, which `getNextSerialNumbers` calls.+ - Complete dialog: it unlocks the quantity whenever the item has a serial sequence and units are unnumbered or have no row (`getSerialCompleteChoice`, mode `numberOnReceipt`) and says the serials are drawn at receipt. For an item with no sequence it stays locked to what the shop floor finished.- Dialog logic lives in `ui/Jobs/job-complete-logic.ts` (pure, no JSX/lingui, unit-tested by `apps/erp/test/job-complete-logic.test.ts`); the SQL is covered by `packages/database/supabase/tests/job-completion-received-quantity.test.sql`, hand-run like its siblings (nothing in CI runs `supabase/tests/`).### Loaded operation and unattributed machine timediff --cc apps/erp/app/modules/settings/settings.models.tsindex 61ca62df22,7586e4561e..0e1af75ebe--- a/apps/erp/app/modules/settings/settings.models.ts+++ b/apps/erp/app/modules/settings/settings.models.ts@@@ -522,28 -511,13 +527,15 @@@ export const itemSerialSequenceValidatosuffix: zfd.text(z.string().optional()),next: zfd.numeric(z.number().min(0)),step: zfd.numeric(z.number().min(1)),- size: zfd.numeric(z.number().min(1).max(20))+ size: zfd.numeric(z.number().min(1).max(20)),+ // Empty follows the company's serial number timing.+ serialNumberTiming: zfd.text(z.enum(serialNumberTimings).optional())});- export const themes = [- "zinc",- "neutral",- "red",- "orange",- "yellow",- "green",- "blue",- "violet"- ] as const;- export type Theme = (typeof themes)[number];+ export type Theme = ThemeName;- export const themeValidator = z.object({- next: zfd.text(z.string().optional()),- theme: z.enum(themes, {- error: "Theme is required"- })+ export const themeValidator = themeColorValidator.extend({+ next: zfd.text(z.string().optional())});export const webhookValidator = zdiff --cc apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 47f2173292,3e175d88c1..81df61ad18--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@@ -1521,7 -1523,7 +1523,7 @@@{"name":"settings_getApiKeys","classification":"WRITE","schema":"cd40ae40fad5","response":"14fbafc2ddf8","permission":"users:update","paginates":true},{"name":"settings_getCompanies","classification":"READ","schema":"31b84d65b2ac","response":"5783a32e0f4a","permission":"settings:view","paginates":false},{"name":"settings_getCompany","classification":"READ","schema":"31b84d65b2ac","response":"81a93f0029ec","permission":"settings:view","paginates":false},- {"name":"settings_getCompanySettings","classification":"READ","schema":"31b84d65b2ac","response":"60f2d2fca190","permission":"settings:view","paginates":false},- {"name":"settings_getCompanySettings","classification":"READ","schema":"31b84d65b2ac","response":"eda36f7f778c","permission":"settings:view","paginates":false},++ {"name":"settings_getCompanySettings","classification":"READ","schema":"31b84d65b2ac","response":"48e7c9c6359b","permission":"settings:view","paginates":false},{"name":"settings_getConfig","classification":"READ","schema":"31b84d65b2ac","response":"aa1021ff34cf","permission":"settings:view","paginates":false},{"name":"settings_getCurrentSequence","classification":"READ","schema":"31018ffa701d","response":"00404e686415","permission":"settings:view","paginates":false},{"name":"settings_getCustomField","classification":"READ","schema":"7f8214d1083f","response":"a533a796c094","permission":"settings:view","paginates":false},@@@ -1563,8 -1565,8 +1565,8 @@@{"name":"settings_updateItemsSettings","classification":"WRITE","schema":"b4f7e7addad9","response":"03604adb2677","permission":"settings:update","paginates":false},{"name":"settings_updatePlanningSettings","classification":"WRITE","schema":"0c543ed217a3","response":"0b9572e63423","permission":"settings:update","paginates":false},{"name":"settings_updatePostingSync","classification":"WRITE","schema":"a545e3ef8da3","response":"f95fa90d0071","permission":"settings:update","paginates":false},- {"name":"settings_updateProductionSettings","classification":"WRITE","schema":"aab377266e08","response":"be6b8045779d","permission":"settings:update","paginates":false},+ {"name":"settings_updateProductionSettings","classification":"WRITE","schema":"1ba094b13528","response":"c1002c089757","permission":"settings:update","paginates":false},- {"name":"settings_updatePurchasingSettings","classification":"WRITE","schema":"bac40d77d38a","response":"b3fda8ac0d5f","permission":"settings:update","paginates":false},+ {"name":"settings_updatePurchasingSettings","classification":"WRITE","schema":"21a4367cb133","response":"8e3c8fcc0dc8","permission":"settings:update","paginates":false},{"name":"settings_updateQualitySettings","classification":"WRITE","schema":"1bcfa3043aa1","response":"e87697c359ae","permission":"settings:update","paginates":false},{"name":"settings_updateResourcesSettings","classification":"WRITE","schema":"ba1b98fe944a","response":"ec0f37163627","permission":"settings:update","paginates":false},{"name":"settings_updateSalesSettings","classification":"WRITE","schema":"b200fc3300ac","response":"8becbd99be1d","permission":"settings:update","paginates":false},diff --cc packages/database/src/swagger-docs-schema.tsindex a652624f07,8a409c239c..4c869c78f7--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@@ -102582,9 -102627,9 +102639,12 @@@ export default{$ref: "#/parameters/rowFilter.companySettings.receiptQuantitiesStartAtZero"},+ {+ $ref: "#/parameters/rowFilter.companySettings.serialNumberTiming"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.requirePurchaseOrderApprovalSignature"+ },{$ref: "#/parameters/select"},@@@ -102866,9 -102911,9 +102926,12 @@@{$ref: "#/parameters/rowFilter.companySettings.receiptQuantitiesStartAtZero"},+ {+ $ref: "#/parameters/rowFilter.companySettings.serialNumberTiming"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.requirePurchaseOrderApprovalSignature"+ },{$ref: "#/parameters/preferReturn"}@@@ -103104,9 -103149,9 +103167,12 @@@{$ref: "#/parameters/rowFilter.companySettings.receiptQuantitiesStartAtZero"},+ {+ $ref: "#/parameters/rowFilter.companySettings.serialNumberTiming"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.requirePurchaseOrderApprovalSignature"+ },{$ref: "#/parameters/body.companySettings"},@@@ -167387,7 -167283,7 +167549,8 @@@"requireBackflushStorageUnit","preventNegativeBackflush","receiptQuantitiesStartAtZero",- "serialNumberTiming"++ "serialNumberTiming",+ "requirePurchaseOrderApprovalSignature"],properties: {id: {@@@ -167791,10 -167687,10 +167954,15 @@@format: "boolean",type: "boolean"},+ serialNumberTiming: {+ default: "jobCreation",+ format: "text",+ type: "string"++ },+ requirePurchaseOrderApprovalSignature: {+ default: false,+ format: "boolean",+ type: "boolean"}},type: "object"@@@ -223621,12 -223571,12 +223855,18 @@@in: "query",type: "string"},+ "rowFilter.companySettings.serialNumberTiming": {+ name: "serialNumberTiming",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.companySettings.requirePurchaseOrderApprovalSignature": {+ name: "requirePurchaseOrderApprovalSignature",+ required: false,+ in: "query",+ type: "string"+ },"body.part": {name: "part",description: "part",diff --cc packages/database/supabase/migrations/20261028153412_serial-number-timing.sqlindex fa31ea9c05,0000000000..fa31ea9c05mode 100644,000000..100644--- a/packages/database/supabase/migrations/20261028153412_serial-number-timing.sql+++ b/packages/database/supabase/migrations/20261028153412_serial-number-timing.sqldiff --cc packages/database/supabase/migrations/20261028153518_serial-number-timing-completion.sqlindex c07b2df7ae,0000000000..c07b2df7aemode 100644,000000..100644--- a/packages/database/supabase/migrations/20261028153518_serial-number-timing-completion.sql+++ b/packages/database/supabase/migrations/20261028153518_serial-number-timing-completion.sqldiff --cc packages/jobs/manifests/schema.jsonindex 9690c166c3,6f68303b09..e897d2d623--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@@ -1,11 -1,11 +1,11 @@@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20261027064600",- "schemaVersion": "20261028143517",++ "schemaVersion": "20261028153518","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-27T11:39:06.156Z",- "exportedAt": "2026-10-27T22:55:12.218Z",++ "exportedAt": "2026-10-28T08:01:48.922Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",@@@ -482,10 -483,10 +483,11 @@@"leaseIncrementalBorrowingRate","leaseShortTermExpedient","leaseReminderDays",- "serialNumberTiming","requireBackflushStorageUnit","preventNegativeBackflush",- "receiptQuantitiesStartAtZero"+ "receiptQuantitiesStartAtZero",++ "serialNumberTiming",+ "requirePurchaseOrderApprovalSignature"]},{