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.

13.0 KB
Raw Blame

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, one defineServiceFn const each (createIssue, setIssueStatus, completeIssue, rejectInspection, …). A route calls them as api.quality.setIssueStatus(input).
  • ui/Issue/ — IssueHeader, IssueContent, IssueForm, IssueProperties, IssueStatus, DispositionStatus, IssueTask, ActionTasksList, ReviewersList, AssociatedItemsList, IssueAssociations, IssuesTable (see ui/Issue/index.ts). Plus ui/IssueTypes/, ui/IssueWorkflows/, ui/RequiredActions/, ui/Actions/.
  • Task creation: createDocument (apps/erp/app/modules/shared/shared.service.ts, the create posting), 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 start Pending; they do not auto-start.
  • Source (nonConformanceSource): Internal, External.
  • Priority (nonConformancePriority): Low, Medium, High, Critical.
  • Approval requirement (nonConformanceApproval / nonConformanceApprovalRequirement): only MRB (Material Review Board).
  • Disposition: DB enum disposition has 11 values (Conditional Acceptance, Deviation Accepted, Hold, No Action Required, Pending, Quarantine, Repair, Return to Supplier, Rework, Scrap, Use As Is); on nonConformanceItem.disposition (default 'Pending'), added 20251114222648. DispositionStatus.tsx renders all 11. Gotcha: the disposition const array in quality.models.ts currently has most values commented out (only Pending, Return to Supplier, Rework, Scrap, Use As Is active) — the picker is a deliberate subset of the DB enum.
  • Non-tracked disposition: nonConformanceItem rows exist for non-tracked items (Inventory / Non-Inventory, e.g. a job-operation NCR from apps/mes or a rejected non-tracked inbound-inspection lot) — they carry a quantity and no nonConformanceItemTrackedEntity links. AssociatedItemsList.tsx renders these as an inline-editable quantity + disposition Select (no entity chips; "Move entities" stays gated on links.length > 0). The quantity saves through item+/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 a nonConformanceInspection link (the reject already wrote off the lot, and closeIssue restores row.quantity on Use As Is / Rework). The write is a compare-and-set on expectedQuantity (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 from updatedBy (the audit handler's fallback when auth.uid() is null).
  • Issue disposition lock: lockIssueDispositions (@carbon/database/quality) takes FOR NO KEY UPDATE on the nonConformance row. Every writer that inserts nonConformanceItemTrackedEntity / nonConformanceInspection rows or changes nonConformanceItem.quantity takes it first, inside its transaction, before touching any item row: the quantity edit, assignEntitiesToIssueItem, splitIssueItem, the inspection association (createIssueAssociation), the job-operation auto-link of createIssue, the ERP inspection reject (rejectInspection), sales-return escalation, and MES linkIssueDispositionContext (which also writes the MES reject's inspection link, via createQualityIssue({ inspectionId })). linkEntitiesToIssueItemRow is 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 (splitIssueItem creates a new Pending row 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. closeIssue still requires every row (tracked or not) to be non-Pending.
  • Disposition GL/cost posting (closeIssue + inspection reject): inventory value movements go through the post-nonconformance posting (postNonconformance, quality.service.ts: itemLedger + costLedger relief via calculateCOGS + a balanced journal offset to accountDefault.scrapAccount for every company — Provisional before the accounting cutover, when an empty scrapAccount becomes a stand-in line on retained earnings; after it an empty one falls back to inventoryAdjustmentVarianceAccount), not raw itemLedger inserts. closeIssue builds movements[] 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.qty per entity; non-tracked Inventory non-inspection Scrap → -row.qty write-off; non-tracked Inventory inspection-originated Use-As-Is/Rework → +row.qty restore (undoing the reject write-off); inspection-originated Return to Supplier → nothing, because the supplier return shipment puts those units back before it ships them (getReturnLineWriteOffs in postShipment, 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 any Non-Inventory move no value. Origin detected via the nonConformanceInspection link. Reopen is blocked once a Non-Conformance itemLedger row exists (setIssueStatus). See .claude/rules/inspection-system.md and .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) → POST path.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, sets Closed, clears assignee, sets closeDate).
  • 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} → _index redirects to …/details. There are no separate /investigations, /actions, or /review view tabs — action tasks and reviewers render inline in $id.details.tsx. ($id.review.tsx and $id.status.tsx/$id.close.tsx are POST-only.)
  • Other actions under x+/issue+/: new.tsx, task.$id.status.tsx, task.supplier.tsx (only nonConformanceActionTask), 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, and item+/ (update, assign-entities, split).

Core tables (current schema)

  • nonConformance — main entity. id (id('nc')), nonConformanceId (readable), name, description, source, status (default Registered), priority, requiredActionIds TEXT[], approvalRequirements nonConformanceApproval[], nonConformanceWorkflowId, nonConformanceTypeId, content JSON, locationId, openDate/dueDate/closeDate, quantity, assignee, audit. (itemId was dropped 20250905122922 → moved to junction.)
  • nonConformanceType (name case-insensitively unique per company — unique index on ("companyId", LOWER("name")) since 20260804134212; the issue-type routes also pre-check case-insensitively via getIssueTypeByName), 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 (created 20260421091238 as nonConformanceInboundInspection; renamed 20260722132135).

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.sql dropped nonConformanceInvestigationTask and nonConformanceInvestigationType, merged investigationTypeIds into requiredActionIds, and dropped the nonConformanceInvestigation/nonConformanceAction enums. Investigation types are now just nonConformanceRequiredAction rows; their tasks are nonConformanceActionTask rows. Dead code: IssueTask.tsx getTable() and api+/assign.ts still have an "investigation" branch returning "nonConformanceInvestigationTask" — that table no longer exists; treat the type: "investigation" UI path as vestigial.
  • The module is quality, not issue; permission key is quality. 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, integrationConnection metadata) — the old nonconformance_channel_id / nonconformance_notifications_enabled jsonschema fields were dropped in 20261026151304 (they had no readers).
  • Filename 20251114222648_supplier_id.sql is non-conformance work (supplier links + disposition enum), not a generic "supplier" change.