Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add batch properties to receipt
Brad Barbin145ab9fda163
diff --git a/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx b/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsxindex 5cd809710f..599afba1eb 100644--- a/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx+++ b/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx@@ -84,7 +84,12 @@ function ParameterField({ parameter }: ParameterFieldProps) {case "numeric":return (<div className="space-y-2">- <Label htmlFor={parameter.key}>{parameter.label}</Label>+ <Label+ className="text-xs text-muted-foreground"+ htmlFor={parameter.key}+ >+ {parameter.label}+ </Label><NumberFieldonChange={(value) => handleChange(Number(value))}value={formData[parameter.key] as number}@@ -107,7 +112,12 @@ function ParameterField({ parameter }: ParameterFieldProps) {case "text":return (<div className="space-y-2">- <Label htmlFor={parameter.key}>{parameter.label}</Label>+ <Label+ className="text-xs text-muted-foreground"+ htmlFor={parameter.key}+ >+ {parameter.label}+ </Label><Inputid={parameter.key}type="text"@@ -121,7 +131,12 @@ function ParameterField({ parameter }: ParameterFieldProps) {case "list":return (<div className="space-y-2">- <Label htmlFor={parameter.key}>{parameter.label}</Label>+ <Label+ className="text-xs text-muted-foreground"+ htmlFor={parameter.key}+ >+ {parameter.label}+ </Label><Selectvalue={formData[parameter.key] as string}onValueChange={handleChange}@@ -143,7 +158,12 @@ function ParameterField({ parameter }: ParameterFieldProps) {case "boolean":return (<div className="flex flex-col items-start gap-2">- <Label htmlFor={parameter.key}>{parameter.label}</Label>+ <Label+ className="text-xs text-muted-foreground"+ htmlFor={parameter.key}+ >+ {parameter.label}+ </Label><Switchid={parameter.key}checked={(formData[parameter.key] as boolean) || false}diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 136df89c09..1bdf3c977f 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -213,14 +213,15 @@ export async function deleteShippingMethod(export async function getBatchProperties(client: SupabaseClient<Database>,- itemId: string,+ itemIds: string[],companyId: string) {return client.from("batchProperty").select("*")- .eq("itemId", itemId)- .eq("companyId", companyId);+ .in("itemId", itemIds)+ .eq("companyId", companyId)+ .order("sortOrder");}export async function getInventoryItems(@@ -342,7 +343,7 @@ export async function getReceiptLineTracking(return client.from("receiptLineTracking").select(- "*, batchNumber(id, number, manufacturingDate, expirationDate), serialNumber(id, number)"+ "*, batchNumber(id, number, manufacturingDate, expirationDate, properties), serialNumber(id, number)").eq("receiptId", receiptId);}diff --git a/apps/erp/app/modules/inventory/Batches/BatchHeader.tsx b/apps/erp/app/modules/inventory/ui/Batches/BatchHeader.tsxsimilarity index 100%rename from apps/erp/app/modules/inventory/Batches/BatchHeader.tsxrename to apps/erp/app/modules/inventory/ui/Batches/BatchHeader.tsxdiff --git a/apps/erp/app/modules/inventory/Batches/BatchProperties.tsx b/apps/erp/app/modules/inventory/ui/Batches/BatchPropertiesConfig.tsxsimilarity index 72%rename from apps/erp/app/modules/inventory/Batches/BatchProperties.tsxrename to apps/erp/app/modules/inventory/ui/Batches/BatchPropertiesConfig.tsxindex 9624a185c6..0ecbc1e462 100644--- a/apps/erp/app/modules/inventory/Batches/BatchProperties.tsx+++ b/apps/erp/app/modules/inventory/ui/Batches/BatchPropertiesConfig.tsx@@ -18,6 +18,7 @@ import {IconButton,ModalCard,ModalCardBody,+ ModalCardContent,ModalCardHeader,ModalCardProvider,ModalCardTitle,@@ -38,12 +39,7 @@ import {} from "@dnd-kit/core";import { SortableContext, useSortable } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";-import {- useFetcher,- useFetchers,- useParams,- useSubmit,-} from "@remix-run/react";+import { useFetcher, useFetchers, useSubmit } from "@remix-run/react";import { useEffect, useRef, useState } from "react";import { createPortal } from "react-dom";import {@@ -58,20 +54,21 @@ import { configurationParameterDataTypes } from "~/modules/items/items.models";import type { action as batchPropertyAction } from "~/routes/x+/inventory+/batch-property+/$itemId.property";import { path } from "~/utils/path";import { capitalize } from "~/utils/string";-import { batchPropertyValidator } from "../inventory.models";-import type { BatchProperty } from "../types";+import { batchPropertyValidator } from "../../inventory.models";+import type { BatchProperty } from "../../types";-export default function BatchPropertiesForm({+export default function BatchPropertiesConfig({+ itemId,properties: initialProperties,type = "card",onClose,}: {+ itemId: string;properties: BatchProperty[];type?: "card" | "modal";onClose?: () => void;}) {- const { isList, itemId, onChangeCheckForListType, setIsList } =- useBatchProperties();+ const { isList, onChangeCheckForListType, setIsList } = useBatchProperties();const submit = useSubmit();const fetcher = useFetcher<typeof batchPropertyAction>();@@ -115,107 +112,111 @@ export default function BatchPropertiesForm({return (<ModalCardProvider type={type}><ModalCard onClose={onClose}>- <ModalCardHeader>- <ModalCardTitle>Batch Properties</ModalCardTitle>- </ModalCardHeader>-- <ModalCardBody>- <div className="flex flex-col gap-4">- <div className="p-6 border rounded-lg">- <ValidatedForm- action={path.to.batchProperty(itemId)}- method="post"- fetcher={fetcher}- validator={batchPropertyValidator}- resetAfterSubmit- onSubmit={() => {- setIsList(false);- }}- defaultValues={{- itemId: itemId,- label: "",- dataType: "text",- listOptions: [],- }}- className="w-full"- >- <Hidden name="id" />- <Hidden name="itemId" />- <VStack spacing={4}>- <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">- <VStack>- <Input name="label" label="Label" />- </VStack>-- <Select- name="dataType"- label="Data Type"- options={configurationParameterDataTypes.map((type) => ({- label: (- <HStack className="w-full">- <ConfiguratorDataTypeIcon- type={type}- className="mr-2"+ <ModalCardContent>+ <ModalCardHeader>+ <ModalCardTitle>Batch Properties</ModalCardTitle>+ </ModalCardHeader>++ <ModalCardBody>+ <div className="flex flex-col gap-4">+ <div className="p-6 border rounded-lg">+ <ValidatedForm+ action={path.to.batchProperty(itemId)}+ method="post"+ fetcher={fetcher}+ validator={batchPropertyValidator}+ resetAfterSubmit+ onSubmit={() => {+ setIsList(false);+ }}+ defaultValues={{+ itemId: itemId,+ label: "",+ dataType: "text",+ listOptions: [],+ }}+ className="w-full"+ >+ <Hidden name="id" />+ <Hidden name="itemId" />+ <VStack spacing={4}>+ <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">+ <VStack>+ <Input name="label" label="Label" />+ </VStack>++ <Select+ name="dataType"+ label="Data Type"+ options={configurationParameterDataTypes.map(+ (type) => ({+ label: (+ <HStack className="w-full">+ <ConfiguratorDataTypeIcon+ type={type}+ className="mr-2"+ />+ {capitalize(type)}+ </HStack>+ ),+ value: type,+ })+ )}+ onChange={onChangeCheckForListType}+ />+ {isList && (+ <ArrayInput name="listOptions" label="List Options" />+ )}+ </div>+ <HStack spacing={2}>+ <Submit+ leftIcon={<LuCirclePlus />}+ isDisabled={fetcher.state !== "idle"}+ isLoading={fetcher.state !== "idle"}+ >+ Add Property+ </Submit>+ </HStack>+ </VStack>+ </ValidatedForm>+ </div>++ {properties.length > 0 && (+ <DndContext+ sensors={sensors}+ onDragStart={onDragStart}+ onDragEnd={onDragEnd}+ >+ <SortableContext items={properties.map((p) => p.id)}>+ <div className="flex flex-col gap-2">+ {properties.map((property) => (+ <BatchPropertyComponent+ key={property.id}+ property={property}+ />+ ))}+ </div>+ </SortableContext>+ <ClientOnly fallback={null}>+ {() =>+ createPortal(+ <DragOverlay>+ {activeProperty && (+ <BatchPropertyComponent+ property={activeProperty}+ isOverlay/>- {capitalize(type)}- </HStack>- ),- value: type,- }))}- onChange={onChangeCheckForListType}- />- {isList && (- <ArrayInput name="listOptions" label="List Options" />- )}- </div>- <HStack spacing={2}>- <Submit- leftIcon={<LuCirclePlus />}- isDisabled={fetcher.state !== "idle"}- isLoading={fetcher.state !== "idle"}- >- Add Property- </Submit>- </HStack>- </VStack>- </ValidatedForm>+ )}+ </DragOverlay>,+ document.body+ )+ }+ </ClientOnly>+ </DndContext>+ )}</div>-- {properties.length > 0 && (- <DndContext- sensors={sensors}- onDragStart={onDragStart}- onDragEnd={onDragEnd}- >- <SortableContext items={properties.map((p) => p.id)}>- <div className="flex flex-col gap-2">- {properties.map((property) => (- <BatchPropertyComponent- key={property.id}- property={property}- />- ))}- </div>- </SortableContext>- <ClientOnly fallback={null}>- {() =>- createPortal(- <DragOverlay>- {activeProperty && (- <BatchPropertyComponent- property={activeProperty}- isOverlay- />- )}- </DragOverlay>,- document.body- )- }- </ClientOnly>- </DndContext>- )}- </div>- </ModalCardBody>+ </ModalCardBody>+ </ModalCardContent></ModalCard></ModalCardProvider>);@@ -456,9 +457,6 @@ function BatchPropertyComponent({}function useBatchProperties(property?: BatchProperty) {- const { itemId } = useParams();- if (!itemId) throw new Error("Could not find itemId");-const [isList, setIsList] = useState(property?.dataType === "list");const onChangeCheckForListType = (@@ -474,7 +472,6 @@ function useBatchProperties(property?: BatchProperty) {return {isList,- itemId,onChangeCheckForListType,setIsList,};diff --git a/apps/erp/app/modules/inventory/ui/Batches/BatchPropertiesFields.tsx b/apps/erp/app/modules/inventory/ui/Batches/BatchPropertiesFields.tsxnew file mode 100644index 0000000000..76e312a36e--- /dev/null+++ b/apps/erp/app/modules/inventory/ui/Batches/BatchPropertiesFields.tsx@@ -0,0 +1,184 @@+import {+ Input,+ Label,+ NumberDecrementStepper,+ NumberField,+ NumberIncrementStepper,+ NumberInput,+ NumberInputGroup,+ NumberInputStepper,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Switch,+} from "@carbon/react";+import { useEffect, useState } from "react";+import {+ LuChevronDown,+ LuChevronUp,+ LuHash,+ LuList,+ LuText,+ LuToggleRight,+} from "react-icons/lu";+import type { BatchProperty } from "~/modules/inventory/types";++interface FormData {+ [key: string]: string | number | boolean;+}++interface PropertyFieldProps {+ property: BatchProperty;+ value: string | number | boolean;+ onChange: (value: string | number | boolean) => void;+}++function PropertyField({ property, value, onChange }: PropertyFieldProps) {+ const [localTextValue, setLocalTextValue] = useState((value as string) || "");++ useEffect(() => {+ setLocalTextValue(value as string);+ }, [value]);++ switch (property.dataType) {+ case "numeric":+ return (+ <div className="space-y-2">+ <Label+ className="flex items-center gap-2 font-normal text-xs text-muted-foreground"+ htmlFor={property.id}+ >+ <LuHash />+ {property.label}+ </Label>+ <NumberField+ onChange={(val) => onChange(Number(val))}+ value={value as number}+ >+ <NumberInputGroup className="relative">+ <NumberInput id={property.id} />+ <NumberInputStepper>+ <NumberIncrementStepper>+ <LuChevronUp size="1em" strokeWidth="3" />+ </NumberIncrementStepper>+ <NumberDecrementStepper>+ <LuChevronDown size="1em" strokeWidth="3" />+ </NumberDecrementStepper>+ </NumberInputStepper>+ </NumberInputGroup>+ </NumberField>+ </div>+ );++ case "text":+ return (+ <div className="space-y-2">+ <Label+ className="flex items-center gap-2 font-normal text-xs text-muted-foreground"+ htmlFor={property.id}+ >+ <LuText />+ {property.label}+ </Label>+ <Input+ id={property.id}+ type="text"+ value={localTextValue}+ onChange={(e) => setLocalTextValue(e.target.value)}+ onBlur={() => onChange(localTextValue)}+ className="w-full"+ />+ </div>+ );++ case "list":+ return (+ <div className="space-y-2">+ <Label+ className="flex items-center gap-2 font-normal text-xs text-muted-foreground"+ htmlFor={property.id}+ >+ <LuList />+ {property.label}+ </Label>+ <Select+ value={value as string}+ onValueChange={(val) => onChange(val)}+ >+ <SelectTrigger id={property.id}>+ <SelectValue placeholder="Select an option" />+ </SelectTrigger>+ <SelectContent>+ {property.listOptions?.map((option) => (+ <SelectItem key={option} value={option}>+ {option}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ );++ case "boolean":+ return (+ <div className="flex flex-col items-start gap-2">+ <Label+ className="flex items-center gap-2 font-normal text-xs text-muted-foreground"+ htmlFor={property.id}+ >+ <LuToggleRight />+ {property.label}+ </Label>+ <Switch+ id={property.id}+ checked={(value as boolean) || false}+ onCheckedChange={(val) => onChange(val)}+ className="mt-1"+ />+ </div>+ );++ default:+ return null;+ }+}++interface BatchPropertiesFieldsProps {+ itemId: string;+ properties: BatchProperty[];+ values: FormData;+ onChange: (values: FormData) => void;+}++export function BatchPropertiesFields({+ properties,+ values,+ onChange,+}: BatchPropertiesFieldsProps) {+ return properties.map((property) => (+ <PropertyField+ key={property.id}+ property={property}+ value={values[property.id] ?? getDefaultValue(property.dataType)}+ onChange={(value) => {+ onChange({+ ...values,+ [property.id]: value,+ });+ }}+ />+ ));+}++function getDefaultValue(dataType: string) {+ switch (dataType) {+ case "boolean":+ return false;+ case "numeric":+ return 0;+ default:+ return "";+ }+}diff --git a/apps/erp/app/modules/inventory/Batches/BatchesTable.tsx b/apps/erp/app/modules/inventory/ui/Batches/BatchesTable.tsxsimilarity index 100%rename from apps/erp/app/modules/inventory/Batches/BatchesTable.tsxrename to apps/erp/app/modules/inventory/ui/Batches/BatchesTable.tsxdiff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsxindex 04adc91512..991dbec6e9 100644--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx@@ -1,5 +1,6 @@import { useCarbon } from "@carbon/auth";import {+ Button,Card,CardContent,CardHeader,@@ -7,6 +8,7 @@ import {cn,Combobox,DatePicker,+ Heading,HStack,IconButton,Input,@@ -16,6 +18,7 @@ import {Tooltip,TooltipContent,TooltipTrigger,+ useDisclosure,VStack,} from "@carbon/react";import { type CalendarDate, parseDate } from "@internationalized/date";@@ -46,6 +49,7 @@ import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";import { TrackingTypeIcon } from "~/components/Icons";import { useRouteData, useUser } from "~/hooks";import type {+ BatchProperty,Receipt,ReceiptLine,ReceiptLineTracking,@@ -56,6 +60,8 @@ import { useItems } from "~/stores";import type { StorageItem } from "~/types";import { path } from "~/utils/path";import { stripSpecialCharacters } from "~/utils/string";+import BatchPropertiesConfig from "../Batches/BatchPropertiesConfig";+import { BatchPropertiesFields } from "../Batches/BatchPropertiesFields";const ReceiptLines = () => {const { receiptId } = useParams();@@ -68,6 +74,7 @@ const ReceiptLines = () => {receiptLines: ReceiptLine[];receiptFiles: PostgrestResponse<StorageItem>;receiptLineTracking: ReceiptLineTracking[];+ batchProperties: PostgrestResponse<BatchProperty>;}>(path.to.receipt(receiptId));const receiptsById = new Map<string, ReceiptLine>(@@ -199,6 +206,7 @@ const ReceiptLines = () => {[line.id]: newSerialNumbers,}));}}+ batchProperties={routeData?.batchProperties}batchNumber={routeData?.receiptLineTracking.find((t) => t.receiptLineId === line.id && t.batchNumber !== null@@ -207,6 +215,7 @@ const ReceiptLines = () => {number: "",manufacturingDate: null,expirationDate: null,+ properties: {},}}upload={(files) => upload(files, line.id)}@@ -228,6 +237,7 @@ function ReceiptLineItem({isReadOnly,onUpdate,files,+ batchProperties,batchNumber,serialNumbers,getPath,@@ -240,11 +250,13 @@ function ReceiptLineItem({className?: string;isReadOnly: boolean;files?: PostgrestResponse<StorageItem>;+ batchProperties?: PostgrestResponse<BatchProperty>;batchNumber: {id: string;number: string;manufacturingDate?: string | null;expirationDate?: string | null;+ properties?: any;};serialNumbers: { index: number; number: string }[];getPath: (file: StorageItem) => string;@@ -371,12 +383,15 @@ function ReceiptLineItem({</div></div>{line.requiresBatchTracking && (- <BatchForm- receipt={receipt}- line={line}- isReadOnly={isReadOnly}- initialValues={batchNumber}- />+ <>+ <BatchForm+ receipt={receipt}+ line={line}+ isReadOnly={isReadOnly}+ initialValues={batchNumber}+ batchProperties={batchProperties}+ />+ </>)}{line.requiresSerialTracking && (<SerialForm@@ -444,17 +459,20 @@ function ReceiptLineItem({function BatchForm({line,receipt,+ batchProperties,initialValues,isReadOnly,}: {line: ReceiptLine;receipt?: Receipt;isReadOnly: boolean;+ batchProperties?: PostgrestResponse<BatchProperty>;initialValues?: {id: string;number: string;manufacturingDate?: string | null;expirationDate?: string | null;+ properties?: any;};}) {const submit = useSubmit();@@ -462,6 +480,7 @@ function BatchForm({number: string;manufacturingDate?: CalendarDate;expirationDate?: CalendarDate;+ properties: any;}>(initialValues? {@@ -472,23 +491,44 @@ function BatchForm({expirationDate: initialValues.expirationDate? parseDate(initialValues.expirationDate): undefined,+ properties: initialValues.properties ?? {},}: {number: "",manufacturingDate: undefined,expirationDate: undefined,+ properties: {},});- const updateBatchNumber = async (newValues: typeof values) => {+ const { carbon } = useCarbon();+ const updateBatchNumber = async (newValues: typeof values, isNew = false) => {if (!receipt?.id || !newValues.number.trim()) return;- if (- newValues.manufacturingDate &&- newValues.manufacturingDate.year < 1900- ) {- return;- }- if (newValues.expirationDate && newValues.expirationDate.year < 1900) {++ const batchMatch = isNew+ ? (await carbon+ ?.from("batchNumber")+ .select("*")+ .eq("number", newValues.number.trim())+ .eq("itemId", line.itemId)+ .eq("companyId", receipt.companyId)+ .maybeSingle()) ?? { data: null }+ : { data: null };++ let valuesToSubmit = newValues;++ if (batchMatch.data) {+ // Just update the local state without triggering another database write+ setValues({+ ...newValues,+ manufacturingDate: batchMatch.data.manufacturingDate+ ? parseDate(batchMatch.data.manufacturingDate)+ : undefined,+ expirationDate: batchMatch.data.expirationDate+ ? parseDate(batchMatch.data.expirationDate)+ : undefined,+ properties: batchMatch.data.properties ?? {},+ });return;}@@ -497,15 +537,31 @@ function BatchForm({formData.append("receiptId", receipt.id);formData.append("receiptLineId", line.id);formData.append("trackingType", "batch");- formData.append("batchNumber", newValues.number.trim());- formData.append(- "manufacturingDate",- newValues.manufacturingDate?.toString() ?? ""- );- formData.append(- "expirationDate",- newValues.expirationDate?.toString() ?? ""- );+ formData.append("batchNumber", valuesToSubmit.number.trim());+ if (+ valuesToSubmit.manufacturingDate &&+ valuesToSubmit.manufacturingDate.year >= 1900+ ) {+ formData.append(+ "manufacturingDate",+ valuesToSubmit.manufacturingDate.toString()+ );+ } else {+ formData.append("manufacturingDate", "");+ }+ if (+ valuesToSubmit.expirationDate &&+ valuesToSubmit.expirationDate.year >= 1900+ ) {+ formData.append(+ "expirationDate",+ valuesToSubmit.expirationDate.toString()+ );+ } else {+ formData.append("expirationDate", "");+ }++ formData.append("properties", JSON.stringify(valuesToSubmit.properties));formData.append("quantity", line.receivedQuantity.toString());submit(formData, {@@ -521,63 +577,123 @@ function BatchForm({) => {const newValues = {...values,- [field]: newDate ?? undefined,+ [field]: newDate ?? null,};setValues(newValues);updateBatchNumber(newValues);};+ const handlePropertiesChange = (newProperties: any) => {+ const newValues = {+ ...values,+ properties: newProperties,+ };+ setValues(newValues);+ updateBatchNumber(newValues);+ };++ const propertiesDisclosure = useDisclosure();+return (- <div className="grid grid-cols-1 lg:grid-cols-3 gap-x-4 gap-y-3 w-full p-4 border rounded-lg">- <div className="flex flex-col gap-2 w-full">- <label className="text-xs text-muted-foreground flex items-center gap-2">- <LuGroup /> Batch Number- </label>-- <Input- placeholder={`Batch number`}- disabled={isReadOnly}- value={values.number}- onChange={(e) => {- setValues((prev) => ({- ...prev,- number: e.target.value,- }));- }}- onBlur={() => {- updateBatchNumber(values);- }}- />+ <div className="flex flex-col gap-6 w-full p-6 border rounded-lg">+ <div className="flex justify-between items-center gap-4">+ <Heading size="h4">Batch Properties</Heading>+ <Button+ variant="secondary"+ size="sm"+ onClick={propertiesDisclosure.onOpen}+ >+ Edit Properties+ </Button></div>+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 ">+ <div className="flex flex-col gap-2 w-full">+ <label className="text-xs text-muted-foreground flex items-center gap-2">+ <LuGroup /> Batch Number+ </label>++ <Input+ placeholder={`Batch number`}+ disabled={isReadOnly}+ value={values.number}+ onChange={(e) => {+ setValues((prev) => ({+ ...prev,+ number: e.target.value,+ }));+ }}+ onBlur={() => {+ updateBatchNumber(values, true);+ }}+ />+ </div>- <div className="flex flex-col gap-2 w-full">- <label className="text-xs text-muted-foreground flex items-center gap-2">- <LuCalendar /> Manufactured Date- </label>-- <DatePicker- value={values.manufacturingDate}- isDisabled={isReadOnly}- onChange={(newDate) => {- handleDateChange("manufacturingDate", newDate);- }}- />- </div>+ <div className="flex flex-col gap-2 w-full">+ <label className="text-xs text-muted-foreground flex items-center gap-2">+ <LuCalendar /> Manufactured Date+ </label>- <div className="flex flex-col gap-2 w-full">- <label className="text-xs text-muted-foreground flex items-center gap-2">- <LuCalendar /> Expiration Date- </label>-- <DatePicker- value={values.expirationDate}- isDisabled={isReadOnly}- onChange={(newDate) => {- handleDateChange("expirationDate", newDate);- }}- minValue={values.manufacturingDate}- />+ <DatePicker+ value={values.manufacturingDate}+ isDisabled={isReadOnly}+ onChange={(newDate) => {+ handleDateChange("manufacturingDate", newDate);+ }}+ />+ </div>++ <div className="flex flex-col gap-2 w-full">+ <label className="text-xs text-muted-foreground flex items-center gap-2">+ <LuCalendar /> Expiration Date+ </label>++ <DatePicker+ value={values.expirationDate}+ isDisabled={isReadOnly}+ onChange={(newDate) => {+ handleDateChange("expirationDate", newDate);+ }}+ minValue={values.manufacturingDate}+ />+ </div>++ <Suspense fallback={null}>+ <Await resolve={batchProperties}>+ {(resolvedBatchProperties) => {+ return (+ <BatchPropertiesFields+ itemId={line.itemId}+ properties={+ resolvedBatchProperties?.data?.filter(+ (p) => p.itemId === line.itemId+ ) ?? []+ }+ values={values.properties}+ onChange={(newProperties) => {+ handlePropertiesChange(newProperties);+ }}+ />+ );+ }}+ </Await>+ </Suspense></div>+ {propertiesDisclosure.isOpen && (+ <Suspense fallback={null}>+ <Await resolve={batchProperties}>+ {(resolvedBatchProperties) => {+ return (+ <BatchPropertiesConfig+ itemId={line.itemId}+ properties={resolvedBatchProperties?.data ?? []}+ type="modal"+ onClose={propertiesDisclosure.onClose}+ />+ );+ }}+ </Await>+ </Suspense>+ )}</div>);}@@ -667,7 +783,7 @@ function SerialForm({);return (- <div className="flex flex-col gap-2 p-4 border rounded-lg">+ <div className="flex flex-col gap-2 p-6 border rounded-lg"><label className="text-xs text-muted-foreground flex items-center gap-2"><LuBarcode /> Serial Numbers</label>diff --git a/apps/erp/app/routes/x+/batch+/$batchId.tsx b/apps/erp/app/routes/x+/batch+/$batchId.tsxindex d5b9ad2fbc..874f5c4e43 100644--- a/apps/erp/app/routes/x+/batch+/$batchId.tsx+++ b/apps/erp/app/routes/x+/batch+/$batchId.tsx@@ -48,8 +48,8 @@ import {} from "~/components";import { usePermissions, useUser } from "~/hooks";import type { BatchDetails } from "~/modules/inventory";-import BatchHeader from "~/modules/inventory/Batches/BatchHeader";import { getBatch, getBatchFiles } from "~/modules/inventory/inventory.service";+import BatchHeader from "~/modules/inventory/ui/Batches/BatchHeader";import type { Handle } from "~/utils/handle";import { getPrivateUrl, path } from "~/utils/path";@@ -169,7 +169,9 @@ function BatchSummary() {</HStack></CardHeader><CardContent>- <VStack></VStack>+ <VStack>+ <pre>{JSON.stringify(batch.properties, null, 2)}</pre>+ </VStack></CardContent></Card>);diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsxindex 10bfb2a038..672f651902 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx@@ -9,7 +9,7 @@ import { defer, redirect } from "@vercel/remix";import { Suspense } from "react";import { useRouteData } from "~/hooks";import { getBatchProperties, InventoryDetails } from "~/modules/inventory";-import BatchPropertiesForm from "~/modules/inventory/Batches/BatchProperties";+import BatchPropertiesConfig from "~/modules/inventory/ui/Batches/BatchPropertiesConfig";import type { Consumable, UnitOfMeasureListItem } from "~/modules/items";import {getItemQuantities,@@ -146,7 +146,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {itemShelfQuantities: itemShelfQuantities.data,quantities: quantities.data,itemId,- batchProperties: getBatchProperties(client, itemId, companyId),+ batchProperties: getBatchProperties(client, [itemId], companyId),});}@@ -240,8 +240,9 @@ export default function ConsumableInventoryRoute() {<Suspense fallback={null}><Await resolve={batchProperties}>{(resolvedProperties) => (- <BatchPropertiesForm+ <BatchPropertiesConfigkey={`batch-properties:${itemId}`}+ itemId={itemId}properties={resolvedProperties.data ?? []}/>)}diff --git a/apps/erp/app/routes/x+/inventory+/batches.tsx b/apps/erp/app/routes/x+/inventory+/batches.tsxindex bf0f94c677..53ff68764d 100644--- a/apps/erp/app/routes/x+/inventory+/batches.tsx+++ b/apps/erp/app/routes/x+/inventory+/batches.tsx@@ -6,7 +6,7 @@ import { Outlet, useLoaderData } from "@remix-run/react";import type { LoaderFunctionArgs } from "@vercel/remix";import { json, redirect } from "@vercel/remix";import { getBatches } from "~/modules/inventory";-import BatchesTable from "~/modules/inventory/Batches/BatchesTable";+import BatchesTable from "~/modules/inventory/ui/Batches/BatchesTable";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";diff --git a/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/material+/$itemId.inventory.tsxindex dff89d4ff8..0547c85ebd 100644--- a/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx@@ -9,7 +9,7 @@ import { defer, redirect } from "@vercel/remix";import { Suspense } from "react";import { useRouteData } from "~/hooks";import { getBatchProperties, InventoryDetails } from "~/modules/inventory";-import BatchPropertiesForm from "~/modules/inventory/Batches/BatchProperties";+import BatchPropertiesConfig from "~/modules/inventory/ui/Batches/BatchPropertiesConfig";import type { Material, UnitOfMeasureListItem } from "~/modules/items";import {getItemQuantities,@@ -143,7 +143,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {itemShelfQuantities: itemShelfQuantities.data,quantities: quantities.data,itemId,- batchProperties: getBatchProperties(client, itemId, companyId),+ batchProperties: getBatchProperties(client, [itemId], companyId),});}@@ -237,7 +237,8 @@ export default function MaterialInventoryRoute() {<Suspense fallback={null}><Await resolve={batchProperties}>{(resolvedProperties) => (- <BatchPropertiesForm+ <BatchPropertiesConfig+ itemId={itemId}key={`batch-properties:${itemId}`}properties={resolvedProperties.data ?? []}/>diff --git a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsxindex 3fb1a03f46..b8b897c006 100644--- a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx@@ -9,7 +9,7 @@ import { defer, redirect } from "@vercel/remix";import { Suspense } from "react";import { useRouteData } from "~/hooks";import { getBatchProperties, InventoryDetails } from "~/modules/inventory";-import BatchPropertiesForm from "~/modules/inventory/Batches/BatchProperties";+import BatchPropertiesConfig from "~/modules/inventory/ui/Batches/BatchPropertiesConfig";import type { PartSummary, UnitOfMeasureListItem } from "~/modules/items";import {getItemQuantities,@@ -135,7 +135,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {itemShelfQuantities: itemShelfQuantities.data,quantities: quantities.data,itemId,- batchProperties: getBatchProperties(client, itemId, companyId),+ batchProperties: getBatchProperties(client, [itemId], companyId),});}@@ -228,7 +228,8 @@ export default function PartInventoryRoute() {<Suspense fallback={null}><Await resolve={batchProperties}>{(resolvedProperties) => (- <BatchPropertiesForm+ <BatchPropertiesConfig+ itemId={itemId}key={`batch-properties:${itemId}`}properties={resolvedProperties.data ?? []}/>diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.tsxindex b16ae30391..17cc3111cc 100644--- a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx@@ -8,6 +8,7 @@ import { defer, redirect } from "@vercel/remix";import { PanelProvider } from "~/components/Layout";import {ReceiptHeader,+ getBatchProperties,getReceipt,getReceiptFiles,getReceiptLineTracking,@@ -49,9 +50,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}let receiptLineIds: string[] = [];+ let itemsWithBatchProperties: string[] = [];if (receiptLines.data) {receiptLineIds = receiptLines.data.map((line) => line.id);+ itemsWithBatchProperties = receiptLines.data+ .filter((line) => line.itemId && line.requiresBatchTracking)+ .map((line) => line.itemId);}return defer({@@ -59,6 +64,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {receiptLines: receiptLines.data ?? [],receiptLineTracking: receiptLineTracking.data ?? [],receiptFiles: getReceiptFiles(serviceRole, companyId, receiptLineIds) ?? [],+ batchProperties:+ getBatchProperties(serviceRole, itemsWithBatchProperties, companyId) ??+ [],});}diff --git a/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx b/apps/erp/app/routes/x+/receipt+/lines.tracking.tsxindex 64a6e9f3bd..f9b5237fe8 100644--- a/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx+++ b/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx@@ -20,7 +20,7 @@ export async function action({ request, context }: ActionFunctionArgs) {| null;const expirationDate = formData.get("expirationDate") as string | null;const quantity = Number(formData.get("quantity"));-+ const properties = formData.get("properties") as string | null;// First, get or create the batch number recordconst { data: existingBatch, error: batchQueryError } = await client.from("batchNumber")@@ -35,6 +35,12 @@ export async function action({ request, context }: ActionFunctionArgs) {}const batchId = existingBatch?.id ?? nanoid();+ let propertiesJson = {};+ try {+ propertiesJson = properties ? JSON.parse(properties) : {};+ } catch (error) {+ console.error(error);+ }// Use a transaction to ensure data consistencyconst { error } = await client.rpc("update_receipt_line_batch_tracking", {@@ -47,6 +53,7 @@ export async function action({ request, context }: ActionFunctionArgs) {// @ts-ignorep_expiration_date: expirationDate || null,p_quantity: quantity,+ p_properties: propertiesJson,});if (error) {diff --git a/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsxindex ef8ba10db0..99215607b5 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx@@ -9,7 +9,7 @@ import { defer, redirect } from "@vercel/remix";import { Suspense } from "react";import { useRouteData } from "~/hooks";import { getBatchProperties, InventoryDetails } from "~/modules/inventory";-import BatchPropertiesForm from "~/modules/inventory/Batches/BatchProperties";+import BatchPropertiesConfig from "~/modules/inventory/ui/Batches/BatchPropertiesConfig";import type { ToolSummary, UnitOfMeasureListItem } from "~/modules/items";import {getItemQuantities,@@ -135,7 +135,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {itemShelfQuantities: itemShelfQuantities.data,quantities: quantities.data,itemId,- batchProperties: getBatchProperties(client, itemId, companyId),+ batchProperties: getBatchProperties(client, [itemId], companyId),});}@@ -228,7 +228,8 @@ export default function ToolInventoryRoute() {<Suspense fallback={null}><Await resolve={batchProperties}>{(resolvedProperties) => (- <BatchPropertiesForm+ <BatchPropertiesConfig+ itemId={itemId}key={`batch-properties:${itemId}`}properties={resolvedProperties.data ?? []}/>diff --git a/packages/database/supabase/migrations/20250128094053_traceability.sql b/packages/database/supabase/migrations/20250128094053_traceability.sqlindex 325ff8b402..e4236501c5 100644--- a/packages/database/supabase/migrations/20250128094053_traceability.sql+++ b/packages/database/supabase/migrations/20250128094053_traceability.sql@@ -402,11 +402,12 @@ CREATE OR REPLACE FUNCTION update_receipt_line_batch_tracking(p_batch_id TEXT,p_manufacturing_date DATE,p_expiration_date DATE,- p_quantity NUMERIC+ p_quantity NUMERIC,+ p_properties JSONB DEFAULT '{}') RETURNS void AS $$BEGIN-- First upsert the batch number- INSERT INTO "batchNumber" ("id", "number", "itemId", "companyId", "manufacturingDate", "expirationDate", "supplierId", "source")+ INSERT INTO "batchNumber" ("id", "number", "itemId", "companyId", "manufacturingDate", "expirationDate", "supplierId", "source", "properties")SELECTp_batch_id,p_batch_number,@@ -415,13 +416,15 @@ BEGINp_manufacturing_date,p_expiration_date,r."supplierId",- 'Purchased'+ 'Purchased',+ p_propertiesFROM "receiptLine" rlJOIN "receipt" r ON r.id = rl."receiptId"WHERE rl.id = p_receipt_line_idON CONFLICT (id) DO UPDATE SET"manufacturingDate" = EXCLUDED."manufacturingDate",- "expirationDate" = EXCLUDED."expirationDate";+ "expirationDate" = EXCLUDED."expirationDate",+ "properties" = EXCLUDED."properties";-- Delete any existing tracking records for this receipt lineDELETE FROM "receiptLineTracking"