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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add search by customer to scheudle
Brad Barbin92ec8f8b8509
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/ScheuleNavigation.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/ScheuleNavigation.tsxindex 7667d15c4e..0747edf906 100644--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/ScheuleNavigation.tsx+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/ScheuleNavigation.tsx@@ -26,16 +26,13 @@ export function ScheduleNavigation() {const getCurrentView = () => {if (location.pathname.includes(path.to.scheduleOperation))return "operations";- if (- location.pathname.includes(path.to.scheduleDates) &&- location.search.includes("view=week")- )+ if (location.pathname.includes(path.to.scheduleDates)) {+ if (location.search.includes("view=month")) {+ return "month";+ }+ // Default to week for scheduleDates path (whether view=week or no view param)return "week";- if (- location.pathname.includes(path.to.scheduleDates) &&- location.search.includes("view=month")- )- return "month";+ }return "operations";};diff --git a/apps/erp/app/routes/x+/schedule+/dates.tsx b/apps/erp/app/routes/x+/schedule+/dates.tsxindex d8975588f1..d16b35aeb6 100644--- a/apps/erp/app/routes/x+/schedule+/dates.tsx+++ b/apps/erp/app/routes/x+/schedule+/dates.tsx@@ -13,6 +13,7 @@ import {Popover,PopoverContent,PopoverTrigger,+ Separator,Spinner,Switch,useLocalStorage,@@ -182,6 +183,7 @@ export async function loader({ request }: LoaderFunctionArgs) {(job) =>job.jobId.toLowerCase().includes(search.toLowerCase()) ||job.itemReadableId?.toLowerCase().includes(search.toLowerCase()) ||+ job.customerName?.toLowerCase().includes(search.toLowerCase()) ||job.itemDescription?.toLowerCase().includes(search.toLowerCase()));}@@ -513,56 +515,67 @@ function DateKanbanSchedule() {aria-label="Next Date"/></HStack>- <Combobox- asButton- size="sm"- value={locationId ?? undefined}- options={locations}- onChange={(selected) => {- const newParams = new URLSearchParams(searchParams);- newParams.set("location", selected);- window.location.href = `${- path.to.scheduleDates- }?${newParams.toString()}`;- }}- />+<Popover><PopoverTrigger asChild>- <Button- leftIcon={<LuSettings2 />}+ <IconButton+ aria-label="Settings"+ icon={<LuSettings2 />}variant="secondary"className="border-dashed border-border"- >- Display- </Button>+ /></PopoverTrigger>- <PopoverContent className="w-48">- <VStack>- {[- { key: "showCustomer", label: "Customer" },- { key: "showDueDate", label: "Due Date" },- { key: "showDuration", label: "Duration" },- { key: "showProgress", label: "Progress" },- { key: "showQuantity", label: "Quantity" },- { key: "showStatus", label: "Status" },- { key: "showSalesOrder", label: "Sales Order" },- { key: "showThumbnail", label: "Thumbnail" },- ].map(({ key, label }) => (- <Switch- key={key}- variant="small"- label={label}- checked={- displaySettings[key as keyof typeof displaySettings]- }- onCheckedChange={(checked) =>- setDisplaySettings((prev) => ({- ...prev,- [key]: checked,- }))- }+ <PopoverContent className="w-64">+ <VStack spacing={3}>+ <span className="text-xs font-medium text-muted-foreground">+ Location+ </span>+ <div className="w-full">+ <Combobox+ asButton+ size="sm"+ value={locationId ?? undefined}+ options={locations}+ onChange={(selected) => {+ const newParams = new URLSearchParams(searchParams);+ newParams.set("location", selected);+ window.location.href = `${+ path.to.scheduleDates+ }?${newParams.toString()}`;+ }}/>- ))}+ </div>+ <Separator />+ <span className="text-xs font-medium text-muted-foreground">+ Display Settings+ </span>+ <VStack>+ {[+ { key: "showCustomer", label: "Customer" },+ { key: "showDueDate", label: "Due Date" },+ { key: "showDuration", label: "Duration" },+ { key: "showProgress", label: "Progress" },+ { key: "showQuantity", label: "Quantity" },+ { key: "showStatus", label: "Status" },+ { key: "showSalesOrder", label: "Sales Order" },+ { key: "showThumbnail", label: "Thumbnail" },+ ].map(({ key, label }) => (+ <Switch+ key={key}+ variant="small"+ label={label}+ checked={+ displaySettings[key as keyof typeof displaySettings]+ }+ onCheckedChange={(checked) =>+ setDisplaySettings((prev) => ({+ ...prev,+ [key]: checked,+ }))+ }+ />+ ))}+ </VStack></VStack></PopoverContent></Popover>diff --git a/apps/erp/app/routes/x+/schedule+/operations.tsx b/apps/erp/app/routes/x+/schedule+/operations.tsxindex 190352ff6a..699b4ee237 100644--- a/apps/erp/app/routes/x+/schedule+/operations.tsx+++ b/apps/erp/app/routes/x+/schedule+/operations.tsx@@ -9,9 +9,11 @@ import {ClientOnly,Combobox,HStack,+ IconButton,Popover,PopoverContent,PopoverTrigger,+ Separator,Spinner,Switch,toast,@@ -196,6 +198,7 @@ export async function loader({ request }: LoaderFunctionArgs) {(op) =>op.jobReadableId.toLowerCase().includes(search.toLowerCase()) ||op.itemReadableId.toLowerCase().includes(search.toLowerCase()) ||+ op.customerName?.toLowerCase().includes(search.toLowerCase()) ||op.description?.toLowerCase().includes(search.toLowerCase()));}@@ -417,54 +420,63 @@ function KanbanSchedule() {</HStack><div className="flex items-center gap-2">- <Combobox- asButton- size="sm"- value={locationId}- options={locations}- onChange={(selected) => {- // hard refresh because initialValues update has no effect otherwise- window.location.href = getLocationPath(selected);- }}- /><Popover><PopoverTrigger asChild>- <Button- leftIcon={<LuSettings2 />}+ <IconButton+ aria-label="Settings"+ icon={<LuSettings2 />}variant="secondary"className="border-dashed border-border"- >- Display- </Button>+ /></PopoverTrigger>- <PopoverContent className="w-48">- <VStack>- {[- { key: "showCustomer", label: "Customer" },- { key: "showDescription", label: "Description" },- { key: "showDueDate", label: "Due Date" },- { key: "showDuration", label: "Duration" },- { key: "showProgress", label: "Progress" },- { key: "showQuantity", label: "Quantity" },- { key: "showStatus", label: "Status" },- { key: "showSalesOrder", label: "Sales Order" },- { key: "showThumbnail", label: "Thumbnail" },- ].map(({ key, label }) => (- <Switch- key={key}- variant="small"- label={label}- checked={- displaySettings[key as keyof typeof displaySettings]- }- onCheckedChange={(checked) =>- setDisplaySettings((prev) => ({- ...prev,- [key]: checked,- }))- }+ <PopoverContent className="w-64">+ <VStack spacing={3}>+ <span className="text-xs font-medium text-muted-foreground">+ Location+ </span>+ <div className="w-full">+ <Combobox+ asButton+ size="sm"+ value={locationId}+ options={locations}+ onChange={(selected) => {+ // hard refresh because initialValues update has no effect otherwise+ window.location.href = getLocationPath(selected);+ }}/>- ))}+ </div>+ <Separator />+ <span className="text-xs font-medium text-muted-foreground">+ Display Settings+ </span>+ <VStack>+ {[+ { key: "showCustomer", label: "Customer" },+ { key: "showDueDate", label: "Due Date" },+ { key: "showDuration", label: "Duration" },+ { key: "showProgress", label: "Progress" },+ { key: "showQuantity", label: "Quantity" },+ { key: "showStatus", label: "Status" },+ { key: "showSalesOrder", label: "Sales Order" },+ { key: "showThumbnail", label: "Thumbnail" },+ ].map(({ key, label }) => (+ <Switch+ key={key}+ variant="small"+ label={label}+ checked={+ displaySettings[key as keyof typeof displaySettings]+ }+ onCheckedChange={(checked) =>+ setDisplaySettings((prev) => ({+ ...prev,+ [key]: checked,+ }))+ }+ />+ ))}+ </VStack></VStack></PopoverContent></Popover>@@ -692,7 +704,9 @@ function useProgressByOperation(const { old: deleted } = payload;setItems((prevItems: OperationItem[]) =>sortItems(- prevItems.filter((item: OperationItem) => item.id !== deleted.id)+ prevItems.filter(+ (item: OperationItem) => item.id !== deleted.id+ )));break;diff --git a/llm/cache/database-migration-patterns.md b/llm/cache/database-migration-patterns.mdindex 670e2ed8ff..0307f485c8 100644--- a/llm/cache/database-migration-patterns.md+++ b/llm/cache/database-migration-patterns.md@@ -8,7 +8,6 @@ To create a database migration use `npm run db:migrate:new <name>`.- Named with timestamps and descriptive names- Applied automatically via Supabase CLI-## 1. Table Creation Patterns### Basic Table Structure@@ -176,7 +175,7 @@ FOR SELECT USING (### Financial Columns-- `NUMERIC(10,2)` or `DECIMAL(10,2)` for monetary values+- `NUMERIC` or `DECIMAL(10,2)` for monetary values- `INTEGER` for quantities- `REAL` for percentagesdiff --git a/llm/cache/purchasing-conversion-factors.md b/llm/cache/purchasing-conversion-factors.mdindex 32dc2d34fb..b8aba8ee4e 100644--- a/llm/cache/purchasing-conversion-factors.md+++ b/llm/cache/purchasing-conversion-factors.md@@ -9,29 +9,35 @@ Carbon's purchasing system includes comprehensive support for conversion factors### Core Tables with Conversion Factor Support#### Supplier Quote Lines (`supplierQuoteLine`)-- `conversionFactor`: NUMERIC(10,5) NOT NULL DEFAULT 1++- `conversionFactor`: NUMERIC NOT NULL DEFAULT 1- `inventoryUnitOfMeasureCode`: Unit used for inventory tracking- `purchaseUnitOfMeasureCode`: Unit used for purchasing from supplier- Created in migration: `20241202192419_supplier-quotes.sql`#### Purchase Order Lines (`purchaseOrderLine`)-- `conversionFactor`: NUMERIC(10,2) DEFAULT 1++- `conversionFactor`: NUMERIC DEFAULT 1- Added in migration: `20240402052512_purchasing-conversion-factors.sql`#### Purchase Invoice Lines (`purchaseInvoiceLine`)-- `conversionFactor`: NUMERIC(10,2) DEFAULT 1++- `conversionFactor`: NUMERIC DEFAULT 1- Added in migration: `20240402052512_purchasing-conversion-factors.sql`#### Receipt Lines (`receiptLine`)-- `conversionFactor`: NUMERIC(10,2) DEFAULT 1++- `conversionFactor`: NUMERIC DEFAULT 1- Added in migration: `20240402052512_purchasing-conversion-factors.sql`## UI Implementation### ConversionFactor Component+**Location**: `/apps/erp/app/components/Form/ConversionFactor.tsx`**Key Features**:+- Interactive modal-based UI for setting conversion factors- Bidirectional conversion direction switching (inventory-to-purchased / purchased-to-inventory)- Automatic calculation and display of conversion relationships@@ -39,6 +45,7 @@ Carbon's purchasing system includes comprehensive support for conversion factors- Disabled when inventory and purchase units are the same (defaults to 1)**Usage Example**:+```typescript<ConversionFactorname="conversionFactor"@@ -52,20 +59,25 @@ Carbon's purchasing system includes comprehensive support for conversion factors## Unit Price Calculations### Supplier Quote Line Pricing+**Location**: `/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteLinePricing.tsx`**Key Calculation** (Line 250):+```typescript-const inventoryUnitPrice = supplierUnitPrice * exchangeRate / conversionFactor;+const inventoryUnitPrice =+ (supplierUnitPrice * exchangeRate) / conversionFactor;```**Explanation**:+1. **Supplier Unit Price**: Price per purchase unit (e.g., $100 per case)2. **Exchange Rate**: Currency conversion (e.g., 1.25 USD per CAD)3. **Conversion Factor**: Units conversion (e.g., 12 pieces per case)-4. **Result**: Price per inventory unit (e.g., $100 * 1.25 / 12 = $10.42 per piece)+4. **Result**: Price per inventory unit (e.g., $100 \* 1.25 / 12 = $10.42 per piece)### Price Display Structure+- **Supplier Unit Price**: Shows price in purchase UOM with supplier currency- **Unit Price**: Shows converted price in inventory UOM with base currency- **Conversion Factor**: Applied to convert between purchase and inventory pricing@@ -73,29 +85,35 @@ const inventoryUnitPrice = supplierUnitPrice * exchangeRate / conversionFactor;## Workflow Integration### Supplier Quote to Purchase Order Flow+1. Supplier quotes capture conversion factors during line creation2. Conversion factors are automatically inherited when creating purchase orders from quotes3. Unit prices are recalculated using the conversion factor for inventory costing### Purchase Order to Receipt Flow+1. Purchase order lines maintain conversion factors for receiving2. Receipt lines inherit conversion factors to properly convert received quantities3. Inventory quantities are updated using converted amounts### Purchase Invoice Processing+1. Invoice lines include conversion factors for accurate cost allocation2. Unit costs are calculated using converted prices for inventory valuation## Business Logic### Automatic Conversion Factor Detection+When selecting items in purchasing forms:+1. System checks for existing supplier parts with pre-defined conversion factors2. Loads item's default inventory unit of measure3. Loads supplier's preferred purchase unit of measure4. Sets conversion factor from supplier part relationship or defaults to 1### Validation Rules+- Conversion factor must be greater than 0- Defaults to 1 when inventory and purchase units are identical- Required for all purchasing transactions to maintain unit consistency@@ -103,6 +121,7 @@ When selecting items in purchasing forms:## Data Models### Supplier Quote Line Validator+```typescriptexport const supplierQuoteLineValidator = z.object({conversionFactor: zfd.numeric(z.number().optional()),@@ -113,6 +132,7 @@ export const supplierQuoteLineValidator = z.object({```### Purchase Order Line Validator+```typescriptexport const purchaseOrderLineValidator = z.object({conversionFactor: zfd.numeric(z.number().optional()),@@ -133,6 +153,7 @@ export const purchaseOrderLineValidator = z.object({## Example Scenarios### Scenario 1: Bulk Purchase with Individual Tracking+- **Item**: Screws- **Inventory UOM**: Each (EA)- **Purchase UOM**: Box@@ -140,10 +161,11 @@ export const purchaseOrderLineValidator = z.object({- **Supplier Price**: $50 per box- **Inventory Unit Cost**: $50 ÷ 100 = $0.50 per screw-### Scenario 2: Material Purchase with Different Measurements+### Scenario 2: Material Purchase with Different Measurements+- **Item**: Steel Sheet- **Inventory UOM**: Square Feet (SF)- **Purchase UOM**: Square Meters (SM)- **Conversion Factor**: 10.764 (10.764 SF per SM)- **Supplier Price**: €25 per SM-- **Inventory Unit Cost**: €25 ÷ 10.764 = €2.32 per SF\ No newline at end of file+- **Inventory Unit Cost**: €25 ÷ 10.764 = €2.32 per SFdiff --git a/llm/cache/quote-discount-system.md b/llm/cache/quote-discount-system.mdindex 8ebb43b9e6..2ac2aa283c 100644--- a/llm/cache/quote-discount-system.md+++ b/llm/cache/quote-discount-system.md@@ -1,32 +1,37 @@# Quote Discount System## Overview+The Carbon ERP system includes discount functionality at the quote line price level, not at the quote header or quote line level directly.## Database Structure### Quote Table+- No discount fields exist on the `quote` table itself- Located in migration: `20240715024405_quotes.sql`### Quote Line Table (`quoteLine`)+- No discount fields exist on the `quoteLine` table itself- Contains: `additionalCharges`, `taxPercent`, but no discount fields### Quote Line Price Table (`quoteLinePrice`)+- Contains the discount functionality- Located in migration: `20240715134816_quote-pricing.sql`- Key fields:- - `discountPercent`: NUMERIC(10,5) NOT NULL DEFAULT 0- - `unitPrice`: NUMERIC(10,5) NOT NULL DEFAULT 0- - `quantity`: NUMERIC(10,5) NOT NULL DEFAULT 1- - `leadTime`: NUMERIC(10,5) NOT NULL DEFAULT 0- - `shippingCost`: NUMERIC(10,5) NOT NULL DEFAULT 0- - `exchangeRate`: NUMERIC(10,5)+ - `discountPercent`: NUMERIC NOT NULL DEFAULT 0+ - `unitPrice`: NUMERIC NOT NULL DEFAULT 0+ - `quantity`: NUMERIC NOT NULL DEFAULT 1+ - `leadTime`: NUMERIC NOT NULL DEFAULT 0+ - `shippingCost`: NUMERIC NOT NULL DEFAULT 0+ - `exchangeRate`: NUMERIC## UI Implementation### QuoteLinePricing Component+- Location: `/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx`- Displays discount as a percentage field- Calculates net unit price as: `unitPrice * (1 - discountPercent)`@@ -36,6 +41,7 @@ The Carbon ERP system includes discount functionality at the quote line price le## Service Layer### Sales Service+- Location: `/apps/erp/app/modules/sales/sales.service.ts`- Handles discount persistence when updating quote line prices- Preserves existing discounts when recalculating prices@@ -47,12 +53,13 @@ The Carbon ERP system includes discount functionality at the quote line price le1. **Per-Quantity Discounts**: Each quantity break can have its own discount percentage2. **Net Price Calculation**: Automatically calculates net price after discount-3. **Precision Control**: Discount percent uses NUMERIC(10,5) allowing up to 5 decimal places+3. **Precision Control**: Discount percent uses NUMERIC allowing up to 5 decimal places4. **UI Integration**: Full editing capabilities in the quote line pricing interface## Type DefinitionsThe `QuotationPrice` type (from `sales.service.ts` exports) includes:+- `discountPercent`: number- `unitPrice`: number- `leadTime`: number@@ -63,6 +70,7 @@ The `QuotationPrice` type (from `sales.service.ts` exports) includes:## Sales Order and Invoice Integration### Sales Order Lines+- The `salesOrderLine` table does NOT contain discount fields- The `salesOrderLines` view (created in `20240412224648_sales-orders.sql`) includes:- Basic sales order line fields@@ -71,6 +79,7 @@ The `QuotationPrice` type (from `sales.service.ts` exports) includes:- **No discount information is included in this view**### Sales Invoice Lines+- The `salesInvoiceLine` table does NOT contain discount fields- The `salesInvoiceLines` view (created in `20250507143421_sales-invoice.sql`) includes:- Basic invoice line fields@@ -80,13 +89,15 @@ The `QuotationPrice` type (from `sales.service.ts` exports) includes:- **No discount information is included in this view**### Quote to Sales Order/Invoice Flow+- Sales orders and invoices were originally designed to reference quotes (via `quoteId`)- This relationship appears to have been removed/commented out in the migrations- Currently, there is no direct link between quote line prices (with discounts) and sales order/invoice lines- Discount information from quotes is NOT automatically propagated to sales orders or invoices## Notes+- Discounts are applied at the price level per quantity, not at the quote or line level- The system calculates net prices dynamically based on unit price and discount percent- No global quote-level discount exists; all discounts are line-item and quantity-specific-- **Important**: Discount information exists only in the `quoteLinePrice` table and is not available in sales order or invoice views\ No newline at end of file+- **Important**: Discount information exists only in the `quoteLinePrice` table and is not available in sales order or invoice viewsdiff --git a/llm/cache/scheduling-data-structures.md b/llm/cache/scheduling-data-structures.mdnew file mode 100644index 0000000000..dd234f1fc4--- /dev/null+++ b/llm/cache/scheduling-data-structures.md@@ -0,0 +1,195 @@+# Scheduling Data Structures++## Overview++This document describes the data structures returned by scheduling-related database functions, particularly focusing on customer and part number fields.++## getActiveJobOperationsByLocation++### Function Signature+```typescript+getActiveJobOperationsByLocation(+ client: SupabaseClient<Database>,+ locationId: string,+ workCenterIds: string[] = []+)+```++### Database Function+Located in: `/packages/database/supabase/migrations/20241024111311_active-job-operations.sql`++### Return Fields++The function returns a table with the following fields:++#### Operation Fields+- `id` TEXT - Operation ID+- `operationOrder` DOUBLE PRECISION - Order of operation in sequence+- `priority` DOUBLE PRECISION - Operation priority+- `processId` TEXT - Process ID+- `workCenterId` TEXT - Work center ID+- `description` TEXT - Operation description+- `setupTime` NUMERIC(10,2) - Setup time+- `setupUnit` factor - Setup time unit+- `laborTime` NUMERIC(10,2) - Labor time+- `laborUnit` factor - Labor time unit+- `machineTime` NUMERIC(10,2) - Machine time+- `machineUnit` factor - Machine time unit+- `operationOrderType` methodOperationOrder - Order type+- `operationStatus` jobOperationStatus - Operation status+- `operationQuantity` NUMERIC(10,2) - Operation quantity+- `quantityComplete` NUMERIC(10,2) - Quantity completed+- `quantityScrapped` NUMERIC(10,2) - Quantity scrapped++#### Job Fields+- `jobId` TEXT - Job ID (internal)+- `jobReadableId` TEXT - Job readable ID (display format)+- `jobStatus` jobStatus - Job status+- `jobDueDate` DATE - Job due date+- `jobDeadlineType` deadlineType - Job deadline type+- `jobCustomerId` TEXT - **Customer ID** (reference to customer table)++#### Item Fields+- `parentMaterialId` TEXT - Parent material ID (null for top-level items)+- `itemReadableId` TEXT - **Part Number** (item's readable ID)++### Additional Fields (from usage in operations.tsx)++When used in the UI layer, the data is enriched with:+- `salesOrderReadableId` - From sales order join+- `salesOrderId` - Sales order ID+- `salesOrderLineId` - Sales order line ID+- `itemDescription` - Item description+- `thumbnailPath` - Thumbnail path++### Customer Name Resolution++The customer name is **NOT** directly returned by this function. To get the customer name, you must:+1. Use the `jobCustomerId` field+2. Join with the `customer` table using `customer.id = jobCustomerId`+3. Access the `customer.name` field++**Note:** The customer name field in the customer table is `name` (not `customerName`).++## getJobsByDateRange++### Function Signature+```typescript+getJobsByDateRange(+ client: SupabaseClient<Database>,+ locationId: string,+ startDate: string,+ endDate: string+)+```++### Database Function+Located in: `/packages/database/supabase/migrations/20251122173055_schedule-jobs.sql`++### Return Fields++The function returns a table with the following fields:++#### Job Fields+- `id` TEXT - Job ID (internal)+- `jobId` TEXT - Job readable ID (display format)+- `status` jobStatus - Job status+- `dueDate` DATE - Job due date+- `completedDate` TIMESTAMP WITH TIME ZONE - Completion date+- `deadlineType` deadlineType - Deadline type+- `quantity` NUMERIC - Job quantity+- `quantityComplete` NUMERIC - Quantity completed+- `quantityShipped` NUMERIC - Quantity shipped+- `priority` DOUBLE PRECISION - Job priority+- `assignee` TEXT - Assigned employee ID+- `tags` TEXT[] - Job tags array++#### Customer Fields+- `customerId` TEXT - Customer ID+- `customerName` TEXT - **Customer Name** (joined from customer table)++#### Sales Order Fields+- `salesOrderReadableId` TEXT - Sales order readable ID+- `salesOrderId` TEXT - Sales order ID (internal)+- `salesOrderLineId` TEXT - Sales order line ID++#### Item Fields+- `itemId` TEXT - Item ID+- `itemReadableId` TEXT - **Part Number** (item's readable ID)+- `itemDescription` TEXT - Item description/name++#### Media Fields+- `thumbnailPath` TEXT - Thumbnail path (from model upload or item)++#### Operation Statistics+- `operationCount` INTEGER - Total number of operations for this job+- `completedOperationCount` INTEGER - Number of completed operations++### Customer Name Resolution++This function **DOES** return the customer name directly via a LEFT JOIN:+```sql+LEFT JOIN "customer" c ON c."id" = rj."customerId"+```+The `customerName` field contains `c.name` from the customer table.++## Key Differences++### Field Naming for Customer+- **getActiveJobOperationsByLocation**: Returns `jobCustomerId` (ID only, no name)+- **getJobsByDateRange**: Returns both `customerId` AND `customerName`++### Field Naming for Part Number+Both functions use `itemReadableId` for the part number:+- `itemReadableId` - This is the item's readable identifier with revision++### Customer Table Schema+- Customer ID field: `id`+- Customer name field: `name` (not `customerName`)++## Usage Examples++### From operations.tsx (getActiveJobOperationsByLocation)+```typescript+const operations = await getActiveJobOperationsByLocation(+ client,+ locationId,+ selectedWorkCenterIds+);++// Access fields:+operations.data?.forEach((op) => {+ const customerId = op.jobCustomerId; // Customer ID only+ const partNumber = op.itemReadableId; // Part number+ const jobNumber = op.jobReadableId; // Job number+});+```++### From dates.tsx (getJobsByDateRange)+```typescript+const jobs = await getJobsByDateRange(+ client,+ locationId,+ startDate,+ endDate+);++// Access fields:+jobs.data?.forEach((job) => {+ const customerId = job.customerId; // Customer ID+ const customerName = job.customerName; // Customer name (directly available!)+ const partNumber = job.itemReadableId; // Part number+ const jobNumber = job.jobId; // Job number+ const partDescription = job.itemDescription; // Part description+});+```++## Summary++| Field Type | getActiveJobOperationsByLocation | getJobsByDateRange |+|-----------|----------------------------------|-------------------|+| Customer ID | `jobCustomerId` | `customerId` |+| Customer Name | Not included (must join) | `customerName` ✓ |+| Part Number | `itemReadableId` | `itemReadableId` |+| Part Description | Not included | `itemDescription` ✓ |+| Job Number | `jobReadableId` | `jobId` |diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex ce566b9f26..2db23d6eca 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -43184,14 +43184,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -45703,14 +45703,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -48819,6 +48819,7 @@ export type Database = {Args: { location_id: string; work_center_ids: string[] }Returns: {assignee: string+ customerName: stringdescription: stringid: stringitemDescription: stringdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex e6c912345f..94a86d2c73 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -48814,16 +48814,14 @@ export type Database = {get_active_job_operations_by_location: {Args: { location_id: string; work_center_ids: string[] }Returns: {- assignee: string+ customerName: stringdescription: stringid: string- itemDescription: stringitemReadableId: stringjobCustomerId: stringjobDeadlineType: Database["public"]["Enums"]["deadlineType"]jobDueDate: stringjobId: string- jobMakeMethodId: stringjobReadableId: stringjobStatus: Database["public"]["Enums"]["jobStatus"]laborTime: number@@ -48839,13 +48837,8 @@ export type Database = {processId: stringquantityComplete: numberquantityScrapped: number- salesOrderId: string- salesOrderLineId: string- salesOrderReadableId: stringsetupTime: numbersetupUnit: Database["public"]["Enums"]["factor"]- tags: string[]- thumbnailPath: stringworkCenterId: string}[]}diff --git a/packages/database/supabase/migrations/20251123000000_add-customer-name-to-operations.sql b/packages/database/supabase/migrations/20251123000000_add-customer-name-to-operations.sqlnew file mode 100644index 0000000000..92d52eff62--- /dev/null+++ b/packages/database/supabase/migrations/20251123000000_add-customer-name-to-operations.sql@@ -0,0 +1,105 @@++-- Add customerName to get_active_job_operations_by_location function+DROP FUNCTION IF EXISTS get_active_job_operations_by_location;+CREATE OR REPLACE FUNCTION get_active_job_operations_by_location(+ location_id TEXT,+ work_center_ids TEXT[]+)+RETURNS TABLE (+ "id" TEXT,+ "jobId" TEXT,+ "jobMakeMethodId" TEXT,+ "operationOrder" DOUBLE PRECISION,+ "priority" DOUBLE PRECISION,+ "processId" TEXT,+ "workCenterId" TEXT,+ "description" TEXT,+ "setupTime" NUMERIC(10,2),+ "setupUnit" factor,+ "laborTime" NUMERIC(10,2),+ "laborUnit" factor,+ "machineTime" NUMERIC(10,2),+ "machineUnit" factor,+ "operationOrderType" "methodOperationOrder",+ "jobReadableId" TEXT,+ "jobStatus" "jobStatus",+ "jobDueDate" DATE,+ "jobDeadlineType" "deadlineType",+ "jobCustomerId" TEXT,+ "customerName" TEXT,+ "parentMaterialId" TEXT,+ "itemReadableId" TEXT,+ "itemDescription" TEXT,+ "operationStatus" "jobOperationStatus",+ "operationQuantity" NUMERIC(10,2),+ "quantityComplete" NUMERIC(10,2),+ "quantityScrapped" NUMERIC(10,2),+ "salesOrderId" TEXT,+ "salesOrderLineId" TEXT,+ "salesOrderReadableId" TEXT,+ "assignee" TEXT,+ "tags" TEXT[],+ "thumbnailPath" TEXT+)+SECURITY INVOKER+AS $$+BEGIN+ RETURN QUERY+ WITH relevant_jobs AS (+ SELECT *+ FROM "job"+ WHERE "locationId" = location_id+ AND ("status" = 'Ready' OR "status" = 'In Progress' OR "status" = 'Paused')+ )+ SELECT+ jo."id",+ jo."jobId",+ jo."jobMakeMethodId",+ jo."order" AS "operationOrder",+ jo."priority",+ jo."processId",+ jo."workCenterId",+ jo."description",+ jo."setupTime",+ jo."setupUnit",+ jo."laborTime",+ jo."laborUnit",+ jo."machineTime",+ jo."machineUnit",+ jo."operationOrder" AS "operationOrderType",+ rj."jobId" AS "jobReadableId",+ rj."status" AS "jobStatus",+ rj."dueDate" AS "jobDueDate",+ rj."deadlineType" AS "jobDeadlineType",+ rj."customerId" AS "jobCustomerId",+ c."name" AS "customerName",+ jmm."parentMaterialId",+ i."readableId" as "itemReadableId",+ i."name" as "itemDescription",+ CASE+ WHEN rj."status" = 'Paused' THEN 'Paused'+ ELSE jo."status"+ END AS "operationStatus",+ jo."operationQuantity",+ jo."quantityComplete",+ jo."quantityScrapped",+ rj."salesOrderId",+ rj."salesOrderLineId",+ so."readableId" as "salesOrderReadableId",+ jo."assignee",+ jo."tags",+ COALESCE(mu."thumbnailPath", i."thumbnailPath") as "thumbnailPath"+ FROM "jobOperation" jo+ JOIN relevant_jobs rj ON rj.id = jo."jobId"+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id+ LEFT JOIN "item" i ON jmm."itemId" = i.id+ LEFT JOIN "customer" c ON rj."customerId" = c.id+ LEFT JOIN "salesOrder" so ON rj."salesOrderId" = so.id+ LEFT JOIN "modelUpload" mu ON i."modelUploadId" = mu.id+ WHERE CASE+ WHEN array_length(work_center_ids, 1) > 0 THEN jo."workCenterId" = ANY(work_center_ids)+ ELSE TRUE+ END+ ORDER BY jo."priority";+END;+$$ LANGUAGE plpgsql;