Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

38.2 KB
Raw Blame

paths: - "apps/erp/app/modules/quality/ui/Inspections/" - "apps/erp/app/modules/quality/quality.{server,service,models}.ts" - "apps/erp/app/routes/x+/inspection+/" - "apps/erp/app/routes/x+/inspection-document+/" - "apps/erp/app/routes/x+/quality+/inspection-plans.tsx" - "apps/erp/app/modules/quality/ui/InspectionDocument/" - "apps/mes/app/components/Inspection/**" - "apps/mes/app/routes/x+/inspection.tsx" - "packages/database/src/quality.ts" - "packages/database/supabase/migrations/inspection.sql" - "apps/erp/app/modules/inventory/inventory.service.ts"

Inspection System

Generic quality-inspection execution keyed by sourceDocument / sourceDocumentId / sourceDocumentLineId / sourceDocumentReadableId (enum inspectionSourceDocument: 'Receipt' and 'Job Operation', both live; no FKs on the generic ids, unique per (sourceDocument, sourceDocumentLineId) — a partial unique index WHERE "sourceDocumentLineId" IS NOT NULL). Renamed from the receipt-only "Inbound Inspections" in 20260722132135_inspections-refactor.sql (tables inspection/inspectionSample/inspectionSamplingPlan/ inspectionMeasurement/inspectionHistory/nonConformanceInspection; readable id column inspectionId, sequence key inspection — existing companies keep their II prefix, new companies seed INS).

Receipt flow: when a receipt is posted, a lot-level inspection is created for each received line whose item has a Receipt-usage inspection plan — i.e. an itemInspectionDocumentAssignment row for usage = 'Receipt' (the item-level requiresInspection flag was removed 2026-07-26; the assigned document IS the gate). A single full-screen execution UI at /x/inspection/{id} (InspectionView + InspectionMeasurementGrid) covers every lot (spec .ai/specs/implemented/2026-07-21-inbound-inspection-execution.md):

  • Drawing pane — shown when the lot has an assigned PDF (pdfUrl != null); hidden otherwise (the grid takes the full body).
  • Feature rows — when the assigned document resolved features, the grid is a features × samples measurement grid: readings auto-valuate against live tolerances, sample status is derived (strict, no override), per-feature AQL sampling (feature rule → document default → All; the per-item itemSamplingPlan tier was removed 2026-07-26, migration 20260726231401_document-sampling-default.sql).
  • No document — the grid collapses to a single synthetic "Overall result" pass/fail row (client-only, featureId = "__overall__"). Its P/F cells set the sample's status directly via the sample route (upsertInspectionSample, status Passed/Failed) rather than recording a measurement; lot-level AQL gating.
  • Columns — serial lots add one column per scanned tracked entity (ScanInspectionSample, identify-only → a Pending sample with a trackedEntityId; the column header shows the entity readableId); non-serial lots pre-create anonymous numbered columns up to the resolved sample size, and an anonymous inspectionSample is materialized lazily on the first cell save (measurement → upsertInspectionMeasurement; overall-result → the sample route with sampleId for idempotent re-toggle).
  • Scanning (serial) — a header "Add Sample" button (not an in-grid column) opens the scanner; it is variant="primary" until samples.length >= inspection.sampleSize, then secondary. A fresh serial lot (0 samples) auto-opens the scanner once on mount.

