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/" - "apps/erp/app/routes/x+/issue+/" - "packages/database/supabase/migrations/ncr.sql"
Issue / Non-Conformance Module
Carbon's quality module tracks non-conformances (NCRs), surfaced in the UI as
"Issues". Code lives in apps/erp/app/modules/quality/ (NOT a separate issue
module); routes live under apps/erp/app/routes/x+/issue+/. Schema is grounded
in the migrations — newest wins; core tables created in
20250327140050_ncr.sql.
Code (real paths)
quality.service.ts— the building blocks: issue/task/association/reviewer queries and writes,closeIssue, the disposition writers (dispositionInspection) and the inspection engine bindings (@carbon/database/quality).quality.models.ts— zod validators + status/enum const arrays.quality.server.ts— the operations, onedefineServiceFnconst each (createIssue,setIssueStatus,completeIssue,rejectInspection, …). A route calls them asapi.quality.setIssueStatus(input).ui/Issue/—IssueHeader,IssueContent,IssueForm,IssueProperties,IssueStatus,DispositionStatus,IssueTask,ActionTasksList,ReviewersList,AssociatedItemsList,IssueAssociations,IssuesTable(seeui/Issue/index.ts). Plusui/IssueTypes/,ui/IssueWorkflows/,ui/RequiredActions/,ui/Actions/.- Task creation:
createDocument(apps/erp/app/modules/shared/shared.service.ts, thecreateposting), case"nonConformanceTasks".
Status enums (verified in quality.models.ts + migrations)
- Issue status (
nonConformanceStatus):Registered→In Progress→Closed. DB column default is'Registered'.isIssueLocked(status)⇒status === "Closed"(blocks edits to issue + task assignments). - Task status (
nonConformanceTaskStatus):Pending,In Progress,Completed,Skipped. Tasks startPending; they do not auto-start. - Source (
nonConformanceSource):Internal,External. - Priority (
nonConformancePriority):Low,Medium,High,Critical. - Approval requirement (
nonConformanceApproval/nonConformanceApprovalRequirement): onlyMRB(Material Review Board). - Disposition: DB enum
dispositionhas 11 values (Conditional Acceptance,Deviation Accepted,Hold,No Action Required,Pending,Quarantine,Repair,Return to Supplier,Rework,Scrap,Use As Is); onnonConformanceItem.disposition(default'Pending'), added20251114222648.DispositionStatus.tsxrenders all 11. Gotcha: thedispositionconst array inquality.models.tscurrently has most values commented out (onlyPending,Return to Supplier,Rework,Scrap,Use As Isactive) — the picker is a deliberate subset of the DB enum. - Non-tracked disposition:
nonConformanceItemrows exist for non-tracked items (Inventory/Non-Inventory, e.g. a job-operation NCR fromapps/mesor a rejected non-tracked inbound-inspection lot) — they carry aquantityand nononConformanceItemTrackedEntitylinks.AssociatedItemsList.tsxrenders these as an inline-editable quantity + dispositionSelect(no entity chips; "Move entities" stays gated onlinks.length > 0). The quantity saves throughitem+/update.tsx(field: "quantity") →updateIssueItemField→updateIssueItemQuantity(quality.service.ts), which refuses rows with entity links (their quantity is the link sum) and any NCR with anonConformanceInspectionlink (the reject already wrote off the lot, andcloseIssuerestoresrow.quantityon Use As Is / Rework). The write is a compare-and-set onexpectedQuantity(the quantity the client last saw), so a stale save matches no row and is refused. It is a Kysely write, so the audit actor comes fromupdatedBy(the audit handler's fallback whenauth.uid()is null). - Issue disposition lock:
lockIssueDispositions(@carbon/database/quality) takesFOR NO KEY UPDATEon thenonConformancerow. Every writer that insertsnonConformanceItemTrackedEntity/nonConformanceInspectionrows or changesnonConformanceItem.quantitytakes it first, inside its transaction, before touching any item row: the quantity edit,assignEntitiesToIssueItem,splitIssueItem, the inspection association (createIssueAssociation), the job-operation auto-link ofcreateIssue, the ERP inspection reject (rejectInspection), sales-return escalation, and MESlinkIssueDispositionContext(which also writes the MES reject's inspection link, viacreateQualityIssue({ inspectionId })).linkEntitiesToIssueItemRowis the shared find-or-create-row + link + grow-quantity step. A new writer of those tables must take the lock too, or the quantity edit's link / inspection checks can race it. - Split works for a non-tracked row as a pure quantity split
(
splitIssueItemcreates a newPendingrow for the split-off quantity and shrinks the original, no entity subdivision), so MRB can e.g. scrap N and use-as-is the rest.closeIssuestill requires every row (tracked or not) to be non-Pending. - Disposition GL/cost posting (
closeIssue+ inspection reject): inventory value movements go through thepost-nonconformanceposting (postNonconformance,quality.service.ts:itemLedger+costLedgerrelief viacalculateCOGS+ a balancedjournaloffset toaccountDefault.scrapAccountfor every company — Provisional before the accounting cutover, when an emptyscrapAccountbecomes a stand-in line on retained earnings; after it an empty one falls back toinventoryAdjustmentVarianceAccount), not rawitemLedgerinserts.closeIssuebuildsmovements[]and invokes it BEFORE the status-flip transaction (idempotent per(documentType,documentId), so a retry is safe; a GL failure aborts the close). Movement rules: tracked Scrap/Return →-link.qtyper entity; non-trackedInventorynon-inspection Scrap →-row.qtywrite-off; non-trackedInventoryinspection-originated Use-As-Is/Rework →+row.qtyrestore (undoing the reject write-off); inspection-originated Return to Supplier → nothing, because the supplier return shipment puts those units back before it ships them (getReturnLineWriteOffsinpostShipment, at the write-off's own cost, Dr Inventory / Cr Scrap; voiding the shipment writes them off again) — without it the shipment relieved units the reject had already written off; tracked Use-As-Is/Rework and anyNon-Inventorymove no value. Origin detected via thenonConformanceInspectionlink. Reopen is blocked once aNon-ConformanceitemLedgerrow exists (setIssueStatus). See.claude/rules/inspection-system.mdand.ai/plans/2026-07-25-inspection-disposition-gl-posting.md.
Workflow (header buttons → routes)
IssueHeader.tsx (all gated by permissions.can("update","quality")):
- Start (when
Registered) → POSTpath.to.issueStatus(id){status:"In Progress"}→setIssueStatus, which takes only Registered / In Progress. - Complete (when
In Progress) →path.to.closeIssue(id)→completeIssue(posts the dispositions, setsClosed, clears assignee, setscloseDate). - Reopen (when
In Progress/Closed, not locked) →issueStatus{status:"Registered"}. - Delete Issue →
path.to.deleteIssue(id).
Issue auto-starts to In Progress when a user first types in a task note while
the issue is still Registered (IssueTask.tsx, one-shot).
Tasks (IssueTask.tsx statusActions): Start (Pending→In Progress),
Complete (In Progress→Completed), Reopen (Completed/Skipped→Pending).
Task status writes go to path.to.issueTaskStatus → setIssueTaskStatus;
updateIssueTaskStatus sets completedDate on Completed.
Required actions & system action types
Issues carry requiredActionIds TEXT[] (IDs into nonConformanceRequiredAction).
The create posting inserts one nonConformanceActionTask per id (1-indexed
sortOrder). nonConformanceRequiredAction.systemType (enum
nonConformanceSystemActionType, added 20260313000001):
Containment, Corrective, Preventive, Verification, Communication. System
rows are protected by trigger protect_system_required_actions_trigger (can't delete
or change systemType); unique per (companyId, systemType). Custom actions have
systemType IS NULL.
Approvals / MRB / reviewers
approvalRequirements nonConformanceApproval[] → the posting inserts a
nonConformanceApprovalTask per requirement. When MRB is newly required it
seeds two nonConformanceReviewer rows (title: "Engineering", "Quality");
removing MRB deletes the reviewers; existing reviewers are left untouched.
Reviewers managed in ReviewersList.tsx (nonConformanceReviewerValidator = just
title); insertIssueReviewer, getIssueReviewers.
Routes & URL structure
- List:
/x/quality/issues(x+/quality+/issues.tsx,IssuesTable). - Detail:
/x/issue/{id}→_indexredirects to…/details. There are no separate/investigations,/actions, or/reviewview tabs — action tasks and reviewers render inline in$id.details.tsx. ($id.review.tsxand$id.status.tsx/$id.close.tsxare POST-only.) - Other actions under
x+/issue+/:new.tsx,task.$id.status.tsx,task.supplier.tsx(onlynonConformanceActionTask),action.$id.due-date.tsx,action.$id.processes.tsx(→nonConformanceActionProcess),action-tasks.order.tsx(sortOrder reorder),$id.association.new.tsx,$id.association.delete.$type.$associationId.tsx, anditem+/(update,assign-entities,split).
Core tables (current schema)
nonConformance— main entity.id(id('nc')),nonConformanceId(readable),name,description,source,status(defaultRegistered),priority,requiredActionIds TEXT[],approvalRequirements nonConformanceApproval[],nonConformanceWorkflowId,nonConformanceTypeId,content JSON,locationId,openDate/dueDate/closeDate,quantity,assignee, audit. (itemIdwas dropped20250905122922→ moved to junction.)nonConformanceType(name case-insensitively unique per company — unique index on("companyId", LOWER("name"))since20260804134212; the issue-type routes also pre-check case-insensitively viagetIssueTypeByName),nonConformanceWorkflow,nonConformanceRequiredAction.- Tasks:
nonConformanceActionTask(actionTypeId→requiredAction,sortOrder,status,supplierId(20251114222648),dueDate),nonConformanceApprovalTask(approvalType),nonConformanceReviewer(title,status). nonConformanceActionProcess— action task ↔ process.- Multi-item:
nonConformanceItem(junction,20250905122922;disposition),nonConformanceItemTrackedEntity(20260421130000). - Associations (10 types, see
nonConformanceAssociationType):nonConformanceCustomer,nonConformanceSupplier(externalLinkId→externalLink),nonConformanceJobOperation,nonConformancePurchaseOrderLine,nonConformanceSalesOrderLine,nonConformanceShipmentLine,nonConformanceReceiptLine,nonConformanceTrackedEntity,nonConformanceInspection(created20260421091238as nonConformanceInboundInspection; renamed20260722132135).
issues view
SECURITY_INVOKER=true; newest def 20260317033634_issues-fix.sql. Selects
nonConformance.* plus items (TEXT[] from nonConformanceItem) and a computed
containmentStatus: Contained (a Containment-systemType action task is
In Progress/Completed), else Uncontained (a Containment task exists), else
N/A. getIssues reads this view. (companySettings.qualityIssueTarget, default
20, added alongside.)
Gotchas
- Investigations were removed. Migration
20251120214020_action-investigation-merge.sqldroppednonConformanceInvestigationTaskandnonConformanceInvestigationType, mergedinvestigationTypeIdsintorequiredActionIds, and dropped thenonConformanceInvestigation/nonConformanceActionenums. Investigation types are now justnonConformanceRequiredActionrows; their tasks arenonConformanceActionTaskrows. Dead code:IssueTask.tsxgetTable()andapi+/assign.tsstill have an"investigation"branch returning"nonConformanceInvestigationTask"— that table no longer exists; treat thetype: "investigation"UI path as vestigial. - The module is
quality, notissue; permission key isquality. Routes are split (x+/quality+/for list/types/workflows,x+/issue+/for the detail + actions). - Slack NC notifications post to the channel picked at Slack install, read off the company's
Slack connection (
getSlackWorkspace().channelId,integrationConnectionmetadata) — the oldnonconformance_channel_id/nonconformance_notifications_enabledjsonschema fields were dropped in20261026151304(they had no readers). - Filename
20251114222648_supplier_id.sqlis non-conformance work (supplier links + disposition enum), not a generic "supplier" change.