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: complete jobs and operations automatically
Brad Barbina9f2be62ea47
diff --git a/apps/erp/app/components/Redirect.tsx b/apps/erp/app/components/Redirect.tsxnew file mode 100644index 0000000000..ea92b63b5d--- /dev/null+++ b/apps/erp/app/components/Redirect.tsx@@ -0,0 +1,16 @@+import { Loading } from "@carbon/react";+import { useEffect, useState } from "react";++export const Redirect = ({ path }: { path: string }) => {+ const [isLoading, setIsLoading] = useState(true);+ useEffect(() => {+ window.location.href = path;+ setIsLoading(false);+ }, [path]);++ return (+ <div className="flex h-screen w-screen items-center justify-center">+ <Loading className="size-8" isLoading={isLoading} />+ </div>+ );+};diff --git a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsxindex c987706596..ab72f4ea10 100644--- a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx+++ b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx@@ -386,11 +386,6 @@ function NodeText({ node }: { node: FlatTreeItem<Method> }) {<span className="text-sm truncate font-medium">{node.data.description || node.data.itemReadableId}</span>- {node.data.revision && node.data.revision !== "0" && (- <Badge variant="outline" className="text-xs opacity-0">- {node.data.revision}- </Badge>- )}</div>);}diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsxindex cb3470dd5f..40e4125483 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx@@ -310,11 +310,6 @@ function NodeText({ node }: { node: FlatTreeItem<JobMethod> }) {<span className="font-medium text-sm truncate">{node.data.description || node.data.itemReadableId}</span>- {node.data.revision && node.data.revision !== "0" && (- <Badge variant="outline" className="text-xs">- {node.data.revision}- </Badge>- )}</div>);}diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsxindex 39a800df21..a376cd89b4 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx@@ -239,11 +239,6 @@ function NodeText({ node }: { node: FlatTreeItem<QuoteMethod> }) {<span className="font-medium text-sm truncate">{node.data.description || node.data.itemReadableId}</span>- {node.data.revision && node.data.revision !== "0" && (- <Badge variant="outline" className="text-xs">- {node.data.revision}- </Badge>- )}</div>);}diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsxindex fd82e31527..a1087cf095 100644--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx@@ -270,7 +270,6 @@ export function SalesOrderJobItem({ job }: { job: SalesOrderJob }) {const releaseModal = useDisclosure();const statusFetcher = useFetcher<{}>();const todaysDate = useMemo(() => today(getLocalTimeZone()), []);- console.log({ job });return (<VStack>diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsxindex 0d2aafe39b..07ead27575 100644--- a/apps/erp/app/routes/api+/kanban.$id.tsx+++ b/apps/erp/app/routes/api+/kanban.$id.tsx@@ -8,7 +8,8 @@ import { Await, useLoaderData } from "@remix-run/react";import { FunctionRegion, type SupabaseClient } from "@supabase/supabase-js";import { tasks } from "@trigger.dev/sdk/v3";import { defer, type LoaderFunctionArgs } from "@vercel/remix";-import { Suspense, useEffect, useState } from "react";+import { Suspense } from "react";+import { Redirect } from "~/components/Redirect";import { getKanban } from "~/modules/inventory";import { getItemReplenishment } from "~/modules/items";@@ -26,10 +27,6 @@ import {import { getNextSequence } from "~/modules/settings";import { path } from "~/utils/path";-export const config = {- runtime: "nodejs",-};-async function handleKanban({client,companyId,@@ -200,12 +197,12 @@ async function handleKanban({let laborTime = operation.laborTime;let machineTime = operation.machineTime;let type: "Setup" | "Labor" | "Machine" = "Labor";- if (setupTime) {- type = "Setup";- }if (machineTime && !laborTime) {type = "Machine";}+ if (setupTime) {+ type = "Setup";+ }redirectUrl = path.to.external.mesJobOperationStart(operationId, type);} else {redirectUrl = path.to.external.mesJobOperation(operationId);@@ -370,24 +367,10 @@ export default function KanbanRedirectRoute() {if (resolvedPromise.error) {return <div>{resolvedPromise.error}</div>;}- return <KanbanRedirect path={resolvedPromise?.data ?? ""} />;+ return <Redirect path={resolvedPromise?.data ?? ""} />;}}</Await></Suspense></div>);}--const KanbanRedirect = ({ path }: { path: string }) => {- const [isLoading, setIsLoading] = useState(true);- useEffect(() => {- window.location.href = path;- setIsLoading(false);- }, [path]);-- return (- <div className="flex h-screen w-screen items-center justify-center">- <Loading className="size-8" isLoading={isLoading} />- </div>- );-};diff --git a/apps/erp/app/routes/api+/kanban.collision.$id.tsx b/apps/erp/app/routes/api+/kanban.collision.$id.tsxindex b784100364..96eb9ceff0 100644--- a/apps/erp/app/routes/api+/kanban.collision.$id.tsx+++ b/apps/erp/app/routes/api+/kanban.collision.$id.tsx@@ -14,10 +14,6 @@ import {} from "~/modules/production/production.service";import { path } from "~/utils/path";-export const config = {- runtime: "nodejs",-};-export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {});diff --git a/apps/erp/app/routes/api+/kanban.complete.$id.tsx b/apps/erp/app/routes/api+/kanban.complete.$id.tsxnew file mode 100644index 0000000000..0962a2a162--- /dev/null+++ b/apps/erp/app/routes/api+/kanban.complete.$id.tsx@@ -0,0 +1,83 @@+import { notFound } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import type { Database } from "@carbon/database";+import { Loading } from "@carbon/react";+import { Await, useLoaderData } from "@remix-run/react";+import type { SupabaseClient } from "@supabase/supabase-js";+import { defer, type LoaderFunctionArgs } from "@vercel/remix";+import { Suspense } from "react";+import { Redirect } from "~/components/Redirect";+import { getKanban } from "~/modules/inventory";+import { getActiveJobOperationByJobId } from "~/modules/production";+import { path } from "~/utils/path";++async function handleKanbanComplete({+ client,+ companyId,+ id,+}: {+ client: SupabaseClient<Database>;+ companyId: string;+ id: string;+}): Promise<{ data: string; error: null } | { data: null; error: string }> {+ const kanban = await getKanban(client, id);+ if (kanban.error) {+ return {+ data: null,+ error: "Kanban not found",+ };+ }++ if (!kanban.data?.jobId) {+ return {+ data: null,+ error: "No job found for kanban",+ };+ }++ const operation = await getActiveJobOperationByJobId(+ client,+ kanban.data.jobId!,+ companyId+ );++ if (!operation) {+ return {+ data: path.to.job(kanban.data.jobId!),+ error: null,+ };+ }++ return {+ data: path.to.external.mesJobOperationComplete(operation.id),+ error: null,+ };+}++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {});++ const { id } = params;+ if (!id) throw notFound("id not found");++ return defer(await handleKanbanComplete({ client, companyId, id }));+}++export default function KanbanRedirectRoute() {+ const promise = useLoaderData<typeof loader>();++ return (+ <div className="flex h-screen w-screen items-center justify-center">+ <Suspense fallback={<Loading className="size-8" isLoading />}>+ <Await resolve={promise}>+ {(resolvedPromise) => {+ if (resolvedPromise.error) {+ return <div>{resolvedPromise.error}</div>;+ }+ return <Redirect path={resolvedPromise?.data ?? ""} />;+ }}+ </Await>+ </Suspense>+ </div>+ );+}diff --git a/apps/erp/app/routes/api+/kanban.start.$id.tsx b/apps/erp/app/routes/api+/kanban.start.$id.tsxindex fd2f9a4eeb..df5dd74d54 100644--- a/apps/erp/app/routes/api+/kanban.start.$id.tsx+++ b/apps/erp/app/routes/api+/kanban.start.$id.tsx@@ -1,23 +1,38 @@import { notFound } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { redirect, type LoaderFunctionArgs } from "@vercel/remix";+import type { Database } from "@carbon/database";+import { Loading } from "@carbon/react";+import { Await, useLoaderData } from "@remix-run/react";+import type { SupabaseClient } from "@supabase/supabase-js";+import { defer, type LoaderFunctionArgs } from "@vercel/remix";+import { Suspense } from "react";+import { Redirect } from "~/components/Redirect";import { getKanban } from "~/modules/inventory";import { getActiveJobOperationByJobId } from "~/modules/production";import { path } from "~/utils/path";-export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {});-- const { id } = params;- if (!id) throw notFound("id not found");-+async function handleKanbanStart({+ client,+ companyId,+ id,+}: {+ client: SupabaseClient<Database>;+ companyId: string;+ id: string;+}): Promise<{ data: string; error: null } | { data: null; error: string }> {const kanban = await getKanban(client, id);if (kanban.error) {- throw notFound("Kanban not found");+ return {+ data: null,+ error: "Kanban not found",+ };}if (!kanban.data?.jobId) {- throw notFound("Kanban has no active job");+ return {+ data: null,+ error: "No job found for kanban",+ };}const operation = await getActiveJobOperationByJobId(@@ -27,19 +42,53 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);if (!operation) {- throw redirect(path.to.job(kanban.data.jobId!));+ return {+ data: path.to.job(kanban.data.jobId!),+ error: null,+ };}let setupTime = operation.setupTime;let laborTime = operation.laborTime;let machineTime = operation.machineTime;let type: "Setup" | "Labor" | "Machine" = "Labor";- if (setupTime) {- type = "Setup";- }if (machineTime && !laborTime) {type = "Machine";}+ if (setupTime) {+ type = "Setup";+ }- throw redirect(path.to.external.mesJobOperationStart(operation.id, type));+ return {+ data: path.to.external.mesJobOperationStart(operation.id, type),+ error: null,+ };+}++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {});++ const { id } = params;+ if (!id) throw notFound("id not found");++ return defer(await handleKanbanStart({ client, companyId, id }));+}++export default function KanbanRedirectRoute() {+ const promise = useLoaderData<typeof loader>();++ return (+ <div className="flex h-screen w-screen items-center justify-center">+ <Suspense fallback={<Loading className="size-8" isLoading />}>+ <Await resolve={promise}>+ {(resolvedPromise) => {+ if (resolvedPromise.error) {+ return <div>{resolvedPromise.error}</div>;+ }+ return <Redirect path={resolvedPromise?.data ?? ""} />;+ }}+ </Await>+ </Suspense>+ </div>+ );}diff --git a/apps/erp/app/routes/x+/inventory+/kanbans.new.tsx b/apps/erp/app/routes/x+/inventory+/kanbans.new.tsxindex 495ce07d2b..45f03de9f3 100644--- a/apps/erp/app/routes/x+/inventory+/kanbans.new.tsx+++ b/apps/erp/app/routes/x+/inventory+/kanbans.new.tsx@@ -33,8 +33,6 @@ export async function action({ request }: ActionFunctionArgs) {const { id, ...data } = validation.data;- console.log({ data });-const createKanban = await upsertKanban(client, {...data,companyId,diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsxindex c3de7e9b51..8887b42974 100644--- a/apps/mes/app/routes/x+/complete.tsx+++ b/apps/mes/app/routes/x+/complete.tsx@@ -11,7 +11,10 @@ import { FunctionRegion } from "@supabase/supabase-js";import type { ActionFunctionArgs } from "@vercel/remix";import { json, redirect } from "@vercel/remix";import { nonScrapQuantityValidator } from "~/services/models";-import { insertProductionQuantity } from "~/services/operations.service";+import {+ finishJobOperation,+ insertProductionQuantity,+} from "~/services/operations.service";import { path } from "~/utils/path";export async function action({ request }: ActionFunctionArgs) {@@ -29,6 +32,38 @@ export async function action({ request }: ActionFunctionArgs) {const serviceRole = await getCarbonServiceRole();+ // Get current job operation and production quantities to check if operation will be finished+ const [jobOperation, productionQuantities] = await Promise.all([+ serviceRole+ .from("jobOperation")+ .select("*")+ .eq("id", validation.data.jobOperationId)+ .maybeSingle(),+ serviceRole+ .from("productionQuantity")+ .select("*")+ .eq("type", "Production")+ .eq("jobOperationId", validation.data.jobOperationId),+ ]);++ if (jobOperation.error || !jobOperation.data) {+ return json(+ {},+ await flash(+ request,+ error(jobOperation.error, "Failed to fetch job operation")+ )+ );+ }++ const currentQuantity =+ productionQuantities.data?.reduce((acc, curr) => acc + curr.quantity, 0) ??+ 0;++ const willBeFinished =+ validation.data.quantity + currentQuantity >=+ (jobOperation.data.operationQuantity ?? 0);+if (validation.data.trackingType === "Serial") {const response = await serviceRole.functions.invoke("issue", {body: {@@ -42,6 +77,28 @@ export async function action({ request }: ActionFunctionArgs) {const trackedEntityId = response.data?.newTrackedEntityId;+ if (willBeFinished) {+ const finishOperation = await finishJobOperation(serviceRole, {+ jobOperationId: jobOperation.data.id,+ userId,+ });++ if (finishOperation.error) {+ return json(+ {},+ await flash(+ request,+ error(finishOperation.error, "Failed to finish operation")+ )+ );+ }++ throw redirect(+ path.to.operations,+ await flash(request, success("Operation finished successfully"))+ );+ }+if (trackedEntityId) {throw redirect(`${path.to.operation(@@ -73,6 +130,28 @@ export async function action({ request }: ActionFunctionArgs) {);}+ if (willBeFinished) {+ const finishOperation = await finishJobOperation(serviceRole, {+ jobOperationId: jobOperation.data.id,+ userId,+ });++ if (finishOperation.error) {+ return json(+ {},+ await flash(+ request,+ error(finishOperation.error, "Failed to finish operation")+ )+ );+ }++ throw redirect(+ path.to.operations,+ await flash(request, success("Operation finished successfully"))+ );+ }+throw redirect(`${path.to.operation(validation.data.jobOperationId)}`);} else {const { trackedEntityId, trackingType, ...data } = validation.data;@@ -110,6 +189,28 @@ export async function action({ request }: ActionFunctionArgs) {);}+ if (willBeFinished) {+ const finishOperation = await finishJobOperation(serviceRole, {+ jobOperationId: jobOperation.data.id,+ userId,+ });++ if (finishOperation.error) {+ return json(+ {},+ await flash(+ request,+ error(finishOperation.error, "Failed to finish operation")+ )+ );+ }++ throw redirect(+ path.to.operations,+ await flash(request, success("Operation finished successfully"))+ );+ }+return json(insertProduction.data,await flash(request, success("Production quantity recorded successfully"))diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsxindex 007e5049c4..cd86027429 100644--- a/apps/mes/app/routes/x+/end.$operationId.tsx+++ b/apps/mes/app/routes/x+/end.$operationId.tsx@@ -2,9 +2,8 @@ import { error, getCarbonServiceRole, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { FunctionRegion } from "@supabase/supabase-js";-import { redirect, type LoaderFunctionArgs } from "@vercel/remix";+import { json, redirect, type LoaderFunctionArgs } from "@vercel/remix";import {- endProductionEventsForJobOperation,finishJobOperation,getTrackedEntitiesByMakeMethodId,insertProductionQuantity,@@ -31,6 +30,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {serviceRole.from("productionQuantity").select("*")+ .eq("type", "Production").eq("jobOperationId", operationId),]);@@ -57,19 +57,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {));}-- const endEvents = await endProductionEventsForJobOperation(serviceRole, {- jobOperationId: jobOperation.data.id,- employeeId: userId,- companyId,- });-- if (endEvents.error) {- throw redirect(- path.to.operations,- await flash(request, error(endEvents.error, "Failed to end event"))- );- }+ const completeAll = jobOperation.data?.completeAllOnScan ?? false;const [jobMakeMethod] = await Promise.all([serviceRole@@ -93,8 +81,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {productionQuantities.data?.reduce((acc, curr) => acc + curr.quantity, 0) ??0;- const quantityToComplete =- (jobOperation.data.operationQuantity ?? 0) - currentQuantity;+ const quantityToComplete = completeAll+ ? Math.max(0, (jobOperation.data.operationQuantity ?? 0) - currentQuantity)+ : 1;++ const willBeFinished =+ quantityToComplete + currentQuantity >=+ (jobOperation.data.operationQuantity ?? 0);const isTrackedEntity =jobMakeMethod.data.requiresSerialTracking ||@@ -138,6 +131,28 @@ export async function loader({ request, params }: LoaderFunctionArgs) {)}?trackedEntityId=${newTrackedEntityId}`);}++ if (willBeFinished) {+ const finishOperation = await finishJobOperation(serviceRole, {+ jobOperationId: jobOperation.data.id,+ userId,+ });++ if (finishOperation.error) {+ return json(+ {},+ await flash(+ request,+ error(finishOperation.error, "Failed to finish operation")+ )+ );+ }++ throw redirect(+ path.to.operations,+ await flash(request, success("Operation finished successfully"))+ );+ }} else if (jobMakeMethod.data.requiresBatchTracking) {const response = await serviceRole.functions.invoke("issue", {body: {@@ -205,23 +220,30 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}}- const finishOperation = await finishJobOperation(serviceRole, {- jobOperationId: jobOperation.data.id,- userId,- });+ if (willBeFinished) {+ const finishOperation = await finishJobOperation(serviceRole, {+ jobOperationId: jobOperation.data.id,+ userId,+ });++ if (finishOperation.error) {+ throw redirect(+ path.to.operation(operationId),+ await flash(+ request,+ error(finishOperation.error, "Failed to finish operation")+ )+ );+ }- if (finishOperation.error) {throw redirect(- path.to.operation(operationId),- await flash(- request,- error(finishOperation.error, "Failed to finish operation")- )+ path.to.operations,+ await flash(request, success("Operation finished successfully")));}throw redirect(- path.to.operations,- await flash(request, success("Operation finished successfully"))+ path.to.operation(operationId),+ await flash(request, success("Successfully completed part")));}diff --git a/apps/mes/app/routes/x+/finish.tsx b/apps/mes/app/routes/x+/finish.tsxindex 8ae30f79c3..76ae3597dc 100644--- a/apps/mes/app/routes/x+/finish.tsx+++ b/apps/mes/app/routes/x+/finish.tsx@@ -30,6 +30,8 @@ export async function action({ request }: ActionFunctionArgs) {userId,});+ console.log({ finishOperation });+if (finishOperation.error) {return json({},diff --git a/apps/mes/app/routes/x+/start.$operationId.tsx b/apps/mes/app/routes/x+/start.$operationId.tsxindex e370502dde..47df425cd0 100644--- a/apps/mes/app/routes/x+/start.$operationId.tsx+++ b/apps/mes/app/routes/x+/start.$operationId.tsx@@ -32,6 +32,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {.select("*").eq("id", operationId).maybeSingle(),+ serviceRole+ .from("productionEvent")+ .update({+ endTime: null,+ updatedBy: userId,+ })+ .eq("jobOperationId", operationId)+ .is("endTime", null),]);if (jobOperation.error || !jobOperation.data) {diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 8a3b187732..a79eb4eaf5 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -32,19 +32,6 @@ export async function finishJobOperation(userId: string;}) {- const closeProductionEvents = await client- .from("productionEvent")- .update({- endTime: new Date().toISOString(),- updatedBy: args.userId,- })- .eq("jobOperationId", args.jobOperationId)- .is("endTime", null);-- if (closeProductionEvents.error) {- return closeProductionEvents;- }-return client.from("jobOperation").update({diff --git a/packages/database/supabase/migrations/20251001133427_remove-production-event-trigger.sql b/packages/database/supabase/migrations/20251001133427_remove-production-event-trigger.sqlnew file mode 100644index 0000000000..82e5e7c6d2--- /dev/null+++ b/packages/database/supabase/migrations/20251001133427_remove-production-event-trigger.sql@@ -0,0 +1,157 @@+DROP TRIGGER IF EXISTS update_job_operation_status_trigger ON "productionEvent";+CREATE INDEX IF NOT EXISTS "kanban_jobId_idx" ON "kanban" ("jobId");+++CREATE OR REPLACE FUNCTION finish_job_operation()+RETURNS TRIGGER AS $$+BEGIN+ -- Set endTime for all open production events+ UPDATE "productionEvent"+ SET "endTime" = NOW()+ WHERE "jobOperationId" = NEW.id AND "endTime" IS NULL;++ -- Find all operations that depend on this one and might be ready+ UPDATE "jobOperation" op+ SET status = 'Ready'+ WHERE EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ WHERE dep."operationId" = op.id+ AND dep."dependsOnId" = NEW.id+ AND op.status = 'Waiting'+ )+ AND NOT EXISTS (+ -- Check no other dependencies are incomplete+ SELECT 1+ FROM "jobOperationDependency" dep2+ JOIN "jobOperation" jo2 ON jo2.id = dep2."dependsOnId"+ WHERE dep2."operationId" = op.id+ AND jo2.status != 'Done'+ AND jo2.id != NEW.id+ );++ -- Set the job operation status to Done+ NEW.status = 'Done';++ -- If this is the last operation, mark the job as Done+ IF is_last_job_operation(NEW.id) THEN+ DECLARE+ request_id TEXT;+ notify_url TEXT;+ api_url TEXT;+ anon_key TEXT;+ group_ids TEXT[];+ assigned_to TEXT;+ sales_order_id TEXT;+ BEGIN+ -- Get job details+ DECLARE+ job_item_id TEXT;+ job_quantity_to_produce INTEGER;+ job_location_id TEXT;+ job_shelf_id TEXT;++ BEGIN+ UPDATE "kanban" SET "jobId" = NULL WHERE "jobId" = NEW."jobId";++ SELECT "locationId"+ INTO job_location_id+ FROM "job"+ WHERE "id" = NEW."jobId";++ SELECT "defaultShelfId"+ INTO job_shelf_id+ FROM "pickMethod"+ WHERE "itemId" = job_item_id+ AND "locationId" = job_location_id+ LIMIT 1;++ -- Get sales order info+ SELECT "salesOrderId" INTO sales_order_id FROM "job" WHERE "id" = NEW."jobId";++ IF sales_order_id IS NOT NULL THEN+ -- Make-to-order: just update job status with quantityComplete+ UPDATE "job"+ SET status = 'Completed',+ "completedDate" = NOW(),+ "quantityComplete" = NEW."quantityComplete",+ "updatedAt" = NOW(),+ "updatedBy" = NEW."updatedBy"+ WHERE id = NEW."jobId";+ ELSE+ -- Make-to-stock: update job status to Done and invoke edge function for inventory+ UPDATE "job"+ SET status = 'Completed',+ "completedDate" = NOW(),+ "updatedAt" = NOW(),+ "updatedBy" = NEW."updatedBy"+ WHERE id = NEW."jobId";++ -- Invoke the issue edge function to handle inventory+ PERFORM util.invoke_edge_function(+ name => 'issue',+ body => CASE+ WHEN job_shelf_id IS NOT NULL THEN+ jsonb_build_object(+ 'type', 'jobCompleteInventory',+ 'jobId', NEW."jobId",+ 'companyId', NEW."companyId",+ 'userId', NEW."updatedBy",+ 'quantityComplete', NEW."quantityComplete",+ 'locationId', job_location_id,+ 'shelfId', job_shelf_id+ )+ ELSE+ jsonb_build_object(+ 'type', 'jobCompleteInventory',+ 'jobId', NEW."jobId",+ 'companyId', NEW."companyId",+ 'userId', NEW."updatedBy",+ 'quantityComplete', NEW."quantityComplete",+ 'locationId', job_location_id+ )+ END+ );+ END IF;+ END;++ SELECT "apiUrl", "anonKey" INTO api_url, anon_key FROM "config" LIMIT 1;+ notify_url := api_url || '/functions/v1/trigger';++ SELECT "assignee", "salesOrderId" INTO assigned_to, sales_order_id FROM "job" WHERE "id" = NEW."jobId";++ IF sales_order_id IS NULL THEN+ SELECT "inventoryJobCompletedNotificationGroup" INTO group_ids FROM "companySettings" WHERE "id" = NEW."companyId";+ ELSE+ SELECT "salesJobCompletedNotificationGroup" INTO group_ids FROM "companySettings" WHERE "id" = NEW."companyId";+ END IF;++ IF assigned_to IS NOT NULL THEN+ SELECT array_append(group_ids, assigned_to) INTO group_ids;+ END IF;++ IF array_length(group_ids, 1) > 0 THEN+ SELECT net.http_post(+ notify_url,+ jsonb_build_object(+ 'type', 'notify',+ 'event', 'job-completed',+ 'documentId', NEW."jobId",+ 'companyId', NEW."companyId",+ 'recipient', jsonb_build_object(+ 'type', 'group',+ 'groupIds', group_ids+ )+ )::jsonb,+ '{}'::jsonb,+ jsonb_build_object('Content-Type', 'application/json', 'Authorization', 'Bearer ' || anon_key)+ ) INTO request_id;+ END IF;++ END;+ END IF;++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;+