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
fix: scrap percentage calculation
Brad Barbine72cedfb33c5
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 7e9930c201..51adefaa70 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -166,9 +166,7 @@ export async function convertSalesOrderLinesToJobs(// Calculate scrap quantity based on item's scrap percentageconst scrapPercentage = manufacturing.data?.scrapPercentage ?? 0;const scrapQuantity =- scrapPercentage > 0- ? Math.ceil(jobQuantity * (scrapPercentage / 100))- : 0;+ scrapPercentage > 0 ? Math.ceil(jobQuantity * scrapPercentage) : 0;const data = {customerId: salesOrder.data?.customerId ?? undefined,diff --git a/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx b/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsxindex d9f71c8cbb..1c9d169956 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx@@ -61,6 +61,7 @@ import { JobOperationStatus } from "./JobOperationStatus";type Operation = z.infer<typeof jobOperationValidator> & {status: JobOperation["status"];operationQuantity: number | null;+ targetQuantity: number | null;};type JobMaterial = NonNullable<@@ -342,7 +343,9 @@ const JobEstimatesVsActuals = ({</Td><Td className="px-2">{`${getCompleteQuantity(operation)}/${- operation.operationQuantity+ operation.targetQuantity ??+ operation.operationQuantity ??+ 0}`}</Td><Td className="px-2">{getScrapQuantity(operation)}</Td>diff --git a/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx b/apps/erp/app/modules/production/ui/Jobs/JobForm.tsxindex 52e9fcbc07..a933ebe146 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx@@ -171,7 +171,7 @@ const JobForm = ({ initialValues }: JobFormProps) => {scrapPercentage: manufacturing?.data?.scrapPercentage ?? 0,scrapQuantity: Math.ceil((manufacturing?.data?.lotSize ?? 0) *- ((manufacturing?.data?.scrapPercentage ?? 0) / 100)+ (manufacturing?.data?.scrapPercentage ?? 0))}));diff --git a/apps/erp/app/modules/production/ui/Jobs/JobOperationsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobOperationsTable.tsxindex 77a7be0132..c507e42eff 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobOperationsTable.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobOperationsTable.tsx@@ -149,9 +149,10 @@ const JobOperationsTable = memo(({ data, count }: JobOperationsTableProps) => {},{- accessorKey: "operationQuantity",+ accessorKey: "targetQuantity",header: "Quantity",- cell: (item) => item.getValue(),+ cell: (item) =>+ item.getValue<number>() ?? item.row.original.operationQuantity ?? 0,meta: {icon: <LuHash />}diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsxindex 86372aaa64..dbaebfcf64 100644--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx@@ -108,7 +108,7 @@ export function SalesOrderLineJobs({: quantityRequired;return {quantity,- scrapQuantity: Math.ceil(quantity * (scrapPercentage / 100))+ scrapQuantity: Math.ceil(quantity * scrapPercentage)};});@@ -311,13 +311,13 @@ export function SalesOrderJobItem({ job }: { job: SalesOrderJob }) {<div><label className="text-xs text-muted-foreground">Complete</label><p className="text-sm">- {job.quantityComplete ?? 0}/{job.productionQuantity ?? 0}+ {job.quantityComplete ?? 0}/{job.quantity ?? 0}</p></div><div><label className="text-xs text-muted-foreground">Shipped</label><p className="text-sm">- {job.quantityShipped ?? 0}/{job.productionQuantity ?? 0}+ {job.quantityShipped ?? 0}/{job.quantity ?? 0}</p></div></HStack>@@ -467,7 +467,9 @@ function JobDetails({ job }: { job: Job }) {<Progressvalue={Math.min(((operation.quantityComplete ?? 0) /- (operation.operationQuantity ?? 0)) *+ (operation.targetQuantity ??+ operation.operationQuantity ??+ 0)) *100,100)}@@ -475,7 +477,9 @@ function JobDetails({ job }: { job: Job }) {operation.quantityComplete ?? 0).toString()}denominator={(- operation.operationQuantity ?? 0+ operation.targetQuantity ??+ operation.operationQuantity ??+ 0).toString()}/></div>diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsxindex 0de832c917..b341198fc0 100644--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx@@ -165,7 +165,7 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {status={status}jobs={jobs.map((job) => ({salesOrderLineId: job.salesOrderLineId,- productionQuantity: job.productionQuantity,+ productionQuantity: job.quantity,quantityComplete: job.quantityComplete,status: job.status}))}@@ -213,7 +213,7 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {const relevantJobs =jobs.filter?.((job) => job.salesOrderLineId === line.id) ?? [];const totalJobQuantity = relevantJobs.reduce(- (acc, job) => acc + job.productionQuantity,+ (acc, job) => acc + job.quantity,0);diff --git a/apps/erp/app/routes/x+/job+/new.tsx b/apps/erp/app/routes/x+/job+/new.tsxindex a2f5259897..37a3a89c60 100644--- a/apps/erp/app/routes/x+/job+/new.tsx+++ b/apps/erp/app/routes/x+/job+/new.tsx@@ -76,7 +76,7 @@ export async function action({ request }: ActionFunctionArgs) {const scrapPercentage = manufacturing.data?.scrapPercentage ?? 0;const calculatedScrapQuantity =scrapPercentage > 0- ? Math.ceil(validation.data.quantity * (scrapPercentage / 100))+ ? Math.ceil(validation.data.quantity * scrapPercentage): 0;// Use the form value if set, otherwise use calculated valueconst scrapQuantity =diff --git a/apps/erp/app/routes/x+/job+/update.tsx b/apps/erp/app/routes/x+/job+/update.tsxindex 52d35665c8..177497e257 100644--- a/apps/erp/app/routes/x+/job+/update.tsx+++ b/apps/erp/app/routes/x+/job+/update.tsx@@ -73,7 +73,7 @@ export async function action({ request }: ActionFunctionArgs) {modelUploadId: item.data?.modelUploadId ?? null,scrapQuantity: Math.ceil((manufacturing?.data?.lotSize ?? 0) *- ((manufacturing?.data?.scrapPercentage ?? 0) / 100)+ (manufacturing?.data?.scrapPercentage ?? 0)),updatedBy: userId,updatedAt: new Date().toISOString()diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsxindex a705382d71..8ebc2e2eb2 100644--- a/apps/erp/app/routes/x+/production+/planning.update.tsx+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx@@ -186,7 +186,7 @@ export async function action({ request }: ActionFunctionArgs) {const scrapPercentage = manufacturing.data?.scrapPercentage ?? 0;const scrapQuantity =scrapPercentage > 0- ? Math.ceil(order.quantity * (scrapPercentage / 100))+ ? Math.ceil(order.quantity * scrapPercentage): 0;const createJob = await upsertJob(diff --git a/apps/mes/app/components/OperationsList.tsx b/apps/mes/app/components/OperationsList.tsxindex de0e2bc4f5..0b270a65ff 100644--- a/apps/mes/app/components/OperationsList.tsx+++ b/apps/mes/app/components/OperationsList.tsx@@ -122,7 +122,7 @@ function OperationCard({</span></div><Heading size="h4" className="text-muted-foreground/70">- {operation.operationQuantity}+ {operation.targetQuantity ?? operation.operationQuantity ?? 0}</Heading></div></CardHeader>diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsxindex d957dad3bf..f2aec1439a 100644--- a/apps/mes/app/routes/x+/complete.tsx+++ b/apps/mes/app/routes/x+/complete.tsx@@ -62,7 +62,9 @@ export async function action({ request }: ActionFunctionArgs) {const willBeFinished =validation.data.quantity + currentQuantity >=- (jobOperation.data.operationQuantity ?? 0);+ (jobOperation.data.targetQuantity ??+ jobOperation.data.operationQuantity ??+ 0);if (validation.data.trackingType === "Serial") {const response = await serviceRole.functions.invoke("issue", {diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsxindex bbf8f2a80b..61005c6487 100644--- a/apps/mes/app/routes/x+/end.$operationId.tsx+++ b/apps/mes/app/routes/x+/end.$operationId.tsx@@ -89,7 +89,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const willBeFinished =quantityToComplete + currentQuantity >=- (jobOperation.data.operationQuantity ?? 0);+ (jobOperation.data.targetQuantity ??+ jobOperation.data.operationQuantity ??+ 0);const isTrackedEntity =jobMakeMethod.data.requiresSerialTracking ||diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 91921c61b4..6526201313 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -52947,6 +52947,7 @@ export type Database = {setupTime: numbersetupUnit: Database["public"]["Enums"]["factor"]tags: string[]+ targetQuantity: numberthumbnailPath: stringworkCenterId: string}[]@@ -53023,6 +53024,7 @@ export type Database = {setupTime: numbersetupUnit: Database["public"]["Enums"]["factor"]tags: string[]+ targetQuantity: numberthumbnailPath: stringworkCenterId: string}[]@@ -54034,6 +54036,7 @@ export type Database = {setupTime: numbersetupUnit: Database["public"]["Enums"]["factor"]tags: string[]+ targetQuantity: numberthumbnailPath: stringworkCenterId: string}[]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 91921c61b4..6526201313 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -52947,6 +52947,7 @@ export type Database = {setupTime: numbersetupUnit: Database["public"]["Enums"]["factor"]tags: string[]+ targetQuantity: numberthumbnailPath: stringworkCenterId: string}[]@@ -53023,6 +53024,7 @@ export type Database = {setupTime: numbersetupUnit: Database["public"]["Enums"]["factor"]tags: string[]+ targetQuantity: numberthumbnailPath: stringworkCenterId: string}[]@@ -54034,6 +54036,7 @@ export type Database = {setupTime: numbersetupUnit: Database["public"]["Enums"]["factor"]tags: string[]+ targetQuantity: numberthumbnailPath: stringworkCenterId: string}[]diff --git a/packages/database/supabase/migrations/20260119130000_add-target-quantity-to-operation-functions.sql b/packages/database/supabase/migrations/20260119130000_add-target-quantity-to-operation-functions.sqlindex 2fdda1dc0d..d35b50f047 100644--- a/packages/database/supabase/migrations/20260119130000_add-target-quantity-to-operation-functions.sql+++ b/packages/database/supabase/migrations/20260119130000_add-target-quantity-to-operation-functions.sql@@ -194,3 +194,323 @@ BEGINLIMIT 1;END;$$ LANGUAGE plpgsql;+++-- Add targetQuantity to get_active_job_operations_by_employee function+DROP FUNCTION IF EXISTS get_active_job_operations_by_employee;+CREATE OR REPLACE FUNCTION get_active_job_operations_by_employee(+ employee_id TEXT,+ company_id TEXT+)+RETURNS TABLE (+ "id" TEXT,+ "jobId" TEXT,+ "operationOrder" DOUBLE PRECISION,+ "processId" TEXT,+ "workCenterId" TEXT,+ "description" TEXT,+ "setupTime" NUMERIC,+ "setupUnit" factor,+ "laborTime" NUMERIC,+ "laborUnit" factor,+ "machineTime" NUMERIC,+ "machineUnit" factor,+ "operationOrderType" "methodOperationOrder",+ "jobReadableId" TEXT,+ "jobStatus" "jobStatus",+ "jobDueDate" DATE,+ "jobDeadlineType" "deadlineType",+ "jobCustomerId" TEXT,+ "salesOrderReadableId" TEXT,+ "salesOrderId" TEXT,+ "salesOrderLineId" TEXT,+ "parentMaterialId" TEXT,+ "itemReadableId" TEXT,+ "itemDescription" TEXT,+ "operationStatus" "jobOperationStatus",+ "targetQuantity" NUMERIC,+ "operationQuantity" NUMERIC,+ "quantityComplete" NUMERIC,+ "quantityScrapped" NUMERIC,+ "thumbnailPath" TEXT,+ "assignee" TEXT,+ "tags" TEXT[]+)+SECURITY INVOKER+AS $$+BEGIN+ RETURN QUERY+ WITH active_production_events AS (+ SELECT DISTINCT "jobOperationId"+ FROM "productionEvent"+ WHERE "employeeId" = employee_id AND "endTime" IS NULL AND "companyId" = company_id+ )+ SELECT+ jo."id",+ jo."jobId",+ jo."order" AS "operationOrder",+ jo."processId",+ jo."workCenterId",+ jo."description",+ jo."setupTime",+ jo."setupUnit",+ jo."laborTime",+ jo."laborUnit",+ jo."machineTime",+ jo."machineUnit",+ jo."operationOrder" AS "operationOrderType",+ j."jobId" AS "jobReadableId",+ j."status" AS "jobStatus",+ j."dueDate" AS "jobDueDate",+ j."deadlineType" AS "jobDeadlineType",+ j."customerId" AS "jobCustomerId",+ so."salesOrderId" AS "salesOrderReadableId",+ so."id" AS "salesOrderId",+ j."salesOrderLineId",+ jmm."parentMaterialId",+ i."readableId" as "itemReadableId",+ i."name" as "itemDescription",+ jo."status" AS "operationStatus",+ jo."targetQuantity"::NUMERIC,+ jo."operationQuantity",+ jo."quantityComplete",+ jo."quantityScrapped",+ CASE+ WHEN jmm."parentMaterialId" IS NULL THEN COALESCE(i."thumbnailPath", j_mu."thumbnailPath", i_mu."thumbnailPath")+ ELSE COALESCE(i."thumbnailPath", i_mu."thumbnailPath")+ END as "thumbnailPath",+ jo."assignee",+ jo."tags"+ FROM "jobOperation" jo+ JOIN "job" j ON j.id = jo."jobId"+ LEFT JOIN "salesOrderLine" sol ON sol."id" = j."salesOrderLineId"+ LEFT JOIN "salesOrder" so ON so."id" = sol."salesOrderId"+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id+ LEFT JOIN "item" i ON jmm."itemId" = i.id+ LEFT JOIN "modelUpload" j_mu ON j_mu.id = j."modelUploadId"+ LEFT JOIN "modelUpload" i_mu ON i_mu.id = i."modelUploadId"+ JOIN active_production_events ape ON ape."jobOperationId" = jo.id;+END;+$$ LANGUAGE plpgsql;+++-- Add targetQuantity to get_recent_job_operations_by_employee function+DROP FUNCTION IF EXISTS get_recent_job_operations_by_employee;+CREATE OR REPLACE FUNCTION get_recent_job_operations_by_employee(+ employee_id TEXT,+ company_id TEXT+)+RETURNS TABLE (+ "id" TEXT,+ "jobId" TEXT,+ "operationOrder" DOUBLE PRECISION,+ "processId" TEXT,+ "workCenterId" TEXT,+ "description" TEXT,+ "setupTime" NUMERIC,+ "setupUnit" factor,+ "laborTime" NUMERIC,+ "laborUnit" factor,+ "machineTime" NUMERIC,+ "machineUnit" factor,+ "operationOrderType" "methodOperationOrder",+ "jobReadableId" TEXT,+ "jobStatus" "jobStatus",+ "jobDueDate" DATE,+ "jobDeadlineType" "deadlineType",+ "jobCustomerId" TEXT,+ "salesOrderReadableId" TEXT,+ "salesOrderId" TEXT,+ "salesOrderLineId" TEXT,+ "parentMaterialId" TEXT,+ "itemReadableId" TEXT,+ "itemDescription" TEXT,+ "operationStatus" "jobOperationStatus",+ "targetQuantity" NUMERIC,+ "operationQuantity" NUMERIC,+ "quantityComplete" NUMERIC,+ "quantityScrapped" NUMERIC,+ "thumbnailPath" TEXT,+ "assignee" TEXT,+ "tags" TEXT[]+)+SECURITY INVOKER+AS $$+BEGIN+ RETURN QUERY+ WITH recent_production_events AS (+ SELECT "jobOperationId", MAX("endTime") as "lastActivity"+ FROM "productionEvent"+ WHERE "employeeId" = employee_id AND "companyId" = company_id+ GROUP BY "jobOperationId"+ ORDER BY MAX("endTime") DESC+ LIMIT 20+ ),+ recent_production_quantities AS (+ SELECT "jobOperationId", MAX("createdAt") as "lastActivity"+ FROM "productionQuantity"+ WHERE "createdBy" = employee_id AND "companyId" = company_id+ GROUP BY "jobOperationId"+ ORDER BY MAX("createdAt") DESC+ LIMIT 20+ ),+ combined_recent_activities AS (+ SELECT DISTINCT ON ("jobOperationId") "jobOperationId", "lastActivity"+ FROM (+ SELECT "jobOperationId", "lastActivity"+ FROM recent_production_events+ UNION ALL+ SELECT "jobOperationId", "lastActivity"+ FROM recent_production_quantities+ ) combined+ ORDER BY "jobOperationId", "lastActivity" DESC+ )+ SELECT+ jo."id",+ jo."jobId",+ jo."order" AS "operationOrder",+ jo."processId",+ jo."workCenterId",+ jo."description",+ jo."setupTime",+ jo."setupUnit",+ jo."laborTime",+ jo."laborUnit",+ jo."machineTime",+ jo."machineUnit",+ jo."operationOrder" AS "operationOrderType",+ j."jobId" AS "jobReadableId",+ j."status" AS "jobStatus",+ j."dueDate" AS "jobDueDate",+ j."deadlineType" AS "jobDeadlineType",+ j."customerId" AS "jobCustomerId",+ so."salesOrderId" AS "salesOrderReadableId",+ so."id" AS "salesOrderId",+ j."salesOrderLineId",+ jmm."parentMaterialId",+ i."readableId" as "itemReadableId",+ i."name" as "itemDescription",+ jo."status" AS "operationStatus",+ jo."targetQuantity"::NUMERIC,+ jo."operationQuantity",+ jo."quantityComplete",+ jo."quantityScrapped",+ CASE+ WHEN jmm."parentMaterialId" IS NULL THEN COALESCE(i."thumbnailPath", j_mu."thumbnailPath", i_mu."thumbnailPath")+ ELSE COALESCE(i."thumbnailPath", i_mu."thumbnailPath")+ END as "thumbnailPath",+ jo."assignee",+ jo."tags"+ FROM combined_recent_activities cra+ JOIN "jobOperation" jo ON jo.id = cra."jobOperationId"+ JOIN "job" j ON j.id = jo."jobId"+ LEFT JOIN "salesOrderLine" sol ON sol."id" = j."salesOrderLineId"+ LEFT JOIN "salesOrder" so ON so."id" = sol."salesOrderId"+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id+ LEFT JOIN "item" i ON jmm."itemId" = i.id+ LEFT JOIN "modelUpload" j_mu ON j_mu.id = j."modelUploadId"+ LEFT JOIN "modelUpload" i_mu ON i_mu.id = i."modelUploadId"+ ORDER BY cra."lastActivity" DESC+ LIMIT 20;+END;+$$ LANGUAGE plpgsql;+++-- Add targetQuantity to get_assigned_job_operations function+DROP FUNCTION IF EXISTS get_assigned_job_operations;+CREATE OR REPLACE FUNCTION get_assigned_job_operations(+ user_id TEXT,+ company_id TEXT+)+RETURNS TABLE (+ "id" TEXT,+ "jobId" TEXT,+ "operationOrder" DOUBLE PRECISION,+ "processId" TEXT,+ "workCenterId" TEXT,+ "description" TEXT,+ "setupTime" NUMERIC,+ "setupUnit" factor,+ "laborTime" NUMERIC,+ "laborUnit" factor,+ "machineTime" NUMERIC,+ "machineUnit" factor,+ "operationOrderType" "methodOperationOrder",+ "jobReadableId" TEXT,+ "jobStatus" "jobStatus",+ "jobDueDate" DATE,+ "jobDeadlineType" "deadlineType",+ "jobCustomerId" TEXT,+ "salesOrderReadableId" TEXT,+ "salesOrderId" TEXT,+ "salesOrderLineId" TEXT,+ "parentMaterialId" TEXT,+ "itemReadableId" TEXT,+ "itemDescription" TEXT,+ "operationStatus" "jobOperationStatus",+ "targetQuantity" NUMERIC,+ "operationQuantity" NUMERIC,+ "quantityComplete" NUMERIC,+ "quantityScrapped" NUMERIC,+ "thumbnailPath" TEXT,+ "assignee" TEXT,+ "tags" TEXT[]+)+SECURITY INVOKER+AS $$+BEGIN+ RETURN QUERY+ SELECT+ jo."id",+ jo."jobId",+ jo."order" AS "operationOrder",+ jo."processId",+ jo."workCenterId",+ jo."description",+ jo."setupTime",+ jo."setupUnit",+ jo."laborTime",+ jo."laborUnit",+ jo."machineTime",+ jo."machineUnit",+ jo."operationOrder" AS "operationOrderType",+ j."jobId" AS "jobReadableId",+ j."status" AS "jobStatus",+ j."dueDate" AS "jobDueDate",+ j."deadlineType" AS "jobDeadlineType",+ j."customerId" AS "jobCustomerId",+ so."salesOrderId" AS "salesOrderReadableId",+ so."id" AS "salesOrderId",+ j."salesOrderLineId",+ jmm."parentMaterialId",+ i."readableId" as "itemReadableId",+ i."name" as "itemDescription",+ CASE+ WHEN j."status" = 'Paused' THEN 'Paused'+ ELSE jo."status"+ END AS "operationStatus",+ jo."targetQuantity"::NUMERIC,+ jo."operationQuantity",+ jo."quantityComplete",+ jo."quantityScrapped",+ CASE+ WHEN jmm."parentMaterialId" IS NULL THEN COALESCE(i."thumbnailPath", j_mu."thumbnailPath", i_mu."thumbnailPath")+ ELSE COALESCE(i."thumbnailPath", i_mu."thumbnailPath")+ END as "thumbnailPath",+ jo."assignee",+ jo."tags"+ FROM "jobOperation" jo+ JOIN "job" j ON j.id = jo."jobId"+ LEFT JOIN "salesOrderLine" sol ON sol."id" = j."salesOrderLineId"+ LEFT JOIN "salesOrder" so ON so."id" = sol."salesOrderId"+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id+ LEFT JOIN "item" i ON jmm."itemId" = i.id+ LEFT JOIN "modelUpload" j_mu ON j_mu.id = j."modelUploadId"+ LEFT JOIN "modelUpload" i_mu ON i_mu.id = i."modelUploadId"+ WHERE jo."assignee" = user_id+ AND jo."status" IN ('Todo', 'Ready', 'Waiting', 'In Progress', 'Paused')+ AND j."status" IN ('Ready', 'In Progress', 'Paused')+ AND j."companyId" = company_id+ ORDER BY jo."priority";+END;+$$ LANGUAGE plpgsql;