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: add ui for tracking serialized items in mes

Brad Barbin8637f6ae10c2
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
index 86bd5d5988..d0425d7e95 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
@@ -8,20 +8,20 @@ const getActivityText = (ledgerRecord: ItemLedger) => {
switch (ledgerRecord.documentType) {
case "Purchase Receipt":
return `received ${ledgerRecord.quantity} units${
- ledgerRecord.batchNumber
- ? ` from batch ${ledgerRecord.batchNumber}`
- : ""
- }${
- ledgerRecord.serialNumber
- ? ` with serial number ${ledgerRecord.serialNumber}`
+ ledgerRecord.trackedEntityId
+ ? ` from ${
+ Math.abs(ledgerRecord.quantity) > 1 ? "batch" : "serial"
+ } ${ledgerRecord.trackedEntityId}`
: ""
}`;
case "Purchase Invoice":
return `invoiced ${ledgerRecord.quantity} units`;
case "Sales Shipment":
return `shipped ${-1 * ledgerRecord.quantity} units${
- ledgerRecord.serialNumber
- ? ` with serial number ${ledgerRecord.serialNumber}`
+ ledgerRecord.trackedEntityId
+ ? ` of ${Math.abs(ledgerRecord.quantity) > 1 ? "batch" : "serial"} ${
+ ledgerRecord.trackedEntityId
+ }`
: ""
}`;
case "Sales Invoice":
@@ -107,7 +107,7 @@ const getActivityText = (ledgerRecord: ItemLedger) => {
const getActivityIcon = (ledgerRecord: ItemLedger) => {
switch (ledgerRecord.entryType) {
case "Positive Adjmt.":
- return <LuCirclePlus className="text-blue-500 w-5 h-5" />;
+ return <LuCirclePlus className="text-emerald-500 w-5 h-5" />;
case "Negative Adjmt.":
case "Consumption":
return <LuCircleMinus className="text-red-500 w-5 h-5" />;
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index f53b9b7b2b..7673dcd350 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -28,6 +28,7 @@ import {
VStack,
} from "@carbon/react";
import { ValidatedForm, Number, Submit } from "@carbon/form";
+import type { TrackedEntityAttributes } from "@carbon/utils";
import {
Await,
Outlet,
@@ -56,7 +57,6 @@ import {
type ReceiptLine,
} from "~/modules/inventory";
import { getDocumentType } from "~/modules/shared/shared.service";
-import type { TrackedEntityAttributes } from "~/modules/shared/types";
import type { action as receiptLinesUpdateAction } from "~/routes/x+/receipt+/lines.update";
import { useItems } from "~/stores";
import type { StorageItem } from "~/types";
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
index a5086616b8..93f7b69fed 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
@@ -23,7 +23,7 @@ import { LuTriangleAlert } from "react-icons/lu";
import { path } from "~/utils/path";
import type { ReceiptLine } from "../../types";
import { getReceiptTracking } from "../../inventory.service";
-import type { TrackedEntityAttributes } from "~/modules/shared";
+import type { TrackedEntityAttributes } from "@carbon/utils";
import { useUser } from "~/hooks";
const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
index ade33a86fe..745d1508d3 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
@@ -7,7 +7,7 @@ import type { ItemTracking, Shipment, ShipmentLine } from "~/modules/inventory";
import { path } from "~/utils/path";
import ShipmentPostModal from "./ShipmentPostModal";
import { RiProgress8Line } from "react-icons/ri";
-import { TrackedEntityAttributes } from "~/modules/shared";
+import type { TrackedEntityAttributes } from "@carbon/utils";
import ShipmentStatus from "./ShipmentStatus";
import { SplitButton } from "~/components/SplitButton";
import { labelSizes } from "@carbon/utils";
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
index 98203d3aed..05b5107fe0 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
@@ -61,7 +61,7 @@ import type { action as shipmentLinesUpdateAction } from "~/routes/x+/shipment+/
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import { ValidatedForm, Submit, Number } from "@carbon/form";
-import type { TrackedEntityAttributes } from "~/modules/shared";
+import type { TrackedEntityAttributes } from "@carbon/utils";
import { SplitButton } from "~/components/SplitButton";
import { labelSizes } from "@carbon/utils";
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
index 33bba02d3a..6f7cffad82 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
@@ -23,7 +23,7 @@ import { LuTriangleAlert } from "react-icons/lu";
import { getShipmentTracking } from "../..";
import type { ShipmentLine } from "../..";
import { path } from "~/utils/path";
-import type { TrackedEntityAttributes } from "~/modules/shared";
+import type { TrackedEntityAttributes } from "@carbon/utils";
import { useUser } from "~/hooks";
const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
index 506c44494a..181a25c784 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
@@ -80,9 +80,10 @@ const JobBreadcrumbs = () => {
material: JobMaterial;
}>(path.to.jobMakeMethod(jobId, methodId!, materialId!));
- const itemId = materialRouteData?.material?.itemId ?? routeData?.job?.itemId;
+ const itemId =
+ materialRouteData?.material?.jobMaterialItemId ?? routeData?.job?.itemId;
const itemType =
- materialRouteData?.material?.itemType ?? routeData?.job?.itemType;
+ materialRouteData?.material?.type ?? routeData?.job?.itemType;
const itemLink =
itemType && itemId
diff --git a/apps/erp/app/modules/shared/types.ts b/apps/erp/app/modules/shared/types.ts
index b28a23e2d9..04846d3ee4 100644
--- a/apps/erp/app/modules/shared/types.ts
+++ b/apps/erp/app/modules/shared/types.ts
@@ -89,18 +89,3 @@ export type SavedView = {
};
export type StandardFactor = (typeof standardFactorType)[number];
-
-export interface TrackedEntityAttributes {
- "Batch Number"?: string;
- Customer?: string;
- "Purchase Order"?: string;
- "Receipt Line Index"?: number;
- "Receipt Line"?: string;
- Receipt?: string;
- Supplier?: string;
- "Serial Number"?: string;
- "Shipment Line Index"?: number;
- "Shipment Line"?: string;
- Shipment?: string;
- "Split Entity ID"?: string;
-}
diff --git a/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx
index 9cbaf62683..59ab315e70 100644
--- a/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx
@@ -5,7 +5,7 @@ import { renderToStream } from "@react-pdf/renderer";
import { redirect, type LoaderFunctionArgs } from "@vercel/remix";
import { getReceiptTracking } from "~/modules/inventory";
import { getCompanySettings } from "~/modules/settings/settings.service";
-import { TrackedEntityAttributes } from "~/modules/shared";
+import type { TrackedEntityAttributes } from "@carbon/utils";
import { path } from "~/utils/path";
export const config = { runtime: "nodejs" };
diff --git a/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx
index 640438c65b..44e455924b 100644
--- a/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx
+++ b/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx
@@ -1,10 +1,10 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { generateProductLabelZPL } from "@carbon/documents/zpl";
import { labelSizes } from "@carbon/utils";
+import type { TrackedEntityAttributes } from "@carbon/utils";
import { redirect, type LoaderFunctionArgs } from "@vercel/remix";
import { getReceiptTracking } from "~/modules/inventory/inventory.service";
import { getCompanySettings } from "~/modules/settings/settings.service";
-import { TrackedEntityAttributes } from "~/modules/shared/types";
import { path } from "~/utils/path";
export const config = { runtime: "nodejs" };
diff --git a/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx
index 052855d14f..b33cddebe8 100644
--- a/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx
@@ -5,7 +5,7 @@ import { renderToStream } from "@react-pdf/renderer";
import { redirect, type LoaderFunctionArgs } from "@vercel/remix";
import { getShipmentTracking } from "~/modules/inventory";
import { getCompanySettings } from "~/modules/settings/settings.service";
-import { TrackedEntityAttributes } from "~/modules/shared";
+import type { TrackedEntityAttributes } from "@carbon/utils";
import { path } from "~/utils/path";
export const config = { runtime: "nodejs" };
diff --git a/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx
index 0120cf242e..eab09cf8ad 100644
--- a/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx
+++ b/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx
@@ -4,7 +4,7 @@ import { labelSizes } from "@carbon/utils";
import { redirect, type LoaderFunctionArgs } from "@vercel/remix";
import { getShipmentTracking } from "~/modules/inventory/inventory.service";
import { getCompanySettings } from "~/modules/settings/settings.service";
-import { TrackedEntityAttributes } from "~/modules/shared/types";
+import type { TrackedEntityAttributes } from "@carbon/utils";
import { path } from "~/utils/path";
export const config = { runtime: "nodejs" };
diff --git a/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx b/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx
index 684cb83df7..c86569d927 100644
--- a/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx
+++ b/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx
@@ -1,7 +1,7 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { json, type ActionFunctionArgs } from "@vercel/remix";
-import { TrackedEntityAttributes } from "~/modules/shared/types";
+import type { TrackedEntityAttributes } from "@carbon/utils";
export async function action({ request, context }: ActionFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index 772875f8b7..f035ad4160 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -6,6 +6,7 @@ import {
Badge,
Button,
Checkbox,
+ Combobox as ComboboxBase,
cn,
DropdownMenu,
DropdownMenuContent,
@@ -53,6 +54,14 @@ import {
useMount,
VStack,
type JSONContent,
+ InputGroup,
+ InputRightElement,
+ NumberDecrementStepper,
+ NumberField,
+ NumberIncrementStepper,
+ NumberInput,
+ NumberInputGroup,
+ NumberInputStepper,
} from "@carbon/react";
import { generateHTML } from "@carbon/react/Editor";
import {
@@ -120,6 +129,7 @@ import {
formatDateTime,
formatDurationMilliseconds,
formatRelativeTime,
+ TrackedEntityAttributes,
} from "@carbon/utils";
import {
getLocalTimeZone,
@@ -139,8 +149,12 @@ import { FaCheck, FaPause, FaPlay, FaPlus, FaTrash } from "react-icons/fa6";
import {
LuActivity,
LuAxis3D,
+ LuCheck,
+ LuChevronDown,
LuChevronLeft,
+ LuChevronUp,
LuCircleCheck,
+ LuCirclePlus,
LuClipboardCheck,
LuDownload,
LuEllipsisVertical,
@@ -148,12 +162,14 @@ import {
LuGitBranchPlus,
LuHammer,
LuHardHat,
+ LuList,
LuPaperclip,
LuQrCode,
LuSend,
LuTimer,
LuTrash,
LuTriangleAlert,
+ LuX,
} from "react-icons/lu";
import {
MethodIcon,
@@ -166,6 +182,8 @@ import ItemThumbnail from "./ItemThumbnail";
import ScrapReason from "./ScrapReason";
import FileDropzone from "./FileDropzone";
import { useNumberFormatter } from "@react-aria/i18n";
+import { getSerialNumbersForItem } from "~/services/inventory.service";
+import { getBatchNumbersForItem } from "~/services/inventory.service";
type JobOperationProps = {
events: ProductionEvent[];
@@ -221,7 +239,6 @@ export const JobOperation = ({
setEventType,
setSelectedMaterial,
setupProductionEvent,
- trackingModal,
} = useOperation(originalOperation, events, isModalOpen);
const controlsHeight = useMemo(() => {
@@ -575,7 +592,9 @@ export const JobOperation = ({
<Td>{material.estimatedQuantity}</Td>
<Td>
- {material.methodType === "Make" ? (
+ {material.methodType === "Make" &&
+ material.requiresBatchTracking === false &&
+ material.requiresSerialTracking === false ? (
<MethodIcon type="Make" />
) : (
material.quantityIssued
@@ -610,7 +629,7 @@ export const JobOperation = ({
flushSync(() => {
setSelectedMaterial(material);
});
- trackingModal.onOpen();
+ issueModal.onOpen();
}}
/>
)}
@@ -1275,23 +1294,46 @@ export const JobOperation = ({
</Await>
</Suspense>
)}
- {trackingModal.isOpen && (
- <TrackingModal
- operationId={operation.id}
- material={selectedMaterial ?? undefined}
- onClose={trackingModal.onClose}
- />
- )}
- {issueModal.isOpen && (
- <IssueModal
- operationId={operation.id}
- material={selectedMaterial ?? undefined}
- onClose={() => {
- setSelectedMaterial(null);
- issueModal.onClose();
- }}
- />
- )}
+
+ {issueModal.isOpen &&
+ selectedMaterial?.requiresBatchTracking !== true &&
+ selectedMaterial?.requiresSerialTracking !== true && (
+ <IssueModal
+ operationId={operation.id}
+ material={selectedMaterial ?? undefined}
+ onClose={() => {
+ setSelectedMaterial(null);
+ issueModal.onClose();
+ }}
+ />
+ )}
+ {issueModal.isOpen &&
+ selectedMaterial?.requiresBatchTracking === true && (
+ <BatchIssueModal
+ parentId={""} // TODO
+ parentIdIsSerialized={false} // TODO
+ operationId={operation.id}
+ material={selectedMaterial ?? undefined}
+ onClose={() => {
+ setSelectedMaterial(null);
+ issueModal.onClose();
+ }}
+ />
+ )}
+ {issueModal.isOpen &&
+ selectedMaterial?.requiresSerialTracking === true && (
+ <SerialIssueModal
+ operationId={operation.id}
+ material={selectedMaterial ?? undefined}
+ parentId={""} // TODO
+ parentIdIsSerialized={false} // TODO
+ onClose={() => {
+ setSelectedMaterial(null);
+ issueModal.onClose();
+ }}
+ />
+ )}
+
{attributeRecordModal.isOpen && selectedAttribute ? (
<RecordModal
key={selectedAttribute.id}
@@ -1546,7 +1588,7 @@ function useOperation(
const completeModal = useDisclosure();
const finishModal = useDisclosure();
const issueModal = useDisclosure();
- const trackingModal = useDisclosure();
+
// we do this to avoid re-rendering when the modal is open
const isAnyModalOpen =
pauseInterval ||
@@ -1765,7 +1807,6 @@ function useOperation(
completeModal,
finishModal,
issueModal,
- trackingModal,
isOverdue: operation.jobDueDate
? new Date(operation.jobDueDate) < new Date()
: false,
@@ -2345,27 +2386,790 @@ function QuantityModal({
</Modal>
);
}
+function SerialIssueModal({
+ operationId,
+ material,
+ parentId,
+ parentIdIsSerialized,
+ onClose,
+}: {
+ parentId: string;
+ parentIdIsSerialized: boolean;
+ operationId: string;
+ material?: JobMaterial;
+ onClose: () => void;
+}) {
+ const { data: serialNumbers } = useSerialNumbers(material?.itemId);
+
+ const [errors, setErrors] = useState<Record<number, string>>({});
+
+ const options = useMemo(() => {
+ return (
+ serialNumbers?.data?.map((serialNumber) => {
+ const attributes = serialNumber.attributes as TrackedEntityAttributes;
+ return {
+ label: serialNumber.sourceDocumentReadableId ?? "",
+ value: serialNumber.id,
+ helper: attributes["Serial Number"]
+ ? `Serial ${attributes["Serial Number"]}`
+ : attributes["Batch Number"]
+ ? `Batch ${attributes["Batch Number"]}`
+ : undefined,
+ };
+ }) ?? []
+ );
+ }, [serialNumbers]);
+
+ const initialQuantity = parentIdIsSerialized
+ ? material?.quantity ?? 1
+ : material?.estimatedQuantity ?? 1;
+
+ const [selectedSerialNumbers, setSelectedSerialNumbers] = useState<
+ Array<{
+ index: number;
+ id: string;
+ }>
+ >(
+ Array(initialQuantity)
+ .fill("")
+ .map((_, index) => ({ index, id: "" }))
+ );
+
+ const validateSerialNumber = useCallback(
+ (value: string, index: number) => {
+ if (!value) return "Serial number is required";
+
+ // Check for duplicates
+ const isDuplicate = selectedSerialNumbers.some(
+ (sn, i) => sn.id === value && i !== index
+ );
+ if (isDuplicate) return "Duplicate serial number";
+
+ // Check if serial number exists in options
+ const isValid = options.some((option) => option.value === value);
+ if (!isValid) return "Invalid serial number";
+
+ return null;
+ },
+ [selectedSerialNumbers, options]
+ );
+
+ const updateSerialNumber = useCallback(
+ (serialNumber: { index: number; id: string }) => {
+ setSelectedSerialNumbers((prev) => {
+ const newSerialNumbers = [...prev];
+ newSerialNumbers[serialNumber.index] = serialNumber;
+ return newSerialNumbers;
+ });
+ },
+ []
+ );
+
+ const addSerialNumber = useCallback(() => {
+ setSelectedSerialNumbers((prev) => {
+ const newIndex = prev.length;
+ return [...prev, { index: newIndex, id: "" }];
+ });
+ }, []);
+
+ const removeSerialNumber = useCallback((indexToRemove: number) => {
+ setSelectedSerialNumbers((prev) => {
+ // Remove the item at the specified index
+ const filtered = prev.filter((_, i) => i !== indexToRemove);
+
+ // Reindex the remaining items
+ return filtered.map((item, i) => ({ ...item, index: i }));
+ });
+
+ // Clean up any errors for the removed index
+ setErrors((prev) => {
+ const newErrors = { ...prev };
+ delete newErrors[indexToRemove];
+
+ // Reindex the errors for indices greater than the removed one
+ const reindexedErrors: Record<number, string> = {};
+ Object.entries(newErrors).forEach(([key, value]) => {
+ const keyNum = parseInt(key);
+ if (keyNum > indexToRemove) {
+ reindexedErrors[keyNum - 1] = value;
+ } else {
+ reindexedErrors[keyNum] = value;
+ }
+ });
+
+ return reindexedErrors;
+ });
+ }, []);
+
+ const handleSubmit = useCallback(() => {
+ // Validate all serial numbers
+ let hasErrors = false;
+ const newErrors: Record<number, string> = {};
+
+ selectedSerialNumbers.forEach((sn) => {
+ const error = validateSerialNumber(sn.id, sn.index);
+ if (error) {
+ newErrors[sn.index] = error;
+ hasErrors = true;
+ }
+ });
+
+ setErrors(newErrors);
+
+ if (!hasErrors) {
+ // Submit to the API
+ console.log({
+ id: operationId,
+ parentId,
+ children: selectedSerialNumbers.map((sn) => ({
+ trackedEntityId: sn.id,
+ quantity: 1,
+ })),
+ });
+ onClose();
+ }
+ }, [
+ selectedSerialNumbers,
+ validateSerialNumber,
+ operationId,
+ parentId,
+ onClose,
+ ]);
+
+ return (
+ <Modal open onOpenChange={onClose}>
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Issue Serial Tracked Parts</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <Tabs defaultValue="scan">
+ <TabsList className="grid w-full grid-cols-2 mb-4">
+ <TabsTrigger value="scan">
+ <LuQrCode className="mr-2" />
+ Scan
+ </TabsTrigger>
+ <TabsTrigger value="select">
+ <LuList className="mr-2" />
+ Select
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="scan">
+ <div className="flex flex-col gap-4">
+ {selectedSerialNumbers.map((serialNumber, index) => (
+ <div
+ key={`${index}-serial-scan`}
+ className="flex flex-col gap-1"
+ >
+ <div className="flex items-center gap-2">
+ <div className="flex-1">
+ <InputGroup>
+ <Input
+ placeholder={`Serial Number ${index + 1}`}
+ value={serialNumber.id}
+ onChange={(e) => {
+ const newValue = e.target.value;
+ const newSerialNumbers = [
+ ...selectedSerialNumbers,
+ ];
+ newSerialNumbers[index] = {
+ index,
+ id: newValue,
+ };
+ setSelectedSerialNumbers(newSerialNumbers);
+ }}
+ onBlur={(e) => {
+ const newValue = e.target.value;
+ const error = validateSerialNumber(
+ newValue,
+ index
+ );
+
+ setErrors((prev) => {
+ const newErrors = { ...prev };
+ if (error) {
+ newErrors[index] = error;
+ } else {
+ delete newErrors[index];
+ }
+ return newErrors;
+ });
+
+ if (!error) {
+ updateSerialNumber({
+ index,
+ id: newValue,
+ });
+ } else {
+ // Clear the input value but keep the error message
+ const newSerialNumbers = [
+ ...selectedSerialNumbers,
+ ];
+ newSerialNumbers[index] = {
+ index,
+ id: "",
+ };
+ setSelectedSerialNumbers(newSerialNumbers);
+ }
+ }}
+ className={cn(
+ errors[index] && "border-destructive"
+ )}
+ />
+ <InputRightElement className="pl-2">
+ {!errors[index] && serialNumber.id ? (
+ <LuCheck className="text-emerald-500" />
+ ) : (
+ <LuQrCode />
+ )}
+ </InputRightElement>
+ </InputGroup>
+ </div>
+ <IconButton
+ aria-label="Remove Serial Number"
+ icon={<LuX />}
+ variant="ghost"
+ onClick={() => removeSerialNumber(index)}
+ className="flex-shrink-0"
+ />
+ </div>
+ {errors[index] && (
+ <span className="text-xs text-destructive">
+ {errors[index]}
+ </span>
+ )}
+ </div>
+ ))}
+ <div>
+ <Button
+ type="button"
+ variant="secondary"
+ leftIcon={<LuCirclePlus />}
+ onClick={addSerialNumber}
+ >
+ Add
+ </Button>
+ </div>
+ </div>
+ </TabsContent>
+ <TabsContent value="select">
+ <div className="flex flex-col gap-4">
+ {selectedSerialNumbers.map((serialNumber, index) => (
+ <div
+ key={`${index}-serial-select`}
+ className="flex flex-col gap-1"
+ >
+ <div className="flex items-center gap-2">
+ <div className="flex-1">
+ <ComboboxBase
+ placeholder={`Select Serial Number ${index + 1}`}
+ value={serialNumber.id}
+ onChange={(value) => {
+ const newSerialNumbers = [...selectedSerialNumbers];
+ newSerialNumbers[index] = {
+ index,
+ id: value,
+ };
+ setSelectedSerialNumbers(newSerialNumbers);
+
+ // Validate on change for select
+ const error = validateSerialNumber(value, index);
+ setErrors((prev) => {
+ const newErrors = { ...prev };
+ if (error) {
+ newErrors[index] = error;
+ } else {
+ delete newErrors[index];
+ }
+ return newErrors;
+ });
+ }}
+ options={options}
+ />
+ </div>
+ <IconButton
+ aria-label="Remove Serial Number"
+ icon={<LuX />}
+ variant="ghost"
+ onClick={() => removeSerialNumber(index)}
+ className="flex-shrink-0"
+ />
+ </div>
+ {errors[index] && (
+ <span className="text-xs text-destructive">
+ {errors[index]}
+ </span>
+ )}
+ </div>
+ ))}
+ <div>
+ <Button
+ type="button"
+ variant="secondary"
+ leftIcon={<LuCirclePlus />}
+ onClick={addSerialNumber}
+ >
+ Add
+ </Button>
+ </div>
+ </div>
+ </TabsContent>
+ </Tabs>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button variant="primary" onClick={handleSubmit}>
+ Issue
+ </Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+}
+
+function useSerialNumbers(itemId?: string) {
+ const serialNumbersFetcher =
+ useFetcher<Awaited<ReturnType<typeof getSerialNumbersForItem>>>();
-function TrackingModal({
+ useEffect(() => {
+ if (itemId) {
+ serialNumbersFetcher.load(path.to.api.serialNumbers(itemId));
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [itemId]);
+
+ return { data: serialNumbersFetcher.data };
+}
+function BatchIssueModal({
+ parentId,
+ parentIdIsSerialized,
operationId,
material,
onClose,
}: {
+ parentId: string;
+ parentIdIsSerialized: boolean;
operationId: string;
material?: JobMaterial;
onClose: () => void;
}) {
+ const { data: batchNumbers } = useBatchNumbers(material?.itemId);
+
+ const [errors, setErrors] = useState<Record<number, string>>({});
+
+ const options = useMemo(() => {
+ return (
+ batchNumbers?.data?.map((batchNumber) => {
+ const attributes = batchNumber.attributes as TrackedEntityAttributes;
+ return {
+ label: batchNumber.sourceDocumentReadableId ?? "",
+ value: batchNumber.id,
+ helper: attributes["Batch Number"]
+ ? `${batchNumber.quantity} Available ${
+ attributes["Batch Number"]
+ ? `of Batch ${attributes["Batch Number"]}`
+ : ""
+ }`
+ : undefined,
+ availableQuantity: batchNumber.quantity,
+ };
+ }) ?? []
+ );
+ }, [batchNumbers]);
+
+ const initialQuantity = parentIdIsSerialized
+ ? material?.quantity ?? 1
+ : material?.estimatedQuantity ?? 1;
+
+ const [selectedBatchNumbers, setSelectedBatchNumbers] = useState<
+ Array<{
+ index: number;
+ id: string;
+ quantity: number;
+ }>
+ >(
+ Array(1)
+ .fill("")
+ .map((_, index) => ({ index, id: "", quantity: initialQuantity }))
+ );
+
+ const validateBatchNumber = useCallback(
+ (value: string, quantity: number, index: number) => {
+ if (!value) return "Batch number is required";
+
+ // Check for duplicates
+ const isDuplicate = selectedBatchNumbers.some(
+ (bn, i) => bn.id === value && i !== index
+ );
+ if (isDuplicate) return "Duplicate batch number";
+
+ // Check if batch number exists in options
+ const batchOption = options.find((option) => option.value === value);
+ if (!batchOption) return "Invalid batch number";
+
+ // Check if quantity is valid
+ if (quantity <= 0) return "Quantity must be greater than 0";
+ if (quantity > batchOption.availableQuantity)
+ return `Quantity cannot exceed available quantity (${batchOption.availableQuantity})`;
+
+ return null;
+ },
+ [selectedBatchNumbers, options]
+ );
+
+ const updateBatchNumber = useCallback(
+ (batchNumber: { index: number; id: string; quantity: number }) => {
+ setSelectedBatchNumbers((prev) => {
+ const newBatchNumbers = [...prev];
+ newBatchNumbers[batchNumber.index] = batchNumber;
+ return newBatchNumbers;
+ });
+ },
+ []
+ );
+
+ const addBatchNumber = useCallback(() => {
+ setSelectedBatchNumbers((prev) => {
+ const newIndex = prev.length;
+ return [...prev, { index: newIndex, id: "", quantity: 1 }];
+ });
+ }, []);
+
+ const removeBatchNumber = useCallback((indexToRemove: number) => {
+ setSelectedBatchNumbers((prev) => {
+ // Remove the item at the specified index
+ const filtered = prev.filter((_, i) => i !== indexToRemove);
+
+ // Reindex the remaining items
+ return filtered.map((item, i) => ({ ...item, index: i }));
+ });
+
+ // Clean up any errors for the removed index
+ setErrors((prev) => {
+ const newErrors = { ...prev };
+ delete newErrors[indexToRemove];
+
+ // Reindex the errors for indices greater than the removed one
+ const reindexedErrors: Record<number, string> = {};
+ Object.entries(newErrors).forEach(([key, value]) => {
+ const keyNum = parseInt(key);
+ if (keyNum > indexToRemove) {
+ reindexedErrors[keyNum - 1] = value;
+ } else {
+ reindexedErrors[keyNum] = value;
+ }
+ });
+
+ return reindexedErrors;
+ });
+ }, []);
+
+ const handleSubmit = useCallback(() => {
+ // Validate all batch numbers
+ let hasErrors = false;
+ const newErrors: Record<number, string> = {};
+
+ selectedBatchNumbers.forEach((bn) => {
+ const error = validateBatchNumber(bn.id, bn.quantity, bn.index);
+ if (error) {
+ newErrors[bn.index] = error;
+ hasErrors = true;
+ }
+ });
+
+ setErrors(newErrors);
+
+ if (!hasErrors) {
+ // Submit to the API
+ console.log({
+ id: operationId,
+ parentId,
+ children: selectedBatchNumbers.map((bn) => ({
+ trackedEntityId: bn.id,
+ quantity: bn.quantity,
+ })),
+ });
+ onClose();
+ }
+ }, [
+ selectedBatchNumbers,
+ validateBatchNumber,
+ operationId,
+ parentId,
+ onClose,
+ ]);
+
+ const validateBatchInput = useCallback(
+ (value: string, index: number) => {
+ if (!value) {
+ setErrors((prev) => ({ ...prev, [index]: "Batch number is required" }));
+ return false;
+ }
+
+ // Check for duplicates by comparing with all other batch numbers
+ // This ensures we catch duplicates even after adding new batch numbers
+ const duplicateIndices = selectedBatchNumbers
+ .map((bn, i) => (bn.id === value && i !== index ? i : -1))
+ .filter((i) => i !== -1);
+
+ if (duplicateIndices.length > 0) {
+ setErrors((prev) => ({ ...prev, [index]: "Duplicate batch number" }));
+ return false;
+ }
+
+ // Check if batch number exists in options
+ const batchOption = options.find((option) => option.value === value);
+ if (!batchOption) {
+ setErrors((prev) => ({ ...prev, [index]: "Invalid batch number" }));
+ return false;
+ }
+
+ // Check if the requested quantity exceeds available quantity
+ const currentBatchNumber = selectedBatchNumbers[index];
+ if (currentBatchNumber.quantity > batchOption.availableQuantity) {
+ // If we need more than available, create a new batch row with remaining quantity
+ const remainingQuantity =
+ currentBatchNumber.quantity - batchOption.availableQuantity;
+
+ // Update current row to use maximum available quantity
+ updateBatchNumber({
+ ...currentBatchNumber,
+ id: value,
+ quantity: batchOption.availableQuantity,
+ });
+
+ // Add a new row for the remaining quantity
+ setSelectedBatchNumbers((prev) => {
+ const newIndex = prev.length;
+ return [
+ ...prev,
+ { index: newIndex, id: "", quantity: remainingQuantity },
+ ];
+ });
+ }
+
+ // Clear errors if valid
+ setErrors((prev) => {
+ const newErrors = { ...prev };
+ delete newErrors[index];
+ return newErrors;
+ });
+ return true;
+ },
+ [selectedBatchNumbers, options, updateBatchNumber]
+ );
+
return (
<Modal open onOpenChange={onClose}>
<ModalContent>
<ModalHeader>
- <ModalTitle>Tracking</ModalTitle>
+ <ModalTitle>Issue Batch Tracked Parts</ModalTitle>
</ModalHeader>
+ <ModalBody>
+ <Tabs defaultValue="scan">
+ <TabsList className="grid w-full grid-cols-2 mb-4">
+ <TabsTrigger value="scan">
+ <LuQrCode className="mr-2" />
+ Scan
+ </TabsTrigger>
+ <TabsTrigger value="select">
+ <LuList className="mr-2" />
+ Select
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="scan">
+ <div className="flex flex-col gap-4">
+ {selectedBatchNumbers.map((batchNumber, index) => (
+ <div key={index} className="flex flex-col gap-2">
+ <div className="flex items-center gap-2">
+ <div className="flex-1">
+ <InputGroup>
+ <Input
+ value={batchNumber.id}
+ onChange={(e) => {
+ const newValue = e.target.value;
+ updateBatchNumber({
+ ...batchNumber,
+ id: newValue,
+ });
+ }}
+ onBlur={(e) => {
+ validateBatchInput(e.target.value, index);
+ }}
+ placeholder="Scan batch number"
+ />
+ <InputRightElement className="pl-2">
+ {!errors[index] && batchNumber.id ? (
+ <LuCheck className="text-emerald-500" />
+ ) : (
+ <LuQrCode />
+ )}
+ </InputRightElement>
+ </InputGroup>
+ </div>
+ <div className="w-24">
+ <NumberField
+ id={`quantity-${index}`}
+ value={batchNumber.quantity}
+ onChange={(value) =>
+ updateBatchNumber({
+ ...batchNumber,
+ quantity: value,
+ })
+ }
+ minValue={1}
+ maxValue={
+ options.find((o) => o.value === batchNumber.id)
+ ?.availableQuantity ?? 999999
+ }
+ >
+ <NumberInputGroup className="relative">
+ <NumberInput />
+ <NumberInputStepper>
+ <NumberIncrementStepper>
+ <LuChevronUp size="1em" strokeWidth="3" />
+ </NumberIncrementStepper>
+ <NumberDecrementStepper>
+ <LuChevronDown size="1em" strokeWidth="3" />
+ </NumberDecrementStepper>
+ </NumberInputStepper>
+ </NumberInputGroup>
+ </NumberField>
+ </div>
+ {index > 0 && (
+ <IconButton
+ aria-label="Remove Batch Number"
+ icon={<LuX />}
+ variant="ghost"
+ onClick={() => removeBatchNumber(index)}
+ />
+ )}
+ </div>
+ {errors[index] && (
+ <span className="text-xs text-destructive">
+ {errors[index]}
+ </span>
+ )}
+ </div>
+ ))}
+ <div>
+ <Button
+ type="button"
+ variant="secondary"
+ leftIcon={<LuCirclePlus />}
+ onClick={addBatchNumber}
+ >
+ Add
+ </Button>
+ </div>
+ </div>
+ </TabsContent>
+ <TabsContent value="select">
+ <div className="flex flex-col gap-4">
+ {selectedBatchNumbers.map((batchNumber, index) => (
+ <div key={index} className="flex flex-col gap-2">
+ <div className="flex items-center gap-2">
+ <div className="flex-1">
+ <ComboboxBase
+ value={batchNumber.id}
+ onChange={(value) => {
+ updateBatchNumber({
+ ...batchNumber,
+ id: value,
+ });
+ validateBatchInput(value, index);
+ }}
+ options={options}
+ placeholder="Select batch number"
+ />
+ </div>
+ <div className="w-24">
+ <NumberField
+ value={batchNumber.quantity}
+ onChange={(value) =>
+ updateBatchNumber({
+ ...batchNumber,
+ quantity: value,
+ })
+ }
+ minValue={1}
+ maxValue={
+ options.find((o) => o.value === batchNumber.id)
+ ?.availableQuantity ?? 999999
+ }
+ >
+ <NumberInputGroup className="relative">
+ <NumberInput />
+ <NumberInputStepper>
+ <NumberIncrementStepper>
+ <LuChevronUp size="1em" strokeWidth="3" />
+ </NumberIncrementStepper>
+ <NumberDecrementStepper>
+ <LuChevronDown size="1em" strokeWidth="3" />
+ </NumberDecrementStepper>
+ </NumberInputStepper>
+ </NumberInputGroup>
+ </NumberField>
+ </div>
+ {index > 0 && (
+ <IconButton
+ aria-label="Remove Batch Number"
+ icon={<LuX />}
+ variant="ghost"
+ onClick={() => removeBatchNumber(index)}
+ />
+ )}
+ </div>
+ {errors[index] && (
+ <span className="text-xs text-destructive">
+ {errors[index]}
+ </span>
+ )}
+ </div>
+ ))}
+ <div>
+ <Button
+ type="button"
+ variant="secondary"
+ leftIcon={<LuCirclePlus />}
+ onClick={addBatchNumber}
+ >
+ Add Batch
+ </Button>
+ </div>
+ </div>
+ </TabsContent>
+ </Tabs>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button variant="primary" onClick={handleSubmit}>
+ Issue
+ </Button>
+ </ModalFooter>
</ModalContent>
</Modal>
);
}
+function useBatchNumbers(itemId?: string) {
+ const batchNumbersFetcher =
+ useFetcher<Awaited<ReturnType<typeof getBatchNumbersForItem>>>();
+
+ useEffect(() => {
+ if (itemId) {
+ batchNumbersFetcher.load(path.to.api.batchNumbers(itemId));
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [itemId]);
+
+ return { data: batchNumbersFetcher.data };
+}
+
function IssueModal({
operationId,
material,
@@ -2422,13 +3226,12 @@ function IssueModal({
name="adjustmentType"
label="Adjustment Type"
options={[
- { label: "Set Quantity", value: "Set Quantity" },
{
- label: "Positive Adjustment",
+ label: "Add to Inventory",
value: "Positive Adjmt.",
},
{
- label: "Negative Adjustment",
+ label: "Pull from Inventory",
value: "Negative Adjmt.",
},
]}
diff --git a/apps/mes/app/routes/api+/batch-numbers.ts b/apps/mes/app/routes/api+/batch-numbers.ts
new file mode 100644
index 0000000000..4147b4a44f
--- /dev/null
+++ b/apps/mes/app/routes/api+/batch-numbers.ts
@@ -0,0 +1,24 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { getBatchNumbersForItem } from "~/services/inventory.service";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {});
+
+ const url = new URL(request.url);
+ const itemId = url.searchParams.get("itemId");
+ if (!itemId) {
+ return json({
+ data: [],
+ error: null,
+ });
+ }
+
+ return json(
+ await getBatchNumbersForItem(client, {
+ companyId,
+ itemId,
+ })
+ );
+}
diff --git a/apps/mes/app/routes/api+/serial-numbers.ts b/apps/mes/app/routes/api+/serial-numbers.ts
new file mode 100644
index 0000000000..31fefd2c0d
--- /dev/null
+++ b/apps/mes/app/routes/api+/serial-numbers.ts
@@ -0,0 +1,24 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { getSerialNumbersForItem } from "~/services/inventory.service";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {});
+
+ const url = new URL(request.url);
+ const itemId = url.searchParams.get("itemId");
+ if (!itemId) {
+ return json({
+ data: [],
+ error: null,
+ });
+ }
+
+ return json(
+ await getSerialNumbersForItem(client, {
+ itemId,
+ companyId,
+ })
+ );
+}
diff --git a/apps/mes/app/services/inventory.service.ts b/apps/mes/app/services/inventory.service.ts
index 343a55f2ce..849f766c94 100644
--- a/apps/mes/app/services/inventory.service.ts
+++ b/apps/mes/app/services/inventory.service.ts
@@ -11,6 +11,41 @@ export const inventoryAdjustmentValidator = z.object({
quantity: zfd.numeric(z.number().min(1, { message: "Quantity is required" })),
});
+export async function getBatchNumbersForItem(
+ client: SupabaseClient<Database>,
+ args: {
+ itemId: string;
+ companyId: string;
+ isReadOnly?: boolean;
+ }
+) {
+ return client
+ .from("trackedEntity")
+ .select("*")
+ .eq("sourceDocument", "Item")
+ .eq("sourceDocumentId", args.itemId)
+ .eq("companyId", args.companyId)
+ .gte("quantity", 1);
+}
+
+export async function getSerialNumbersForItem(
+ client: SupabaseClient<Database>,
+ args: {
+ itemId: string;
+ companyId: string;
+ }
+) {
+ let query = client
+ .from("trackedEntity")
+ .select("*")
+ .eq("sourceDocument", "Item")
+ .eq("sourceDocumentId", args.itemId)
+ .eq("companyId", args.companyId)
+ .eq("quantity", 1);
+
+ return query;
+}
+
export async function insertManualInventoryAdjustment(
client: SupabaseClient<Database>,
inventoryAdjustment: z.infer<typeof inventoryAdjustmentValidator> & {
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index a2e5297383..b62c8f450f 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -11,6 +11,10 @@ export const path = {
to: {
api: {
autodeskToken: `${api}/autodesk/token`,
+ batchNumbers: (itemId: string) =>
+ generatePath(`${api}/batch-numbers?itemId=${itemId}`),
+ serialNumbers: (itemId: string) =>
+ generatePath(`${api}/serial-numbers?itemId=${itemId}`),
},
file: {
previewImage: (bucket: string, path: string) =>
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index 5e349c7873..289688af9c 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -5,11 +5,21 @@ import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { corsHeaders } from "../lib/headers.ts";
import { Database } from "../lib/types.ts";
+import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
const payloadValidator = z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal("jobComplete"),
+ jobId: z.string(),
+ quantityComplete: z.number(),
+ shelfId: z.string().optional(),
+ locationId: z.string().optional(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
z.object({
type: z.literal("jobOperation"),
id: z.string(),
@@ -31,11 +41,16 @@ const payloadValidator = z.discriminatedUnion("type", [
userId: z.string(),
}),
z.object({
- type: z.literal("jobComplete"),
- jobId: z.string(),
- quantityComplete: z.number(),
- shelfId: z.string().optional(),
- locationId: z.string().optional(),
+ type: z.literal("trackedEntitiesToOperation"),
+ id: z.string(),
+ activityDescription: z.string(),
+ parentId: z.string(),
+ children: z.array(
+ z.object({
+ trackedEntityId: z.string(),
+ quantity: z.number(),
+ })
+ ),
companyId: z.string(),
userId: z.string(),
}),
@@ -59,6 +74,68 @@ serve(async (req: Request) => {
[];
switch (validatedPayload.type) {
+ case "jobComplete": {
+ const {
+ jobId,
+ quantityComplete,
+ shelfId,
+ locationId,
+ companyId,
+ userId,
+ } = validatedPayload;
+
+ await db.transaction().execute(async (trx) => {
+ const job = await trx
+ .selectFrom("job")
+ .where("id", "=", jobId)
+ .select(["itemId", "quantityReceivedToInventory"])
+ .executeTakeFirst();
+
+ const item = await trx
+ .selectFrom("item")
+ .where("id", "=", job?.itemId!)
+ .select(["readableId"])
+ .executeTakeFirst();
+
+ const quantityReceivedToInventory =
+ quantityComplete - (job?.quantityReceivedToInventory ?? 0);
+
+ await trx
+ .updateTable("job")
+ .set({
+ status: "Completed" as const,
+ completedDate: new Date().toISOString(),
+ quantityComplete,
+ quantityReceivedToInventory,
+ updatedAt: new Date().toISOString(),
+ updatedBy: userId,
+ })
+ .where("id", "=", jobId)
+ .execute();
+
+ itemLedgerInserts.push({
+ entryType: "Assembly Output",
+ documentType: "Job Receipt",
+ documentId: jobId,
+ companyId,
+ itemId: job?.itemId!,
+ itemReadableId: item?.readableId,
+ quantity: quantityReceivedToInventory,
+ locationId,
+ shelfId,
+ createdBy: userId,
+ });
+
+ if (itemLedgerInserts.length > 0) {
+ await trx
+ .insertInto("itemLedger")
+ .values(itemLedgerInserts)
+ .execute();
+ }
+ });
+
+ break;
+ }
case "jobOperation": {
const { id, companyId, userId } = validatedPayload;
await db.transaction().execute(async (trx) => {
@@ -68,6 +145,9 @@ serve(async (req: Request) => {
.where("quantityToIssue", ">", 0)
.where("itemType", "in", ["Material", "Part", "Consumable"])
.where("methodType", "!=", "Make")
+ .where("estimatedQuantity", ">", 0)
+ .where("requiresBatchTracking", "=", false)
+ .where("requiresSerialTracking", "=", false)
.selectAll()
.execute();
@@ -214,7 +294,7 @@ serve(async (req: Request) => {
adjustmentType === "Positive Adjmt."
? Number(quantity)
: adjustmentType === "Negative Adjmt."
- ? -Number(quantity)
+ ? Number(quantity)
: Number(quantity) - Number(material?.quantityIssued); // set quantity
if (
@@ -232,7 +312,10 @@ serve(async (req: Request) => {
shelfId: material?.defaultShelf
? pickMethod?.defaultShelfId
: material?.shelfId,
- quantity: -Number(quantityToIssue),
+ quantity:
+ adjustmentType === "Positive Adjmt."
+ ? Number(quantityToIssue)
+ : -Number(quantityToIssue),
createdBy: userId,
});
}
@@ -269,7 +352,10 @@ serve(async (req: Request) => {
documentLineId: id,
companyId,
itemId: itemId!,
- quantity: -Number(quantity ?? 0),
+ quantity:
+ adjustmentType === "Positive Adjmt."
+ ? Number(quantity)
+ : -Number(quantity),
locationId: job?.locationId,
shelfId: pickMethod?.defaultShelfId,
createdBy: userId,
@@ -322,57 +408,259 @@ serve(async (req: Request) => {
});
break;
}
- case "jobComplete": {
+ case "trackedEntitiesToOperation": {
const {
- jobId,
- quantityComplete,
- shelfId,
- locationId,
+ id: operationId,
+ children,
+ activityDescription,
+ parentId,
companyId,
userId,
} = validatedPayload;
await db.transaction().execute(async (trx) => {
+ // Get job operation details
+ const jobOperation = await trx
+ .selectFrom("jobOperation")
+ .where("id", "=", operationId)
+ .select(["jobId", "jobMakeMethodId"])
+ .executeTakeFirst();
+
+ // Get job location
const job = await trx
.selectFrom("job")
- .where("id", "=", jobId)
- .select(["itemId", "quantityReceivedToInventory"])
+ .where("id", "=", jobOperation?.jobId!)
+ .select("locationId")
.executeTakeFirst();
+ // Get parent tracked entity details
+ const parentTrackedEntity = await trx
+ .selectFrom("trackedEntity")
+ .where("id", "=", parentId)
+ .select([
+ "id",
+ "sourceDocumentId",
+ "quantity",
+ "attributes",
+ "status",
+ ])
+ .executeTakeFirst();
+
+ if (!parentTrackedEntity) {
+ throw new Error("Parent tracked entity not found");
+ }
+
+ // Get item details
const item = await trx
.selectFrom("item")
- .where("id", "=", job?.itemId!)
- .select(["readableId"])
+ .where("id", "=", parentTrackedEntity.sourceDocumentId)
+ .select(["id", "readableId", "name", "type", "itemTrackingType"])
.executeTakeFirst();
- const quantityReceivedToInventory =
- quantityComplete - (job?.quantityReceivedToInventory ?? 0);
+ // Get current inventory quantity from item ledger
+ const itemLedgerQuantity = await trx
+ .selectFrom("itemLedger")
+ .where("trackedEntityId", "=", parentId)
+ .select(["quantity", "shelfId"])
+ .execute();
+
+ const currentQuantity = itemLedgerQuantity.reduce(
+ (sum, record) => sum + record.quantity,
+ 0
+ );
+ const shelfId = itemLedgerQuantity[0]?.shelfId;
+ // Create tracked activity
+ const activityId = nanoid();
await trx
- .updateTable("job")
- .set({
- status: "Completed" as const,
- completedDate: new Date().toISOString(),
- quantityComplete,
- quantityReceivedToInventory,
- updatedAt: new Date().toISOString(),
- updatedBy: userId,
+ .insertInto("trackedActivity")
+ .values({
+ id: activityId,
+ type: "Operation Consumption",
+ sourceDocument: "Job Operation",
+ sourceDocumentId: operationId,
+ attributes: {
+ description: activityDescription,
+ },
+ companyId,
+ createdBy: userId,
})
- .where("id", "=", jobId)
.execute();
- itemLedgerInserts.push({
- entryType: "Assembly Output",
- documentType: "Job Receipt",
- documentId: jobId,
- companyId,
- itemId: job?.itemId!,
- itemReadableId: item?.readableId,
- quantity: quantityReceivedToInventory,
- locationId,
- shelfId,
- createdBy: userId,
- });
+ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =
+ [];
+ const trackedActivityInputs: Database["public"]["Tables"]["trackedActivityInput"]["Insert"][] =
+ [];
+
+ // If quantities don't match, split the batch
+ if (currentQuantity !== parentTrackedEntity.quantity) {
+ const remainingQuantity =
+ parentTrackedEntity.quantity - currentQuantity;
+ const newTrackedEntityId = nanoid();
+
+ // Create split activity
+ const splitActivityId = nanoid();
+ await trx
+ .insertInto("trackedActivity")
+ .values({
+ id: splitActivityId,
+ type: "Split",
+ sourceDocument: "Job Operation",
+ sourceDocumentId: operationId,
+ attributes: {
+ "Original Quantity": parentTrackedEntity.quantity,
+ "Consumed Quantity": currentQuantity,
+ "Remaining Quantity": remainingQuantity,
+ },
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+
+ // Record original entity as input
+ await trx
+ .insertInto("trackedActivityInput")
+ .values({
+ trackedActivityId: splitActivityId,
+ trackedEntityId: parentId,
+ quantity: parentTrackedEntity.quantity,
+ entityType: "Item",
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+
+ // Create new tracked entity for remaining quantity
+ await trx
+ .insertInto("trackedEntity")
+ .values({
+ id: newTrackedEntityId,
+ sourceDocumentId: item?.id!,
+ sourceDocument: "Item",
+ sourceDocumentReadableId: item?.readableId,
+ quantity: remainingQuantity,
+ status: parentTrackedEntity.status ?? "Available",
+ attributes: parentTrackedEntity.attributes,
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+
+ // Update original entity attributes with split reference
+ await trx
+ .updateTable("trackedEntity")
+ .set({
+ quantity: currentQuantity,
+ attributes: {
+ ...((parentTrackedEntity.attributes as Record<
+ string,
+ unknown
+ >) ?? {}),
+ "Split Entity ID": newTrackedEntityId,
+ },
+ })
+ .where("id", "=", parentId)
+ .execute();
+
+ // Record outputs from split
+ await trx
+ .insertInto("trackedActivityOutput")
+ .values([
+ {
+ trackedActivityId: splitActivityId!,
+ trackedEntityId: newTrackedEntityId!,
+ quantity: remainingQuantity,
+ companyId,
+ createdBy: userId,
+ },
+ {
+ trackedActivityId: splitActivityId!,
+ trackedEntityId: parentId!,
+ quantity: currentQuantity,
+ companyId,
+ createdBy: userId,
+ },
+ ])
+ .execute();
+
+ // Create item ledger entries for split
+ itemLedgerInserts.push(
+ {
+ entryType: "Negative Adjmt.",
+ documentType: "Batch Split",
+ documentId: splitActivityId,
+ companyId,
+ itemId: item?.id!,
+ itemReadableId: item?.readableId,
+ quantity: -parentTrackedEntity.quantity,
+ locationId: job?.locationId,
+ shelfId,
+ trackedEntityId: parentId,
+ createdBy: userId,
+ },
+ {
+ entryType: "Positive Adjmt.",
+ documentType: "Batch Split",
+ documentId: splitActivityId,
+ companyId,
+ itemId: item?.id!,
+ itemReadableId: item?.readableId,
+ quantity: currentQuantity,
+ locationId: job?.locationId,
+ shelfId,
+ trackedEntityId: parentId,
+ createdBy: userId,
+ },
+ {
+ entryType: "Positive Adjmt.",
+ documentType: "Batch Split",
+ documentId: splitActivityId,
+ companyId,
+ itemId: item?.id!,
+ itemReadableId: item?.readableId,
+ quantity: remainingQuantity,
+ locationId: job?.locationId,
+ shelfId,
+ trackedEntityId: newTrackedEntityId,
+ createdBy: userId,
+ }
+ );
+ }
+
+ // Process each child tracked entity
+ for (const child of children) {
+ const { trackedEntityId, quantity } = child;
+
+ trackedActivityInputs.push({
+ trackedActivityId: activityId,
+ trackedEntityId,
+ quantity,
+ entityType: "Material",
+ companyId,
+ createdBy: userId,
+ });
+
+ itemLedgerInserts.push({
+ entryType: "Consumption",
+ documentType: "Job Consumption",
+ documentId: operationId,
+ companyId,
+ itemId: parentTrackedEntity.sourceDocumentId,
+ itemReadableId: item?.readableId,
+ quantity: -quantity,
+ locationId: job?.locationId,
+ shelfId,
+ trackedEntityId,
+ createdBy: userId,
+ });
+ }
+
+ if (trackedActivityInputs.length > 0) {
+ await trx
+ .insertInto("trackedActivityInput")
+ .values(trackedActivityInputs)
+ .execute();
+ }
if (itemLedgerInserts.length > 0) {
await trx
diff --git a/packages/database/supabase/functions/lib/utils.ts b/packages/database/supabase/functions/lib/utils.ts
index 8c5b47a849..5890d06006 100644
--- a/packages/database/supabase/functions/lib/utils.ts
+++ b/packages/database/supabase/functions/lib/utils.ts
@@ -11,6 +11,7 @@ export interface TrackedEntityAttributes {
"Shipment Line"?: string;
Shipment?: string;
"Split Entity ID"?: string;
+ Shelf?: string;
}
// used to generate sequences
diff --git a/packages/utils/src/types.ts b/packages/utils/src/types.ts
index e33d5a807e..a11cec2634 100644
--- a/packages/utils/src/types.ts
+++ b/packages/utils/src/types.ts
@@ -1,2 +1,17 @@
export type PickPartial<T, K extends keyof T> = Omit<T, K> &
Partial<Pick<T, K>>;
+
+export interface TrackedEntityAttributes {
+ "Batch Number"?: string;
+ Customer?: string;
+ "Purchase Order"?: string;
+ "Receipt Line Index"?: number;
+ "Receipt Line"?: string;
+ Receipt?: string;
+ Supplier?: string;
+ "Serial Number"?: string;
+ "Shipment Line Index"?: number;
+ "Shipment Line"?: string;
+ Shipment?: string;
+ "Split Entity ID"?: string;
+}