The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Refactor invoice PDF generation logic
Kiran Kd8a1c59816ce
diff --git a/apps/web/app/(ee)/app.dub.co/invoices/[invoiceId]/domain-renewal-invoice.tsx b/apps/web/app/(ee)/app.dub.co/invoices/[invoiceId]/domain-renewal-invoice.tsxnew file mode 100644index 0000000000..ad19b0be93--- /dev/null+++ b/apps/web/app/(ee)/app.dub.co/invoices/[invoiceId]/domain-renewal-invoice.tsx@@ -0,0 +1,325 @@+import { stripe } from "@/lib/stripe";+import { prisma } from "@dub/prisma";+import {+ currencyFormatter,+ DUB_WORDMARK,+ EU_COUNTRY_CODES,+ formatDate,+} from "@dub/utils";+import { Invoice, Project } from "@prisma/client";+import {+ Document,+ Image,+ Link,+ Page,+ renderToBuffer,+ Text,+ View,+} from "@react-pdf/renderer";+import { createTw } from "react-pdf-tailwind";+import Stripe from "stripe";++const tw = createTw({+ theme: {+ fontFamily: {+ //+ },+ },+});++export async function DomainRenewalInvoice({+ invoice,+ workspace,+}: {+ invoice: Invoice;+ workspace: Pick<Project, "id" | "name" | "stripeId">;+}) {+ const domains = await prisma.registeredDomain.findMany({+ where: {+ slug: {+ in: invoice.registeredDomains as string[],+ },+ },+ select: {+ slug: true,+ renewalFee: true,+ },+ });++ let customer: Stripe.Customer | null = null;++ if (workspace.stripeId) {+ try {+ const response = await stripe.customers.retrieve(workspace.stripeId, {+ expand: ["tax_ids"],+ });++ customer = response as Stripe.Customer;+ } catch (error) {+ console.error(error);+ }+ }++ const invoiceMetadata = [+ {+ label: "Invoice number",+ value: `#${invoice.number}`,+ },+ {+ label: "Date of issue",+ value: formatDate(invoice.createdAt, {+ month: "short",+ day: "2-digit",+ year: "numeric",+ timeZone: "UTC",+ }),+ },+ ];++ const EU_CUSTOMER =+ customer?.address?.country &&+ EU_COUNTRY_CODES.includes(customer.address.country);+ const AU_CUSTOMER =+ customer?.address?.country && customer.address.country === "AU";++ const { amount: chargeAmount, currency: chargeCurrency } =+ invoice.stripeChargeMetadata+ ? (invoice.stripeChargeMetadata as unknown as Stripe.Charge)+ : { amount: undefined, currency: undefined };++ const nonUsdTransactionDisplay =+ chargeAmount && chargeCurrency && chargeCurrency !== "usd"+ ? ` (${currencyFormatter(+ chargeAmount / 100,+ {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ },+ chargeCurrency.toUpperCase(),+ )})`+ : "";++ const invoiceSummaryDetails = [+ {+ label: "Invoice amount",+ value: currencyFormatter(invoice.amount / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ }),+ },+ {+ label: `Platform fees (${Math.round((invoice.fee / invoice.amount) * 100)}%)`,+ value: `${currencyFormatter(invoice.fee / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}`,+ },+ {+ label: "Invoice total",+ value: `${currencyFormatter(invoice.total / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}${nonUsdTransactionDisplay}`,+ },+ // if customer is in EU or AU, add VAT/GST reverse charge note+ ...(EU_CUSTOMER || AU_CUSTOMER+ ? [+ {+ label: `${AU_CUSTOMER ? "GST" : "VAT"} reverse charge`,+ value: "Tax to be paid on reverse charge basis.",+ },+ ]+ : []),+ ];++ // Get the first tax ID if available+ const primaryTaxId = customer?.tax_ids?.data?.[0];++ const addresses = [+ {+ title: "From",+ address: {+ name: "Dub Technologies, Inc.",+ line1: "2261 Market Street STE 5906",+ city: "San Francisco",+ state: "CA",+ postalCode: "94114",+ email: "[email protected]",+ },+ },+ {+ title: "Bill to",+ address: {+ companyName: workspace.name,+ name: customer?.shipping?.name,+ line1: customer?.shipping?.address?.line1,+ line2: customer?.shipping?.address?.line2,+ city: customer?.shipping?.address?.city,+ state: customer?.shipping?.address?.state,+ postalCode: customer?.shipping?.address?.postal_code,+ email: customer?.email,+ taxId: primaryTaxId ? `Tax ID: ${primaryTaxId.value}` : undefined,+ },+ },+ ];++ return await renderToBuffer(+ <Document>+ <Page size="A4" style={tw("p-20 bg-white")}>+ <View style={tw("flex-row justify-between items-center mb-10")}>+ <Image src={DUB_WORDMARK} style={tw("w-20 h-10")} />+ <View style={tw("text-right w-1/2")}>+ <Text style={tw("text-sm font-medium text-neutral-800")}>+ Dub Technologies Inc.+ </Text>+ <Text style={tw("text-sm text-neutral-500 ")}>[email protected]</Text>+ </View>+ </View>++ <View style={tw("flex-col gap-2 text-sm font-medium mb-10")}>+ {invoiceMetadata.map((row) => (+ <View style={tw("flex-row")} key={row.label}>+ <Text style={tw("text-neutral-500 w-1/5")}>{row.label}</Text>+ <Text style={tw("text-neutral-800 w-4/5")}>{row.value}</Text>+ </View>+ ))}+ </View>++ <View style={tw("flex-row justify-between mb-10 ")}>+ {addresses.map(({ title, address }, index) => {+ const cityStatePostal = [+ address.city,+ address.state,+ address.postalCode,+ ]+ .filter(Boolean)+ .join(", ");++ const records = [+ address.companyName,+ address.name,+ address.line1,+ address.line2,+ cityStatePostal,+ address.taxId,+ address.email,+ ].filter((record) => record && record.length > 0);++ return (+ <View style={tw("w-1/2")} key={index}>+ <Text+ style={tw(+ "text-sm font-medium text-neutral-800 leading-6 mb-2",+ )}+ >+ {title}+ </Text>+ {records.map((record, index) => (+ <Text+ style={tw("font-normal text-sm text-neutral-500 leading-6")}+ key={index}+ >+ {record}+ </Text>+ ))}+ </View>+ );+ })}+ </View>++ <View+ style={tw(+ "flex-row justify-between border border-neutral-200 rounded-xl mb-6",+ )}+ >+ <View style={tw("flex-col gap-2 w-1/2 p-4")}>+ <Text style={tw("text-neutral-500 font-normal text-sm")}>+ Domains+ </Text>+ <Text style={tw("text-neutral-800 font-medium text-[16px]")}>+ {domains.length}+ </Text>+ </View>++ <View+ style={tw(+ "flex-col items-start gap-2 border-l border-neutral-200 w-1/2 p-4",+ )}+ >+ <Text style={tw("text-neutral-500 font-normal text-sm")}>+ Total+ </Text>+ <Text style={tw("text-neutral-800 font-medium text-[16px]")}>+ {currencyFormatter(invoice.total / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}+ </Text>+ </View>+ </View>++ {domains.length > 0 && (+ <View style={tw("mb-6 border border-neutral-200 rounded-xl")}>+ <View style={tw("flex-row border-neutral-200 border-b")}>+ <Text+ style={tw("w-1/2 p-3.5 text-sm font-medium text-neutral-700")}+ >+ Domain+ </Text>+ <Text+ style={tw("w-1/2 p-3.5 text-sm font-medium text-neutral-700")}+ >+ Renewal Fee+ </Text>+ </View>++ {domains.map((domain, index) => (+ <View+ key={index}+ style={tw(+ `flex-row text-sm font-medium text-neutral-700 border-neutral-200 items-center ${index + 1 === domains.length ? "" : "border-b"}`,+ )}+ >+ <Text style={tw("w-1/2 p-3.5")}>{domain.slug}</Text>+ <Text style={tw("w-1/2 p-3.5")}>+ {currencyFormatter(domain.renewalFee / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}+ </Text>+ </View>+ ))}+ </View>+ )}++ <View+ style={tw(+ "flex-col gap-2 mb-10 p-4 border border-neutral-100 rounded-xl bg-neutral-50",+ )}+ >+ {invoiceSummaryDetails.map((row) => (+ <View style={tw("flex-row")} key={row.label}>+ <Text style={tw("text-neutral-500 text-sm font-medium w-2/5")}>+ {row.label}+ </Text>+ <Text style={tw("text-neutral-800 text-sm font-medium w-3/5")}>+ {row.value}+ </Text>+ </View>+ ))}+ </View>++ <Text style={tw("text-sm text-neutral-600 mt-6")}>+ If you have any questions, visit our support site at{" "}+ <Link href="https://dub.co/help" style={tw("text-neutral-900")}>+ https://dub.co/help+ </Link>{" "}+ or contact us at{" "}+ <Link href="mailto:[email protected]" style={tw("text-neutral-900")}>+ </Link>+ </Text>+ </Page>+ </Document>,+ );+}diff --git a/apps/web/app/(ee)/app.dub.co/invoices/[invoiceId]/partner-payout-invoice.tsx b/apps/web/app/(ee)/app.dub.co/invoices/[invoiceId]/partner-payout-invoice.tsxnew file mode 100644index 0000000000..3bc4ac2b48--- /dev/null+++ b/apps/web/app/(ee)/app.dub.co/invoices/[invoiceId]/partner-payout-invoice.tsx@@ -0,0 +1,396 @@+import { stripe } from "@/lib/stripe";+import { prisma } from "@dub/prisma";+import {+ currencyFormatter,+ DUB_WORDMARK,+ EU_COUNTRY_CODES,+ formatDate,+ OG_AVATAR_URL,+} from "@dub/utils";+import { Invoice, Project } from "@prisma/client";+import {+ Document,+ Image,+ Link,+ Page,+ renderToBuffer,+ Text,+ View,+} from "@react-pdf/renderer";+import { endOfMonth, startOfMonth } from "date-fns";+import { createTw } from "react-pdf-tailwind";+import Stripe from "stripe";++const tw = createTw({+ theme: {+ fontFamily: {+ //+ },+ },+});++export async function PartnerPayoutInvoice({+ invoice,+ workspace,+}: {+ invoice: Invoice;+ workspace: Pick<Project, "id" | "name" | "stripeId">;+}) {+ const payouts = await prisma.payout.findMany({+ where: {+ invoiceId: invoice.id,+ },+ select: {+ periodStart: true,+ periodEnd: true,+ amount: true,+ partner: {+ select: {+ name: true,+ image: true,+ },+ },+ },+ orderBy: {+ amount: "desc",+ },+ });++ let customer: Stripe.Customer | null = null;++ if (workspace.stripeId) {+ try {+ const response = await stripe.customers.retrieve(workspace.stripeId, {+ expand: ["tax_ids"],+ });+ customer = response as Stripe.Customer;+ } catch (error) {+ console.error(error);+ }+ }++ const { amount: chargeAmount, currency: chargeCurrency } =+ invoice.stripeChargeMetadata+ ? (invoice.stripeChargeMetadata as unknown as Stripe.Charge)+ : { amount: undefined, currency: undefined };++ const earliestPeriodStart = payouts.reduce(+ (acc, payout) => {+ if (!acc) return payout.periodStart;+ if (!payout.periodStart) return acc;+ return payout.periodStart < (acc as Date) ? payout.periodStart : acc;+ },+ null as Date | null,+ );++ const latestPeriodEnd = payouts.reduce(+ (acc, payout) => {+ if (!acc) return payout.periodEnd;+ if (!payout.periodEnd) return acc;+ return payout.periodEnd > (acc as Date) ? payout.periodEnd : acc;+ },+ null as Date | null,+ );++ const invoiceMetadata = [+ {+ label: "Invoice number",+ value: `#${invoice.number}`,+ },+ {+ label: "Date of issue",+ value: formatDate(invoice.createdAt, {+ month: "short",+ day: "2-digit",+ year: "numeric",+ timeZone: "UTC",+ }),+ },+ {+ label: "Payout period",+ value: `${formatDate(+ startOfMonth(earliestPeriodStart || invoice.createdAt),+ {+ month: "short",+ year: "numeric",+ },+ )} - ${formatDate(endOfMonth(latestPeriodEnd || invoice.createdAt), {+ month: "short",+ year: "numeric",+ })}`,+ },+ ];++ const EU_CUSTOMER =+ customer?.address?.country &&+ EU_COUNTRY_CODES.includes(customer.address.country);+ const AU_CUSTOMER =+ customer?.address?.country && customer.address.country === "AU";++ const nonUsdTransactionDisplay =+ chargeAmount && chargeCurrency && chargeCurrency !== "usd"+ ? ` (${currencyFormatter(+ chargeAmount / 100,+ {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ },+ chargeCurrency.toUpperCase(),+ )})`+ : "";++ const invoiceSummaryDetails = [+ {+ label: "Invoice amount",+ value: currencyFormatter(invoice.amount / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ }),+ },+ {+ label: `Platform fees (${Math.round((invoice.fee / invoice.amount) * 100)}%)`,+ value: `${currencyFormatter(invoice.fee / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}`,+ },+ {+ label: "Invoice total",+ value: `${currencyFormatter(invoice.total / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}${nonUsdTransactionDisplay}`,+ },+ // if customer is in EU or AU, add VAT/GST reverse charge note+ ...(EU_CUSTOMER || AU_CUSTOMER+ ? [+ {+ label: `${AU_CUSTOMER ? "GST" : "VAT"} reverse charge`,+ value: "Tax to be paid on reverse charge basis.",+ },+ ]+ : []),+ ];++ // Get the first tax ID if available+ const primaryTaxId = customer?.tax_ids?.data?.[0];++ const addresses = [+ {+ title: "From",+ address: {+ name: "Dub Technologies, Inc.",+ line1: "2261 Market Street STE 5906",+ city: "San Francisco",+ state: "CA",+ postalCode: "94114",+ email: "[email protected]",+ },+ },+ {+ title: "Bill to",+ address: {+ companyName: workspace.name,+ name: customer?.shipping?.name,+ line1: customer?.shipping?.address?.line1,+ line2: customer?.shipping?.address?.line2,+ city: customer?.shipping?.address?.city,+ state: customer?.shipping?.address?.state,+ postalCode: customer?.shipping?.address?.postal_code,+ email: customer?.email,+ taxId: primaryTaxId ? `Tax ID: ${primaryTaxId.value}` : undefined,+ },+ },+ ];++ return await renderToBuffer(+ <Document>+ <Page size="A4" style={tw("p-20 bg-white")}>+ <View style={tw("flex-row justify-between items-center mb-10")}>+ <Image src={DUB_WORDMARK} style={tw("w-20 h-10")} />+ <View style={tw("text-right w-1/2")}>+ <Text style={tw("text-sm font-medium text-neutral-800")}>+ Dub Technologies Inc.+ </Text>+ <Text style={tw("text-sm text-neutral-500 ")}>[email protected]</Text>+ </View>+ </View>++ <View style={tw("flex-col gap-2 text-sm font-medium mb-10")}>+ {invoiceMetadata.map((row) => (+ <View style={tw("flex-row")} key={row.label}>+ <Text style={tw("text-neutral-500 w-1/5")}>{row.label}</Text>+ <Text style={tw("text-neutral-800 w-4/5")}>{row.value}</Text>+ </View>+ ))}+ </View>++ <View style={tw("flex-row justify-between mb-10 ")}>+ {addresses.map(({ title, address }, index) => {+ const cityStatePostal = [+ address.city,+ address.state,+ address.postalCode,+ ]+ .filter(Boolean)+ .join(", ");++ const records = [+ address.companyName,+ address.name,+ address.line1,+ address.line2,+ cityStatePostal,+ address.taxId,+ address.email,+ ].filter((record) => record && record.length > 0);++ return (+ <View style={tw("w-1/2")} key={index}>+ <Text+ style={tw(+ "text-sm font-medium text-neutral-800 leading-6 mb-2",+ )}+ >+ {title}+ </Text>+ {records.map((record, index) => (+ <Text+ style={tw("font-normal text-sm text-neutral-500 leading-6")}+ key={index}+ >+ {record}+ </Text>+ ))}+ </View>+ );+ })}+ </View>++ <View+ style={tw(+ "flex-row justify-between border border-neutral-200 rounded-xl mb-6",+ )}+ >+ <View style={tw("flex-col gap-2 w-1/2 p-4")}>+ <Text style={tw("text-neutral-500 font-normal text-sm")}>+ Payouts+ </Text>+ <Text style={tw("text-neutral-800 font-medium text-[16px]")}>+ {payouts.length}+ </Text>+ </View>++ <View+ style={tw(+ "flex-col items-start gap-2 border-l border-neutral-200 w-1/2 p-4",+ )}+ >+ <Text style={tw("text-neutral-500 font-normal text-sm")}>+ Total+ </Text>+ <Text style={tw("text-neutral-800 font-medium text-[16px]")}>+ {currencyFormatter(invoice.total / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}+ </Text>+ </View>+ </View>++ {payouts.length > 0 && (+ <View style={tw("mb-6 border border-neutral-200 rounded-xl")}>+ <View style={tw("flex-row border-neutral-200 border-b")}>+ <Text+ style={tw("w-2/6 p-3.5 text-sm font-medium text-neutral-700")}+ >+ Partner+ </Text>+ <Text+ style={tw("w-2/6 p-3.5 text-sm font-medium text-neutral-700")}+ >+ Period+ </Text>+ <Text+ style={tw("w-1/6 p-3.5 text-sm font-medium text-neutral-700")}+ >+ Amount+ </Text>+ </View>++ {payouts.map((payout, index) => (+ <View+ key={index}+ style={tw(+ `flex-row text-sm font-medium text-neutral-700 border-neutral-200 items-center ${index + 1 === payouts.length ? "" : "border-b"}`,+ )}+ >+ <View style={tw("flex-row items-center gap-2 w-2/6 p-3.5")}>+ <Image+ src={+ payout.partner.image ??+ `${OG_AVATAR_URL}${payout.partner.name}`+ }+ style={tw("w-5 h-5 rounded-full")}+ />+ <Text>{payout.partner.name}</Text>+ </View>+ <Text style={tw("w-2/6 p-3.5")}>+ {payout.periodStart && payout.periodEnd ? (+ <>+ {formatDate(payout.periodStart, {+ month: "short",+ year:+ new Date(payout.periodStart).getFullYear() ===+ new Date(payout.periodEnd).getFullYear()+ ? undefined+ : "numeric",+ })}+ -{formatDate(payout.periodEnd, { month: "short" })}+ </>+ ) : (+ "-"+ )}+ </Text>+ <Text style={tw("w-1/6 p-3.5")}>+ {currencyFormatter(payout.amount / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}+ </Text>+ </View>+ ))}+ </View>+ )}++ <View+ style={tw(+ "flex-col gap-2 mb-10 p-4 border border-neutral-100 rounded-xl bg-neutral-50",+ )}+ >+ {invoiceSummaryDetails.map((row) => (+ <View style={tw("flex-row")} key={row.label}>+ <Text style={tw("text-neutral-500 text-sm font-medium w-2/5")}>+ {row.label}+ </Text>+ <Text style={tw("text-neutral-800 text-sm font-medium w-3/5")}>+ {row.value}+ </Text>+ </View>+ ))}+ </View>++ <Text style={tw("text-sm text-neutral-600 mt-6")}>+ If you have any questions, visit our support site at{" "}+ <Link href="https://dub.co/help" style={tw("text-neutral-900")}>+ https://dub.co/help+ </Link>{" "}+ or contact us at{" "}+ <Link href="mailto:[email protected]" style={tw("text-neutral-900")}>+ </Link>+ </Text>+ </Page>+ </Document>,+ );+}diff --git a/apps/web/app/(ee)/app.dub.co/invoices/[invoiceId]/route.tsx b/apps/web/app/(ee)/app.dub.co/invoices/[invoiceId]/route.tsxindex f071ab589d..345b08db3c 100644--- a/apps/web/app/(ee)/app.dub.co/invoices/[invoiceId]/route.tsx+++ b/apps/web/app/(ee)/app.dub.co/invoices/[invoiceId]/route.tsx@@ -1,37 +1,11 @@import { DubApiError } from "@/lib/api/errors";import { withSession } from "@/lib/auth";-import { stripe } from "@/lib/stripe";import { prisma } from "@dub/prisma";-import {- currencyFormatter,- DUB_WORDMARK,- EU_COUNTRY_CODES,- formatDate,- OG_AVATAR_URL,-} from "@dub/utils";-import {- Document,- Image,- Link,- Page,- renderToBuffer,- Text,- View,-} from "@react-pdf/renderer";-import { endOfMonth, startOfMonth } from "date-fns";-import { createTw } from "react-pdf-tailwind";-import Stripe from "stripe";+import { DomainRenewalInvoice } from "./domain-renewal-invoice";+import { PartnerPayoutInvoice } from "./partner-payout-invoice";export const dynamic = "force-dynamic";-const tw = createTw({- theme: {- fontFamily: {- // sans: ["Times-Bold"],- },- },-});-export const GET = withSession(async ({ session, params }) => {const { invoiceId } = params;@@ -40,22 +14,6 @@ export const GET = withSession(async ({ session, params }) => {id: invoiceId,},include: {- payouts: {- select: {- periodStart: true,- periodEnd: true,- amount: true,- partner: {- select: {- name: true,- image: true,- },- },- },- orderBy: {- amount: "desc",- },- },workspace: {select: {id: true,@@ -82,346 +40,26 @@ export const GET = withSession(async ({ session, params }) => {});}- let customer: Stripe.Customer | null = null;+ let pdf: Buffer | null = null;- if (invoice.workspace.stripeId) {- try {- const response = await stripe.customers.retrieve(- invoice.workspace.stripeId,- {- expand: ["tax_ids"],- },- );- customer = response as Stripe.Customer;- } catch (error) {- console.error(error);- }+ if (invoice.type === "partnerPayout") {+ pdf = await PartnerPayoutInvoice({+ invoice,+ workspace: invoice.workspace,+ });+ } else if (invoice.type === "domainRenewal") {+ pdf = await DomainRenewalInvoice({+ invoice,+ workspace: invoice.workspace,+ });}- const { amount: chargeAmount, currency: chargeCurrency } =- invoice.stripeChargeMetadata- ? (invoice.stripeChargeMetadata as unknown as Stripe.Charge)- : { amount: undefined, currency: undefined };-- const earliestPeriodStart = invoice.payouts.reduce(- (acc, payout) => {- if (!acc) return payout.periodStart;- if (!payout.periodStart) return acc;- return payout.periodStart < (acc as Date) ? payout.periodStart : acc;- },- null as Date | null,- );-- const latestPeriodEnd = invoice.payouts.reduce(- (acc, payout) => {- if (!acc) return payout.periodEnd;- if (!payout.periodEnd) return acc;- return payout.periodEnd > (acc as Date) ? payout.periodEnd : acc;- },- null as Date | null,- );-- const invoiceMetadata = [- {- label: "Invoice number",- value: `#${invoice.number}`,- },- {- label: "Date of issue",- value: formatDate(invoice.createdAt, {- month: "short",- day: "2-digit",- year: "numeric",- timeZone: "UTC",- }),- },- {- label: "Payout period",- value: `${formatDate(- startOfMonth(earliestPeriodStart || invoice.createdAt),- {- month: "short",- year: "numeric",- },- )} - ${formatDate(endOfMonth(latestPeriodEnd || invoice.createdAt), {- month: "short",- year: "numeric",- })}`,- },- ];-- const EU_CUSTOMER =- customer?.address?.country &&- EU_COUNTRY_CODES.includes(customer.address.country);- const AU_CUSTOMER =- customer?.address?.country && customer.address.country === "AU";-- const nonUsdTransactionDisplay =- chargeAmount && chargeCurrency && chargeCurrency !== "usd"- ? ` (${currencyFormatter(- chargeAmount / 100,- {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- },- chargeCurrency.toUpperCase(),- )})`- : "";-- const invoiceSummaryDetails = [- {- label: "Invoice amount",- value: currencyFormatter(invoice.amount / 100, {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- }),- },- {- label: `Platform fees (${Math.round((invoice.fee / invoice.amount) * 100)}%)`,- value: `${currencyFormatter(invoice.fee / 100, {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- })}`,- },- {- label: "Invoice total",- value: `${currencyFormatter(invoice.total / 100, {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- })}${nonUsdTransactionDisplay}`,- },- // if customer is in EU or AU, add VAT/GST reverse charge note- ...(EU_CUSTOMER || AU_CUSTOMER- ? [- {- label: `${AU_CUSTOMER ? "GST" : "VAT"} reverse charge`,- value: "Tax to be paid on reverse charge basis.",- },- ]- : []),- ];-- // Get the first tax ID if available- const primaryTaxId = customer?.tax_ids?.data?.[0];-- const addresses = [- {- title: "From",- address: {- name: "Dub Technologies, Inc.",- line1: "2261 Market Street STE 5906",- city: "San Francisco",- state: "CA",- postalCode: "94114",- email: "[email protected]",- },- },- {- title: "Bill to",- address: {- companyName: invoice.workspace.name,- name: customer?.shipping?.name,- line1: customer?.shipping?.address?.line1,- line2: customer?.shipping?.address?.line2,- city: customer?.shipping?.address?.city,- state: customer?.shipping?.address?.state,- postalCode: customer?.shipping?.address?.postal_code,- email: customer?.email,- taxId: primaryTaxId ? `Tax ID: ${primaryTaxId.value}` : undefined,- },- },- ];-- const pdf = await renderToBuffer(- <Document>- <Page size="A4" style={tw("p-20 bg-white")}>- <View style={tw("flex-row justify-between items-center mb-10")}>- <Image src={DUB_WORDMARK} style={tw("w-20 h-10")} />- <View style={tw("text-right w-1/2")}>- <Text style={tw("text-sm font-medium text-neutral-800")}>- Dub Technologies Inc.- </Text>- <Text style={tw("text-sm text-neutral-500 ")}>[email protected]</Text>- </View>- </View>-- <View style={tw("flex-col gap-2 text-sm font-medium mb-10")}>- {invoiceMetadata.map((row) => (- <View style={tw("flex-row")} key={row.label}>- <Text style={tw("text-neutral-500 w-1/5")}>{row.label}</Text>- <Text style={tw("text-neutral-800 w-4/5")}>{row.value}</Text>- </View>- ))}- </View>-- <View style={tw("flex-row justify-between mb-10 ")}>- {addresses.map(({ title, address }, index) => {- const cityStatePostal = [- address.city,- address.state,- address.postalCode,- ]- .filter(Boolean)- .join(", ");-- const records = [- address.companyName,- address.name,- address.line1,- address.line2,- cityStatePostal,- address.taxId,- address.email,- ].filter((record) => record && record.length > 0);-- return (- <View style={tw("w-1/2")} key={index}>- <Text- style={tw(- "text-sm font-medium text-neutral-800 leading-6 mb-2",- )}- >- {title}- </Text>- {records.map((record, index) => (- <Text- style={tw("font-normal text-sm text-neutral-500 leading-6")}- key={index}- >- {record}- </Text>- ))}- </View>- );- })}- </View>-- <View- style={tw(- "flex-row justify-between border border-neutral-200 rounded-xl mb-6",- )}- >- <View style={tw("flex-col gap-2 w-1/2 p-4")}>- <Text style={tw("text-neutral-500 font-normal text-sm")}>- Payouts- </Text>- <Text style={tw("text-neutral-800 font-medium text-[16px]")}>- {invoice.payouts.length}- </Text>- </View>-- <View- style={tw(- "flex-col items-start gap-2 border-l border-neutral-200 w-1/2 p-4",- )}- >- <Text style={tw("text-neutral-500 font-normal text-sm")}>- Total- </Text>- <Text style={tw("text-neutral-800 font-medium text-[16px]")}>- {currencyFormatter(invoice.total / 100, {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- })}- </Text>- </View>- </View>-- {invoice.payouts.length > 0 && (- <View style={tw("mb-6 border border-neutral-200 rounded-xl")}>- <View style={tw("flex-row border-neutral-200 border-b")}>- <Text- style={tw("w-2/6 p-3.5 text-sm font-medium text-neutral-700")}- >- Partner- </Text>- <Text- style={tw("w-2/6 p-3.5 text-sm font-medium text-neutral-700")}- >- Period- </Text>- <Text- style={tw("w-1/6 p-3.5 text-sm font-medium text-neutral-700")}- >- Amount- </Text>- </View>-- {invoice.payouts.map((payout, index) => (- <View- key={index}- style={tw(- `flex-row text-sm font-medium text-neutral-700 border-neutral-200 items-center ${index + 1 === invoice.payouts.length ? "" : "border-b"}`,- )}- >- <View style={tw("flex-row items-center gap-2 w-2/6 p-3.5")}>- <Image- src={- payout.partner.image ??- `${OG_AVATAR_URL}${payout.partner.name}`- }- style={tw("w-5 h-5 rounded-full")}- />- <Text>{payout.partner.name}</Text>- </View>- <Text style={tw("w-2/6 p-3.5")}>- {payout.periodStart && payout.periodEnd ? (- <>- {formatDate(payout.periodStart, {- month: "short",- year:- new Date(payout.periodStart).getFullYear() ===- new Date(payout.periodEnd).getFullYear()- ? undefined- : "numeric",- })}- -{formatDate(payout.periodEnd, { month: "short" })}- </>- ) : (- "-"- )}- </Text>- <Text style={tw("w-1/6 p-3.5")}>- {currencyFormatter(payout.amount / 100, {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- })}- </Text>- </View>- ))}- </View>- )}-- <View- style={tw(- "flex-col gap-2 mb-10 p-4 border border-neutral-100 rounded-xl bg-neutral-50",- )}- >- {invoiceSummaryDetails.map((row) => (- <View style={tw("flex-row")} key={row.label}>- <Text style={tw("text-neutral-500 text-sm font-medium w-2/5")}>- {row.label}- </Text>- <Text style={tw("text-neutral-800 text-sm font-medium w-3/5")}>- {row.value}- </Text>- </View>- ))}- </View>-- <Text style={tw("text-sm text-neutral-600 mt-6")}>- If you have any questions, visit our support site at{" "}- <Link href="https://dub.co/help" style={tw("text-neutral-900")}>- https://dub.co/help- </Link>{" "}- or contact us at{" "}- <Link href="mailto:[email protected]" style={tw("text-neutral-900")}>- </Link>- </Text>- </Page>- </Document>,- );+ if (!pdf) {+ throw new DubApiError({+ code: "bad_request",+ message: `Invoice ${invoiceId} not found in workspace.`,+ });+ }return new Response(pdf, {headers: {