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.

12.7 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import type { Database } from "@carbon/database";
import {
  formatCityStatePostalCode,
  formatDate,
  formatPercent
} from "@carbon/utils";
import {
  Body,
  Column,
  Hr,
  Img,
  Preview,
  Row,
  Section,
  Text
} from "react-email";
import type { Email } from "../types";
import {
  getLineDescription,
  getLineDescriptionDetails,
  getLineTotal,
  getTotal
} from "../utils/sales-invoice";
import { getMoneyFormatter, getRateFormatter } from "../utils/shared";
import { DocumentCard, documentCardStyles } from "./components/DocumentCard";
import {
  detailText,
  labelText,
  lineDetail,
  lineTitle
} from "./components/documentStyles";
import ExternalNotes from "./components/ExternalNotes";
import {
  EmailThemeProvider,
  getEmailInlineStyles,
  getEmailThemeClasses,
  HeadStyle
} from "./components/Theme";

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 }[];
  /** currency.decimalPlaces for the document currency; null falls back to 2 */
  currencyDecimals?: number | null;
}

const SalesInvoiceEmail = ({
  company,
  locale,
  salesInvoice,
  salesInvoiceLines,
  salesInvoiceLocations,
  salesInvoiceShipment,
  recipient,
  sender,
  currencyDecimals,
  paymentTerms
}: SalesInvoiceEmailProps) => {
  const {
    invoiceCustomerName,
    invoiceAddressLine1,
    invoiceAddressLine2,
    invoiceCity,
    invoiceStateProvince,
    invoicePostalCode,
    invoiceCountryName
  } = salesInvoiceLocations;

  const currencyCode = salesInvoice.currencyCode ?? company.baseCurrencyCode;
  const formatter = getMoneyFormatter(locale, currencyDecimals, currencyCode);
  // A unit price is a RATE, not a settlement amount: the currency's
  // decimals are its FLOOR, not its ceiling, so a sub-cent price does not
  // print as 0.00. The PDFs already split these two kinds.
  const rateFormatter = getRateFormatter(
    locale,
    currencyDecimals,
    currencyCode
  );
  const preview = (
    <Preview>{`${salesInvoice.invoiceId} from ${company.name}`}</Preview>
  );
  const themeClasses = getEmailThemeClasses();
  const lightStyles = getEmailInlineStyles("light");

  return (
    <EmailThemeProvider
      preview={preview}
      additionalHeadContent={<HeadStyle css={documentCardStyles} />}
    >
      <Body
        className={`my-auto mx-auto font-sans ${themeClasses.body}`}
        style={lightStyles.body}
      >
        <DocumentCard>
          <Section>
            <Row>
              <Column>
                {company.logoLightIcon ? (
                  <Img
                    src={company.logoLightIcon}
                    width="auto"
                    height="42"
                    alt={`${company.name} Logo`}
                  />
                ) : (
                  <Text
                    className={`text-3xl font-bold ${themeClasses.text}`}
                    style={{ color: lightStyles.text.color }}
                  >
                    {company.name}
                  </Text>
                )}
              </Column>
              <Column className="text-right">
                <Text
                  className={themeClasses.text}
                  style={{
                    margin: 0,
                    paddingLeft: "16px",
                    fontSize: "22px",
                    lineHeight: "28px",
                    color: lightStyles.text.color
                  }}
                >
                  Sales Invoice
                </Text>
              </Column>
            </Row>
          </Section>
          <Section>
            <Text
              className={`text-left text-sm font-medium ${themeClasses.text} my-9`}
              style={{ color: lightStyles.text.color }}
            >
              {recipient.firstName ? `Hi ${recipient.firstName}, ` : "Hi, "}
              please see the attached invoice and let me know if you have any
              questions.
            </Text>
          </Section>
          <ExternalNotes content={salesInvoice.externalNotes} />
          <Section className="bg-gray-50 rounded-[8px] text-xs email-panel">
            <Row>
              <Column className="p-5 align-top" colSpan={2}>
                <Section>
                  <Row>
                    <Column>
                      <Text
                        className={`${themeClasses.mutedText} uppercase`}
                        style={{
                          ...labelText,
                          color: lightStyles.mutedText.color
                        }}
                      >
                        Payment Terms
                      </Text>
                      <Text style={detailText}>
                        {
                          paymentTerms?.find(
                            (term) => term.id === salesInvoice.paymentTermId
                          )?.name
                        }
                      </Text>
                    </Column>
                  </Row>
                  <Row>
                    <Column>
                      <Text
                        className={`${themeClasses.mutedText} uppercase`}
                        style={{
                          ...labelText,
                          color: lightStyles.mutedText.color
                        }}
                      >
                        Invoice ID
                      </Text>
                      <Text style={detailText}>{salesInvoice.invoiceId}</Text>
                    </Column>
                    <Column>
                      <Text
                        className={`${themeClasses.mutedText} uppercase`}
                        style={{
                          ...labelText,
                          color: lightStyles.mutedText.color
                        }}
                      >
                        Due Date
                      </Text>
                      <Text style={detailText}>
                        {salesInvoice.dateDue
                          ? formatDate(salesInvoice.dateDue, undefined, locale)
                          : "-"}
                      </Text>
                    </Column>
                  </Row>
                </Section>
              </Column>
              <Column className="p-5 align-top" colSpan={2}>
                <Text
                  className={`${themeClasses.mutedText} uppercase`}
                  style={{ ...labelText, color: lightStyles.mutedText.color }}
                >
                  Ship To
                </Text>
                <Text style={detailText}>{invoiceCustomerName}</Text>
                {invoiceAddressLine1 && (
                  <Text style={detailText}>{invoiceAddressLine1}</Text>
                )}
                {invoiceAddressLine2 && (
                  <Text style={detailText}>{invoiceAddressLine2}</Text>
                )}
                <Text style={detailText}>
                  {formatCityStatePostalCode(
                    invoiceCity,
                    invoiceStateProvince,
                    invoicePostalCode
                  )}
                </Text>
                <Text style={detailText}>{invoiceCountryName}</Text>
              </Column>
            </Row>
          </Section>

          <Section>
            <Row className="mb-2.5">
              <Column>
                <Text
                  className={`text-xs uppercase ${themeClasses.mutedText}`}
                  style={{ color: lightStyles.mutedText.color }}
                >
                  Description
                </Text>
              </Column>
              <Column className="text-right align-top w-[100px]">
                <Text
                  className={`text-xs uppercase ${themeClasses.mutedText}`}
                  style={{ color: lightStyles.mutedText.color }}
                >
                  Quantity
                </Text>
              </Column>
              <Column className="text-right align-top w-[100px]">
                <Text
                  className={`text-xs uppercase ${themeClasses.mutedText}`}
                  style={{ color: lightStyles.mutedText.color }}
                >
                  Unit Price
                </Text>
              </Column>
              <Column className="text-right align-top w-[100px]">
                <Text
                  className={`text-xs uppercase ${themeClasses.mutedText}`}
                  style={{ color: lightStyles.mutedText.color }}
                >
                  Subtotal
                </Text>
              </Column>
            </Row>
            {salesInvoiceLines.map((line) => (
              <Row key={line.id} className="mb-2.5">
                <Column>
                  <Text style={lineTitle}>{getLineDescription(line)}</Text>
                  {getLineDescriptionDetails(line)
                    ?.split("\n")
                    .map((l, i) => (
                      <Text
                        key={i}
                        className={themeClasses.mutedText}
                        style={{
                          ...lineDetail,
                          color: lightStyles.mutedText.color
                        }}
                      >
                        {l}
                      </Text>
                    ))}
                </Column>
                <Column className="text-right align-top w-[100px]">
                  <Text style={lineTitle}>
                    {line.invoiceLineType === "Comment"
                      ? ""
                      : `${line.quantity}`}
                  </Text>
                </Column>
                <Column className="text-right align-top w-[100px]">
                  <Text style={lineTitle}>
                    {line.invoiceLineType === "Comment"
                      ? "-"
                      : rateFormatter.format(line.convertedUnitPrice ?? 0)}
                  </Text>
                  {line.invoiceLineType !== "Comment" &&
                  (line.discountPercent ?? 0) > 0 ? (
                    <Text
                      className={themeClasses.mutedText}
                      style={{
                        ...lineDetail,
                        color: lightStyles.mutedText.color
                      }}
                    >
                      {formatPercent(-(line.discountPercent ?? 0), locale)}
                    </Text>
                  ) : null}
                </Column>
                <Column className="text-right align-top w-[100px]">
                  <Text style={lineTitle}>
                    {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 ${themeClasses.mutedText}`}
                  style={{ color: lightStyles.mutedText.color }}
                >
                  TOTAL
                </Text>
              </Column>
              <Column className={`border-l border-gray-200 h-12`}></Column>
              <Column className="w-[90px]">
                <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 ${themeClasses.text}`}
                    style={{ color: lightStyles.text.color }}
                  >
                    {company.name}
                  </Text>
                )}
              </Column>
            </Row>
          </Section>
        </DocumentCard>
      </Body>
    </EmailThemeProvider>
  );
};

export default SalesInvoiceEmail;