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.
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
itemSamplingPlantier was removed 2026-07-26, migration20260726231401_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 atrackedEntityId; the column header shows the entityreadableId); non-serial lots pre-create anonymous numbered columns up to the resolved sample size, and an anonymousinspectionSampleis materialized lazily on the first cell save (measurement →upsertInspectionMeasurement; overall-result → the sample route withsampleIdfor idempotent re-toggle). - Scanning (serial) — a header "Add Sample" button (not an in-grid column)
opens the scanner; it is
variant="primary"untilsamples.length >= inspection.sampleSize, thensecondary. 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).
— dropped 2026-07-26 (along with the vestigialitem.requiresInspectionpurchaseOrderLine.requiresInspection/salesOrderLine.requiresInspectioncolumns). Receipt inspection is now gated by the item's Receipt-usageitemInspectionDocumentAssignment(see Receipt flow above), not a boolean flag.companySettings.samplingStandardenumsamplingStandard(ANSI_Z1_4|ISO_2859_1, defaultANSI_Z1_4) andcompanySettings.enforceInspectionFourEyesBOOLEAN.inspectionDocument.sampling*— the document-level default sampling rule (six nullable columns mirroring the per-feature set; added20260726231401_document-sampling-default.sql, which also droppeditemSamplingPlan— plans that existed were backfilled onto the item's documents viapartId). NULL default = All (100%).inspection(lot level, PK =id) —inspectionId(human id,IIseq, 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. NoitemTrackingTypecolumn — joined fromitem.inspectionSample— one row per recorded result:inspectionId,trackedEntityId(nullable since20260612151947),status(inspectionSampleStatusType: Pending/Passed/Failed),inspectedBy/inspectedAt. A partial unique indexinspectionSample_trackedEntityId_key WHERE trackedEntityId IS NOT NULLkeeps 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 oninspectionSampleIdis the double-count guard: a sample's verdict can produce at most one posting. The same migration forkssync_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 withquantityComplete = 0and receives nothing) andcomplete_job_to_inventory(the serial branch excludesRejectedentities).20260914095239_complete-job-received-quantity.sqlthen rewrote that branch: it no longer loops every entity and no longer releases them all toAvailable— it receives only the delta between the cumulative completed quantity and what the job already received, oldest-numbered first, skippingConsumed,RejectedandScrapped, and flips only the units it received.
Execution-layer tables (20260722040401_inbound-inspection-execution.sql):
inspection.inspectionDocumentId— live reference to the assignedinspectionDocument(ON DELETE SET NULL); no feature snapshot.itemInspectionDocumentAssignment— PK(itemId, usage);usageenuminspectionDocumentUsage(v1: only'Receipt'; FAI/Production are additive enum values later). Edited on the item Quality tab (ItemQualityView).inspectionFeaturegained six nullable per-feature sampling columns (samplingPlanType/SampleSize/Percentage/Aql/InspectionLevel/Severity); NULL = inherit the document's default rule. Persisted through thesave_inspection_document_atomicfork 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$idloader 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), eventcarbon/pmi-inspection-plan. Senders:model-optimizeafter a run that wrotepmi.json(every item on the model), and thequeue_pmi_inspection_plansstatement handler onitemwhen an INSERT/UPDATE points an item at a model that already haspmiPath(that item only; skipped underapp.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 → nominal0, Tol+ = zone, Tol−0. Datums, notes, labels and valueless dimensions are left out. Units are the file's own (mm/in),degfor angles. - Once per item and model.
createPmiInspectionPlan(@carbon/database/quality) inserts withON CONFLICT DO NOTHINGon the partial unique indexinspectionDocument_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 callsdeleteUnusedPmiInspectionPlans(@carbon/database/quality), which deletes the items' PMI plans noinspectionused, so an automatic plan never tripspartId's RESTRICT; a used one still refuses the delete. Pinned, withcreatePmiInspectionPlan, bypackages/database/src/pmi-inspection-plan.test.ts; the trigger bysupabase/tests/pmi-inspection-plans.test.sql; the mapping againstvaluateMeasurementbypackages/jobs/.../pmi-inspection-plan.test.ts. - Screens.
InspectionView(ERP and MES) showsModelUploadPreview(@carbon/viewer/model-upload-preview, shared — not an app copy) in the drawing pane's place when the loader returnsmodel. ItspmiLinks(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
modelUploadIdnull (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.deleteUnusedPmiInspectionPlansruns as the system inside the item delete, soparts_deletealone can remove an unused PMI plan. - Recreating the
inspectionDocumentsview also added the sixsampling*columns added after it was first created (d.*is fixed at creation), sogetInspectionDocuments(thequality_getInspectionDocumentstool) reads the document's sampling default. - The Inspection Plans list (
/x/quality/inspection-plans) is one row per part, read from theinspectionPlanPartsview (getInspectionPlanParts,20261028161842_inspection-plan-parts-view.sql, recreated by20261028222414_inspection-plan-parts-group-tags.sql): the part, its plan count, its item group (itemCost.itemPostingGroupId) and tags (part.tags), and aplansjsonb 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 (expandRowsForon 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 thesave_inspection_document_atomicfork 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 byrecordInspectionGauge(@carbon/database/quality): closed-lot guard, company-scoped gauge, refusesInactivegauges and a gauge whose type differs from the feature'sgaugeTypeId. A gauge recorded on a closed lot (Passed/Failed/Partial) cannot be deleted — the triggerprevent_deleting_gauge_recorded_on_closed_inspection(20261001022340_inspection-gauge-history.sql) raises23503, 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: ERPx+/inspection+/$id.gauge.tsx, MESx+/inspection-lot.$id.gauge.tsx(path.to.inspectionGauge), quiet POSTs like the measurement cells. - Picker —
InspectionGaugePicker(ERPui/Inspections/, touch-sized copy in MEScomponents/Inspection/): a button filling the whole Gauge cell opens a search + list of Active gauges (thegaugesview, 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 —getRecentInspectionGaugesreturns the gauges most recently recorded at the lot's station: a Job Operation lot's station is its operation'sworkCenterId; 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:
- Loads items (
id, itemTrackingType, replenishmentSystem), companysamplingStandard, Receipt-usageitemInspectionDocumentAssignmentrows (assignmentByItemId), and the assigned documents'inspectionFeaturerows + default sampling columns. - Per receipt line whose item has a Receipt-usage assignment (
assignmentByItemId.get(itemId)) andreceivedQuantity > 0: the assigned document is the plan gate — no assignment, no lot. Resolves the lot plan viaresolveSamplingPlan(plan, lotSize, standard)frompackages/database/src/sampling.ts(ANSI Z1.4 / ISO 2859-1 tables; returns{ sampleSize, acceptance, rejection, codeLetter }). Document with no default rule →type: "All", levelII,Normal. Always resolves each feature viaresolveFeatureSamplingPlan(feature, documentDefault, lotSize, standard)(feature rule → document default → All), always stampsinspectionDocumentId = assignedDocumentIdon the lot (even a drawing-only document with no features), sets the lot-levelsampleSizeto the max across features (or the snapshot size when featureless), and (after the insert.returnings the lot ids) batch-inserts theinspectionSamplingPlanrows. - Tracked entities for items with a Receipt-usage assignment are set to
"On Hold"at receipt (not Available); everything else flips toAvailable. 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 companyautoStartOperationTimersetting; 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 gainedkonva/react-konva/pdfjs-distdeps + canvas SSR stub + worker bootstrap),ScanInspectionSample(adapted:@carbon/formfields, samples from make-method WIP entities),DispositionModal(the Reject/Partial failed-set allocator; replacedRejectLotModal2026-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), eachrequirePermissions({ update: "quality" })→ MES validators (~/services/models) → the shared engine withgetDatabaseClient()(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 theirapplySampleEntityStatusactivity writes) are guardedsourceDocument === "Receipt", matchingdispositionInspection'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 toRejected(see below). - MES reads:
apps/mes/app/services/quality.service.ts(copies of the ERP reads + a simplifiedgetInspectionDocumentWithBalloonsthat builds the/file/preview/private/pdfUrl frominspectionDocument.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):
- 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). 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).- Postings, each carrying provenance links (
productionQuantity.inspectionIdinspectionSampleId; 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.
- Optional NCR (
createNcr),willBeFinishedmirror fromcomplete.tsxfortargetQuantity = 0operations.
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
requiresInspectioncheckbox 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 onroutes/x+/{part,material,tool,consumable,service}+/$itemId.quality.tsx(actions branch onintent=assignment). The tab is always shown (norequiresInspectiongate in the item navigation hooks), for every item type, gated only by thequalityview permission. - Execution view:
.../ui/Inspections/InspectionView.tsx— full-screen, data-prop reusable (AssemblyView pattern, for later MES reuse). RendersInspectionDrawingPane.tsx(lazy react-pdf + Konva balloons, click ↔ row sync) aboveInspectionMeasurementGrid.tsxwhenpdfUrl != 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 whenliveFeatures.length > 0, otherwise the singleOVERALL_ROW_IDpass/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).isSerialshows Scan/Select tabs (entity required) and posts a Pending sample column with atrackedEntityId(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 oldinspections.$id.tsxis a redirect stub to the full-screen treex+/inspection+/(_layout.tsxmodulequality;$id.tsxloader 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 aKysely<KyselyDatabase>first param; ERP'squality.service.tswraps those engine calls with the caller'sdb(a route'sgetDatabaseClient(), a service function'sctx.asSystem.pg), and also holds the plan editor's server-only helpers (legacy save-payload translationtranslateLegacyInspectionSavePayload, the balloon-region vision callrunInspectionBalloonRegionVisionAnalysis).packages/database/src/sampling.tsis the pure resolver; the engine andpost-receiptboth consume it, so they share ONE resolver copy (ERP'ssamplingStandards.tsclient copy remains for UI previews).- Voided receipt (2026-10-16): a Receipt lot whose receipt is
Voidedis closed too.assertReceiptNotVoided(reads the receiptFOR 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$idloader passesreceiptVoidedsoInspectionViewtreats 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) andupsertInspectionMeasurement("Inspection is closed") andchangeInspectionDocument. Updating an EXISTING sample (or a measurement on one) additionally fails when aproductionQuantityrow links itsinspectionSampleId— the unit was already completed from that verdict; deleting the row in the ERP unlocks it (assertSampleNotLinked). upsertInspectionSample— upsert precedence: bytrackedEntityId(serial), else bysampleId(the "Overall result" row re-toggling an anonymous column in place), else insert a fresh anonymous sample. Entity flip +trackedActivityvia the sharedapplySampleEntityStatushelper; skipped forPending(identify-only) samples. The$id.sample.tsxroute returns thesampleIdand, whenquiet=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 featurerecorded >= n && failed <= Ac; Reject: the pureisRejectableWithoutReason(some featurefailed >= Reor a failed sample; with no features, failed samples > Ac — the rule both apps' Reject buttons apply, pinned bypackages/database/src/quality.test.ts) or areason, so a lot can be rejected with nothing failed, e.g. a suspected counterfeit, and the reason is stored as the lot'snotes); 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 anitemLedgerInbound Inspectionnegative adjustment); Partial leaves entities; always writesinspectionHistory. OptionalrequireOpen(one-shot mode, MES disposition route only): the status UPDATE gainsWHERE 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
rejectInspectionoperation (quality.server.ts, called byx+/inspection+/$id.reject.tsx), optional viacreateNcr, linking throughnonConformanceInspection; the description includes thereasonand a "Failed features" block built from the lot's measurements, and the lot'ssupplierIdis written as the issue'snonConformanceSupplier(insertIssue'ssupplierId). The$idloader 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'ssupplierId, never the inspection: an inspection link tellscloseIssuethe lot was written off at reject, which is only true for a rejected lot.
- Voided receipt (2026-10-16): a Receipt lot whose receipt is
- Service
quality.service.ts:getInspections(list),getInspection,getInspectionTrackedEntities,getInspectionSamplingPlans(embedsinspectionFeature(...)by table name),getInspectionMeasurements,getItemInspectionDocumentAssignments/upsertItemInspectionDocumentAssignment(empty documentId deletes the slot). - Validators
quality.models.ts:inspectionSampleValidator(trackedEntityIdoptional; status includesPending),inspectionDispositionValidator,inspectionMeasurementValidator(valuexorpassed),itemInspectionDocumentAssignmentValidator,inspectionDocumentUsagesconst. - Sampling engines (kept in sync manually):
resolveSamplingPlan+resolveFeatureSamplingPlanin bothapps/erp/app/modules/quality/samplingStandards.tsandpackages/database/src/sampling.ts.
Gotchas
- Lot-based, not entity-based. The Phase-1 per-entity
inspectionwas dropped; read the20260419163058migration (and newer) for the real shape.receiptLineIdis 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. trackedEntityIdis 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 def20261001022635) 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.tsxwhile 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/newBalloonIdinui/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, andmergeSaveResponse(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 sendtempId/tempBalloonAnchorIdand read thefeatureIdMap/balloonAnchorIdMapback. 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), soORDER 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 bycreatedAt, 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 idempotentpost-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
(
productionQuantitylinks 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.