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.

docs: add link to documentation

Brad Barbinc5eef145d3a2
diff --git a/README.md b/README.md
index 7e609884f2..48bf8d6c41 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,7 @@
·
<a href="https://carbon.ms">Website</a>
·
- <a href="https://github.com/crbnos/carbon/issues">Issues</a>
+ <a href="https://docs.carbon.ms">Documentation</a>
</p>
</p>
<p align="center">
diff --git a/llm/cache/authentication-system.md b/llm/cache/authentication-system.md
index 113596590a..4b819b45d2 100644
--- a/llm/cache/authentication-system.md
+++ b/llm/cache/authentication-system.md
@@ -149,7 +149,7 @@ Located at `/packages/auth/`, the auth package provides:
- `public.userPermission` table with the user's ID
3. **Identity Group**: A separate trigger creates an identity group for the user
-<<<<<<< HEAD
+
### Self-Signup Flow
diff --git a/llm/cache/coding-conventions.md b/llm/cache/coding-conventions.md
index ba7537df94..2af2b1ccb8 100644
--- a/llm/cache/coding-conventions.md
+++ b/llm/cache/coding-conventions.md
@@ -69,12 +69,10 @@ The project uses a custom form library with validators:
import { validator } from "@carbon/form";
import { z } from "zod";
-export const customerValidator = validator(
- z.object({
- name: z.string().min(1),
- email: z.string().email(),
- })
-);
+export const customerValidator = z.object({
+ name: z.string().min(1),
+ email: z.string().email(),
+});
```
## Route Patterns
diff --git a/llm/cache/database-migration-patterns.md b/llm/cache/database-migration-patterns.md
index 1692f93652..670e2ed8ff 100644
--- a/llm/cache/database-migration-patterns.md
+++ b/llm/cache/database-migration-patterns.md
@@ -2,6 +2,13 @@
This document analyzes common patterns found in the Carbon database migrations.
+To create a database migration use `npm run db:migrate:new <name>`.
+
+- Migrations are stored in `/packages/database/supabase/migrations/`
+- Named with timestamps and descriptive names
+- Applied automatically via Supabase CLI
+
+
## 1. Table Creation Patterns
### Basic Table Structure
diff --git a/llm/cache/database-patterns.md b/llm/cache/database-patterns.md
index 7c6ffcf151..2aa3e7704a 100644
--- a/llm/cache/database-patterns.md
+++ b/llm/cache/database-patterns.md
@@ -30,13 +30,6 @@ import { getCarbonServiceRole } from "@carbon/auth";
const client = getCarbonServiceRole();
```
-### API Key Client
-
-```typescript
-import { getCarbonAPIKeyClient } from "@carbon/auth";
-
-const client = getCarbonAPIKeyClient(apiKey);
-```
## Query Patterns
@@ -128,7 +121,7 @@ const { data, error } = await client.rpc("create_sales_order", {
```typescript
const subscription = client
- .channel("sales_orders")
+ .channel("salesOrder")
.on(
"postgres_changes",
{
@@ -146,19 +139,14 @@ const subscription = client
## Error Handling
```typescript
-try {
- const { data, error } = await client.from("table").select().single();
-
- if (error) {
- console.error("Database error:", error);
- throw new Error("Failed to fetch data");
- }
+const { data, error } = await client.from("table").select().single();
- return data;
-} catch (err) {
- // Handle error appropriately
- throw err;
+if (error) {
+ console.error("Database error:", error);
+ throw new Error("Failed to fetch data");
}
+
+return data;
```
## Migration Management
@@ -167,14 +155,4 @@ try {
- Named with timestamps and descriptive names
- Applied automatically via Supabase CLI
-## Common Tables
-
-Based on the codebase, common tables include:
-- `customer` - Customer information
-- `supplier` - Supplier information
-- `item` - Products/parts/materials
-- `salesOrder` - Sales orders
-- `purchaseOrder` - Purchase orders
-- `employee` - Employee records
-- `company` - Company/tenant information
diff --git a/llm/cache/project-overview.md b/llm/cache/project-overview.md
index b67af1f9d0..fa18e41742 100644
--- a/llm/cache/project-overview.md
+++ b/llm/cache/project-overview.md
@@ -84,23 +84,6 @@ The ERP app organizes business logic into modules:
- File serving routes under `file+/` prefix
- External/shared routes under `share+/` prefix
-## External Links System
-
-The system supports external links for sharing quotes and customer portals:
-
-### Database Structure
-
-- `externalLink` table stores external link records
-- Fields: `id` (UUID), `documentType` (enum), `documentId`, `customerId`, `createdAt`, `expiresAt`, `companyId`
-- Document types: `'Quote'`, `'Customer'` (added in 2025-07-11 migration)
-
-### URL Structure
-
-External links follow these patterns:
-
-- **Quote Links**: `/share/quote/{externalLinkId}`
- - Example: `https://domain.com/share/quote/123e4567-e89b-12d3-a456-426614174000`
-- **Customer Portal Links**: Expected pattern `/share/customer/{externalLinkId}` (route not yet implemented)
### Path Configuration
@@ -111,13 +94,11 @@ In `/apps/erp/app/utils/path.ts`:
### Services
-- `upsertExternalLink()` - Create/update external links
+Each module defines a set of methods for interacting with the module. The convention is to have at least four methods for each table.
+
+- `deleteCustomerPortal()` - Delete customer portal link
- `getCustomerPortals()` - List customer portal links
- `getCustomerPortal()` - Get specific customer portal
-- `deleteCustomerPortal()` - Delete customer portal link
+- `upsertCustomerPortal()` - Create/update customer portal
-### Current Implementation Status
-- ✅ Quote external links fully implemented (`/share/quote/{id}`)
-- ⚠️ Customer portal links have database support but no public route yet
-- ⚠️ Customer portal form exists but routes incomplete (`path.to.customerPortal()`, `path.to.newCustomerPortal` not defined)
diff --git a/llm/cache/traceability-model.md b/llm/cache/traceability-model.md
new file mode 100644
index 0000000000..8a5b1d70e9
--- /dev/null
+++ b/llm/cache/traceability-model.md
@@ -0,0 +1,295 @@
+# Traceability Model
+
+## Overview
+
+Carbon's traceability system tracks the complete lineage of materials and products through the manufacturing process. The system is built around two core concepts:
+
+- **Tracked Entities** - Physical items, batches, or lots that need to be tracked (nodes in the graph)
+- **Tracked Activities** - Transformations or processes that consume inputs and produce outputs (edges in the graph)
+
+Together, these form a **directed acyclic graph (DAG)** that represents material flow from raw materials through transformations to finished products.
+
+## Core Tables
+
+### trackedEntity
+
+Represents a physical item, batch, or lot that needs to be tracked through the system.
+
+**Schema:**
+```sql
+CREATE TABLE "trackedEntity" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "quantity" NUMERIC NOT NULL,
+ "status" "trackedEntityStatus" NOT NULL DEFAULT 'Available',
+ "sourceDocument" TEXT NOT NULL,
+ "sourceDocumentId" TEXT NOT NULL,
+ "sourceDocumentReadableId" TEXT,
+ "attributes" JSONB NOT NULL DEFAULT '{}',
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL
+)
+```
+
+**Key Fields:**
+- `id` - Unique identifier (xid)
+- `quantity` - Current quantity of this entity
+- `status` - Enum: 'Available', 'Reserved', 'On Hold', 'Consumed'
+- `sourceDocument` - Type of document that created this entity (e.g., "Receipt", "Manufacturing")
+- `sourceDocumentId` - UUID of the specific revision that created this entity
+- `sourceDocumentReadableId` - Human-readable ID of the source document
+- `attributes` - JSONB containing:
+ - Serial numbers
+ - Batch numbers
+ - Manufacturing dates
+ - Expiration dates
+ - Receipt/supplier info
+ - Custom properties
+
+**Relationship to Item Ledger:**
+- `itemLedger.trackedEntityId` → `trackedEntity.id`
+- Each inventory transaction can be linked to a specific tracked entity
+- On deletion: SET NULL, On update: CASCADE
+
+### trackedActivity
+
+Represents a transformation or process that converts input entities into output entities.
+
+**Schema:**
+```sql
+CREATE TABLE "trackedActivity" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "type" TEXT NOT NULL,
+ "sourceDocument" TEXT,
+ "sourceDocumentId" TEXT,
+ "sourceDocumentReadableId" TEXT,
+ "attributes" JSONB NOT NULL DEFAULT '{}',
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL
+)
+```
+
+**Key Fields:**
+- `id` - Unique identifier
+- `type` - Describes the transformation (e.g., "Manufacturing", "Assembly", "Conversion")
+- `sourceDocument` - Document type that triggered this activity
+- `sourceDocumentId` - Specific document instance
+- `attributes` - Additional metadata about the transformation
+
+### Bridge Tables: trackedActivityInput & trackedActivityOutput
+
+These tables link activities to entities and define the graph structure.
+
+**trackedActivityInput:**
+```sql
+CREATE TABLE "trackedActivityInput" (
+ "trackedActivityId" TEXT NOT NULL,
+ "trackedEntityId" TEXT NOT NULL,
+ "quantity" NUMERIC NOT NULL,
+ "entityType" TEXT,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
+)
+```
+
+**trackedActivityOutput:**
+```sql
+CREATE TABLE "trackedActivityOutput" (
+ "trackedActivityId" TEXT NOT NULL,
+ "trackedEntityId" TEXT NOT NULL,
+ "quantity" NUMERIC NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
+)
+```
+
+## Graph Construction
+
+### Graph Structure
+
+The traceability system forms a **directed acyclic graph (DAG)** where:
+
+**Nodes:** TrackedEntity records
+- Represent physical items, batches, or lots
+- Have a status ('Available', 'Reserved', 'On Hold', 'Consumed')
+- Contain attributes specific to the entity
+
+**Edges:** TrackedActivity records with Input/Output relationships
+- Represent transformations or processes
+- Link consumed entities (inputs) to produced entities (outputs)
+- Create parent-child relationships in the lineage
+
+### Graph Pattern
+
+```
+[Entity A] ──input──> [Activity 1] ──output──> [Entity C]
+[Entity B] ──input──┘ └──output──> [Entity D]
+```
+
+For example, a manufacturing operation might consume raw materials (Entity A, B) through a manufacturing activity (Activity 1) to produce finished goods (Entity C, D).
+
+### TypeScript Graph Types
+
+From `apps/erp/app/modules/inventory/types.ts`:
+
+```typescript
+export interface GraphNode {
+ id: string;
+ type: "entity" | "activity";
+ data: TrackedEntity | Activity;
+ parentId: string | null;
+}
+
+export interface GraphLink {
+ source: string;
+ target: string;
+ type: "input" | "output";
+ quantity: number;
+}
+
+export interface GraphData {
+ nodes: GraphNode[];
+ links: GraphLink[];
+}
+```
+
+## Graph Traversal
+
+### SQL Functions
+
+Two key functions enable bidirectional graph traversal:
+
+**Get Descendants (Forward Tracing):**
+```sql
+get_direct_descendants_of_tracked_entity_strict(entity_id TEXT)
+```
+- Follows: Entity → Activity Input → Activity → Activity Output → Descendant Entity
+- Returns all entities produced from the given entity
+- Used for forward tracing (where did this material go?)
+
+**Get Ancestors (Backward Tracing):**
+```sql
+get_direct_ancestors_of_tracked_entity_strict(entity_id TEXT)
+```
+- Follows: Entity → Activity Output → Activity → Activity Input → Ancestor Entity
+- Returns all entities consumed to produce the given entity
+- Used for backward tracing (where did this come from?)
+
+### Graph Visualization
+
+The traceability graph is visualized in `apps/erp/app/routes/x+/traceability+/graph.tsx`:
+- Constructs nodes and links from entities and activities
+- Supports ancestor/descendant traversal
+- Provides interactive visualization of material lineage
+
+## Common Workflows
+
+### Creating Tracked Entities
+
+Tracked entities are created during various operations:
+
+1. **Receipt** (`post-receipt/index.ts`)
+ - Creates trackedEntity for received materials
+ - Links to receipt document
+ - Stores supplier info, batch numbers, etc. in attributes
+
+2. **Manufacturing** (`post-production/index.ts`, MES operations)
+ - Creates trackedActivity
+ - Links input materials via trackedActivityInput
+ - Creates output entities via trackedActivityOutput
+ - Updates entity statuses (inputs → 'Consumed', outputs → 'Available')
+
+3. **Shipment** (`post-shipment/index.ts`)
+ - May create activities for shipped items
+ - Tracks what entities left the facility
+
+4. **Stock Transfer** (`post-stock-transfer/index.ts`)
+ - Transfers entities between locations
+ - Maintains traceability across locations
+
+### Conversion Pattern
+
+Step-by-step process for converting tracked entities (e.g., material → part):
+
+1. Create a `trackedActivity` record describing the transformation
+2. Create `trackedActivityInput` records for consumed entities
+3. Create `trackedActivityOutput` records for produced items
+4. Update item ledgers with deductions (inputs) and additions (outputs)
+5. Update entity statuses (consumed entities → 'Consumed')
+
+**Example from revision-system.md:**
+```sql
+-- 1. Create the activity
+INSERT INTO "trackedActivity" (id, type, sourceDocument, sourceDocumentId, ...)
+VALUES ('activity_123', 'Manufacturing', 'ProductionOrder', 'po_456', ...);
+
+-- 2. Link consumed entities
+INSERT INTO "trackedActivityInput" (trackedActivityId, trackedEntityId, quantity, ...)
+VALUES ('activity_123', 'material_entity_1', 10, ...);
+
+-- 3. Link produced entities
+INSERT INTO "trackedActivityOutput" (trackedActivityId, trackedEntityId, quantity, ...)
+VALUES ('activity_123', 'part_entity_1', 5, ...);
+
+-- 4. Update ledgers and statuses
+UPDATE "trackedEntity" SET status = 'Consumed' WHERE id = 'material_entity_1';
+```
+
+## Key Service Functions
+
+### ERP Inventory Service
+`apps/erp/app/modules/inventory/inventory.service.ts`:
+- `getTrackedEntities()` - Get entities for an item
+- `getTrackedEntitiesByMakeMethodId()` - Get entities produced by a make method
+- `getTrackedEntitiesByOperationId()` - Get entities produced by an operation
+
+### MES Operations Service
+`apps/mes/app/services/operations.service.ts`:
+- `getTrackedEntitiesByMakeMethodId()` - Get available entities for production
+- `getTrackedEntity()` - Get specific entity details
+- `getTrackedInputs()` - Get consumed inputs for an activity
+- `startProductionEvent()` - Creates activities and links during production
+
+## QR Code Integration
+
+Tracked entities can have QR codes generated for labeling:
+- `ProductLabelPDF` uses `generateQRCode(item.trackedEntityId, size)`
+- Enables scanning for instant traceability lookup
+- Reference: `llm/cache/pdf-generation-patterns.md:43`
+
+## Common Queries
+
+### Get Tracked Entities for an Item (All Revisions)
+```sql
+SELECT te.*
+FROM "trackedEntity" te
+JOIN "item" i ON i.id = te."sourceDocumentId"
+WHERE i."readableId" = 'ITEM-001'
+ AND te."sourceDocument" = 'Item';
+```
+
+### Get Tracked Entities for Specific Revision
+```sql
+SELECT *
+FROM "trackedEntity"
+WHERE "sourceDocumentId" = '<item-revision-uuid>'
+ AND "sourceDocument" = 'Item';
+```
+
+### Get Complete Lineage Chain
+Combine ancestor and descendant queries to trace the full path from raw material to finished product.
+
+## Migration History
+
+- `20250225145619_tracked-entities.sql` - Initial schema creation
+- `20250301125444_tracked-materials.sql` - Added graph traversal functions and triggers
+
+## Related Documentation
+
+- `llm/cache/revision-system.md` - Complete revision and traceability documentation
+- `llm/cache/pdf-generation-patterns.md` - QR code generation for entities
+- `apps/erp/app/modules/inventory/types.ts` - TypeScript type definitions
+- `apps/erp/app/routes/x+/traceability+/graph.tsx` - Graph visualization implementation