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.

feat: llm implementation of pick lists backend

Brad Barbin55db62217088
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.ts
index 2fc70dddba..f3b884d176 100644
--- a/apps/erp/app/modules/inventory/inventory.models.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.ts
@@ -267,3 +267,32 @@ export const warehouseTransferLineValidator = z
message: "From and To locations must be different",
path: ["toLocationId"],
});
+
+export const pickListStatusType = [
+ "Draft",
+ "Released",
+ "In Progress",
+ "Completed",
+] as const;
+
+export const pickListValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ locationId: z.string().min(1, { message: "Location is required" }),
+ status: z.enum(pickListStatusType).optional(),
+ createdDate: zfd.text(z.string().optional()),
+ completedDate: zfd.text(z.string().optional()),
+});
+
+export const pickListLineValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ pickListId: z.string().min(1, { message: "Pick list is required" }),
+ jobId: zfd.text(z.string().optional()),
+ jobMaterialId: zfd.text(z.string().optional()),
+ itemId: z.string().min(1, { message: "Item is required" }),
+ fromShelfId: zfd.text(z.string().optional()),
+ toShelfId: zfd.text(z.string().optional()),
+ quantity: zfd.numeric(
+ z.number().min(0, { message: "Quantity must be greater than or equal to 0" })
+ ),
+ pickedQuantity: zfd.numeric(z.number().min(0).optional()),
+});
diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.ts
index 10babf4feb..5fcfccb68b 100644
--- a/apps/erp/app/modules/items/items.models.ts
+++ b/apps/erp/app/modules/items/items.models.ts
@@ -211,6 +211,7 @@ export const methodMaterialValidator = z.object({
unitOfMeasureCode: z
.string()
.min(1, { message: "Unit of Measure is required" }),
+ shelfId: z.string().optional().nullable(),
});
export const methodOperationValidator = z
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 80c73c9511..c4478b121f 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -583,6 +583,7 @@ const baseMaterialValidator = z.object({
unitOfMeasureCode: z
.string()
.min(1, { message: "Unit of Measure is required" }),
+ shelfId: z.string().optional().nullable(),
});
export const jobMaterialValidator = baseMaterialValidator
diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.toml
index 7a2c9e37a5..99a5440a5a 100644
--- a/packages/database/supabase/config.toml
+++ b/packages/database/supabase/config.toml
@@ -144,3 +144,14 @@ verify_jwt = true
enabled = true
verify_jwt = true
+
+[functions.pick]
+enabled = true
+verify_jwt = true
+import_map = "./functions/pick/deno.json"
+# Uncomment to specify a custom file path to the entrypoint.
+# Supported file extensions are: .ts, .js, .mjs, .jsx, .tsx
+entrypoint = "./functions/pick/index.ts"
+# Specifies static files to be bundled with the function. Supports glob patterns.
+# For example, if you want to serve static HTML pages in your function:
+# static_files = [ "./functions/pick/*.html" ]
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 5b90d6d34e..6d9c6829ae 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -2295,6 +2295,7 @@ serve(async (req: Request) => {
order: child.data.order,
quantity: child.data.quantity,
unitOfMeasureCode: child.data.unitOfMeasureCode,
+ shelfId: child.data.shelfId || null,
companyId,
createdBy: userId,
customFields: {},
@@ -2574,6 +2575,7 @@ serve(async (req: Request) => {
order: child.data.order,
quantity: child.data.quantity,
unitOfMeasureCode: child.data.unitOfMeasureCode,
+ shelfId: child.data.shelfId || null,
companyId,
createdBy: userId,
customFields: {},
@@ -3150,6 +3152,7 @@ serve(async (req: Request) => {
order: child.data.order,
quantity: child.data.quantity,
unitOfMeasureCode: child.data.unitOfMeasureCode,
+ shelfId: child.data.shelfId || null,
companyId,
createdBy: userId,
customFields: {},
@@ -3440,6 +3443,7 @@ serve(async (req: Request) => {
order: child.data.order,
quantity: child.data.quantity,
unitOfMeasureCode: child.data.unitOfMeasureCode,
+ shelfId: child.data.shelfId || null,
companyId,
createdBy: userId,
customFields: {},
diff --git a/packages/database/supabase/functions/pick/.npmrc b/packages/database/supabase/functions/pick/.npmrc
new file mode 100644
index 0000000000..48c6388638
--- /dev/null
+++ b/packages/database/supabase/functions/pick/.npmrc
@@ -0,0 +1,3 @@
+# Configuration for private npm package dependencies
+# For more information on using private registries with Edge Functions, see:
+# https://supabase.com/docs/guides/functions/import-maps#importing-from-private-registries
diff --git a/packages/database/supabase/functions/pick/deno.json b/packages/database/supabase/functions/pick/deno.json
new file mode 100644
index 0000000000..f6ca8454c5
--- /dev/null
+++ b/packages/database/supabase/functions/pick/deno.json
@@ -0,0 +1,3 @@
+{
+ "imports": {}
+}
diff --git a/packages/database/supabase/functions/pick/index.ts b/packages/database/supabase/functions/pick/index.ts
new file mode 100644
index 0000000000..c829fd287d
--- /dev/null
+++ b/packages/database/supabase/functions/pick/index.ts
@@ -0,0 +1,468 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
+import { z } from "npm:zod@^3.24.1";
+
+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { getSupabaseServiceRole } from "../lib/supabase.ts";
+
+import { corsHeaders } from "../lib/headers.ts";
+import { getNextSequence } from "../shared/get-next-sequence.ts";
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+
+const payloadValidator = z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal("stageJob"),
+ jobId: z.string(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
+ z.object({
+ type: z.literal("generatePickList"),
+ locationId: z.string(),
+ jobIds: z.array(z.string()).optional(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
+ z.object({
+ type: z.literal("executePick"),
+ pickListLineId: z.string(),
+ pickedQuantity: z.number(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
+ z.object({
+ type: z.literal("completePickList"),
+ pickListId: z.string(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
+]);
+
+serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+ const payload = await req.json();
+
+ try {
+ const { type, companyId, userId } = payloadValidator.parse(payload);
+
+ console.log({
+ function: "pick",
+ type,
+ companyId,
+ userId,
+ });
+
+ const client = await getSupabaseServiceRole(
+ req.headers.get("Authorization"),
+ req.headers.get("carbon-key") ?? "",
+ companyId
+ );
+
+ switch (type) {
+ case "stageJob": {
+ const { jobId } = payload;
+
+ // Get job and its location
+ const { data: job, error: jobError } = await client
+ .from("job")
+ .select("*, locationId")
+ .eq("id", jobId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (jobError || !job) {
+ return new Response(JSON.stringify({ error: "Job not found" }), {
+ status: 404,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ });
+ }
+
+ if (job.status !== "Draft") {
+ return new Response(
+ JSON.stringify({ error: "Only draft jobs can be staged" }),
+ {
+ status: 400,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ // Get all job materials with their shelf requirements
+ const { data: jobMaterials, error: materialsError } = await client
+ .from("jobMaterial")
+ .select("*, item:itemId(id, name, readableId)")
+ .eq("jobId", jobId)
+ .eq("companyId", companyId);
+
+ if (materialsError) {
+ return new Response(
+ JSON.stringify({ error: "Failed to fetch job materials" }),
+ {
+ status: 500,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ // Get inventory quantities for each material
+ const warnings = [];
+ for (const material of jobMaterials || []) {
+ const { data: inventory } = await client.rpc(
+ "get_inventory_quantities",
+ {
+ p_company_id: companyId,
+ p_item_id: material.itemId,
+ p_location_id: job.locationId,
+ }
+ );
+
+ const quantityOnHand = inventory?.[0]?.quantityOnHand || 0;
+ const requiredQuantity = material.quantity;
+
+ if (quantityOnHand < requiredQuantity) {
+ warnings.push({
+ itemId: material.itemId,
+ itemName: material.item?.name,
+ required: requiredQuantity,
+ available: quantityOnHand,
+ shortage: requiredQuantity - quantityOnHand,
+ shelfId: material.shelfId,
+ });
+ }
+ }
+
+ // Update job status to Staged
+ const { error: updateError } = await client
+ .from("job")
+ .update({
+ status: "Staged",
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .eq("id", jobId)
+ .eq("companyId", companyId);
+
+ if (updateError) {
+ return new Response(
+ JSON.stringify({ error: "Failed to update job status" }),
+ {
+ status: 500,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ return new Response(
+ JSON.stringify({
+ success: true,
+ jobId,
+ warnings,
+ }),
+ {
+ status: 200,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ case "generatePickList": {
+ const { locationId, jobIds } = payload;
+
+ // Get all staged jobs at this location
+ let jobQuery = client
+ .from("job")
+ .select("id, locationId, shelfId")
+ .eq("companyId", companyId)
+ .eq("locationId", locationId)
+ .eq("status", "Staged");
+
+ if (jobIds && jobIds.length > 0) {
+ jobQuery = jobQuery.in("id", jobIds);
+ }
+
+ const { data: jobs, error: jobsError } = await jobQuery;
+
+ if (jobsError || !jobs || jobs.length === 0) {
+ return new Response(
+ JSON.stringify({ error: "No staged jobs found" }),
+ {
+ status: 404,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ // Create pick list
+ const pickListId = `PL-${nanoid(10)}`;
+ const { error: pickListError } = await client.from("pickList").insert({
+ id: pickListId,
+ locationId,
+ status: "Draft",
+ companyId,
+ createdBy: userId,
+ });
+
+ if (pickListError) {
+ return new Response(
+ JSON.stringify({ error: "Failed to create pick list" }),
+ {
+ status: 500,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ // Aggregate materials from all jobs
+ const pickListLines = [];
+ for (const job of jobs) {
+ const { data: jobMaterials } = await client
+ .from("jobMaterial")
+ .select("*")
+ .eq("jobId", job.id)
+ .eq("companyId", companyId);
+
+ for (const material of jobMaterials || []) {
+ if (material.shelfId || job.shelfId) {
+ pickListLines.push({
+ id: `PLL-${nanoid(10)}`,
+ pickListId,
+ jobId: job.id,
+ jobMaterialId: material.id,
+ itemId: material.itemId,
+ fromShelfId: material.shelfId,
+ toShelfId: job.shelfId,
+ quantity: material.quantity,
+ pickedQuantity: 0,
+ companyId,
+ createdBy: userId,
+ });
+ }
+ }
+ }
+
+ if (pickListLines.length > 0) {
+ const { error: linesError } = await client
+ .from("pickListLine")
+ .insert(pickListLines);
+
+ if (linesError) {
+ return new Response(
+ JSON.stringify({ error: "Failed to create pick list lines" }),
+ {
+ status: 500,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+ }
+
+ return new Response(
+ JSON.stringify({
+ success: true,
+ pickListId,
+ linesCreated: pickListLines.length,
+ }),
+ {
+ status: 200,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ case "executePick": {
+ const { pickListLineId, pickedQuantity } = payload;
+
+ return await db.transaction().execute(async (trx) => {
+ // Get the pick list line
+ const { data: pickListLine, error: lineError } = await client
+ .from("pickListLine")
+ .select("*, pickList:pickListId(locationId)")
+ .eq("id", pickListLineId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (lineError || !pickListLine) {
+ return new Response(
+ JSON.stringify({ error: "Pick list line not found" }),
+ {
+ status: 404,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ // Update picked quantity
+ const { error: updateError } = await client
+ .from("pickListLine")
+ .update({
+ pickedQuantity,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .eq("id", pickListLineId)
+ .eq("companyId", companyId);
+
+ if (updateError) {
+ return new Response(
+ JSON.stringify({ error: "Failed to update pick list line" }),
+ {
+ status: 500,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ // Create item ledger entry for the transfer
+ if (pickListLine.fromShelfId && pickListLine.toShelfId) {
+ const ledgerSequence = await getNextSequence(
+ trx,
+ "itemLedger",
+ companyId
+ );
+
+ await trx
+ .insertInto("itemLedger")
+ .values({
+ id: `IL-${ledgerSequence}`,
+ companyId,
+ entryType: "Transfer",
+ documentType: "Pick Transfer",
+ documentId: pickListLineId,
+ itemId: pickListLine.itemId,
+ locationId: pickListLine.pickList?.locationId,
+ shelfId: pickListLine.fromShelfId,
+ quantity: -pickedQuantity,
+ postingDate: new Date(),
+ createdBy: userId,
+ })
+ .execute();
+
+ await trx
+ .insertInto("itemLedger")
+ .values({
+ id: `IL-${ledgerSequence + 1}`,
+ companyId,
+ entryType: "Transfer",
+ documentType: "Pick Transfer",
+ documentId: pickListLineId,
+ itemId: pickListLine.itemId,
+ locationId: pickListLine.pickList?.locationId,
+ shelfId: pickListLine.toShelfId,
+ quantity: pickedQuantity,
+ postingDate: new Date(),
+ createdBy: userId,
+ })
+ .execute();
+ }
+
+ return new Response(
+ JSON.stringify({
+ success: true,
+ pickListLineId,
+ pickedQuantity,
+ }),
+ {
+ status: 200,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ });
+ }
+
+ case "completePickList": {
+ const { pickListId } = payload;
+
+ // Verify all lines are fully picked
+ const { data: lines, error: linesError } = await client
+ .from("pickListLine")
+ .select("id, quantity, pickedQuantity")
+ .eq("pickListId", pickListId)
+ .eq("companyId", companyId);
+
+ if (linesError) {
+ return new Response(
+ JSON.stringify({ error: "Failed to fetch pick list lines" }),
+ {
+ status: 500,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ const incomplete = lines?.filter(
+ (line) => line.pickedQuantity < line.quantity
+ );
+
+ if (incomplete && incomplete.length > 0) {
+ return new Response(
+ JSON.stringify({
+ error: "Not all lines are fully picked",
+ incompleteLines: incomplete.length,
+ }),
+ {
+ status: 400,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ // Update pick list status
+ const { error: updateError } = await client
+ .from("pickList")
+ .update({
+ status: "Completed",
+ completedDate: new Date().toISOString(),
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .eq("id", pickListId)
+ .eq("companyId", companyId);
+
+ if (updateError) {
+ return new Response(
+ JSON.stringify({ error: "Failed to complete pick list" }),
+ {
+ status: 500,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ return new Response(
+ JSON.stringify({
+ success: true,
+ pickListId,
+ }),
+ {
+ status: 200,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ default:
+ return new Response(
+ JSON.stringify({ error: "Invalid operation type" }),
+ {
+ status: 400,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+ } catch (error) {
+ console.error("Error in pick:", error);
+ return new Response(
+ JSON.stringify({
+ error: error instanceof Error ? error.message : "Unknown error",
+ }),
+ {
+ status: 500,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+});
diff --git a/packages/database/supabase/migrations/20251007014240_pick-lists.sql b/packages/database/supabase/migrations/20251007014240_pick-lists.sql
new file mode 100644
index 0000000000..44e7e59862
--- /dev/null
+++ b/packages/database/supabase/migrations/20251007014240_pick-lists.sql
@@ -0,0 +1,155 @@
+-- Add shelfId to methodMaterial table for pick-from location
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_name = 'methodMaterial' AND column_name = 'shelfId'
+ ) THEN
+ ALTER TABLE "methodMaterial" ADD COLUMN "shelfId" TEXT;
+ ALTER TABLE "methodMaterial" ADD CONSTRAINT "methodMaterial_shelfId_fkey"
+ FOREIGN KEY ("shelfId") REFERENCES "shelf" ("id") ON DELETE SET NULL ON UPDATE CASCADE;
+ END IF;
+END $$;
+
+-- Add shelfId to jobMaterial table for pick-from location
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_name = 'jobMaterial' AND column_name = 'shelfId'
+ ) THEN
+ ALTER TABLE "jobMaterial" ADD COLUMN "shelfId" TEXT;
+ ALTER TABLE "jobMaterial" ADD CONSTRAINT "jobMaterial_shelfId_fkey"
+ FOREIGN KEY ("shelfId") REFERENCES "shelf" ("id") ON DELETE SET NULL ON UPDATE CASCADE;
+ END IF;
+END $$;
+
+-- Update jobMaterialWithMakeMethodId view to include shelfId
+DROP VIEW IF EXISTS "jobMaterialWithMakeMethodId";
+CREATE OR REPLACE VIEW "jobMaterialWithMakeMethodId" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ jm.*,
+ jmm."id" AS "jobMaterialMakeMethodId",
+ jmm.version AS "version",
+ i."readableIdWithRevision" as "itemReadableId",
+ i."readableId" as "itemReadableIdWithoutRevision"
+ FROM "jobMaterial" jm
+ LEFT JOIN "jobMakeMethod" jmm
+ ON jmm."parentMaterialId" = jm."id"
+ INNER JOIN "item" i ON i.id = jm."itemId";
+
+-- Add Staged status to job status enum
+DO $$
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_type t
+ JOIN pg_enum e ON t.oid = e.enumtypid
+ WHERE t.typname = 'jobStatus' AND e.enumlabel = 'Staged') THEN
+ -- Add 'Staged' value after 'Draft' in the enum
+ ALTER TYPE "jobStatus" ADD VALUE 'Staged' AFTER 'Draft';
+ END IF;
+END $$;
+
+-- Create pick list status enum
+CREATE TYPE "pickListStatus" AS ENUM (
+ 'Draft',
+ 'Released',
+ 'In Progress',
+ 'Completed'
+);
+
+-- Create pickList table
+CREATE TABLE "pickList" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "locationId" TEXT NOT NULL,
+ "status" "pickListStatus" NOT NULL DEFAULT 'Draft',
+ "createdDate" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+ "completedDate" TIMESTAMP WITH TIME ZONE,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "pickList_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "pickList_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "pickList_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "pickList_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "pickList_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+CREATE INDEX "pickList_locationId_idx" ON "pickList" ("locationId");
+CREATE INDEX "pickList_status_idx" ON "pickList" ("status");
+
+-- Create pickListLine table
+CREATE TABLE "pickListLine" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "pickListId" TEXT NOT NULL,
+ "jobId" TEXT,
+ "jobMaterialId" TEXT,
+ "itemId" TEXT NOT NULL,
+ "fromShelfId" TEXT,
+ "toShelfId" TEXT,
+ "quantity" NUMERIC(10, 4) NOT NULL DEFAULT 0,
+ "pickedQuantity" NUMERIC(10, 4) NOT NULL DEFAULT 0,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "pickListLine_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "pickListLine_pickListId_fkey" FOREIGN KEY ("pickListId", "companyId") REFERENCES "pickList" ("id", "companyId") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "pickListLine_jobId_fkey" FOREIGN KEY ("jobId") REFERENCES "job" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "pickListLine_jobMaterialId_fkey" FOREIGN KEY ("jobMaterialId") REFERENCES "jobMaterial" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "pickListLine_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "pickListLine_fromShelfId_fkey" FOREIGN KEY ("fromShelfId") REFERENCES "shelf" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "pickListLine_toShelfId_fkey" FOREIGN KEY ("toShelfId") REFERENCES "shelf" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "pickListLine_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "pickListLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "pickListLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+CREATE INDEX "pickListLine_pickListId_idx" ON "pickListLine" ("pickListId");
+CREATE INDEX "pickListLine_jobId_idx" ON "pickListLine" ("jobId");
+CREATE INDEX "pickListLine_itemId_idx" ON "pickListLine" ("itemId");
+
+-- Extend itemLedger documentType enum with pick and transfer types
+DO $$
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_type t
+ JOIN pg_enum e ON t.oid = e.enumtypid
+ WHERE t.typname = 'documentType' AND e.enumlabel = 'Pick Transfer') THEN
+ ALTER TYPE "documentType" ADD VALUE 'Pick Transfer';
+ END IF;
+
+ IF NOT EXISTS (SELECT 1 FROM pg_type t
+ JOIN pg_enum e ON t.oid = e.enumtypid
+ WHERE t.typname = 'documentType' AND e.enumlabel = 'Vehicle Transfer') THEN
+ ALTER TYPE "documentType" ADD VALUE 'Vehicle Transfer';
+ END IF;
+
+ IF NOT EXISTS (SELECT 1 FROM pg_type t
+ JOIN pg_enum e ON t.oid = e.enumtypid
+ WHERE t.typname = 'documentType' AND e.enumlabel = 'Scrap Transfer') THEN
+ ALTER TYPE "documentType" ADD VALUE 'Scrap Transfer';
+ END IF;
+
+ IF NOT EXISTS (SELECT 1 FROM pg_type t
+ JOIN pg_enum e ON t.oid = e.enumtypid
+ WHERE t.typname = 'documentType' AND e.enumlabel = 'Quarantine Transfer') THEN
+ ALTER TYPE "documentType" ADD VALUE 'Quarantine Transfer';
+ END IF;
+
+ IF NOT EXISTS (SELECT 1 FROM pg_type t
+ JOIN pg_enum e ON t.oid = e.enumtypid
+ WHERE t.typname = 'documentType' AND e.enumlabel = 'Customer Transfer') THEN
+ ALTER TYPE "documentType" ADD VALUE 'Customer Transfer';
+ END IF;
+
+ IF NOT EXISTS (SELECT 1 FROM pg_type t
+ JOIN pg_enum e ON t.oid = e.enumtypid
+ WHERE t.typname = 'documentType' AND e.enumlabel = 'Rejection Transfer') THEN
+ ALTER TYPE "documentType" ADD VALUE 'Rejection Transfer';
+ END IF;
+END $$;
+
diff --git a/packages/database/supabase/migrations/20251007014346_update-job-method-rpcs-with-shelf.sql b/packages/database/supabase/migrations/20251007014346_update-job-method-rpcs-with-shelf.sql
new file mode 100644
index 0000000000..33d9e15128
--- /dev/null
+++ b/packages/database/supabase/migrations/20251007014346_update-job-method-rpcs-with-shelf.sql
@@ -0,0 +1,177 @@
+-- Update get_job_methods_by_method_id to include shelfId
+DROP FUNCTION IF EXISTS get_job_methods_by_method_id;
+CREATE OR REPLACE FUNCTION get_job_methods_by_method_id(mid TEXT)
+RETURNS TABLE (
+ "jobId" TEXT,
+ "methodMaterialId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "jobMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "kit" BOOLEAN,
+ "isRoot" BOOLEAN,
+ "shelfId" TEXT
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "jobId",
+ "id",
+ "id" AS "jobMakeMethodId",
+ 'Make'::"methodType" AS "methodType",
+ "id" AS "jobMaterialMakeMethodId",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC AS "quantity",
+ 0::NUMERIC AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ FALSE AS "kit",
+ TRUE AS "isRoot",
+ NULL::TEXT AS "shelfId"
+ FROM
+ "jobMakeMethod"
+ WHERE
+ "id" = mid
+ UNION
+ SELECT
+ child."jobId",
+ child."id",
+ child."jobMakeMethodId",
+ child."methodType",
+ child."jobMaterialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ child."kit",
+ FALSE AS "isRoot",
+ child."shelfId"
+ FROM
+ "jobMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."jobMaterialMakeMethodId" = child."jobMakeMethodId"
+ WHERE parent."methodType" = 'Make'
+)
+SELECT
+ material."jobId",
+ material.id as "methodMaterialId",
+ material."jobMakeMethodId",
+ material."jobMaterialMakeMethodId",
+ material."itemId",
+ item."readableId" AS "itemReadableId",
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."kit",
+ material."isRoot",
+ material."shelfId"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+-- Update get_job_method to include shelfId
+DROP FUNCTION IF EXISTS get_job_method;
+CREATE OR REPLACE FUNCTION get_job_method(jid TEXT)
+RETURNS TABLE (
+ "jobId" TEXT,
+ "methodMaterialId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "jobMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN,
+ "revision" TEXT,
+ "version" NUMERIC(10,2),
+ "shelfId" TEXT
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "jobId",
+ "id",
+ "id" AS "jobMakeMethodId",
+ 'Make'::"methodType" AS "methodType",
+ "id" AS "jobMaterialMakeMethodId",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC AS "quantity",
+ 0::NUMERIC AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot",
+ FALSE AS "kit",
+ "version",
+ NULL::TEXT AS "shelfId"
+ FROM
+ "jobMakeMethod"
+ WHERE
+ "jobId" = jid
+ AND "parentMaterialId" IS NULL
+ UNION
+ SELECT
+ child."jobId",
+ child."id",
+ child."jobMakeMethodId",
+ child."methodType",
+ child."jobMaterialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ FALSE AS "isRoot",
+ child."kit",
+ child."version",
+ child."shelfId"
+ FROM
+ "jobMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."jobMaterialMakeMethodId" = child."jobMakeMethodId"
+ WHERE parent."methodType" = 'Make'
+)
+SELECT
+ material."jobId",
+ material.id as "methodMaterialId",
+ material."jobMakeMethodId",
+ material."jobMaterialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."name" AS "description",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot",
+ material."kit",
+ item."revision",
+ material."version",
+ material."shelfId"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+WHERE material."jobId" = jid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;