Skip to content

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

feat: add validation to serial number, and receipt posting

Brad Barbin030eea058406
diff --git a/apps/erp/app/components/Table/Table.tsx b/apps/erp/app/components/Table/Table.tsx
index e3bc90e44b..a1cc01368e 100644
--- a/apps/erp/app/components/Table/Table.tsx
+++ b/apps/erp/app/components/Table/Table.tsx
@@ -636,9 +636,9 @@ const Table = <T extends object>({
</TableBase>
</div>
) : hasFilters ? (
- <div className="flex flex-col w-full h-full items-center justify-center gap-4">
+ <div className="flex flex-col w-full h-full items-center justify-start gap-4 pt-[15dvh]">
<div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">
- <LuTriangleAlert className="h-6 w-6" />
+ <LuTriangleAlert className="h-6 w-6 flex-shrink-0" />
</div>
<span className="text-xs font-mono font-light text-foreground uppercase">
No results found
@@ -648,9 +648,9 @@ const Table = <T extends object>({
</Button>
</div>
) : (
- <div className="flex flex-col w-full h-full items-center justify-center gap-4">
+ <div className="flex flex-col w-full h-full items-center justify-start gap-4 pt-[15dvh]">
<div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">
- <LuTriangleAlert className="h-6 w-6" />
+ <LuTriangleAlert className="h-6 w-6 flex-shrink-0" />
</div>
<span className="text-xs font-mono font-light text-foreground uppercase">
No data exists
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index f4558118bc..155974b4fd 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -240,6 +240,18 @@ export async function getReceiptLines(
return client.from("receiptLine").select("*").eq("receiptId", receiptId);
}
+export async function getReceiptLineTracking(
+ client: SupabaseClient<Database>,
+ receiptId: string
+) {
+ return client
+ .from("receiptLineTracking")
+ .select(
+ "*, lotNumber(id, number, manufacturingDate, expirationDate), serialNumber(id, number)"
+ )
+ .eq("receiptId", receiptId);
+}
+
export async function getReceiptFiles(
client: SupabaseClient<Database>,
companyId: string,
diff --git a/apps/erp/app/modules/inventory/types.ts b/apps/erp/app/modules/inventory/types.ts
index 799a929de5..edf983b4ea 100644
--- a/apps/erp/app/modules/inventory/types.ts
+++ b/apps/erp/app/modules/inventory/types.ts
@@ -3,6 +3,7 @@ import type {
getInventoryItems,
getItemLedgerPage,
getReceiptLines,
+ getReceiptLineTracking,
getReceipts,
getShippingMethods,
} from "./inventory.service";
@@ -19,6 +20,10 @@ export type Receipt = NonNullable<
Awaited<ReturnType<typeof getReceipts>>["data"]
>[number];
+export type ReceiptLineTracking = NonNullable<
+ Awaited<ReturnType<typeof getReceiptLineTracking>>["data"]
+>[number];
+
export type ReceiptSourceDocument =
Database["public"]["Enums"]["receiptSourceDocument"];
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index 321c0e22a5..08c0fb9a7a 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -29,7 +29,7 @@ import {
useSubmit,
} from "@remix-run/react";
import type { PostgrestResponse } from "@supabase/supabase-js";
-import { Suspense, useCallback, useState } from "react";
+import { Suspense, useCallback, useEffect, useState } from "react";
import {
LuBarcode,
LuCalendar,
@@ -45,7 +45,11 @@ import { useShelves } from "~/components/Form/Shelf";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { TrackingTypeIcon } from "~/components/Icons";
import { useRouteData, useUser } from "~/hooks";
-import type { Receipt, ReceiptLine } from "~/modules/inventory";
+import type {
+ Receipt,
+ ReceiptLine,
+ ReceiptLineTracking,
+} from "~/modules/inventory";
import { getDocumentType } from "~/modules/shared/shared.service";
import type { action as receiptLinesUpdateAction } from "~/routes/x+/receipt+/lines.update";
import { useItems } from "~/stores";
@@ -63,17 +67,18 @@ const ReceiptLines = () => {
receipt: Receipt;
receiptLines: ReceiptLine[];
receiptFiles: PostgrestResponse<StorageItem>;
+ receiptLineTracking: ReceiptLineTracking[];
}>(path.to.receipt(receiptId));
const receiptsById = new Map<string, ReceiptLine>(
routeData?.receiptLines.map((line) => [line.id, line])
);
- const pendingItems = usePendingItems();
+ const pendingReceiptLines = usePendingReceiptLines();
- for (let pendingItem of pendingItems) {
- let item = receiptsById.get(pendingItem.id);
- let merged = item ? { ...item, ...pendingItem } : pendingItem;
- receiptsById.set(pendingItem.id, merged as ReceiptLine);
+ 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());
@@ -86,26 +91,48 @@ const ReceiptLines = () => {
...acc,
[line.id]: Array(line.receivedQuantity)
.fill(null)
- .map((_, index) => ({
- index,
- number: "",
- })),
+ .map((_, index) => {
+ const serialNumber = routeData?.receiptLineTracking.find(
+ (t) =>
+ t.receiptLineId === line.id &&
+ t.serialNumber !== null &&
+ t.index === index
+ )?.serialNumber;
+ return {
+ index,
+ number: serialNumber?.number ?? "",
+ };
+ }),
}),
{}
);
});
- const [lotNumberByLineId, setLotNumberByLineId] = useState<
- Record<
- string,
- {
- id: string;
- number: string;
- manufacturingDate: string;
- expirationDate: string;
- }
- >
- >({});
+ useEffect(() => {
+ setSerialNumbersByLineId(
+ receiptLines.reduce(
+ (acc, line) => ({
+ ...acc,
+ [line.id]: Array(line.receivedQuantity)
+ .fill(null)
+ .map((_, index) => {
+ const serialNumber = routeData?.receiptLineTracking.find(
+ (t) =>
+ t.receiptLineId === line.id &&
+ t.serialNumber !== null &&
+ t.index === index
+ )?.serialNumber;
+ return {
+ index,
+ number: serialNumber?.number ?? "",
+ };
+ }),
+ }),
+ {}
+ )
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [routeData?.receipt?.sourceDocumentId]);
const onUpdateReceiptLine = useCallback(
async ({
@@ -172,7 +199,16 @@ const ReceiptLines = () => {
[line.id]: newSerialNumbers,
}));
}}
- lotNumber={lotNumberByLineId[line.id] || ""}
+ lotNumber={
+ routeData?.receiptLineTracking.find(
+ (t) => t.receiptLineId === line.id && t.lotNumber !== null
+ )?.lotNumber ?? {
+ id: "",
+ number: "",
+ manufacturingDate: null,
+ expirationDate: null,
+ }
+ }
upload={(files) => upload(files, line.id)}
deleteFile={(file) => deleteFile(file, line.id)}
/>
@@ -207,8 +243,8 @@ function ReceiptLineItem({
lotNumber: {
id: string;
number: string;
- manufacturingDate?: string;
- expirationDate?: string;
+ manufacturingDate?: string | null;
+ expirationDate?: string | null;
};
serialNumbers: { index: number; number: string }[];
getPath: (file: StorageItem) => string;
@@ -417,8 +453,8 @@ function LotForm({
initialValues?: {
id: string;
number: string;
- manufacturingDate?: string;
- expirationDate?: string;
+ manufacturingDate?: string | null;
+ expirationDate?: string | null;
};
}) {
const submit = useSubmit();
@@ -561,12 +597,36 @@ function SerialForm({
serialNumbers: { index: number; number: string }[]
) => void;
}) {
- const submit = useSubmit();
+ 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 updateSerialNumber = useCallback(
async (serialNumber: { index: number; number: string }) => {
if (!receipt?.id || !serialNumber.number.trim()) return;
+ const error = validateSerialNumber(
+ serialNumber.number,
+ serialNumber.index
+ );
+ if (error) {
+ setErrors((prev) => ({ ...prev, [serialNumber.index]: error }));
+ return;
+ }
+
const formData = new FormData();
formData.append("itemId", line.itemId);
formData.append("receiptId", receipt.id);
@@ -575,13 +635,35 @@ function SerialForm({
formData.append("index", serialNumber.index.toString());
formData.append("serialNumber", serialNumber.number.trim());
- submit(formData, {
- method: "post",
- action: path.to.receiptLinesTracking(receipt.id),
- navigate: false,
- });
+ try {
+ const response = await fetch(path.to.receiptLinesTracking(receipt.id), {
+ method: "POST",
+ body: formData,
+ });
+
+ if (response.ok) {
+ // Clear error if submission was successful
+ setErrors((prev) => {
+ const newErrors = { ...prev };
+ delete newErrors[serialNumber.index];
+ return newErrors;
+ });
+ } else {
+ setErrors((prev) => ({
+ ...prev,
+ [serialNumber.index]: "Serial number already exists",
+ }));
+ }
+ } catch (error) {
+ if (error instanceof Error && error.message.includes("duplicate")) {
+ setErrors((prev) => ({
+ ...prev,
+ [serialNumber.index]: "Serial number already exists for this item",
+ }));
+ }
+ }
},
- [line.id, line.itemId, receipt?.id, submit]
+ [line.id, line.itemId, receipt?.id, validateSerialNumber]
);
return (
@@ -592,39 +674,60 @@ function SerialForm({
<div className="grid grid-cols-1 lg:grid-cols-3 gap-x-4 gap-y-3">
{serialNumbers.map((serialNumber, index) => (
- <Input
+ <div
key={`${line.id}-${index}-serial`}
- placeholder={`Serial ${index + 1}`}
- disabled={isReadOnly}
- value={serialNumber.number}
- onChange={(e) => {
- const newSerialNumbers = [...serialNumbers];
- newSerialNumbers[index] = {
- index,
- number: e.target.value,
- };
- onSerialNumbersChange(newSerialNumbers);
- }}
- onBlur={() => {
- if (serialNumber.number.trim()) {
- updateSerialNumber(serialNumber);
- }
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- e.preventDefault();
+ className="flex flex-col gap-1"
+ >
+ <Input
+ placeholder={`Serial ${index + 1}`}
+ disabled={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={() => {
if (serialNumber.number.trim()) {
updateSerialNumber(serialNumber);
}
- const nextInput = e.currentTarget
- .closest("div")
- ?.querySelector(`input[placeholder="Serial ${index + 2}"]`);
- if (nextInput) {
- (nextInput as HTMLElement).focus();
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ if (serialNumber.number.trim()) {
+ updateSerialNumber(serialNumber);
+ }
+ const nextInput = e.currentTarget
+ .closest("div")
+ ?.querySelector(`input[placeholder="Serial ${index + 2}"]`);
+ if (nextInput) {
+ (nextInput as HTMLElement).focus();
+ }
}
- }
- }}
- />
+ }}
+ className={cn(errors[index] && "border-destructive")}
+ />
+ {errors[index] && (
+ <span className="text-xs text-destructive">{errors[index]}</span>
+ )}
+ </div>
))}
</div>
</div>
@@ -665,7 +768,7 @@ function Shelf({
);
}
-const usePendingItems = () => {
+const usePendingReceiptLines = () => {
type PendingItem = ReturnType<typeof useFetchers>[number] & {
formData: FormData;
};
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
index b1fdbb1532..56c91c8cea 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
@@ -1,15 +1,24 @@
+import { useCarbon } from "@carbon/auth";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
Button,
HStack,
Modal,
ModalBody,
ModalContent,
+ ModalDescription,
ModalFooter,
ModalHeader,
ModalOverlay,
ModalTitle,
+ toast,
+ useMount,
} from "@carbon/react";
import { Form, useNavigation, useParams } from "@remix-run/react";
+import { useState } from "react";
+import { LuTriangleAlert } from "react-icons/lu";
import { path } from "~/utils/path";
const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
@@ -17,6 +26,74 @@ const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
if (!receiptId) throw new Error("receiptId not found");
const navigation = useNavigation();
+ const { carbon } = useCarbon();
+ const [validated, setValidated] = useState(false);
+ const [validationErrors, setValidationErrors] = useState<
+ {
+ itemReadableId: string | null;
+ receivedQuantity: number;
+ receivedQuantityError: string;
+ }[]
+ >([]);
+
+ const getReceiptLines = async () => {
+ if (!carbon) {
+ toast.error("Carbon client not found");
+ return;
+ }
+ const receiptLines = await carbon
+ .from("receiptLine")
+ .select(
+ "id, itemReadableId, receivedQuantity, requiresLotTracking, requiresSerialTracking, receiptLineTracking(id, quantity, serialNumber(number), lotNumber(number))"
+ )
+ .eq("receiptId", receiptId);
+
+ if (receiptLines.error) {
+ toast.error("Error fetching receipt lines");
+ return;
+ }
+
+ const errors: {
+ itemReadableId: string | null;
+ receivedQuantity: number;
+ receivedQuantityError: string;
+ }[] = [];
+
+ receiptLines.data.forEach((line) => {
+ if (
+ line.requiresLotTracking &&
+ (line.receiptLineTracking.length === 0 ||
+ !line.receiptLineTracking[0].lotNumber)
+ ) {
+ errors.push({
+ itemReadableId: line.itemReadableId,
+ receivedQuantity: line.receivedQuantity,
+ receivedQuantityError: "Lot number is required",
+ });
+ }
+
+ if (line.requiresSerialTracking) {
+ const quantityWithSerial = line.receiptLineTracking.reduce(
+ (acc, tracking) => acc + tracking.quantity,
+ 0
+ );
+ if (quantityWithSerial !== line.receivedQuantity) {
+ errors.push({
+ itemReadableId: line.itemReadableId,
+ receivedQuantity: line.receivedQuantity,
+ receivedQuantityError: "Serial numbers are missing",
+ });
+ }
+ }
+ });
+
+ setValidationErrors(errors);
+ setValidated(true);
+ };
+
+ useMount(() => {
+ getReceiptLines();
+ });
return (
<Modal
@@ -29,15 +106,47 @@ const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
<ModalContent>
<ModalHeader>
<ModalTitle>Post Receipt</ModalTitle>
+ <ModalDescription>
+ Are you sure you want to post this receipt?
+ </ModalDescription>
</ModalHeader>
- <ModalBody>Are you sure you want to post this receipt?</ModalBody>
+ <ModalBody>
+ {validationErrors.length > 0 && (
+ <Alert variant="destructive">
+ <LuTriangleAlert className="h-4 w-4" />
+ <AlertTitle>Missing Information</AlertTitle>
+ <AlertDescription>
+ <ul className="list-disc pl-4 mt-2 space-y-1">
+ {validationErrors.map((error, index) => (
+ <li key={index} className="text-sm font-medium">
+ <span className="font-mono">{error.itemReadableId}</span>
+ <span className="text-muted-foreground ml-2">
+ {error.receivedQuantity}
+ </span>
+ <span className="block mt-0.5 text-red-500 font-normal">
+ {error.receivedQuantityError}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </AlertDescription>
+ </Alert>
+ )}
+ </ModalBody>
<ModalFooter>
<HStack>
<Button variant="solid" onClick={onClose}>
Cancel
</Button>
<Form action={path.to.receiptPost(receiptId)} method="post">
- <Button isDisabled={navigation.state !== "idle"} type="submit">
+ <Button
+ isDisabled={
+ navigation.state !== "idle" ||
+ !validated ||
+ validationErrors.length > 0
+ }
+ type="submit"
+ >
Post Receipt
</Button>
</Form>
diff --git a/apps/erp/app/routes/_public+/invite.$code.tsx b/apps/erp/app/routes/_public+/invite.$code.tsx
index eea1ee2b2d..d2ec9f3032 100644
--- a/apps/erp/app/routes/_public+/invite.$code.tsx
+++ b/apps/erp/app/routes/_public+/invite.$code.tsx
@@ -147,7 +147,7 @@ export default function Invite() {
</Heading>
<motion.p
{...fade}
- transition={{ duration: 1.4, ease: "easeInOut", delay: 1.9 }}
+ transition={{ duration: 1.2, ease: "easeInOut", delay: 1.5 }}
className="text-muted-foreground text-sm pb-4"
>
CarbonOS is the operating system for manufacturing
@@ -156,7 +156,7 @@ export default function Invite() {
<Form method="post">
<Button
{...fade}
- transition={{ duration: 1, delay: 2.4 }}
+ transition={{ duration: 1.2, ease: "easeInOut", delay: 1.5 }}
size="lg"
type="submit"
>
diff --git a/apps/erp/app/routes/_public+/magic-link.tsx b/apps/erp/app/routes/_public+/magic-link.tsx
index 94a09dc932..ceefa74de9 100644
--- a/apps/erp/app/routes/_public+/magic-link.tsx
+++ b/apps/erp/app/routes/_public+/magic-link.tsx
@@ -57,7 +57,7 @@ export default function ConfirmMagicLink() {
</Heading>
<motion.p
{...fade}
- transition={{ duration: 0.8, ease: "easeInOut", delay: 0.9 }}
+ transition={{ duration: 0.8, ease: "easeInOut", delay: 0.5 }}
className="text-muted-foreground text-sm pb-4"
>
CarbonOS is the operating system for manufacturing
@@ -65,7 +65,7 @@ export default function ConfirmMagicLink() {
<Button
{...fade}
- transition={{ duration: 0.8, ease: "easeInOut", delay: 1.4 }}
+ transition={{ duration: 0.8, ease: "easeInOut", delay: 0.5 }}
size="lg"
onClick={() => {
window.location.href = getConfirmationURL(token);
diff --git a/apps/erp/app/routes/onboarding+/_index.tsx b/apps/erp/app/routes/onboarding+/_index.tsx
index 3c1735ad1d..a61b24f485 100644
--- a/apps/erp/app/routes/onboarding+/_index.tsx
+++ b/apps/erp/app/routes/onboarding+/_index.tsx
@@ -41,7 +41,7 @@ export default function GetStarted() {
</Heading>
<motion.p
{...fade}
- transition={{ duration: 1.4, ease: "easeInOut", delay: 1.9 }}
+ transition={{ duration: 1.2, ease: "easeInOut", delay: 1.5 }}
className="text-muted-foreground text-sm pb-4"
>
CarbonOS is the operating system for manufacturing
@@ -49,7 +49,7 @@ export default function GetStarted() {
<Button
{...fade}
- transition={{ duration: 1, delay: 2.4 }}
+ transition={{ duration: 1.2, ease: "easeInOut", delay: 1.5 }}
size="lg"
asChild
>
diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
index 5f825110dd..b16ae30391 100644
--- a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx
@@ -10,6 +10,7 @@ import {
ReceiptHeader,
getReceipt,
getReceiptFiles,
+ getReceiptLineTracking,
getReceiptLines,
} from "~/modules/inventory";
import type { Handle } from "~/utils/handle";
@@ -30,9 +31,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { receiptId } = params;
if (!receiptId) throw new Error("Could not find receiptId");
- const [receipt, receiptLines] = await Promise.all([
+ const [receipt, receiptLines, receiptLineTracking] = await Promise.all([
getReceipt(serviceRole, receiptId),
getReceiptLines(serviceRole, receiptId),
+ getReceiptLineTracking(serviceRole, receiptId),
]);
if (receipt.error) {
@@ -55,6 +57,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return defer({
receipt: receipt.data,
receiptLines: receiptLines.data ?? [],
+ receiptLineTracking: receiptLineTracking.data ?? [],
receiptFiles: getReceiptFiles(serviceRole, companyId, receiptLineIds) ?? [],
});
}
diff --git a/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx b/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx
index 167b1a8775..c678112c9a 100644
--- a/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx
+++ b/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx
@@ -57,6 +57,30 @@ export async function action({ request, context }: ActionFunctionArgs) {
const serialNumber = formData.get("serialNumber") as string;
const index = Number(formData.get("index"));
+ // Check if serial number already exists for this item
+ const { data: existingSerial, error: queryError } = await client
+ .from("serialNumber")
+ .select("id, receiptLineTracking(id)")
+ .eq("number", serialNumber)
+ .eq("itemId", itemId)
+ .neq("receiptLineTracking.receiptLineId", receiptLineId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (queryError) {
+ return json({ error: "Failed to check serial number" }, { status: 500 });
+ }
+
+ if (
+ Array.isArray(existingSerial?.receiptLineTracking) &&
+ existingSerial?.receiptLineTracking?.length > 0
+ ) {
+ return json(
+ { error: "Serial number already exists for this item" },
+ { status: 400 }
+ );
+ }
+
// Use a transaction to ensure data consistency
const { error } = await client.rpc("update_receipt_line_serial_tracking", {
p_receipt_line_id: receiptLineId,
@@ -67,6 +91,13 @@ export async function action({ request, context }: ActionFunctionArgs) {
if (error) {
console.error(error);
+ // Check if error is due to unique constraint violation
+ if (error.message?.includes("duplicate key value")) {
+ return json(
+ { error: "Serial number already exists for this item" },
+ { status: 400 }
+ );
+ }
return json({ error: "Failed to update tracking" }, { status: 500 });
}
}
diff --git a/apps/erp/app/routes/x+/receipt+/lines.update.tsx b/apps/erp/app/routes/x+/receipt+/lines.update.tsx
index 9de53dc647..9d3bd919f3 100644
--- a/apps/erp/app/routes/x+/receipt+/lines.update.tsx
+++ b/apps/erp/app/routes/x+/receipt+/lines.update.tsx
@@ -31,6 +31,14 @@ export async function action({ request }: ActionFunctionArgs) {
.in("id", ids as string[])
.eq("companyId", companyId);
+ if (field === "receivedQuantity") {
+ await client
+ .from("receiptLineTracking")
+ .delete()
+ .in("receiptLineId", ids as string[])
+ .gte("index", Number(value) - 1);
+ }
+
return json(update);
default:
return json({
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 1cb6d04147..55c96af62a 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -14101,10 +14101,10 @@ export default {
$ref: "#/parameters/rowFilter.purchaseInvoiceLines.taxAmount",
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLines.taxPercent",
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLines.totalAmount",
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLines.totalAmount",
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLines.taxPercent",
},
{
$ref: "#/parameters/rowFilter.purchaseInvoiceLines.thumbnailPath",
@@ -39604,10 +39604,10 @@ export default {
$ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxAmount",
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxPercent",
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.totalAmount",
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.totalAmount",
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxPercent",
},
{
$ref: "#/parameters/select",
@@ -39774,10 +39774,10 @@ export default {
$ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxAmount",
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxPercent",
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.totalAmount",
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.totalAmount",
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxPercent",
},
{
$ref: "#/parameters/preferReturn",
@@ -39898,10 +39898,10 @@ export default {
$ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxAmount",
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxPercent",
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.totalAmount",
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.totalAmount",
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxPercent",
},
{
$ref: "#/parameters/body.purchaseInvoiceLine",
@@ -41436,6 +41436,101 @@ export default {
tags: ["(rpc) groups_query"],
},
},
+ "/rpc/update_receipt_line_serial_tracking": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "p_receipt_line_id",
+ required: true,
+ type: "string",
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "p_receipt_id",
+ required: true,
+ type: "string",
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "p_serial_number",
+ required: true,
+ type: "string",
+ },
+ {
+ format: "integer",
+ in: "query",
+ name: "p_index",
+ required: true,
+ type: "integer",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) update_receipt_line_serial_tracking"],
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_index: {
+ format: "integer",
+ type: "integer",
+ },
+ p_receipt_id: {
+ format: "text",
+ type: "string",
+ },
+ p_receipt_line_id: {
+ format: "text",
+ type: "string",
+ },
+ p_serial_number: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: [
+ "p_receipt_line_id",
+ "p_receipt_id",
+ "p_serial_number",
+ "p_index",
+ ],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) update_receipt_line_serial_tracking"],
+ },
+ },
"/rpc/update_receipt_line_lot_tracking": {
get: {
parameters: [
@@ -49673,11 +49768,11 @@ export default {
format: "numeric",
type: "number",
},
- taxPercent: {
+ totalAmount: {
format: "numeric",
type: "number",
},
- totalAmount: {
+ taxPercent: {
format: "numeric",
type: "number",
},
@@ -61336,11 +61431,11 @@ export default {
format: "numeric",
type: "number",
},
- taxPercent: {
+ totalAmount: {
format: "numeric",
type: "number",
},
- totalAmount: {
+ taxPercent: {
format: "numeric",
type: "number",
},
@@ -70174,15 +70269,15 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.purchaseInvoiceLines.taxPercent": {
- name: "taxPercent",
+ "rowFilter.purchaseInvoiceLines.totalAmount": {
+ name: "totalAmount",
required: false,
format: "numeric",
in: "query",
type: "string",
},
- "rowFilter.purchaseInvoiceLines.totalAmount": {
- name: "totalAmount",
+ "rowFilter.purchaseInvoiceLines.taxPercent": {
+ name: "taxPercent",
required: false,
format: "numeric",
in: "query",
@@ -85505,15 +85600,15 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.purchaseInvoiceLine.taxPercent": {
- name: "taxPercent",
+ "rowFilter.purchaseInvoiceLine.totalAmount": {
+ name: "totalAmount",
required: false,
format: "numeric",
in: "query",
type: "string",
},
- "rowFilter.purchaseInvoiceLine.totalAmount": {
- name: "totalAmount",
+ "rowFilter.purchaseInvoiceLine.taxPercent": {
+ name: "taxPercent",
required: false,
format: "numeric",
in: "query",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 91c585266d..dab2251ab7 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -33531,25 +33531,15 @@ export type Database = {
};
Returns: undefined;
};
- update_receipt_line_serial_tracking:
- | {
- Args: {
- p_receipt_line_id: string;
- p_receipt_id: string;
- p_serial_number: string;
- p_index: number;
- };
- Returns: undefined;
- }
- | {
- Args: {
- p_receipt_line_id: string;
- p_receipt_id: string;
- p_serial_numbers: string[];
- p_quantity: number;
- };
- Returns: undefined;
- };
+ update_receipt_line_serial_tracking: {
+ Args: {
+ p_receipt_line_id: string;
+ p_receipt_id: string;
+ p_serial_number: string;
+ p_index: number;
+ };
+ Returns: undefined;
+ };
users_for_groups: {
Args: {
groups: string[];
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 91c585266d..dab2251ab7 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -33531,25 +33531,15 @@ export type Database = {
};
Returns: undefined;
};
- update_receipt_line_serial_tracking:
- | {
- Args: {
- p_receipt_line_id: string;
- p_receipt_id: string;
- p_serial_number: string;
- p_index: number;
- };
- Returns: undefined;
- }
- | {
- Args: {
- p_receipt_line_id: string;
- p_receipt_id: string;
- p_serial_numbers: string[];
- p_quantity: number;
- };
- Returns: undefined;
- };
+ update_receipt_line_serial_tracking: {
+ Args: {
+ p_receipt_line_id: string;
+ p_receipt_id: string;
+ p_serial_number: string;
+ p_index: number;
+ };
+ Returns: undefined;
+ };
users_for_groups: {
Args: {
groups: string[];
diff --git a/packages/database/supabase/migrations/20250128094053_traceability.sql b/packages/database/supabase/migrations/20250128094053_traceability.sql
index 1d6517812e..758a96e29d 100644
--- a/packages/database/supabase/migrations/20250128094053_traceability.sql
+++ b/packages/database/supabase/migrations/20250128094053_traceability.sql
@@ -348,45 +348,45 @@ DECLARE
v_serial_id TEXT;
BEGIN
-- First upsert the serial number
- INSERT INTO "serialNumber" ("id", "number", "itemId", "companyId", "supplierId")
- SELECT
- xid(),
- p_serial_number,
- rl."itemId",
- rl."companyId",
- r."supplierId"
- FROM "receiptLine" rl
- JOIN "receipt" r ON r.id = rl."receiptId"
- WHERE rl.id = p_receipt_line_id
- ON CONFLICT ("number", "itemId") DO UPDATE SET
- "supplierId" = EXCLUDED."supplierId"
- RETURNING id INTO v_serial_id;
+ INSERT INTO "serialNumber" ("id", "number", "itemId", "companyId", "supplierId")
+ SELECT
+ xid(),
+ p_serial_number,
+ rl."itemId",
+ rl."companyId",
+ r."supplierId"
+ FROM "receiptLine" rl
+ JOIN "receipt" r ON r.id = rl."receiptId"
+ WHERE rl.id = p_receipt_line_id
+ ON CONFLICT ("number", "itemId") DO UPDATE SET
+ "supplierId" = EXCLUDED."supplierId"
+ RETURNING id INTO v_serial_id;
-- Delete any existing tracking record for this index
DELETE FROM "receiptLineTracking"
WHERE "receiptLineId" = p_receipt_line_id
AND "index" = p_index;
- -- Insert the tracking record
- INSERT INTO "receiptLineTracking" (
- "receiptLineId",
- "receiptId",
- "itemId",
- "serialNumberId",
- "quantity",
- "index",
- "companyId"
- )
- SELECT
- p_receipt_line_id,
- p_receipt_id,
- rl."itemId",
- v_serial_id,
- 1,
- p_index,
- rl."companyId"
- FROM "receiptLine" rl
- JOIN "receipt" r ON r.id = rl."receiptId"
- WHERE rl.id = p_receipt_line_id;
+ -- Insert the tracking record
+ INSERT INTO "receiptLineTracking" (
+ "receiptLineId",
+ "receiptId",
+ "itemId",
+ "serialNumberId",
+ "quantity",
+ "index",
+ "companyId"
+ )
+ SELECT
+ p_receipt_line_id,
+ p_receipt_id,
+ rl."itemId",
+ v_serial_id,
+ 1,
+ p_index,
+ rl."companyId"
+ FROM "receiptLine" rl
+ JOIN "receipt" r ON r.id = rl."receiptId"
+ WHERE rl.id = p_receipt_line_id;
END;
$$ LANGUAGE plpgsql;
diff --git a/packages/react/src/Avatar.tsx b/packages/react/src/Avatar.tsx
index 3f66cd55c1..a7423bfbe1 100644
--- a/packages/react/src/Avatar.tsx
+++ b/packages/react/src/Avatar.tsx
@@ -20,7 +20,7 @@ import {
import { cn } from "./utils/cn";
export const avatarVariants = cva(
- "flex flex-shrink-0 overflow-hidden rounded-full items-center justify-center font-semibold",
+ "flex flex-shrink-0 overflow-hidden rounded-full items-center justify-center font-semibold transition-transform duration-200 ease-in-out",
{
variants: {
size: {
@@ -33,7 +33,7 @@ export const avatarVariants = cva(
xxs: "h-4 w-4 text-[8px] tracking-tight",
},
isGroup: {
- true: "ring-2 ring-background",
+ true: "ring-2 ring-background hover:-translate-y-1 hover:scale-110",
},
},
defaultVariants: {
@@ -166,7 +166,7 @@ const AvatarGroup = forwardRef<HTMLDivElement, AvatarGroupProps>(
<div
ref={ref}
className={cn(
- "flex items-center justify-start -space-x-2",
+ "flex items-center justify-start -space-x-2 [&>*:not(:first-of-type)]:mask-radial",
className
)}
{...props}