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 date to batch properties
Brad Barbin9249a42bf2f0
diff --git a/apps/erp/app/components/Configurator/Icons.tsx b/apps/erp/app/components/Configurator/Icons.tsxindex aa2c78540a..cece060076 100644--- a/apps/erp/app/components/Configurator/Icons.tsx+++ b/apps/erp/app/components/Configurator/Icons.tsx@@ -1,12 +1,12 @@import { cn } from "@carbon/react";-import { LuHash, LuList, LuToggleLeft, LuType } from "react-icons/lu";-import type { ConfiguratorDataType } from "./types";+import { LuCalendar, LuHash, LuList, LuToggleLeft, LuType } from "react-icons/lu";+import type { BatchPropertyDataType } from "./types";export function ConfiguratorDataTypeIcon({type,className,}: {- type: ConfiguratorDataType;+ type: BatchPropertyDataType;className?: string;}) {switch (type) {@@ -21,6 +21,8 @@ export function ConfiguratorDataTypeIcon({case "enum":case "list":return <LuList className={cn("w-4 h-4 text-orange-600", className)} />;+ case "date":+ return <LuCalendar className={cn("w-4 h-4 text-red-600", className)} />;default:return null;}diff --git a/apps/erp/app/components/Configurator/types.ts b/apps/erp/app/components/Configurator/types.tsindex 5561700e11..c1224b9317 100644--- a/apps/erp/app/components/Configurator/types.ts+++ b/apps/erp/app/components/Configurator/types.ts@@ -6,12 +6,17 @@ export type Configuration = {defaultValue?: string | number | boolean | string[] | null;};+export type ConfiguratorDataType =- | "boolean"- | "list"- | "numeric"- | "text"- | "enum";+| "boolean"+| "list"+| "numeric"+| "text"+| "enum";++export type BatchPropertyDataType =+ | ConfiguratorDataType+ | "date";export interface ListTypeConfig {options: string[];diff --git a/apps/erp/app/components/Form/Item.tsx b/apps/erp/app/components/Form/Item.tsxindex b99541ee44..f755103e20 100644--- a/apps/erp/app/components/Form/Item.tsx+++ b/apps/erp/app/components/Form/Item.tsx@@ -142,6 +142,7 @@ const Item = ({};const canSwitchItemType = typeof onTypeChange === "function";+ const submitRef = useRef<HTMLButtonElement>(null);return (<>@@ -292,6 +293,9 @@ const Item = ({size="lg"onClick={() => {onTypeChange?.(itemType);+ setTimeout(() => {+ submitRef.current?.focus();+ }, 0);}}>{itemType}@@ -309,6 +313,7 @@ const Item = ({Cancel</Button><Button+ ref={submitRef}isDisabled={type === "Item"}onClick={() => {selectTypeModal.onClose();diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.tsindex 6a25f9b46d..b4ca2965bd 100644--- a/apps/erp/app/modules/inventory/inventory.models.ts+++ b/apps/erp/app/modules/inventory/inventory.models.ts@@ -1,6 +1,6 @@import { z } from "zod";import { zfd } from "zod-form-data";-import { configurationParameterDataTypes } from "../items/items.models";+import { batchPropertyDataTypes } from "../items/items.models";export const itemTypes = ["Part",@@ -47,7 +47,7 @@ export const batchPropertyValidator = zid: zfd.text(z.string().optional()),itemId: z.string().min(1, { message: "Item ID is required" }),label: z.string().min(1, { message: "Label is required" }),- dataType: z.enum(configurationParameterDataTypes),+ dataType: z.enum(batchPropertyDataTypes),listOptions: z.string().min(1).array().optional(),configurationParameterGroupId: z.string().optional(),})diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 3ac55d8223..36b0135d5d 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -250,6 +250,22 @@ export async function getReceiptFiles(};}+export async function getAvailableSerialNumbersForItem(+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+) {+ return client.from("trackedEntity").select("*").eq("sourceDocument", "Item").eq("sourceDocumentId", itemId).eq("companyId", companyId).eq("status", "Available");+}++export async function getAvailableBatchNumbersForItem(+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+) {+ return client.from("trackedEntity").select("*").eq("sourceDocument", "Item").eq("sourceDocumentId", itemId).eq("companyId", companyId).eq("status", "Available");+}+export async function getShelvesList(client: SupabaseClient<Database>,companyId: string@@ -317,6 +333,7 @@ export async function getShipmentLines(return client.from("shipmentLine").select("*").eq("shipmentId", shipmentId);}+export async function getShipmentLinesWithDetails(client: SupabaseClient<Database>,shipmentId: string@@ -362,6 +379,30 @@ export async function getShipmentFiles(};}+export async function getShipmentTracking(+ client: SupabaseClient<Database>,+ shipmentId: string,+ companyId: string+) {+ return client+ .from("trackedEntity")+ .select("*")+ .eq("attributes ->> Shipment", shipmentId)+ .eq("companyId", companyId);+}++export async function getShipmentLineTracking(+ client: SupabaseClient<Database>,+ shipmentLineId: string,+ companyId: string+) {+ return client+ .from("trackedEntity")+ .select("*")+ .eq("attributes ->> Shipment Line", shipmentLineId)+ .eq("companyId", companyId);+}+export async function getShippingMethod(client: SupabaseClient<Database>,shippingMethodId: stringdiff --git a/apps/erp/app/modules/inventory/types.ts b/apps/erp/app/modules/inventory/types.tsindex 83412a68fe..1221f2373e 100644--- a/apps/erp/app/modules/inventory/types.ts+++ b/apps/erp/app/modules/inventory/types.ts@@ -9,7 +9,7 @@ import type {getShipments,getShipmentLines,getShippingMethods,- getShipmentLineTracking,+ getShipmentTracking,} from "./inventory.service";export type BatchProperty = NonNullable<@@ -53,7 +53,7 @@ export type ShipmentLine = NonNullable<>[number];export type ShipmentLineTracking = NonNullable<- Awaited<ReturnType<typeof getShipmentLineTracking>>["data"]+ Awaited<ReturnType<typeof getShipmentTracking>>["data"]>[number];export type ShippingCarrier = Database["public"]["Enums"]["shippingCarrier"];diff --git a/apps/erp/app/modules/inventory/ui/Batches/BatchHeader.tsx b/apps/erp/app/modules/inventory/ui/Batches/BatchHeader.tsxdeleted file mode 100644index 2f93336059..0000000000--- a/apps/erp/app/modules/inventory/ui/Batches/BatchHeader.tsx+++ /dev/null@@ -1,38 +0,0 @@-import { HStack, Heading } from "@carbon/react";-import { Link, useParams } from "@remix-run/react";-import { Copy } from "~/components";-import { useRouteData } from "~/hooks";-import type { BatchDetails } from "~/modules/inventory";-import { path } from "~/utils/path";--const BatchHeader = () => {- const { batchId } = useParams();- if (!batchId) throw new Error("batchId not found");-- const routeData = useRouteData<{- batch: BatchDetails;- }>(path.to.batch(batchId));-- if (!routeData?.batch) throw new Error("Failed to load batch");- const { batch } = routeData;-- return (- <>- <div className="flex flex-shrink-0 items-center justify-between py-2 px-4 bg-card border-b border-border h-[50px] overflow-x-auto scrollbar-hide dark:border-none dark:shadow-[inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]">- <HStack className="w-full justify-between">- <HStack>- <Link to={path.to.batch(batchId)}>- <Heading size="h4" className="flex items-center gap-2">- <span>Batch {batch.number}</span>- </Heading>- </Link>- <Copy text={batch?.number ?? ""} />- </HStack>- <HStack></HStack>- </HStack>- </div>- </>- );-};--export default BatchHeader;diff --git a/apps/erp/app/modules/inventory/ui/Batches/BatchesTable.tsx b/apps/erp/app/modules/inventory/ui/Batches/BatchesTable.tsxdeleted file mode 100644index 3789b49475..0000000000--- a/apps/erp/app/modules/inventory/ui/Batches/BatchesTable.tsx+++ /dev/null@@ -1,164 +0,0 @@-import { Badge, MenuIcon, MenuItem, VStack } from "@carbon/react";-import { formatDate } from "@carbon/utils";-import { useNavigate } from "@remix-run/react";-import type { ColumnDef } from "@tanstack/react-table";-import { memo, useCallback, useMemo } from "react";-import { AiOutlinePartition } from "react-icons/ai";-import {- LuBookMarked,- LuCalendar,- LuContainer,- LuPencil,- LuTruck,-} from "react-icons/lu";-import { Hyperlink, SupplierAvatar, Table } from "~/components";-import { usePermissions } from "~/hooks";-import type { BatchTableRow } from "~/modules/inventory";-import { useItems, useSuppliers } from "~/stores";-import { path } from "~/utils/path";--type BatchesTableProps = {- data: BatchTableRow[];- count: number;-};--const BatchesTable = memo(({ data, count }: BatchesTableProps) => {- const navigate = useNavigate();- const permissions = usePermissions();- const [items] = useItems();- const [suppliers] = useSuppliers();-- const columns = useMemo<ColumnDef<BatchTableRow>[]>(() => {- const result: ColumnDef<BatchTableRow>[] = [- {- accessorKey: "batchId",- header: "Batch ID",- cell: ({ row }) => (- <Hyperlink to={path.to.batch(row.original.id!)}>- {row.original.number}- </Hyperlink>- ),- meta: {- icon: <LuBookMarked />,- },- },- {- accessorKey: "itemId",- header: "Item",- cell: ({ row }) => (- <VStack spacing={0}>- <span className="text-sm font-medium">{row.original.itemName}</span>- <span className="text-sm text-muted-foreground">- {row.original.itemReadableId}- </span>- </VStack>- ),- meta: {- icon: <AiOutlinePartition />,- filter: {- type: "static",- options: items.map((item) => ({- value: item.id,- label: item.readableId,- helperText: item.name,- })),- },- },- },- {- accessorKey: "source",- header: "Source",- cell: ({ row }) =>- row.original.source === "Purchased" ? (- <Badge variant="green">Purchased</Badge>- ) : (- <Badge variant="blue">Manufactured</Badge>- ),- meta: {- icon: <LuTruck />,- filter: {- type: "static",- options: [- { value: "Purchased", label: "Purchased" },- { value: "Manufactured", label: "Manufactured" },- ],- },- },- },- {- accessorKey: "supplierId",- header: "Supplier",- cell: ({ row }) => (- <SupplierAvatar supplierId={row.original.supplierId} />- ),- meta: {- icon: <LuContainer />,- filter: {- type: "static",- options: suppliers.map((supplier) => ({- value: supplier.id,- label: supplier.name,- })),- },- },- },- {- accessorKey: "manufacturingDate",- header: "Manufactured Date",- cell: (item) => formatDate(item.getValue<string>()),- meta: {- icon: <LuCalendar />,- },- },- {- accessorKey: "expirationDate",- header: "Expiry Date",- cell: (item) => formatDate(item.getValue<string>()),- meta: {- icon: <LuCalendar />,- },- },- ];-- return result;- }, [items, suppliers]);-- const renderContextMenu = useCallback(- (row: BatchTableRow) => {- return (- <>- <MenuItem- disabled={!permissions.can("update", "inventory")}- onClick={() => {- navigate(`${path.to.batch(row.id!)}`);- }}- >- <MenuIcon icon={<LuPencil />} />- View Batch- </MenuItem>- </>- );- },- [navigate, permissions]- );-- return (- <>- <Table<BatchTableRow>- data={data}- columns={columns}- count={count}- defaultColumnPinning={{- left: ["batchId"],- }}- renderContextMenu={renderContextMenu}- title="Batches"- table="batchNumber"- withSavedView- />- </>- );-});--BatchesTable.displayName = "BatchesTable";-export default BatchesTable;diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsxindex dbea5d84f0..f8eaaa600a 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx@@ -34,6 +34,8 @@ import type { ListItem } from "~/types";import { path } from "~/utils/path";import { inventoryAdjustmentValidator } from "../../inventory.models";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";+import { LuQrCode } from "react-icons/lu";+import { Copy } from "~/components";type InventoryShelvesProps = {pickMethod: z.infer<typeof pickMethodValidator>;@@ -83,8 +85,9 @@ const InventoryShelves = ({<Thead><Tr><Th>Shelf</Th>- <Th>Tracking ID</Th>+<Th>QoH</Th>+ <Th>Tracking ID</Th></Tr></Thead><Tbody>@@ -96,8 +99,14 @@ const InventoryShelves = ({{shelves.find((s) => s.id === item.shelfId)?.name ||item.shelfId}</Td>- <Td>{item.trackedEntityId}</Td>- <Td>{item.quantity}</Td>++ <Td className="flex items-center gap-2">+ <span>{item.quantity}</span>++ </Td>+ <Td>+ <Copy icon={<LuQrCode />} text={item.trackedEntityId} />+ </Td></Tr>))}</Tbody>diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsxindex 0a053388cf..b89eefc062 100644--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx@@ -69,10 +69,10 @@ 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";import { labelSizes } from "@carbon/utils";import { SplitButton } from "~/components/SplitButton";+import BatchPropertiesConfig from "../Batches/BatchPropertiesConfig";const ReceiptLines = () => {const { receiptId } = useParams();@@ -630,6 +630,7 @@ function BatchForm({</SplitButton><Buttonvariant="secondary"+ leftIcon={<LuGroup />}size="sm"onClick={propertiesDisclosure.onOpen}>diff --git a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsxindex 278bd50e4f..b74f03a826 100644--- a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx+++ b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx@@ -1,7 +1,4 @@import {- // LuBarcode,- LuBox,- LuGroup,LuHandCoins,LuTally5,LuTruck,@@ -22,18 +19,7 @@ const inventoryRoutes: AuthenticatedRouteGroup[] = [icon: <LuTally5 />,table: "inventory",},- {- name: "Batches",- to: path.to.batches,- icon: <LuGroup />,- table: "batchNumber",- },- // {- // name: "Serial Numbers",- // to: path.to.serialNumbers,- // icon: <LuBarcode />,- // table: "serialNumber",- // },+],},{diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.tsindex fecb910336..1d49a4ebca 100644--- a/apps/erp/app/modules/items/items.models.ts+++ b/apps/erp/app/modules/items/items.models.ts@@ -8,6 +8,14 @@ import {standardFactorType,} from "../shared";+export const batchPropertyDataTypes = [+ "text",+ "numeric",+ "boolean",+ "list",+ "date",+] as const;+export const configurationParameterDataTypes = ["text","numeric",@@ -101,7 +109,7 @@ export const configurationParameterValidator = zitemId: z.string().min(1, { message: "Item ID is required" }),key: zfd.text(z.string().optional()),label: z.string().min(1, { message: "Label is required" }),- dataType: z.enum(configurationParameterDataTypes),+ dataType: z.enum([...configurationParameterDataTypes, "date"] ),listOptions: z.string().min(1).array().optional(),configurationParameterGroupId: z.string().optional(),})diff --git a/apps/erp/app/routes/x+/batch+/$batchId.tsx b/apps/erp/app/routes/x+/batch+/$batchId.tsxdeleted file mode 100644index 7d22fbbfb3..0000000000--- a/apps/erp/app/routes/x+/batch+/$batchId.tsx+++ /dev/null@@ -1,578 +0,0 @@-import { error, useCarbon } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import type { JSONContent } from "@carbon/react";-import {- Badge,- Card,- CardAction,- CardContent,- CardDescription,- CardHeader,- CardTitle,- Checkbox,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,- HStack,- IconButton,- Tabs,- TabsContent,- TabsList,- TabsTrigger,- toast,- useDebounce,- VStack,-} from "@carbon/react";-import { Editor, generateHTML } from "@carbon/react/Editor";-import { useRouteData } from "@carbon/remix";-import { formatDate, formatRelativeTime } from "@carbon/utils";-import { useNumberFormatter } from "@react-aria/i18n";-import { Await, Link, useLoaderData, useParams } from "@remix-run/react";-import type { LoaderFunctionArgs } from "@vercel/remix";-import { defer, redirect } from "@vercel/remix";-import { nanoid } from "nanoid";-import { Suspense, useState } from "react";-import {- LuEllipsisVertical,- LuFactory,- LuHammer,- LuHandCoins,- LuTruck,-} from "react-icons/lu";-import {- Documents,- EmployeeAvatar,- Empty,- Hyperlink,- SupplierAvatar,-} from "~/components";-import { ConfiguratorDataTypeIcon } from "~/components/Configurator/Icons";-import { usePermissions, useUser } from "~/hooks";-import type { BatchDetails, BatchProperty } from "~/modules/inventory";-import {- getBatch,- getBatchFiles,- getBatchProperties,-} 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";--export const handle: Handle = {- breadcrumb: "Batches",- to: path.to.batches,- module: "inventory",-};--export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "inventory",- bypassRls: true,- });-- const { batchId } = params;- if (!batchId) throw new Error("Batch ID is required");-- const batch = await getBatch(client, batchId, companyId);- if (batch.error) {- throw redirect(- path.to.batches,- await flash(request, error(batch.error, "Failed to load batch"))- );- }-- const batchProperties = await getBatchProperties(- client,- [batch.data.itemId],- companyId- );-- const receiptLineIds = batch.data.itemTracking- .filter((tracking) => tracking.sourceDocument === "Receipt")- .map((tracking) => tracking.sourceDocumentId);-- return defer({- batch: batch.data,- batchProperties: batchProperties?.data ?? [],- receiptFiles: getBatchFiles(client, companyId, {- receiptLineIds,- batchId,- }) ?? { data: [], error: null },- });-}--export default function BatchDetailRoute() {- const { receiptFiles } = useLoaderData<typeof loader>();- const { batchId } = useParams();- if (!batchId) throw new Error("Could not find batchId");-- return (- <div className="flex flex-col h-[calc(100dvh-49px)] overflow-hidden w-full">- <BatchHeader />- <div className="flex h-[calc(100dvh-99px)] overflow-y-auto scrollbar-hide w-full">- <VStack- spacing={4}- className="h-full p-2 w-full max-w-5xl mx-auto pb-32"- >- <BatchSummary />- <BatchTransactions />- <BatchNotes />- <Suspense fallback={null}>- <Await resolve={receiptFiles}>- {(files) => (- <Documents- writeBucket="inventory"- writeBucketPermission="inventory"- files={files.data ?? []}- sourceDocumentId={batchId}- />- )}- </Await>- </Suspense>- </VStack>- </div>- </div>- );-}--function BatchSummary() {- const { batchId } = useParams();- if (!batchId) throw new Error("Could not find batchId");-- const routeData = useRouteData<{- batch: BatchDetails;- batchProperties: BatchProperty[];- }>(path.to.batch(batchId));-- const numberFormatter = useNumberFormatter();- if (!routeData?.batch) throw new Error("Could not find batch");-- const { batch, batchProperties } = routeData;-- const properties = batch.properties- ? Object.entries(batch.properties)- .reduce<(BatchProperty & { value: string | number | boolean })[]>(- (acc, [key, value]) => {- const property = batchProperties.find((p) => p.id === key);- if (property) {- acc.push({ ...property, value });- }- return acc;- },- []- )- .sort((a, b) => a.sortOrder - b.sortOrder)- : [];-- return (- <Card>- <CardHeader>- <HStack className="justify-between items-center">- <div className="flex flex-col gap-1">- <CardTitle>{batch.item.readableId}</CardTitle>- <CardDescription className="flex flex-col gap-2">- <span>{batch.item.name}</span>- <div>- {batch.source === "Purchased" ? (- <Badge variant="green">Purchased</Badge>- ) : (- <Badge variant="blue">Manufactured</Badge>- )}- </div>- </CardDescription>- </div>- <div className="flex flex-col gap-1 items-end">- <SupplierAvatar supplierId={batch.supplierId ?? null} />- {batch.manufacturingDate && (- <span className="text-muted-foreground text-sm">- Manufactured {formatDate(batch.manufacturingDate)}- </span>- )}- {batch.expirationDate && (- <span className="text-muted-foreground text-sm">- Expires {formatDate(batch.expirationDate)}- </span>- )}- </div>- </HStack>- </CardHeader>- <CardContent>- <VStack>- {properties.map((property) => (- <div- key={property.id}- className="flex items-center justify-between p-6 rounded-lg border w-full"- >- <HStack spacing={4} className="flex-1">- <div className="bg-muted border rounded-full flex items-center justify-center p-2">- <ConfiguratorDataTypeIcon- type={property.dataType}- className="w-4 h-4"- />- </div>-- <span className="text-sm font-medium">{property.label}</span>- </HStack>- <span className="text-base font-medium">- {property.dataType === "boolean" ? (- <Checkbox isChecked={property.value as boolean} />- ) : property.dataType === "numeric" ? (- numberFormatter.format(property.value as number)- ) : (- property.value- )}- </span>- </div>- ))}- </VStack>- </CardContent>- </Card>- );-}--function BatchTransactions() {- const { batchId } = useParams();- if (!batchId) throw new Error("Could not find batchId");-- const routeData = useRouteData<{- batch: BatchDetails;- }>(path.to.batch(batchId));-- if (!routeData?.batch) return null;-- const { batch } = routeData;-- // Combine all tracking types and sort by time- const allTransactions = batch.itemTracking.sort(- (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()- );-- return (- <Card>- <Tabs defaultValue="all">- <HStack className="justify-between w-full">- <CardHeader>- <CardTitle>Transactions</CardTitle>- </CardHeader>- <CardAction>- <TabsList>- <TabsTrigger value="all">All</TabsTrigger>- <TabsTrigger value="received">Received</TabsTrigger>- <TabsTrigger value="consumed">Consumed</TabsTrigger>- <TabsTrigger value="produced">Produced</TabsTrigger>- <TabsTrigger value="shipped">Shipped</TabsTrigger>- </TabsList>- </CardAction>- </HStack>- <CardContent>- <TabsContent className="w-full" value="all">- <VStack className="w-full" spacing={4}>- {allTransactions.length === 0 ? (- <Empty className="text-sm text-muted-foreground">- No transactions found- </Empty>- ) : (- allTransactions.map((transaction) => (- <Transaction key={transaction.id} transaction={transaction} />- ))- )}- </VStack>- </TabsContent>- <TabsContent className="w-full" value="received">- <VStack className="w-full" spacing={4}>- {batch.itemTracking.filter(- (tracking) => tracking.sourceDocument === "Receipt"- ).length === 0 ? (- <Empty className="text-sm text-muted-foreground">- No received transactions found- </Empty>- ) : (- batch.itemTracking- .filter((tracking) => tracking.sourceDocument === "Receipt")- .map((tracking) => (- <Transaction key={tracking.id} transaction={tracking} />- ))- )}- </VStack>- </TabsContent>- <TabsContent className="w-full" value="consumed">- <VStack className="w-full" spacing={4}>- {batch.itemTracking.filter(- (tracking) => tracking.sourceDocument === "Job Material"- ).length === 0 ? (- <Empty className="text-sm text-muted-foreground">- No consumed transactions found- </Empty>- ) : (- batch.itemTracking- .filter(- (tracking) => tracking.sourceDocument === "Job Material"- )- .map((tracking) => (- <Transaction key={tracking.id} transaction={tracking} />- ))- )}- </VStack>- </TabsContent>- <TabsContent className="w-full" value="produced">- <VStack className="w-full" spacing={4}>- {batch.itemTracking.filter(- (tracking) => tracking.sourceDocument === "Job Production"- ).length === 0 ? (- <Empty className="text-sm text-muted-foreground">- No produced transactions found- </Empty>- ) : (- batch.itemTracking- .filter(- (tracking) => tracking.sourceDocument === "Job Production"- )- .map((tracking) => (- <Transaction key={tracking.id} transaction={tracking} />- ))- )}- </VStack>- </TabsContent>- <TabsContent className="w-full" value="shipped">- <VStack className="w-full" spacing={4}>- {batch.itemTracking.filter(- (tracking) => tracking.sourceDocument === "Shipment"- ).length === 0 ? (- <Empty className="text-sm text-muted-foreground">- No shipped transactions found- </Empty>- ) : (- batch.itemTracking- .filter((tracking) => tracking.sourceDocument === "Shipment")- .map((tracking) => (- <Transaction key={tracking.id} transaction={tracking} />- ))- )}- </VStack>- </TabsContent>- </CardContent>- </Tabs>- </Card>- );-}--function Transaction({- transaction,-}: {- transaction: BatchDetails["itemTracking"][number];-}) {- const getTransactionDetails = () => {- switch (transaction.sourceDocument) {- case "Receipt":- return {- link: path.to.receipt(transaction.sourceDocumentId),- description: `Received from ${transaction.sourceDocumentReadableId}`,- showMoreMenu: true,- };- case "Job Material":- return {- link: path.to.jobMaterials(transaction.sourceDocumentId),- description: "Consumed by Job",- showMoreMenu: true,- };- case "Job Production":- return {- link: path.to.job(transaction.sourceDocumentId),- description: "Job Production",- showMoreMenu: false,- };- case "Shipment":- return {- link: path.to.shipment(transaction.sourceDocumentId),- description: "Shipped",- showMoreMenu: false,- };- default:- return {- link: "null",- description: "",- showMoreMenu: false,- };- }- };-- const { link, description, showMoreMenu } = getTransactionDetails();-- return (- <div className="flex flex-col border p-6 w-full rounded-lg">- <div className="flex flex-1 justify-between items-center w-full">- <HStack spacing={4} className="w-1/2">- <HStack spacing={4} className="flex-1">- <TransactionIcon type={transaction.sourceDocument} />- <VStack spacing={0}>- {link ? (- <Hyperlink to={link} className="text-sm font-medium">- {transaction.sourceDocumentReadableId}- </Hyperlink>- ) : (- <span className="text-sm font-medium">- {transaction.sourceDocumentReadableId}- </span>- )}- <span className="text-xs text-muted-foreground">- {description}- </span>- </VStack>- <span className="text-base text-muted-foreground text-right">- {transaction.quantity}- </span>- </HStack>- </HStack>- <div className="flex items-center justify-end gap-2">- <HStack spacing={2}>- <span className="text-xs text-muted-foreground">- Created {formatRelativeTime(transaction.createdAt)}- </span>- <EmployeeAvatar- employeeId={transaction.createdBy}- withName={false}- />- </HStack>- {showMoreMenu && <MoreMenu link={link} />}- </div>- </div>- </div>- );-}--function TransactionIcon({- type,-}: {- type: BatchDetails["itemTracking"][number]["sourceDocument"];-}) {- if (type === "Receipt")- return (- <div className="bg-blue-500 text-white border rounded-full flex items-center justify-center p-2">- <LuHandCoins className="size-4" />- </div>- );- if (type === "Job Material")- return (- <div className="bg-orange-500 text-white border rounded-full flex items-center justify-center p-2">- <LuFactory className="size-4" />- </div>- );- if (type === "Job Production")- return (- <div className="bg-emerald-500 text-zinc-900 border rounded-full flex items-center justify-center p-2">- <LuHammer className="size-4" />- </div>- );- if (type === "Shipment")- return (- <div className="bg-yellow-500 text-zinc-900 border rounded-full flex items-center justify-center p-2">- <LuTruck className="size-4" />- </div>- );-}--function BatchNotes() {- const {- company: { id: companyId },- } = useUser();-- const { batchId } = useParams();- if (!batchId) throw new Error("Could not find batchId");-- const routeData = useRouteData<{- batch: BatchDetails;- }>(path.to.batch(batchId));-- if (!routeData?.batch) throw new Error("Could not find batch");-- const { batch } = routeData;-- const { carbon } = useCarbon();- const permissions = usePermissions();- const [tab, setTab] = useState("internal");- const [notes, setNotes] = useState(batch.notes ?? {});-- const onUploadImage = async (file: File) => {- const fileType = file.name.split(".").pop();- const fileName = `${companyId}/inventory/${batchId}/${nanoid()}.${fileType}`;-- const result = await carbon?.storage.from("private").upload(fileName, file);-- if (result?.error) {- toast.error("Failed to upload image");- throw new Error(result.error.message);- }-- if (!result?.data) {- throw new Error("Failed to upload image");- }-- return getPrivateUrl(result.data.path);- };-- const onUpdateNotes = useDebounce(- async (content: JSONContent) => {- await carbon- ?.from("batchNumber")- .update({- notes: content,- })- .eq("id", batchId!);- },- 2500,- true- );-- return (- <>- <Card>- <Tabs value={tab} onValueChange={setTab}>- <CardHeader>- <CardTitle>Notes</CardTitle>- </CardHeader>-- <CardContent>- {permissions.can("update", "inventory") ? (- <Editor- initialValue={(notes ?? {}) as JSONContent}- onUpload={onUploadImage}- onChange={(value) => {- setNotes(value);- onUpdateNotes(value);- }}- />- ) : (- <div- className="prose dark:prose-invert"- dangerouslySetInnerHTML={{- __html: generateHTML(notes as JSONContent),- }}- />- )}- </CardContent>- </Tabs>- </Card>- </>- );-}--function MoreMenu({ link }: { link: string }) {- return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- aria-label="Open menu"- icon={<LuEllipsisVertical />}- variant="ghost"- />- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem asChild>- <Link to={link}>View</Link>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- );-}diff --git a/apps/erp/app/routes/x+/batch+/_layout.tsx b/apps/erp/app/routes/x+/batch+/_layout.tsxdeleted file mode 100644index 53bf700878..0000000000--- a/apps/erp/app/routes/x+/batch+/_layout.tsx+++ /dev/null@@ -1,27 +0,0 @@-import { requirePermissions } from "@carbon/auth/auth.server";-import { Outlet } from "@remix-run/react";-import type { LoaderFunctionArgs, MetaFunction } from "@vercel/remix";-import type { Handle } from "~/utils/handle";-import { path } from "~/utils/path";--export const meta: MetaFunction = () => {- return [{ title: "Carbon | Batch" }];-};--export const handle: Handle = {- breadcrumb: "Inventory",- to: path.to.inventory,- module: "inventory",-};--export async function loader({ request }: LoaderFunctionArgs) {- await requirePermissions(request, {- view: "inventory",- });-- return null;-}--export default function BatchRoute() {- return <Outlet />;-}diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsxindex eb2cfcbd74..a8cf49c35b 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx@@ -10,6 +10,7 @@ import { Suspense } from "react";import { useRouteData } from "~/hooks";import { getBatchProperties, InventoryDetails } from "~/modules/inventory";import BatchPropertiesConfig from "~/modules/inventory/ui/Batches/BatchPropertiesConfig";+import type { Consumable, UnitOfMeasureListItem } from "~/modules/items";import {getItemQuantities,diff --git a/apps/erp/app/routes/x+/inventory+/batches.tsx b/apps/erp/app/routes/x+/inventory+/batches.tsxdeleted file mode 100644index 53ff68764d..0000000000--- a/apps/erp/app/routes/x+/inventory+/batches.tsx+++ /dev/null@@ -1,62 +0,0 @@-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { VStack } from "@carbon/react";-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/ui/Batches/BatchesTable";-import type { Handle } from "~/utils/handle";-import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--export const handle: Handle = {- breadcrumb: "Batches",- to: path.to.batches,-};--export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "inventory",- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [batches] = await Promise.all([- getBatches(client, companyId, {- search,- limit,- offset,- sorts,- filters,- }),- ]);-- if (batches.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(request, error(null, "Error loading batches"))- );- }-- return json({- batches: batches.data ?? [],- count: batches.count ?? 0,- });-}--export default function ReceiptsRoute() {- const { batches, count } = useLoaderData<typeof loader>();-- return (- <VStack spacing={0} className="h-full">- <BatchesTable data={batches} count={count ?? 0} />- <Outlet />- </VStack>- );-}diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.tsxindex d8f193c794..8b99c759df 100644--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx@@ -9,7 +9,7 @@ import { PanelProvider } from "~/components/Layout";import {getBatchProperties,getShipment,- getShipmentLineTracking,+ getShipmentTracking,getShipmentLines,} from "~/modules/inventory";import ShipmentHeader from "~/modules/inventory/ui/Shipments/ShipmentHeader";@@ -34,7 +34,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const [shipment, shipmentLines, shipmentLineTracking] = await Promise.all([getShipment(serviceRole, shipmentId),getShipmentLines(serviceRole, shipmentId),- getShipmentLineTracking(serviceRole, shipmentId),+ getShipmentTracking(serviceRole, shipmentId),]);if (shipment.error) {diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex e0d909a23e..a0298602d6 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -174,8 +174,6 @@ export const path = {generatePath(`${x}/people/attributes/${id}`),attributeCategoryList: (id: string) =>generatePath(`${x}/people/attributes/list/${id}`),- batches: `${x}/inventory/batches`,- batch: (id: string) => generatePath(`${x}/batch/${id}`),batchProperty: (itemId: string) =>generatePath(`${x}/inventory/batch-property/${itemId}/property`),batchPropertyOrder: (itemId: string) =>diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 2acb48571e..c981845de2 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -48154,7 +48154,7 @@ export default {type: "string",},dataType: {- enum: ["text", "numeric", "boolean", "list"],+ enum: ["text", "numeric", "boolean", "list", "date"],format: 'public."configurationParameterDataType"',type: "string",},@@ -56074,7 +56074,7 @@ export default {type: "string",},dataType: {- enum: ["text", "numeric", "boolean", "list"],+ enum: ["text", "numeric", "boolean", "list", "date"],format: 'public."configurationParameterDataType"',type: "string",},diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 0c7a2d661a..09ea898700 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -36200,7 +36200,12 @@ export type Database = {}Enums: {accountingPeriodStatus: "Inactive" | "Active"- configurationParameterDataType: "text" | "numeric" | "boolean" | "list"+ configurationParameterDataType:+ | "text"+ | "numeric"+ | "boolean"+ | "list"+ | "date"costLedgerType:| "Direct Cost"| "Revaluation"diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 0c7a2d661a..09ea898700 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -36200,7 +36200,12 @@ export type Database = {}Enums: {accountingPeriodStatus: "Inactive" | "Active"- configurationParameterDataType: "text" | "numeric" | "boolean" | "list"+ configurationParameterDataType:+ | "text"+ | "numeric"+ | "boolean"+ | "list"+ | "date"costLedgerType:| "Direct Cost"| "Revaluation"diff --git a/packages/database/supabase/migrations/20250225145619_tracked-entities.sql b/packages/database/supabase/migrations/20250225145619_tracked-entities.sqlindex 320b2eb038..725788186b 100644--- a/packages/database/supabase/migrations/20250225145619_tracked-entities.sql+++ b/packages/database/supabase/migrations/20250225145619_tracked-entities.sql@@ -16,6 +16,8 @@ DROP VIEW IF EXISTS "serialNumbers";DROP TYPE IF EXISTS "serialStatus";CREATE TYPE "trackedEntityStatus" AS ENUM('Available', 'Reserved', 'On Hold', 'Consumed');+ALTER TYPE "configurationParameterDataType" ADD VALUE 'date';+-- Create tracked entity tableCREATE TABLE "trackedEntity" ("id" TEXT NOT NULL DEFAULT xid(),