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.

fix(sales): stop phantom "Shipped" badge on non-service lines + dark-mode palette tune (#1295)

Brad Barbin2049209141c5
diff --git a/.ai/plans/2026-07-31-service-only-completion-fulfillment.md b/.ai/plans/2026-07-31-service-only-completion-fulfillment.md
new file mode 100644
index 0000000000..f6ce871897
--- /dev/null
+++ b/.ai/plans/2026-07-31-service-only-completion-fulfillment.md
@@ -0,0 +1,34 @@
+# Fix: SO line marked "Shipped" with no shipment (Non-Inventory Parts)
+
+## Problem
+Sales order line PRT-103771.A (S000328) shows a green **SHIPPED** badge, but no
+shipment exists and `job.quantityShipped = 0/3`. The badge is data-driven:
+`getSalesOrderJobStatus` (`packages/utils/src/status.ts:145`) shows "Shipped" when
+`isCompleted && line.sentComplete`. So `salesOrderLine.sentComplete = true` with no shipment.
+
+## Root cause
+Two code paths disagree on what "never ships" means:
+- **Shipment creation** (`create` edge fn, `functions/create/index.ts:2027`) skips only
+ `salesOrderLineType === "Service"` — a Non-Inventory **Part** DOES get a shipment line and ships normally.
+- **Job completion** (`complete_job_to_inventory`, newest def
+ `20260727031247_inspection-production-links.sql:262`) fulfills the SO line
+ (`sentComplete/quantitySent/sentDate`) for **every** `itemTrackingType = 'Non-Inventory'` item.
+
+`itemTrackingType = 'Non-Inventory'` ⊋ `type = 'Service'`. A Non-Inventory Part is
+Non-Inventory-tracked but has `salesOrderLineType = 'Part'`, so it ships — yet completion
+auto-marks it fulfilled. Same flaw in `recompute_service_line_fulfillment`
+(`20260723132843`).
+
+## Fix (one migration, fix-forward — prior migrations are on main)
+1. `complete_job_to_inventory` — narrow the SO-line fulfillment guard from
+ `itemTrackingType = 'Non-Inventory'` to also require `salesOrderLineType = 'Service'`.
+ (Only the fulfillment block; the other Non-Inventory guards — inventory/COGS skips — are correct and untouched.)
+2. `recompute_service_line_fulfillment` — same narrowing (keeps reopen recompute consistent).
+3. Data repair: reset `quantitySent=0, sentComplete=false, sentDate=NULL` on lines that were
+ erroneously auto-fulfilled — Non-Inventory, non-Service, `sentComplete=true`, have a
+ Completed/Closed job, and have NO shipmentLine with `shippedQuantity > 0`. Idempotent.
+
+## Verification
+- `pnpm exec turbo run typecheck --filter=@carbon/database` (no type surface change; sanity).
+- Confirm the affected production row via the diagnostic query once DB reachable.
+- Genuine Service Make-to-Order lines still fulfill on completion (guard still matches them).
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.shipment.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.shipment.tsx
index b5da6f13f5..667660d9bf 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.shipment.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.shipment.tsx
@@ -45,6 +45,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ if (!salesOrderLine.data.locationId) {
+ throw redirect(
+ path.to.salesOrderLine(orderId, lineId),
+ await flash(
+ request,
+ error(
+ null,
+ "Set a location on this sales order line before creating a shipment"
+ )
+ )
+ );
+ }
+
const salesOrderShipment = await serviceRole.functions.invoke<{
id: string;
}>("create", {
diff --git a/apps/erp/app/routes/x+/shipment+/new.tsx b/apps/erp/app/routes/x+/shipment+/new.tsx
index facb536095..d82f89474a 100644
--- a/apps/erp/app/routes/x+/shipment+/new.tsx
+++ b/apps/erp/app/routes/x+/shipment+/new.tsx
@@ -34,6 +34,18 @@ export async function action({ request }: ActionFunctionArgs) {
switch (sourceDocument) {
case "Sales Order":
+ if (!defaults.data?.locationId) {
+ throw redirect(
+ path.to.salesOrder(sourceDocumentId),
+ await flash(
+ request,
+ error(
+ null,
+ "Set a default location in your settings before creating a shipment"
+ )
+ )
+ );
+ }
const salesOrderShipment = await serviceRole.functions.invoke<{
id: string;
}>("create", {
@@ -67,6 +79,18 @@ export async function action({ request }: ActionFunctionArgs) {
throw redirect(path.to.shipmentDetails(salesOrderShipment.data.id));
case "Purchase Order":
+ if (!defaults.data?.locationId) {
+ throw redirect(
+ path.to.purchaseOrder(sourceDocumentId),
+ await flash(
+ request,
+ error(
+ null,
+ "Set a default location in your settings before creating a shipment"
+ )
+ )
+ );
+ }
const purchaseOrderShipment = await serviceRole.functions.invoke<{
id: string;
}>("create", {
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 87e89d698a..05a653b871 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -100190,7 +100190,7 @@ export default {
properties: {
id: {
description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string"
},
@@ -100239,7 +100239,7 @@ export default {
},
supplierLocationId: {
description:
- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string"
},
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 4df16bf76e..6fe6e945e0 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -64772,14 +64772,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.ts
index a55990cad2..f29fb09429 100644
--- a/packages/database/supabase/functions/create/index.ts
+++ b/packages/database/supabase/functions/create/index.ts
@@ -11,6 +11,34 @@ import { getNextSequence } from "../shared/get-next-sequence.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
+// Resolves a fallback location when a caller omits locationId, so creating a
+// blank shipment degrades gracefully instead of failing payload validation.
+// Prefers the creating user's assigned employeeJob location, then the company's
+// earliest-created location. Only safe where locationId does not scope which
+// source-document lines are shipped (i.e. shipmentDefault).
+async function getFallbackLocationId(
+ client: Awaited<ReturnType<typeof requirePermissions>>,
+ companyId: string,
+ userId: string,
+): Promise<string | null> {
+ const employeeJob = await client
+ .from("employeeJob")
+ .select("locationId")
+ .eq("id", userId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (employeeJob.data?.locationId) return employeeJob.data.locationId;
+
+ const location = await client
+ .from("location")
+ .select("id")
+ .eq("companyId", companyId)
+ .order("createdAt", { ascending: true })
+ .limit(1)
+ .maybeSingle();
+ return location.data?.id ?? null;
+}
+
const payloadValidator = z.discriminatedUnion("type", [
z.object({
type: z.literal("nonConformanceTasks"),
@@ -64,7 +92,7 @@ const payloadValidator = z.discriminatedUnion("type", [
}),
z.object({
type: z.literal("shipmentDefault"),
- locationId: z.string(),
+ locationId: z.string().optional(),
companyId: z.string(),
userId: z.string(),
}),
@@ -1474,6 +1502,9 @@ serve(async (req: Request) => {
userId,
});
try {
+ const effectiveLocationId =
+ locationId ?? (await getFallbackLocationId(client, companyId, userId));
+
await db.transaction().execute(async (trx) => {
createdDocumentId = await getNextSequence(trx, "shipment", companyId);
@@ -1482,7 +1513,7 @@ serve(async (req: Request) => {
.values({
shipmentId: createdDocumentId,
companyId: companyId,
- locationId: locationId,
+ locationId: effectiveLocationId,
createdBy: userId,
})
.returning(["id", "shipmentId"])
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 4df16bf76e..6fe6e945e0 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -64772,14 +64772,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
diff --git a/packages/database/supabase/migrations/20260731164213_service-only-completion-fulfillment.sql b/packages/database/supabase/migrations/20260731164213_service-only-completion-fulfillment.sql
new file mode 100644
index 0000000000..bed1993744
--- /dev/null
+++ b/packages/database/supabase/migrations/20260731164213_service-only-completion-fulfillment.sql
@@ -0,0 +1,870 @@
+-- =============================================================================
+-- Fix: sales-order lines wrongly marked "Shipped" with NO shipment.
+--
+-- getSalesOrderJobStatus renders a green "Shipped" badge when the linked jobs are
+-- complete AND salesOrderLine.sentComplete = true. sentComplete was being set to
+-- true on JOB COMPLETION for every Non-Inventory item, via complete_job_to_inventory
+-- (20260727031247) and recompute_service_line_fulfillment (20260723132843). Their
+-- guard, `itemTrackingType = 'Non-Inventory'`, is too broad: it is a superset of
+-- genuine Service items. A Non-Inventory *Part* (or Material/Tool/etc.) is
+-- Non-Inventory-tracked but has salesOrderLineType <> 'Service', so the shipment
+-- pipeline (the `create` edge fn skips ONLY salesOrderLineType='Service') DOES create
+-- a shipment line for it and it ships normally — yet completion pre-marked it
+-- fulfilled, producing the phantom "Shipped" badge with quantitySent set and
+-- job.quantityShipped still 0.
+--
+-- Fix: only genuine Service lines (salesOrderLineType = 'Service') fulfill by
+-- completion — matching the shipment-creation gate. Everything else fulfills via
+-- post-shipment. Plus an idempotent data repair that rebuilds each affected
+-- line's fulfillment from its POSTED shipments (covering both no-shipment and
+-- partially-shipped lines the old behaviour corrupted).
+--
+-- CREATE OR REPLACE preserves each function's signature/OID, so attached event
+-- triggers (attach_event_trigger('job', ...)) keep pointing at them — no re-wiring.
+-- =============================================================================
+
+
+-- -----------------------------------------------------------------------------
+-- (1) complete_job_to_inventory — forked verbatim from 20260727031247 with ONLY
+-- the SO-line fulfillment guard narrowed to genuine Service lines. All other
+-- Non-Inventory branches (inventory/COGS skips) are unchanged and correct.
+-- -----------------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION complete_job_to_inventory(
+ p_job_id TEXT,
+ p_quantity_complete NUMERIC,
+ p_storage_unit_id TEXT DEFAULT NULL,
+ p_location_id TEXT DEFAULT NULL,
+ p_company_id TEXT DEFAULT NULL,
+ p_user_id TEXT DEFAULT NULL
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_item_id TEXT;
+ v_item_tracking_type "itemTrackingType";
+ v_cogs_account TEXT;
+ v_sales_order_line_id TEXT;
+ v_line_quantity_complete NUMERIC;
+ v_job_company_id TEXT;
+ v_prior_quantity_received NUMERIC;
+ v_quantity_received_to_inventory NUMERIC;
+ v_job_id_readable TEXT;
+ v_job_make_method RECORD;
+ v_tracked_entity RECORD;
+ v_accounting_enabled BOOLEAN;
+ v_company_group_id TEXT;
+ v_raw_materials_account TEXT;
+ v_finished_goods_account TEXT;
+ v_item_inventory_account TEXT;
+ v_item_inventory_description TEXT;
+ v_wip_account TEXT;
+ v_labor_absorption_account TEXT;
+ v_overhead_absorption_account TEXT;
+ v_dimension_item_posting_group TEXT;
+ v_dimension_item TEXT;
+ v_dimension_location TEXT;
+ v_dimension_cost_center TEXT;
+ v_dimension_employee TEXT;
+ v_event RECORD;
+ v_duration_hours NUMERIC;
+ v_rate NUMERIC;
+ v_labor_cost NUMERIC;
+ v_overhead_cost NUMERIC;
+ v_event_reference TEXT;
+ v_labor_journal_line_reference TEXT;
+ v_labor_accounting_period_id TEXT;
+ v_labor_journal_entry_id TEXT;
+ v_labor_journal_id TEXT;
+ v_labor_jl_id TEXT;
+ v_accumulated_wip_cost NUMERIC;
+ v_today DATE;
+ v_journal_line_reference TEXT;
+ v_accounting_period_id TEXT;
+ v_journal_entry_id TEXT;
+ v_journal_id TEXT;
+ v_jl_ids TEXT[];
+ v_new_per_unit_cost NUMERIC;
+ v_costing_method TEXT;
+ v_existing_unit_cost NUMERIC;
+ v_item_posting_group_id TEXT;
+ v_job_location_id TEXT;
+ v_total_qty_on_hand NUMERIC;
+ v_prior_qty NUMERIC;
+ v_prior_value NUMERIC;
+ v_new_unit_cost NUMERIC;
+BEGIN
+ -- Never let a NULL user reach NOT NULL audit columns; fall back to the job creator
+ p_user_id := COALESCE(p_user_id, (SELECT "createdBy" FROM "job" WHERE id = p_job_id));
+
+ -- Fetch job details
+ SELECT "itemId", "quantityReceivedToInventory", "jobId", "locationId", "salesOrderLineId", "companyId"
+ INTO STRICT v_item_id, v_prior_quantity_received, v_job_id_readable, v_job_location_id, v_sales_order_line_id, v_job_company_id
+ FROM "job"
+ WHERE id = p_job_id;
+
+ -- SECURITY DEFINER bypasses RLS: bind the call to the job's own company so a
+ -- caller can never complete another tenant's job or post into a mismatched
+ -- company's ledger/journal.
+ IF p_company_id IS NULL OR v_job_company_id IS DISTINCT FROM p_company_id THEN
+ RAISE EXCEPTION 'Job % does not belong to company %', p_job_id, COALESCE(p_company_id, '<null>');
+ END IF;
+
+ -- Non-Inventory items (services) never enter inventory
+ SELECT "itemTrackingType"
+ INTO v_item_tracking_type
+ FROM "item"
+ WHERE id = v_item_id
+ AND "companyId" = p_company_id;
+
+ -- Delta for this completion: drives the itemLedger/costLedger quantities and
+ -- the WIP-discharge journal. The job column itself stores the CUMULATIVE
+ -- quantity (get_inventory_quantities computes on-production supply as
+ -- production + scrap - received - shipped, which requires cumulative).
+ v_quantity_received_to_inventory := p_quantity_complete - COALESCE(v_prior_quantity_received, 0);
+
+ -- Fetch jobMakeMethod for the top-level (no parentMaterialId)
+ SELECT *
+ INTO STRICT v_job_make_method
+ FROM "jobMakeMethod"
+ WHERE "jobId" = p_job_id
+ AND "parentMaterialId" IS NULL;
+
+ -- Update job status. quantityReceivedToInventory is CUMULATIVE (not the
+ -- delta): re-completions previously overwrote it with the delta, corrupting
+ -- get_inventory_quantities' on-production supply math. Non-Inventory items
+ -- never receive to inventory, so their value is left unchanged.
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = p_quantity_complete,
+ "quantityReceivedToInventory" = CASE
+ WHEN v_item_tracking_type = 'Non-Inventory' THEN v_prior_quantity_received
+ ELSE p_quantity_complete
+ END,
+ "updatedAt" = NOW(),
+ "updatedBy" = p_user_id
+ WHERE id = p_job_id;
+
+ -- Services never ship, so job completion is the fulfillment event: advance
+ -- the linked sales-order line the way post-shipment does for physical lines.
+ -- Lives HERE (not in app code) because completion has multiple entry points —
+ -- the ERP complete route AND the sync_finish_job_operation interceptor that
+ -- auto-completes when the last operation finishes. Recomputed from ALL jobs
+ -- on the line, so it is idempotent and lot-split safe. Runs before the
+ -- accounting-enabled / zero-WIP early returns.
+ -- NARROWED: only genuine Service lines (salesOrderLineType = 'Service') fulfill
+ -- by completion. They never receive a shipment line (the `create` edge fn skips
+ -- salesOrderLineType='Service'), so completion is their only fulfillment event.
+ -- A Non-Inventory *Part* (or Material/Tool/etc.) still ships via post-shipment and
+ -- must NOT be auto-fulfilled here — that was marking SO lines "Shipped" with no shipment.
+ IF v_item_tracking_type = 'Non-Inventory' AND v_sales_order_line_id IS NOT NULL
+ AND EXISTS (
+ SELECT 1 FROM "salesOrderLine" sol
+ WHERE sol.id = v_sales_order_line_id
+ AND sol."companyId" = p_company_id
+ AND sol."salesOrderLineType" = 'Service'
+ ) THEN
+ SELECT COALESCE(SUM("quantityComplete"), 0)
+ INTO v_line_quantity_complete
+ FROM "job"
+ WHERE "salesOrderLineId" = v_sales_order_line_id
+ AND "companyId" = p_company_id
+ AND status != 'Cancelled';
+
+ UPDATE "salesOrderLine" sol
+ SET "quantitySent" = v_line_quantity_complete,
+ "sentComplete" = (COALESCE(sol."saleQuantity", 0) > 0 AND v_line_quantity_complete >= sol."saleQuantity"),
+ "sentDate" = CASE
+ WHEN COALESCE(sol."saleQuantity", 0) > 0
+ AND v_line_quantity_complete >= sol."saleQuantity"
+ AND sol."sentDate" IS NULL
+ THEN CURRENT_DATE
+ ELSE sol."sentDate"
+ END,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE sol.id = v_sales_order_line_id
+ AND sol."companyId" = p_company_id;
+ END IF;
+
+ -- Insert itemLedger entries based on tracking type.
+ -- Non-Inventory items (services) never enter inventory.
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ IF v_job_make_method."requiresBatchTracking" THEN
+ SELECT *
+ INTO v_tracked_entity
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed'
+ ORDER BY "createdAt" DESC
+ LIMIT 1;
+
+ IF v_tracked_entity.id IS NULL THEN
+ RAISE EXCEPTION 'Tracked entity not found';
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+
+ ELSIF v_job_make_method."requiresSerialTracking" THEN
+ FOR v_tracked_entity IN
+ SELECT *
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ -- Rejected units (scrapped at inspection) must not be received.
+ AND status NOT IN ('Consumed', 'Rejected')
+ LOOP
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, 1, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+ END LOOP;
+
+ UPDATE "trackedEntity"
+ SET status = 'Available'
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ -- Rejected units (scrapped at inspection) stay Rejected, out of stock.
+ AND status NOT IN ('Consumed', 'Rejected');
+
+ ELSE
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ p_user_id
+ );
+ END IF;
+ END IF;
+
+ -- Update pickMethod defaultStorageUnitId if needed
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' AND p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN
+ IF NOT EXISTS (
+ SELECT 1 FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id
+ AND "storageUnitId" IS NOT NULL
+ AND "storageUnitId" != p_storage_unit_id
+ LIMIT 1
+ ) THEN
+ IF EXISTS (
+ SELECT 1 FROM "pickMethod"
+ WHERE "itemId" = v_item_id AND "locationId" = p_location_id
+ ) THEN
+ UPDATE "pickMethod"
+ SET "defaultStorageUnitId" = p_storage_unit_id,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id;
+ ELSE
+ INSERT INTO "pickMethod" (
+ "itemId", "locationId", "defaultStorageUnitId",
+ "companyId", "createdBy", "createdAt"
+ ) VALUES (
+ v_item_id, p_location_id, p_storage_unit_id,
+ p_company_id, p_user_id, NOW()
+ );
+ END IF;
+ END IF;
+ END IF;
+
+ -- Backflush unissued materials (delegated to shared function)
+ PERFORM backflush_job_materials(p_job_id, p_quantity_complete, p_company_id, p_user_id);
+
+ -- Check if accounting is enabled
+ SELECT "accountingEnabled"
+ INTO v_accounting_enabled
+ FROM "companySettings"
+ WHERE id = p_company_id;
+
+ v_accounting_enabled := COALESCE(v_accounting_enabled, false);
+
+ IF NOT v_accounting_enabled THEN
+ RETURN;
+ END IF;
+
+ -- Fetch company group
+ SELECT "companyGroupId"
+ INTO STRICT v_company_group_id
+ FROM company
+ WHERE id = p_company_id;
+
+ -- Fetch account defaults
+ SELECT "rawMaterialsAccount", "finishedGoodsAccount", "workInProgressAccount", "laborAbsorptionAccount", "overheadAbsorptionAccount", "costOfGoodsSoldAccount"
+ INTO STRICT v_raw_materials_account, v_finished_goods_account, v_wip_account, v_labor_absorption_account, v_overhead_absorption_account, v_cogs_account
+ FROM "accountDefault"
+ WHERE "companyId" = p_company_id;
+
+ -- Resolve Raw Materials vs Finished Goods from the produced item:
+ -- Buy → Raw Materials; Make / Buy and Make → Finished Goods.
+ SELECT
+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN v_raw_materials_account ELSE v_finished_goods_account END,
+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN 'Raw Materials Account' ELSE 'Finished Goods Account' END
+ INTO v_item_inventory_account, v_item_inventory_description
+ FROM "item" i
+ WHERE i."id" = v_item_id
+ AND i."companyId" = p_company_id;
+
+ -- Non-Inventory (Service): the produced output is never stocked, so completion
+ -- relieves WIP straight to Cost of Goods Sold (Epicor "Make Direct" pattern).
+ -- >>> REV-REC SEAM (spec .ai/specs/2026-07-04-revenue-recognition.md, issue #1048):
+ -- when revenue recognition lands, Percent-of-Completion elements will gate THIS
+ -- branch off and post COGS as-incurred in the recognition run instead. <<<
+ IF v_item_tracking_type = 'Non-Inventory' THEN
+ v_item_inventory_account := v_cogs_account;
+ v_item_inventory_description := 'Cost of Goods Sold';
+ END IF;
+
+ -- Fetch dimension IDs
+ SELECT
+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),
+ MAX(CASE WHEN "entityType" = 'Location' THEN id END),
+ MAX(CASE WHEN "entityType" = 'CostCenter' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Employee' THEN id END)
+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location,
+ v_dimension_cost_center, v_dimension_employee
+ FROM dimension
+ WHERE "companyGroupId" = v_company_group_id
+ AND active = true
+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location', 'CostCenter', 'Employee');
+
+ -- Post unposted production events as labor/machine + overhead absorption JEs
+ -- (mirrors post-production-event; this is the catch-up path for events that
+ -- were never posted individually)
+ FOR v_event IN
+ SELECT
+ pe.id,
+ pe.duration,
+ pe.type,
+ pe."employeeId",
+ wc."laborRate",
+ wc."machineRate",
+ wc."overheadRate"
+ FROM "productionEvent" pe
+ INNER JOIN "jobOperation" jo ON jo.id = pe."jobOperationId"
+ INNER JOIN "workCenter" wc ON wc.id = pe."workCenterId"
+ WHERE jo."jobId" = p_job_id
+ AND pe."endTime" IS NOT NULL
+ AND pe."postedToGL" = false
+ AND pe.duration > 0
+ LOOP
+ v_duration_hours := v_event.duration::NUMERIC / 3600;
+ v_rate := CASE
+ WHEN v_event.type = 'Machine' THEN COALESCE(v_event."machineRate", 0)
+ ELSE COALESCE(v_event."laborRate", 0)
+ END;
+ v_labor_cost := v_duration_hours * v_rate;
+ v_overhead_cost := v_duration_hours * COALESCE(v_event."overheadRate", 0);
+ v_event_reference := 'production-event:' || v_event.id;
+
+ IF (v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL)
+ OR (v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL) THEN
+ v_labor_journal_line_reference := nanoid();
+
+ -- Get current accounting period
+ SELECT id INTO v_labor_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ RETURNING id INTO v_labor_accounting_period_id;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', CURRENT_DATE)::DATE,
+ (date_trunc('month', CURRENT_DATE) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_labor_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_labor_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_labor_journal_entry_id, v_labor_accounting_period_id,
+ v_event.type || ' Time — Job ' || v_job_id_readable,
+ CURRENT_DATE, p_company_id, 'Production Event', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_labor_journal_id;
+
+ IF v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL THEN
+ -- DR WIP (labor/machine)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account',
+ v_labor_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on WIP line (the finished good this labor rolls into)
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ -- CR Labor/Machine Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_labor_absorption_account, 'Labor/Machine Absorption',
+ -v_labor_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on absorption line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+ END IF;
+
+ IF v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL THEN
+ -- DR WIP (overhead)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account (Overhead)',
+ v_overhead_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP overhead line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on WIP overhead line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ -- CR Overhead Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_overhead_absorption_account, 'Overhead Absorption',
+ -v_overhead_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on overhead absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on overhead absorption line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+ END IF;
+ END IF;
+
+ UPDATE "productionEvent"
+ SET "postedToGL" = true
+ WHERE id = v_event.id;
+ END LOOP;
+
+ -- Calculate accumulated WIP cost for this job
+ SELECT COALESCE(ABS(SUM(jl.amount)), 0)
+ INTO v_accumulated_wip_cost
+ FROM "journalLine" jl
+ INNER JOIN journal j ON j.id = jl."journalId"
+ WHERE jl."accountId" = v_wip_account
+ AND jl."documentId" = p_job_id
+ AND j."companyId" = p_company_id;
+
+ IF v_accumulated_wip_cost <= 0 THEN
+ RETURN;
+ END IF;
+
+ v_today := CURRENT_DATE;
+ v_journal_line_reference := nanoid();
+
+ -- Get accounting period for WIP discharge
+ SELECT id INTO v_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ RETURNING id INTO v_accounting_period_id;
+
+ IF v_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', v_today)::DATE,
+ (date_trunc('month', v_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_journal_entry_id, v_accounting_period_id,
+ 'Job Completion ' || v_job_id_readable,
+ v_today, p_company_id, 'Job Receipt', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_journal_id;
+
+ -- DR Inventory (Raw Materials or Finished Goods by item)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_item_inventory_account, v_item_inventory_description,
+ v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := ARRAY[v_labor_jl_id];
+
+ -- CR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_wip_account, 'WIP Account',
+ -v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := v_jl_ids || v_labor_jl_id;
+
+ -- Write costLedger entry for finished good (skipped for Non-Inventory: no
+ -- output layer exists for a service — its cost went straight to COGS above)
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ INSERT INTO "costLedger" (
+ "itemLedgerType", "costLedgerType", adjustment,
+ "documentType", "documentId", "itemId",
+ quantity, cost, "remainingQuantity", "companyId"
+ ) VALUES (
+ 'Output', 'Direct Cost', false,
+ 'Job Receipt', p_job_id, v_item_id,
+ v_quantity_received_to_inventory, v_accumulated_wip_cost,
+ v_quantity_received_to_inventory, p_company_id
+ );
+ END IF;
+
+ -- Update item cost
+ SELECT "costingMethod", "unitCost", "itemPostingGroupId"
+ INTO v_costing_method, v_existing_unit_cost, v_item_posting_group_id
+ FROM "itemCost"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ -- Update itemCost.unitCost (skipped for Non-Inventory: a service has no
+ -- stocked unit cost; the read above still feeds the dimension inserts below)
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ v_new_per_unit_cost := v_accumulated_wip_cost / v_quantity_received_to_inventory;
+
+ IF v_costing_method = 'Average' THEN
+ SELECT COALESCE(SUM(quantity), 0)
+ INTO v_total_qty_on_hand
+ FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ v_prior_qty := v_total_qty_on_hand - v_quantity_received_to_inventory;
+ v_prior_value := v_prior_qty * COALESCE(v_existing_unit_cost, 0);
+
+ IF v_total_qty_on_hand > 0 THEN
+ v_new_unit_cost := (v_prior_value + v_accumulated_wip_cost) / v_total_qty_on_hand;
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ ELSIF v_costing_method IN ('FIFO', 'LIFO') THEN
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_per_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+ END IF;
+
+ -- Insert dimensions on WIP discharge journal lines
+ IF v_jl_ids IS NOT NULL AND array_length(v_jl_ids, 1) > 0 THEN
+ FOR i IN 1..array_length(v_jl_ids, 1)
+ LOOP
+ IF v_item_posting_group_id IS NOT NULL AND v_dimension_item_posting_group IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item_posting_group, v_item_posting_group_id, p_company_id
+ );
+ END IF;
+
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id
+ );
+ END IF;
+ END LOOP;
+ END IF;
+END;
+$$;
+
+
+
+-- -----------------------------------------------------------------------------
+-- (2) recompute_service_line_fulfillment — forked from 20260723132843, guard
+-- narrowed the same way so reopening/cancelling a job only recomputes genuine
+-- Service lines (a Non-Inventory Part's shipment-driven fulfillment is never
+-- clobbered by job status changes).
+-- -----------------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION recompute_service_line_fulfillment(
+ p_sales_order_line_id TEXT,
+ p_company_id TEXT,
+ p_user_id TEXT
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_item_tracking_type "itemTrackingType";
+ v_line_type "salesOrderLineType";
+ v_fulfilled NUMERIC;
+BEGIN
+ IF p_sales_order_line_id IS NULL OR p_company_id IS NULL THEN
+ RETURN;
+ END IF;
+
+ -- Only genuine Service lines fulfill by completion (kept in sync with
+ -- complete_job_to_inventory). A Non-Inventory Part ships via post-shipment.
+ SELECT i."itemTrackingType", sol."salesOrderLineType"
+ INTO v_item_tracking_type, v_line_type
+ FROM "salesOrderLine" sol
+ JOIN "item" i ON i.id = sol."itemId" AND i."companyId" = sol."companyId"
+ WHERE sol.id = p_sales_order_line_id
+ AND sol."companyId" = p_company_id;
+
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'
+ OR v_line_type IS DISTINCT FROM 'Service' THEN
+ RETURN;
+ END IF;
+
+ -- Fulfilled quantity = sum over this line's jobs that are actually completed.
+ SELECT COALESCE(SUM("quantityComplete"), 0)
+ INTO v_fulfilled
+ FROM "job"
+ WHERE "salesOrderLineId" = p_sales_order_line_id
+ AND "companyId" = p_company_id
+ AND status IN ('Completed', 'Closed');
+
+ UPDATE "salesOrderLine" sol
+ SET "quantitySent" = v_fulfilled,
+ "sentComplete" = (COALESCE(sol."saleQuantity", 0) > 0 AND v_fulfilled >= sol."saleQuantity"),
+ "sentDate" = CASE
+ WHEN COALESCE(sol."saleQuantity", 0) > 0 AND v_fulfilled >= sol."saleQuantity"
+ THEN COALESCE(sol."sentDate", CURRENT_DATE)
+ ELSE NULL
+ END,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE sol.id = p_sales_order_line_id
+ AND sol."companyId" = p_company_id;
+END;
+$$;
+
+
+-- -----------------------------------------------------------------------------
+-- (3) Data repair — rebuild fulfillment from real shipments for every line the
+-- old completion logic could have corrupted. For a non-Service line,
+-- quantitySent must reflect ONLY posted shipments (post-shipment increments
+-- it by each posted shipmentLine.shippedQuantity; completion should never
+-- have touched it). So recompute quantitySent = SUM of shippedQuantity over
+-- POSTED shipments and re-derive sentComplete/sentDate from it.
+--
+-- Corruption signature (the exact class the old guard over-matched):
+-- * item is Non-Inventory AND the line is NOT a Service line,
+-- * the line has a Completed/Closed job (what triggered the bad fulfill).
+-- Both the no-shipment phantom "Shipped" (posted sum = 0 → reset) and the
+-- partially-shipped-but-inflated case (posted sum < saleQuantity → drops
+-- sentComplete, keeps the true shipped qty) collapse into this one rule.
+-- Only POSTED shipments count — a Draft/Pending shipmentLine carries an
+-- editable shippedQuantity that has not yet advanced quantitySent, so it
+-- must be excluded. Idempotent: it is a no-op for never-corrupted lines
+-- (their quantitySent already equals the posted sum). Fixed Asset lines are
+-- excluded (no itemId join / no job).
+-- -----------------------------------------------------------------------------
+UPDATE "salesOrderLine" sol
+SET "quantitySent" = fix."postedQty",
+ "sentComplete" = (
+ COALESCE(fix."saleQuantity", 0) > 0
+ AND fix."postedQty" >= fix."saleQuantity"
+ ),
+ "sentDate" = CASE
+ WHEN COALESCE(fix."saleQuantity", 0) > 0
+ AND fix."postedQty" >= fix."saleQuantity"
+ THEN COALESCE(fix."sentDate", CURRENT_DATE)
+ ELSE NULL
+ END,
+ "updatedAt" = NOW()
+FROM (
+ SELECT
+ sol2."id" AS "lineId",
+ sol2."companyId" AS "companyId",
+ sol2."saleQuantity" AS "saleQuantity",
+ sol2."sentDate" AS "sentDate",
+ COALESCE(ps."qty", 0) AS "postedQty"
+ FROM "salesOrderLine" sol2
+ JOIN "item" i
+ ON i."id" = sol2."itemId"
+ AND i."companyId" = sol2."companyId"
+ LEFT JOIN (
+ SELECT sl."lineId", sl."companyId", SUM(sl."shippedQuantity") AS "qty"
+ FROM "shipmentLine" sl
+ JOIN "shipment" s ON s."id" = sl."shipmentId"
+ WHERE s."status" = 'Posted'
+ AND sl."lineId" IS NOT NULL
+ GROUP BY sl."lineId", sl."companyId"
+ ) ps
+ ON ps."lineId" = sol2."id"
+ AND ps."companyId" = sol2."companyId"
+ WHERE i."itemTrackingType" = 'Non-Inventory'
+ AND sol2."salesOrderLineType" IS DISTINCT FROM 'Service'
+ AND EXISTS (
+ SELECT 1 FROM "job" j
+ WHERE j."salesOrderLineId" = sol2."id"
+ AND j."companyId" = sol2."companyId"
+ AND j."status" IN ('Completed', 'Closed')
+ )
+) fix
+WHERE sol."id" = fix."lineId"
+ AND sol."companyId" = fix."companyId";
diff --git a/packages/utils/src/themes.ts b/packages/utils/src/themes.ts
index f6217b9063..b4badb9da3 100644
--- a/packages/utils/src/themes.ts
+++ b/packages/utils/src/themes.ts
@@ -36,9 +36,9 @@ export const themes = [
},
dark: {
// Vercel/Geist-inspired dark mode - pure black base
- background: "0 0% 0%",
+ background: "0 14.3% 6.1%",
foreground: "0 0% 93%",
- card: "0 0% 4%",
+ card: "0 10% 3.9%",
"card-foreground": "0 0% 93%",
popover: "0 0% 7%",
"popover-foreground": "0 0% 93%",
@@ -48,7 +48,7 @@ export const themes = [
"active-foreground": "0 0% 100%",
secondary: "0 0% 7%",
"secondary-foreground": "0 0% 93%",
- muted: "0 0% 15%",
+ muted: "0 0% 13.6%",
"muted-foreground": "0 0% 63%",
accent: "0 0% 10%",
"accent-foreground": "0 0% 93%",
@@ -96,9 +96,9 @@ export const themes = [
"success-foreground": "0 0% 98%"
},
dark: {
- background: "20 33% 4%",
+ background: "20 14.3% 6.1%",
foreground: "0 0% 98%",
- card: "0 0% 5%",
+ card: "0 10% 3.9%",
"card-foreground": "0 0% 98%",
popover: "0 0% 8.9%",
"popover-foreground": "0 0% 98%",
@@ -108,7 +108,7 @@ export const themes = [
"active-foreground": "0 0% 98%",
secondary: "0 0% 14.9%",
"secondary-foreground": "0 0% 98%",
- muted: "0 0% 14.9%",
+ muted: "0 0% 13.6%",
"muted-foreground": "0 0% 63.9%",
accent: "0 0% 14.9%",
"accent-foreground": "0 0% 98%",
@@ -156,9 +156,9 @@ export const themes = [
"success-foreground": "0 0% 98%"
},
dark: {
- background: "0 0% 6.9%",
+ background: "0 14.3% 6.1%",
foreground: "0 0% 98%",
- card: "0 0% 5%",
+ card: "0 10% 3.9%",
"card-foreground": "0 0% 98%",
popover: "0 0% 8.9%",
"popover-foreground": "0 0% 98%",
@@ -168,7 +168,7 @@ export const themes = [
"active-foreground": "0 80% 63%",
secondary: "0 0% 14.9%",
"secondary-foreground": "0 0% 98%",
- muted: "0 0% 14.9%",
+ muted: "0 0% 13.6%",
"muted-foreground": "0 0% 63.9%",
accent: "0 0% 14.9%",
"accent-foreground": "0 0% 98%",
@@ -216,9 +216,9 @@ export const themes = [
"success-foreground": "0 0% 98%"
},
dark: {
- background: "20 14.3% 3.1%",
+ background: "20 14.3% 6.1%",
foreground: "20 9.1% 97.8%",
- card: "20 14.3% 5%",
+ card: "20 10% 3.9%",
"card-foreground": "60 9.1% 97.8%",
popover: "20 14.3% 8.9%",
"popover-foreground": "60 9.1% 97.8%",
@@ -228,7 +228,7 @@ export const themes = [
"active-foreground": "18 80% 63%",
secondary: "12 6.5% 15.1%",
"secondary-foreground": "60 9.1% 97.8%",
- muted: "12 6.5% 15.1%",
+ muted: "12 0% 13.6%",
"muted-foreground": "24 5.4% 63.9%",
accent: "12 6.5% 15.1%",
"accent-foreground": "60 9.1% 97.8%",
@@ -276,9 +276,9 @@ export const themes = [
"success-foreground": "0 0% 98%"
},
dark: {
- background: "61 14.3% 3.1%",
+ background: "61 14.3% 6.1%",
foreground: "61 9.1% 97.8%",
- card: "61 14.3% 5%",
+ card: "61 10% 3.9%",
"card-foreground": "61 9.1% 97.8%",
popover: "61 14.3% 4.1%",
"popover-foreground": "61 9.1% 97.8%",
@@ -289,7 +289,7 @@ export const themes = [
secondary: "12 6.5% 15.1%",
"secondary-foreground": "61 9.1% 97.8%",
- muted: "12 6.5% 15.1%",
+ muted: "12 0% 13.6%",
"muted-foreground": "24 5.4% 63.9%",
accent: "12 6.5% 15.1%",
"accent-foreground": "61 9.1% 97.8%",
@@ -338,11 +338,11 @@ export const themes = [
"success-foreground": "0 0% 98%"
},
dark: {
- background: "151 14.3% 3.1%",
+ background: "151 14.3% 6.1%",
foreground: "0 0% 95%",
popover: "151 0% 9%",
"popover-foreground": "151 0% 95%",
- card: "151 0% 5%",
+ card: "151 10% 3.9%",
"card-foreground": "151 0% 95%",
primary: "171 98% 59%",
"primary-foreground": "144.9 80.4% 10%",
@@ -350,7 +350,7 @@ export const themes = [
"active-foreground": "171 98% 59%",
secondary: "151 3.7% 15.9%",
"secondary-foreground": "0 0% 98%",
- muted: "151 0% 15%",
+ muted: "151 0% 13.6%",
"muted-foreground": "151 5% 64.9%",
accent: "151 6.5% 15.1%",
"accent-foreground": "0 0% 98%",
@@ -398,11 +398,11 @@ export const themes = [
"success-foreground": "0 0% 98%"
},
dark: {
- background: "220 14.3% 3.1%",
+ background: "220 14.3% 6.1%",
foreground: "220 0% 95%",
popover: "216 0% 9%",
"popover-foreground": "220 0% 95%",
- card: "220 10% 5%",
+ card: "220 10% 3.9%",
"card-foreground": "220 10% 95%",
primary: "216 98% 52%",
"primary-foreground": "216 80.4% 100%",
@@ -410,7 +410,7 @@ export const themes = [
"active-foreground": "216 98% 58%",
secondary: "220 10% 15.9%",
"secondary-foreground": "220 0% 98%",
- muted: "220 10% 15.9%",
+ muted: "220 0% 13.6%",
"muted-foreground": "220 5% 64.9%",
accent: "220 10% 15.9%",
"accent-foreground": "0 0% 98%",
@@ -464,8 +464,8 @@ export const themes = [
"card-foreground": "210 20% 98%",
popover: "263 41.4 8.9%",
"popover-foreground": "210 20% 98%",
- primary: "327 70% 40.4%",
- "primary-foreground": "210 20% 98%",
+ primary: "171 98% 59%",
+ "primary-foreground": "144.9 80.4% 10%",
active: "327 40% 17%",
"active-foreground": "327 80% 63%",
secondary: "263 27.9% 16.9%",