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: issue parts from the shelf specified in the job bill of material

Brad Barbin9fcf842f3c55
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
index b75be45e78..d4afa4d38d 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
@@ -8,6 +8,8 @@ const getActivityText = (ledgerRecord: ItemLedger) => {
switch (ledgerRecord.documentType) {
case "Purchase Receipt":
return `received ${ledgerRecord.quantity} units${
+ ledgerRecord.shelf?.name ? ` to ${ledgerRecord.shelf.name}` : ""
+ }${
ledgerRecord.trackedEntityId
? ` from ${
Math.abs(ledgerRecord.quantity) > 1 ? "batch" : "serial"
@@ -15,9 +17,13 @@ const getActivityText = (ledgerRecord: ItemLedger) => {
: ""
}`;
case "Purchase Invoice":
- return `invoiced ${ledgerRecord.quantity} units`;
+ return `invoiced ${ledgerRecord.quantity} units${
+ ledgerRecord.shelf?.name ? ` on ${ledgerRecord.shelf.name}` : ""
+ }`;
case "Sales Shipment":
return `shipped ${-1 * ledgerRecord.quantity} units${
+ ledgerRecord.shelf?.name ? ` from ${ledgerRecord.shelf.name}` : ""
+ }${
ledgerRecord.trackedEntityId
? ` of ${Math.abs(ledgerRecord.quantity) > 1 ? "batch" : "serial"} ${
ledgerRecord.trackedEntityId
@@ -25,7 +31,9 @@ const getActivityText = (ledgerRecord: ItemLedger) => {
: ""
}`;
case "Sales Invoice":
- return `invoiced ${ledgerRecord.quantity} units for sale`;
+ return `invoiced ${ledgerRecord.quantity} units for sale${
+ ledgerRecord.shelf?.name ? ` from ${ledgerRecord.shelf.name}` : ""
+ }`;
case "Transfer Shipment":
return `shipped ${-1 * ledgerRecord.quantity} units${
ledgerRecord.shelf?.name ? ` from ${ledgerRecord.shelf.name}` : ""
@@ -39,29 +47,50 @@ const getActivityText = (ledgerRecord: ItemLedger) => {
ledgerRecord.shelf?.name ? ` to ${ledgerRecord.shelf.name}` : ""
}`;
case "Inventory Receipt":
- return `received ${ledgerRecord.quantity} units into inventory`;
+ return `received ${ledgerRecord.quantity} units into inventory${
+ ledgerRecord.shelf?.name ? ` on ${ledgerRecord.shelf.name}` : ""
+ }`;
case "Inventory Shipment":
- return `shipped ${-1 * ledgerRecord.quantity} units from inventory`;
+ return `shipped ${-1 * ledgerRecord.quantity} units from inventory${
+ ledgerRecord.shelf?.name ? ` from ${ledgerRecord.shelf.name}` : ""
+ }`;
case "Posted Assembly":
- return `assembled ${ledgerRecord.quantity} units`;
+ return `assembled ${ledgerRecord.quantity} units${
+ ledgerRecord.shelf?.name ? ` on ${ledgerRecord.shelf.name}` : ""
+ }`;
case "Purchase Credit Memo":
- return `credited ${ledgerRecord.quantity} units for purchase`;
+ return `credited ${ledgerRecord.quantity} units for purchase${
+ ledgerRecord.shelf?.name ? ` on ${ledgerRecord.shelf.name}` : ""
+ }`;
case "Purchase Return Shipment":
- return `returned ${ledgerRecord.quantity} units to supplier`;
+ return `returned ${ledgerRecord.quantity} units to supplier${
+ ledgerRecord.shelf?.name ? ` from ${ledgerRecord.shelf.name}` : ""
+ }`;
case "Sales Credit Memo":
- return `credited ${ledgerRecord.quantity} units for sale`;
+ return `credited ${ledgerRecord.quantity} units for sale${
+ ledgerRecord.shelf?.name ? ` on ${ledgerRecord.shelf.name}` : ""
+ }`;
case "Sales Return Receipt":
- return `received ${ledgerRecord.quantity} units as sales return`;
+ return `received ${ledgerRecord.quantity} units as sales return${
+ ledgerRecord.shelf?.name ? ` to ${ledgerRecord.shelf.name}` : ""
+ }`;
case "Service Credit Memo":
- return `credited ${ledgerRecord.quantity} units for service`;
+ return `credited ${ledgerRecord.quantity} units for service${
+ ledgerRecord.shelf?.name ? ` on ${ledgerRecord.shelf.name}` : ""
+ }`;
case "Service Invoice":
- return `invoiced ${ledgerRecord.quantity} units for service`;
+ return `invoiced ${ledgerRecord.quantity} units for service${
+ ledgerRecord.shelf?.name ? ` from ${ledgerRecord.shelf.name}` : ""
+ }`;
case "Service Shipment":
- return `shipped ${-1 * ledgerRecord.quantity} units for service`;
+ return `shipped ${-1 * ledgerRecord.quantity} units for service${
+ ledgerRecord.shelf?.name ? ` from ${ledgerRecord.shelf.name}` : ""
+ }`;
case "Job Consumption":
return (
<span>
issued {-1 * ledgerRecord.quantity} units{" "}
+ {ledgerRecord.shelf?.name ? `from ${ledgerRecord.shelf.name} ` : ""}
{ledgerRecord.trackedEntityId ? (
<>
from {Math.abs(ledgerRecord.quantity) > 1 ? "batch" : "serial"}{" "}
@@ -96,7 +125,11 @@ const getActivityText = (ledgerRecord: ItemLedger) => {
case "Job Receipt":
return (
<>
- <span>received {ledgerRecord.quantity} units from a</span>{" "}
+ <span>
+ received {ledgerRecord.quantity} units
+ {ledgerRecord.shelf?.name ? ` to ${ledgerRecord.shelf.name}` : ""}{" "}
+ from a
+ </span>{" "}
<Hyperlink
className="inline-flex"
to={path.to.jobDetails(ledgerRecord.documentId!)}
diff --git a/apps/erp/app/modules/quality/ui/Gauge/GaugeForm.tsx b/apps/erp/app/modules/quality/ui/Gauge/GaugeForm.tsx
index 9fdb682a23..63506f39ce 100644
--- a/apps/erp/app/modules/quality/ui/Gauge/GaugeForm.tsx
+++ b/apps/erp/app/modules/quality/ui/Gauge/GaugeForm.tsx
@@ -370,7 +370,7 @@ function GaugeFormContent({
value: type.id,
}))}
/>
- <Supplier name="supplierId" label="Supplier" />
+ <Supplier name="supplierId" label="Manufacturer" />
<Input name="modelNumber" label="Model Number" />
<Input name="serialNumber" label="Serial Number" />
{/* <Select
diff --git a/apps/erp/app/modules/quality/ui/Gauge/GaugesTable.tsx b/apps/erp/app/modules/quality/ui/Gauge/GaugesTable.tsx
index d6364167f7..d23e803532 100644
--- a/apps/erp/app/modules/quality/ui/Gauge/GaugesTable.tsx
+++ b/apps/erp/app/modules/quality/ui/Gauge/GaugesTable.tsx
@@ -101,7 +101,7 @@ const GaugesTable = memo(({ data, types, count }: GaugesTableProps) => {
},
{
id: "supplierId",
- header: "Supplier",
+ header: "Manufacturer",
cell: ({ row }) => {
return <SupplierAvatar supplierId={row.original.supplierId} />;
},
diff --git a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx
index 112c1aaa3d..a0e27aca1e 100644
--- a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx
+++ b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx
@@ -6,6 +6,7 @@ import type { LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { useCallback, useState } from "react";
import InfiniteScroll from "~/components/InfiniteScroll";
+import type { ItemLedger } from "~/modules/inventory";
import { getItemLedgerPage, InventoryActivity } from "~/modules/inventory";
import { getLocationsList } from "~/modules/resources";
import { getUserDefaults } from "~/modules/users/users.server";
@@ -83,7 +84,8 @@ export default function ItemInventoryActivityRoute() {
const { carbon } = useCarbon();
- const [itemLedgers, setItemLedgers] = useState<any[]>(initialItemLedgers);
+ const [itemLedgers, setItemLedgers] =
+ useState<ItemLedger[]>(initialItemLedgers);
const [page, setPage] = useState(1);
const [isLoading, setIsLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
diff --git a/apps/mes/app/components/Icons.tsx b/apps/mes/app/components/Icons.tsx
index 30df9e4071..0ef278b5c6 100644
--- a/apps/mes/app/components/Icons.tsx
+++ b/apps/mes/app/components/Icons.tsx
@@ -200,7 +200,7 @@ export function OperationStatusIcon({
return <TodoStatusIcon className="text-blue-600" />;
case "Waiting":
case "Canceled":
- return <LuCircleX className="text-muted-foreground" />;
+ return <LuCircleX className="text-red-600" />;
case "Done":
return <LuCircleCheck className="text-green-600" />;
case "In Progress":
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index df515f91ab..50910efc26 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -78,6 +78,7 @@ import { flushSync } from "react-dom";
import { FaTasks } from "react-icons/fa";
import { FaCheck, FaPlus, FaTrash } from "react-icons/fa6";
import {
+ LuArrowLeft,
LuAxis3D,
LuBarcode,
LuCheck,
@@ -88,6 +89,7 @@ import {
LuDownload,
LuEllipsisVertical,
LuGitBranchPlus,
+ LuGitPullRequest,
LuHammer,
LuHardHat,
LuPrinter,
@@ -806,7 +808,7 @@ export const JobOperation = ({
<Thead>
<Tr>
<Th>Part</Th>
- <Th className="lg:table-cell hidden">Method</Th>
+ <Th className="lg:table-cell hidden">Source</Th>
<Th>Estimated</Th>
<Th>Actual</Th>
<Th className="text-right" />
@@ -882,7 +884,7 @@ export const JobOperation = ({
) : null}
</HStack>
</Td>
- <Td className="lg:table-cell hidden">
+ <Td className="flex flex-row items-center gap-1">
<Badge variant="secondary">
<MethodIcon
type={material.methodType ?? ""}
@@ -894,6 +896,20 @@ export const JobOperation = ({
? "Kit"
: material.methodType}
</Badge>
+ <LuArrowLeft
+ className={cn(
+ material.methodType === "Make"
+ ? "rotate-180"
+ : ""
+ )}
+ />
+ <Badge variant="secondary">
+ <LuGitPullRequest className="size-3 mr-1" />
+ {material.shelfName ??
+ (material.methodType === "Make"
+ ? "WIP"
+ : "Default Shelf")}
+ </Badge>
</Td>
<Td>
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 9036bf118c..5f7b0e6b21 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -39085,6 +39085,7 @@ export type Database = {
requiresSerialTracking: boolean | null
scrapQuantity: number | null
shelfId: string | null
+ shelfName: string | null
unitCost: number | null
unitOfMeasureCode: string | null
updatedAt: string | null
@@ -42858,14 +42859,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index ea76b7f4bc..b339db08b0 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -29,6 +29,7 @@ import {
traverseQuoteMethod,
} from "../lib/methods.ts";
import { importTypeScript } from "../lib/sandbox.ee.ts";
+import { getShelfId } from "../lib/shelves.ts";
import {
getNextRevisionSequence,
getNextSequence,
@@ -768,9 +769,14 @@ serve(async (req: Request) => {
description,
quantity,
shelfId: locationId
- ? // @ts-ignore
- (child.data.shelfIds?.[locationId] as string) || null
- : null,
+ ? await getShelfId(
+ trx,
+ child.data.itemId,
+ locationId,
+ // @ts-ignore
+ child.data.shelfIds?.[locationId] as string
+ )
+ : undefined,
requiresSerialTracking,
requiresBatchTracking,
unitOfMeasureCode,
@@ -1127,7 +1133,9 @@ serve(async (req: Request) => {
) ?? {};
}
- const mapMethodMaterialToJobMaterial = (child: MethodTreeItem) => ({
+ const mapMethodMaterialToJobMaterial = async (
+ child: MethodTreeItem
+ ) => ({
jobId: jobMakeMethod.data?.jobId!,
jobMakeMethodId: parentJobMakeMethodId!,
jobOperationId:
@@ -1143,26 +1151,32 @@ serve(async (req: Request) => {
requiresSerialTracking: child.data.itemTrackingType === "Serial",
unitOfMeasureCode: child.data.unitOfMeasureCode,
unitCost: child.data.unitCost,
- // @ts-ignore
- shelfId: child.data.shelfIds?.[job.data.locationId] || null,
+ shelfId: await getShelfId(
+ trx,
+ child.data.itemId,
+ job.data?.locationId ?? "",
+ // @ts-ignore
+ child.data.shelfIds?.[job.data.locationId] ?? undefined
+ ),
companyId,
createdBy: userId,
customFields: {},
});
- const madeChildren = node.children.filter(
- (child) => child.data.methodType === "Make"
- );
- const unmadeChildren = node.children.filter(
- (child) => child.data.methodType !== "Make"
- );
+ const madeMaterials: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =
+ [];
+ const pickedOrBoughtMaterials: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =
+ [];
+
+ for await (const child of node.children) {
+ const material = await mapMethodMaterialToJobMaterial(child);
+ if (child.data.methodType === "Make") {
+ madeMaterials.push(material);
+ } else {
+ pickedOrBoughtMaterials.push(material);
+ }
+ }
- const madeMaterials = madeChildren.map(
- mapMethodMaterialToJobMaterial
- );
- const pickedOrBoughtMaterials = unmadeChildren.map(
- mapMethodMaterialToJobMaterial
- );
if (madeMaterials.length > 0) {
const madeMaterialIds = await trx
.insertInto("jobMaterial")
@@ -1189,7 +1203,9 @@ serve(async (req: Request) => {
});
// Use proper correlation instead of index-based assumption
- for (const [index, child] of madeChildren.entries()) {
+ for (const [index, child] of node.children
+ .filter((child) => child.data.methodType === "Make")
+ .entries()) {
const materialId = madeMaterialIds[index]?.id;
const jobMakeMethodId = materialId
? materialIdToJobMakeMethodId[materialId]
@@ -3654,11 +3670,18 @@ serve(async (req: Request) => {
}
const [
+ job,
jobMakeMethod,
quoteMakeMethod,
quoteMaterials,
quoteOperations,
] = await Promise.all([
+ client
+ .from("job")
+ .select("locationId")
+ .eq("id", jobId)
+ .eq("companyId", companyId)
+ .single(),
client
.from("jobMakeMethod")
.select("*")
@@ -3687,6 +3710,10 @@ serve(async (req: Request) => {
.eq("companyId", companyId),
]);
+ if (job.error) {
+ throw new Error("Failed to get job");
+ }
+
if (jobMakeMethod.error || !jobMakeMethod.data) {
throw new Error("Failed to get job make method");
}
@@ -3768,7 +3795,12 @@ serve(async (req: Request) => {
child.data.quoteMakeMethodId
],
quantity: child.data.quantity,
- shelfId: child.data.shelfId,
+ shelfId: await getShelfId(
+ trx,
+ child.data.itemId,
+ job.data.locationId,
+ child.data.shelfId
+ ),
requiresBatchTracking:
child.data.itemTrackingType === "Batch",
requiresSerialTracking:
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index c966c8444e..47553aa270 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -4,8 +4,11 @@ import { z } from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";
-import { Transaction } from "https://esm.sh/v135/[email protected]/dist/cjs/kysely.d.ts";
import { corsHeaders } from "../lib/headers.ts";
+import {
+ getShelfWithHighestQuantity,
+ updatePickMethodDefaultShelfIfNeeded,
+} from "../lib/shelves.ts";
import { getSupabaseServiceRole } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
import { TrackedEntityAttributes } from "../lib/utils.ts";
@@ -332,20 +335,6 @@ serve(async (req: Request) => {
}
if (materialsToIssue.length > 0) {
- const itemIds = new Set(
- materialsToIssue.map((material) => material.itemId)
- );
- const itemIdsWithDefaultShelf = new Set(
- materialsToIssue
- .filter((material) => material.defaultShelf)
- .map((material) => material.itemId)
- );
- const itemIdsWithoutDefaultShelf = new Set(
- materialsToIssue
- .filter((material) => !material.defaultShelf)
- .map((material) => material.itemId)
- );
-
const jobId = materialsToIssue[0].jobId;
const [job, items] = await Promise.all([
@@ -356,7 +345,11 @@ serve(async (req: Request) => {
.executeTakeFirst(),
trx
.selectFrom("item")
- .where("id", "in", Array.from(itemIds))
+ .where(
+ "id",
+ "in",
+ materialsToIssue.map((material) => material.itemId)
+ )
.select(["id", "item.itemTrackingType"])
.execute(),
]);
@@ -365,55 +358,6 @@ serve(async (req: Request) => {
throw new Error("Job location is required");
}
- const pickMethods = await trx
- .selectFrom("pickMethod")
- .select(["itemId", "defaultShelfId"])
- .where("itemId", "in", Array.from(itemIdsWithDefaultShelf))
- .where("locationId", "=", job?.locationId!)
- .where("companyId", "=", companyId)
- .execute();
-
- // For items without defaultShelf, find the shelf with the last positive adjustment
- const shelfIdsForItemsWithoutDefault = new Map<
- string,
- string | null
- >();
-
- if (itemIdsWithoutDefaultShelf.size > 0) {
- for (const itemId of itemIdsWithoutDefaultShelf) {
- const shelfId = await getShelfWithHighestQuantity(
- trx,
- itemId,
- job?.locationId!
- );
- shelfIdsForItemsWithoutDefault.set(itemId, shelfId);
- }
- }
-
- const shelfIdsToUse = new Map(
- pickMethods.map((pickMethod) => [
- pickMethod.itemId,
- pickMethod.defaultShelfId,
- ])
- );
-
- // Handle items with defaultShelf=true but null defaultShelfId
- for (const pickMethod of pickMethods) {
- if (pickMethod.defaultShelfId === null) {
- const shelfId = await getShelfWithHighestQuantity(
- trx,
- pickMethod.itemId,
- job?.locationId!
- );
- shelfIdsToUse.set(pickMethod.itemId, shelfId);
- }
- }
-
- // Add shelf IDs for items without default shelf
- for (const [itemId, shelfId] of shelfIdsForItemsWithoutDefault) {
- shelfIdsToUse.set(itemId, shelfId);
- }
-
const itemIdIsTracked = new Map(
items.map((item) => [
item.id,
@@ -426,8 +370,39 @@ serve(async (req: Request) => {
// Calculate the quantity to issue based on payload quantity multiplied by the material quantity
const quantityToIssue = Number(material.quantity) * quantity;
- const proposedShelfId =
- shelfIdsToUse.get(material.itemId) ?? material.shelfId;
+ // Determine shelf to use - prioritize material.shelfId, then fetch if needed
+ let proposedShelfId = material.shelfId;
+
+ if (!proposedShelfId) {
+ if (material.defaultShelf) {
+ // Fetch pick method default shelf
+ const pickMethod = await trx
+ .selectFrom("pickMethod")
+ .where("itemId", "=", material.itemId)
+ .where("locationId", "=", job?.locationId!)
+ .where("companyId", "=", companyId)
+ .select("defaultShelfId")
+ .executeTakeFirst();
+
+ proposedShelfId = pickMethod?.defaultShelfId;
+
+ // If defaultShelfId is null, get shelf with highest quantity
+ if (!proposedShelfId) {
+ proposedShelfId = await getShelfWithHighestQuantity(
+ trx,
+ material.itemId,
+ job?.locationId!
+ );
+ }
+ } else {
+ // Get shelf with highest quantity
+ proposedShelfId = await getShelfWithHighestQuantity(
+ trx,
+ material.itemId,
+ job?.locationId!
+ );
+ }
+ }
// Get current quantity on this shelf for diagnostics
const currentShelfQuantity = await trx
@@ -466,7 +441,7 @@ serve(async (req: Request) => {
? current
: best
);
- finalShelfId = bestShelf.shelfId;
+ finalShelfId = bestShelf.shelfId ?? null;
}
const isTracked = itemIdIsTracked.get(material.itemId);
@@ -803,7 +778,10 @@ serve(async (req: Request) => {
.executeTakeFirst();
let shelfId: string | null | undefined;
- if (material?.defaultShelf) {
+ // Prioritize material.shelfId if available
+ if (material?.shelfId) {
+ shelfId = material.shelfId;
+ } else if (material?.defaultShelf) {
const pickMethod = await trx
.selectFrom("pickMethod")
.where("itemId", "=", itemId)
@@ -812,13 +790,11 @@ serve(async (req: Request) => {
.executeTakeFirst();
shelfId = pickMethod?.defaultShelfId;
} else {
- shelfId =
- material?.shelfId ??
- (await getShelfWithHighestQuantity(
- trx,
- itemId,
- job?.locationId!
- ));
+ shelfId = await getShelfWithHighestQuantity(
+ trx,
+ itemId,
+ job?.locationId!
+ );
}
const quantityToIssue =
@@ -2049,83 +2025,3 @@ serve(async (req: Request) => {
});
}
});
-
-// Utility function to get the shelf with the highest quantity
-async function getShelfWithHighestQuantity(
- trx: Transaction<DB>,
- itemId: string,
- locationId: string
-): Promise<string | null> {
- const shelfWithHighestQuantity = await trx
- .selectFrom("itemLedger")
- .where("itemId", "=", itemId)
- .where("locationId", "=", locationId)
- .where("shelfId", "is not", null)
- .groupBy("shelfId")
- .select(["shelfId", (eb) => eb.fn.sum("quantity").as("totalQuantity")])
- .having((eb) => eb.fn.sum("quantity"), ">", 0)
- .orderBy("totalQuantity", "desc")
- .executeTakeFirst();
-
- return shelfWithHighestQuantity?.shelfId ?? null;
-}
-
-// Utility function to update pickMethod defaultShelfId if this is the only non-null shelf
-async function updatePickMethodDefaultShelfIfNeeded(
- trx: Transaction<DB>,
- itemId: string,
- locationId: string | null | undefined,
- shelfId: string | null | undefined,
- companyId: string,
- userId: string
-): Promise<void> {
- // Only proceed if shelfId and locationId are not null
- if (!shelfId || !locationId) return;
-
- // Check if there are other non-null shelves for this item/location
- const otherShelves = await trx
- .selectFrom("itemLedger")
- .where("itemId", "=", itemId)
- .where("locationId", "=", locationId)
- .where("shelfId", "is not", null)
- .where("shelfId", "!=", shelfId)
- .select("shelfId")
- .executeTakeFirst();
-
- // If there are no other non-null shelves, update or insert pickMethod
- if (!otherShelves) {
- const existingPickMethod = await trx
- .selectFrom("pickMethod")
- .where("itemId", "=", itemId)
- .where("locationId", "=", locationId)
- .select("defaultShelfId")
- .executeTakeFirst();
-
- if (existingPickMethod) {
- // Update existing pickMethod
- await trx
- .updateTable("pickMethod")
- .set({
- defaultShelfId: shelfId,
- updatedBy: userId,
- updatedAt: new Date().toISOString(),
- })
- .where("itemId", "=", itemId)
- .where("locationId", "=", locationId)
- .execute();
- } else {
- // Insert new pickMethod
- await trx
- .insertInto("pickMethod")
- .values({
- itemId,
- locationId,
- defaultShelfId: shelfId,
- companyId,
- createdBy: userId,
- createdAt: new Date().toISOString(),
- })
- .execute();
- }
- }
-}
diff --git a/packages/database/supabase/functions/lib/shelves.ts b/packages/database/supabase/functions/lib/shelves.ts
new file mode 100644
index 0000000000..dfbaf45208
--- /dev/null
+++ b/packages/database/supabase/functions/lib/shelves.ts
@@ -0,0 +1,108 @@
+import { Transaction } from "https://esm.sh/v135/[email protected]/dist/cjs/kysely.d.ts";
+import { DB } from "../lib/database.ts";
+
+export async function getShelfId(
+ trx: Transaction<DB>,
+ itemId: string,
+ locationId: string,
+ shelfId?: string
+): Promise<string | undefined> {
+ if (shelfId) return shelfId;
+
+ const pickMethod = await trx
+ .selectFrom("pickMethod")
+ .where("itemId", "=", itemId)
+ .where("locationId", "=", locationId)
+ .select("defaultShelfId")
+ .executeTakeFirst();
+
+ if (pickMethod?.defaultShelfId) return pickMethod.defaultShelfId;
+
+ const shelfWithHighestQuantity = await getShelfWithHighestQuantity(
+ trx,
+ itemId,
+ locationId
+ );
+
+ return shelfWithHighestQuantity ?? undefined;
+}
+
+// Utility function to get the shelf with the highest quantity
+export async function getShelfWithHighestQuantity(
+ trx: Transaction<DB>,
+ itemId: string,
+ locationId: string
+): Promise<string | null> {
+ const shelfWithHighestQuantity = await trx
+ .selectFrom("itemLedger")
+ .where("itemId", "=", itemId)
+ .where("locationId", "=", locationId)
+ .where("shelfId", "is not", null)
+ .groupBy("shelfId")
+ .select(["shelfId", (eb) => eb.fn.sum("quantity").as("totalQuantity")])
+ .having((eb) => eb.fn.sum("quantity"), ">", 0)
+ .orderBy("totalQuantity", "desc")
+ .executeTakeFirst();
+
+ return shelfWithHighestQuantity?.shelfId ?? null;
+}
+
+// Utility function to update pickMethod defaultShelfId if this is the only non-null shelf
+export async function updatePickMethodDefaultShelfIfNeeded(
+ trx: Transaction<DB>,
+ itemId: string,
+ locationId: string | null | undefined,
+ shelfId: string | null | undefined,
+ companyId: string,
+ userId: string
+): Promise<void> {
+ // Only proceed if shelfId and locationId are not null
+ if (!shelfId || !locationId) return;
+
+ // Check if there are other non-null shelves for this item/location
+ const otherShelves = await trx
+ .selectFrom("itemLedger")
+ .where("itemId", "=", itemId)
+ .where("locationId", "=", locationId)
+ .where("shelfId", "is not", null)
+ .where("shelfId", "!=", shelfId)
+ .select("shelfId")
+ .executeTakeFirst();
+
+ // If there are no other non-null shelves, update or insert pickMethod
+ if (!otherShelves) {
+ const existingPickMethod = await trx
+ .selectFrom("pickMethod")
+ .where("itemId", "=", itemId)
+ .where("locationId", "=", locationId)
+ .select("defaultShelfId")
+ .executeTakeFirst();
+
+ if (existingPickMethod) {
+ // Update existing pickMethod
+ await trx
+ .updateTable("pickMethod")
+ .set({
+ defaultShelfId: shelfId,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .where("itemId", "=", itemId)
+ .where("locationId", "=", locationId)
+ .execute();
+ } else {
+ // Insert new pickMethod
+ await trx
+ .insertInto("pickMethod")
+ .values({
+ itemId,
+ locationId,
+ defaultShelfId: shelfId,
+ companyId,
+ createdBy: userId,
+ createdAt: new Date().toISOString(),
+ })
+ .execute();
+ }
+ }
+}
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 9036bf118c..5f7b0e6b21 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -39085,6 +39085,7 @@ export type Database = {
requiresSerialTracking: boolean | null
scrapQuantity: number | null
shelfId: string | null
+ shelfName: string | null
unitCost: number | null
unitOfMeasureCode: string | null
updatedAt: string | null
@@ -42858,14 +42859,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/migrations/20251007014240_pick-lists.sql b/packages/database/supabase/migrations/20251007014240_pick-lists.sql
index 3ce1d1ea0b..cfa98db81b 100644
--- a/packages/database/supabase/migrations/20251007014240_pick-lists.sql
+++ b/packages/database/supabase/migrations/20251007014240_pick-lists.sql
@@ -36,11 +36,12 @@ BEGIN
END IF;
END $$;
--- Update jobMaterialWithMakeMethodId view to include shelfId
+-- Update jobMaterialWithMakeMethodId view to include shelfId and shelfName
DROP VIEW IF EXISTS "jobMaterialWithMakeMethodId";
CREATE OR REPLACE VIEW "jobMaterialWithMakeMethodId" WITH(SECURITY_INVOKER=true) AS
SELECT
jm.*,
+ s."name" AS "shelfName",
jmm."id" AS "jobMaterialMakeMethodId",
jmm.version AS "version",
i."readableIdWithRevision" as "itemReadableId",
@@ -48,6 +49,7 @@ CREATE OR REPLACE VIEW "jobMaterialWithMakeMethodId" WITH(SECURITY_INVOKER=true)
FROM "jobMaterial" jm
LEFT JOIN "jobMakeMethod" jmm
ON jmm."parentMaterialId" = jm."id"
+ LEFT JOIN "shelf" s ON s.id = jm."shelfId"
INNER JOIN "item" i ON i.id = jm."itemId";