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: generate sales order pdf on confirm

Brad Barbinb630b0aaa014
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index 8a6d3c743b..5b7cdf20cf 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -176,6 +176,17 @@ export async function getSalesInvoice(
.single();
}
+export async function getSalesInvoiceCustomerDetails(
+ client: SupabaseClient<Database>,
+ salesInvoiceId: string
+) {
+ return client
+ .from("salesInvoiceLocations")
+ .select("*")
+ .eq("id", salesInvoiceId)
+ .single();
+}
+
export async function getSalesInvoices(
client: SupabaseClient<Database>,
companyId: string,
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index e123daa8d2..9472a11c48 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -542,6 +542,19 @@ export const salesOrderStatusType = [
"Closed",
] as const;
+export const salesConfirmValidator = 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 salesOrderValidator = z.object({
id: zfd.text(z.string().optional()),
salesOrderId: zfd.text(z.string().optional()),
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
index 46d9a27a37..d585fc1bca 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
@@ -9,9 +9,19 @@ import {
HStack,
Heading,
IconButton,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ VStack,
+ toast,
useDisclosure,
} from "@carbon/react";
+import type { FetcherWithComponents } from "@remix-run/react";
import { Await, Link, useFetcher, useParams } from "@remix-run/react";
import {
LuCheckCheck,
@@ -31,22 +41,128 @@ import {
import { usePanels } from "~/components/Layout";
import { usePermissions, useRouteData } from "~/hooks";
+import type { action as confirmAction } from "~/routes/x+/sales-order+/$orderId.confirm";
import type { action as statusAction } from "~/routes/x+/sales-order+/$orderId.status";
import { path } from "~/utils/path";
import type { Opportunity, SalesOrder, SalesOrderLine } from "../../types";
-import { Suspense, useMemo } from "react";
+import { SelectControlled, ValidatedForm } from "@carbon/form";
+import { Suspense, useEffect, useMemo, useState } from "react";
import { CSVLink } from "react-csv";
+import { CustomerContact } from "~/components/Form";
import Confirm from "~/components/Modals/Confirm/Confirm";
+import { useIntegrations } from "~/hooks/useIntegrations";
import type { Shipment } from "~/modules/inventory/types";
import { ShipmentStatus } from "~/modules/inventory/ui/Shipments";
import type { SalesInvoice } from "~/modules/invoicing/types";
import SalesInvoiceStatus from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceStatus";
import type { Job } from "~/modules/production/types";
import { useCustomers } from "~/stores/customers";
+import { salesConfirmValidator } from "../../sales.models";
import SalesStatus from "./SalesStatus";
import { useSalesOrder } from "./useSalesOrder";
+const SalesOrderConfirmModal = ({
+ fetcher,
+ salesOrder,
+ onClose,
+}: {
+ fetcher: FetcherWithComponents<{ success: boolean; message: string }>;
+ salesOrder?: SalesOrder;
+ onClose: () => void;
+}) => {
+ const { orderId } = useParams();
+ if (!orderId) throw new Error("orderId not found");
+
+ const integrations = useIntegrations();
+ const canEmail = integrations.has("resend");
+
+ const [notificationType, setNotificationType] = useState<"Email" | "None">(
+ canEmail ? "Email" : "None"
+ );
+
+ useEffect(() => {
+ if (fetcher.data?.success) {
+ onClose();
+ } else if (fetcher.data?.success === false && fetcher.data?.message) {
+ toast.error(fetcher.data.message);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fetcher.data?.success]);
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ onClose();
+ }
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ action={path.to.salesOrderConfirm(orderId)}
+ validator={salesConfirmValidator}
+ onSubmit={onClose}
+ defaultValues={{
+ notification: notificationType,
+ customerContact: salesOrder?.customerContactId ?? undefined,
+ }}
+ fetcher={fetcher}
+ >
+ <ModalHeader>
+ <ModalTitle>{`Confirm ${salesOrder?.salesOrderId}`}</ModalTitle>
+ <ModalDescription>
+ Are you sure you want to confirm this sales order? Confirming the
+ order will affect on order quantities used to calculate supply and
+ demand.
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={4}>
+ {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 as "Email" | "None");
+ }}
+ />
+ )}
+ {notificationType === "Email" && (
+ <CustomerContact
+ name="customerContact"
+ customer={salesOrder?.customerId ?? undefined}
+ />
+ )}
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button type="submit" isLoading={fetcher.state !== "idle"}>
+ Confirm
+ </Button>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+};
+
const SalesOrderHeader = () => {
const { orderId } = useParams();
if (!orderId) throw new Error("orderId not found");
@@ -69,9 +185,11 @@ const SalesOrderHeader = () => {
const permissions = usePermissions();
const statusFetcher = useFetcher<typeof statusAction>();
+ const confirmFetcher = useFetcher<typeof confirmAction>();
const { ship, invoice } = useSalesOrder();
const salesOrderToJobsModal = useDisclosure();
+ const confirmDisclosure = useDisclosure();
const [customers] = useCustomers();
const csvExportData = useMemo(() => {
@@ -195,31 +313,26 @@ const SalesOrderHeader = () => {
</DropdownMenuContent>
</DropdownMenu>
- <statusFetcher.Form
- method="post"
- action={path.to.salesOrderStatus(orderId)}
+ <Button
+ leftIcon={<LuCheckCheck />}
+ variant={
+ routeData?.salesOrder?.status === "Draft"
+ ? "primary"
+ : "secondary"
+ }
+ isLoading={confirmFetcher.state !== "idle"}
+ onClick={confirmDisclosure.onOpen}
+ isDisabled={
+ confirmFetcher.state !== "idle" ||
+ !["Draft", "Needs Approval"].includes(
+ routeData?.salesOrder?.status ?? ""
+ ) ||
+ routeData?.lines.length === 0 ||
+ !permissions.can("update", "sales")
+ }
>
- <input type="hidden" name="status" value="To Ship and Invoice" />
- <Button
- isDisabled={
- !["Draft", "Needs Approval"].includes(
- routeData?.salesOrder?.status ?? ""
- ) ||
- statusFetcher.state !== "idle" ||
- !permissions.can("update", "sales")
- }
- isLoading={
- statusFetcher.state !== "idle" &&
- statusFetcher.formData?.get("status") ===
- "To Ship and Invoice"
- }
- leftIcon={<LuCheckCheck />}
- type="submit"
- variant="secondary"
- >
- Confirm
- </Button>
- </statusFetcher.Form>
+ Confirm
+ </Button>
<statusFetcher.Form
method="post"
@@ -454,6 +567,13 @@ const SalesOrderHeader = () => {
action={path.to.salesOrderLinesToJobs(orderId)}
/>
)}
+ {confirmDisclosure.isOpen && (
+ <SalesOrderConfirmModal
+ fetcher={confirmFetcher}
+ salesOrder={routeData?.salesOrder}
+ onClose={confirmDisclosure.onClose}
+ />
+ )}
</>
);
};
diff --git a/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx
new file mode 100644
index 0000000000..a2c0a47650
--- /dev/null
+++ b/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx
@@ -0,0 +1,150 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { SalesInvoicePDF } from "@carbon/documents/pdf";
+import type { JSONContent } from "@carbon/react";
+import { renderToStream } from "@react-pdf/renderer";
+import { type LoaderFunctionArgs } from "@vercel/remix";
+import { getPaymentTermsList } from "~/modules/accounting";
+import { getShippingMethodsList } from "~/modules/inventory";
+import {
+ getSalesInvoice,
+ getSalesInvoiceCustomerDetails,
+ getSalesInvoiceLines,
+ getSalesInvoiceShipment,
+} from "~/modules/invoicing";
+import { getSalesTerms } from "~/modules/sales";
+import { getCompany } from "~/modules/settings";
+import { getBase64ImageFromSupabase } from "~/modules/shared";
+import { getLocale } from "~/utils/request";
+
+export const config = { runtime: "nodejs" };
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const [
+ company,
+ salesInvoice,
+ salesInvoiceLines,
+ salesInvoiceLocations,
+ salesInvoiceShipment,
+ terms,
+ paymentTerms,
+ shippingMethods,
+ ] = await Promise.all([
+ getCompany(client, companyId),
+ getSalesInvoice(client, id),
+ getSalesInvoiceLines(client, id),
+ getSalesInvoiceCustomerDetails(client, id),
+ getSalesInvoiceShipment(client, id),
+ getSalesTerms(client, companyId),
+ getPaymentTermsList(client, companyId),
+ getShippingMethodsList(client, companyId),
+ ]);
+
+ if (company.error) {
+ console.error(company.error);
+ }
+
+ if (salesInvoice.error) {
+ console.error(salesInvoice.error);
+ }
+
+ if (salesInvoiceLines.error) {
+ console.error(salesInvoiceLines.error);
+ }
+
+ if (salesInvoiceShipment.error) {
+ console.error(salesInvoiceShipment.error);
+ }
+
+ if (salesInvoiceLocations.error) {
+ console.error(salesInvoiceLocations.error);
+ }
+
+ if (terms.error) {
+ console.error(terms.error);
+ }
+
+ if (
+ company.error ||
+ salesInvoice.error ||
+ salesInvoiceLines.error ||
+ salesInvoiceLocations.error ||
+ salesInvoiceShipment.error ||
+ terms.error
+ ) {
+ throw new Error("Failed to load sales order");
+ }
+
+ const thumbnailPaths = salesInvoiceLines.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 locale = getLocale(request);
+
+ const stream = await renderToStream(
+ <SalesInvoicePDF
+ company={company.data}
+ locale={locale}
+ meta={{
+ author: "CarbonOS",
+ keywords: "sales order",
+ subject: "Sales Invoice",
+ }}
+ salesInvoice={salesInvoice.data}
+ salesInvoiceLines={salesInvoiceLines.data ?? []}
+ salesInvoiceLocations={salesInvoiceLocations.data}
+ salesInvoiceShipment={salesInvoiceShipment.data}
+ terms={(terms?.data?.salesTerms ?? {}) as JSONContent}
+ paymentTerms={paymentTerms.data ?? []}
+ shippingMethods={shippingMethods.data ?? []}
+ title="Sales Invoice"
+ 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 });
+}
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 0294a60161..17fb4f9400 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
@@ -1,17 +1,41 @@
-import { getCarbonServiceRole } from "@carbon/auth";
+import { assertIsPost, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import type { ActionFunctionArgs } from "@vercel/remix";
-import { json } from "@vercel/remix";
+import { SalesInvoiceEmail } from "@carbon/documents/email";
+import { validationError, 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 { upsertDocument } from "~/modules/documents";
+import {
+ getSalesInvoice,
+ getSalesInvoiceCustomerDetails,
+ getSalesInvoiceLines,
+ getSalesInvoiceShipment,
+} from "~/modules/invoicing";
+import { getCustomerContact, salesConfirmValidator } from "~/modules/sales";
+import { getCompany } from "~/modules/settings";
+import { getUser } from "~/modules/users/users.server";
+import { loader as pdfLoader } from "~/routes/file+/sales-invoice+/$id[.]pdf";
+import type { sendEmailResendTask } from "~/trigger/send-email-resend";
+import { stripSpecialCharacters } from "~/utils/string";
export const config = { runtime: "nodejs" };
-export async function action({ request, params }: ActionFunctionArgs) {
+export async function action(args: ActionFunctionArgs) {
+ const { request, params } = args;
+ assertIsPost(request);
+
const { client, companyId, userId } = await requirePermissions(request, {
- update: "invoicing",
+ create: "invoicing",
+ role: "employee",
});
const { invoiceId } = params;
- if (!invoiceId) throw new Error("invoiceId not found");
+ if (!invoiceId) throw new Error("Could not find invoiceId");
+
+ let file: ArrayBuffer;
+ let fileName: string;
const setPendingState = await client
.from("salesInvoice")
@@ -21,14 +45,15 @@ export async function action({ request, params }: ActionFunctionArgs) {
.eq("id", invoiceId);
if (setPendingState.error) {
- return json({
+ return {
success: false,
- message: "Failed to post sales invoice",
- });
+ message: "Failed to update sales invoice status",
+ };
}
+ // Call the edge function to post the invoice
+ const serviceRole = getCarbonServiceRole();
try {
- const serviceRole = await getCarbonServiceRole();
const postSalesInvoice = await serviceRole.functions.invoke(
"post-sales-invoice",
{
@@ -41,6 +66,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
if (postSalesInvoice.error) {
+ // Revert to Draft status if posting fails
await client
.from("salesInvoice")
.update({
@@ -48,12 +74,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
.eq("id", invoiceId);
- return json({
+ return {
success: false,
message: "Failed to post sales invoice",
- });
+ };
}
- } catch (error) {
+ } catch (err) {
+ // Revert to Draft status if an exception occurs
await client
.from("salesInvoice")
.update({
@@ -61,14 +88,185 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
.eq("id", invoiceId);
- return json({
+ return {
success: false,
message: "Failed to post sales invoice",
+ };
+ }
+
+ const [salesInvoice] = await Promise.all([
+ getSalesInvoice(serviceRole, invoiceId),
+ ]);
+ if (salesInvoice.error) {
+ return {
+ success: false,
+ message: "Failed to get sales invoice",
+ };
+ }
+
+ if (salesInvoice.data.companyId !== companyId) {
+ return {
+ success: false,
+ message: "You are not authorized to confirm this sales invoice",
+ };
+ }
+
+ const acceptLanguage = request.headers.get("accept-language");
+ const locales = parseAcceptLanguage(acceptLanguage, {
+ validate: Intl.DateTimeFormat.supportedLocalesOf,
+ });
+
+ try {
+ const pdf = await pdfLoader(args);
+ if (pdf.headers.get("content-type") !== "application/pdf")
+ throw new Error("Failed to generate PDF");
+
+ file = await pdf.arrayBuffer();
+ fileName = stripSpecialCharacters(
+ `${salesInvoice.data.invoiceId} - ${new Date()
+ .toISOString()
+ .slice(0, -5)}.pdf`
+ );
+
+ const documentFilePath = `${companyId}/opportunity/${salesInvoice.data.opportunityId}/${fileName}`;
+
+ const documentFileUpload = await serviceRole.storage
+ .from("private")
+ .upload(documentFilePath, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ contentType: "application/pdf",
+ upsert: true,
+ });
+
+ if (documentFileUpload.error) {
+ return {
+ success: false,
+ message: "Failed to upload file",
+ };
+ }
+
+ const createDocument = await upsertDocument(serviceRole, {
+ path: documentFilePath,
+ name: fileName,
+ size: Math.round(file.byteLength / 1024),
+ sourceDocument: "Sales Invoice",
+ sourceDocumentId: invoiceId,
+ readGroups: [userId],
+ writeGroups: [userId],
+ createdBy: userId,
+ companyId,
});
+
+ if (createDocument.error) {
+ return {
+ success: false,
+ message: "Failed to create document",
+ };
+ }
+ } catch (err) {
+ return {
+ success: false,
+ message: "Failed to generate PDF",
+ };
+ }
+
+ const validation = await validator(salesConfirmValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { notification, customerContact } = validation.data;
+
+ switch (notification) {
+ case "Email":
+ try {
+ if (!customerContact) throw new Error("Customer contact is required");
+
+ const [
+ company,
+ customer,
+ salesInvoice,
+ salesInvoiceLines,
+ salesInvoiceLocations,
+ salesInvoiceShipment,
+ seller,
+ ] = await Promise.all([
+ getCompany(serviceRole, companyId),
+ getCustomerContact(serviceRole, customerContact),
+ getSalesInvoice(serviceRole, invoiceId),
+ getSalesInvoiceLines(serviceRole, invoiceId),
+ getSalesInvoiceCustomerDetails(serviceRole, invoiceId),
+ getSalesInvoiceShipment(serviceRole, invoiceId),
+ getUser(serviceRole, userId),
+ ]);
+
+ 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");
+
+ const emailTemplate = SalesInvoiceEmail({
+ company: company.data,
+ locale: locales?.[0] ?? "en-US",
+ salesInvoice: salesInvoice.data,
+ salesInvoiceLines: salesInvoiceLines.data ?? [],
+ salesInvoiceLocations: salesInvoiceLocations.data,
+ salesInvoiceShipment: salesInvoiceShipment.data,
+ recipient: {
+ email: customer.data.contact.email,
+ firstName: customer.data.contact.firstName ?? undefined,
+ lastName: customer.data.contact.lastName ?? undefined,
+ },
+ sender: {
+ email: seller.data.email,
+ firstName: seller.data.firstName,
+ lastName: seller.data.lastName,
+ },
+ });
+
+ const html = await renderAsync(emailTemplate);
+ const text = await renderAsync(emailTemplate, { plainText: true });
+
+ 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}`,
+ html,
+ text,
+ attachments: [
+ {
+ content: Buffer.from(file).toString("base64"),
+ filename: fileName,
+ },
+ ],
+ companyId,
+ });
+ } catch (err) {
+ return {
+ success: false,
+ message: "Failed to send email",
+ };
+ }
+
+ break;
+ case undefined:
+ case "None":
+ break;
+ default:
+ return {
+ success: false,
+ message: "Invalid notification type",
+ };
}
- return json({
+ return {
success: true,
- message: "Sales invoice posted successfully",
- });
+ message: "Sales invoice confirmed",
+ };
}
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
new file mode 100644
index 0000000000..1841831e1f
--- /dev/null
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
@@ -0,0 +1,286 @@
+import { assertIsPost, getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { SalesOrderEmail } from "@carbon/documents/email";
+import { validator } from "@carbon/form";
+import { getLocalTimeZone, today } from "@internationalized/date";
+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 { upsertDocument } from "~/modules/documents";
+import {
+ getCustomerContact,
+ getSalesOrder,
+ getSalesOrderCustomerDetails,
+ getSalesOrderLines,
+ salesConfirmValidator,
+} from "~/modules/sales";
+import { getCompany } from "~/modules/settings";
+import { getUser } from "~/modules/users/users.server";
+import { loader as pdfLoader } from "~/routes/file+/sales-order+/$id[.]pdf";
+import type { sendEmailResendTask } from "~/trigger/send-email-resend";
+import { stripSpecialCharacters } from "~/utils/string";
+
+export const config = { runtime: "nodejs" };
+
+export async function action(args: ActionFunctionArgs) {
+ const { request, params } = args;
+
+ try {
+ assertIsPost(request);
+
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "sales",
+ role: "employee",
+ });
+
+ const { orderId } = params;
+ if (!orderId) {
+ return json({
+ success: false,
+ message: "Could not find orderId",
+ });
+ }
+
+ let file: ArrayBuffer;
+ let fileName: string;
+
+ const serviceRole = getCarbonServiceRole();
+
+ const [salesOrder] = await Promise.all([
+ getSalesOrder(serviceRole, orderId),
+ ]);
+ if (salesOrder.error) {
+ return json({
+ success: false,
+ message: "Failed to get sales order",
+ });
+ }
+
+ if (salesOrder.data.companyId !== companyId) {
+ return json({
+ success: false,
+ message: "You are not authorized to confirm this sales order",
+ });
+ }
+
+ const acceptLanguage = request.headers.get("accept-language");
+ const locales = parseAcceptLanguage(acceptLanguage, {
+ validate: Intl.DateTimeFormat.supportedLocalesOf,
+ });
+
+ try {
+ // Pass orderId as id for PDF generation
+ const pdfArgs = {
+ ...args,
+ params: { ...args.params, id: orderId },
+ };
+ const pdf = await pdfLoader(pdfArgs);
+
+ if (pdf.headers.get("content-type") !== "application/pdf") {
+ return json({
+ success: false,
+ message: "Failed to generate PDF",
+ });
+ }
+
+ file = await pdf.arrayBuffer();
+ fileName = stripSpecialCharacters(
+ `${salesOrder.data.salesOrderId} - ${new Date()
+ .toISOString()
+ .slice(0, -5)}.pdf`
+ );
+
+ const documentFilePath = `${companyId}/opportunity/${salesOrder.data.opportunityId}/${fileName}`;
+
+ const documentFileUpload = await serviceRole.storage
+ .from("private")
+ .upload(documentFilePath, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ contentType: "application/pdf",
+ upsert: true,
+ });
+
+ if (documentFileUpload.error) {
+ return json({
+ success: false,
+ message: "Failed to upload file",
+ });
+ }
+
+ const createDocument = await upsertDocument(serviceRole, {
+ path: documentFilePath,
+ name: fileName,
+ size: Math.round(file.byteLength / 1024),
+ sourceDocument: "Sales Order",
+ sourceDocumentId: orderId,
+ readGroups: [userId],
+ writeGroups: [userId],
+ createdBy: userId,
+ companyId,
+ });
+
+ if (createDocument.error) {
+ return json({
+ success: false,
+ message: "Failed to create document",
+ });
+ }
+ } catch (err) {
+ return json({
+ success: false,
+ message: "Failed to generate PDF",
+ });
+ }
+
+ const validation = await validator(salesConfirmValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return json({
+ success: false,
+ message: "Invalid form data",
+ });
+ }
+
+ const { notification, customerContact } = validation.data;
+
+ switch (notification) {
+ case "Email":
+ try {
+ if (!customerContact) {
+ return json({
+ success: false,
+ message: "Customer contact is required",
+ });
+ }
+
+ const [
+ company,
+ customer,
+ salesOrder,
+ salesOrderLines,
+ salesOrderLocations,
+ seller,
+ ] = await Promise.all([
+ getCompany(serviceRole, companyId),
+ getCustomerContact(serviceRole, customerContact),
+ getSalesOrder(serviceRole, orderId),
+ getSalesOrderLines(serviceRole, orderId),
+ getSalesOrderCustomerDetails(serviceRole, orderId),
+ getUser(serviceRole, userId),
+ ]);
+
+ if (!customer?.data?.contact) {
+ return json({
+ success: false,
+ message: "Failed to get customer contact",
+ });
+ }
+ if (!company.data) {
+ return json({
+ success: false,
+ message: "Failed to get company",
+ });
+ }
+ if (!seller.data) {
+ return json({
+ success: false,
+ message: "Failed to get user",
+ });
+ }
+ if (!salesOrder.data) {
+ return json({
+ success: false,
+ message: "Failed to get sales order",
+ });
+ }
+ if (!salesOrderLocations.data) {
+ return json({
+ success: false,
+ message: "Failed to get sales order locations",
+ });
+ }
+
+ const emailTemplate = SalesOrderEmail({
+ company: company.data,
+ locale: locales?.[0] ?? "en-US",
+ salesOrder: salesOrder.data,
+ salesOrderLines: salesOrderLines.data ?? [],
+ salesOrderLocations: salesOrderLocations.data,
+ recipient: {
+ email: customer.data.contact.email,
+ firstName: customer.data.contact.firstName ?? undefined,
+ lastName: customer.data.contact.lastName ?? undefined,
+ },
+ sender: {
+ email: seller.data.email,
+ firstName: seller.data.firstName,
+ lastName: seller.data.lastName,
+ },
+ });
+
+ const html = await renderAsync(emailTemplate);
+ const text = await renderAsync(emailTemplate, { plainText: true });
+
+ 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}`,
+ html,
+ text,
+ attachments: [
+ {
+ content: Buffer.from(file).toString("base64"),
+ filename: fileName,
+ },
+ ],
+ companyId,
+ });
+ } catch (err) {
+ return json({
+ success: false,
+ message: "Failed to send email",
+ });
+ }
+ break;
+ case undefined:
+ case "None":
+ break;
+ default:
+ return json({
+ success: false,
+ message: "Invalid notification type",
+ });
+ }
+
+ const confirm = await client
+ .from("salesOrder")
+ .update({
+ status: "To Ship and Invoice",
+ orderDate: today(getLocalTimeZone()).toString(),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", orderId);
+
+ if (confirm.error) {
+ return json({
+ success: false,
+ message: "Failed to confirm sales order",
+ });
+ }
+
+ return json({
+ success: true,
+ message: "Sales order confirmed",
+ });
+ } catch (err) {
+ return json({
+ success: false,
+ message:
+ err instanceof Error ? err.message : "An unexpected error occurred",
+ });
+ }
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 2d678d3cd5..eef034c3c4 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -186,6 +186,8 @@ export const path = {
},
salesOrder: (id: string) => generatePath(`${file}/sales-order/${id}.pdf`),
+ salesInvoice: (id: string) =>
+ generatePath(`${file}/sales-invoice/${id}.pdf`),
shipment: (id: string) => generatePath(`${file}/shipment/${id}.pdf`),
shipmentLabelsPdf: (
id: string,
@@ -1034,6 +1036,8 @@ export const path = {
generatePath(`${x}/sales-invoice/${id}/shipment`),
salesInvoices: `${x}/sales/invoices`,
salesOrder: (id: string) => generatePath(`${x}/sales-order/${id}`),
+ salesOrderConfirm: (id: string) =>
+ generatePath(`${x}/sales-order/${id}/confirm`),
salesOrderShipment: (id: string) =>
generatePath(`${x}/sales-order/${id}/shipment`),
salesOrderDetails: (id: string) =>
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index c50650f7be..7c2bd9296f 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -23808,6 +23808,13 @@ export type Database = {
referencedRelation: "salesInvoice"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoiceLine_invoiceId_fkey"
+ columns: ["invoiceId"]
+ isOneToOne: false
+ referencedRelation: "salesInvoiceLocations"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoiceLine_invoiceId_fkey"
columns: ["invoiceId"]
@@ -24061,6 +24068,13 @@ export type Database = {
referencedRelation: "salesInvoice"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoiceShipment_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "salesInvoiceLocations"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoiceShipment_id_fkey"
columns: ["id"]
@@ -39026,6 +39040,13 @@ export type Database = {
referencedRelation: "salesInvoice"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoiceLine_invoiceId_fkey"
+ columns: ["invoiceId"]
+ isOneToOne: false
+ referencedRelation: "salesInvoiceLocations"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoiceLine_invoiceId_fkey"
columns: ["invoiceId"]
@@ -39168,6 +39189,43 @@ export type Database = {
},
]
}
+ salesInvoiceLocations: {
+ Row: {
+ customerAddressLine1: string | null
+ customerAddressLine2: string | null
+ customerCity: string | null
+ customerCountryCode: string | null
+ customerCountryName: string | null
+ customerName: string | null
+ customerPostalCode: string | null
+ customerStateProvince: string | null
+ id: string | null
+ invoiceAddressLine1: string | null
+ invoiceAddressLine2: string | null
+ invoiceCity: string | null
+ invoiceCountryCode: string | null
+ invoiceCountryName: string | null
+ invoiceCustomerName: string | null
+ invoicePostalCode: string | null
+ invoiceStateProvince: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "address_countryCode_fkey"
+ columns: ["invoiceCountryCode"]
+ isOneToOne: false
+ referencedRelation: "country"
+ referencedColumns: ["alpha2"]
+ },
+ {
+ foreignKeyName: "address_countryCode_fkey"
+ columns: ["customerCountryCode"]
+ isOneToOne: false
+ referencedRelation: "country"
+ referencedColumns: ["alpha2"]
+ },
+ ]
+ }
salesInvoices: {
Row: {
assignee: string | null
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index c50650f7be..7c2bd9296f 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -23808,6 +23808,13 @@ export type Database = {
referencedRelation: "salesInvoice"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoiceLine_invoiceId_fkey"
+ columns: ["invoiceId"]
+ isOneToOne: false
+ referencedRelation: "salesInvoiceLocations"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoiceLine_invoiceId_fkey"
columns: ["invoiceId"]
@@ -24061,6 +24068,13 @@ export type Database = {
referencedRelation: "salesInvoice"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoiceShipment_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "salesInvoiceLocations"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoiceShipment_id_fkey"
columns: ["id"]
@@ -39026,6 +39040,13 @@ export type Database = {
referencedRelation: "salesInvoice"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoiceLine_invoiceId_fkey"
+ columns: ["invoiceId"]
+ isOneToOne: false
+ referencedRelation: "salesInvoiceLocations"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoiceLine_invoiceId_fkey"
columns: ["invoiceId"]
@@ -39168,6 +39189,43 @@ export type Database = {
},
]
}
+ salesInvoiceLocations: {
+ Row: {
+ customerAddressLine1: string | null
+ customerAddressLine2: string | null
+ customerCity: string | null
+ customerCountryCode: string | null
+ customerCountryName: string | null
+ customerName: string | null
+ customerPostalCode: string | null
+ customerStateProvince: string | null
+ id: string | null
+ invoiceAddressLine1: string | null
+ invoiceAddressLine2: string | null
+ invoiceCity: string | null
+ invoiceCountryCode: string | null
+ invoiceCountryName: string | null
+ invoiceCustomerName: string | null
+ invoicePostalCode: string | null
+ invoiceStateProvince: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "address_countryCode_fkey"
+ columns: ["invoiceCountryCode"]
+ isOneToOne: false
+ referencedRelation: "country"
+ referencedColumns: ["alpha2"]
+ },
+ {
+ foreignKeyName: "address_countryCode_fkey"
+ columns: ["customerCountryCode"]
+ isOneToOne: false
+ referencedRelation: "country"
+ referencedColumns: ["alpha2"]
+ },
+ ]
+ }
salesInvoices: {
Row: {
assignee: string | null
diff --git a/packages/database/supabase/migrations/20250507143421_sales-invoice.sql b/packages/database/supabase/migrations/20250507143421_sales-invoice.sql
index 7a2931c9e9..fca3e15d32 100644
--- a/packages/database/supabase/migrations/20250507143421_sales-invoice.sql
+++ b/packages/database/supabase/migrations/20250507143421_sales-invoice.sql
@@ -228,3 +228,42 @@ CREATE OR REPLACE VIEW "salesInvoiceLines" WITH(SECURITY_INVOKER=true) AS (
LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
);
+
+
+-- Create the salesInvoiceLocations view
+CREATE OR REPLACE VIEW "salesInvoiceLocations" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ si.id,
+ c.name AS "customerName",
+ ca."addressLine1" AS "customerAddressLine1",
+ ca."addressLine2" AS "customerAddressLine2",
+ ca."city" AS "customerCity",
+ ca."stateProvince" AS "customerStateProvince",
+ ca."postalCode" AS "customerPostalCode",
+ ca."countryCode" AS "customerCountryCode",
+ cc."name" AS "customerCountryName",
+ ic.name AS "invoiceCustomerName",
+ ica."addressLine1" AS "invoiceAddressLine1",
+ ica."addressLine2" AS "invoiceAddressLine2",
+ ica."city" AS "invoiceCity",
+ ica."stateProvince" AS "invoiceStateProvince",
+ ica."postalCode" AS "invoicePostalCode",
+ ica."countryCode" AS "invoiceCountryCode",
+ icc."name" AS "invoiceCountryName"
+ FROM "salesInvoice" si
+ INNER JOIN "customer" c
+ ON c.id = si."customerId"
+ LEFT OUTER JOIN "customerLocation" cl
+ ON cl.id = si."locationId"
+ LEFT OUTER JOIN "address" ca
+ ON ca.id = cl."addressId"
+ LEFT OUTER JOIN "country" cc
+ ON cc.alpha2 = ca."countryCode"
+ LEFT OUTER JOIN "customer" ic
+ ON ic.id = si."invoiceCustomerId"
+ LEFT OUTER JOIN "customerLocation" icl
+ ON icl.id = si."invoiceCustomerLocationId"
+ LEFT OUTER JOIN "address" ica
+ ON ica.id = icl."addressId"
+ LEFT OUTER JOIN "country" icc
+ ON icc.alpha2 = ica."countryCode";
\ No newline at end of file
diff --git a/packages/documents/src/pdf/SalesInvoicePDF.tsx b/packages/documents/src/pdf/SalesInvoicePDF.tsx
new file mode 100644
index 0000000000..b4696cf218
--- /dev/null
+++ b/packages/documents/src/pdf/SalesInvoicePDF.tsx
@@ -0,0 +1,296 @@
+import type { Database } from "@carbon/database";
+import { Image, Text, View } from "@react-pdf/renderer";
+import { createTw } from "react-pdf-tailwind";
+
+import type { JSONContent } from "@carbon/react";
+import { formatCityStatePostalCode } from "@carbon/utils";
+import type { PDF } from "../types";
+import {
+ getLineDescription,
+ getLineDescriptionDetails,
+ getLineTaxesAndFees,
+ getLineTotal,
+ getTotal,
+} from "../utils/sales-invoice";
+import { getCurrencyFormatter } from "../utils/shared";
+import { Header, Note, Summary, Template } from "./components";
+
+interface SalesInvoicePDFProps extends PDF {
+ 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 }[];
+ shippingMethods: { id: string; name: string }[];
+ terms: JSONContent;
+ thumbnails?: Record<string, string | null>;
+}
+
+// Initialize tailwind-styled-components
+const tw = createTw({
+ theme: {
+ fontFamily: {
+ sans: ["Helvetica", "Arial", "sans-serif"],
+ },
+ extend: {
+ colors: {
+ gray: {
+ 500: "#7d7d7d",
+ },
+ },
+ },
+ },
+});
+
+const SalesInvoicePDF = ({
+ company,
+ locale,
+ meta,
+ salesInvoice,
+ salesInvoiceShipment,
+ salesInvoiceLines,
+ salesInvoiceLocations,
+ terms,
+ paymentTerms,
+ shippingMethods,
+ thumbnails,
+ title = "Sales Invoice",
+}: SalesInvoicePDFProps) => {
+ const {
+ customerName,
+ customerAddressLine1,
+ customerAddressLine2,
+ customerCity,
+ customerStateProvince,
+ customerPostalCode,
+ customerCountryName,
+ invoiceCustomerName,
+ invoiceAddressLine1,
+ invoiceAddressLine2,
+ invoiceCity,
+ invoiceStateProvince,
+ invoicePostalCode,
+ invoiceCountryName,
+ } = salesInvoiceLocations;
+
+ const currencyCode = salesInvoice.currencyCode ?? company.baseCurrencyCode;
+ const formatter = getCurrencyFormatter(currencyCode, locale);
+
+ const summaryItems = [
+ {
+ label: "Date Issued",
+ value: salesInvoice?.dateIssued,
+ },
+ {
+ label: "Invoice #",
+ value: salesInvoice?.invoiceId,
+ },
+ ];
+
+ if (salesInvoice?.paymentTermId) {
+ summaryItems.push({
+ label: "Payment Terms",
+ value: paymentTerms.find(
+ (term) => term.id === salesInvoice?.paymentTermId
+ )?.name,
+ });
+ }
+
+ if (salesInvoice?.dateDue) {
+ summaryItems.push({
+ label: "Due Date",
+ value: salesInvoice?.dateDue,
+ });
+ }
+
+ return (
+ <Template
+ title={title}
+ meta={{
+ author: meta?.author ?? "CarbonOS",
+ keywords: meta?.keywords ?? "sales order",
+ subject: meta?.subject ?? "Sales Invoice",
+ }}
+ >
+ <View>
+ <Header title={title} company={company} />
+ <Summary company={company} items={summaryItems} />
+ <View style={tw("flex flex-row justify-between mb-5")}>
+ <View style={tw("flex flex-col gap-1 w-1/3")}>
+ <Text style={tw("text-gray-500 text-xs")}>Ship To</Text>
+ <Text style={tw("text-sm")}>{customerName}</Text>
+ {customerAddressLine1 && (
+ <Text style={tw("text-sm")}>{customerAddressLine1}</Text>
+ )}
+ {customerAddressLine2 && (
+ <Text style={tw("text-sm")}>{customerAddressLine2}</Text>
+ )}
+ <Text style={tw("text-sm")}>
+ {formatCityStatePostalCode(
+ customerCity,
+ customerStateProvince,
+ customerPostalCode
+ )}
+ </Text>
+ <Text style={tw("text-sm")}>{customerCountryName}</Text>
+ </View>
+ <View style={tw("flex flex-col gap-1 w-1/3")}>
+ <Text style={tw("text-gray-500 text-xs")}>Bill To</Text>
+ <Text style={tw("text-sm")}>{invoiceCustomerName}</Text>
+ {invoiceAddressLine1 && (
+ <Text style={tw("text-sm")}>{invoiceAddressLine1}</Text>
+ )}
+ {invoiceAddressLine2 && (
+ <Text style={tw("text-sm")}>{invoiceAddressLine2}</Text>
+ )}
+ <Text style={tw("text-sm")}>
+ {formatCityStatePostalCode(
+ invoiceCity,
+ invoiceStateProvince,
+ invoicePostalCode
+ )}
+ </Text>
+ <Text style={tw("text-sm")}>{invoiceCountryName}</Text>
+ </View>
+ </View>
+ <View style={tw("flex flex-row justify-between mb-5")}>
+ <View style={tw("flex flex-col gap-1 w-1/3")}>
+ <Text style={tw("text-gray-500 text-xs")}>Customer Invoice #</Text>
+ <Text style={tw("text-sm")}>{salesInvoice?.customerReference}</Text>
+ </View>
+ <View style={tw("flex flex-col gap-1 w-1/3")}>
+ <Text style={tw("text-gray-500 text-xs")}>Due Date</Text>
+ <Text style={tw("text-sm")}>{salesInvoice?.dateDue}</Text>
+ </View>
+ </View>
+ <View style={tw("flex flex-row justify-between mb-5")}>
+ <View style={tw("flex flex-col gap-1 w-1/3")}>
+ <Text style={tw("text-gray-500 text-xs")}>Shipping Method</Text>
+ <Text style={tw("text-sm")}>
+ {
+ shippingMethods.find(
+ (method) =>
+ method.id === salesInvoiceShipment?.shippingMethodId
+ )?.name
+ }
+ </Text>
+ </View>
+ <View style={tw("flex flex-col gap-1 w-1/3")}>
+ <Text style={tw("text-gray-500 text-xs")}>Shipping Terms</Text>
+ <Text style={tw("text-sm")}>
+ {salesInvoiceShipment?.shippingTermId}
+ </Text>
+ </View>
+ </View>
+ <View style={tw("mb-5 text-xs")}>
+ <View
+ style={tw(
+ "flex flex-row justify-between items-center mt-5 py-3 px-[6px] border-t border-b border-gray-300 font-bold uppercase"
+ )}
+ >
+ <Text style={tw("w-5/12 text-left")}>Description</Text>
+ <Text style={tw("w-1/6 text-right")}>Qty</Text>
+ <Text style={tw("w-1/6 text-right")}>Price</Text>
+ <Text style={tw("w-1/6 text-right")}>Tax & Fees</Text>
+ <Text style={tw("w-1/6 text-right")}>Total</Text>
+ </View>
+ {salesInvoiceLines.map((line) => {
+ return (
+ <View
+ style={tw(
+ "flex flex-row justify-between py-3 px-[6px] border-b border-gray-300"
+ )}
+ key={line.id}
+ >
+ <View style={tw("w-5/12")}>
+ <Text style={tw("font-bold mb-1")}>
+ {getLineDescription(line)}
+ </Text>
+ <Text style={tw("text-[9px] opacity-80")}>
+ {getLineDescriptionDetails(line)}
+ </Text>
+
+ {thumbnails &&
+ line.id in thumbnails &&
+ thumbnails[line.id] && (
+ <View style={tw("mt-2")}>
+ <Image
+ src={thumbnails[line.id]!}
+ style={tw("w-full h-auto")}
+ />
+ </View>
+ )}
+
+ <View style={tw("mt-1")}>
+ {Object.keys(line.externalNotes ?? {}).length > 0 && (
+ <Note
+ key={`${line.id}-notes`}
+ content={line.externalNotes as JSONContent}
+ />
+ )}
+ </View>
+ </View>
+ <Text style={tw("w-1/6 text-right")}>
+ {line.invoiceLineType === "Comment"
+ ? ""
+ : `${line.quantity} ${line.unitOfMeasureCode}`}
+ </Text>
+ <Text style={tw("w-1/6 text-right")}>
+ {line.invoiceLineType === "Comment"
+ ? null
+ : formatter.format(line.convertedUnitPrice ?? 0)}
+ </Text>
+ <Text style={tw("w-1/6 text-right")}>
+ {line.invoiceLineType === "Comment"
+ ? null
+ : formatter.format(getLineTaxesAndFees(line))}
+ </Text>
+ <Text style={tw("w-1/6 text-right")}>
+ {line.invoiceLineType === "Comment"
+ ? null
+ : formatter.format(getLineTotal(line))}
+ </Text>
+ </View>
+ );
+ })}
+ {salesInvoiceShipment?.shippingCost && (
+ <View
+ style={tw(
+ "flex flex-row justify-between items-center py-3 px-[6px] border-b border-gray-300 font-bold text-gray-500 uppercase"
+ )}
+ >
+ <Text>Shipping</Text>
+ <Text style={tw("text-black")}>
+ {formatter.format(
+ (salesInvoiceShipment.shippingCost ?? 0) *
+ (salesInvoice.exchangeRate ?? 1)
+ )}
+ </Text>
+ </View>
+ )}
+ <View
+ style={tw(
+ "flex flex-row justify-between items-center py-3 px-[6px] border-b border-gray-300 font-bold uppercase"
+ )}
+ >
+ <Text>Total</Text>
+ <Text style={tw("font-bold text-black")}>
+ {formatter.format(
+ getTotal(salesInvoiceLines, salesInvoice, salesInvoiceShipment)
+ )}
+ </Text>
+ </View>
+ </View>
+ <View style={tw("flex flex-col gap-4 w-full")}>
+ <Note
+ title="Notes"
+ content={(salesInvoice.externalNotes ?? {}) as JSONContent}
+ />
+ <Note title="Standard Terms & Conditions" content={terms} />
+ </View>
+ </View>
+ </Template>
+ );
+};
+
+export default SalesInvoicePDF;
diff --git a/packages/documents/src/pdf/index.ts b/packages/documents/src/pdf/index.ts
index 7eb16c17ea..92c4d40f1a 100644
--- a/packages/documents/src/pdf/index.ts
+++ b/packages/documents/src/pdf/index.ts
@@ -3,6 +3,7 @@ import PackingSlipPDF from "./PackingSlipPDF";
import ProductLabelPDF from "./ProductLabelPDF";
import PurchaseOrderPDF from "./PurchaseOrderPDF";
import QuotePDF from "./QuotePDF";
+import SalesInvoicePDF from "./SalesInvoicePDF";
import SalesOrderPDF from "./SalesOrderPDF";
export {
JobTravelerPDF,
@@ -10,5 +11,6 @@ export {
ProductLabelPDF,
PurchaseOrderPDF,
QuotePDF,
+ SalesInvoicePDF,
SalesOrderPDF,
};
diff --git a/packages/documents/src/utils/sales-invoice.ts b/packages/documents/src/utils/sales-invoice.ts
new file mode 100644
index 0000000000..2183d9c033
--- /dev/null
+++ b/packages/documents/src/utils/sales-invoice.ts
@@ -0,0 +1,74 @@
+import type { Database } from "@carbon/database";
+
+export function getLineDescription(
+ line: Database["public"]["Views"]["salesInvoiceLines"]["Row"]
+) {
+ switch (line?.invoiceLineType) {
+ case "Fixed Asset":
+ return line?.assetId;
+ case "Comment":
+ return line?.description;
+ default:
+ return line?.itemReadableId;
+ }
+}
+
+export function getLineDescriptionDetails(
+ line: Database["public"]["Views"]["salesInvoiceLines"]["Row"]
+) {
+ switch (line?.invoiceLineType) {
+ case "Fixed Asset":
+ return line?.description;
+ case "Comment":
+ default:
+ return line?.description ?? "";
+ }
+}
+
+export function getLineSubtotal(
+ line: Database["public"]["Views"]["salesInvoiceLines"]["Row"]
+) {
+ if (line?.quantity && line?.convertedUnitPrice) {
+ return (
+ line.quantity * line.convertedUnitPrice +
+ (line.convertedAddOnCost ?? 0) +
+ (line.convertedShippingCost ?? 0)
+ );
+ }
+ return 0;
+}
+
+export function getLineTaxesAndFees(
+ line: Database["public"]["Views"]["salesInvoiceLines"]["Row"]
+) {
+ const taxPercent = line.taxPercent ?? 0;
+ const tax = getLineSubtotal(line) * taxPercent;
+ const fees =
+ (line.convertedAddOnCost ?? 0) + (line.convertedShippingCost ?? 0);
+ return tax + fees;
+}
+
+export function getLineTotal(
+ line: Database["public"]["Views"]["salesInvoiceLines"]["Row"]
+) {
+ const taxPercent = line.taxPercent ?? 0;
+ const tax = getLineSubtotal(line) * taxPercent;
+ return getLineSubtotal(line) + tax;
+}
+
+export function getTotal(
+ lines: Database["public"]["Views"]["salesInvoiceLines"]["Row"][],
+ salesInvoice: Database["public"]["Views"]["salesInvoices"]["Row"],
+ salesInvoiceShipment: Database["public"]["Tables"]["salesInvoiceShipment"]["Row"]
+) {
+ let total = 0;
+
+ lines.forEach((line) => {
+ total += getLineTotal(line);
+ });
+
+ return (
+ total +
+ (salesInvoiceShipment.shippingCost ?? 0) * (salesInvoice.exchangeRate ?? 1)
+ );
+}