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
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { useCarbon } from "@carbon/auth";
import {
getDocumentType,
isPreviewableDocumentType,
storage
} from "@carbon/files";
import { Boolean, Number, Submit, ValidatedForm } from "@carbon/form";
import { useAction, useRevalidator } from "@carbon/query";
import {
Button,
Card,
CardContent,
CardHeader,
CardTitle,
Checkbox,
cn,
DatePicker,
DropdownMenu,
DropdownMenuContent,
DropdownMenuIcon,
DropdownMenuItem,
DropdownMenuTrigger,
Heading,
HStack,
IconButton,
Input,
MENU_ITEM_SHORTCUTS,
Modal,
ModalBody,
ModalContent,
ModalDescription,
ModalFooter,
ModalHeader,
ModalTitle,
NumberField,
NumberInput,
RadioGroup,
RadioGroupItem,
Textarea,
Tooltip,
TooltipContent,
TooltipTrigger,
toast,
useDisclosure,
VStack
} from "@carbon/react";
import type { TrackedEntityAttributes } from "@carbon/utils";
import { parseDate } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { Suspense, useCallback, useEffect, useState } from "react";
import {
LuCalendar,
LuCircleAlert,
LuClipboardCheck,
LuEllipsisVertical,
LuGroup,
LuSplit,
LuTrash,
LuX
} from "react-icons/lu";
import {
Await,
Link,
Outlet,
useFetchers,
useParams,
useSubmit
} from "react-router";
import { z } from "zod";
import {
DocumentPreview,
Empty,
ItemThumbnail,
PrintButton
} from "~/components";
import DocumentIcon from "~/components/DocumentIcon";
import { Enumerable } from "~/components/Enumerable";
import FileDropzone from "~/components/FileDropzone";
import StorageUnit from "~/components/Form/StorageUnit";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { ConfirmDelete } from "~/components/Modals";
import { usePermissions, useRouteData, useUser } from "~/hooks";
import { splitValidator } from "~/modules/inventory/inventory.models";
import type {
BatchProperty,
ItemTracking,
Receipt,
ReceiptLine,
RentalReceiptLine
} from "~/modules/inventory/types";
import type { action as splitAction } from "~/routes/x+/receipt+/lines.split";
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 { RentalUnitRow } from "../Shipments/RentalUnitRow";
import { ReturnEntityForm } from "./ReturnEntityForm";
const ReceiptLines = () => {
const { receiptId } = useParams();
if (!receiptId) throw new Error("receiptId not found");
const fetcher = useAction();
const { upload, deleteFile, getPath } = useReceiptFiles(receiptId);
const routeData = useRouteData<{
receipt: Receipt;
receiptLines: ReceiptLine[];
fixedAssetLines: {
id: string;
purchaseOrderLineId: string;
assetId: string;
assetName: string | null;
assetReadableId: string | null;
description: string | null;
received: boolean;
serialNumber: string | null;
}[];
rentalLines: RentalReceiptLine[];
receiptInspections: ReceiptLineInspection[];
inspectedItemIds: string[];
receiptFiles: PostgrestResponse<StorageItem>;
receiptLineTracking: ItemTracking[];
batchProperties: PostgrestResponse<BatchProperty>;
itemShelfLife: PostgrestResponse<{
itemId: string;
mode: string;
days: number | null;
}>;
}>(path.to.receipt(receiptId));
const receiptsById = new Map<string, ReceiptLine>(
// @ts-expect-error
routeData?.receiptLines.map((line) => [line.id, line])
);
const pendingReceiptLines = usePendingReceiptLines();
for (let pendingReceiptLine of pendingReceiptLines) {
let item = receiptsById.get(pendingReceiptLine.id);
let merged = item ? { ...item, ...pendingReceiptLine } : pendingReceiptLine;
receiptsById.set(pendingReceiptLine.id, merged as ReceiptLine);
}
const receiptLines = Array.from(receiptsById.values());
const [serialNumbersByLineId, setSerialNumbersByLineId] = useState<
Record<string, { index: number; number: string }[]>
>(() => {
return receiptLines.reduce((acc, line) => {
if (!line.requiresSerialTracking) return acc;
const trackedEntitiesForLine = routeData?.receiptLineTracking.filter(
(t) => {
const attributes = t.attributes as TrackedEntityAttributes;
return attributes["Receipt Line"] === line.id;
}
);
if (!trackedEntitiesForLine) return acc;
return {
...acc,
[line.id!]: Array.from(
{ length: line.receivedQuantity ?? 0 },
(_, index) => {
const serialNumberEntity = trackedEntitiesForLine.find((t) => {
const attributes = t.attributes as TrackedEntityAttributes;
return attributes["Receipt Line Index"] === index;
});
const serialNumber = serialNumberEntity?.readableId || "";
return {
index,
number: serialNumber
};
}
)
};
}, {});
});
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
useEffect(() => {
setSerialNumbersByLineId(
receiptLines.reduce((acc, line) => {
if (!line.requiresSerialTracking) return acc;
const trackedEntitiesForLine = routeData?.receiptLineTracking.filter(
(t) => {
const attributes = t.attributes as TrackedEntityAttributes;
return attributes["Receipt Line"] === line.id;
}
);
if (!trackedEntitiesForLine) return acc;
return {
...acc,
[line.id!]: Array.from(
{ length: line.receivedQuantity ?? 0 },
(_, index) => {
const serialNumberEntity = trackedEntitiesForLine.find((t) => {
const attributes = t.attributes as TrackedEntityAttributes;
return attributes["Receipt Line Index"] === index;
});
const serialNumber = serialNumberEntity?.readableId || "";
return {
index,
number: serialNumber
};
}
)
};
}, {})
);
}, [routeData?.receipt?.sourceDocumentId, routeData?.receiptLines?.length]);
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
const onUpdateReceiptLine = useCallback(
async ({
lineId,
field,
value
}:
| {
lineId: string;
field: "receivedQuantity";
value: number;
}
| {
lineId: string;
field: "storageUnitId";
value: string;
}) => {
const formData = new FormData();
formData.append("ids", lineId);
formData.append("field", field);
formData.append("value", value.toString());
fetcher.submit(formData, {
method: "post",
action: path.to.bulkUpdateReceiptLine
});
},
[]
);
const isPosted =
routeData?.receipt.status === "Posted" ||
routeData?.receipt.status === "Voided";
const isRental = routeData?.receipt?.sourceDocument === "Rental Agreement";
return (
<>
{!isRental && (
<Card>
<CardHeader>
<CardTitle>
<Trans>Receipt Lines</Trans>
</CardTitle>
</CardHeader>
<CardContent>
<div className="border rounded-lg">
{receiptLines.length === 0 ? (
<Empty className="py-6" />
) : (
receiptLines.map((line, index) => {
const trackingCandidates =
routeData?.receiptLineTracking?.filter((t) => {
const attributes =
t.attributes as TrackedEntityAttributes;
return attributes["Receipt Line"] === line.id;
}) ?? [];
const tracking =
trackingCandidates.find((t) => t.expirationDate) ??
trackingCandidates[0];
const inspection = routeData?.receiptInspections?.find(
(i) => i.sourceDocumentLineId === line.id
);
return (
<ReceiptLineItem
key={line.id}
line={line}
receipt={routeData?.receipt}
inspection={inspection}
requiresInspection={
!!inspection ||
(!!line.itemId &&
!!routeData?.inspectedItemIds?.includes(line.itemId))
}
isReadOnly={isPosted}
onUpdate={onUpdateReceiptLine}
files={routeData?.receiptFiles}
className={
index === receiptLines.length - 1 ? "border-none" : ""
}
serialNumbers={serialNumbersByLineId[line.id!] || []}
getPath={(file) => getPath(file, line.id!)}
onSerialNumbersChange={(newSerialNumbers) => {
setSerialNumbersByLineId((prev) => ({
...prev,
[line.id!]: newSerialNumbers
}));
}}
batchProperties={routeData?.batchProperties}
itemShelfLife={routeData?.itemShelfLife}
tracking={tracking}
upload={(files) => upload(files, line.id!)}
deleteFile={(file) => deleteFile(file, line.id!)}
/>
);
})
)}
</div>
</CardContent>
</Card>
)}
{routeData?.fixedAssetLines && routeData.fixedAssetLines.length > 0 && (
<Card>
<CardHeader>
<CardTitle>
<Trans>Fixed Assets</Trans>
</CardTitle>
</CardHeader>
<CardContent>
<div className="border rounded-lg">
{routeData.fixedAssetLines.map((line, index) => (
<ReceiptFixedAssetLineItem
key={line.id}
line={line}
isReadOnly={isPosted}
className={
index < routeData.fixedAssetLines.length - 1
? "border-b"
: ""
}
/>
))}
</div>
</CardContent>
</Card>
)}
{isRental && (
<Card>
<CardHeader>
<CardTitle>
<Trans>Rental Units</Trans>
</CardTitle>
</CardHeader>
<CardContent>
<div className="border rounded-lg">
{(routeData?.rentalLines ?? []).length === 0 ? (
<Empty className="py-6" />
) : (
routeData!.rentalLines.map((line, index) => (
<ReceiptRentalLineItem
key={line.id}
line={line}
isReadOnly={isPosted}
className={
index < routeData!.rentalLines.length - 1
? "border-b"
: ""
}
/>
))
)}
</div>
</CardContent>
</Card>
)}
<Outlet />
</>
);
};
function ReceiptFixedAssetLineItem({
line,
isReadOnly,
className
}: {
line: {
id: string;
purchaseOrderLineId: string;
assetId: string;
assetName: string | null;
assetReadableId: string | null;
description: string | null;
received: boolean;
serialNumber: string | null;
};
isReadOnly: boolean;
className?: string;
}) {
const fetcher = useAction();
const [serialNumber, setSerialNumber] = useState(line.serialNumber ?? "");
const updateField = (field: string, value: string) => {
const formData = new FormData();
formData.append("id", line.id);
formData.append("field", field);
formData.append("value", value);
fetcher.submit(formData, {
method: "post",
action: path.to.receiptFixedAssetLineUpdate
});
};
return (
<div
className={cn(
"flex items-center gap-4 p-6 max-md:flex-wrap max-md:p-4",
className
)}
>
<Checkbox
isChecked={line.received}
disabled={isReadOnly}
onCheckedChange={(checked) =>
updateField("received", String(checked === true))
}
/>
<VStack spacing={0} className="flex-1 min-w-0">
<span className="text-sm font-medium">
{line.assetName ?? line.description ?? "Fixed Asset"}
</span>
{line.assetReadableId && (
<span className="text-xs text-muted-foreground">
{line.assetReadableId}
</span>
)}
</VStack>
<Input
placeholder="Serial Number"
value={serialNumber}
isDisabled={isReadOnly}
className="w-48 max-md:w-full"
onChange={(e) => setSerialNumber(e.target.value)}
onBlur={() => {
if (serialNumber !== (line.serialNumber ?? "")) {
updateField("serialNumber", serialNumber);
}
}}
/>
</div>
);
}
function ReceiptRentalLineItem({
line,
isReadOnly,
className
}: {
line: RentalReceiptLine;
isReadOnly: boolean;
className?: string;
}) {
const { t } = useLingui();
const fetcher = useAction();
const [notes, setNotes] = useState(line.notes ?? "");
const [takeOutOfService, setTakeOutOfService] = useState(
line.takeOutOfService
);
const [outOfServiceReason, setOutOfServiceReason] = useState(
line.outOfServiceReason ?? ""
);
// Unique per line: the switch's id is its field name.
const outOfServiceField = `takeOutOfService-${line.id}`;
const updateField = (field: string, value: string) => {
const formData = new FormData();
formData.append("id", line.id);
formData.append("field", field);
formData.append("value", value);
fetcher.submit(formData, {
method: "post",
action: path.to.receiptFixedAssetLineUpdate
});
};
return (
<div className={cn("@container flex flex-col gap-6 p-6", className)}>
<RentalUnitRow
line={line}
checked={line.received}
checkedLabel={t`Received`}
isReadOnly={isReadOnly}
onCheckedChange={(checked) => updateField("received", String(checked))}
onMeterChange={(meter) => updateField("meter", meter)}
/>
<VStack spacing={4}>
<VStack spacing={1}>
<label className="text-xs text-muted-foreground">
<Trans>Notes</Trans>
</label>
<Textarea
aria-label={t`Notes`}
value={notes}
disabled={isReadOnly}
onChange={(e) => setNotes(e.target.value)}
onBlur={() => {
if (notes !== (line.notes ?? "")) {
updateField("notes", notes);
}
}}
/>
</VStack>
<VStack spacing={2}>
{/* A form only for the field's context: the switch saves through
updateField like every other field on the line. */}
<ValidatedForm
defaultValues={{ [outOfServiceField]: line.takeOutOfService }}
validator={z.object({ [outOfServiceField]: z.any() })}
className="w-full"
>
<Boolean
name={outOfServiceField}
label={t`Take out of service`}
bordered
value={takeOutOfService}
isDisabled={isReadOnly}
onChange={(isTicked) => {
setTakeOutOfService(isTicked);
if (!isTicked) {
setOutOfServiceReason("");
updateField("outOfService", "");
}
}}
/>
</ValidatedForm>
{takeOutOfService && (
<>
<Input
aria-label={t`Reason`}
placeholder={t`Reason`}
value={outOfServiceReason}
isDisabled={isReadOnly}
onChange={(e) => setOutOfServiceReason(e.target.value)}
onBlur={() => {
const reason = outOfServiceReason.trim();
if (reason && reason !== (line.outOfServiceReason ?? "")) {
updateField("outOfService", reason);
}
}}
/>
{!line.outOfServiceReason && (
<span className="text-xs text-muted-foreground">
<Trans>Enter a reason to take the unit out of service</Trans>
</span>
)}
</>
)}
{line.lessorClassification === "Sale" && (
<VStack spacing={1} className="pt-2">
<label className="text-xs text-muted-foreground">
<Trans>Return To</Trans>
</label>
<RadioGroup
value={line.residualDestination ?? ""}
disabled={isReadOnly}
onValueChange={(value) =>
updateField("residualDestination", value)
}
>
<HStack spacing={2}>
<RadioGroupItem
value="Fleet"
id={`${line.id}:residualDestination:Fleet`}
/>
<label
htmlFor={`${line.id}:residualDestination:Fleet`}
className="text-sm"
>
<Trans>Rental fleet, as a new fleet asset</Trans>
</label>
</HStack>
<HStack spacing={2}>
<RadioGroupItem
value="Inventory"
id={`${line.id}:residualDestination:Inventory`}
/>
<label
htmlFor={`${line.id}:residualDestination:Inventory`}
className="text-sm"
>
<Trans>Inventory, as finished goods</Trans>
</label>
</HStack>
</RadioGroup>
</VStack>
)}
</VStack>
</VStack>
</div>
);
}
/** An inspection lot posting the receipt opened for one of its lines. */
type ReceiptLineInspection = {
id: string;
inspectionId: string;
sourceDocumentLineId: string | null;
status: string;
};
/**
* A small red mark beside a line whose item is inspected at receipt: before
* posting, the item has a Receipt-usage inspection plan; after, the lot posting
* opened, which the mark links to.
*/
function ReceiptLineInspectionMark({
inspection
}: {
inspection?: ReceiptLineInspection;
}) {
const { t } = useLingui();
const permissions = usePermissions();
const icon = <LuClipboardCheck className="size-4 shrink-0 text-red-500" />;
return (
<Tooltip>
<TooltipTrigger asChild>
{inspection && permissions.can("view", "quality") ? (
<Link
to={path.to.inspection(inspection.id)}
aria-label={t`Inspection ${inspection.inspectionId}`}
>
{icon}
</Link>
) : (
<span role="img" aria-label={t`Requires inspection`}>
{icon}
</span>
)}
</TooltipTrigger>
<TooltipContent>
{inspection ? (
<Trans>
Inspection {inspection.inspectionId} · {inspection.status}
</Trans>
) : (
<Trans>
Requires inspection. A lot opens when the receipt posts.
</Trans>
)}
</TooltipContent>
</Tooltip>
);
}
function ReceiptLineItem({
line,
receipt,
inspection,
requiresInspection,
className,
isReadOnly,
onUpdate,
files,
batchProperties,
itemShelfLife,
tracking,
serialNumbers,
getPath,
onSerialNumbersChange,
upload,
deleteFile
}: {
line: ReceiptLine;
receipt?: Receipt;
inspection?: ReceiptLineInspection;
requiresInspection: boolean;
className?: string;
isReadOnly: boolean;
files?: PostgrestResponse<StorageItem>;
batchProperties?: PostgrestResponse<BatchProperty>;
itemShelfLife?: PostgrestResponse<{
itemId: string;
mode: string;
days: number | null;
}>;
tracking: ItemTracking | undefined;
serialNumbers: { index: number; number: string }[];
getPath: (file: StorageItem) => string;
onSerialNumbersChange: (
serialNumbers: { index: number; number: string }[]
) => void;
onUpdate: ({
lineId,
field,
value
}:
| {
lineId: string;
field: "receivedQuantity";
value: number;
}
| {
lineId: string;
field: "storageUnitId";
value: string;
}) => Promise<void>;
upload: (files: File[]) => Promise<void>;
deleteFile: (file: StorageItem) => Promise<void>;
}) {
const { t } = useLingui();
const [items] = useItems();
const item = items.find((p) => p.id === line.itemId);
const unitsOfMeasure = useUnitOfMeasure();
const splitDisclosure = useDisclosure();
const deleteDisclosure = useDisclosure();
const remainingQuantity =
(line.outstandingQuantity ?? 0) - (line.receivedQuantity ?? 0);
const isSurplus = remainingQuantity < 0;
return (
<div
className={cn(
"@container flex flex-col border-b p-6 gap-6 relative max-md:p-4 max-md:gap-4",
className
)}
>
<div className="absolute top-3 right-6 max-md:right-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<IconButton
aria-label={t`Line options`}
variant="secondary"
icon={<LuEllipsisVertical />}
size="sm"
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem
disabled={isReadOnly}
onClick={splitDisclosure.onOpen}
>
<DropdownMenuIcon icon={<LuSplit />} />
{t`Split receipt line`}
</DropdownMenuItem>
<DropdownMenuItem
shortcut={MENU_ITEM_SHORTCUTS.delete}
destructive
disabled={isReadOnly}
onClick={deleteDisclosure.onOpen}
>
<DropdownMenuIcon icon={<LuTrash />} />
{t`Delete receipt line`}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{/* Sized by the line's own width, not the viewport: the content pane
it sits in is resizable. The item takes what the quantities leave,
and they stay on one line once the row is wide enough. pr-10 clears
the line menu. */}
<div className="flex flex-1 flex-col @3xl:flex-row @3xl:items-center gap-4 w-full pr-10">
<HStack spacing={4} className="w-full @3xl:w-auto @3xl:flex-1 min-w-0">
<HStack spacing={4} className="flex-1 min-w-0">
<ItemThumbnail
size="md"
thumbnailPath={line.thumbnailPath}
type={(item?.type as "Part") ?? "Part"}
/>
<VStack spacing={0} className="flex-1 min-w-0">
<HStack spacing={1} className="w-full min-w-0">
<span
className="text-sm font-medium truncate block min-w-0"
title={item?.name}
>
{item?.name}
</span>
{requiresInspection && (
<ReceiptLineInspectionMark inspection={inspection} />
)}
</HStack>
<span className="text-xs text-muted-foreground line-clamp-2">
{item?.readableIdWithRevision}
</span>
<div className="mt-2">
<Enumerable
value={
unitsOfMeasure?.find((u) => u.value === line.unitOfMeasure)
?.label ?? null
}
/>
</div>
</VStack>
</HStack>
</HStack>
<div className="flex flex-wrap @3xl:flex-nowrap items-center gap-x-6 gap-y-4 w-full @3xl:w-auto @3xl:shrink-0">
<HStack spacing={4}>
<VStack spacing={1}>
<label className="text-xs text-muted-foreground">
<Trans>Received</Trans>
</label>
<NumberField
value={line.receivedQuantity ?? 0}
onChange={(value) => {
// Default to 0 if value is NaN, null, or undefined
const safeValue = isNaN(value) || value == null ? 0 : value;
onUpdate({
lineId: line.id!,
field: "receivedQuantity",
value: safeValue
});
// Adjust serial numbers array size while preserving existing values
if (safeValue > serialNumbers.length) {
onSerialNumbersChange([
...serialNumbers,
...Array.from(
{ length: safeValue - serialNumbers.length },
() => ({
index: serialNumbers.length,
number: ""
})
)
]);
} else if (safeValue < serialNumbers.length) {
onSerialNumbersChange(serialNumbers.slice(0, safeValue));
}
}}
>
<NumberInput
className="disabled:bg-transparent disabled:opacity-100 min-w-[100px] max-md:w-full"
isDisabled={isReadOnly}
size="sm"
min={0}
/>
</NumberField>
</VStack>
<VStack spacing={1} className="text-center items-center">
<label className="text-xs text-muted-foreground">
<Trans>Ordered</Trans>
</label>
<span className="text-sm py-1.5">{line.orderQuantity ?? 0}</span>
</VStack>
<VStack spacing={1} className="text-center items-center">
<label className="text-xs text-muted-foreground">
{isSurplus ? (
<Trans>Surplus</Trans>
) : (
<Trans>Outstanding</Trans>
)}
</label>
<HStack className="justify-center">
<span
className={cn("text-sm py-1.5", isSurplus && "text-red-500")}
>
{Math.abs(remainingQuantity)}
</span>
{isSurplus && (
<Tooltip>
<TooltipTrigger>
<LuCircleAlert className="text-red-500" />
</TooltipTrigger>
<TooltipContent>
<Trans>There are more received than ordered</Trans>
</TooltipContent>
</Tooltip>
)}
</HStack>
</VStack>
</HStack>
<div className="flex flex-col items-start gap-1 min-w-[140px] text-sm max-md:w-full">
<label className="text-xs text-muted-foreground">
<Trans>Storage Unit</Trans>
</label>
<StorageUnit
locationId={line.locationId}
value={line.storageUnitId}
isReadOnly={isReadOnly}
onChange={(storageUnit) => {
onUpdate({
lineId: line.id!,
field: "storageUnitId",
value: storageUnit?.id ?? ""
});
}}
/>
</div>
</div>
</div>
{line.requiresBatchTracking &&
(receipt?.sourceDocument === "Sales Return Order" ? (
<ReturnEntityForm
receipt={receipt}
line={line}
trackingType="batch"
isReadOnly={isReadOnly}
>
<BatchForm
receipt={receipt}
line={line}
isReadOnly={isReadOnly}
tracking={tracking}
batchProperties={batchProperties}
itemShelfLife={itemShelfLife}
/>
</ReturnEntityForm>
) : (
<BatchForm
receipt={receipt}
line={line}
isReadOnly={isReadOnly}
tracking={tracking}
batchProperties={batchProperties}
itemShelfLife={itemShelfLife}
/>
))}
{line.requiresSerialTracking &&
(receipt?.sourceDocument === "Sales Return Order" ? (
<ReturnEntityForm
receipt={receipt}
line={line}
trackingType="serial"
isReadOnly={isReadOnly}
>
<SerialForm
receipt={receipt}
line={line}
serialNumbers={serialNumbers}
isReadOnly={isReadOnly}
onSerialNumbersChange={onSerialNumbersChange}
itemShelfLife={itemShelfLife}
tracking={tracking}
/>
</ReturnEntityForm>
) : (
<SerialForm
receipt={receipt}
line={line}
serialNumbers={serialNumbers}
isReadOnly={isReadOnly}
onSerialNumbersChange={onSerialNumbersChange}
itemShelfLife={itemShelfLife}
tracking={tracking}
/>
))}
{(line.requiresBatchTracking || line.requiresSerialTracking) && (
<>
<Suspense fallback={null}>
<Await resolve={files}>
{(resolvedFiles) => {
const lineFiles = resolvedFiles?.data?.filter(
(file) => file.bucket === line.id
);
return Array.isArray(lineFiles) && lineFiles.length > 0 ? (
<div className="flex flex-col gap-2">
{lineFiles.map((file) => {
const documentType = getDocumentType(file.name);
return (
<HStack key={file.id}>
<DocumentIcon type={documentType} />
<span className="font-medium text-sm">
{isPreviewableDocumentType(documentType) ? (
<DocumentPreview
bucket="private"
pathToFile={getPath(file)}
type={documentType}
>
{file.name}
</DocumentPreview>
) : (
file.name
)}
</span>
<IconButton
icon={<LuX />}
aria-label={t`Delete file`}
variant="ghost"
onClick={() => deleteFile(file)}
/>
</HStack>
);
})}
</div>
) : null;
}}
</Await>
</Suspense>
<FileDropzone onDrop={upload} />
{splitDisclosure.isOpen && (
<SplitReceiptLineModal
line={line}
onClose={splitDisclosure.onClose}
/>
)}
{deleteDisclosure.isOpen && (
<ConfirmDelete
name="Receipt Line"
text="Are you sure you want to delete this receipt line?"
action={path.to.receiptLineDelete(line.id!)}
onCancel={deleteDisclosure.onClose}
onSubmit={deleteDisclosure.onClose}
/>
)}
</>
)}
</div>
);
}
function BatchForm({
line,
receipt,
batchProperties,
itemShelfLife,
tracking,
isReadOnly
}: {
line: ReceiptLine;
receipt?: Receipt;
isReadOnly: boolean;
batchProperties?: PostgrestResponse<BatchProperty>;
itemShelfLife?: PostgrestResponse<{
itemId: string;
mode: string;
days: number | null;
}>;
tracking: ItemTracking | undefined;
}) {
const { t } = useLingui();
const submit = useSubmit();
const shelfLife = itemShelfLife?.data?.find(
(sl) => sl.itemId === line.itemId
);
const showExpiryField = shelfLife?.mode === "Set on Receipt";
const [values, setValues] = useState<{
number: string;
properties: any;
expirationDate: string;
}>(() => {
if (tracking) {
const attributes = tracking.attributes as TrackedEntityAttributes;
return {
number: tracking.readableId || "",
expirationDate: tracking.expirationDate ?? "",
properties: Object.entries(attributes)
.filter(
([key]) =>
![
"Shipment Line",
"Shipment",
"Shipment Line Index",
"Receipt Line",
"Receipt",
"expirationDate"
].includes(key)
)
.reduce((acc, [key, value]) => ({ ...acc, [key]: value || "" }), {})
};
}
return {
number: "",
properties: {},
expirationDate: ""
};
});
useEffect(() => {
if (!tracking) return;
setValues((prev) => {
const attributes = tracking.attributes as TrackedEntityAttributes;
const newExpiration = tracking.expirationDate ?? "";
const newNumber = tracking.readableId || "";
if (prev.expirationDate === newExpiration && prev.number === newNumber)
return prev;
return {
number: newNumber || prev.number,
expirationDate: newExpiration || prev.expirationDate,
properties: Object.entries(attributes)
.filter(
([key]) =>
![
"Shipment Line",
"Shipment",
"Shipment Line Index",
"Receipt Line",
"Receipt",
"expirationDate"
].includes(key)
)
.reduce((acc, [key, value]) => ({ ...acc, [key]: value || "" }), {})
};
});
}, [tracking]);
const updateBatchNumber = async (newValues: typeof values, isNew = false) => {
if (!receipt?.id || !newValues.number.trim()) return;
let batchMatch = null;
if (isNew && tracking) {
batchMatch = tracking.readableId;
}
let valuesToSubmit = newValues;
if (batchMatch) {
const attributes = tracking?.attributes as TrackedEntityAttributes;
valuesToSubmit = {
...newValues,
properties: Object.entries(attributes)
.filter(([key]) => !["Receipt Line"].includes(key))
.reduce((acc, [key, value]) => ({ ...acc, [key]: value || "" }), {})
};
// Just update the local state without triggering another database write
setValues(valuesToSubmit);
}
const formData = new FormData();
formData.append("itemId", line.itemId!);
formData.append("receiptId", receipt.id);
formData.append("receiptLineId", line.id!);
formData.append("trackingType", "batch");
if (tracking?.id) {
formData.append("trackedEntityId", tracking.id);
}
formData.append("batchNumber", valuesToSubmit.number.trim());
const propertiesWithExpiry = valuesToSubmit.expirationDate
? {
...valuesToSubmit.properties,
expirationDate: valuesToSubmit.expirationDate
}
: valuesToSubmit.properties;
formData.append("properties", JSON.stringify(propertiesWithExpiry));
formData.append("quantity", (line.receivedQuantity ?? 0).toString());
submit(formData, {
method: "post",
action: path.to.receiptLinesTracking(receipt.id),
navigate: false
});
};
const handlePropertiesChange = (newProperties: any) => {
const newValues = {
...values,
properties: newProperties
};
setValues(newValues);
updateBatchNumber(newValues);
};
const propertiesDisclosure = useDisclosure();
return (
<div className="flex flex-col gap-6 w-full p-6 border rounded-lg max-md:gap-4 max-md:p-4">
<div className="flex justify-between items-center gap-4">
<Heading size="h4">Batch Properties</Heading>
<div className="flex items-center gap-2">
{values.number.trim() !== "" && (
<PrintButton
sourceDocument="Receipt"
sourceDocumentId={receipt?.id ?? ""}
locationId={receipt?.locationId ?? undefined}
context="receiving"
fileRoutes={{
pdf: (id, opts) =>
path.to.file.receiptLabelsPdf(id, {
...opts,
lineId: line.id!
}),
zpl: (id, opts) =>
path.to.file.receiptLabelsZpl(id, {
...opts,
lineId: line.id!
})
}}
/>
)}
<Button
variant="secondary"
leftIcon={<LuGroup />}
size="md"
onClick={propertiesDisclosure.onOpen}
>
Edit Properties
</Button>
</div>
</div>
<div className="grid grid-cols-1 @min-[42rem]: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 /> <Trans>Batch Number</Trans>
{showExpiryField && (
<span className="text-destructive-foreground">*</span>
)}
</label>
<Input
placeholder={`Batch number`}
isDisabled={isReadOnly}
value={values.number}
onChange={(e) => {
setValues((prev) => ({
...prev,
number: e.target.value
}));
}}
onBlur={() => {
updateBatchNumber(values, true);
}}
/>
</div>
{showExpiryField && (
<div className="flex flex-col gap-2 w-full">
<label className="text-xs text-muted-foreground flex items-center gap-2">
<LuCalendar /> <Trans>Expiration Date</Trans>
</label>
<DatePicker
isDisabled={isReadOnly}
value={
values.expirationDate ? parseDate(values.expirationDate) : null
}
onChange={(date) => {
const next = date?.toString() ?? "";
const newValues = { ...values, expirationDate: next };
setValues(newValues);
if (newValues.number.trim()) {
updateBatchNumber(newValues, true);
} else if (next) {
toast.error(
t`Enter a batch number before setting the expiration date`
);
}
}}
/>
</div>
)}
<Suspense fallback={null}>
<Await resolve={batchProperties}>
{(resolvedBatchProperties) => {
return (
<BatchPropertiesFields
itemId={line.itemId!}
properties={
resolvedBatchProperties?.data?.filter(
(p) => p.itemId === line.itemId
) ?? []
}
isReadOnly={isReadOnly}
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>
);
}
function SerialForm({
line,
receipt,
batchProperties,
itemShelfLife,
serialNumbers,
isReadOnly,
onSerialNumbersChange,
tracking
}: {
line: ReceiptLine;
receipt?: Receipt;
batchProperties?: PostgrestResponse<BatchProperty>;
itemShelfLife?: PostgrestResponse<{
itemId: string;
mode: string;
days: number | null;
}>;
serialNumbers: { index: number; number: string }[];
isReadOnly: boolean;
onSerialNumbersChange: (
serialNumbers: { index: number; number: string }[]
) => void;
tracking: ItemTracking | undefined;
}) {
const shelfLife = itemShelfLife?.data?.find(
(sl) => sl.itemId === line.itemId
);
const showExpiryField = shelfLife?.mode === "Set on Receipt";
const [expiryDate, setExpiryDate] = useState(tracking?.expirationDate ?? "");
useEffect(() => {
if (tracking?.expirationDate) {
setExpiryDate((prev) => prev || tracking.expirationDate || "");
}
}, [tracking?.expirationDate]);
const [errors, setErrors] = useState<Record<number, string>>({});
// Check for duplicates within the current form
const validateSerialNumber = useCallback(
(serialNumber: string, currentIndex: number) => {
const trimmedNumber = serialNumber.trim();
if (!trimmedNumber) return null;
const isDuplicate = serialNumbers.some(
(sn, idx) => idx !== currentIndex && sn.number.trim() === trimmedNumber
);
return isDuplicate ? "Duplicate serial number" : null;
},
[serialNumbers]
);
const saveSerialNumber = useCallback(
async (index: number, value: string) => {
if (!receipt?.id) return { ok: true, error: null };
const formData = new FormData();
formData.append("itemId", line.itemId!);
formData.append("receiptId", receipt.id);
formData.append("receiptLineId", line.id!);
formData.append("trackingType", "serial");
formData.append("index", index.toString());
formData.append("serialNumber", value);
if (expiryDate) {
formData.append("expiryDate", expiryDate);
}
try {
const response = await fetch(path.to.receiptLinesTracking(receipt.id), {
method: "POST",
body: formData
});
// The operation's result, `{ data, error }`; a refused form is a 422.
const result: { error: { message: string } | null } | null = response.ok
? await response.json()
: null;
if (result && !result.error) return { ok: true, error: null };
return {
ok: false,
error: result?.error?.message ?? "Failed to save the serial number"
};
} catch {
return { ok: false, error: "Failed to save the serial number" };
}
},
[line.id, line.itemId, receipt?.id, expiryDate]
);
const updateSerialNumber = useCallback(
async (serialNumber: { index: number; number: string }) => {
const { index } = serialNumber;
const saved = await saveSerialNumber(index, serialNumber.number.trim());
setErrors((prev) => {
const next = { ...prev };
if (saved.error) next[index] = saved.error;
else delete next[index];
return next;
});
},
[saveSerialNumber]
);
const propertiesDisclosure = useDisclosure();
return (
<div className="flex flex-col gap-6 p-6 border rounded-lg max-md:gap-4 max-md:p-4">
<div className="flex justify-between items-center gap-6">
<Heading size="h4">Serial Numbers</Heading>
<div className="flex items-center gap-2">
<PrintButton
sourceDocument="Receipt"
sourceDocumentId={receipt?.id ?? ""}
locationId={receipt?.locationId ?? undefined}
context="receiving"
fileRoutes={{
pdf: (id, opts) =>
path.to.file.receiptLabelsPdf(id, {
...opts,
lineId: line.id!
}),
zpl: (id, opts) =>
path.to.file.receiptLabelsZpl(id, {
...opts,
lineId: line.id!
})
}}
/>
</div>
</div>
{showExpiryField && (
<div className="flex flex-col gap-2 max-w-xs max-md:max-w-none">
<label className="text-xs text-muted-foreground flex items-center gap-2">
<LuCalendar />{" "}
<Trans>Expiration Date (applies to all serials on this line)</Trans>
</label>
<DatePicker
isDisabled={isReadOnly}
value={expiryDate ? parseDate(expiryDate) : null}
onChange={(date) => setExpiryDate(date?.toString() ?? "")}
/>
</div>
)}
<div
data-serial-boxes
className="grid grid-cols-1 @min-[42rem]:grid-cols-3 gap-x-4 gap-y-3"
>
{serialNumbers.map((serialNumber, index) => (
<div
key={`${line.id}-${index}-serial`}
className="flex flex-col gap-1"
>
<Input
placeholder={`Serial ${index + 1}`}
isDisabled={isReadOnly}
value={serialNumber.number}
onChange={(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;
});
const newSerialNumbers = [...serialNumbers];
newSerialNumbers[index] = {
index,
number: newValue
};
onSerialNumbersChange(newSerialNumbers);
}}
onBlur={() => {
updateSerialNumber(serialNumber);
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
const nextInput = e.currentTarget
.closest("[data-serial-boxes]")
?.querySelector<HTMLInputElement>(
`input[placeholder="Serial ${index + 2}"]`
);
if (nextInput) nextInput.focus();
else e.currentTarget.blur();
}
}}
className={cn(errors[index] && "border-destructive")}
/>
{errors[index] && (
<span className="text-xs text-destructive">{errors[index]}</span>
)}
</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>
</div>
);
}
function SplitReceiptLineModal({
line,
onClose
}: {
line: ReceiptLine;
onClose: () => void;
}) {
const { t } = useLingui();
const fetcher = useAction<typeof splitAction>({ onSuccess: onClose });
return (
<Modal open onOpenChange={onClose}>
<ModalContent>
<ValidatedForm
method="post"
action={path.to.receiptLineSplit}
validator={splitValidator}
fetcher={fetcher}
>
<ModalHeader>
<ModalTitle>Split Receipt Line</ModalTitle>
<ModalDescription>
Select the quantity that you'd like to split into a new line.
</ModalDescription>
</ModalHeader>
<ModalBody>
<input
type="hidden"
name="documentId"
value={line.receiptId ?? ""}
/>
<input type="hidden" name="documentLineId" value={line.id!} />
<input
type="hidden"
name="locationId"
value={line.locationId ?? ""}
/>
<Number
name="quantity"
label={t`Quantity`}
maxValue={line.orderQuantity ?? 0 - 0.0001}
minValue={0.0001}
/>
</ModalBody>
<ModalFooter>
<Button variant="secondary" onClick={onClose}>
Cancel
</Button>
<Submit>Split Line</Submit>
</ModalFooter>
</ValidatedForm>
</ModalContent>
</Modal>
);
}
const usePendingReceiptLines = () => {
type PendingItem = ReturnType<typeof useFetchers>[number] & {
formData: FormData;
};
return useFetchers()
.filter((fetcher): fetcher is PendingItem => {
return fetcher.formAction === path.to.bulkUpdateReceiptLine;
})
.reduce<{ id: string; [key: string]: string | null }[]>((acc, fetcher) => {
const lineId = fetcher.formData.get("ids") as string;
const field = fetcher.formData.get("field") as string;
const value = fetcher.formData.get("value") as string;
if (lineId && field && value) {
const newItem: { id: string; [key: string]: string | null } = {
id: lineId,
[field]: value
};
return [...acc, newItem];
}
return acc;
}, []);
};
export default ReceiptLines;
function useReceiptFiles(receiptId: string) {
const { t } = useLingui();
const { company } = useUser();
const { carbon } = useCarbon();
const getPath = useCallback(
({ name }: { name: string }, lineId: string) => {
return `${company.id}/inventory/${lineId}/${stripSpecialCharacters(
name
)}`;
},
[company.id]
);
const submit = useSubmit();
const revalidator = useRevalidator();
const upload = useCallback(
async (files: File[], lineId: string) => {
if (!carbon) {
toast.error(t`Carbon client not available`);
return;
}
for (const file of files) {
const fileName = getPath({ name: file.name }, lineId);
toast.info(`Uploading ${file.name}`);
const fileUpload = await storage(carbon)
.company(company.id)
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
});
if (fileUpload.error) {
toast.error(`Failed to upload file: ${file.name}`);
} else if (fileUpload.data?.path) {
toast.success(`Uploaded: ${file.name}`);
const formData = new FormData();
formData.append("path", fileUpload.data.path);
formData.append("name", file.name);
formData.append("size", Math.round(file.size / 1024).toString());
formData.append("sourceDocument", "Receipt");
formData.append("sourceDocumentId", receiptId);
submit(formData, {
method: "post",
action: path.to.newDocument,
navigate: false,
fetcherKey: `${lineId}:${file.name}`
});
}
}
revalidator.revalidate();
},
[carbon, company.id, revalidator, getPath, receiptId, submit, t]
);
const deleteFile = useCallback(
async (file: StorageItem, lineId: string) => {
if (!carbon) {
toast.error("Error deleting file");
return;
}
const { error } = await storage(carbon)
.company(company.id)
.remove([getPath(file, lineId)]);
if (error) {
toast.error(error.message || "Error deleting file");
return;
}
toast.success(`${file.name} deleted successfully`);
revalidator.revalidate();
},
[getPath, carbon, company.id, revalidator]
);
return { upload, deleteFile, getPath };
}