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: link shipments and invoices

Brad Barbinf43973e6a37c
diff --git a/apps/erp/app/modules/documents/documents.models.ts b/apps/erp/app/modules/documents/documents.models.ts
index 4472bb130d..67192c2f4f 100644
--- a/apps/erp/app/modules/documents/documents.models.ts
+++ b/apps/erp/app/modules/documents/documents.models.ts
@@ -10,6 +10,7 @@ export const documentSourceTypes = [
"Supplier Quote",
"Sales Order",
"Sales Invoice",
+ "Shipment",
...methodItemType,
] as const;
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 47dcf3299b..6c11d677dc 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -400,6 +400,20 @@ export async function getShipmentFiles(
};
}
+export async function getShipmentRelatedItems(
+ client: SupabaseClient<Database>,
+ shipmentId: string
+) {
+ const invoices = await client
+ .from("salesInvoice")
+ .select("*")
+ .eq("shipmentId", shipmentId);
+
+ return {
+ invoices: invoices.data ?? [],
+ };
+}
+
export async function getShipmentTracking(
client: SupabaseClient<Database>,
shipmentId: string,
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
index f5ce8ffcad..5aac2f8683 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
@@ -1,26 +1,38 @@
import {
Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
HStack,
Heading,
SplitButton,
useDisclosure,
} from "@carbon/react";
-import { Link, useParams } from "@remix-run/react";
+import { Await, Link, useNavigate, useParams } from "@remix-run/react";
import {
- LuCheckCheck,
LuBarcode,
+ LuCheckCheck,
+ LuChevronDown,
+ LuCirclePlus,
+ LuCreditCard,
LuQrCode,
LuShoppingCart,
} from "react-icons/lu";
import { usePermissions, useRouteData } from "~/hooks";
import type { ItemTracking, Shipment, ShipmentLine } from "~/modules/inventory";
+import type { TrackedEntityAttributes } from "@carbon/utils";
+import { labelSizes } from "@carbon/utils";
+import { Suspense } from "react";
+import { RiProgress8Line } from "react-icons/ri";
+import type { SalesInvoice } from "~/modules/invoicing/types";
+import SalesInvoiceStatus from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceStatus";
import { path } from "~/utils/path";
import ShipmentPostModal from "./ShipmentPostModal";
-import { RiProgress8Line } from "react-icons/ri";
-import type { TrackedEntityAttributes } from "@carbon/utils";
import ShipmentStatus from "./ShipmentStatus";
-import { labelSizes } from "@carbon/utils";
const ShipmentHeader = () => {
const { shipmentId } = useParams();
@@ -30,18 +42,23 @@ const ShipmentHeader = () => {
shipment: Shipment;
shipmentLines: ShipmentLine[];
shipmentLineTracking: ItemTracking[];
+ relatedItems?: Promise<{
+ invoices: SalesInvoice[];
+ }>;
}>(path.to.shipment(shipmentId));
if (!routeData?.shipment) throw new Error("Failed to load shipment");
const permissions = usePermissions();
const postModal = useDisclosure();
+ const navigate = useNavigate();
const canPost =
routeData.shipmentLines.length > 0 &&
routeData.shipmentLines.some((line) => (line.shippedQuantity ?? 0) !== 0);
const isPosted = routeData.shipment.status === "Posted";
+ const isInvoiced = routeData.shipment.invoiced;
const hasTrackingLabels = routeData.shipmentLineTracking.some(
(line) => "Split Entity ID" in (line.attributes as TrackedEntityAttributes)
);
@@ -65,6 +82,14 @@ const ShipmentHeader = () => {
}
};
+ const invoice = (shipment?: Shipment) => {
+ if (!shipment) return;
+ // Navigate to create invoice from shipment
+ navigate(
+ `${path.to.newSalesInvoice}?sourceDocument=Shipment&sourceDocumentId=${shipmentId}`
+ );
+ };
+
return (
<>
<div className="flex flex-shrink-0 items-center justify-between px-4 py-2 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)]">
@@ -112,6 +137,180 @@ const ShipmentHeader = () => {
routeData.shipment.sourceDocumentReadableId ?? undefined
}
/>
+
+ {permissions.can("view", "invoicing") && (
+ <>
+ {routeData?.shipment.sourceDocument === "Sales Order" && (
+ <Suspense
+ fallback={
+ <Button
+ leftIcon={<LuCreditCard />}
+ variant="secondary"
+ isLoading
+ >
+ Loading...
+ </Button>
+ }
+ >
+ <Await resolve={routeData?.relatedItems}>
+ {(relatedItems) => {
+ const invoices = relatedItems?.invoices || [];
+ return invoices.length > 0 ? (
+ invoices.length === 1 ? (
+ <Button
+ leftIcon={<LuCreditCard />}
+ variant={!isInvoiced ? "primary" : "secondary"}
+ isDisabled={!isPosted}
+ asChild
+ >
+ <Link to={path.to.salesInvoice(invoices[0].id!)}>
+ Invoice
+ </Link>
+ </Button>
+ ) : (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ leftIcon={<LuCreditCard />}
+ rightIcon={<LuChevronDown />}
+ variant={
+ !isInvoiced ? "primary" : "secondary"
+ }
+ >
+ Invoice
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ disabled={!isPosted}
+ onClick={() => {
+ invoice(routeData?.shipment);
+ }}
+ >
+ <DropdownMenuIcon icon={<LuCirclePlus />} />
+ New Invoice
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ {invoices.map((invoice) => (
+ <DropdownMenuItem key={invoice.id} asChild>
+ <Link
+ to={path.to.salesInvoice(invoice.id!)}
+ >
+ <DropdownMenuIcon
+ icon={<LuCreditCard />}
+ />
+ <HStack spacing={8}>
+ <span>{invoice.invoiceId}</span>
+ <SalesInvoiceStatus
+ status={invoice.status}
+ />
+ </HStack>
+ </Link>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+ ) : (
+ <Button
+ leftIcon={<LuCreditCard />}
+ variant={isPosted ? "primary" : "secondary"}
+ isDisabled={!isPosted}
+ onClick={() => {
+ invoice(routeData?.shipment);
+ }}
+ >
+ Invoice
+ </Button>
+ );
+ }}
+ </Await>
+ </Suspense>
+ )}
+ {routeData?.shipment.sourceDocument === "Sales Invoice" && (
+ <Suspense
+ fallback={
+ <Button
+ leftIcon={<LuCreditCard />}
+ variant="secondary"
+ isLoading
+ >
+ Loading...
+ </Button>
+ }
+ >
+ <Await resolve={routeData?.relatedItems}>
+ {(relatedItems) => {
+ const invoices = relatedItems?.invoices || [];
+
+ if (invoices.length === 0) {
+ return (
+ <Button
+ variant="secondary"
+ leftIcon={<LuCreditCard />}
+ asChild
+ >
+ <Link
+ to={path.to.salesInvoice(
+ routeData.shipment.sourceDocumentId!
+ )}
+ >
+ Invoice
+ </Link>
+ </Button>
+ );
+ } else if (invoices.length === 1) {
+ return (
+ <Button
+ variant="secondary"
+ leftIcon={<LuCreditCard />}
+ asChild
+ >
+ <Link to={path.to.salesInvoice(invoices[0].id!)}>
+ Invoice
+ </Link>
+ </Button>
+ );
+ } else {
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ leftIcon={<LuCreditCard />}
+ rightIcon={<LuChevronDown />}
+ variant="secondary"
+ >
+ Invoices
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {invoices.map((invoice) => (
+ <DropdownMenuItem key={invoice.id} asChild>
+ <Link
+ to={path.to.salesInvoice(invoice.id!)}
+ >
+ <DropdownMenuIcon
+ icon={<LuCreditCard />}
+ />
+ <HStack spacing={8}>
+ <span>{invoice.invoiceId}</span>
+ <SalesInvoiceStatus
+ status={invoice.status}
+ />
+ </HStack>
+ </Link>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+ }
+ }}
+ </Await>
+ </Suspense>
+ )}
+ </>
+ )}
<Button
variant={canPost && !isPosted ? "primary" : "secondary"}
onClick={postModal.onOpen}
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx
index 16cc8f51af..4b74e0606c 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx
@@ -142,6 +142,21 @@ const ShipmentsTable = memo(({ data, count }: ShipmentsTableProps) => {
icon: <LuClock />,
},
},
+ {
+ accessorKey: "invoiced",
+ header: "Invoiced",
+ cell: (item) => <Checkbox isChecked={item.getValue<boolean>()} />,
+ meta: {
+ filter: {
+ type: "static",
+ options: [
+ { value: "true", label: "Yes" },
+ { value: "false", label: "No" },
+ ],
+ },
+ icon: <LuCheck />,
+ },
+ },
{
id: "postedBy",
header: "Posted By",
@@ -201,23 +216,6 @@ const ShipmentsTable = memo(({ data, count }: ShipmentsTableProps) => {
icon: <LuUser />,
},
},
-
- {
- accessorKey: "invoiced",
- header: "Invoiced",
- cell: (item) => <Checkbox isChecked={item.getValue<boolean>()} />,
- meta: {
- filter: {
- type: "static",
- options: [
- { value: "true", label: "Yes" },
- { value: "false", label: "No" },
- ],
- },
- pluralHeader: "Invoiced Statuses",
- icon: <LuCheck />,
- },
- },
{
accessorKey: "externalDocumentId",
header: "External Ref.",
diff --git a/apps/erp/app/modules/invoicing/invoicing.models.ts b/apps/erp/app/modules/invoicing/invoicing.models.ts
index fcb50cd1d6..b5fb2eea22 100644
--- a/apps/erp/app/modules/invoicing/invoicing.models.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.models.ts
@@ -165,6 +165,19 @@ export const salesInvoiceValidator = z.object({
exchangeRateUpdatedAt: zfd.text(z.string().optional()),
});
+export const salesInvoicePostValidator = z
+ .object({
+ notification: z.enum(["Email", "None"]).optional(),
+ customerContact: zfd.text(z.string().optional()),
+ })
+ .refine(
+ (data) => (data.notification === "Email" ? data.customerContact : true),
+ {
+ message: "Customer contact is required for email",
+ path: ["customerContact"], // path of error
+ }
+ );
+
export const salesInvoiceShipmentValidator = z.object({
id: z.string(),
locationId: zfd.text(z.string().optional()),
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index 5b7cdf20cf..408722ba45 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -57,6 +57,22 @@ export async function createSalesInvoiceFromSalesOrder(
});
}
+export async function createSalesInvoiceFromShipment(
+ client: SupabaseClient<Database>,
+ shipmentId: string,
+ companyId: string,
+ userId: string
+) {
+ return client.functions.invoke<{ id: string }>("convert", {
+ body: {
+ type: "shipmentToSalesInvoice",
+ id: shipmentId,
+ companyId,
+ userId,
+ },
+ });
+}
+
export async function deletePurchaseInvoice(
client: SupabaseClient<Database>,
purchaseInvoiceId: string
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
index f8903879b7..bd7208cd56 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
@@ -3,6 +3,7 @@ import {
Button,
DropdownMenu,
DropdownMenuContent,
+ DropdownMenuIcon,
DropdownMenuItem,
DropdownMenuTrigger,
HStack,
@@ -10,13 +11,12 @@ import {
IconButton,
useDisclosure,
} from "@carbon/react";
-import { Link, useParams } from "@remix-run/react";
+import { Link, useFetcher, useParams } from "@remix-run/react";
import { useEffect, useState } from "react";
import { flushSync } from "react-dom";
import {
LuCheckCheck,
LuChevronDown,
- LuHandCoins,
LuPanelLeft,
LuPanelRight,
LuTruck,
@@ -24,15 +24,17 @@ import {
import { RiProgress8Line } from "react-icons/ri";
import { usePanels } from "~/components/Layout/Panels";
import { usePermissions, useRouteData } from "~/hooks";
+import { ShipmentStatus } from "~/modules/inventory/ui/Shipments";
import type { SalesInvoice, SalesInvoiceLine } from "~/modules/invoicing";
+import type { action } from "~/routes/x+/sales-invoice+/$invoiceId.post";
import { path } from "~/utils/path";
import SalesInvoicePostModal from "./SalesInvoicePostModal";
import SalesInvoiceStatus from "./SalesInvoiceStatus";
-
const SalesInvoiceHeader = () => {
const permissions = usePermissions();
const { invoiceId } = useParams();
const postingModal = useDisclosure();
+ const postFetcher = useFetcher<typeof action>();
const { carbon } = useCarbon();
const [linesNotAssociatedWithSO, setLinesNotAssociatedWithSO] = useState<
@@ -58,12 +60,12 @@ const SalesInvoiceHeader = () => {
const [relatedDocs, setRelatedDocs] = useState<{
salesOrders: { id: string; readableId: string }[];
- shipments: { id: string; readableId: string }[];
+ shipments: { id: string; readableId: string; status: string }[];
}>({ salesOrders: [], shipments: [] });
// Load related documents on mount
useEffect(() => {
- async function loadRelatedDocs() {
+ async function getRelatedDocuments() {
if (!carbon || !salesInvoice.opportunityId) return;
const [salesOrdersResult, shipmentsResult] = await Promise.all([
@@ -73,7 +75,7 @@ const SalesInvoiceHeader = () => {
.eq("opportunityId", salesInvoice.opportunityId),
carbon
.from("shipment")
- .select("id, shipmentId")
+ .select("id, shipmentId, status")
.eq("opportunityId", salesInvoice.opportunityId),
]);
@@ -91,12 +93,13 @@ const SalesInvoiceHeader = () => {
shipmentsResult.data?.map((r) => ({
id: r.id,
readableId: r.shipmentId,
+ status: r.status,
})) ?? [],
});
}
- loadRelatedDocs();
- }, [carbon, salesInvoice.opportunityId]);
+ getRelatedDocuments();
+ }, [carbon, salesInvoice.opportunityId, salesInvoice.status]);
const showPostModal = async () => {
// check if there are any lines that are not associated with a PO
@@ -157,9 +160,15 @@ const SalesInvoiceHeader = () => {
</Button>
)}
- {relatedDocs.shipments.length === 1 && (
+ {(relatedDocs.shipments.length === 1 ||
+ routeData?.salesInvoice.shipmentId) && (
<Button variant="secondary" leftIcon={<LuTruck />} asChild>
- <Link to={path.to.shipment(relatedDocs.shipments[0].id)}>
+ <Link
+ to={path.to.shipment(
+ routeData?.salesInvoice.shipmentId ??
+ relatedDocs.shipments[0].id
+ )}
+ >
Shipment
</Link>
</Button>
@@ -184,28 +193,35 @@ const SalesInvoiceHeader = () => {
</DropdownMenu>
)}
- {relatedDocs.shipments.length > 1 && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="secondary"
- leftIcon={<LuHandCoins />}
- rightIcon={<LuChevronDown />}
- >
- Shipments
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- {relatedDocs.shipments.map((shipment) => (
- <DropdownMenuItem key={shipment.id} asChild>
- <Link to={path.to.shipment(shipment.id)}>
- {shipment.readableId}
- </Link>
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- )}
+ {relatedDocs.shipments.length > 1 &&
+ !routeData.salesInvoice.shipmentId && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="secondary"
+ leftIcon={<LuTruck />}
+ rightIcon={<LuChevronDown />}
+ >
+ Shipments
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ {relatedDocs.shipments.map((shipment) => (
+ <DropdownMenuItem key={shipment.id} asChild>
+ <Link to={path.to.shipment(shipment.id)}>
+ <DropdownMenuIcon icon={<LuTruck />} />
+ <HStack spacing={8}>
+ <span>{shipment.readableId}</span>
+ <ShipmentStatus
+ status={shipment.status as "Posted"}
+ />
+ </HStack>
+ </Link>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
<Button
leftIcon={<LuCheckCheck />}
variant={
@@ -236,9 +252,12 @@ const SalesInvoiceHeader = () => {
{postingModal.isOpen && (
<SalesInvoicePostModal
invoiceId={invoiceId}
+ customerId={salesInvoice.invoiceCustomerId}
+ customerContactId={salesInvoice.invoiceCustomerContactId}
isOpen={postingModal.isOpen}
onClose={postingModal.onClose}
linesToShip={linesNotAssociatedWithSO}
+ fetcher={postFetcher}
/>
)}
</>
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsx
index 9e33a80248..203b089a19 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsx
@@ -1,9 +1,11 @@
+import { ValidatedForm } from "@carbon/form";
import {
Button,
HStack,
Modal,
ModalBody,
ModalContent,
+ ModalDescription,
ModalFooter,
ModalHeader,
ModalTitle,
@@ -17,12 +19,15 @@ import {
VStack,
} from "@carbon/react";
-import { useFetcher } from "@remix-run/react";
-import { useEffect } from "react";
-import type { action } from "~/routes/x+/sales-invoice+/$invoiceId.post";
+import type { FetcherWithComponents } from "@remix-run/react";
+import { useEffect, useState } from "react";
+import { CustomerContact, SelectControlled } from "~/components/Form";
+import { useIntegrations } from "~/hooks/useIntegrations";
import { path } from "~/utils/path";
+import { salesInvoicePostValidator } from "../../invoicing.models";
type SalesInvoicePostModalProps = {
+ fetcher: FetcherWithComponents<{ success: boolean; message: string }>;
isOpen: boolean;
onClose: () => void;
invoiceId: string;
@@ -32,17 +37,26 @@ type SalesInvoicePostModalProps = {
description: string | null;
quantity: number;
}[];
+ customerId: string | null;
+ customerContactId: string | null;
};
const SalesInvoicePostModal = ({
+ fetcher,
isOpen,
onClose,
invoiceId,
linesToShip,
+ customerId,
+ customerContactId,
}: SalesInvoicePostModalProps) => {
const hasLinesToShip = linesToShip.length > 0;
+ const integrations = useIntegrations();
+ const canEmail = integrations.has("resend");
- const fetcher = useFetcher<typeof action>();
+ const [notificationType, setNotificationType] = useState(
+ canEmail ? "Email" : "None"
+ );
useEffect(() => {
if (fetcher.data?.success) {
@@ -61,55 +75,95 @@ const SalesInvoicePostModal = ({
}}
>
<ModalContent>
- <ModalHeader>
- <ModalTitle>Post Invoice</ModalTitle>
- </ModalHeader>
- <ModalBody>
- {hasLinesToShip ? (
- <div className="gap-4 w-full flex flex-col">
- <p>
- Are you sure you want to post this invoice? A shipment will be
- automatically created and posted for:
- </p>
- <Table>
- <Thead>
- <Tr>
- <Th>Item</Th>
- <Th className="text-right">Quantity</Th>
- </Tr>
- </Thead>
- <Tbody>
- {linesToShip.map((line) => (
- <Tr key={line.itemId} className="text-sm">
- <Td>
- <VStack spacing={0}>
- <span>{line.itemReadableId}</span>
- {line.description && (
- <span className="text-xs text-muted-foreground">
- {line.description}
- </span>
- )}
- </VStack>
- </Td>
- <Td className="text-right">{line.quantity}</Td>
- </Tr>
- ))}
- </Tbody>
- </Table>
- </div>
- ) : (
- <p>Are you sure you want to post this invoice?</p>
- )}
- </ModalBody>
- <ModalFooter>
- <HStack>
- <Button variant="secondary" onClick={onClose}>
- Cancel
- </Button>
- <fetcher.Form
- method="post"
- action={path.to.salesInvoicePost(invoiceId)}
- >
+ <ValidatedForm
+ method="post"
+ validator={salesInvoicePostValidator}
+ action={path.to.salesInvoicePost(invoiceId)}
+ defaultValues={{
+ notification: notificationType as "Email" | "None",
+ customerContact: customerContactId ?? undefined,
+ }}
+ fetcher={fetcher}
+ >
+ <ModalHeader>
+ <ModalTitle>Post Invoice</ModalTitle>
+ <ModalDescription>
+ {hasLinesToShip ? (
+ <>
+ A shipment will be automatically created and posted for the
+ items below.
+ </>
+ ) : (
+ <>Are you sure you want to post this invoice?</>
+ )}
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={4}>
+ {hasLinesToShip && (
+ <div className="w-full">
+ <Table>
+ <Thead>
+ <Tr>
+ <Th>Item</Th>
+ <Th className="text-right">Quantity</Th>
+ </Tr>
+ </Thead>
+ <Tbody>
+ {linesToShip.map((line) => (
+ <Tr key={line.itemId} className="text-sm">
+ <Td>
+ <VStack spacing={0}>
+ <span>{line.itemReadableId}</span>
+ {line.description && (
+ <span className="text-xs text-muted-foreground">
+ {line.description}
+ </span>
+ )}
+ </VStack>
+ </Td>
+ <Td className="text-right">{line.quantity}</Td>
+ </Tr>
+ ))}
+ </Tbody>
+ </Table>
+ </div>
+ )}
+
+ {canEmail && (
+ <SelectControlled
+ label="Send Via"
+ name="notification"
+ options={[
+ {
+ label: "None",
+ value: "None",
+ },
+ {
+ label: "Email",
+ value: "Email",
+ },
+ ]}
+ value={notificationType}
+ onChange={(t) => {
+ if (t) setNotificationType(t.value);
+ }}
+ />
+ )}
+
+ {notificationType === "Email" && (
+ <CustomerContact
+ name="customerContact"
+ customer={customerId ?? undefined}
+ />
+ )}
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
<Button
isDisabled={fetcher.state !== "idle"}
isLoading={fetcher.state !== "idle"}
@@ -117,9 +171,9 @@ const SalesInvoicePostModal = ({
>
{hasLinesToShip ? "Post and Ship Invoice" : "Post Invoice"}
</Button>
- </fetcher.Form>
- </HStack>
- </ModalFooter>
+ </HStack>
+ </ModalFooter>
+ </ValidatedForm>
</ModalContent>
</Modal>
);
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsx
index 4879a34d25..2df6d287ec 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsx
@@ -204,7 +204,7 @@ const SalesInvoiceProperties = () => {
>
<InputControlled
name="customerReference"
- label="Customer Ref. Number"
+ label="Customer PO"
value={routeData?.salesInvoice?.customerReference ?? ""}
size="sm"
inline
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx
index 3a151f45a4..cca31133c3 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx
@@ -111,7 +111,7 @@ const SalesInvoicesTable = memo(({ data, count }: SalesInvoicesTableProps) => {
},
{
accessorKey: "customerReference",
- header: "Customer Ref.",
+ header: "Customer PO",
cell: (item) => item.getValue(),
meta: {
icon: <LuQrCode />,
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 5afcc1f494..918e325a58 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -86,6 +86,7 @@ export async function convertQuoteToOrder(
id: string;
selectedLines: z.infer<typeof selectedLinesValidator>;
companyId: string;
+ purchaseOrderNumber?: string;
userId: string;
digitalQuoteAcceptedBy?: string;
digitalQuoteAcceptedByEmail?: string;
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteForm.tsx
index 9f506f7efe..90fa35c024 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteForm.tsx
@@ -129,7 +129,7 @@ const QuoteForm = ({ initialValues }: QuoteFormProps) => {
label="Customer"
onChange={onCustomerChange}
/>
- <Input name="customerReference" label="Customer Ref. Number" />
+ <Input name="customerReference" label="Customer RFQ" />
<CustomerLocation
name="customerLocationId"
label="Customer Location"
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteProperties.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteProperties.tsx
index 68cba22676..cf2d68f7b6 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteProperties.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteProperties.tsx
@@ -198,7 +198,7 @@ const QuoteProperties = () => {
>
<InputControlled
name="customerReference"
- label="Customer Ref. Number"
+ label="Customer RFQ"
value={routeData?.quote?.customerReference ?? ""}
size="sm"
inline
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx
index cd4a8a1743..cc281cc247 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx
@@ -10,6 +10,7 @@ import {
DrawerTitle,
Heading,
HStack,
+ Input,
Label,
NumberField,
NumberInput,
@@ -82,6 +83,7 @@ const QuoteToOrderDrawer = ({
const [selectedLines, setSelectedLines] = useState<
Record<string, SelectedLine>
>({});
+ const [poNumber, setPoNumber] = useState<string>("");
const { carbon } = useCarbon();
const { quoteId } = useParams();
@@ -115,6 +117,12 @@ const QuoteToOrderDrawer = ({
const file = acceptedFiles[0];
if (file) {
upload([file]);
+
+ // Extract PO number from filename if it's a PDF
+ if (file.name.toLowerCase().endsWith(".pdf") && poNumber === "") {
+ const extractedPoNumber = file.name.replace(/\.pdf$/i, "");
+ setPoNumber(extractedPoNumber);
+ }
}
const purchaseOrderDocumentPath = getPath(file);
@@ -161,6 +169,7 @@ const QuoteToOrderDrawer = ({
toast.error("Failed to remove purchase order");
} else {
setPurchaseOrder(null);
+ setPoNumber("");
toast.success("Purchase order removed successfully");
}
setUploading(false);
@@ -204,19 +213,31 @@ const QuoteToOrderDrawer = ({
)}
<LuUpload className="mx-auto mt-4 h-12 w-12 text-muted-foreground" />
</div>
- {purchaseOrder ? (
- <Button
- className="w-full"
- leftIcon={<LuTrash />}
- size="lg"
- isDisabled={uploading}
- isLoading={uploading}
- variant="secondary"
- onClick={removePurchaseOrder}
- >
- Remove
- </Button>
- ) : (
+
+ <VStack spacing={2} className="w-full">
+ <Label htmlFor="poNumber">Purchase Order Number</Label>
+ <Input
+ id="poNumber"
+ value={poNumber}
+ onChange={(e) => setPoNumber(e.target.value)}
+ placeholder="Enter PO number"
+ />
+ {purchaseOrder && (
+ <Button
+ className="w-full"
+ leftIcon={<LuTrash />}
+ size="lg"
+ isDisabled={uploading}
+ isLoading={uploading}
+ variant="secondary"
+ onClick={removePurchaseOrder}
+ >
+ Remove
+ </Button>
+ )}
+ </VStack>
+
+ {!purchaseOrder && (
<Button
className="w-full"
leftIcon={<LuBan />}
@@ -268,7 +289,7 @@ const QuoteToOrderDrawer = ({
case 2:
return (
<VStack spacing={4}>
- <CustomerDetailsForm />
+ <CustomerDetailsForm poNumber={poNumber} />
<PaymentDetailsForm />
<ShippingDetailsForm />
</VStack>
@@ -327,6 +348,7 @@ const QuoteToOrderDrawer = ({
name="selectedLines"
value={JSON.stringify(selectedLines)}
/>
+ <input type="hidden" name="poNumber" value={poNumber} />
</Form>
)}
</DrawerFooter>
@@ -806,7 +828,7 @@ function PaymentDetailsForm() {
);
}
-function CustomerDetailsForm() {
+function CustomerDetailsForm({ poNumber }: { poNumber: string }) {
const [isExpanded, setIsExpanded] = useState(true);
const { quoteId } = useParams();
if (!quoteId) throw new Error("Could not find quoteId");
@@ -841,9 +863,15 @@ function CustomerDetailsForm() {
</Td>
</Tr>
<Tr>
- <Td className="w-1/2">Customer Ref:</Td>
+ <Td className="w-1/2">Customer RFQ</Td>
<Td>{quoteData?.quote.customerReference}</Td>
</Tr>
+ {poNumber && (
+ <Tr>
+ <Td className="w-1/2">Customer PO</Td>
+ <Td>{poNumber}</Td>
+ </Tr>
+ )}
</Tbody>
</Table>
)}
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx
index 1c19e2ad9e..00e3a9ef77 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx
@@ -139,7 +139,7 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {
},
{
accessorKey: "customerReference",
- header: "Customer Reference",
+ header: "Customer RFQ",
cell: (item) => item.getValue(),
meta: {
icon: <LuQrCode />,
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
index d585fc1bca..e995af3191 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
@@ -186,7 +186,7 @@ const SalesOrderHeader = () => {
const statusFetcher = useFetcher<typeof statusAction>();
const confirmFetcher = useFetcher<typeof confirmAction>();
- const { ship, invoice } = useSalesOrder();
+ const { ship } = useSalesOrder();
const salesOrderToJobsModal = useDisclosure();
const confirmDisclosure = useDisclosure();
@@ -450,7 +450,7 @@ const SalesOrderHeader = () => {
Ship
</Button>
)}
- {invoices?.length > 0 ? (
+ {invoices?.length > 0 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
@@ -464,24 +464,10 @@ const SalesOrderHeader = () => {
: "secondary"
}
>
- Invoice
+ Invoices
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
- <DropdownMenuItem
- disabled={
- !["To Invoice", "To Ship and Invoice"].includes(
- routeData?.salesOrder?.status ?? ""
- )
- }
- onClick={() => {
- invoice(routeData?.salesOrder);
- }}
- >
- <DropdownMenuIcon icon={<LuCirclePlus />} />
- New Invoice
- </DropdownMenuItem>
- <DropdownMenuSeparator />
{invoices.map((invoice) => (
<DropdownMenuItem key={invoice.id} asChild>
<Link to={path.to.salesInvoice(invoice.id!)}>
@@ -497,27 +483,6 @@ const SalesOrderHeader = () => {
))}
</DropdownMenuContent>
</DropdownMenu>
- ) : (
- <Button
- leftIcon={<LuCreditCard />}
- isDisabled={
- !["To Invoice", "To Ship and Invoice"].includes(
- routeData?.salesOrder?.status ?? ""
- )
- }
- variant={
- ["To Invoice", "To Ship and Invoice"].includes(
- routeData?.salesOrder?.status ?? ""
- )
- ? "primary"
- : "secondary"
- }
- onClick={() => {
- invoice(routeData?.salesOrder);
- }}
- >
- Invoice
- </Button>
)}
</>
);
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderProperties.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderProperties.tsx
index ec982bd225..4cf39b4157 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderProperties.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderProperties.tsx
@@ -204,7 +204,7 @@ const SalesOrderProperties = () => {
>
<InputControlled
name="customerReference"
- label="Customer Ref. Number"
+ label="Customer PO"
value={routeData?.salesOrder?.customerReference ?? ""}
size="sm"
inline
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
index ab8be68132..a626c6a5b1 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
@@ -254,7 +254,7 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {
},
{
accessorKey: "customerReference",
- header: "Customer Ref.",
+ header: "Customer PO",
cell: (item) => item.getValue(),
meta: {
icon: <LuQrCode />,
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/useSalesOrder.ts b/apps/erp/app/modules/sales/ui/SalesOrder/useSalesOrder.ts
index 2217a4bcf6..2a4f4990b3 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/useSalesOrder.ts
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/useSalesOrder.ts
@@ -11,13 +11,13 @@ export const useSalesOrder = () => {
[navigate]
);
- const invoice = useCallback(
- (salesOrder: SalesOrder) =>
- navigate(
- `${path.to.newSalesInvoice}?sourceDocument=Sales Order&sourceDocumentId=${salesOrder.id}`
- ),
- [navigate]
- );
+ // const invoice = useCallback(
+ // (salesOrder: SalesOrder) =>
+ // navigate(
+ // `${path.to.newSalesInvoice}?sourceDocument=Sales Order&sourceDocumentId=${salesOrder.id}`
+ // ),
+ // [navigate]
+ // );
const ship = useCallback(
(salesOrder: SalesOrder) =>
@@ -29,7 +29,7 @@ export const useSalesOrder = () => {
return {
edit,
- invoice,
+ // invoice,
ship,
};
};
diff --git a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx
index 4eb6f20694..558f8235e0 100644
--- a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQForm.tsx
@@ -78,7 +78,7 @@ const SalesRFQForm = ({ initialValues }: SalesRFQFormProps) => {
setCustomer(newValue?.value as string | undefined)
}
/>
- <Input name="customerReference" label="Customer Ref. Number" />
+ <Input name="customerReference" label="Customer RFQ" />
<CustomerLocation
name="customerLocationId"
label="Customer Location"
diff --git a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx
index bbcd2b529f..ca0c8b1fc4 100644
--- a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx
@@ -185,7 +185,7 @@ const SalesRFQProperties = () => {
>
<InputControlled
name="customerReference"
- label="Customer Ref. Number"
+ label="Customer RFQ"
value={routeData?.rfqSummary?.customerReference ?? ""}
size="sm"
inline
diff --git a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx
index a2b197ae3f..4e454bdf36 100644
--- a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx
@@ -104,7 +104,7 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {
},
{
accessorKey: "customerReference",
- header: "Customer Reference",
+ header: "Customer RFQ",
cell: (item) => item.getValue(),
meta: {
icon: <LuQrCode />,
diff --git a/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx b/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx
index 191ffc1836..34a045f02d 100644
--- a/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx
+++ b/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx
@@ -67,6 +67,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
const selectedLines = parseResult.data;
+ // Extract purchase order number from PDF filename if available
+ let purchaseOrderNumber = "";
+ if (file instanceof File && file.name.toLowerCase().endsWith(".pdf")) {
+ purchaseOrderNumber = file.name.replace(/\.pdf$/i, "");
+ }
+
const [convert] = await Promise.all([
convertQuoteToOrder(serviceRole, {
id: quote.data.id,
@@ -75,6 +81,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
selectedLines,
digitalQuoteAcceptedBy,
digitalQuoteAcceptedByEmail,
+ purchaseOrderNumber,
}),
]);
diff --git a/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx
index 351dcdeedc..ed55902e1f 100644
--- a/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx
@@ -177,6 +177,118 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const headers = new Headers({ "Content-Type": "application/pdf" });
return new Response(body, { status: 200, headers });
}
+ case "Sales Invoice": {
+ const salesInvoice = await client
+ .from("salesInvoice")
+ .select("*, salesInvoiceShipment(*)")
+ .eq("id", shipment.data.sourceDocumentId ?? "")
+ .single();
+
+ if (salesInvoice.error) {
+ console.error(salesInvoice.error);
+ throw new Error("Failed to load sales invoice");
+ }
+
+ const [
+ customer,
+ customerLocation,
+ paymentTerm,
+ shippingMethod,
+ shipmentTracking,
+ ] = await Promise.all([
+ client
+ .from("customer")
+ .select("*")
+ .eq("id", salesInvoice.data?.customerId ?? "")
+ .single(),
+ getCustomerLocation(client, salesInvoice.data?.locationId ?? ""),
+ getPaymentTerm(client, salesInvoice.data?.paymentTermId ?? ""),
+ getShippingMethod(
+ client,
+ shipment.data.shippingMethodId ??
+ salesInvoice.data?.salesInvoiceShipment?.shippingMethodId ??
+ ""
+ ),
+ getShipmentTracking(client, shipment.data.id, companyId),
+ ]);
+
+ if (customer.error) {
+ console.error(customer.error);
+ throw new Error("Failed to load customer");
+ }
+
+ const thumbnailPaths = shipmentLines.data?.reduce<
+ Record<string, string | null>
+ >((acc, line) => {
+ if (line.thumbnailPath) {
+ acc[line.id!] = line.thumbnailPath;
+ }
+ return acc;
+ }, {});
+
+ const thumbnails: Record<string, string | null> =
+ (thumbnailPaths
+ ? await Promise.all(
+ Object.entries(thumbnailPaths).map(([id, path]) => {
+ if (!path) {
+ return null;
+ }
+ return getBase64ImageFromSupabase(client, path).then(
+ (data) => ({
+ id,
+ data,
+ })
+ );
+ })
+ )
+ : []
+ )?.reduce<Record<string, string | null>>((acc, thumbnail) => {
+ if (thumbnail) {
+ acc[thumbnail.id] = thumbnail.data;
+ }
+ return acc;
+ }, {}) ?? {};
+
+ const stream = await renderToStream(
+ <PackingSlipPDF
+ company={company.data}
+ customer={customer.data}
+ locale={locale}
+ meta={{
+ author: "CarbonOS",
+ keywords: "packing slip",
+ subject: "Packing Slip",
+ }}
+ customerReference={salesInvoice.data?.customerReference ?? undefined}
+ sourceDocument="Sales Invoice"
+ sourceDocumentId={salesInvoice.data?.invoiceId ?? undefined}
+ shipment={shipment.data}
+ shipmentLines={shipmentLines.data ?? []}
+ // @ts-ignore
+ shippingAddress={customerLocation.data?.address}
+ terms={(terms?.data?.salesTerms ?? {}) as JSONContent}
+ paymentTerm={paymentTerm.data ?? { id: "", name: "" }}
+ shippingMethod={shippingMethod.data ?? { id: "", name: "" }}
+ trackedEntities={shipmentTracking.data ?? []}
+ title="Packing Slip"
+ thumbnails={thumbnails}
+ />
+ );
+
+ const body: Buffer = await new Promise((resolve, reject) => {
+ const buffers: Uint8Array[] = [];
+ stream.on("data", (data) => {
+ buffers.push(data);
+ });
+ stream.on("end", () => {
+ resolve(Buffer.concat(buffers));
+ });
+ stream.on("error", reject);
+ });
+
+ const headers = new Headers({ "Content-Type": "application/pdf" });
+ return new Response(body, { status: 200, headers });
+ }
case "Purchase Order": {
const [purchaseOrder, purchaseOrderDelivery] = await Promise.all([
getPurchaseOrder(client, shipment.data.sourceDocumentId),
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
index db1fcabda7..b9402a61ae 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
@@ -12,6 +12,7 @@ import { renderAsync } from "@react-email/components";
import { tasks } from "@trigger.dev/sdk/v3";
import { redirect, type ActionFunctionArgs } from "@vercel/remix";
import { parseAcceptLanguage } from "intl-parse-accept-language";
+import { getPaymentTermsList } from "~/modules/accounting";
import { upsertDocument } from "~/modules/documents";
import {
finalizePurchaseOrder,
@@ -167,6 +168,7 @@ export async function action(args: ActionFunctionArgs) {
purchaseOrder,
purchaseOrderLines,
purchaseOrderLocations,
+ paymentTerms,
buyer,
] = await Promise.all([
getCompany(serviceRole, companyId),
@@ -174,6 +176,7 @@ export async function action(args: ActionFunctionArgs) {
getPurchaseOrder(serviceRole, orderId),
getPurchaseOrderLines(serviceRole, orderId),
getPurchaseOrderLocations(serviceRole, orderId),
+ getPaymentTermsList(serviceRole, companyId),
getUser(serviceRole, userId),
]);
@@ -185,6 +188,7 @@ export async function action(args: ActionFunctionArgs) {
throw new Error("Failed to get purchase order");
if (!purchaseOrderLocations.data)
throw new Error("Failed to get purchase order locations");
+ if (!paymentTerms.data) throw new Error("Failed to get payment terms");
const emailTemplate = PurchaseOrderEmail({
company: company.data,
@@ -202,6 +206,7 @@ export async function action(args: ActionFunctionArgs) {
firstName: buyer.data.firstName,
lastName: buyer.data.lastName,
},
+ paymentTerms: paymentTerms.data,
});
const html = await renderAsync(emailTemplate);
@@ -210,7 +215,7 @@ export async function action(args: ActionFunctionArgs) {
await tasks.trigger<typeof sendEmailResendTask>("send-email-resend", {
to: [buyer.data.email, supplier.data.contact.email],
from: buyer.data.email,
- subject: `${purchaseOrder.data.purchaseOrderId} from ${company.data.name}`,
+ subject: `Purchase Order ${purchaseOrder.data.purchaseOrderId} from ${company.data.name}`,
html,
text,
attachments: [
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
index c846948074..ace52492e0 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
@@ -26,6 +26,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const formData = await request.formData();
const selectedLinesRaw = formData.get("selectedLines") ?? "{}";
+ const poNumber = (formData.get("poNumber") ?? "") as string;
if (typeof selectedLinesRaw !== "string") {
throw redirect(
@@ -51,6 +52,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const serviceRole = getCarbonServiceRole();
const convert = await convertQuoteToOrder(serviceRole, {
id: quoteId,
+ purchaseOrderNumber: poNumber ?? "",
companyId,
userId,
selectedLines,
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx
index 67da594e0b..8b892be900 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx
@@ -111,6 +111,7 @@ export default function EditSalesInvoiceLineRoute() {
id: salesInvoiceLine?.id ?? undefined,
invoiceId: salesInvoiceLine?.invoiceId ?? "",
invoiceLineType: (salesInvoiceLine?.invoiceLineType ?? "Part") as "Part",
+ methodType: (salesInvoiceLine?.methodType ?? "Pick") as "Pick",
itemId: salesInvoiceLine?.itemId ?? "",
itemReadableId: salesInvoiceLine?.itemReadableId ?? "",
accountNumber: salesInvoiceLine?.accountNumber ?? "",
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
index 17fb4f9400..ba28253c9d 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
@@ -1,11 +1,12 @@
import { assertIsPost, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { SalesInvoiceEmail } from "@carbon/documents/email";
-import { validationError, validator } from "@carbon/form";
+import { validator } from "@carbon/form";
import { renderAsync } from "@react-email/components";
import { tasks } from "@trigger.dev/sdk/v3";
import { type ActionFunctionArgs } from "@vercel/remix";
import { parseAcceptLanguage } from "intl-parse-accept-language";
+import { getPaymentTermsList } from "~/modules/accounting";
import { upsertDocument } from "~/modules/documents";
import {
getSalesInvoice,
@@ -32,7 +33,12 @@ export async function action(args: ActionFunctionArgs) {
});
const { invoiceId } = params;
- if (!invoiceId) throw new Error("Could not find invoiceId");
+ if (!invoiceId) {
+ return {
+ success: false,
+ message: "Could not find invoiceId",
+ };
+ }
let file: ArrayBuffer;
let fileName: string;
@@ -51,8 +57,8 @@ export async function action(args: ActionFunctionArgs) {
};
}
- // Call the edge function to post the invoice
const serviceRole = getCarbonServiceRole();
+
try {
const postSalesInvoice = await serviceRole.functions.invoke(
"post-sales-invoice",
@@ -66,7 +72,6 @@ export async function action(args: ActionFunctionArgs) {
);
if (postSalesInvoice.error) {
- // Revert to Draft status if posting fails
await client
.from("salesInvoice")
.update({
@@ -80,7 +85,6 @@ export async function action(args: ActionFunctionArgs) {
};
}
} catch (err) {
- // Revert to Draft status if an exception occurs
await client
.from("salesInvoice")
.update({
@@ -117,9 +121,17 @@ export async function action(args: ActionFunctionArgs) {
});
try {
- const pdf = await pdfLoader(args);
- if (pdf.headers.get("content-type") !== "application/pdf")
- throw new Error("Failed to generate PDF");
+ const pdf = await pdfLoader({
+ ...args,
+ params: { ...args.params, id: invoiceId },
+ });
+
+ if (pdf.headers.get("content-type") !== "application/pdf") {
+ return {
+ success: false,
+ message: "Failed to generate PDF",
+ };
+ }
file = await pdf.arrayBuffer();
fileName = stripSpecialCharacters(
@@ -175,7 +187,10 @@ export async function action(args: ActionFunctionArgs) {
);
if (validation.error) {
- return validationError(validation.error);
+ return {
+ success: false,
+ message: "Invalid notification type",
+ };
}
const { notification, customerContact } = validation.data;
@@ -183,7 +198,12 @@ export async function action(args: ActionFunctionArgs) {
switch (notification) {
case "Email":
try {
- if (!customerContact) throw new Error("Customer contact is required");
+ if (!customerContact) {
+ return {
+ success: false,
+ message: "Customer contact is required",
+ };
+ }
const [
company,
@@ -193,6 +213,7 @@ export async function action(args: ActionFunctionArgs) {
salesInvoiceLocations,
salesInvoiceShipment,
seller,
+ paymentTerms,
] = await Promise.all([
getCompany(serviceRole, companyId),
getCustomerContact(serviceRole, customerContact),
@@ -201,15 +222,51 @@ export async function action(args: ActionFunctionArgs) {
getSalesInvoiceCustomerDetails(serviceRole, invoiceId),
getSalesInvoiceShipment(serviceRole, invoiceId),
getUser(serviceRole, userId),
+ getPaymentTermsList(serviceRole, companyId),
]);
- if (!customer?.data?.contact)
- throw new Error("Failed to get customer contact");
- if (!company.data) throw new Error("Failed to get company");
- if (!seller.data) throw new Error("Failed to get user");
- if (!salesInvoice.data) throw new Error("Failed to get sales invoice");
- if (!salesInvoiceLocations.data)
- throw new Error("Failed to get sales invoice locations");
+ if (!customer?.data?.contact) {
+ return {
+ success: false,
+ message: "Failed to get customer contact",
+ };
+ }
+ if (!company.data) {
+ return {
+ success: false,
+ message: "Failed to get company",
+ };
+ }
+ if (!seller.data) {
+ return {
+ success: false,
+ message: "Failed to get user",
+ };
+ }
+ if (!salesInvoice.data) {
+ return {
+ success: false,
+ message: "Failed to get sales invoice",
+ };
+ }
+ if (!salesInvoiceLocations.data) {
+ return {
+ success: false,
+ message: "Failed to get sales invoice locations",
+ };
+ }
+ if (!salesInvoiceShipment.data) {
+ return {
+ success: false,
+ message: "Failed to get sales invoice shipment",
+ };
+ }
+ if (!paymentTerms.data) {
+ return {
+ success: false,
+ message: "Failed to get payment terms",
+ };
+ }
const emailTemplate = SalesInvoiceEmail({
company: company.data,
@@ -228,6 +285,7 @@ export async function action(args: ActionFunctionArgs) {
firstName: seller.data.firstName,
lastName: seller.data.lastName,
},
+ paymentTerms: paymentTerms.data,
});
const html = await renderAsync(emailTemplate);
@@ -236,7 +294,7 @@ export async function action(args: ActionFunctionArgs) {
await tasks.trigger<typeof sendEmailResendTask>("send-email-resend", {
to: [seller.data.email, customer.data.contact.email],
from: seller.data.email,
- subject: `${salesInvoice.data.invoiceId} from ${company.data.name}`,
+ subject: `Invoice ${salesInvoice.data.invoiceId} from ${company.data.name}`,
html,
text,
attachments: [
@@ -253,7 +311,6 @@ export async function action(args: ActionFunctionArgs) {
message: "Failed to send email",
};
}
-
break;
case undefined:
case "None":
diff --git a/apps/erp/app/routes/x+/sales-invoice+/new.tsx b/apps/erp/app/routes/x+/sales-invoice+/new.tsx
index 6cd716178d..1cd3669a14 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/new.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/new.tsx
@@ -9,6 +9,7 @@ import { redirect } from "@vercel/remix";
import { useUrlParams, useUser } from "~/hooks";
import {
createSalesInvoiceFromSalesOrder,
+ createSalesInvoiceFromShipment,
salesInvoiceValidator,
upsertSalesInvoice,
} from "~/modules/invoicing";
@@ -59,6 +60,27 @@ export async function loader({ request }: LoaderFunctionArgs) {
throw redirect(path.to.salesInvoice(result.data?.id!));
+ case "Shipment":
+ if (!sourceDocumentId) throw new Error("Missing sourceDocumentId");
+ result = await createSalesInvoiceFromShipment(
+ getCarbonServiceRole(),
+ sourceDocumentId,
+ companyId,
+ userId
+ );
+
+ if (result.error || !result?.data) {
+ throw redirect(
+ request.headers.get("Referer") ?? path.to.shipment(sourceDocumentId),
+ await flash(
+ request,
+ error(result.error, "Failed to create sales invoice")
+ )
+ );
+ }
+
+ throw redirect(path.to.salesInvoice(result.data?.id!));
+
default:
return null;
}
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
index 1841831e1f..c3ac4f7d90 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
@@ -7,6 +7,7 @@ import { renderAsync } from "@react-email/components";
import { tasks } from "@trigger.dev/sdk/v3";
import { json, type ActionFunctionArgs } from "@vercel/remix";
import { parseAcceptLanguage } from "intl-parse-accept-language";
+import { getPaymentTermsList } from "~/modules/accounting";
import { upsertDocument } from "~/modules/documents";
import {
getCustomerContact,
@@ -163,6 +164,7 @@ export async function action(args: ActionFunctionArgs) {
salesOrderLines,
salesOrderLocations,
seller,
+ paymentTerms,
] = await Promise.all([
getCompany(serviceRole, companyId),
getCustomerContact(serviceRole, customerContact),
@@ -170,6 +172,7 @@ export async function action(args: ActionFunctionArgs) {
getSalesOrderLines(serviceRole, orderId),
getSalesOrderCustomerDetails(serviceRole, orderId),
getUser(serviceRole, userId),
+ getPaymentTermsList(serviceRole, companyId),
]);
if (!customer?.data?.contact) {
@@ -203,6 +206,13 @@ export async function action(args: ActionFunctionArgs) {
});
}
+ if (!paymentTerms.data) {
+ return json({
+ success: false,
+ message: "Failed to get payment terms",
+ });
+ }
+
const emailTemplate = SalesOrderEmail({
company: company.data,
locale: locales?.[0] ?? "en-US",
@@ -219,6 +229,7 @@ export async function action(args: ActionFunctionArgs) {
firstName: seller.data.firstName,
lastName: seller.data.lastName,
},
+ paymentTerms: paymentTerms.data,
});
const html = await renderAsync(emailTemplate);
@@ -227,7 +238,7 @@ export async function action(args: ActionFunctionArgs) {
await tasks.trigger<typeof sendEmailResendTask>("send-email-resend", {
to: [seller.data.email, customer.data.contact.email],
from: seller.data.email,
- subject: `${salesOrder.data.salesOrderId} from ${company.data.name}`,
+ subject: `Order ${salesOrder.data.salesOrderId} from ${company.data.name}`,
html,
text,
attachments: [
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
index e44a2996e9..d63002ec4f 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
@@ -3,7 +3,10 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
+import { upsertDocument } from "~/modules/documents";
+import { loader as pdfLoader } from "~/routes/file+/shipment+/$id[.]pdf";
import { path } from "~/utils/path";
+import { stripSpecialCharacters } from "~/utils/string";
export async function action({ request, params }: ActionFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
@@ -31,7 +34,79 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
try {
- const serviceRole = await getCarbonServiceRole();
+ const serviceRole = getCarbonServiceRole();
+
+ // Get shipment details to check if it's related to a sales order
+ const { data: shipment } = await serviceRole
+ .from("shipment")
+ .select("sourceDocument, sourceDocumentId, shipmentId")
+ .eq("id", shipmentId)
+ .single();
+
+ // If the shipment is related to a sales order, save the packing slip PDF
+ if (
+ shipment?.sourceDocument === "Sales Order" &&
+ shipment?.sourceDocumentId
+ ) {
+ try {
+ // Get the opportunity ID from the sales order
+ const { data: salesOrder } = await serviceRole
+ .from("salesOrder")
+ .select("opportunityId")
+ .eq("id", shipment.sourceDocumentId)
+ .single();
+
+ if (salesOrder?.opportunityId) {
+ // Generate the packing slip PDF
+ const pdfArgs = {
+ request,
+ params: { id: shipmentId },
+ context: {},
+ };
+
+ const pdf = await pdfLoader(pdfArgs);
+
+ if (pdf.headers.get("content-type") === "application/pdf") {
+ const file = await pdf.arrayBuffer();
+ const fileName = stripSpecialCharacters(
+ `${shipment.shipmentId} - ${new Date()
+ .toISOString()
+ .slice(0, -5)}.pdf`
+ );
+
+ const documentFilePath = `${companyId}/opportunity/${salesOrder.opportunityId}/${fileName}`;
+
+ // Upload the PDF to storage
+ const documentFileUpload = await serviceRole.storage
+ .from("private")
+ .upload(documentFilePath, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ contentType: "application/pdf",
+ upsert: true,
+ });
+
+ if (!documentFileUpload.error) {
+ // Create document record
+ await upsertDocument(serviceRole, {
+ path: documentFilePath,
+ name: fileName,
+ size: Math.round(file.byteLength / 1024),
+ sourceDocument: "Shipment",
+ sourceDocumentId: shipmentId,
+ readGroups: [userId],
+ writeGroups: [userId],
+ createdBy: userId,
+ companyId,
+ });
+ }
+ }
+ }
+ } catch (err) {
+ // Continue with posting even if PDF generation fails
+ console.error("Failed to generate packing slip PDF:", err);
+ }
+ }
+
const postShipment = await serviceRole.functions.invoke("post-shipment", {
body: {
shipmentId: shipmentId,
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx
index 6cced3c800..0dcfab937e 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx
@@ -1,4 +1,4 @@
-import { error, getCarbonServiceRole } from "@carbon/auth";
+import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { VStack } from "@carbon/react";
@@ -8,8 +8,9 @@ import { defer, redirect } from "@vercel/remix";
import { PanelProvider } from "~/components/Layout";
import {
getShipment,
- getShipmentTracking,
getShipmentLines,
+ getShipmentRelatedItems,
+ getShipmentTracking,
} from "~/modules/inventory";
import ShipmentHeader from "~/modules/inventory/ui/Shipments/ShipmentHeader";
import type { Handle } from "~/utils/handle";
@@ -21,19 +22,18 @@ export const handle: Handle = {
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { companyId } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "inventory",
+ bypassRls: true,
});
- const serviceRole = await getCarbonServiceRole();
-
const { shipmentId } = params;
if (!shipmentId) throw new Error("Could not find shipmentId");
const [shipment, shipmentLines, shipmentLineTracking] = await Promise.all([
- getShipment(serviceRole, shipmentId),
- getShipmentLines(serviceRole, shipmentId),
- getShipmentTracking(serviceRole, shipmentId, companyId),
+ getShipment(client, shipmentId),
+ getShipmentLines(client, shipmentId),
+ getShipmentTracking(client, shipmentId, companyId),
]);
if (shipment.error) {
@@ -51,6 +51,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
shipment: shipment.data,
shipmentLines: shipmentLines.data ?? [],
shipmentLineTracking: shipmentLineTracking.data ?? [],
+ relatedItems: getShipmentRelatedItems(client, shipmentId),
});
}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index cd12067571..37d0c21ec1 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -10113,6 +10113,99 @@ export default {
tags: ["department"],
},
},
+ "/salesInvoiceLocations": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.customerName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.customerAddressLine1",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.customerAddressLine2",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.customerCity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.customerStateProvince",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.customerPostalCode",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.customerCountryCode",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.customerCountryName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.invoiceCustomerName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.invoiceAddressLine1",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.invoiceAddressLine2",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.invoiceCity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.invoiceStateProvince",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.invoicePostalCode",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.invoiceCountryCode",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLocations.invoiceCountryName",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/salesInvoiceLocations",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["salesInvoiceLocations"],
+ },
+ },
"/itemLedger": {
get: {
parameters: [
@@ -11802,6 +11895,9 @@ export default {
{
$ref: "#/parameters/rowFilter.salesInvoice.opportunityId",
},
+ {
+ $ref: "#/parameters/rowFilter.salesInvoice.shipmentId",
+ },
{
$ref: "#/parameters/rowFilter.salesInvoice.assignee",
},
@@ -11960,6 +12056,9 @@ export default {
{
$ref: "#/parameters/rowFilter.salesInvoice.opportunityId",
},
+ {
+ $ref: "#/parameters/rowFilter.salesInvoice.shipmentId",
+ },
{
$ref: "#/parameters/rowFilter.salesInvoice.assignee",
},
@@ -12072,6 +12171,9 @@ export default {
{
$ref: "#/parameters/rowFilter.salesInvoice.opportunityId",
},
+ {
+ $ref: "#/parameters/rowFilter.salesInvoice.shipmentId",
+ },
{
$ref: "#/parameters/rowFilter.salesInvoice.assignee",
},
@@ -25428,6 +25530,9 @@ export default {
{
$ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxPercent",
},
+ {
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.jobOperationId",
+ },
{
$ref: "#/parameters/select",
},
@@ -25598,6 +25703,9 @@ export default {
{
$ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxPercent",
},
+ {
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.jobOperationId",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -25722,6 +25830,9 @@ export default {
{
$ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxPercent",
},
+ {
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.jobOperationId",
+ },
{
$ref: "#/parameters/body.purchaseInvoiceLine",
},
@@ -35337,6 +35448,9 @@ export default {
{
$ref: "#/parameters/rowFilter.salesInvoices.opportunityId",
},
+ {
+ $ref: "#/parameters/rowFilter.salesInvoices.shipmentId",
+ },
{
$ref: "#/parameters/rowFilter.salesInvoices.assignee",
},
@@ -57845,7 +57959,7 @@ export default {
properties: {
id: {
description:
- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string",
},
@@ -57894,7 +58008,7 @@ export default {
},
supplierLocationId: {
description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string",
},
@@ -59397,6 +59511,84 @@ export default {
},
type: "object",
},
+ salesInvoiceLocations: {
+ properties: {
+ id: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ customerName: {
+ format: "text",
+ type: "string",
+ },
+ customerAddressLine1: {
+ format: "text",
+ type: "string",
+ },
+ customerAddressLine2: {
+ format: "text",
+ type: "string",
+ },
+ customerCity: {
+ format: "text",
+ type: "string",
+ },
+ customerStateProvince: {
+ format: "text",
+ type: "string",
+ },
+ customerPostalCode: {
+ format: "text",
+ type: "string",
+ },
+ customerCountryCode: {
+ description:
+ "Note:\nThis is a Foreign Key to `country.alpha2`.<fk table='country' column='alpha2'/>",
+ format: "text",
+ type: "string",
+ },
+ customerCountryName: {
+ format: "text",
+ type: "string",
+ },
+ invoiceCustomerName: {
+ format: "text",
+ type: "string",
+ },
+ invoiceAddressLine1: {
+ format: "text",
+ type: "string",
+ },
+ invoiceAddressLine2: {
+ format: "text",
+ type: "string",
+ },
+ invoiceCity: {
+ format: "text",
+ type: "string",
+ },
+ invoiceStateProvince: {
+ format: "text",
+ type: "string",
+ },
+ invoicePostalCode: {
+ format: "text",
+ type: "string",
+ },
+ invoiceCountryCode: {
+ description:
+ "Note:\nThis is a Foreign Key to `country.alpha2`.<fk table='country' column='alpha2'/>",
+ format: "text",
+ type: "string",
+ },
+ invoiceCountryName: {
+ format: "text",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
itemLedger: {
required: [
"id",
@@ -60183,7 +60375,7 @@ export default {
},
invoiceCustomerContactId: {
description:
- "Note:\nThis is a Foreign Key to `contact.id`.<fk table='contact' column='id'/>",
+ "Note:\nThis is a Foreign Key to `customerContact.id`.<fk table='customerContact' column='id'/>",
format: "text",
type: "string",
},
@@ -60261,6 +60453,12 @@ export default {
format: "text",
type: "string",
},
+ shipmentId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shipment.id`.<fk table='shipment' column='id'/>",
+ format: "text",
+ type: "string",
+ },
assignee: {
format: "text",
type: "string",
@@ -66345,6 +66543,12 @@ export default {
format: "numeric",
type: "number",
},
+ jobOperationId: {
+ description:
+ "Note:\nThis is a Foreign Key to `jobOperation.id`.<fk table='jobOperation' column='id'/>",
+ format: "text",
+ type: "string",
+ },
},
type: "object",
},
@@ -71015,7 +71219,7 @@ export default {
},
invoiceCustomerContactId: {
description:
- "Note:\nThis is a Foreign Key to `contact.id`.<fk table='contact' column='id'/>",
+ "Note:\nThis is a Foreign Key to `customerContact.id`.<fk table='customerContact' column='id'/>",
format: "text",
type: "string",
},
@@ -71087,6 +71291,12 @@ export default {
format: "text",
type: "string",
},
+ shipmentId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shipment.id`.<fk table='shipment' column='id'/>",
+ format: "text",
+ type: "string",
+ },
assignee: {
format: "text",
type: "string",
@@ -83674,6 +83884,117 @@ export default {
in: "query",
type: "string",
},
+ "body.salesInvoiceLocations": {
+ name: "salesInvoiceLocations",
+ description: "salesInvoiceLocations",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/salesInvoiceLocations",
+ },
+ },
+ "rowFilter.salesInvoiceLocations.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.customerName": {
+ name: "customerName",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.customerAddressLine1": {
+ name: "customerAddressLine1",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.customerAddressLine2": {
+ name: "customerAddressLine2",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.customerCity": {
+ name: "customerCity",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.customerStateProvince": {
+ name: "customerStateProvince",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.customerPostalCode": {
+ name: "customerPostalCode",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.customerCountryCode": {
+ name: "customerCountryCode",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.customerCountryName": {
+ name: "customerCountryName",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.invoiceCustomerName": {
+ name: "invoiceCustomerName",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.invoiceAddressLine1": {
+ name: "invoiceAddressLine1",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.invoiceAddressLine2": {
+ name: "invoiceAddressLine2",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.invoiceCity": {
+ name: "invoiceCity",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.invoiceStateProvince": {
+ name: "invoiceStateProvince",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.invoicePostalCode": {
+ name: "invoicePostalCode",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.invoiceCountryCode": {
+ name: "invoiceCountryCode",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLocations.invoiceCountryName": {
+ name: "invoiceCountryName",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.itemLedger": {
name: "itemLedger",
description: "itemLedger",
@@ -84568,6 +84889,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.salesInvoice.shipmentId": {
+ name: "shipmentId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.salesInvoice.assignee": {
name: "assignee",
required: false,
@@ -91384,6 +91711,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.purchaseInvoiceLine.jobOperationId": {
+ name: "jobOperationId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.materialForm": {
name: "materialForm",
description: "materialForm",
@@ -96913,6 +97246,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.salesInvoices.shipmentId": {
+ name: "shipmentId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.salesInvoices.assignee": {
name: "assignee",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 7c2bd9296f..d65e7958e5 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -18010,7 +18010,6 @@ export type Database = {
invoiceSupplierContactId: string | null
invoiceSupplierId: string | null
invoiceSupplierLocationId: string | null
- jobOperationId: string | null
locationId: string | null
paymentTermId: string | null
postingDate: string | null
@@ -18045,7 +18044,6 @@ export type Database = {
invoiceSupplierContactId?: string | null
invoiceSupplierId?: string | null
invoiceSupplierLocationId?: string | null
- jobOperationId?: string | null
locationId?: string | null
paymentTermId?: string | null
postingDate?: string | null
@@ -18080,7 +18078,6 @@ export type Database = {
invoiceSupplierContactId?: string | null
invoiceSupplierId?: string | null
invoiceSupplierLocationId?: string | null
- jobOperationId?: string | null
locationId?: string | null
paymentTermId?: string | null
postingDate?: string | null
@@ -18258,27 +18255,6 @@ export type Database = {
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "purchaseInvoice_jobOperationId_fkey"
- columns: ["jobOperationId"]
- isOneToOne: false
- referencedRelation: "jobOperation"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "purchaseInvoice_jobOperationId_fkey"
- columns: ["jobOperationId"]
- isOneToOne: false
- referencedRelation: "jobOperationsWithDependencies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "purchaseInvoice_jobOperationId_fkey"
- columns: ["jobOperationId"]
- isOneToOne: false
- referencedRelation: "jobOperationsWithMakeMethods"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "purchaseInvoice_locationId_fkey"
columns: ["locationId"]
@@ -23347,6 +23323,7 @@ export type Database = {
opportunityId: string | null
paymentTermId: string | null
postingDate: string | null
+ shipmentId: string | null
status: Database["public"]["Enums"]["salesInvoiceStatus"]
subtotal: number
tags: string[] | null
@@ -23382,6 +23359,7 @@ export type Database = {
opportunityId?: string | null
paymentTermId?: string | null
postingDate?: string | null
+ shipmentId?: string | null
status?: Database["public"]["Enums"]["salesInvoiceStatus"]
subtotal?: number
tags?: string[] | null
@@ -23417,6 +23395,7 @@ export type Database = {
opportunityId?: string | null
paymentTermId?: string | null
postingDate?: string | null
+ shipmentId?: string | null
status?: Database["public"]["Enums"]["salesInvoiceStatus"]
subtotal?: number
tags?: string[] | null
@@ -23522,7 +23501,7 @@ export type Database = {
foreignKeyName: "salesInvoice_invoiceCustomerContactId_fkey"
columns: ["invoiceCustomerContactId"]
isOneToOne: false
- referencedRelation: "contact"
+ referencedRelation: "customerContact"
referencedColumns: ["id"]
},
{
@@ -23574,6 +23553,13 @@ export type Database = {
referencedRelation: "paymentTerm"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoice_shipmentId_fkey"
+ columns: ["shipmentId"]
+ isOneToOne: false
+ referencedRelation: "shipment"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoice_updatedBy_fkey"
columns: ["updatedBy"]
@@ -39212,14 +39198,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -39256,6 +39242,7 @@ export type Database = {
opportunityId: string | null
paymentTermId: string | null
postingDate: string | null
+ shipmentId: string | null
status: Database["public"]["Enums"]["salesInvoiceStatus"] | null
subtotal: number | null
tags: string[] | null
@@ -39362,7 +39349,7 @@ export type Database = {
foreignKeyName: "salesInvoice_invoiceCustomerContactId_fkey"
columns: ["invoiceCustomerContactId"]
isOneToOne: false
- referencedRelation: "contact"
+ referencedRelation: "customerContact"
referencedColumns: ["id"]
},
{
@@ -39414,6 +39401,13 @@ export type Database = {
referencedRelation: "paymentTerm"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoice_shipmentId_fkey"
+ columns: ["shipmentId"]
+ isOneToOne: false
+ referencedRelation: "shipment"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoice_updatedBy_fkey"
columns: ["updatedBy"]
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index 9b1486dc65..1d8feea012 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -35,6 +35,7 @@ const payloadValidator = z.discriminatedUnion("type", [
id: z.string(),
companyId: z.string(),
userId: z.string(),
+ purchaseOrderNumber: z.string().optional(),
selectedLines: z.record(
z.string(),
z.object({
@@ -57,6 +58,12 @@ const payloadValidator = z.discriminatedUnion("type", [
companyId: z.string(),
userId: z.string(),
}),
+ z.object({
+ type: z.literal("shipmentToSalesInvoice"),
+ id: z.string(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
z.object({
type: z.literal("supplierQuoteToPurchaseOrder"),
id: z.string(),
@@ -271,6 +278,7 @@ serve(async (req: Request) => {
case "quoteToSalesOrder": {
const {
selectedLines,
+ purchaseOrderNumber,
digitalQuoteAcceptedBy,
digitalQuoteAcceptedByEmail,
} = payload;
@@ -325,7 +333,7 @@ serve(async (req: Request) => {
customerId: quote.data.customerId,
customerContactId: quote.data.customerContactId,
customerLocationId: quote.data.customerLocationId,
- customerReference: quote.data.customerReference,
+ customerReference: purchaseOrderNumber ?? "",
locationId: quote.data.locationId,
salesPersonId: quote.data.salesPersonId ?? userId,
status: salesOrderStatus,
@@ -586,10 +594,6 @@ serve(async (req: Request) => {
if (!salesInvoice.id) throw new Error("Purchase invoice not created");
salesInvoiceId = salesInvoice.id;
- console.log({
- salesOrderShipment: salesOrderShipment.data,
- });
-
await trx
.insertInto("salesInvoiceShipment")
.values({
@@ -1005,6 +1009,196 @@ serve(async (req: Request) => {
);
break;
}
+ case "shipmentToSalesInvoice": {
+ const shipmentId = id;
+ const [shipment, shipmentLines] = await Promise.all([
+ client.from("shipment").select("*").eq("id", shipmentId).single(),
+ client.from("shipmentLine").select("*").eq("shipmentId", shipmentId),
+ ]);
+
+ if (shipmentLines.error) throw shipmentLines.error;
+
+ const quantitiesByLine = shipmentLines.data.reduce<
+ Record<string, number>
+ >((acc, line) => {
+ acc[line.lineId!] = line.shippedQuantity;
+ return acc;
+ }, {});
+
+ const salesOrderLineIds = Object.keys(quantitiesByLine);
+
+ if (
+ !shipment.data?.sourceDocumentId ||
+ shipment.data?.sourceDocument !== "Sales Order"
+ ) {
+ throw new Error("Shipment has no source document id");
+ }
+
+ const [
+ salesOrder,
+ salesOrderLines,
+ salesOrderPayment,
+ salesOrderShipment,
+ ] = await Promise.all([
+ client
+ .from("salesOrder")
+ .select("*")
+ .eq("id", shipment.data?.sourceDocumentId)
+ .single(),
+ client.from("salesOrderLine").select("*").in("id", salesOrderLineIds),
+ client
+ .from("salesOrderPayment")
+ .select("*")
+ .eq("id", shipment.data?.sourceDocumentId)
+ .single(),
+ client
+ .from("salesOrderShipment")
+ .select("*")
+ .eq("id", shipment.data?.sourceDocumentId)
+ .single(),
+ ]);
+
+ if (!salesOrder.data) throw new Error("Purchase order not found");
+ if (salesOrderLines.error)
+ throw new Error(salesOrderLines.error.message);
+ if (!salesOrderPayment.data)
+ throw new Error("Purchase order payment not found");
+ if (!salesOrderShipment.data)
+ throw new Error("Purchase order delivery not found");
+
+ const uninvoicedLines = salesOrderLines?.data?.reduce<
+ (typeof salesOrderLines)["data"]
+ >((acc, line) => {
+ if (line.id in quantitiesByLine && quantitiesByLine[line.id] > 0) {
+ acc.push({
+ ...line,
+ quantityToInvoice: quantitiesByLine[line.id],
+ });
+ }
+
+ return acc;
+ }, []);
+
+ const uninvoicedSubtotal = uninvoicedLines?.reduce((acc, line) => {
+ if (
+ line?.quantityToInvoice &&
+ line.unitPrice &&
+ line.quantityToInvoice > 0
+ ) {
+ acc += line.quantityToInvoice * line.unitPrice;
+ }
+
+ return acc;
+ }, 0);
+
+ let salesInvoiceId = "";
+
+ await db.transaction().execute(async (trx) => {
+ salesInvoiceId = await getNextSequence(
+ trx,
+ "salesInvoice",
+ companyId
+ );
+
+ const salesInvoice = await trx
+ .insertInto("salesInvoice")
+ .values({
+ invoiceId: salesInvoiceId!,
+ status: "Draft",
+ customerId: salesOrder.data.customerId,
+ customerReference: salesOrder.data.customerReference ?? "",
+ invoiceCustomerId: salesOrderPayment.data.invoiceCustomerId,
+ invoiceCustomerContactId:
+ salesOrderPayment.data.invoiceCustomerContactId,
+ invoiceCustomerLocationId:
+ salesOrderPayment.data.invoiceCustomerLocationId,
+ locationId: salesOrderShipment.data.locationId,
+ paymentTermId: salesOrderPayment.data.paymentTermId,
+ currencyCode: salesOrder.data.currencyCode ?? "USD",
+ dateIssued: new Date().toISOString().split("T")[0],
+ exchangeRate: salesOrder.data.exchangeRate ?? 1,
+ subtotal: uninvoicedSubtotal ?? 0,
+ opportunityId: salesOrder.data.opportunityId,
+ shipmentId: shipmentId,
+ totalDiscount: 0,
+ totalAmount: uninvoicedSubtotal ?? 0,
+ totalTax: 0,
+ balance: uninvoicedSubtotal ?? 0,
+ companyId,
+ createdBy: userId,
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ if (!salesInvoice.id) throw new Error("Purchase invoice not created");
+ salesInvoiceId = salesInvoice.id;
+
+ await trx
+ .insertInto("salesInvoiceShipment")
+ .values({
+ id: salesInvoiceId,
+ locationId: salesOrderShipment.data.locationId,
+ shippingCost: salesOrderShipment.data.shippingCost ?? 0,
+ shippingMethodId: salesOrderShipment.data.shippingMethodId,
+ shippingTermId: salesOrderShipment.data.shippingTermId,
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+
+ const salesInvoiceLines = uninvoicedLines?.reduce<
+ Database["public"]["Tables"]["salesInvoiceLine"]["Insert"][]
+ >((acc, line) => {
+ if (
+ line?.quantityToInvoice &&
+ line.quantityToInvoice > 0 &&
+ !line.invoicedComplete
+ ) {
+ acc.push({
+ invoiceId: salesInvoiceId,
+ invoiceLineType: line.salesOrderLineType,
+ salesOrderId: line.salesOrderId,
+ salesOrderLineId: line.id,
+ methodType: line.methodType,
+ itemId: line.itemId,
+ itemReadableId: line.itemReadableId,
+ locationId: line.locationId,
+ shelfId: line.shelfId,
+ accountNumber: line.accountNumber,
+ assetId: line.assetId,
+ description: line.description,
+ quantity: line.quantityToInvoice,
+ unitPrice: line.unitPrice ?? 0,
+ addOnCost: line.addOnCost ?? 0,
+ shippingCost: line.shippingCost ?? 0,
+ taxPercent: line.taxPercent ?? 0,
+ unitOfMeasureCode: line.unitOfMeasureCode ?? "EA",
+ exchangeRate: line.exchangeRate ?? 1,
+ companyId,
+ createdBy: userId,
+ });
+ }
+ return acc;
+ }, []);
+
+ if (salesInvoiceLines.length > 0) {
+ await trx
+ .insertInto("salesInvoiceLine")
+ .values(salesInvoiceLines)
+ .execute();
+ }
+ });
+
+ return new Response(
+ JSON.stringify({
+ id: salesInvoiceId,
+ }),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 201,
+ }
+ );
+ }
case "supplierQuoteToPurchaseOrder": {
const { selectedLines } = payload;
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 7c2bd9296f..d65e7958e5 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -18010,7 +18010,6 @@ export type Database = {
invoiceSupplierContactId: string | null
invoiceSupplierId: string | null
invoiceSupplierLocationId: string | null
- jobOperationId: string | null
locationId: string | null
paymentTermId: string | null
postingDate: string | null
@@ -18045,7 +18044,6 @@ export type Database = {
invoiceSupplierContactId?: string | null
invoiceSupplierId?: string | null
invoiceSupplierLocationId?: string | null
- jobOperationId?: string | null
locationId?: string | null
paymentTermId?: string | null
postingDate?: string | null
@@ -18080,7 +18078,6 @@ export type Database = {
invoiceSupplierContactId?: string | null
invoiceSupplierId?: string | null
invoiceSupplierLocationId?: string | null
- jobOperationId?: string | null
locationId?: string | null
paymentTermId?: string | null
postingDate?: string | null
@@ -18258,27 +18255,6 @@ export type Database = {
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "purchaseInvoice_jobOperationId_fkey"
- columns: ["jobOperationId"]
- isOneToOne: false
- referencedRelation: "jobOperation"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "purchaseInvoice_jobOperationId_fkey"
- columns: ["jobOperationId"]
- isOneToOne: false
- referencedRelation: "jobOperationsWithDependencies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "purchaseInvoice_jobOperationId_fkey"
- columns: ["jobOperationId"]
- isOneToOne: false
- referencedRelation: "jobOperationsWithMakeMethods"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "purchaseInvoice_locationId_fkey"
columns: ["locationId"]
@@ -23347,6 +23323,7 @@ export type Database = {
opportunityId: string | null
paymentTermId: string | null
postingDate: string | null
+ shipmentId: string | null
status: Database["public"]["Enums"]["salesInvoiceStatus"]
subtotal: number
tags: string[] | null
@@ -23382,6 +23359,7 @@ export type Database = {
opportunityId?: string | null
paymentTermId?: string | null
postingDate?: string | null
+ shipmentId?: string | null
status?: Database["public"]["Enums"]["salesInvoiceStatus"]
subtotal?: number
tags?: string[] | null
@@ -23417,6 +23395,7 @@ export type Database = {
opportunityId?: string | null
paymentTermId?: string | null
postingDate?: string | null
+ shipmentId?: string | null
status?: Database["public"]["Enums"]["salesInvoiceStatus"]
subtotal?: number
tags?: string[] | null
@@ -23522,7 +23501,7 @@ export type Database = {
foreignKeyName: "salesInvoice_invoiceCustomerContactId_fkey"
columns: ["invoiceCustomerContactId"]
isOneToOne: false
- referencedRelation: "contact"
+ referencedRelation: "customerContact"
referencedColumns: ["id"]
},
{
@@ -23574,6 +23553,13 @@ export type Database = {
referencedRelation: "paymentTerm"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoice_shipmentId_fkey"
+ columns: ["shipmentId"]
+ isOneToOne: false
+ referencedRelation: "shipment"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoice_updatedBy_fkey"
columns: ["updatedBy"]
@@ -39212,14 +39198,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -39256,6 +39242,7 @@ export type Database = {
opportunityId: string | null
paymentTermId: string | null
postingDate: string | null
+ shipmentId: string | null
status: Database["public"]["Enums"]["salesInvoiceStatus"] | null
subtotal: number | null
tags: string[] | null
@@ -39362,7 +39349,7 @@ export type Database = {
foreignKeyName: "salesInvoice_invoiceCustomerContactId_fkey"
columns: ["invoiceCustomerContactId"]
isOneToOne: false
- referencedRelation: "contact"
+ referencedRelation: "customerContact"
referencedColumns: ["id"]
},
{
@@ -39414,6 +39401,13 @@ export type Database = {
referencedRelation: "paymentTerm"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoice_shipmentId_fkey"
+ columns: ["shipmentId"]
+ isOneToOne: false
+ referencedRelation: "shipment"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoice_updatedBy_fkey"
columns: ["updatedBy"]
diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.ts
index e7d40f698d..2ff456f582 100644
--- a/packages/database/supabase/functions/post-sales-invoice/index.ts
+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts
@@ -39,6 +39,7 @@ serve(async (req: Request) => {
invoiceId,
userId,
});
+
const client = await getSupabaseServiceRole(
req.headers.get("Authorization"),
req.headers.get("carbon-key") ?? "",
@@ -677,6 +678,16 @@ serve(async (req: Request) => {
.execute();
}
+ if (salesInvoice.data.shipmentId) {
+ await trx
+ .updateTable("shipment")
+ .set({
+ invoiced: true,
+ })
+ .where("id", "=", salesInvoice.data.shipmentId)
+ .execute();
+ }
+
await trx
.updateTable("salesInvoice")
.set({
diff --git a/packages/database/supabase/migrations/20250507143421_sales-invoice.sql b/packages/database/supabase/migrations/20250507143421_sales-invoice.sql
index fca3e15d32..04a52ef2c1 100644
--- a/packages/database/supabase/migrations/20250507143421_sales-invoice.sql
+++ b/packages/database/supabase/migrations/20250507143421_sales-invoice.sql
@@ -46,6 +46,7 @@ CREATE TABLE "salesInvoice" (
"exchangeRate" NUMERIC NOT NULL DEFAULT 1,
"exchangeRateUpdatedAt" TIMESTAMP WITH TIME ZONE,
"opportunityId" TEXT,
+ "shipmentId" TEXT,
"assignee" TEXT,
"companyId" TEXT NOT NULL,
"customFields" JSONB NOT NULL DEFAULT '{}',
@@ -63,10 +64,11 @@ CREATE TABLE "salesInvoice" (
CONSTRAINT "salesInvoice_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "salesInvoice_invoiceCustomerId_fkey" FOREIGN KEY ("invoiceCustomerId") REFERENCES "customer"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "salesInvoice_invoiceCustomerLocationId_fkey" FOREIGN KEY ("invoiceCustomerLocationId") REFERENCES "customerLocation"("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "salesInvoice_invoiceCustomerContactId_fkey" FOREIGN KEY ("invoiceCustomerContactId") REFERENCES "contact"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "salesInvoice_invoiceCustomerContactId_fkey" FOREIGN KEY ("invoiceCustomerContactId") REFERENCES "customerContact"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "salesInvoice_paymentTermId_fkey" FOREIGN KEY ("paymentTermId") REFERENCES "paymentTerm"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "salesInvoice_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currencyCode"("code") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "salesInvoice_opportunityId_fkey" FOREIGN KEY ("opportunityId") REFERENCES "opportunity"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "salesInvoice_shipmentId_fkey" FOREIGN KEY ("shipmentId") REFERENCES "shipment"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "salesInvoice_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "salesInvoice_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,
CONSTRAINT "salesInvoice_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE
@@ -75,6 +77,47 @@ CREATE TABLE "salesInvoice" (
CREATE INDEX "salesInvoice_companyId_idx" ON "salesInvoice" ("companyId");
CREATE INDEX "salesInvoice_customerId_idx" ON "salesInvoice" ("customerId");
+
+CREATE POLICY "SELECT" ON "public"."salesInvoice"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('invoicing_view')
+ )::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."salesInvoice"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('invoicing_create')
+ )::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesInvoice"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('invoicing_update')
+ )::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."salesInvoice"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('invoicing_delete')
+ )::text[]
+ )
+);
+
CREATE TYPE "salesInvoiceLineType" AS ENUM (
'Comment',
'Part',
@@ -143,6 +186,46 @@ CREATE INDEX "salesInvoiceLine_invoiceId_idx" ON "salesInvoiceLine" ("invoiceId"
CREATE INDEX "salesInvoiceLine_itemId_idx" ON "salesInvoiceLine" ("itemId");
CREATE INDEX "salesInvoiceLine_locationId_idx" ON "salesInvoiceLine" ("locationId");
+CREATE POLICY "SELECT" ON "public"."salesInvoiceLine"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('invoicing_view')
+ )::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."salesInvoiceLine"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('invoicing_create')
+ )::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesInvoiceLine"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('invoicing_update')
+ )::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."salesInvoiceLine"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('invoicing_delete')
+ )::text[]
+ )
+);
+
CREATE TABLE "salesInvoiceShipment" (
"id" TEXT NOT NULL,
"shippingCost" NUMERIC NOT NULL DEFAULT 0,
@@ -165,6 +248,46 @@ CREATE TABLE "salesInvoiceShipment" (
CREATE INDEX "salesInvoiceShipment_companyId_idx" ON "salesInvoiceShipment" ("companyId");
+CREATE POLICY "SELECT" ON "public"."salesInvoiceShipment"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('invoicing_view')
+ )::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."salesInvoiceShipment"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('invoicing_create')
+ )::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesInvoiceShipment"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('invoicing_update')
+ )::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."salesInvoiceShipment"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('invoicing_delete')
+ )::text[]
+ )
+);
+
DROP VIEW IF EXISTS "salesInvoices";
CREATE OR REPLACE VIEW "salesInvoices" WITH(SECURITY_INVOKER=true) AS
SELECT
diff --git a/packages/documents/src/email/PurchaseOrderEmail.tsx b/packages/documents/src/email/PurchaseOrderEmail.tsx
index 4d95c0975d..fabaa00588 100644
--- a/packages/documents/src/email/PurchaseOrderEmail.tsx
+++ b/packages/documents/src/email/PurchaseOrderEmail.tsx
@@ -26,6 +26,7 @@ interface PurchaseOrderEmailProps extends Email {
purchaseOrder: Database["public"]["Views"]["purchaseOrders"]["Row"];
purchaseOrderLines: Database["public"]["Views"]["purchaseOrderLines"]["Row"][];
purchaseOrderLocations: Database["public"]["Views"]["purchaseOrderLocations"]["Row"];
+ paymentTerms: { id: string; name: string }[];
}
const PurchaseOrderEmail = ({
@@ -35,6 +36,7 @@ const PurchaseOrderEmail = ({
purchaseOrderLocations,
recipient,
sender,
+ paymentTerms,
}: PurchaseOrderEmailProps) => {
const {
deliveryName,
@@ -121,7 +123,7 @@ const PurchaseOrderEmail = ({
</Section>
<Section>
<Text className="text-left text-sm font-medium text-gray-900 my-9">
- {recipient.firstName ? `Hi ${recipient.firstName},` : "Hi,"}
+ {recipient.firstName ? `Hi ${recipient.firstName}, ` : "Hi, "}
please see the attached purchase order and let me know if you
have any questions.
</Text>
@@ -148,7 +150,13 @@ const PurchaseOrderEmail = ({
<Text className="text-gray-600 uppercase text-[10px]">
Payment Terms
</Text>
- <Text>{purchaseOrder.paymentTermName ?? "-"}</Text>
+ <Text>
+ {
+ paymentTerms?.find(
+ (term) => term.id === purchaseOrder.paymentTermId
+ )?.name
+ }
+ </Text>
</Column>
</Row>
<Row>
diff --git a/packages/documents/src/email/SalesInvoiceEmail.tsx b/packages/documents/src/email/SalesInvoiceEmail.tsx
new file mode 100644
index 0000000000..4ef5110504
--- /dev/null
+++ b/packages/documents/src/email/SalesInvoiceEmail.tsx
@@ -0,0 +1,287 @@
+import type { Database } from "@carbon/database";
+import { formatCityStatePostalCode } from "@carbon/utils";
+import {
+ Body,
+ Column,
+ Container,
+ Font,
+ Hr,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Row,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+import type { Email } from "../types";
+import {
+ getLineDescription,
+ getLineDescriptionDetails,
+ getLineTotal,
+ getTotal,
+} from "../utils/sales-invoice";
+import { getCurrencyFormatter } from "../utils/shared";
+
+interface SalesInvoiceEmailProps extends Email {
+ salesInvoice: Database["public"]["Views"]["salesInvoices"]["Row"];
+ salesInvoiceLines: Database["public"]["Views"]["salesInvoiceLines"]["Row"][];
+ salesInvoiceLocations: Database["public"]["Views"]["salesInvoiceLocations"]["Row"];
+ salesInvoiceShipment: Database["public"]["Tables"]["salesInvoiceShipment"]["Row"];
+ paymentTerms: { id: string; name: string }[];
+}
+
+const SalesInvoiceEmail = ({
+ company,
+ locale,
+ salesInvoice,
+ salesInvoiceLines,
+ salesInvoiceLocations,
+ salesInvoiceShipment,
+ recipient,
+ sender,
+ paymentTerms,
+}: SalesInvoiceEmailProps) => {
+ const {
+ invoiceCustomerName,
+ invoiceAddressLine1,
+ invoiceAddressLine2,
+ invoiceCity,
+ invoiceStateProvince,
+ invoicePostalCode,
+ invoiceCountryName,
+ } = salesInvoiceLocations;
+
+ const reSubject = `Re: ${salesInvoice.invoiceId} from ${company.name}`;
+
+ const currencyCode = salesInvoice.currencyCode ?? company.baseCurrencyCode;
+ const formatter = getCurrencyFormatter(currencyCode, locale);
+
+ return (
+ <Html>
+ <Preview>{`${salesInvoice.invoiceId} from ${company.name}`}</Preview>
+ <Tailwind>
+ <head>
+ <Font
+ fontFamily="Geist"
+ fallbackFontFamily="Helvetica"
+ webFont={{
+ url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-400-normal.woff2",
+ format: "woff2",
+ }}
+ fontWeight={400}
+ fontStyle="normal"
+ />
+
+ <Font
+ fontFamily="Geist"
+ fallbackFontFamily="Helvetica"
+ webFont={{
+ url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-500-normal.woff2",
+ format: "woff2",
+ }}
+ fontWeight={500}
+ fontStyle="normal"
+ />
+ <Font
+ fontFamily="Geist"
+ fallbackFontFamily="Helvetica"
+ webFont={{
+ url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-800-normal.woff2",
+ format: "woff2",
+ }}
+ fontWeight={800}
+ fontStyle="normal"
+ />
+ </head>
+ <Body className="bg-white font-sans">
+ <Container className="mx-auto py-5 px-0 w-[660px] max-w-full">
+ <Section>
+ <Row>
+ <Column>
+ {company.logoLightIcon ? (
+ <Img
+ src={company.logoLightIcon}
+ width="auto"
+ height="42"
+ alt={`${company.name} Logo`}
+ />
+ ) : (
+ <Text className="text-3xl font-bold text-gray-900">
+ {company.name}
+ </Text>
+ )}
+ </Column>
+ <Column className="text-right">
+ <Text className="text-3xl font-light text-gray-500">
+ Sales Invoice
+ </Text>
+ </Column>
+ </Row>
+ </Section>
+ <Section>
+ <Text className="text-left text-sm font-medium text-gray-900 my-9">
+ {recipient.firstName ? `Hi ${recipient.firstName}, ` : "Hi, "}
+ please see the attached invoice and let me know if you have any
+ questions.
+ </Text>
+ </Section>
+ <Section className="bg-gray-50 rounded-lg text-xs">
+ <Row>
+ <Column className="p-5" colSpan={2}>
+ <Section>
+ <Row>
+ <Column>
+ <Text className="text-gray-600 uppercase text-[10px]">
+ Seller
+ </Text>
+ <Link
+ href={`mailto:${sender.email}?subject=${reSubject}`}
+ className="text-blue-600 underline"
+ >
+ {`${sender.firstName} ${sender.lastName}`}
+ </Link>
+ </Column>
+ </Row>
+ <Row>
+ <Column>
+ <Text className="text-gray-600 uppercase text-[10px]">
+ Payment Terms
+ </Text>
+ <Text>
+ {
+ paymentTerms?.find(
+ (term) => term.id === salesInvoice.paymentTermId
+ )?.name
+ }
+ </Text>
+ </Column>
+ </Row>
+ <Row>
+ <Column>
+ <Text className="text-gray-600 uppercase text-[10px]">
+ Invoice ID
+ </Text>
+ <Text>{salesInvoice.invoiceId}</Text>
+ </Column>
+ <Column>
+ <Text className="text-gray-600 uppercase text-[10px]">
+ Due Date
+ </Text>
+ <Text>{salesInvoice.dateDue ?? "-"}</Text>
+ </Column>
+ </Row>
+ </Section>
+ </Column>
+ <Column className="p-5" colSpan={2}>
+ <Text className="text-gray-600 uppercase text-[10px]">
+ Ship To
+ </Text>
+ <Text>{invoiceCustomerName}</Text>
+ {invoiceAddressLine1 && <Text>{invoiceAddressLine1}</Text>}
+ {invoiceAddressLine2 && <Text>{invoiceAddressLine2}</Text>}
+ <Text>
+ {formatCityStatePostalCode(
+ invoiceCity,
+ invoiceStateProvince,
+ invoicePostalCode
+ )}
+ </Text>
+ <Text>{invoiceCountryName}</Text>
+ </Column>
+ </Row>
+ </Section>
+ <Section className="mt-8 mb-4">
+ <Text className="text-gray-600 uppercase text-[10px] pl-5">
+ Sales Invoice Lines
+ </Text>
+ </Section>
+ <Section>
+ {salesInvoiceLines.map((line) => (
+ <Row key={line.id} className="mb-2.5 pl-5">
+ <Column>
+ <Text className="text-xs font-semibold">
+ {getLineDescription(line)}
+ </Text>
+ {getLineDescriptionDetails(line)
+ ?.split("\n")
+ .map((l, i) => (
+ <Text key={i} className="text-xs text-gray-600">
+ {l}
+ </Text>
+ ))}
+ </Column>
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text className="text-xs font-semibold">
+ {line.invoiceLineType === "Comment"
+ ? ""
+ : `(${line.quantity} ${line.unitOfMeasureCode})`}
+ </Text>
+ </Column>
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text className="text-xs font-semibold">
+ {line.invoiceLineType === "Comment"
+ ? "-"
+ : formatter.format(line.convertedUnitPrice ?? 0)}
+ </Text>
+ </Column>
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text className="text-xs font-semibold">
+ {line.invoiceLineType === "Comment"
+ ? "-"
+ : formatter.format(getLineTotal(line))}
+ </Text>
+ </Column>
+ </Row>
+ ))}
+ </Section>
+ <Hr className="my-8" />
+ <Section className="text-right">
+ <Row>
+ <Column className="pr-8">
+ <Text className="text-[10px] font-semibold text-gray-600">
+ TOTAL
+ </Text>
+ </Column>
+ <Column className="border-l border-gray-200 h-12"></Column>
+ <Column className="w-[90px] pr-5">
+ <Text className="text-base font-semibold whitespace-nowrap">
+ {formatter.format(
+ getTotal(
+ salesInvoiceLines,
+ salesInvoice,
+ salesInvoiceShipment
+ )
+ )}
+ </Text>
+ </Column>
+ </Row>
+ </Section>
+ <Hr className="mb-20" />
+ <Section>
+ <Row>
+ <Column className="text-center">
+ {company.logoLightIcon ? (
+ <Img
+ src={company.logoLightIcon}
+ width="60"
+ height="auto"
+ alt={`${company.name} Logo`}
+ />
+ ) : (
+ <Text className="text-3xl font-bold text-gray-900">
+ {company.name}
+ </Text>
+ )}
+ </Column>
+ </Row>
+ </Section>
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+};
+
+export default SalesInvoiceEmail;
diff --git a/packages/documents/src/email/SalesOrderEmail.tsx b/packages/documents/src/email/SalesOrderEmail.tsx
index bcde920493..50299a9515 100644
--- a/packages/documents/src/email/SalesOrderEmail.tsx
+++ b/packages/documents/src/email/SalesOrderEmail.tsx
@@ -28,6 +28,7 @@ interface SalesOrderEmailProps extends Email {
salesOrder: Database["public"]["Views"]["salesOrders"]["Row"];
salesOrderLines: Database["public"]["Views"]["salesOrderLines"]["Row"][];
salesOrderLocations: Database["public"]["Views"]["salesOrderLocations"]["Row"];
+ paymentTerms: { id: string; name: string }[];
}
const SalesOrderEmail = ({
@@ -38,6 +39,7 @@ const SalesOrderEmail = ({
salesOrderLocations,
recipient,
sender,
+ paymentTerms,
}: SalesOrderEmailProps) => {
const {
customerName,
@@ -124,7 +126,7 @@ const SalesOrderEmail = ({
</Section>
<Section>
<Text className="text-left text-sm font-medium text-gray-900 my-9">
- {recipient.firstName ? `Hi ${recipient.firstName},` : "Hi,"}
+ {recipient.firstName ? `Hi ${recipient.firstName}, ` : "Hi, "}
please see the attached sales order and let me know if you have
any questions.
</Text>
@@ -151,7 +153,13 @@ const SalesOrderEmail = ({
<Text className="text-gray-600 uppercase text-[10px]">
Payment Terms
</Text>
- <Text>{salesOrder.paymentTermName ?? "-"}</Text>
+ <Text>
+ {
+ paymentTerms?.find(
+ (term) => term.id === salesOrder.paymentTermId
+ )?.name
+ }
+ </Text>
</Column>
</Row>
<Row>
diff --git a/packages/documents/src/email/index.ts b/packages/documents/src/email/index.ts
index bcb601641c..e4700e8312 100644
--- a/packages/documents/src/email/index.ts
+++ b/packages/documents/src/email/index.ts
@@ -1,6 +1,13 @@
import InviteEmail from "./InviteEmail";
import PurchaseOrderEmail from "./PurchaseOrderEmail";
import QuoteEmail from "./QuoteEmail";
+import SalesInvoiceEmail from "./SalesInvoiceEmail";
import SalesOrderEmail from "./SalesOrderEmail";
-export { InviteEmail, PurchaseOrderEmail, QuoteEmail, SalesOrderEmail };
+export {
+ InviteEmail,
+ PurchaseOrderEmail,
+ QuoteEmail,
+ SalesInvoiceEmail,
+ SalesOrderEmail,
+};
diff --git a/packages/documents/src/pdf/SalesInvoicePDF.tsx b/packages/documents/src/pdf/SalesInvoicePDF.tsx
index b4696cf218..8ea572d822 100644
--- a/packages/documents/src/pdf/SalesInvoicePDF.tsx
+++ b/packages/documents/src/pdf/SalesInvoicePDF.tsx
@@ -54,7 +54,7 @@ const SalesInvoicePDF = ({
paymentTerms,
shippingMethods,
thumbnails,
- title = "Sales Invoice",
+ title = "Invoice",
}: SalesInvoicePDFProps) => {
const {
customerName,
@@ -108,8 +108,8 @@ const SalesInvoicePDF = ({
title={title}
meta={{
author: meta?.author ?? "CarbonOS",
- keywords: meta?.keywords ?? "sales order",
- subject: meta?.subject ?? "Sales Invoice",
+ keywords: meta?.keywords ?? "sales invoice",
+ subject: meta?.subject ?? "Invoice",
}}
>
<View>