Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.
TypeScript fintechinvoiceinvoice-generatorinvoice-pdfinvoice-templateinvoicesnextjsopen-sourcequotesreactreact-pdf-rendererself-hostedshadcn-uitailwindcsstypescript
feat: format item previews with the invoice's number format (#274)
Vlad Sazonaubb937b41fe63
diff --git a/e2e/default-invoice-template/default-invoice-template.test.ts b/e2e/default-invoice-template/default-invoice-template.test.tsindex 5d21f5a..a7ba192 100644--- a/e2e/default-invoice-template/default-invoice-template.test.ts+++ b/e2e/default-invoice-template/default-invoice-template.test.ts@@ -110,9 +110,10 @@ test.describe("Default Invoice Template", () => {const finalSection = page.getByTestId(`final-section`);- // Check that the total is correct (should be 3,300.00)+ // Check that the total is correct, written in the Polish number format the language+ // switch selected (the grouping space is a no-break one, which `\s` matches)const totalTextbox = page.getByRole("textbox", { name: "Total" });- await expect(totalTextbox).toHaveValue("3,300.00");+ await expect(totalTextbox).toHaveValue(/^3\s300,00$/);/** TEST PERSON AUTHORIZED TO RECEIVE FIELD */const personAuthorizedToReceiveFieldset = finalSection.getByRole("group", {@@ -489,25 +490,25 @@ test.describe("Default Invoice Template", () => {}),).toHaveValue("23");- // Verify calculations are correct+ // Verify calculations are correct, written in the French number formatawait expect(invoiceItemsSection.getByRole("textbox", {name: "Net Amount",exact: true,}),- ).toHaveValue("150.00");+ ).toHaveValue("150,00");await expect(invoiceItemsSection.getByRole("textbox", {name: "TVA Amount",exact: true,}),- ).toHaveValue("34.50");+ ).toHaveValue("34,50");await expect(invoiceItemsSection.getByRole("textbox", {name: "Pre-tax Amount",exact: true,}),- ).toHaveValue("184.50");+ ).toHaveValue("184,50");});test("should display and persist invoice number in different languages", async ({diff --git a/e2e/invoice-form.test.ts b/e2e/invoice-form.test.tsindex d86ff26..cdf36e5 100644--- a/e2e/invoice-form.test.ts+++ b/e2e/invoice-form.test.ts@@ -1285,7 +1285,7 @@ test.describe("Invoice Generator Page", () => {await expect(netAmountFormElement).toHaveText("€EUR");await expect(- invoiceItemsSection.getByText("Preview: €0.00 (zero EUR 00/100)"),+ invoiceItemsSection.getByText("Preview: 0.00 EUR (zero EUR 00/100)"),).toBeVisible();const currencyCombobox = page.getByRole("combobox", { name: "Currency" });@@ -1315,7 +1315,7 @@ test.describe("Invoice Generator Page", () => {await expect(invoiceItemsSection.getByText(- "Preview: $100.75 (one hundred USD 75/100)",+ "Preview: 100.75 USD (one hundred USD 75/100)",{exact: true,},diff --git a/e2e/invoice-templates-common/template-languages.test.ts b/e2e/invoice-templates-common/template-languages.test.tsindex dd24d90..1930624 100644--- a/e2e/invoice-templates-common/template-languages.test.ts+++ b/e2e/invoice-templates-common/template-languages.test.ts@@ -66,9 +66,27 @@ const INVOICE_ITEM = {quantity: "3",netPrice: "1234.56",// 3 * 1234.56- total: "3,703.68",+ total: 3703.68,} as const;+/**+ * The invoice total as the read-only "Total" field writes it: in the number format the+ * language switch selected.+ */+function expectedTotal(language: SupportedLanguages) {+ return (+ new Intl.NumberFormat(language, {+ // like the app, group a four-digit amount too, which Polish and Spanish don't by default+ useGrouping: "always",+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })+ .format(INVOICE_ITEM.total)+ // the app swaps the narrow no-break space French groups with for a regular no-break one+ .replaceAll(String.fromCodePoint(0x20_2f), String.fromCodePoint(0x00_a0))+ );+}+async function selectTemplate(page: Page, template: Template) {if (template !== "default") {await page@@ -191,9 +209,9 @@ test.describe("Invoice Template PDF languages", () => {}).fill(INVOICE_ITEM.netPrice);- // Check that the total is correct+ // Check that the total is correct, written in the selected language's number formatawait expect(page.getByRole("textbox", { name: "Total" })).toHaveValue(- INVOICE_ITEM.total,+ expectedTotal(language),);const { suggestedFilename } = await expectPdfScreenshot(page, {diff --git a/src/app/(main)/(app)/components/__tests__/changelog-update-popup.test.tsx b/src/app/(main)/(app)/components/__tests__/changelog-update-popup.test.tsxindex df441cb..ac8c76c 100644--- a/src/app/(main)/(app)/components/__tests__/changelog-update-popup.test.tsx+++ b/src/app/(main)/(app)/components/__tests__/changelog-update-popup.test.tsx@@ -96,9 +96,10 @@ describe("ChangelogUpdatePopup", () => {expect(popup).toHaveAttribute("data-layout", "dock");expect(popup).toHaveTextContent(`What's new: ${RELEASE_SUMMARY}`);- expect(- screen.getByRole("link", { name: "See what's new" }),- ).toHaveAttribute("href", "/changelog");+ expect(screen.getByRole("link", { name: "Learn more" })).toHaveAttribute(+ "href",+ "/changelog",+ );expect(screen.queryByRole("button", { name: "Continue" }),).not.toBeInTheDocument();diff --git a/src/app/(main)/(app)/components/changelog-update-popup.tsx b/src/app/(main)/(app)/components/changelog-update-popup.tsxindex 3326f1f..e489718 100644--- a/src/app/(main)/(app)/components/changelog-update-popup.tsx+++ b/src/app/(main)/(app)/components/changelog-update-popup.tsx@@ -243,7 +243,7 @@ export function ChangelogUpdatePopup({onDismiss();}}>- See what's new+ Learn more</Link></Button>)}@@ -332,7 +332,7 @@ function DockNotice({onDismiss();}}>- See what's new+ Learn more</Link>)}</p>diff --git a/src/app/(main)/(app)/components/invoice-form/index.tsx b/src/app/(main)/(app)/components/invoice-form/index.tsxindex ff8df2b..11aa147 100644--- a/src/app/(main)/(app)/components/invoice-form/index.tsx+++ b/src/app/(main)/(app)/components/invoice-form/index.tsx@@ -11,6 +11,7 @@ import {getAppStorageItem,setAppStorageItem,} from "@/app/(main)/(app)/utils/app-local-storage";+import { formatAmount } from "@/app/(main)/(app)/utils/format-amount";import { formatDateWithLocale } from "@/app/(main)/(app)/utils/format-date-with-locale";import { updateAppMetadata } from "@/app/(main)/(app)/utils/get-app-metadata";import {@@ -18,6 +19,7 @@ import {accordionSchema,invoiceSchema,PDF_DATA_LOCAL_STORAGE_KEY,+ resolveNumberFormatLocale,type AccordionState,type InvoiceData,type InvoiceItemData,@@ -328,6 +330,14 @@ export const InvoiceForm = memo(function InvoiceForm({const template = useWatch({ control, name: "template" });const taxLabelText = useWatch({ control, name: "taxLabelText" }) || "VAT";+ const selectedNumberFormatLocale = useWatch({+ control,+ name: "numberFormatLocale",+ });+ const numberFormatLocale = resolveNumberFormatLocale({+ language,+ numberFormatLocale: selectedNumberFormatLocale,+ });/*** Remove an invoice item from the form and trigger the form update@@ -532,6 +542,7 @@ export const InvoiceForm = memo(function InvoiceForm({append={append}template={template}taxLabelText={taxLabelText}+ numberFormatLocale={numberFormatLocale}getValues={getValues}/></AccordionContent>@@ -556,9 +567,9 @@ export const InvoiceForm = memo(function InvoiceForm({{...field}id={`total`}currency={currency}- value={field.value.toLocaleString("en-US", {- minimumFractionDigits: 2,- maximumFractionDigits: 2,+ value={formatAmount({+ amount: field.value,+ numberFormatLocale,})}/>);diff --git a/src/app/(main)/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsx b/src/app/(main)/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsxindex 78d33b3..bac424e 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsx@@ -13,7 +13,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { getInitialInvoiceData } from "@/app/constants";import type * as InvoiceSchema from "@/app/schema";-import type { InvoiceData } from "@/app/schema";+import type { InvoiceData, SupportedNumberFormatLocale } from "@/app/schema";import { TooltipProvider } from "@/components/ui/tooltip";import { MOCK_INVOICE_ITEM_DATA } from "@/utils/__tests__/data";import "@testing-library/jest-dom/vitest";@@ -57,6 +57,10 @@ interface InvoiceItemsTestHarnessProps {onRemove?: (index: number) => void;/** Overrides the name of the item at each given index. */itemNames?: Record<number, string>;+ /** The invoice's resolved number format, `en` unless a test picks another one. */+ numberFormatLocale?: SupportedNumberFormatLocale;+ /** The invoice's template, `default` unless a test picks another one. */+ template?: InvoiceData["template"];}function InvoiceItemsTestHarness({@@ -64,6 +68,8 @@ function InvoiceItemsTestHarness({append,onRemove = vi.fn(),itemNames,+ numberFormatLocale = "en",+ template = "default",}: InvoiceItemsTestHarnessProps) {const invoiceData = useMemo(() => {return {@@ -102,8 +108,9 @@ function InvoiceItemsTestHarness({errors={{}}currency="EUR"language="en"- template="default"+ template={template}taxLabelText="VAT"+ numberFormatLocale={numberFormatLocale}getValues={getValues}/></TooltipProvider>@@ -480,3 +487,96 @@ describe("InvoiceItems with several invoice items", () => {}});});++/** Previews print grouping spaces as no-break ones, so compare with plain spaces. */+function getPreviewText(pattern: RegExp) {+ return screen.getByText(pattern).textContent?.replaceAll("\u00A0", " ");+}++describe("InvoiceItems net price preview", () => {+ afterEach(() => {+ cleanup();+ });++ it.each([+ ["en", "default", "12,345.67 EUR"],+ ["de", "default", "12.345,67 EUR"],+ ["pl", "default", "12 345,67 EUR"],+ ["international", "default", "12 345.67 EUR"],+ ["en", "stripe", "€12,345.67"],+ ["de", "stripe", "12.345,67 €"],+ ] as const)(+ "writes the preview in the '%s' number format for the '%s' template",+ async (numberFormatLocale, template, expectedPreview) => {+ const user = userEvent.setup();++ renderInvoiceItems({ itemCount: 1, numberFormatLocale, template });++ const netPriceInput = screen.getByRole("spinbutton", {+ name: /^Net Price/,+ });+ await user.clear(netPriceInput);+ await user.type(netPriceInput, "12345.67");++ expect(getPreviewText(/^Preview: .*12/)).toContain(+ `Preview: ${expectedPreview} (`,+ );+ },+ );+});++describe("InvoiceItems amount preview", () => {+ afterEach(() => {+ cleanup();+ });++ it.each([+ ["en", "1,234.5"],+ ["de", "1.234,5"],+ ["pl", "1 234,5"],+ ["international", "1 234.5"],+ ] as const)(+ "writes the preview in the '%s' number format",+ async (numberFormatLocale, expectedPreview) => {+ const user = userEvent.setup();++ renderInvoiceItems({ itemCount: 1, numberFormatLocale });++ const amountInput = screen.getByRole("spinbutton", {+ name: /^Amount/,+ });+ await user.clear(amountInput);+ await user.type(amountInput, "1234.5");++ expect(getPreviewText(/^Preview: 1\D234/)).toBe(+ `Preview: ${expectedPreview}`,+ );+ },+ );+});++describe("InvoiceItems read-only amounts", () => {+ afterEach(() => {+ cleanup();+ });++ it.each([+ ["en", { netAmount: "201.00", vatAmount: "46.23", preTaxAmount: "247.23" }],+ ["de", { netAmount: "201,00", vatAmount: "46,23", preTaxAmount: "247,23" }],+ ] as const)(+ "writes the calculated amounts in the '%s' number format",+ (numberFormatLocale, expectedAmounts) => {+ renderInvoiceItems({ itemCount: 1, numberFormatLocale });++ expect(screen.getByRole("textbox", { name: "Net Amount" })).toHaveValue(+ expectedAmounts.netAmount,+ );+ expect(screen.getByRole("textbox", { name: "VAT Amount" })).toHaveValue(+ expectedAmounts.vatAmount,+ );+ expect(+ screen.getByRole("textbox", { name: "Pre-tax Amount" }),+ ).toHaveValue(expectedAmounts.preTaxAmount);+ },+ );+});diff --git a/src/app/(main)/(app)/components/invoice-form/sections/general-information.tsx b/src/app/(main)/(app)/components/invoice-form/sections/general-information.tsxindex c6d9184..4f09e20 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/general-information.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/general-information.tsx@@ -19,9 +19,8 @@ import {getDefaultInvoiceNumberLabel,INVOICE_PDF_TRANSLATIONS,} from "@/app/(main)/(app)/pdf-i18n-translations/pdf-translations";-import { formatAmount } from "@/app/(main)/(app)/utils/format-amount";-import { formatCurrency } from "@/app/(main)/(app)/utils/format-currency";import { formatTodayWithLocale } from "@/app/(main)/(app)/utils/format-date-with-locale";+import { formatMoneyForTemplate } from "@/app/(main)/(app)/utils/format-money-for-template";import {getCurrentMonthAndYear,isServicePeriodStartInCurrentMonth,@@ -33,9 +32,7 @@ import {getDateFormatsForLanguage,getDefaultDateFormat,getNumberFormatLocaleAfterLanguageChange,- type SupportedCurrencies,type SupportedNumberFormatLocale,- type SupportedTemplates,SUPPORTED_INVOICE_PDF_LANGUAGES,SUPPORTED_NUMBER_FORMAT_LOCALES,SUPPORTED_TEMPLATES,@@ -574,7 +571,7 @@ export const GeneralInformation = memo(function GeneralInformation({// the invoice's own total, written the way the selected template// writes it, so the picker shows the number this invoice's reader// will actually see- const preview = formatNumberFormatPreview({+ const preview = formatMoneyForTemplate({amount: invoiceTotal,currency,numberFormatLocale: supportedNumberFormatLocale,@@ -1221,34 +1218,3 @@ export const GeneralInformation = memo(function GeneralInformation({</div>);});--interface FormatNumberFormatPreviewArgs {- /** The invoice total, which is what the picker previews. */- amount: number;- /** The invoice's currency. */- currency: SupportedCurrencies;- /** The option being previewed. */- numberFormatLocale: SupportedNumberFormatLocale;- /** The template the invoice is rendered with. */- template: SupportedTemplates;-}--/**- * One option's preview, written the way its template writes money.- *- * The two templates present a currency differently -- the default one puts an ISO 4217 code- * next to the amount, the Stripe one puts the symbol wherever the locale puts it -- and a- * preview that showed the wrong one would promise a PDF the invoice is not going to be.- */-function formatNumberFormatPreview({- amount,- currency,- numberFormatLocale,- template,-}: FormatNumberFormatPreviewArgs) {- if (template === "default") {- return `${formatAmount({ amount, numberFormatLocale })} ${currency}`;- }-- return formatCurrency({ amount, currency, numberFormatLocale });-}diff --git a/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsx b/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsxindex 5b262d7..fe588b2 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsx@@ -15,10 +15,13 @@ import {type ItemPendingDeletion,} from "@/app/(main)/(app)/components/invoice-form/sections/components/delete-invoice-item-dialog";import { INVOICE_PDF_TRANSLATIONS } from "@/app/(main)/(app)/pdf-i18n-translations/pdf-translations";+import { formatAmount } from "@/app/(main)/(app)/utils/format-amount";+import { formatMoneyForTemplate } from "@/app/(main)/(app)/utils/format-money-for-template";import {type InvoiceData,type SupportedCurrencies,type SupportedLanguages,+ type SupportedNumberFormatLocale,MAX_INVOICE_ITEMS,} from "@/app/schema";import { Legend } from "@/components/legend";@@ -51,6 +54,8 @@ interface InvoiceItemsSettingsProps {language: SupportedLanguages;template: InvoiceData["template"];taxLabelText: string;+ /** The invoice's number format, already resolved against its language. */+ numberFormatLocale: SupportedNumberFormatLocale;getValues: UseFormGetValues<InvoiceData>;}@@ -64,6 +69,7 @@ export const InvoiceItems = memo(function InvoiceItems({append,template,taxLabelText,+ numberFormatLocale,getValues,}: InvoiceItemsSettingsProps) {const [itemPendingDeletion, setItemPendingDeletion] =@@ -301,11 +307,12 @@ export const InvoiceItems = memo(function InvoiceItems({render={({ field }) => {// oxlint-disable-next-line typescript/no-unnecessary-type-conversion -- `<Input type="number">` gives back a string at runtime, the schema type says numberconst fieldValueNumber = Number(field.value) || 0;- const previewFormattedValue =- fieldValueNumber.toLocaleString("en-US", {- style: "decimal",- maximumFractionDigits: 3,- });+ const previewFormattedValue = formatAmount({+ amount: fieldValueNumber,+ numberFormatLocale,+ minimumFractionDigits: 0,+ maximumFractionDigits: 3,+ });return (<>@@ -444,13 +451,14 @@ export const InvoiceItems = memo(function InvoiceItems({// oxlint-disable-next-line typescript/no-unnecessary-type-conversion -- `<Input type="number">` gives back a string at runtime, the schema type says numberconst fieldValueNumber = Number(field.value) || 0;- const previewFormattedValue =- fieldValueNumber.toLocaleString("en-US", {- style: "currency",- currency: currency,- minimumFractionDigits: 2,- maximumFractionDigits: 2,- });+ // written in the invoice's number format and the way its template+ // shows the currency, so the preview matches the PDF+ const previewFormattedValue = formatMoneyForTemplate({+ amount: fieldValueNumber,+ currency,+ numberFormatLocale,+ template,+ });const previewAmountInWords = getAmountInWords({amount: fieldValueNumber,@@ -651,9 +659,9 @@ export const InvoiceItems = memo(function InvoiceItems({{...field}id={`itemNetAmount${index}`}currency={currency}- value={field.value.toLocaleString("en-US", {- minimumFractionDigits: 2,- maximumFractionDigits: 2,+ value={formatAmount({+ amount: field.value,+ numberFormatLocale,})}className={inputErrorClassName(!!errors.items?.[index]?.netAmount,@@ -725,9 +733,9 @@ export const InvoiceItems = memo(function InvoiceItems({{...field}id={`itemVatAmount${index}`}currency={currency}- value={field.value.toLocaleString("en-US", {- minimumFractionDigits: 2,- maximumFractionDigits: 2,+ value={formatAmount({+ amount: field.value,+ numberFormatLocale,})}className={inputErrorClassName(!!errors.items?.[index]?.vatAmount,@@ -800,9 +808,9 @@ export const InvoiceItems = memo(function InvoiceItems({{...field}id={`itemPreTaxAmount${index}`}currency={currency}- value={field.value.toLocaleString("en-US", {- minimumFractionDigits: 2,- maximumFractionDigits: 2,+ value={formatAmount({+ amount: field.value,+ numberFormatLocale,})}className={inputErrorClassName(!!errors.items?.[index]?.preTaxAmount,diff --git a/src/app/(main)/(app)/utils/format-money-for-template.ts b/src/app/(main)/(app)/utils/format-money-for-template.tsnew file mode 100644index 0000000..96ffe75--- /dev/null+++ b/src/app/(main)/(app)/utils/format-money-for-template.ts@@ -0,0 +1,39 @@+import type {+ SupportedCurrencies,+ SupportedNumberFormatLocale,+ SupportedTemplates,+} from "@/app/schema";++import { formatAmount } from "./format-amount";+import { formatCurrency } from "./format-currency";++interface FormatMoneyForTemplateArgs {+ /** The amount to write. */+ amount: number;+ /** The invoice's currency. */+ currency: SupportedCurrencies;+ /** The locale, already resolved against the invoice's language. */+ numberFormatLocale: SupportedNumberFormatLocale;+ /** The template the invoice is rendered with. */+ template: SupportedTemplates;+}++/**+ * An amount written the way the invoice's template writes money, for the form's previews.+ *+ * The two templates present a currency differently -- the default one puts an ISO 4217 code+ * next to the amount, the Stripe one puts the symbol wherever the locale puts it -- and a+ * preview that showed the wrong one would promise a PDF the invoice is not going to be.+ */+export function formatMoneyForTemplate({+ amount,+ currency,+ numberFormatLocale,+ template,+}: FormatMoneyForTemplateArgs) {+ if (template === "default") {+ return `${formatAmount({ amount, numberFormatLocale })} ${currency}`;+ }++ return formatCurrency({ amount, currency, numberFormatLocale });+}