(The pre-unification "fallback" samples table and the scanner's mode="record" pass/fail path were removed 2026-07-25; scanning is always identify.)

Disposition is always a human decision. The ERP's Reject Lot is available on any open receipt lot: with no statistical failure, RejectLotModal requires a reason (a suspected counterfeit, the wrong part, transit damage), which rejectInspection passes to the engine as reason. Reject/Partial can auto-create an NCR whose description includes the failed features (documentation only — never required, and the NCR does not drive the physical outcome). The ERP receipt UI exposes Accept and Reject (its $id.partial.tsx route exists but has no header button). The MES job-operation UI exposes Accept, Partial, and Reject, and its dispositions carry their physical production outcome (see "Disposition → production outcome" below). All three terminal statuses (Passed/Failed/Partial) are hard-terminal in the engine since 2026-07-27: samples and measurements are guarded closed on all of them.

Data model (newest migration wins: 20260722132135_inspections-refactor.sql)

Lineage: Phase-1 20260419094132_inbound-inspections.sql (dropped) → Phase-2 lot rebuild 20260419163058_inbound-inspection-sampling.sql → execution layer 20260722040401_inbound-inspection-execution.sql → the rename/source refactor 20260722132135. Old constraint/index NAMES still carry inboundInspection strings (cosmetic).

  • item.requiresInspection — dropped 2026-07-26 (along with the vestigial purchaseOrderLine.requiresInspection / salesOrderLine.requiresInspection columns). Receipt inspection is now gated by the item's Receipt-usage itemInspectionDocumentAssignment (see Receipt flow above), not a boolean flag.
  • companySettings.samplingStandard enum samplingStandard (ANSI_Z1_4 | ISO_2859_1, default ANSI_Z1_4) and companySettings.enforceInspectionFourEyes BOOLEAN.
  • inspectionDocument.sampling* — the document-level default sampling rule (six nullable columns mirroring the per-feature set; added 20260726231401_document-sampling-default.sql, which also dropped itemSamplingPlan — plans that existed were backfilled onto the item's documents via partId). NULL default = All (100%).
  • inspection (lot level, PK = id) — inspectionId (human id, II seq, unique per company), receiptLineId (unique — one lot per receipt line), receiptId, itemId, itemReadableId, supplierId, lotSize, snapshot of the resolved plan (samplingStandard, samplingPlanType, sampleSize, acceptanceNumber, rejectionNumber, aql, inspectionLevel, severity, codeLetter), status (inspectionStatusType: Pending/In Progress/Passed/Failed/Partial), dispositionedBy/dispositionedAt. No itemTrackingType column — joined from item.
  • inspectionSample — one row per recorded result: inspectionId, trackedEntityId (nullable since 20260612151947), status (inspectionSampleStatusType: Pending/Passed/Failed), inspectedBy/inspectedAt. A partial unique index inspectionSample_trackedEntityId_key WHERE trackedEntityId IS NOT NULL keeps a serial entity sampleable once while allowing many anonymous samples.
  • inspectionHistory — one row per disposition (skeleton for future plan auto-switching).
  • nonConformanceInspection (20260421091238) — links an auto-created NCR back to the inspection (unique (nonConformanceId, inspectionId)).
  • productionQuantity.inspectionId / .inspectionSampleId (20260727031247_inspection-production-links.sql) — nullable FKs (ON DELETE SET NULL) recording which inspection/sample drove a posting. The partial UNIQUE index on inspectionSampleId is the double-count guard: a sample's verdict can produce at most one posting. The same migration forks sync_finish_job_operation (the zero-completions fallback to the full job quantity now applies ONLY when the job recorded no scrap/rework — a fully scrapped job closes with quantityComplete = 0 and receives nothing) and complete_job_to_inventory (the serial branch excludes Rejected entities). 20260914095239_complete-job-received-quantity.sql then rewrote that branch: it no longer loops every entity and no longer releases them all to Available — it receives only the delta between the cumulative completed quantity and what the job already received, oldest-numbered first, skipping Consumed, Rejected and Scrapped, and flips only the units it received.

Execution-layer tables (20260722040401_inbound-inspection-execution.sql):

  • inspection.inspectionDocumentId — live reference to the assigned inspectionDocument (ON DELETE SET NULL); no feature snapshot.
  • itemInspectionDocumentAssignment — PK (itemId, usage); usage enum inspectionDocumentUsage (v1: only 'Receipt'; FAI/Production are additive enum values later). Edited on the item Quality tab (ItemQualityView).
  • inspectionFeature gained six nullable per-feature sampling columns (samplingPlanType/SampleSize/Percentage/Aql/InspectionLevel/Severity); NULL = inherit the document's default rule. Persisted through the save_inspection_document_atomic fork in the same migration (newest def).
  • inspectionSamplingPlan — per-lot per-feature resolved plan (sampleSize, acceptanceNumber, rejectionNumber, codeLetter), unique (inspectionId, inspectionFeatureId). Created at receipt; lazily reconciled by the $id loader for features added to the live document later.
  • inspectionMeasurement — one reading per (sampleId, featureId) (unique): value NUMERIC (NULL for attribute features), status (inspectionSampleStatusType — the valuation at entry; tolerance edits never rewrite recorded statuses), notes, inspectedBy/At.

RLS on all tables: standard SELECT/INSERT/UPDATE/DELETE gated by quality_view/create/update/delete.

Plans made from a model's PMI (20261027122437_pmi-inspection-plans.sql)

Spec: .ai/specs/2026-10-27-pmi-inspection-plans.md. A STEP AP242 model's PMI (modelUpload.pmiPath, see packages/viewer/AGENTS.md) becomes an inspection plan automatically. The plan holds the model (inspectionDocument.modelUploadId, ON DELETE SET NULL) and no PDF; each feature names its PMI item (inspectionFeature.pmiItemId, d1/t3) and has pageNumber = 1.

  • Made by pmi-inspection-plan (packages/jobs/.../tasks/pmi-inspection-plan.ts), event carbon/pmi-inspection-plan. Senders: model-optimize after a run that wrote pmi.json (every item on the model), and the queue_pmi_inspection_plans statement handler on item when an INSERT/UPDATE points an item at a model that already has pmiPath (that item only; skipped under app.sync_in_progress).
  • Mapping is pmiInspectionCharacteristics (@carbon/viewer/pmi, tested): a ± dimension → nominal/tol± (re-centred on its band when both deviations share a sign, since the verdict reads Tol± as magnitudes); a limit dimension → midpoint ± half range; a dimension with no numeric limit (fit class, min/max) or a tolerance with no zone → nominal null (Pass/Fail); a geometric tolerance → nominal 0, Tol+ = zone, Tol− 0. Datums, notes, labels and valueless dimensions are left out. Units are the file's own (mm/in), deg for angles.
  • Once per item and model. createPmiInspectionPlan (@carbon/database/quality) inserts with ON CONFLICT DO NOTHING on the partial unique index inspectionDocument_part_model_key. A re-optimise never rewrites an edited plan; a new model on the item makes a new plan and leaves the old one (and its assignments) alone. No plan is made when no characteristic results.
  • Item delete (deleteItemsWithPriceBreaks) first calls deleteUnusedPmiInspectionPlans (@carbon/database/quality), which deletes the items' PMI plans no inspection used, so an automatic plan never trips partId's RESTRICT; a used one still refuses the delete. Pinned, with createPmiInspectionPlan, by packages/database/src/pmi-inspection-plan.test.ts; the trigger by supabase/tests/pmi-inspection-plans.test.sql; the mapping against valuateMeasurement by packages/jobs/.../pmi-inspection-plan.test.ts.
  • Screens. InspectionView (ERP and MES) shows ModelUploadPreview (@carbon/viewer/model-upload-preview, shared — not an app copy) in the drawing pane's place when the loader returns model. Its pmiLinks (feature id → pmiItemId) tie the active feature to its PMI item both ways; a pick on a datum or note clears the active feature. The editor shows the model in its top pane, does not render the PDF tools or the Balloon action, and gives each PMI row a Show action.
  • Deleting the model sets modelUploadId null (ON DELETE SET NULL): the plan keeps its features and shows no drawing pane, and the item-delete cleanup no longer recognises it as a PMI plan, so it blocks a part delete like a hand-made plan. deleteUnusedPmiInspectionPlans runs as the system inside the item delete, so parts_delete alone can remove an unused PMI plan.
  • Recreating the inspectionDocuments view also added the six sampling* columns added after it was first created (d.* is fixed at creation), so getInspectionDocuments (the quality_getInspectionDocuments tool) reads the document's sampling default.
  • The Inspection Plans list (/x/quality/inspection-plans) is one row per part, read from the inspectionPlanParts view (getInspectionPlanParts, 20261028161842_inspection-plan-parts-view.sql, recreated by 20261028222414_inspection-plan-parts-group-tags.sql): the part, its plan count, its item group (itemCost.itemPostingGroupId) and tags (part.tags), and a plans jsonb rollup the expanded row lists, as the Change Notices list lists a notice's affected items. Clicking a row expands it; the part is not a link. Item Group and Tags are filterable columns, hidden by default. A search expands every row and marks the matches (expandRowsFor on the Table, Highlight / searchMatches).
  • PMI ids are per-kind counters in file order, stable for one file. An extractor change that reorders items would point an old plan's features at other items.

Gauges (20260929203517_inspection-gauges.sql)

  • Plan side — inspectionFeature.gaugeTypeId (nullable FK → gaugeType, ON DELETE SET NULL): the gauge TYPE a feature must be measured with. Edited in the inspection plan editor's Gauge Type column (clearable = any gauge), persisted by the save_inspection_document_atomic fork in that migration, which refuses another company's gauge type (the FK alone would accept it).
  • Execution side — the gauge actually used is recorded per lot × feature on inspectionSamplingPlan.gaugeId (+ gaugeRecordedAt), not per measurement — one gauge per characteristic per lot, as SAP QM / FAI forms do. Written by recordInspectionGauge (@carbon/database/quality): closed-lot guard, company-scoped gauge, refuses Inactive gauges and a gauge whose type differs from the feature's gaugeTypeId. A gauge recorded on a closed lot (Passed/Failed/Partial) cannot be deleted — the trigger prevent_deleting_gauge_recorded_on_closed_inspection (20261001022340_inspection-gauge-history.sql) raises 23503, which also refuses a gauge-type delete reaching it through its cascade; set the gauge Inactive instead. Open lots keep the FK's SET NULL, and a company wipe (app.sync_in_progress, or children deleted first) is never blocked. Out-of-calibration is shown (red icon in the cell, calibration status badge in the list) but does NOT block. Routes: ERP x+/inspection+/$id.gauge.tsx, MES x+/inspection-lot.$id.gauge.tsx (path.to.inspectionGauge), quiet POSTs like the measurement cells.
  • Picker — InspectionGaugePicker (ERP ui/Inspections/, touch-sized copy in MES components/Inspection/): a button filling the whole Gauge cell opens a search + list of Active gauges (the gauges view, filtered to the feature's type). The loader also returns any gauge already recorded on the lot whatever its status, so a gauge retired after use still shows by its readable id ("(Inactive)") — that record is what a calibration recall reads. "Recently used" comes first — getRecentInspectionGauges returns the gauges most recently recorded at the lot's station: a Job Operation lot's station is its operation's workCenterId; all receipts are one station. No Gauge column on the no-document "Overall result" row.

Receipt → inspection flow (postReceipt, inventory.service.ts)

apps/erp/app/modules/inventory/inventory.service.ts:

  1. Loads items (id, itemTrackingType, replenishmentSystem), company samplingStandard, Receipt-usage itemInspectionDocumentAssignment rows (assignmentByItemId), and the assigned documents' inspectionFeature rows + default sampling columns.
  2. Per receipt line whose item has a Receipt-usage assignment (assignmentByItemId.get(itemId)) and receivedQuantity > 0: the assigned document is the plan gate — no assignment, no lot. Resolves the lot plan via resolveSamplingPlan(plan, lotSize, standard) from packages/database/src/sampling.ts (ANSI Z1.4 / ISO 2859-1 tables; returns { sampleSize, acceptance, rejection, codeLetter }). Document with no default rule → type: "All", level II, Normal. Always resolves each feature via resolveFeatureSamplingPlan(feature, documentDefault, lotSize, standard) (feature rule → document default → All), always stamps inspectionDocumentId = assignedDocumentId on the lot (even a drawing-only document with no features), sets the lot-level sampleSize to the max across features (or the snapshot size when featureless), and (after the insert .returnings the lot ids) batch-inserts the inspectionSamplingPlan rows.
  3. Tracked entities for items with a Receipt-usage assignment are set to "On Hold" at receipt (not Available); everything else flips to Available. They are released individually by sample inspection / derived measurement status or en masse by lot disposition.

Job Operation → inspection flow (MES, added 2026-07-26)

Job operations with operationType = 'Inspection' execute in the MES at /x/inspection/{jobOperationId} (apps/mes/app/routes/x+/inspection.$operationId.tsx, guard-redirect pattern per ADR-0005; operation.$operationId.tsx redirects Inspection ops here). The lot is created lazily on first open by getOrCreateJobOperationInspection (@carbon/database/quality): mirrors post-receipt plan resolution (document default → All; per-feature plans from the operation's inspectionDocumentId FK — stamped even when the document has no features yet, so drawing-only docs render and later features reconcile in), sourceDocument='Job Operation', sourceDocumentId=job.id, sourceDocumentLineId=jobOperationId, sourceDocumentReadableId=job.jobId, itemId = the make method's item (subassembly ops inspect the subassembly), lotSize = operationQuantity, human id from the inspection sequence. Concurrent first-opens are settled by the partial unique index (23505 → reselect).

  • MES UI: apps/mes/app/components/Inspection/ — InspectionView (AssemblyView shell: header segments for Add Sample / Complete passed (n) / Reject / Partial / Accept, TimerControl → /x/event — the labor clock auto-starts on open whenever no clock is running, always on for inspections, independent of the company autoStartOperationTimer setting; action sheet for Scrap/Rework/Finish/Quality Issue via the shared JobOperation modals), InspectionMeasurementMatrix (plain touch-first table, SAME per-cell quiet POST contract as the ERP grid), InspectionDrawingPane (verbatim copy of the ERP pane; MES gained konva/react-konva/pdfjs-dist deps + canvas SSR stub + worker bootstrap), ScanInspectionSample (adapted: @carbon/form fields, samples from make-method WIP entities), DispositionModal (the Reject/Partial failed-set allocator; replaced RejectLotModal 2026-07-27).
  • MES routes: view param is the jobOperationId; lot actions use the lot id under a distinct prefix — x+/inspection-lot.$id.{measurement,sample,disposition,complete-passed}.tsx (path.to.inspectionMeasurement|Sample|Disposition|CompletePassed; the old accept/reject routes were retired 2026-07-27), each requirePermissions({ update: "quality" }) → MES validators (~/services/models) → the shared engine with getDatabaseClient() (apps/mes/app/services/database.server.ts, same singleton as ERP's).
  • WIP entities are never flipped by sampling or by the quality engine. The entity flips in upsertInspectionSample / upsertInspectionMeasurement (and their applySampleEntityStatus activity writes) are guarded sourceDocument === "Receipt", matching dispositionInspection's existing guard — job WIP entities keep their job-owned status (Reserved etc.). The ONE exception lives in the production-outcome layer, not the engine: the MES disposition route flips the scrap-allocated serial subset to Rejected (see below).
  • MES reads: apps/mes/app/services/quality.service.ts (copies of the ERP reads + a simplified getInspectionDocumentWithBalloons that builds the /file/preview/private/ pdfUrl from inspectionDocument.storagePath).

Disposition → production outcome (MES, added 2026-07-27)

The MES verdict carries its physical posting — one decision surface instead of parallel Accept/Reject + menu Log-Completed/Scrap/Rework vocabularies. The quality engine stays pure (verdicts only); orchestration lives in x+/inspection-lot.$id.disposition.tsx on top of shared helpers in apps/mes/app/services/quality.server.ts (getInspectionOutcomeState — buckets recomputed fresh from the DB per POST; getSerialCompletionCandidates / postSerialCompletions / postBulkCompletion; createInspectionRejectionIssue — the NCR block lifted from the retired reject route; it passes inspectionId to createQualityIssue so the inspection link is written with the disposition row under the issue lock).

Decision Physical postings
Accept Completes the open remainder (serial: per-entity issue jobOperationSerialComplete, Pending-sampled and un-sampled units included, failed-sample units EXCLUDED; non-serial: one bulk posting of the op-column remaining via jobOperationBatchComplete or insertProductionQuantity+backflush)
Reject The operator allocates the open remainder in DispositionModal: serial per-unit Scrap/Rework toggles, non-serial scrap+rework quantity fields; the rest is record-only. Scrap subset → one insertScrapQuantity (+reason, + backflush) and the serial subset flips → Rejected. Rework subset → ONE trigger-rework invoke (targets from rework-targets; the routing clone includes the inspection op → fresh lot → automatic re-inspection) + recalculate jobRequirements; reworked entities are NOT flipped.
Partial Terminal mixed close, gated inspected >= lotSize && passes > 0 && fails > 0. Passed units complete; the failed set is allocated exactly like Reject (allocation restricted to failed units).
Complete passed (n) header chip Progressive completion of passed-but-unposted units any time the lot is open ($id.complete-passed.tsx) — explicit button, not auto-on-pass, so verdict typos need no compensating transaction.

Mechanics (in order, per POST):

  1. Buckets recomputed server-side and validated (allocation ids must be open make-method entities; quantities clamped to the op-column remaining = target − complete − scrapped − reworked, so escape-hatch menu postings are never double-counted; serial divergence blocks with an error).
  2. dispositionInspection({ requireOpen: true }) closes the lot FIRST — the one-shot status UPDATE is the serialization point; a concurrent second POST dies before any posting can re-run (a re-POST can never re-clone the rework path).
  3. Postings, each carrying provenance links (productionQuantity.inspectionId
    • inspectionSampleId; serial completes processed in ascending sample order; non-serial bulk rows link the lowest unlinked passed sample as a serializing representative). Failures after step 2 leave a closed lot with partial postings — surfaced loudly in the flash; the links make the arithmetic self-heal for manual ERP fixes.
  4. Optional NCR (createNcr), willBeFinished mirror from complete.tsx for targetQuantity = 0 operations.

The action sheet keeps Scrap/Rework (escape hatches for non-quality losses), Finish, and Quality Issue; Log Completed was removed (verdict-driven completion replaced it).

Tracking types

All four itemTrackingType values support inbound inspection (the only UI gate is purchased items — see Code map). Serial parts produce N tracked entities and the inspector scans/selects a discrete entity per sample; non-serial (Batch/Inventory/Non-Inventory) record pass/fail with trackedEntityId = NULL (same UI, no scan). Inventory items that aren't tracked have no per-row status to flip, so a Reject posts a compensating write-off instead (see disposition).

Reject / disposition GL posting. A non-tracked Inventory reject and every NCR disposition route their inventory value through the post-nonconformance posting (postNonconformance, quality.service.ts: itemLedger + costLedger relief + a journal offset to accountDefault.scrapAccount for every company, Provisional before the accounting cutover; idempotent per (documentType, documentId)). The reject route ($id.reject.tsx) invokes it with the lot write-off (documentType 'Inbound Inspection', documentId = inspection.id) after dispositionInspection commits — dispositionInspection itself no longer writes itemLedger, it returns a writeOff descriptor. Disposition close (closeIssue) invokes it with documentType 'Non-Conformance', documentId = ncrId. Non-tracked disposition rows are dispositionable in AssociatedItemsList.tsx (quantity + Select, split by quantity, no move); Use-As-Is/Rework on an inspection-rejected Inventory lot restores value, non-inspection Scrap writes it off, Non-Inventory never posts. See issue-module.md → Disposition GL/cost posting and .ai/plans/2026-07-25-inspection-disposition-gl-posting.md.

Code map (ERP)

  • No items toggle: the requiresInspection checkbox was removed from the item Properties sidebars (Parts/Materials/Tools/Consumables) 2026-07-26. Inbound inspection is configured entirely on the item Quality tab by assigning a Receipt-usage inspection document; there is no per-item boolean.
  • Item Quality tab: .../ui/Item/ItemQualityView.tsx (documents card + usage-slot assignments card; sampling lives on the document, not the item), mounted on routes/x+/{part,material,tool,consumable,service}+/$itemId.quality.tsx (actions branch on intent=assignment). The tab is always shown (no requiresInspection gate in the item navigation hooks), for every item type, gated only by the quality view permission.
  • Execution view: .../ui/Inspections/InspectionView.tsx — full-screen, data-prop reusable (AssemblyView pattern, for later MES reuse). Renders InspectionDrawingPane.tsx (lazy react-pdf + Konva balloons, click ↔ row sync) above InspectionMeasurementGrid.tsx when pdfUrl != null, else the grid alone. InspectionMeasurementGrid.tsx (shared Table inline editing, per-cell quiet POSTs, capture-phase Enter/Tab nav, attribute P/F toggle cells; every cell is recordable — a feature's n is the required MINIMUM, extra readings up to the lot size are allowed) shows feature rows when liveFeatures.length > 0, otherwise the single OVERALL_ROW_ID pass/fail row whose cells write the sample status via the sample route. RejectLotModal.tsx (extracted) previews failed features.
  • Sample modal: .../ui/Inspections/ScanInspectionSample.tsx — identify-only; opened by the header "Add Sample" button (InspectionView, serial lots; primary until the sample size is covered, auto-opened once on a fresh 0-sample lot). isSerial shows Scan/Select tabs (entity required) and posts a Pending sample column with a trackedEntityId (verdict set later in the grid). Non-serial columns are pre-created, so the modal is serial-only in practice.
  • Routes: list stays x+/quality+/inspections.tsx; the old inspections.$id.tsx is a redirect stub to the full-screen tree x+/inspection+/ (_layout.tsx module quality; $id.tsx loader reconciles features + loads document/balloons via service role; actions: $id.measurement.tsx (per-cell), $id.sample.tsx, $id.document.tsx (swap, only unmeasured non-terminal lots), $id.{accept,reject,partial}.tsx). Path helpers: path.to.inspection*.
  • Server — the transactional engine lives in @carbon/database/quality (packages/database/src/quality.ts; moved 2026-07-26 so ERP and MES run one engine). Every function takes a Kysely<KyselyDatabase> first param; ERP's quality.service.ts wraps those engine calls with the caller's db (a route's getDatabaseClient(), a service function's ctx.asSystem.pg), and also holds the plan editor's server-only helpers (legacy save-payload translation translateLegacyInspectionSavePayload, the balloon-region vision call runInspectionBalloonRegionVisionAnalysis). packages/database/src/sampling.ts is the pure resolver; the engine and post-receipt both consume it, so they share ONE resolver copy (ERP's samplingStandards.ts client copy remains for UI previews).
    • Voided receipt (2026-10-16): a Receipt lot whose receipt is Voided is closed too. assertReceiptNotVoided (reads the receipt FOR SHARE, so it waits for a void in progress) refuses samples, measurements, gauges, document swaps and dispositions with "The receipt of this inspection was voided", and the $id loader passes receiptVoided so InspectionView treats the lot as closed and shows a "Receipt voided" badge. The lot keeps its Pending status: there is no cancelled inspection status.
    • Closed guards + linked-sample locks (2026-07-27): all three terminal statuses (Passed/Failed/Partial) block upsertInspectionSample (guard is NEW — it had none) and upsertInspectionMeasurement ("Inspection is closed") and changeInspectionDocument. Updating an EXISTING sample (or a measurement on one) additionally fails when a productionQuantity row links its inspectionSampleId — the unit was already completed from that verdict; deleting the row in the ERP unlocks it (assertSampleNotLinked).
    • upsertInspectionSample — upsert precedence: by trackedEntityId (serial), else by sampleId (the "Overall result" row re-toggling an anonymous column in place), else insert a fresh anonymous sample. Entity flip + trackedActivity via the shared applySampleEntityStatus helper; skipped for Pending (identify-only) samples. The $id.sample.tsx route returns the sampleId and, when quiet=true (grid overall-result POST), suppresses the success flash.
    • valuateMeasurement (exported, unit-tested) — numeric in [nominal − |tol−|, nominal + |tol+|]; unparseable nominal / non-Measurement types valuate as attributes.
    • upsertInspectionMeasurement — creates anonymous samples on demand, upserts the reading, derives the sample status count-based (not positional): any failed reading ⇒ Failed; every plan feature Passed on the sample ⇒ Passed; else Pending. A feature's n is the required minimum across ANY samples (per-feature disposition gating enforces the counts); extra readings up to the lot size are allowed. Applies entity transitions (revert → On Hold, no activity), recomputes non-terminal lot status.
    • reconcileInspectionSamplingPlans — lazy per-lot plan rows for features added post-receipt.
    • changeInspectionDocument — swap/clear guarded to unmeasured non-terminal lots; wipes plan rows for re-resolution.
    • dispositionInspection — per-feature gating when the lot has features (Accept: every feature recorded >= n && failed <= Ac; Reject: the pure isRejectableWithoutReason (some feature failed >= Re or a failed sample; with no features, failed samples > Ac — the rule both apps' Reject buttons apply, pinned by packages/database/src/quality.test.ts) or a reason, so a lot can be rejected with nothing failed, e.g. a suspected counterfeit, and the reason is stored as the lot's notes); Accept releases every non-failed lot entity to Available (un-sampled AND partially-inspected Pending samples included); Reject flips all lot entities to Rejected (and for a non-tracked Inventory item posts an itemLedger Inbound Inspection negative adjustment); Partial leaves entities; always writes inspectionHistory. Optional requireOpen (one-shot mode, MES disposition route only): the status UPDATE gains WHERE status NOT IN (Passed,Failed,Partial) and the call throws "Inspection is already dispositioned" on zero rows — concurrency safe because a second transaction blocks on the row lock, re-evaluates the predicate against the committed terminal status, and matches nothing. ERP receipt lots do NOT pass it, preserving re-disposition (write-off retry) semantics.
    • NCR auto-creation lives in the rejectInspection operation (quality.server.ts, called by x+/inspection+/$id.reject.tsx), optional via createNcr, linking through nonConformanceInspection; the description includes the reason and a "Failed features" block built from the lot's measurements, and the lot's supplierId is written as the issue's nonConformanceSupplier (insertIssue's supplierId). The $id loader reads the lot's issues (getInspectionIssues) and the header links them (one: a button with the issue's readable id; several: an Issues menu). The header's Create Issue button passes the failed entities and the lot's supplierId, never the inspection: an inspection link tells closeIssue the lot was written off at reject, which is only true for a rejected lot.
  • Service quality.service.ts: getInspections (list), getInspection, getInspectionTrackedEntities, getInspectionSamplingPlans (embeds inspectionFeature(...) by table name), getInspectionMeasurements, getItemInspectionDocumentAssignments / upsertItemInspectionDocumentAssignment (empty documentId deletes the slot).
  • Validators quality.models.ts: inspectionSampleValidator (trackedEntityId optional; status includes Pending), inspectionDispositionValidator, inspectionMeasurementValidator (value xor passed), itemInspectionDocumentAssignmentValidator, inspectionDocumentUsages const.
  • Sampling engines (kept in sync manually): resolveSamplingPlan + resolveFeatureSamplingPlan in both apps/erp/app/modules/quality/samplingStandards.ts and packages/database/src/sampling.ts.

Gotchas

  • Lot-based, not entity-based. The Phase-1 per-entity inspection was dropped; read the 20260419163058 migration (and newer) for the real shape. receiptLineId is unique — one inspection lot per received line.
  • Inspection-required tracked entities post On Hold, not Available. They are not on-hand until released by sampling/disposition.
  • trackedEntityId is nullable on samples; serial uniqueness is enforced by a partial index.
  • Inspection documents ("Inspection Plans") are authored in the quality module (list at /x/quality/inspection-plans, editor at /x/inspection-document/{id}; inspectionDocument/ inspectionFeature/balloon + save_inspection_document_atomic, newest def 20261001022635) and are now consumed by this flow via the item's Receipt-usage assignment. The lot references the document live — measurement rows store the valuation at entry, so later tolerance edits never rewrite recorded results.
  • The plan editor autosaves — there is no Save button. A debounced effect posts the whole diff to x+/inspection-document+/$id.save.tsx while the editor is quiet (a drag saves when it ends), one save at a time; the toolbar shows Saving… / Saved / Could not save, and leaving the page first flushes the save (useBlocker). The editor mints the ids of the characteristics and balloons it creates (ift_… / bbn_…, newFeatureId / newBalloonId in ui/InspectionDocument/autosave.ts), and the RPC inserts with them (20261001022635_inspection-plan-client-ids.sql; a taken id fails the insert, it never overwrites). So a row keeps one id from the moment it is drawn: an id the server has not created yet is in the editor's unsaved set and goes out as a create, every edit marks its row dirty, and mergeSaveResponse (tested) only swaps in the server copy of rows untouched since the save went out. Deletes are always queued once a row has left the browser (deleting an id the server never created is a no-op). Other callers may still send tempId / tempBalloonAnchorId and read the featureIdMap / balloonAnchorIdMap back. A PDF upload goes through the same save. The route skips revalidation after a save (the response carries the rows).
  • Features saved together share one createdAt (the RPC is one transaction, NOW() is fixed), so ORDER BY "createdAt" alone returns them in heap order, and an UPDATE moves a row to the end. Anything listing features must break the tie — the editor sorts by createdAt, then label (natural), then id, on load only.
  • Sample status is derived on document-driven lots — do not add manual sample pass/fail UI there; deviations resolve at disposition via MRB/NCR (spec decision).
  • Per-cell measurement saves are quiet (plain fetch, no revalidation) — the grid and the view mirror statuses locally from the action's returned {sampleId, measurementStatus, sampleStatus}.
  • MES dispositions are one-shot; ERP receipt dispositions are not. Only the MES disposition route passes requireOpen — don't add it to ERP receipt routes (their Reject retry re-invokes the idempotent post-nonconformance).
  • A crash between the one-shot close and the postings leaves a closed lot with missing postings (by design — close-first is what makes rework un-repeatable). Recovery is manual: post the missing rows from the ERP (productionQuantity links make completed-vs-not arithmetic self-healing); deleting a linked Production row makes that sample's unit completable again.
  • ERP inspection views of Job Operation lots are verdict-only. The execution surface (postings, allocation, complete-passed) is the MES; the ERP shows the lot, samples, and measurements but exposes no outcome orchestration for job-op lots.