Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix: type for files fetcher

Brad Barbind9581ab81208
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index 8cb7bcd0e4..fe937668dd 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -343,7 +343,7 @@ function ReceiptLineItem({
onClick={splitDisclosure.onOpen}
>
<DropdownMenuIcon icon={<LuSplit />} />
- Split shipment line
+ Split receipt line
</DropdownMenuItem>
<DropdownMenuItem
destructive
@@ -351,7 +351,7 @@ function ReceiptLineItem({
onClick={deleteDisclosure.onOpen}
>
<DropdownMenuIcon icon={<LuTrash />} />
- Delete shipment line
+ Delete receipt line
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -429,7 +429,10 @@ function ReceiptLineItem({
</label>
<HStack className="justify-center">
<span className="text-sm py-1.5">
- {line.outstandingQuantity ?? 0}
+ {isReadOnly
+ ? (line.outstandingQuantity ?? 0) -
+ (line.receivedQuantity ?? 0)
+ : line.outstandingQuantity ?? 0}
</span>
{(line.receivedQuantity ?? 0) >
@@ -537,8 +540,8 @@ function ReceiptLineItem({
)}
{deleteDisclosure.isOpen && (
<ConfirmDelete
- name="Shipment Line"
- text="Are you sure you want to delete this shipment line?"
+ name="Receipt Line"
+ text="Are you sure you want to delete this receipt line?"
action={path.to.receiptLineDelete(line.id!)}
onCancel={deleteDisclosure.onClose}
onSubmit={deleteDisclosure.onClose}
@@ -1061,6 +1064,7 @@ function Shelf({
value={shelfId ?? undefined}
onChange={onChange}
disabled={isReadOnly}
+ isReadOnly={isReadOnly}
inline={ShelfPreview}
onCreateOption={(option) => {
newShelfModal.onOpen();
diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
index 53cdc2baf0..89337b44ce 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
@@ -79,12 +79,14 @@ export const ItemPlanningChart = ({
locationId,
plannedOrders = [],
safetyStock,
+ conversionFactor = 1,
}: {
compact?: boolean;
itemId: string;
locationId: string;
plannedOrders?: PlannedOrder[];
safetyStock?: number;
+ conversionFactor?: number;
}) => {
const forecastFetcher = useFetcher<typeof forecastLoader>();
const isFetching = forecastFetcher.state !== "idle" || !forecastFetcher.data;
@@ -142,8 +144,13 @@ export const ItemPlanningChart = ({
}
if (groupedData[periodId]) {
- groupedData[periodId]["Planned"] +=
+ // Convert purchase quantity to inventory quantity for display
+ // Inventory Quantity = Purchase Quantity × Conversion Factor
+ const purchaseQuantityDelta =
(order.quantity ?? 0) - (order.existingQuantity ?? 0);
+ const inventoryQuantityDelta = purchaseQuantityDelta * conversionFactor;
+
+ groupedData[periodId]["Planned"] += inventoryQuantityDelta;
}
});
@@ -197,7 +204,7 @@ export const ItemPlanningChart = ({
period.Projection = runningProjection;
return period;
});
- }, [forecastFetcher.data, plannedOrders]);
+ }, [forecastFetcher.data, plannedOrders, conversionFactor]);
const combinedSupplyAndDemand = useMemo(() => {
let projectedQuantity = forecastFetcher.data?.quantityOnHand ?? 0;
@@ -239,7 +246,10 @@ export const ItemPlanningChart = ({
(item) => item.id === order.existingId
);
if (existingIndex >= 0) {
- forecastData[existingIndex].quantity = order.quantity ?? 0;
+ // Convert purchase quantity to inventory quantity
+ const purchaseQuantity = order.quantity ?? 0;
+ const inventoryQuantity = purchaseQuantity * conversionFactor;
+ forecastData[existingIndex].quantity = inventoryQuantity;
}
}
});
@@ -250,7 +260,7 @@ export const ItemPlanningChart = ({
...filteredPlannedOrders.map((order) => ({
...order,
sourceType: "Planned" as SourceType,
- quantity: order.quantity ?? 0,
+ quantity: (order.quantity ?? 0) * conversionFactor,
documentReadableId: "Planned",
documentId: null,
id: null,
@@ -279,7 +289,7 @@ export const ItemPlanningChart = ({
.toLowerCase()
.includes(searchTerm.toLowerCase())
);
- }, [forecastFetcher.data, searchTerm, plannedOrders]);
+ }, [forecastFetcher.data, searchTerm, plannedOrders, conversionFactor]);
if (
forecastFetcher.data?.demand.length === 0 &&
diff --git a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
index 1ccde6bb6f..00b2e64533 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
@@ -276,13 +276,21 @@ export function getPurchaseOrdersFromPlanning(
): PlannedOrder[] {
const suppliers = supplierPartValidator.safeParse(itemPlanning.suppliers);
const supplier = suppliers.data?.find(
- (supplier) => supplier.id === supplierId
+ (supplier) => supplier.supplierId === supplierId
);
const item = items.find((item) => item.id === itemPlanning.id);
+ // Get the conversion factor from the selected supplier
+ const conversionFactor = supplier?.conversionFactor ?? 1;
+
return calculateOrders({ itemPlanning, periods }).map((order) => ({
...order,
+ // Convert inventory quantity to purchase quantity by dividing by conversion factor
+ quantity:
+ conversionFactor > 0
+ ? Math.ceil(order.quantity / conversionFactor)
+ : order.quantity,
supplierId: supplier?.supplierId ?? itemPlanning.preferredSupplierId,
itemReadableId: item?.readableIdWithRevision,
description: item?.name,
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 3acf5594c4..3d70071e41 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -1,5 +1,6 @@
import type { Database, Json } from "@carbon/database";
import type { JSONContent } from "@carbon/react";
+import type { FileObject, StorageError } from "@supabase/storage-js";
import {
FunctionRegion,
type PostgrestError,
@@ -156,9 +157,16 @@ export async function getJobDocuments(
companyId: string,
job: Job
): Promise<StorageItem[]> {
- const promises: Promise<any>[] = [
- client.storage.from("private").list(`${companyId}/job/${job.id}`),
- ];
+ const promises: Promise<
+ | {
+ data: FileObject[];
+ error: null;
+ }
+ | {
+ data: null;
+ error: StorageError;
+ }
+ >[] = [client.storage.from("private").list(`${companyId}/job/${job.id}`)];
// Add opportunity line files if available
if (job.salesOrderLineId || job.quoteLineId) {
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
index 689c14dcd6..47a5006e94 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
@@ -28,6 +28,7 @@ import {
LuCalendar,
LuClock,
LuHash,
+ LuMapPin,
LuPencil,
LuSquareUser,
LuTag,
@@ -43,6 +44,8 @@ import {
New,
Table,
} from "~/components";
+import { Enumerable } from "~/components/Enumerable";
+import { useLocations } from "~/components/Form/Location";
import { ConfirmDelete } from "~/components/Modals";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
@@ -85,6 +88,7 @@ const JobsTable = memo(({ data, count, tags }: JobsTableProps) => {
const [people] = usePeople();
const [customers] = useCustomers();
+ const locations = useLocations();
const permissions = usePermissions();
const deleteModal = useDisclosure();
@@ -389,6 +393,28 @@ const JobsTable = memo(({ data, count, tags }: JobsTableProps) => {
icon: <LuHash />,
},
},
+ {
+ accessorKey: "locationId",
+ header: "Location",
+ cell: ({ row }) => (
+ <Enumerable
+ value={
+ locations.find((l) => l.value === row.original.locationId)
+ ?.label ?? null
+ }
+ />
+ ),
+ meta: {
+ icon: <LuMapPin />,
+ filter: {
+ type: "static",
+ options: locations.map((l) => ({
+ value: l.value,
+ label: <Enumerable value={l.label} />,
+ })),
+ },
+ },
+ },
{
id: "createdBy",
header: "Created By",
diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
index 80d9ab305d..200fc790a2 100644
--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
@@ -278,9 +278,22 @@ const OrderDrawer = memo(
const onAddOrder = useCallback(() => {
if (selectedItem.id) {
+ // Get the conversion factor from the selected supplier
+ const supplier = (selectedItem.suppliers as SupplierPart[])?.find(
+ (s) => s.supplierId === selectedSupplier
+ );
+ const conversionFactor = supplier?.conversionFactor ?? 1;
+
+ // Convert inventory quantity to purchase quantity
+ const inventoryQuantity =
+ selectedItem.lotSize ?? selectedItem.minimumOrderQuantity ?? 0;
+ const purchaseQuantity =
+ conversionFactor > 0
+ ? Math.ceil(inventoryQuantity / conversionFactor)
+ : inventoryQuantity;
+
const newOrder: PlannedOrder = {
- quantity:
- selectedItem.lotSize ?? selectedItem.minimumOrderQuantity ?? 0,
+ quantity: purchaseQuantity,
dueDate: today(getLocalTimeZone())
.add({ days: selectedItem.leadTime ?? 0 })
.toString(),
@@ -292,7 +305,7 @@ const OrderDrawer = memo(
};
setOrders(selectedItem, [...orders, newOrder]);
}
- }, [selectedItem, orders, setOrders, periods]);
+ }, [selectedItem, orders, setOrders, periods, selectedSupplier]);
const onRemoveOrder = useCallback(
(index: number) => {
@@ -551,6 +564,37 @@ const OrderDrawer = memo(
<SupplierAvatar supplierId={selectedSupplier} />
</HStack>
<Separator />
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">
+ Purchase Unit:
+ </span>
+ <span>
+ {unitOfMeasureOptions.find(
+ (uom) =>
+ uom.value ===
+ (selectedItem.suppliers as SupplierPart[])?.find(
+ (s) => s.supplierId === selectedSupplier
+ )?.supplierUnitOfMeasureCode
+ )?.label ??
+ selectedItem.unitOfMeasureCode ??
+ "EA"}
+ </span>
+ </HStack>
+ {(() => {
+ const supplier = (
+ selectedItem.suppliers as SupplierPart[]
+ )?.find((s) => s.supplierId === selectedSupplier);
+ const conversionFactor = supplier?.conversionFactor ?? 1;
+ return conversionFactor !== 1 ? (
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">
+ Conversion:
+ </span>
+ <span>1 Purchase = {conversionFactor} Inventory</span>
+ </HStack>
+ ) : null;
+ })()}
+ <Separator />
{selectedItem.reorderingPolicy === "Maximum Quantity" && (
<>
<HStack className="justify-between w-full">
@@ -652,7 +696,7 @@ const OrderDrawer = memo(
<Th>
<div className="flex items-center gap-2 text-right">
<LuPackage />
- <span>Quantity</span>
+ <span>Purchase Qty</span>
</div>
</Th>
<Th>
@@ -769,6 +813,11 @@ const OrderDrawer = memo(
locationId={locationId}
safetyStock={selectedItem.demandAccumulationSafetyStock}
plannedOrders={orders}
+ conversionFactor={
+ (selectedItem.suppliers as SupplierPart[])?.find(
+ (s) => s.supplierId === selectedSupplier
+ )?.conversionFactor ?? 1
+ }
/>
</TabsContent>
</div>
diff --git a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
index 09da10918e..83ce2f9944 100644
--- a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
@@ -488,9 +488,17 @@ export async function action({ request }: ActionFunctionArgs) {
}
const periodId = order.periodId;
+
+ // Convert purchase quantity back to inventory quantity for supply forecast
+ // Inventory Quantity = Purchase Quantity × Conversion Factor
+ const conversionFactor = supplierPart?.conversionFactor ?? 1;
+ const purchaseQuantityDelta =
+ order.quantity - (order.existingQuantity ?? 0);
+ const inventoryQuantityDelta =
+ purchaseQuantityDelta * conversionFactor;
+
supplyForecastByPeriod[periodId] =
- (supplyForecastByPeriod[periodId] || 0) +
- (order.quantity - (order.existingQuantity ?? 0));
+ (supplyForecastByPeriod[periodId] || 0) + inventoryQuantityDelta;
}
if (itemProcessed) {
diff --git a/apps/erp/app/routes/x+/schedule+/index.tsx b/apps/erp/app/routes/x+/schedule+/index.tsx
index f430e8a1f6..f33c509955 100644
--- a/apps/erp/app/routes/x+/schedule+/index.tsx
+++ b/apps/erp/app/routes/x+/schedule+/index.tsx
@@ -7,6 +7,7 @@ import { flash } from "@carbon/auth/session.server";
import {
Button,
ClientOnly,
+ Combobox,
HStack,
Popover,
PopoverContent,
@@ -32,6 +33,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { LuCirclePlus, LuSettings2, LuTriangleAlert } from "react-icons/lu";
import { SearchFilter } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import { useLocations } from "~/components/Form/Location";
import { ActiveFilters, Filter } from "~/components/Table/components/Filter";
import type { ColumnFilter } from "~/components/Table/components/Filter/types";
import { useFilters } from "~/components/Table/components/Filter/useFilters";
@@ -286,6 +288,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}, {} as Record<string, boolean>)
).map(([tag]) => tag),
tags: tags.data ?? [],
+ locationId,
});
}
@@ -311,8 +314,11 @@ function KanbanSchedule() {
salesOrders,
availableTags,
tags,
+ locationId,
} = useLoaderData<typeof loader>();
+ const locations = useLocations();
+
const [items, setItems] = useState<Item[]>(initialItems);
const [displaySettings, setDisplaySettings] = useLocalStorage(
DISPLAY_SETTINGS_KEY,
@@ -411,45 +417,59 @@ function KanbanSchedule() {
<Filter filters={filters} />
</HStack>
- <Popover>
- <PopoverTrigger asChild>
- <Button
- leftIcon={<LuSettings2 />}
- variant="secondary"
- className="border-dashed border-border"
- >
- Display
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-48">
- <VStack>
- {[
- { key: "showCustomer", label: "Customer" },
- { key: "showDescription", label: "Description" },
- { key: "showDueDate", label: "Due Date" },
- { key: "showDuration", label: "Duration" },
- { key: "showProgress", label: "Progress" },
- { key: "showQuantity", label: "Quantity" },
- { key: "showStatus", label: "Status" },
- { key: "showSalesOrder", label: "Sales Order" },
- { key: "showThumbnail", label: "Thumbnail" },
- ].map(({ key, label }) => (
- <Switch
- key={key}
- variant="small"
- label={label}
- checked={displaySettings[key as keyof typeof displaySettings]}
- onCheckedChange={(checked) =>
- setDisplaySettings((prev) => ({
- ...prev,
- [key]: checked,
- }))
- }
- />
- ))}
- </VStack>
- </PopoverContent>
- </Popover>
+ <div className="flex items-center gap-2">
+ <Combobox
+ asButton
+ size="sm"
+ value={locationId}
+ options={locations}
+ onChange={(selected) => {
+ // hard refresh because initialValues update has no effect otherwise
+ window.location.href = getLocationPath(selected);
+ }}
+ />
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ leftIcon={<LuSettings2 />}
+ variant="secondary"
+ className="border-dashed border-border"
+ >
+ Display
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-48">
+ <VStack>
+ {[
+ { key: "showCustomer", label: "Customer" },
+ { key: "showDescription", label: "Description" },
+ { key: "showDueDate", label: "Due Date" },
+ { key: "showDuration", label: "Duration" },
+ { key: "showProgress", label: "Progress" },
+ { key: "showQuantity", label: "Quantity" },
+ { key: "showStatus", label: "Status" },
+ { key: "showSalesOrder", label: "Sales Order" },
+ { key: "showThumbnail", label: "Thumbnail" },
+ ].map(({ key, label }) => (
+ <Switch
+ key={key}
+ variant="small"
+ label={label}
+ checked={
+ displaySettings[key as keyof typeof displaySettings]
+ }
+ onCheckedChange={(checked) =>
+ setDisplaySettings((prev) => ({
+ ...prev,
+ [key]: checked,
+ }))
+ }
+ />
+ ))}
+ </VStack>
+ </PopoverContent>
+ </Popover>
+ </div>
</HStack>
{currentFilters.length > 0 && (
<HStack className="px-4 py-1.5 justify-between bg-card border-b border-border w-full">
@@ -744,3 +764,7 @@ function useProgressByOperation(
return { progressByOperation };
}
+
+function getLocationPath(locationId: string) {
+ return `${path.to.schedule}?location=${locationId}`;
+}
diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.ts
index e44a1cd30a..6641cabd49 100644
--- a/packages/database/supabase/functions/create/index.ts
+++ b/packages/database/supabase/functions/create/index.ts
@@ -752,16 +752,16 @@ serve(async (req: Request) => {
const {
purchaseOrderId,
receiptId: existingReceiptId,
- locationId,
+ locationId: userLocationId,
} = payload;
console.log({
function: "create",
type,
companyId,
- locationId,
purchaseOrderId,
existingReceiptId,
+ userLocationId,
userId,
});
@@ -774,7 +774,7 @@ serve(async (req: Request) => {
const [purchaseOrder, purchaseOrderLines, receipt] = await Promise.all([
client
- .from("purchaseOrder")
+ .from("purchaseOrders")
.select("*")
.eq("id", purchaseOrderId)
.single(),
@@ -788,8 +788,8 @@ serve(async (req: Request) => {
"Tool",
"Fixture",
"Consumable",
- ])
- .or(`locationId.eq.${locationId},locationId.is.null`),
+ ]),
+
client
.from("receipt")
.select("*")
@@ -801,12 +801,24 @@ serve(async (req: Request) => {
if (purchaseOrderLines.error)
throw new Error(purchaseOrderLines.error.message);
+ let locationId = purchaseOrder.data.locationId;
+ if (
+ purchaseOrderLines.data.some(
+ (d) =>
+ d.locationId !== locationId && d.locationId === userLocationId
+ )
+ ) {
+ locationId = userLocationId;
+ }
+
const items = await client
.from("item")
.select("id, itemTrackingType")
.in(
"id",
- purchaseOrderLines.data.map((d) => d.itemId)
+ purchaseOrderLines.data
+ .filter((d) => d.locationId === locationId)
+ .map((d) => d.itemId)
);
const serializedItems = new Set(
items.data
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index 4565a8200e..80610176a0 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -4,6 +4,7 @@ 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 { getSupabaseServiceRole } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
@@ -252,6 +253,18 @@ serve(async (req: Request) => {
.insertInto("itemLedger")
.values(itemLedgerInserts)
.execute();
+
+ // Update pickMethod defaultShelfId if needed for each inserted ledger
+ for (const ledger of itemLedgerInserts) {
+ await updatePickMethodDefaultShelfIfNeeded(
+ trx,
+ ledger.itemId,
+ ledger.locationId,
+ ledger.shelfId,
+ companyId,
+ userId
+ );
+ }
}
});
@@ -310,6 +323,11 @@ serve(async (req: Request) => {
.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;
@@ -338,6 +356,23 @@ serve(async (req: Request) => {
.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,
@@ -345,6 +380,23 @@ serve(async (req: Request) => {
])
);
+ // 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,
@@ -354,6 +406,50 @@ serve(async (req: Request) => {
for await (const material of materialsToIssue) {
if (material.quantityToIssue) {
+ const proposedShelfId =
+ shelfIdsToUse.get(material.itemId) ?? material.shelfId;
+
+ // Get current quantity on this shelf for diagnostics
+ const currentShelfQuantity = await trx
+ .selectFrom("itemLedger")
+ .select((eb) => eb.fn.sum("quantity").as("quantity"))
+ .where("itemId", "=", material.itemId)
+ .where("locationId", "=", job.locationId!)
+ .where("shelfId", "=", proposedShelfId ?? "")
+ .executeTakeFirst();
+
+ // Get all shelf quantities for this item for diagnostics
+ const allShelfQuantities = await trx
+ .selectFrom("itemLedger")
+ .select([
+ "shelfId",
+ (eb) => eb.fn.sum("quantity").as("quantity"),
+ ])
+ .where("itemId", "=", material.itemId)
+ .where("locationId", "=", job.locationId!)
+ .groupBy("shelfId")
+ .having((eb) => eb.fn.sum("quantity"), ">", 0)
+ .execute();
+
+ // Use shelf with highest quantity if proposed shelf has insufficient quantity
+ let finalShelfId = proposedShelfId;
+ const currentQuantity = Number(
+ currentShelfQuantity?.quantity ?? 0
+ );
+ const quantityToIssue = Number(material.quantityToIssue);
+
+ if (
+ currentQuantity < quantityToIssue &&
+ allShelfQuantities.length > 0
+ ) {
+ const bestShelf = allShelfQuantities.reduce((best, current) =>
+ Number(current.quantity) > Number(best.quantity)
+ ? current
+ : best
+ );
+ finalShelfId = bestShelf.shelfId;
+ }
+
if (itemIdIsTracked.get(material.itemId)) {
itemLedgerInserts.push({
entryType: "Consumption",
@@ -364,9 +460,7 @@ serve(async (req: Request) => {
itemId: material.itemId,
quantity: -Number(material.quantityToIssue),
locationId: job?.locationId,
- shelfId: material.defaultShelf
- ? shelfIdsToUse.get(material.itemId)
- : material.shelfId,
+ shelfId: finalShelfId,
createdBy: userId,
});
}
@@ -388,6 +482,18 @@ serve(async (req: Request) => {
.insertInto("itemLedger")
.values(itemLedgerInserts)
.execute();
+
+ // Update pickMethod defaultShelfId if needed for each inserted ledger
+ for (const ledger of itemLedgerInserts) {
+ await updatePickMethodDefaultShelfIfNeeded(
+ trx,
+ ledger.itemId,
+ ledger.locationId,
+ ledger.shelfId,
+ companyId,
+ userId
+ );
+ }
}
}
});
@@ -670,19 +776,30 @@ serve(async (req: Request) => {
]);
if (materialId) {
- const [material, pickMethod] = await Promise.all([
- trx
- .selectFrom("jobMaterial")
- .where("id", "=", materialId)
- .selectAll()
- .executeTakeFirst(),
- trx
+ const material = await trx
+ .selectFrom("jobMaterial")
+ .where("id", "=", materialId)
+ .selectAll()
+ .executeTakeFirst();
+
+ let shelfId: string | null | undefined;
+ if (material?.defaultShelf) {
+ const pickMethod = await trx
.selectFrom("pickMethod")
.where("itemId", "=", itemId)
.where("locationId", "=", job?.locationId!)
.select("defaultShelfId")
- .executeTakeFirst(),
- ]);
+ .executeTakeFirst();
+ shelfId = pickMethod?.defaultShelfId;
+ } else {
+ shelfId =
+ material?.shelfId ??
+ (await getShelfWithHighestQuantity(
+ trx,
+ itemId,
+ job?.locationId!
+ ));
+ }
const quantityToIssue =
adjustmentType === "Positive Adjmt."
@@ -703,9 +820,7 @@ serve(async (req: Request) => {
companyId,
itemId: material?.itemId!,
locationId: job?.locationId,
- shelfId: material?.defaultShelf
- ? pickMethod?.defaultShelfId
- : material?.shelfId,
+ shelfId,
quantity:
adjustmentType === "Positive Adjmt."
? Number(quantityToIssue)
@@ -729,8 +844,21 @@ serve(async (req: Request) => {
.insertInto("itemLedger")
.values(itemLedgerInserts)
.execute();
+
+ // Update pickMethod defaultShelfId if needed for each inserted ledger
+ for (const ledger of itemLedgerInserts) {
+ await updatePickMethodDefaultShelfIfNeeded(
+ trx,
+ ledger.itemId,
+ ledger.locationId,
+ ledger.shelfId,
+ companyId,
+ userId
+ );
+ }
}
} else {
+ let shelfId: string | null | undefined;
if (item?.itemTrackingType === "Inventory") {
const pickMethod = await trx
.selectFrom("pickMethod")
@@ -739,6 +867,14 @@ serve(async (req: Request) => {
.select("defaultShelfId")
.executeTakeFirst();
+ shelfId =
+ pickMethod?.defaultShelfId ??
+ (await getShelfWithHighestQuantity(
+ trx,
+ itemId,
+ job?.locationId!
+ ));
+
itemLedgerInserts.push({
entryType: "Consumption",
documentType: "Job Consumption",
@@ -751,24 +887,16 @@ serve(async (req: Request) => {
? Number(quantity)
: -Number(quantity),
locationId: job?.locationId,
- shelfId: pickMethod?.defaultShelfId,
+ shelfId,
createdBy: userId,
});
}
- const [itemCost, pickMethod] = await Promise.all([
- trx
- .selectFrom("itemCost")
- .where("itemId", "=", itemId!)
- .select("unitCost")
- .executeTakeFirst(),
- trx
- .selectFrom("pickMethod")
- .where("itemId", "=", itemId!)
- .where("locationId", "=", job?.locationId!)
- .select("defaultShelfId")
- .executeTakeFirst(),
- ]);
+ const itemCost = await trx
+ .selectFrom("itemCost")
+ .where("itemId", "=", itemId!)
+ .select("unitCost")
+ .executeTakeFirst();
await trx
.insertInto("jobMaterial")
@@ -783,7 +911,7 @@ serve(async (req: Request) => {
jobId: jobOperation?.jobId!,
jobMakeMethodId: jobOperation?.jobMakeMethodId,
jobOperationId: id,
- shelfId: pickMethod?.defaultShelfId,
+ shelfId,
methodType: "Pick",
quantity: 0,
quantityIssued: Number(quantity ?? 0),
@@ -796,6 +924,18 @@ serve(async (req: Request) => {
.insertInto("itemLedger")
.values(itemLedgerInserts)
.execute();
+
+ // Update pickMethod defaultShelfId if needed for each inserted ledger
+ for (const ledger of itemLedgerInserts) {
+ await updatePickMethodDefaultShelfIfNeeded(
+ trx,
+ ledger.itemId,
+ ledger.locationId,
+ ledger.shelfId,
+ companyId,
+ userId
+ );
+ }
}
}
});
@@ -1131,6 +1271,18 @@ serve(async (req: Request) => {
.insertInto("itemLedger")
.values(itemLedgerInserts)
.execute();
+
+ // Update pickMethod defaultShelfId if needed for each inserted ledger
+ for (const ledger of itemLedgerInserts) {
+ await updatePickMethodDefaultShelfIfNeeded(
+ trx,
+ ledger.itemId,
+ ledger.locationId,
+ ledger.shelfId,
+ companyId,
+ userId
+ );
+ }
}
const totalChildQuantity = children.reduce((sum, child) => {
@@ -1334,6 +1486,18 @@ serve(async (req: Request) => {
.insertInto("itemLedger")
.values(itemLedgerInserts)
.execute();
+
+ // Update pickMethod defaultShelfId if needed for each inserted ledger
+ for (const ledger of itemLedgerInserts) {
+ await updatePickMethodDefaultShelfIfNeeded(
+ trx,
+ ledger.itemId,
+ ledger.locationId,
+ ledger.shelfId,
+ companyId,
+ userId
+ );
+ }
}
const totalChildQuantity = children.reduce((sum, child) => {
@@ -1380,3 +1544,83 @@ 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/jobs/trigger/recalculate.ts b/packages/jobs/trigger/recalculate.ts
index 912cf08f0e..b223b79a6a 100644
--- a/packages/jobs/trigger/recalculate.ts
+++ b/packages/jobs/trigger/recalculate.ts
@@ -79,9 +79,9 @@ async function recalculateJobRequirements(
userId: string;
}
) {
- return client.functions.invoke("scheduler", {
+ return client.functions.invoke("recalculate", {
body: {
- type: "requirements",
+ type: "jobRequirements",
...params,
},
});
diff --git a/packages/jobs/trigger/sales-order-to-jobs.ts b/packages/jobs/trigger/sales-order-to-jobs.ts
index 5a0eab88fa..20f0227156 100644
--- a/packages/jobs/trigger/sales-order-to-jobs.ts
+++ b/packages/jobs/trigger/sales-order-to-jobs.ts
@@ -198,7 +198,7 @@ export const salesOrderToJobsTask = task({
await serviceRole.functions.invoke("scheduler", {
body: {
- type: "requirements",
+ type: "dependencies",
id: createJob.data.id,
companyId,
userId,