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
fix: stripe custom invoice number label, improvements to buttons, etc (#256)
Vlad Sazonau912b237576da
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.ymlindex 50bc829..64e4498 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e.yml@@ -78,6 +78,7 @@ jobs:- name: 🔍 Get PR URLid: pr-url+ if: always()env:GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}GH_REPOSITORY: ${{ github.repository }}diff --git a/e2e/default-invoice-template/default-invoice-template.test.ts b/e2e/default-invoice-template/default-invoice-template.test.tsindex 7b0314a..6c1676b 100644--- a/e2e/default-invoice-template/default-invoice-template.test.ts+++ b/e2e/default-invoice-template/default-invoice-template.test.ts@@ -26,7 +26,7 @@ test.describe("Default Invoice Template", () => {downloadDir,}) => {const downloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});// Wait for download button to be visible and enabledawait expect(downloadPdfEnglishButton).toBeVisible();@@ -93,7 +93,7 @@ test.describe("Default Invoice Template", () => {// Wait for the download button to be visible and enabled for Stripe templateconst downloadPdfStripeButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfStripeButton).toBeVisible();@@ -153,7 +153,7 @@ test.describe("Default Invoice Template", () => {// we wait until this button is visible and enabled, that means that the PDF preview has been regeneratedconst downloadPdfPolishButton = page.getByRole("link", {- name: "Download PDF in Polish",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfPolishButton).toBeVisible();@@ -335,7 +335,7 @@ test.describe("Default Invoice Template", () => {// Wait for the download button to be visible and enabled for Stripe templateconst downloadPdfStripeButton = page.getByRole("link", {- name: "Download PDF in Polish",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfStripeButton).toBeVisible();@@ -521,7 +521,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(700);const downloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfEnglishButton).toBeVisible();@@ -574,7 +574,7 @@ test.describe("Default Invoice Template", () => {// Wait for the download button to be ready after navigationconst newDownloadPdfButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(newDownloadPdfButton).toBeVisible();await expect(newDownloadPdfButton).toBeEnabled();@@ -606,7 +606,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(700);const downloadPdfStripeButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfStripeButton).toBeVisible();@@ -663,7 +663,7 @@ test.describe("Default Invoice Template", () => {// Download button in English is visible and enabledconst downloadPdfButtonEnglish = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});// Wait for download button to be visibleawait expect(downloadPdfButtonEnglish).toBeVisible();@@ -699,7 +699,9 @@ test.describe("Default Invoice Template", () => {name: "Value",});- await invoiceNumberLabelInput.fill("MOBILE-TEST-001:");+ const INVOICE_NUMBER_LABEL = "INVOICE NUMBER MOBILE TEST:";++ await invoiceNumberLabelInput.fill(INVOICE_NUMBER_LABEL);await invoiceNumberValueInput.fill("2/05-2024");const finalSection = page.getByTestId("final-section");@@ -745,7 +747,7 @@ test.describe("Default Invoice Template", () => {// we wait until this button is visible and enabled, that means that the PDF preview has been regeneratedconst downloadPdfFrenchBtn = page.getByRole("link", {- name: "Download PDF in French",+ name: /^(Download PDF|Download PDF in .+)$/,});// Wait for download button to be visible and enabledawait expect(downloadPdfFrenchBtn).toBeVisible();@@ -834,7 +836,7 @@ test.describe("Default Invoice Template", () => {).toBeHidden();// Verify form data persists- await expect(invoiceNumberLabelInput).toHaveValue("MOBILE-TEST-001:");+ await expect(invoiceNumberLabelInput).toHaveValue(INVOICE_NUMBER_LABEL);await expect(invoiceNumberValueInput).toHaveValue("2/05-2024");await expect(@@ -907,6 +909,9 @@ test.describe("Default Invoice Template", () => {name: "Invoice Template",});await expect(templateSelect).toHaveValue("stripe");+ await expect(invoiceNumberLabelInput).toHaveValue(+ INVOICE_PDF_TRANSLATIONS.fr.stripe.invoice,+ );const newFinalSection = page.getByTestId(`final-section`);@@ -922,7 +927,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(700);const downloadPdfStripeButton = page.getByRole("link", {- name: "Download PDF in French",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfStripeButton).toBeVisible();@@ -1012,20 +1017,20 @@ test.describe("Default Invoice Template", () => {await invoiceNumberLabelInput.fill("Faktura TEST:");// check that warning message appears- const switchToDefaultFormatButton = page.getByRole("button", {- name: `Switch to default label ("Faktura nr:")`,+ const resetToDefaultFormatButton = page.getByRole("button", {+ name: `Reset to default ("Faktura nr:")`,});- await expect(switchToDefaultFormatButton).toBeVisible();+ await expect(resetToDefaultFormatButton).toBeVisible();- // switch to default format- await switchToDefaultFormatButton.click();+ // reset to default format+ await resetToDefaultFormatButton.click();// check that the invoice number is updated to the default formatawait expect(invoiceNumberLabelInput).toHaveValue(`Faktura nr:`);- // check that the switch to default format button is hidden- await expect(switchToDefaultFormatButton).toBeHidden();+ // check that the reset to default format button is hidden+ await expect(resetToDefaultFormatButton).toBeHidden();// fill once again the invoice numberawait invoiceNumberLabelInput.fill("Faktura TEST:");@@ -1056,7 +1061,7 @@ test.describe("Default Invoice Template", () => {// Verify that the download PDF button is visible after page reloadconst downloadPdfPlButton = page.getByRole("link", {- name: "Download PDF in Polish",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfPlButton).toBeVisible();@@ -1089,7 +1094,7 @@ test.describe("Default Invoice Template", () => {await expect(page.getByRole("button", {- name: `Switch to default label ("Fatura N°:")`,+ name: `Reset to default ("Fatura N°:")`,}),).toBeVisible();@@ -1109,7 +1114,7 @@ test.describe("Default Invoice Template", () => {// we wait until this button is visible and enabled, that means that the PDF preview has been regeneratedconst downloadPdfPtButton = page.getByRole("link", {- name: "Download PDF in Portuguese",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfPtButton).toBeVisible();@@ -1175,6 +1180,22 @@ test.describe("Default Invoice Template", () => {});await expect(templateSelect).toHaveValue("stripe");+ // Switching templates replaces a custom label with the new template's+ // localized default.+ await expect(newInvoiceNumberLabelInput).toHaveValue(+ INVOICE_PDF_TRANSLATIONS.pt.stripe.invoice,+ );++ // Language changes use the Stripe heading instead of the default+ // template's invoice-number label.+ await newLanguageSelect.selectOption("en");+ await expect(newInvoiceNumberLabelInput).toHaveValue("Invoice");++ await newLanguageSelect.selectOption("pt");+ await expect(newInvoiceNumberLabelInput).toHaveValue("Fatura");++ await newInvoiceNumberLabelInput.fill("Fatura CUSTOM LABEL N°:");+// Currency should be CHF after navigating back to the previous pageconst currencyCombobox3 = page.getByRole("combobox", { name: "Currency" });await expect(currencyCombobox3).toContainText("CHF");@@ -1196,7 +1217,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(700);const downloadPdfStripeButton = page.getByRole("link", {- name: "Download PDF in Portuguese",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfStripeButton).toBeVisible();@@ -1294,7 +1315,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(700);const downloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfEnglishButton).toBeVisible();@@ -1404,7 +1425,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(700);const newDownloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});// Download the PDF again@@ -1520,7 +1541,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(700);const downloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfEnglishButton).toBeVisible();@@ -1596,7 +1617,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(800);const downloadPDFButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPDFButton).toBeVisible();@@ -1673,7 +1694,7 @@ test.describe("Default Invoice Template", () => {// Download PDF with Stripe template + logoconst stripeDownloadPDFButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(stripeDownloadPDFButton).toBeVisible();@@ -1780,7 +1801,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(700);const downloadPdfButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfButton).toBeVisible();await expect(downloadPdfButton).toBeEnabled();@@ -1900,7 +1921,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(700);const newDownloadPdfButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(newDownloadPdfButton).toBeVisible();await expect(newDownloadPdfButton).toBeEnabled();@@ -1981,10 +2002,10 @@ test.describe("Default Invoice Template", () => {CUSTOM_SERVICE_PERIOD_LABEL,);- // Check that "Switch to default label ("Service period")" text is displayed+ // Check that the reset helper is displayedawait expect(servicePeriodFieldset.getByRole("button", {- name: 'Switch to default label ("Service period")',+ name: 'Reset to default ("Service period")',}),).toBeVisible();@@ -2009,7 +2030,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(700);const downloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfEnglishButton).toBeVisible();@@ -2102,7 +2123,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(700);const newDownloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});const [downloadWithoutServicePeriod] = await Promise.all([@@ -2164,10 +2185,10 @@ test.describe("Default Invoice Template", () => {CUSTOM_DATE_OF_SALES_LABEL,);- // Check that "Switch to default label ("Date of sales")" text is displayed+ // Check that the reset helper is displayedawait expect(servicePeriodFieldset.getByRole("button", {- name: 'Switch to default label ("Date of sales/of executing the service")',+ name: 'Reset to default ("Date of sales/of executing the service")',}),).toBeVisible();@@ -2186,7 +2207,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(700);const downloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfEnglishButton).toBeVisible();@@ -2271,7 +2292,7 @@ test.describe("Default Invoice Template", () => {await page.waitForTimeout(700);const newDownloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});const [downloadWithoutDateOfSales] = await Promise.all([diff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-Desktop-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-Desktop-Chrome-darwin.pngindex 56c9ca3..9f89aa7 100644Binary files a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-Desktop-Chrome-darwin.png and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-Desktop-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-Mobile-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-Mobile-Chrome-darwin.pngindex f59c196..69f49b3 100644Binary files a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-Mobile-Chrome-darwin.png and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-Mobile-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-Mobile-Safari-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-Mobile-Safari-darwin.pngindex 7d2967d..77da71f 100644Binary files a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-Mobile-Safari-darwin.png and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-Mobile-Safari-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-stripe-template-Desktop-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-stripe-template-Desktop-Chrome-darwin.pngindex f686cf4..c902a9c 100644Binary files a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-stripe-template-Desktop-Chrome-darwin.png and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-stripe-template-Desktop-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-stripe-template-Mobile-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-stripe-template-Mobile-Chrome-darwin.pngindex a91da25..790db77 100644Binary files a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-stripe-template-Mobile-Chrome-darwin.png and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/completes-full-invoice-flow-on-mobile-stripe-template-Mobile-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/should-display-and-persist-invoice-number-in-different-languages-stripe-template-Desktop-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/should-display-and-persist-invoice-number-in-different-languages-stripe-template-Desktop-Chrome-darwin.pngindex 4a0b821..ce24a14 100644Binary files a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/should-display-and-persist-invoice-number-in-different-languages-stripe-template-Desktop-Chrome-darwin.png and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/should-display-and-persist-invoice-number-in-different-languages-stripe-template-Desktop-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/should-display-and-persist-invoice-number-in-different-languages-stripe-template-Mobile-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/should-display-and-persist-invoice-number-in-different-languages-stripe-template-Mobile-Chrome-darwin.pngindex a737ecf..33b550f 100644Binary files a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/should-display-and-persist-invoice-number-in-different-languages-stripe-template-Mobile-Chrome-darwin.png and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/should-display-and-persist-invoice-number-in-different-languages-stripe-template-Mobile-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/should-display-and-persist-invoice-number-in-different-languages-stripe-template-Mobile-Safari-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/should-display-and-persist-invoice-number-in-different-languages-stripe-template-Mobile-Safari-darwin.pngindex f2945c7..9943585 100644Binary files a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/should-display-and-persist-invoice-number-in-different-languages-stripe-template-Mobile-Safari-darwin.png and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/should-display-and-persist-invoice-number-in-different-languages-stripe-template-Mobile-Safari-darwin.png differdiff --git a/e2e/generate-invoice-link.test.ts b/e2e/generate-invoice-link.test.tsindex c8515f5..0ddcd48 100644--- a/e2e/generate-invoice-link.test.ts+++ b/e2e/generate-invoice-link.test.ts@@ -37,7 +37,7 @@ const TEST_BUYER_DATA = {notes: "This is a BUYER test note",} as const satisfies BuyerData;-test.describe("Generate Invoice Link", () => {+test.describe("Generate Invoice Link (Get link)", () => {test.beforeEach(async ({ page }) => {await page.goto("/");@@ -175,7 +175,7 @@ test.describe("Generate Invoice Link", () => {await page.waitForTimeout(700);// Generate share link- await page.getByRole("button", { name: "Generate invoice link" }).click();+ await page.getByRole("button", { name: "Get link" }).click();// Wait for URL to update with share dataawait page.waitForURL((url) => url.searchParams.has("data"));@@ -330,7 +330,9 @@ test.describe("Generate Invoice Link", () => {// ensure page is loadedawait expect(- page.getByRole("link", { name: "Download PDF in English" }),+ page.getByRole("link", {+ name: /^(Download PDF|Download PDF in .+)$/,+ }),).toBeVisible();// Verify error toast appears@@ -374,7 +376,9 @@ test.describe("Generate Invoice Link", () => {// ensure page content is displayedawait expect(- page.getByRole("link", { name: "Download PDF in English" }),+ page.getByRole("link", {+ name: /^(Download PDF|Download PDF in .+)$/,+ }),).toBeVisible();});@@ -389,7 +393,9 @@ test.describe("Generate Invoice Link", () => {/* Ensure page content is displayed */await expect(- page.getByRole("link", { name: "Download PDF in English" }),+ page.getByRole("link", {+ name: /^(Download PDF|Download PDF in .+)$/,+ }),).toBeVisible();/* VERIFY ERROR TOAST IS SHOWN */@@ -438,9 +444,7 @@ test.describe("Generate Invoice Link", () => {).toBeVisible();await expect(- page.getByText(- "Click 'Generate invoice link' to create a new shareable link.",- ),+ page.getByText("Click 'Get link' to create a new shareable link."),).toBeVisible();// Wait for URL to be cleared and verify@@ -449,7 +453,9 @@ test.describe("Generate Invoice Link", () => {/* Ensure page content is displayed */await expect(- page.getByRole("link", { name: "Download PDF in English" }),+ page.getByRole("link", {+ name: /^(Download PDF|Download PDF in .+)$/,+ }),).toBeVisible();});@@ -488,6 +494,7 @@ test.describe("Generate Invoice Link", () => {name: "Invoice Number",});+ // Old URLs load without ?template=, so the stored default-template label is kept.await expect(invoiceNumberFieldset.getByRole("textbox", { name: "Label" }),).toHaveValue("Faktura nr:");@@ -549,9 +556,10 @@ test.describe("Generate Invoice Link", () => {name: "Invoice Number",});+ // Compressed URLs include ?template=stripe, so the label migrates to the Stripe default.await expect(newInvoiceNumberFieldset.getByRole("textbox", { name: "Label" }),- ).toHaveValue("Faktura nr:");+ ).toHaveValue("Faktura");await expect(newInvoiceNumberFieldset.getByRole("textbox", { name: "Value" }),@@ -644,7 +652,7 @@ test.describe("Generate Invoice Link", () => {await page.waitForTimeout(700);// Generate share link- await page.getByRole("button", { name: "Generate invoice link" }).click();+ await page.getByRole("button", { name: "Get link" }).click();// Verify the share invoice link description toast appears after generating the linkconst toast = page.getByTestId("share-invoice-link-description-toast");@@ -936,7 +944,7 @@ test.describe("Generate Invoice Link", () => {await page.waitForTimeout(700);// Try to generate share link - should fail with error toast- await page.getByRole("button", { name: "Generate invoice link" }).click();+ await page.getByRole("button", { name: "Get link" }).click();// Verify error toast appears with correct textawait expect(diff --git a/e2e/invoice-form.test.ts b/e2e/invoice-form.test.tsindex ef65260..7ca51e8 100644--- a/e2e/invoice-form.test.ts+++ b/e2e/invoice-form.test.ts@@ -110,11 +110,11 @@ test.describe("Invoice Generator Page", () => {).toBeVisible();// Check main action buttons+ await expect(page.getByRole("button", { name: "Get link" })).toBeVisible();await expect(- page.getByRole("button", { name: "Generate invoice link" }),- ).toBeVisible();- await expect(- page.getByRole("link", { name: "Download PDF in English" }),+ page.getByRole("link", {+ name: /^(Download PDF|Download PDF in .+)$/,+ }),).toBeVisible();const shareFeedbackLink = header.getByRole("link", {@@ -198,11 +198,11 @@ test.describe("Invoice Generator Page", () => {await expect(githubStarCtaButton).toHaveAttribute("target", "_blank");// Verify buttons are enabled+ await expect(page.getByRole("button", { name: "Get link" })).toBeEnabled();await expect(- page.getByRole("button", { name: "Generate invoice link" }),- ).toBeEnabled();- await expect(- page.getByRole("link", { name: "Download PDF in English" }),+ page.getByRole("link", {+ name: /^(Download PDF|Download PDF in .+)$/,+ }),).toBeEnabled();});@@ -707,13 +707,13 @@ test.describe("Invoice Generator Page", () => {await servicePeriodLabelInput.fill("My custom period");await expect(servicePeriodFieldset.getByRole("button", {- name: `Switch to default label ("${INVOICE_PDF_TRANSLATIONS.pl.servicePeriod}")`,+ name: `Reset to default ("${INVOICE_PDF_TRANSLATIONS.pl.servicePeriod}")`,}),).toBeVisible();await servicePeriodFieldset.getByRole("button", {- name: `Switch to default label ("${INVOICE_PDF_TRANSLATIONS.pl.servicePeriod}")`,+ name: `Reset to default ("${INVOICE_PDF_TRANSLATIONS.pl.servicePeriod}")`,}).click();@@ -1747,7 +1747,7 @@ test.describe("Invoice Generator Page", () => {await expect(page.getByLabel("Payment Due")).toHaveValue("2025-12-15");});- test("allows switching service period PDF label to default from inline helper", async ({+ test("allows resetting service period PDF label from the inline helper", async ({page,}) => {const generalInfoSection = page.getByRole("region", {@@ -1760,21 +1760,21 @@ test.describe("Invoice Generator Page", () => {name: "Service period PDF label",});const defaultLabel = INVOICE_PDF_TRANSLATIONS.en.servicePeriod;- const switchToDefaultButton = servicePeriodFieldset.getByRole("button", {- name: `Switch to default label ("${defaultLabel}")`,+ const resetToDefaultButton = servicePeriodFieldset.getByRole("button", {+ name: `Reset to default ("${defaultLabel}")`,});await servicePeriodLabelInput.fill("Custom service period label");- await expect(switchToDefaultButton).toBeVisible();+ await expect(resetToDefaultButton).toBeVisible();- await switchToDefaultButton.click();+ await resetToDefaultButton.click();await expect(servicePeriodLabelInput).toHaveValue(defaultLabel);- await expect(switchToDefaultButton).toBeHidden();+ await expect(resetToDefaultButton).toBeHidden();});- test("allows switching date of sales PDF label to default from inline helper", async ({+ test("allows resetting date of sales PDF label from the inline helper", async ({page,}) => {const generalInfoSection = page.getByRole("region", {@@ -1787,18 +1787,18 @@ test.describe("Invoice Generator Page", () => {name: "Date of sales PDF label",});const defaultLabel = INVOICE_PDF_TRANSLATIONS.en.dateOfService;- const switchToDefaultButton = servicePeriodFieldset.getByRole("button", {- name: `Switch to default label ("${defaultLabel}")`,+ const resetToDefaultButton = servicePeriodFieldset.getByRole("button", {+ name: `Reset to default ("${defaultLabel}")`,});await dateOfServiceLabelInput.fill("Custom date of sales label");- await expect(switchToDefaultButton).toBeVisible();+ await expect(resetToDefaultButton).toBeVisible();- await switchToDefaultButton.click();+ await resetToDefaultButton.click();await expect(dateOfServiceLabelInput).toHaveValue(defaultLabel);- await expect(switchToDefaultButton).toBeHidden();+ await expect(resetToDefaultButton).toBeHidden();});test("allows setting a partial service period", async ({ page }) => {diff --git a/e2e/stripe-invoice-template/share-logic.test.ts b/e2e/stripe-invoice-template/share-logic.test.tsindex 99c45d2..e1abfb5 100644--- a/e2e/stripe-invoice-template/share-logic.test.ts+++ b/e2e/stripe-invoice-template/share-logic.test.ts@@ -25,7 +25,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {// Verify share button is still enabled (no logo uploaded)const shareButton = page.getByRole("button", {- name: "Generate invoice link",+ name: "Get link",});await expect(shareButton).toBeVisible();await expect(shareButton).toBeEnabled();@@ -131,7 +131,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {// Verify share button is disabledconst shareButton = page.getByRole("button", {- name: "Generate invoice link",+ name: "Get link",});await expect(shareButton).toHaveAttribute("data-disabled", "true");@@ -173,7 +173,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {// Verify share button is disabledconst shareButton = page.getByRole("button", {- name: "Generate invoice link",+ name: "Get link",});await expect(shareButton).toHaveAttribute("data-disabled", "true");@@ -225,7 +225,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {// Start with default template and verify share button is enabledconst shareButton = page.getByRole("button", {- name: "Generate invoice link",+ name: "Get link",});await expect(shareButton).toBeEnabled();@@ -280,7 +280,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {).toBeVisible();const shareButton = page.getByRole("button", {- name: "Generate invoice link",+ name: "Get link",});// Verify share button is disabled@@ -329,7 +329,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {// Verify share button is visible and enabled in mobileconst shareButton = page.getByRole("button", {- name: "Generate invoice link",+ name: "Get link",});await expect(shareButton).toBeVisible();await expect(shareButton).toBeEnabled();@@ -396,7 +396,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {// Click share button — should show error toast because form has validation errorsconst shareButton = page.getByRole("button", {- name: "Generate invoice link",+ name: "Get link",});await shareButton.click();diff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts b/e2e/stripe-invoice-template/stripe-invoice-template.test.tsindex 7223075..8f6f18e 100644--- a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts+++ b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts@@ -4,6 +4,7 @@ import {STRIPE_DEFAULT_DATE_FORMAT,type InvoiceData,} from "@/app/schema";+import { INITIAL_INVOICE_DATA } from "@/app/constants";import fs from "node:fs";import path from "node:path";import { uploadLogoFile } from "./utils";@@ -24,6 +25,51 @@ test.describe("Stripe Invoice Template", () => {await page.goto("/?template=default");});+ test("uses template-specific default invoice number labels", async ({+ page,+ }) => {+ // Older Stripe drafts stored the default-template label even though the+ // Stripe PDF ignored it. Verify that loading one migrates only the default.+ await page.evaluate(+ ({ invoiceData, storageKey }) => {+ localStorage.setItem(storageKey, JSON.stringify(invoiceData));+ },+ {+ storageKey: PDF_DATA_LOCAL_STORAGE_KEY,+ invoiceData: {+ ...INITIAL_INVOICE_DATA,+ template: "stripe",+ },+ },+ );++ await page.goto("/?template=stripe");++ const generalInfoSection = page.getByTestId("general-information-section");+ const invoiceNumberFieldset = generalInfoSection.getByRole("group", {+ name: "Invoice Number",+ });+ const invoiceNumberLabelInput = invoiceNumberFieldset.getByRole("textbox", {+ name: "Label",+ });++ await expect(invoiceNumberLabelInput).toHaveValue("Invoice");++ await page+ .getByRole("combobox", { name: "Invoice PDF Language" })+ .selectOption("pl");++ await expect(invoiceNumberLabelInput).toHaveValue("Faktura");++ await invoiceNumberLabelInput.fill("Custom invoice label");++ await page+ .getByRole("combobox", { name: "Invoice Template" })+ .selectOption("default");++ await expect(invoiceNumberLabelInput).toHaveValue("Faktura nr:");+ });+test("displays correct OG meta tags for Stripe template", async ({page,}) => {@@ -787,7 +833,7 @@ test.describe("Stripe Invoice Template", () => {// Generate PDF to verify Tax column is visibleconst downloadPDFButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPDFButton).toBeVisible();@@ -930,7 +976,7 @@ test.describe("Stripe Invoice Template", () => {expect(parsedData.logo).toBeTruthy();const downloadPDFButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPDFButton).toBeVisible();@@ -1043,7 +1089,7 @@ test.describe("Stripe Invoice Template", () => {await page.waitForTimeout(700);const downloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfEnglishButton).toBeVisible();@@ -1152,7 +1198,7 @@ test.describe("Stripe Invoice Template", () => {await page.waitForTimeout(700);const newDownloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});// Download the PDF again@@ -1262,7 +1308,7 @@ test.describe("Stripe Invoice Template", () => {await page.waitForTimeout(700);const downloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfEnglishButton).toBeVisible();@@ -1344,7 +1390,7 @@ test.describe("Stripe Invoice Template", () => {await page.waitForTimeout(700);const newDownloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});const [downloadWithoutServicePeriod] = await Promise.all([@@ -1451,7 +1497,7 @@ test.describe("Stripe Invoice Template", () => {await page.waitForTimeout(700);const downloadPdfEnglishButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfEnglishButton).toBeVisible();@@ -1574,7 +1620,7 @@ test.describe("Stripe Invoice Template", () => {await page.waitForTimeout(700);const downloadPdfButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(downloadPdfButton).toBeVisible();await expect(downloadPdfButton).toBeEnabled();@@ -1695,7 +1741,7 @@ test.describe("Stripe Invoice Template", () => {await page.waitForTimeout(700);const newDownloadPdfButton = page.getByRole("link", {- name: "Download PDF in English",+ name: /^(Download PDF|Download PDF in .+)$/,});await expect(newDownloadPdfButton).toBeVisible();await expect(newDownloadPdfButton).toBeEnabled();diff --git a/sentry.client.config.ts b/sentry.client.config.tsindex e6c5031..eb0097e 100644--- a/sentry.client.config.ts+++ b/sentry.client.config.ts@@ -4,6 +4,11 @@import * as Sentry from "@sentry/nextjs";+import {+ scrubSensitiveUrlParamsBeforeBreadcrumb,+ scrubSensitiveUrlParamsFromEvent,+} from "@/lib/sentry/scrub-sensitive-url-params";+const isCI = process.env.CI === "true";// Check if we're on a Vercel preview deployment, we want to run only on prod domain@@ -28,6 +33,12 @@ if (isSentryEnabled) {// Recommended production settingsdebug: false,+ // Privacy: the invoice data lives in the `?data=` query param, redact it in+ // every URL we report (request url, referrer, breadcrumbs, spans)+ beforeSend: scrubSensitiveUrlParamsFromEvent,+ beforeSendTransaction: scrubSensitiveUrlParamsFromEvent,+ beforeBreadcrumb: scrubSensitiveUrlParamsBeforeBreadcrumb,+// Performance settingsreplaysSessionSampleRate: 0.1, // Sample 10% of sessionsreplaysOnErrorSampleRate: 1.0, // But capture all sessions with errorsdiff --git a/sentry.edge.config.ts b/sentry.edge.config.tsindex 5dfaba1..5ae40a0 100644--- a/sentry.edge.config.ts+++ b/sentry.edge.config.ts@@ -5,6 +5,11 @@import * as Sentry from "@sentry/nextjs";+import {+ scrubSensitiveUrlParamsBeforeBreadcrumb,+ scrubSensitiveUrlParamsFromEvent,+} from "@/lib/sentry/scrub-sensitive-url-params";+const isCI = process.env.CI === "true";const isSentryEnabled = process.env.SENTRY_ENABLED === "true" && !isCI;@@ -20,6 +25,12 @@ if (isSentryEnabled) {// Recommended production settingsdebug: false,+ // Privacy: the invoice data lives in the `?data=` query param, redact it in+ // every URL we report (request url, referrer, breadcrumbs, spans)+ beforeSend: scrubSensitiveUrlParamsFromEvent,+ beforeSendTransaction: scrubSensitiveUrlParamsFromEvent,+ beforeBreadcrumb: scrubSensitiveUrlParamsBeforeBreadcrumb,+// Performance settingsreplaysSessionSampleRate: 0.1, // Sample 10% of sessionsreplaysOnErrorSampleRate: 1.0, // But capture all sessions with errorsdiff --git a/sentry.server.config.ts b/sentry.server.config.tsindex ae3e704..fe240b4 100644--- a/sentry.server.config.ts+++ b/sentry.server.config.ts@@ -4,6 +4,11 @@import * as Sentry from "@sentry/nextjs";+import {+ scrubSensitiveUrlParamsBeforeBreadcrumb,+ scrubSensitiveUrlParamsFromEvent,+} from "@/lib/sentry/scrub-sensitive-url-params";+const isCI = process.env.CI === "true";const isSentryEnabled = process.env.SENTRY_ENABLED === "true" && !isCI;@@ -19,6 +24,12 @@ if (isSentryEnabled) {// Recommended production settingsdebug: false,+ // Privacy: the invoice data lives in the `?data=` query param, redact it in+ // every URL we report (request url, referrer, breadcrumbs, spans)+ beforeSend: scrubSensitiveUrlParamsFromEvent,+ beforeSendTransaction: scrubSensitiveUrlParamsFromEvent,+ beforeBreadcrumb: scrubSensitiveUrlParamsBeforeBreadcrumb,+// Performance settingsreplaysSessionSampleRate: 0.1, // Sample 10% of sessionsreplaysOnErrorSampleRate: 1.0, // But capture all sessions with errorsdiff --git a/src/app/(app)/components/__tests__/invoice-pdf-download-link.test.tsx b/src/app/(app)/components/__tests__/invoice-pdf-download-link.test.tsxindex fd9731c..1ca4e2d 100644--- a/src/app/(app)/components/__tests__/invoice-pdf-download-link.test.tsx+++ b/src/app/(app)/components/__tests__/invoice-pdf-download-link.test.tsx@@ -3,7 +3,6 @@import { getInitialInvoiceData } from "@/app/constants";import { CTAToastProvider } from "@/app/(app)/contexts/cta-toast-context";import { CTA_TOAST_TIMEOUT } from "@/app/(app)/components/cta-toasts";-import { LOADING_BUTTON_TEXT } from "@/app/(app)/components/invoice-form";import { DeviceContextProvider } from "@/contexts/device-context";import type { InvoiceData } from "@/app/schema";import { TooltipProvider } from "@/components/ui/tooltip";@@ -91,7 +90,10 @@ vi.mock("sonner", () => ({}),}));-import { InvoicePDFDownloadLink } from "../invoice-pdf-download-link";+import {+ InvoicePDFDownloadLink,+ LOADING_BUTTON_TEXT,+} from "../invoice-pdf-download-link";import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";import * as Sentry from "@sentry/nextjs";import { isTelegramInAppBrowser } from "@/utils/is-telegram-in-app-browser";@@ -143,7 +145,7 @@ function renderInvoicePDFDownloadLink({}function getDownloadLink() {- return screen.getByRole("link", { name: /Download PDF in/i });+ return screen.getByRole("link", { name: /Download PDF/i });}describe("InvoicePDFDownloadLink", () => {@@ -158,12 +160,19 @@ describe("InvoicePDFDownloadLink", () => {vi.useRealTimers();});- it("should render download link with language label when PDF is ready", () => {+ it("should render a language-specific desktop download link when PDF is ready", () => {renderInvoicePDFDownloadLink();expect(getDownloadLink()).toHaveTextContent("Download PDF in English");});+ it("should render a concise mobile download link", () => {+ renderInvoicePDFDownloadLink({ isMobile: true });++ expect(getDownloadLink()).toHaveTextContent("Download PDF");+ expect(getDownloadLink()).not.toHaveTextContent("Download PDF in English");+ });+it("should call updatePdfInstance when document mounts", () => {renderInvoicePDFDownloadLink();diff --git a/src/app/(app)/components/index.tsx b/src/app/(app)/components/index.tsxindex 4bdd66b..fb8c6ea 100644--- a/src/app/(app)/components/index.tsx+++ b/src/app/(app)/components/index.tsx@@ -7,7 +7,12 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { CustomTooltip } from "@/components/ui/tooltip";import { cn } from "@/lib/utils";import dayjs from "dayjs";-import { AlertCircleIcon, FileTextIcon, PencilIcon } from "lucide-react";+import {+ AlertCircleIcon,+ FileTextIcon,+ LinkIcon,+ PencilIcon,+} from "lucide-react";import dynamic from "next/dynamic";import Link from "next/link";@@ -237,7 +242,8 @@ export function InvoiceClientPage({variant="outline"className={cn("mx-2 w-full")}>- Generate invoice link+ <LinkIcon className="mr-1.5 size-4" />+ Get link</Button>}content={@@ -285,12 +291,12 @@ export function InvoiceClientPage({/></div>{/** Mobile version */}- <div className="relative mt-2 flex flex-wrap items-center justify-center gap-x-2 gap-y-1 text-center text-xs text-zinc-700 duration-500 animate-in fade-in slide-in-from-bottom-2">+ <div className="relative mx-2 mt-2 flex flex-wrap items-center justify-center gap-x-2 gap-y-1 text-center text-xs text-zinc-700 duration-500 animate-in fade-in slide-in-from-bottom-2"><LocalStorageNotice />{invoiceLastUpdatedAtFormatted ? (<><span- className="hidden h-3 w-px bg-zinc-400 sm:block"+ className="hidden h-3 w-px bg-zinc-400 min-[453px]:block"aria-hidden="true"/><span>diff --git a/src/app/(app)/components/invoice-form/__tests__/calculate-invoice-total.test.ts b/src/app/(app)/components/invoice-form/__tests__/calculate-invoice-total.test.tsnew file mode 100644index 0000000..3b626d7--- /dev/null+++ b/src/app/(app)/components/invoice-form/__tests__/calculate-invoice-total.test.ts@@ -0,0 +1,163 @@+import { describe, expect, it } from "vitest";+import type { InvoiceItemData } from "@/app/schema";+import { MOCK_INVOICE_ITEM_DATA } from "@/utils/__tests__/data";+import {+ calculateInvoiceTotal,+ getSafeNumber,+} from "../utils/calculate-invoice-total";+import { parseValidatedInvoiceItems } from "../utils/validated-invoice-items";++function createItem(overrides: Partial<InvoiceItemData> = {}): InvoiceItemData {+ return {+ ...MOCK_INVOICE_ITEM_DATA,+ ...overrides,+ };+}++function createValidatedItems(items: InvoiceItemData[] = [createItem()]) {+ const result = parseValidatedInvoiceItems(items);++ if (!result.success) {+ throw new Error("Expected valid invoice items in test fixture");+ }++ return result.data;+}++describe("getSafeNumber", () => {+ it("returns the number when value is a finite number", () => {+ expect(getSafeNumber(42)).toBe(42);+ expect(getSafeNumber(0)).toBe(0);+ expect(getSafeNumber(-12.34)).toBe(-12.34);+ });++ it("coerces numeric strings to numbers", () => {+ expect(getSafeNumber("10.5")).toBe(10.5);+ expect(getSafeNumber("0")).toBe(0);+ });++ it("returns 0 for null and undefined", () => {+ expect(getSafeNumber(null)).toBe(0);+ expect(getSafeNumber(undefined)).toBe(0);+ });++ it("returns 0 for non-finite numbers", () => {+ expect(getSafeNumber(Number.NaN)).toBe(0);+ expect(getSafeNumber(Number.POSITIVE_INFINITY)).toBe(0);+ expect(getSafeNumber(Number.NEGATIVE_INFINITY)).toBe(0);+ });++ it("returns 0 for non-numeric values", () => {+ expect(getSafeNumber("")).toBe(0);+ expect(getSafeNumber("abc")).toBe(0);+ expect(getSafeNumber({})).toBe(0);+ });+});++describe("calculateInvoiceTotal", () => {+ it("returns 0 when there are no items", () => {+ expect(calculateInvoiceTotal(createValidatedItems([]))).toBe(0);+ });++ it("sums preTaxAmount from a single item", () => {+ expect(+ calculateInvoiceTotal(+ createValidatedItems([createItem({ preTaxAmount: 247.23 })]),+ ),+ ).toBe(247.23);+ });++ it("sums preTaxAmount across multiple items", () => {+ expect(+ calculateInvoiceTotal(+ createValidatedItems([+ createItem({ preTaxAmount: 100 }),+ createItem({ preTaxAmount: 50.5 }),+ createItem({ preTaxAmount: 12.25 }),+ ]),+ ),+ ).toBe(162.75);+ });++ it("rounds the total to two decimal places", () => {+ expect(+ calculateInvoiceTotal(+ createValidatedItems([+ createItem({ preTaxAmount: 10.005 }),+ createItem({ preTaxAmount: 10.005 }),+ ]),+ ),+ ).toBe(20.01);+ });++ // Note: the parse step, not `calculateInvoiceTotal`, is what turns string+ // amounts into numbers. These cases cover that parse -> total path end to end.+ it("sums string preTaxAmount once the parse step has coerced it", () => {+ expect(+ calculateInvoiceTotal(+ createValidatedItems([+ createItem({ preTaxAmount: "100.5" as unknown as number }),+ createItem({ preTaxAmount: "12.25" as unknown as number }),+ ]),+ ),+ ).toBe(112.75);++ expect(+ calculateInvoiceTotal(+ createValidatedItems([+ createItem({ preTaxAmount: 50 }),+ createItem({ preTaxAmount: "25.5" as unknown as number }),+ createItem({ preTaxAmount: "0" as unknown as number }),+ ]),+ ),+ ).toBe(75.5);+ });++ // `z.coerce.number().nonnegative()` accepts Infinity, so these reach+ // `calculateInvoiceTotal` through the real parse path and are the cases that+ // `getSafeNumber` actually exists to handle.+ it("treats a non-finite preTaxAmount that passed validation as 0", () => {+ expect(+ calculateInvoiceTotal(+ createValidatedItems([+ createItem({ preTaxAmount: 100 }),+ createItem({ preTaxAmount: Number.POSITIVE_INFINITY }),+ ]),+ ),+ ).toBe(100);+ });++ it("treats an overflowing numeric string as 0", () => {+ const validatedItems = createValidatedItems([+ createItem({ preTaxAmount: 100 }),+ createItem({ preTaxAmount: "1e999" as unknown as number }),+ ]);++ // the string overflows to Infinity during coercion, not to a parse error+ expect(validatedItems[1].preTaxAmount).toBe(Number.POSITIVE_INFINITY);+ expect(calculateInvoiceTotal(validatedItems)).toBe(100);+ });++ it("coerces string preTaxAmount when raw form values reach it", () => {+ // The totals effect passes raw `useWatch` items straight in, so this call+ // shape is the real one. `zodResolver` validates but never writes coerced+ // values back into form state, so nothing guarantees a number here - this+ // pins the guard that keeps a string from crashing the form.+ const rawFormItems = [+ { preTaxAmount: "10" },+ { preTaxAmount: "20" },+ ] as unknown as ReadonlyArray<Pick<InvoiceItemData, "preTaxAmount">>;++ // Without coercion, `0 + "10"` becomes `"010"`, then string concat continues+ // and `.toFixed` throws: TypeError: f.reduce(...).toFixed is not a function+ expect(() =>+ Number(+ rawFormItems+ .reduce((sum, item) => sum + item.preTaxAmount, 0)+ .toFixed(2),+ ),+ ).toThrow(TypeError);++ expect(calculateInvoiceTotal(rawFormItems)).toBe(30);+ });+});diff --git a/src/app/(app)/components/invoice-form/__tests__/has-item-totals-changed.test.ts b/src/app/(app)/components/invoice-form/__tests__/has-item-totals-changed.test.tsindex 41e9ea9..9328b67 100644--- a/src/app/(app)/components/invoice-form/__tests__/has-item-totals-changed.test.ts+++ b/src/app/(app)/components/invoice-form/__tests__/has-item-totals-changed.test.ts@@ -5,6 +5,7 @@ import {hasAnyItemTotalsChanged,hasItemTotalsChanged,} from "../utils/has-item-totals-changed";+import { parseValidatedInvoiceItems } from "../utils/validated-invoice-items";function createItem(overrides: Partial<InvoiceItemData> = {}) {return {@@ -13,15 +14,35 @@ function createItem(overrides: Partial<InvoiceItemData> = {}) {} as const satisfies InvoiceItemData;}+function createValidatedItem(overrides: Partial<InvoiceItemData> = {}) {+ const result = parseValidatedInvoiceItems([createItem(overrides)]);++ if (!result.success) {+ throw new Error("Expected valid invoice item in test fixture");+ }++ return result.data[0];+}++function createValidatedItems(items: InvoiceItemData[]) {+ const result = parseValidatedInvoiceItems(items);++ if (!result.success) {+ throw new Error("Expected valid invoice items in test fixture");+ }++ return result.data;+}+describe("hasItemTotalsChanged", () => {it("returns false when item totals match calculated values", () => {- expect(hasItemTotalsChanged(createItem())).toBe(false);+ expect(hasItemTotalsChanged(createValidatedItem())).toBe(false);});it("returns true when netAmount is stale", () => {expect(hasItemTotalsChanged(- createItem({+ createValidatedItem({netAmount: 999,}),),@@ -31,7 +52,7 @@ describe("hasItemTotalsChanged", () => {it("returns true when vatAmount is stale", () => {expect(hasItemTotalsChanged(- createItem({+ createValidatedItem({vatAmount: 999,}),),@@ -41,7 +62,7 @@ describe("hasItemTotalsChanged", () => {it("returns true when preTaxAmount is stale", () => {expect(hasItemTotalsChanged(- createItem({+ createValidatedItem({preTaxAmount: 999,}),),@@ -51,7 +72,7 @@ describe("hasItemTotalsChanged", () => {it("returns true when input fields changed but totals were not recalculated", () => {expect(hasItemTotalsChanged(- createItem({+ createValidatedItem({amount: 5,netPrice: 100,vat: 23,@@ -66,7 +87,7 @@ describe("hasItemTotalsChanged", () => {it("returns true when vat changed but totals were not recalculated", () => {expect(hasItemTotalsChanged(- createItem({+ createValidatedItem({vat: 8,netAmount: 201,vatAmount: 46.23,@@ -83,21 +104,29 @@ describe("hasAnyItemTotalsChanged", () => {});it("returns false when all items are up to date", () => {- expect(hasAnyItemTotalsChanged([createItem(), createItem()])).toBe(false);+ expect(+ hasAnyItemTotalsChanged(+ createValidatedItems([createItem(), createItem()]),+ ),+ ).toBe(false);});it("returns true when one item in a multi-item array is stale", () => {expect(- hasAnyItemTotalsChanged([createItem(), createItem({ netAmount: 999 })]),+ hasAnyItemTotalsChanged(+ createValidatedItems([createItem(), createItem({ netAmount: 999 })]),+ ),).toBe(true);});it("returns true when all items are stale", () => {expect(- hasAnyItemTotalsChanged([- createItem({ netAmount: 999 }),- createItem({ vatAmount: 999 }),- ]),+ hasAnyItemTotalsChanged(+ createValidatedItems([+ createItem({ netAmount: 999 }),+ createItem({ vatAmount: 999 }),+ ]),+ ),).toBe(true);});});diff --git a/src/app/(app)/components/invoice-form/__tests__/validated-invoice-items.test.ts b/src/app/(app)/components/invoice-form/__tests__/validated-invoice-items.test.tsnew file mode 100644index 0000000..3ee05f8--- /dev/null+++ b/src/app/(app)/components/invoice-form/__tests__/validated-invoice-items.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from "vitest";+import type { InvoiceItemData } from "@/app/schema";+import { MOCK_INVOICE_ITEM_DATA } from "@/utils/__tests__/data";+import { parseValidatedInvoiceItems } from "../utils/validated-invoice-items";++function createItem(overrides: Partial<InvoiceItemData> = {}): InvoiceItemData {+ return {+ ...MOCK_INVOICE_ITEM_DATA,+ ...overrides,+ };+}++describe("parseValidatedInvoiceItems", () => {+ it("accepts items that pass invoiceItemSchema", () => {+ const result = parseValidatedInvoiceItems([createItem()]);++ expect(result.success).toBe(true);++ if (!result.success) {+ return;+ }++ expect(result.data[0].preTaxAmount).toBe(+ MOCK_INVOICE_ITEM_DATA.preTaxAmount,+ );+ });++ it("coerces string amounts on the way through", () => {+ const result = parseValidatedInvoiceItems([+ createItem({ preTaxAmount: "247.23" as unknown as number }),+ ]);++ expect(result.success).toBe(true);++ if (!result.success) {+ return;+ }++ expect(result.data[0].preTaxAmount).toBe(247.23);+ });++ // These are the states the gate exists for: `useWatch` fires on every+ // keystroke, so the totals effect sees them while the user is still typing.+ // Failing the parse is what stops bogus totals being written back.+ it("rejects an amount cleared mid-edit", () => {+ const result = parseValidatedInvoiceItems([+ createItem({ amount: "" as unknown as number }),+ ]);++ expect(result.success).toBe(false);+ });++ it("rejects a VAT rate above the allowed range", () => {+ const result = parseValidatedInvoiceItems([createItem({ vat: 500 })]);++ expect(result.success).toBe(false);+ });++ it("rejects a negative calculated amount", () => {+ const result = parseValidatedInvoiceItems([+ createItem({ preTaxAmount: -1 }),+ ]);++ expect(result.success).toBe(false);+ });+});diff --git a/src/app/(app)/components/invoice-form/index.tsx b/src/app/(app)/components/invoice-form/index.tsxindex 3ec598a..7adf389 100644--- a/src/app/(app)/components/invoice-form/index.tsx+++ b/src/app/(app)/components/invoice-form/index.tsx@@ -3,7 +3,6 @@import {ACCORDION_STATE_LOCAL_STORAGE_KEY,accordionSchema,- invoiceItemSchema,invoiceSchema,PDF_DATA_LOCAL_STORAGE_KEY,type AccordionState,@@ -27,9 +26,11 @@ import { Textarea } from "@/components/ui/textarea";import { CustomTooltip } from "@/components/ui/tooltip";import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";import type { NonReadonly, Prettify } from "@/types";+import { calculateInvoiceTotal } from "./utils/calculate-invoice-total";import { calculateItemTotals } from "./utils/calculate-item-totals";import { formErrorsToToast } from "./utils/form-errors-to-toast";import { hasAnyItemTotalsChanged } from "./utils/has-item-totals-changed";+import { parseValidatedInvoiceItems } from "./utils/validated-invoice-items";import { zodResolver } from "@hookform/resolvers/zod";import * as Sentry from "@sentry/nextjs";@@ -45,7 +46,6 @@ import {import { Controller, useFieldArray, useForm, useWatch } from "react-hook-form";import { toast } from "sonner";import { useDebouncedCallback } from "use-debounce";-import { z } from "zod";import { updateAppMetadata } from "@/app/(app)/utils/get-app-metadata";import { AlertIcon, ErrorMessage } from "./common";@@ -54,8 +54,6 @@ import { GeneralInformation } from "./sections/general-information";import { InvoiceItems } from "./sections/invoice-items";import { SellerInformation } from "./sections/seller-information";-export const LOADING_BUTTON_TIMEOUT = 400;-export const LOADING_BUTTON_TEXT = "Generating Document...";const DEBOUNCE_TIMEOUT = 500;const DEFAULT_ACCORDION_VALUES = [@@ -124,28 +122,30 @@ export const InvoiceForm = memo(function InvoiceForm({// calculate totals and other values when invoice items changeuseEffect(() => {- // run validations before calculations because user can input invalid data- const validatedItems = z.array(invoiceItemSchema).safeParse(invoiceItems);+ // Bail out while the user is mid-edit with input the schema rejects, so we+ // never turn half-typed values into totals and write them back. Clearing the+ // amount field to retype it would otherwise zero out the item's totals, and+ // a VAT of 500 would persist a bogus tax amount.+ // `zodResolver` does not do this for us: it populates `errors`, but form+ // state (and so `useWatch`) still holds the raw, unvalidated input.+ const validatedItemsResult = parseValidatedInvoiceItems(invoiceItems);++ if (!validatedItemsResult.success) {+ console.error("Invalid items:", validatedItemsResult.error);++ Sentry.captureException(validatedItemsResult.error);- if (!validatedItems.success) {- console.error("Invalid items:", validatedItems.error);return;}- // Always calculate total, even when no items- const total = invoiceItems?.length- ? Number(- invoiceItems- .reduce((sum, item) => sum + (item?.preTaxAmount || 0), 0)- .toFixed(2),- )- : 0;+ const total = calculateInvoiceTotal(invoiceItems);- console.log(+ // eslint-disable-next-line no-console+ console.info("[useEffect] recalculating totals because invoice items changed",{invoiceItems,- validatedItems,+ validatedItemsResult,total,},);diff --git a/src/app/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsx b/src/app/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsxnew file mode 100644index 0000000..9972b26--- /dev/null+++ b/src/app/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsx@@ -0,0 +1,203 @@+// @vitest-environment happy-dom++import { getInitialInvoiceData } from "@/app/constants";+import type { InvoiceData } from "@/app/schema";+import { TooltipProvider } from "@/components/ui/tooltip";+import { MOCK_INVOICE_ITEM_DATA } from "@/utils/__tests__/data";+import { cleanup, render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { useMemo } from "react";+import {+ type Control,+ type FieldArrayWithId,+ type UseFieldArrayAppend,+ useForm,+} from "react-hook-form";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import "@testing-library/jest-dom/vitest";++const { MOCK_MAX_INVOICE_ITEMS } = vi.hoisted(() => ({+ MOCK_MAX_INVOICE_ITEMS: 3,+}));++vi.mock("@/app/schema", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/app/schema")>();++ return {+ ...actual,+ MAX_INVOICE_ITEMS: MOCK_MAX_INVOICE_ITEMS,+ };+});++vi.mock("@/lib/umami-analytics-track-event", () => ({+ umamiTrackEvent: vi.fn(),+}));++vi.mock("@/hooks/use-media-query", () => ({+ useIsDesktop: () => true,+}));++import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";+import { InvoiceItems } from "../invoice-items";++interface InvoiceItemsTestHarnessProps {+ itemCount: number;+ append?: UseFieldArrayAppend<InvoiceData, "items">;+ onRemove?: (index: number) => void;+}++function InvoiceItemsTestHarness({+ itemCount,+ append = vi.fn(),+ onRemove = vi.fn(),+}: InvoiceItemsTestHarnessProps) {+ const invoiceData = useMemo(+ () => ({+ ...getInitialInvoiceData(),+ items: Array.from({ length: itemCount }, () => ({+ ...MOCK_INVOICE_ITEM_DATA,+ })),+ }),+ [itemCount],+ );++ const { control } = useForm<InvoiceData>({+ defaultValues: invoiceData,+ });++ const fields = Array.from({ length: itemCount }, (_, index) => ({+ id: `item-${index}`,+ })) as FieldArrayWithId<InvoiceData, "items", "id">[];++ return (+ <TooltipProvider delayDuration={0}>+ <InvoiceItems+ control={control as Control<InvoiceData>}+ fields={fields}+ handleRemoveInvoiceItem={onRemove}+ append={append}+ errors={{}}+ currency="EUR"+ language="en"+ template="default"+ taxLabelText="VAT"+ invoiceData={invoiceData}+ />+ </TooltipProvider>+ );+}++function renderInvoiceItems(props: InvoiceItemsTestHarnessProps) {+ return render(<InvoiceItemsTestHarness {...props} />);+}++function getAddInvoiceItemButton() {+ return screen.getByRole("button", { name: "Add invoice item" });+}++describe("InvoiceItems max invoice items", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ afterEach(() => {+ cleanup();+ });++ it("enables the add button when below the item limit", () => {+ renderInvoiceItems({ itemCount: MOCK_MAX_INVOICE_ITEMS - 1 });++ expect(getAddInvoiceItemButton()).toBeEnabled();+ });++ it("disables the add button when the item limit is reached", () => {+ renderInvoiceItems({ itemCount: MOCK_MAX_INVOICE_ITEMS });++ expect(getAddInvoiceItemButton()).toBeDisabled();+ });++ it("appends a new item with default values when below the limit", async () => {+ const user = userEvent.setup();+ const append = vi.fn();++ renderInvoiceItems({+ itemCount: MOCK_MAX_INVOICE_ITEMS - 1,+ append,+ });++ await user.click(getAddInvoiceItemButton());++ expect(append).toHaveBeenCalledTimes(1);+ expect(append).toHaveBeenCalledWith({+ invoiceItemNumberIsVisible: true,+ name: "",+ nameFieldIsVisible: true,+ amount: 1,+ amountFieldIsVisible: true,+ unit: "",+ unitFieldIsVisible: true,+ netPrice: 0,+ netPriceFieldIsVisible: true,+ vat: "NP",+ vatFieldIsVisible: true,+ netAmount: 0,+ netAmountFieldIsVisible: true,+ vatAmount: 0,+ vatAmountFieldIsVisible: true,+ preTaxAmount: 0,+ preTaxAmountFieldIsVisible: true,+ typeOfGTU: "",+ typeOfGTUFieldIsVisible: true,+ });+ expect(umamiTrackEvent).toHaveBeenCalledWith("add_invoice_item");+ });++ it("does not append when the item limit is reached", async () => {+ const user = userEvent.setup();+ const append = vi.fn();++ renderInvoiceItems({+ itemCount: MOCK_MAX_INVOICE_ITEMS,+ append,+ });++ await user.click(getAddInvoiceItemButton());++ expect(append).not.toHaveBeenCalled();+ expect(umamiTrackEvent).not.toHaveBeenCalled();+ });++ it("shows the max items tooltip when the limit is reached", async () => {+ const user = userEvent.setup();++ renderInvoiceItems({ itemCount: MOCK_MAX_INVOICE_ITEMS });++ await user.hover(getAddInvoiceItemButton());++ expect(await screen.findByRole("tooltip")).toHaveTextContent(+ `Invoices support at most ${MOCK_MAX_INVOICE_ITEMS} line items`,+ );+ });++ it("shows the default add-item tooltip when below the limit", async () => {+ const user = userEvent.setup();++ renderInvoiceItems({ itemCount: 1 });++ await user.hover(getAddInvoiceItemButton());++ expect(await screen.findByRole("tooltip")).toHaveTextContent(+ "Add a new line item with name, quantity, price and tax details",+ );+ });++ it("renders one fieldset per invoice item", () => {+ renderInvoiceItems({ itemCount: 2 });++ const fieldsets = screen.getAllByRole("group", { name: /Item \d+/ });++ expect(fieldsets).toHaveLength(2);+ expect(within(fieldsets[0]).getByText("Item 1")).toBeInTheDocument();+ expect(within(fieldsets[1]).getByText("Item 2")).toBeInTheDocument();+ });+});diff --git a/src/app/(app)/components/invoice-form/sections/general-information.tsx b/src/app/(app)/components/invoice-form/sections/general-information.tsxindex d0a0fbf..c27078e 100644--- a/src/app/(app)/components/invoice-form/sections/general-information.tsx+++ b/src/app/(app)/components/invoice-form/sections/general-information.tsx@@ -3,7 +3,10 @@ import {ErrorMessage,inputErrorClassName,} from "@/app/(app)/components/invoice-form/common";-import { INVOICE_PDF_TRANSLATIONS } from "@/app/(app)/pdf-i18n-translations/pdf-translations";+import {+ getDefaultInvoiceNumberLabel,+ INVOICE_PDF_TRANSLATIONS,+} from "@/app/(app)/pdf-i18n-translations/pdf-translations";import {isFirstDayOfMonth,isServicePeriodStartInCurrentMonth,@@ -89,7 +92,10 @@ export const GeneralInformation = memo(function GeneralInformation({const paymentDue = useWatch({ control, name: "paymentDue" });const t = INVOICE_PDF_TRANSLATIONS[language];- const defaultInvoiceNumber = `${t.invoiceNumber}:`;+ const defaultInvoiceNumberLabel = getDefaultInvoiceNumberLabel(+ language,+ template,+ );const defaultServicePeriodLabel = t.servicePeriod;const defaultDateOfServiceLabel = t.dateOfService;@@ -111,7 +117,7 @@ export const GeneralInformation = memo(function GeneralInformation({!isServicePeriodStartInCurrentMonth(dateOfServiceStart);const isDefaultInvoiceNumberLabel =- invoiceNumberLabel === defaultInvoiceNumber;+ invoiceNumberLabel === defaultInvoiceNumberLabel;// extract the month and year from the invoice number (i.e. 1/04-2025 -> 04-2025)const extractInvoiceMonthAndYear = /(\d{2}-\d{4})/.exec(@@ -210,9 +216,17 @@ export const GeneralInformation = memo(function GeneralInformation({id={`template`}className={cn("block", inputErrorClassName(!!errors.template))}onChange={(e) => {+ const newTemplate =+ e.target.value === "stripe" ? "stripe" : "default";+field.onChange(e);- const newTemplate = e.target.value;+ // When the user changes the invoice template, automatically update the invoice number label+ // so it matches the default convention for the selected template and current language.+ setValue(+ "invoiceNumberObject.label",+ getDefaultInvoiceNumberLabel(language, newTemplate),+ );// Handles template-specific form updates for better UX@@ -284,13 +298,10 @@ export const GeneralInformation = memo(function GeneralInformation({const newLanguage = e.target.value as keyof typeof INVOICE_PDF_TRANSLATIONS;- const newInvoiceNumberLabel =- INVOICE_PDF_TRANSLATIONS[newLanguage].invoiceNumber;-// we need to keep the invoice number suffix (e.g. 1/MM-YYYY) for better user experience, when switching languagesetValue("invoiceNumberObject.label",- `${newInvoiceNumberLabel}:`,+ getDefaultInvoiceNumberLabel(newLanguage, template),);setValue("invoiceNumberObject.value", invoiceNumberValue);@@ -451,12 +462,11 @@ export const GeneralInformation = memo(function GeneralInformation({onClick={() => {setValue("invoiceNumberObject.label",- defaultInvoiceNumber,+ defaultInvoiceNumberLabel,);}}>- Switch to default label ("{defaultInvoiceNumber}- ")+ Reset to default ("{defaultInvoiceNumberLabel}")</ButtonHelper></InputHelperMessage>)}@@ -726,8 +736,7 @@ export const GeneralInformation = memo(function GeneralInformation({);}}>- Switch to default label ("{defaultServicePeriodLabel}- ")+ Reset to default ("{defaultServicePeriodLabel}")</ButtonHelper></InputHelperMessage>) : null}@@ -795,8 +804,7 @@ export const GeneralInformation = memo(function GeneralInformation({);}}>- Switch to default label ("{defaultDateOfServiceLabel}- ")+ Reset to default ("{defaultDateOfServiceLabel}")</ButtonHelper></InputHelperMessage>) : null}diff --git a/src/app/(app)/components/invoice-form/sections/invoice-items.tsx b/src/app/(app)/components/invoice-form/sections/invoice-items.tsxindex b8af1da..0f75d21 100644--- a/src/app/(app)/components/invoice-form/sections/invoice-items.tsx+++ b/src/app/(app)/components/invoice-form/sections/invoice-items.tsx@@ -40,6 +40,7 @@ import {AlertDialogTitle,} from "@/components/ui/alert-dialog";import { INVOICE_PDF_TRANSLATIONS } from "@/app/(app)/pdf-i18n-translations/pdf-translations";+import { MAX_INVOICE_ITEMS } from "@/app/schema";const ErrorMessage = ({ children }: { children: React.ReactNode }) => {return <p className="mt-1 text-xs text-red-600">{children}</p>;@@ -71,6 +72,7 @@ export const InvoiceItems = memo(function InvoiceItems({invoiceData,}: InvoiceItemsSettingsProps) {const [deleteItemIndex, setDeleteItemIndex] = useState<number | null>(null);+ const hasReachedItemLimit = fields.length >= MAX_INVOICE_ITEMS;return (<>@@ -806,13 +808,18 @@ export const InvoiceItems = memo(function InvoiceItems({umamiTrackEvent("add_invoice_item");}}variant="default"+ disabled={hasReachedItemLimit}className="w-full gap-2"><Plus className="size-4" />Add invoice item</Button>}- content="Add a new line item with name, quantity, price and tax details"+ content={+ hasReachedItemLimit+ ? `Invoices support at most ${MAX_INVOICE_ITEMS} line items`+ : "Add a new line item with name, quantity, price and tax details"+ }side="bottom"showArrow/>diff --git a/src/app/(app)/components/invoice-form/utils/calculate-invoice-total.ts b/src/app/(app)/components/invoice-form/utils/calculate-invoice-total.tsnew file mode 100644index 0000000..75f956b--- /dev/null+++ b/src/app/(app)/components/invoice-form/utils/calculate-invoice-total.ts@@ -0,0 +1,37 @@+import type { InvoiceItemData } from "@/app/schema";++/**+ * Converts a value to a finite number, returning 0 if the value is not finite.+ *+ * This is the only thing standing between raw form state and the sum, so it+ * covers two cases:+ *+ * - `preTaxAmount` can arrive as a string. `zodResolver` validates form state+ * but never writes coerced values back into it, so a `useWatch` result can+ * still hold `"10"`. Summing that concatenates (`0 + "10"` -> `"010"`) and+ * then throws on `.toFixed`.+ * - `z.coerce.number().nonnegative()` accepts `Infinity`, so a literal+ * `Infinity` or an overflowing numeric string like `"1e999"` survives+ * validation. Summing those renders the invoice total as "Infinity"; a+ * non-finite amount contributes 0 instead so the form stays usable.+ */+export function getSafeNumber(value: unknown) {+ const number = Number(value ?? 0);++ return Number.isFinite(number) ? number : 0;+}++/**+ * Sums pre-tax amounts from invoice items and rounds to two decimal places.+ *+ * Safe to call with raw form values - see `getSafeNumber`.+ */+export function calculateInvoiceTotal(+ items: ReadonlyArray<Pick<InvoiceItemData, "preTaxAmount">>,+) {+ return Number(+ items+ .reduce((sum, item) => sum + getSafeNumber(item.preTaxAmount), 0)+ .toFixed(2),+ );+}diff --git a/src/app/(app)/components/invoice-form/utils/has-item-totals-changed.ts b/src/app/(app)/components/invoice-form/utils/has-item-totals-changed.tsindex f37baaf..c24f36d 100644--- a/src/app/(app)/components/invoice-form/utils/has-item-totals-changed.ts+++ b/src/app/(app)/components/invoice-form/utils/has-item-totals-changed.ts@@ -26,6 +26,8 @@ export function hasItemTotalsChanged(item: InvoiceItemData): boolean {* @param items Array of InvoiceItemData* @returns true if any item has changed totals, false otherwise*/-export function hasAnyItemTotalsChanged(items: InvoiceItemData[]): boolean {+export function hasAnyItemTotalsChanged(+ items: ReadonlyArray<InvoiceItemData>,+): boolean {return items.some(hasItemTotalsChanged);}diff --git a/src/app/(app)/components/invoice-form/utils/validated-invoice-items.ts b/src/app/(app)/components/invoice-form/utils/validated-invoice-items.tsnew file mode 100644index 0000000..0a32878--- /dev/null+++ b/src/app/(app)/components/invoice-form/utils/validated-invoice-items.ts@@ -0,0 +1,23 @@+import { invoiceItemSchema } from "@/app/schema";+import { z } from "zod";++const invoiceItemsSchema = z.array(invoiceItemSchema);++/**+ * Validity gate for the totals effect.+ *+ * `useWatch` fires on every keystroke, including while the user is mid-edit+ * with input the schema rejects - a cleared amount, a VAT above 100. Callers+ * check `success` and bail out in those moments, so half-typed input never gets+ * turned into totals and written back into the form. Without the gate, clearing+ * the amount field to retype it writes 0/0/0 over the item's totals, and a VAT+ * of 500 computes and persists a bogus tax amount.+ *+ * This is a gate, not a coercion step. `zodResolver` never writes transformed+ * values back into form state, but nothing downstream needs it to:+ * `calculateItemTotals` does its own `Number(...)` conversion, and the+ * calculated amount fields are read-only in the UI, so they are always numbers.+ */+export function parseValidatedInvoiceItems(items: unknown) {+ return invoiceItemsSchema.safeParse(items);+}diff --git a/src/app/(app)/components/invoice-page-header.tsx b/src/app/(app)/components/invoice-page-header.tsxindex 945530b..ccaf055 100644--- a/src/app/(app)/components/invoice-page-header.tsx+++ b/src/app/(app)/components/invoice-page-header.tsx@@ -97,7 +97,8 @@ export function InvoicePageHeader({variant="outline"className={cn("mx-2 mb-2 w-full lg:mx-0 lg:mb-0 lg:w-auto")}>- Generate invoice link+ <LinkIcon className="mr-1.5 size-4" />+ Get link</Button>}content={diff --git a/src/app/(app)/components/invoice-pdf-download-link.tsx b/src/app/(app)/components/invoice-pdf-download-link.tsxindex b8085e2..01dee28 100644--- a/src/app/(app)/components/invoice-pdf-download-link.tsx+++ b/src/app/(app)/components/invoice-pdf-download-link.tsx@@ -11,10 +11,9 @@ import { cn } from "@/lib/utils";import { usePDF } from "@react-pdf/renderer/lib/react-pdf.browser";import * as Sentry from "@sentry/nextjs";import dayjs from "dayjs";-import { Loader2 } from "lucide-react";+import { DownloadIcon, Loader2 } from "lucide-react";import { useCallback, useEffect, useMemo, useState } from "react";import { toast } from "sonner";-import { LOADING_BUTTON_TEXT, LOADING_BUTTON_TIMEOUT } from "./invoice-form";import { CustomTooltip } from "@/components/ui/tooltip";import { useDeviceContext } from "@/contexts/device-context";@@ -24,18 +23,23 @@ import { useCTAToast } from "../contexts/cta-toast-context";import { CTA_TOAST_TIMEOUT, showRandomCTAToast } from "./cta-toasts";import { haptic } from "@/lib/haptic";+const LOADING_BUTTON_TIMEOUT = 400;+export const LOADING_BUTTON_TEXT = "Generating Document...";+// Separate button states into a memoized componentconst ButtonContent = ({isLoading,+ isMobile,language,}: {isLoading: boolean;+ isMobile: boolean;language: SupportedLanguages;}) => {if (isLoading) {return (<span className="inline-flex items-center">- <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ <Loader2 className="mr-1.5 size-4 animate-spin" /><span className="animate-pulse">{LOADING_BUTTON_TEXT}</span></span>);@@ -43,7 +47,12 @@ const ButtonContent = ({const languageLabel = LANGUAGE_TO_LABEL[language];- return `Download PDF in ${languageLabel}`;+ return (+ <span className="inline-flex items-center">+ <DownloadIcon className="mr-1.5 size-4" />+ {isMobile ? "Download PDF" : `Download PDF in ${languageLabel}`}+ </span>+ );};export function InvoicePDFDownloadLink({@@ -271,15 +280,16 @@ export function InvoicePDFDownloadLink({"h-[36px] w-full rounded-lg bg-slate-900 px-4 py-2 text-center text-sm font-medium text-white","shadow-sm shadow-black/5 outline-offset-2 hover:bg-slate-900/90 active:scale-[98%] active:transition-transform","focus-visible:border-indigo-500 focus-visible:ring focus-visible:ring-indigo-200 focus-visible:ring-opacity-50",- "dark:bg-slate-50 dark:text-slate-900 dark:hover:bg-slate-50/90 lg:mb-0 lg:w-[210px]",+ "dark:bg-slate-50 dark:text-slate-900 dark:hover:bg-slate-50/90 lg:mb-0 lg:w-[230px]",{"pointer-events-none opacity-70": isLoading,- "lg:w-[240px]": invoiceData.language === "pt",+ "lg:w-[250px]": invoiceData.language === "pt",},)}><ButtonContentisLoading={isLoading}+ isMobile={isMobile}language={invoiceData.language}/></a>diff --git a/src/app/(app)/components/invoice-templates/invoice-pdf-stripe-template/stripe-invoice-header.tsx b/src/app/(app)/components/invoice-templates/invoice-pdf-stripe-template/stripe-invoice-header.tsxindex 512375d..de0b060 100644--- a/src/app/(app)/components/invoice-templates/invoice-pdf-stripe-template/stripe-invoice-header.tsx+++ b/src/app/(app)/components/invoice-templates/invoice-pdf-stripe-template/stripe-invoice-header.tsx@@ -14,6 +14,9 @@ export function StripeInvoiceHeader({const t = INVOICE_PDF_TRANSLATIONS[language];const hasLogo = invoiceData.logo && invoiceData.logo.length > 0;+ const invoiceNumberLabel =+ invoiceData.invoiceNumberObject?.label ?? t.stripe.invoice;+return (<View style={[hasLogo ? {} : { marginBottom: 16 }]}>{hasLogo ? (@@ -29,7 +32,7 @@ export function StripeInvoiceHeader({><View style={{ flex: 1, alignItems: "flex-start" }}><Text style={[styles.fontSize18, styles.fontBold, styles.textDark]}>- {t.stripe.invoice}+ {invoiceNumberLabel}</Text></View><View style={{ flex: 1, alignItems: "flex-end" }}>@@ -47,7 +50,7 @@ export function StripeInvoiceHeader({) : (// Header with title only<Text style={[styles.fontSize18, styles.fontBold, styles.textDark]}>- {t.stripe.invoice}+ {invoiceNumberLabel}</Text>)}</View>diff --git a/src/app/(app)/loading.tsx b/src/app/(app)/loading.tsxindex cbc982c..109c826 100644--- a/src/app/(app)/loading.tsx+++ b/src/app/(app)/loading.tsx@@ -52,8 +52,10 @@ function LoadingHeader() {{/* Desktop Buttons skeleton Share Invoice and Download PDF */}<div className="mb-1 hidden w-full flex-nowrap justify-end gap-3 lg:flex">- <Skeleton className="h-9 w-[163px]" />- <Skeleton className="h-9 w-[210px]" />+ {/* Share Invoice (Get link) */}+ <Skeleton className="h-9 w-[106px]" />+ {/* Download PDF */}+ <Skeleton className="h-9 w-[230px]" /></div></div>diff --git a/src/app/(app)/page.client.tsx b/src/app/(app)/page.client.tsxindex af7f0c7..4f20376 100644--- a/src/app/(app)/page.client.tsx+++ b/src/app/(app)/page.client.tsx@@ -46,6 +46,7 @@ import { useShowRandomCTAToastOnIdle } from "./hooks/use-show-random-cta-toast";import type { ChangelogSummary } from "@/app/changelog/utils";import { generateQrCodeDataUrl } from "./utils/generate-qr-code-data-url";import { handleInvoiceNumberBreakingChange } from "./utils/invoice-number-breaking-change";+import { selectInvoiceTemplate } from "./utils/select-invoice-template";import { InvoicePageLoadingSkeleton } from "@/app/(app)/loading";// TODO: enable later when PRO version is released, this is PRO FEATURE =)@@ -201,19 +202,15 @@ export function AppPageClient({const parsedData = invoiceSchema.parse(updatedJson);- // if template is in url, use it- if (templateValidation.success) {- parsedData.template = templateValidation.data;- }+ const selectedInvoiceData = templateValidation.success+ ? selectInvoiceTemplate(parsedData, templateValidation.data)+ : parsedData;- setInvoiceDataState(parsedData);+ setInvoiceDataState(selectedInvoiceData);} else {if (templateValidation.success) {// if no data in local storage and template is in url, set initial data with template from url- setInvoiceDataState({- ...getInitialInvoiceData(),- template: templateValidation.data,- });+ setInvoiceDataState(getInitialInvoiceData(templateValidation.data));} else {// if no data in local storage, set initial datasetInvoiceDataState(getInitialInvoiceData());@@ -223,7 +220,11 @@ export function AppPageClient({console.error("Failed to load saved invoice data:", error);// fallback to initial data on error- setInvoiceDataState(getInitialInvoiceData());+ setInvoiceDataState(+ getInitialInvoiceData(+ templateValidation.success ? templateValidation.data : undefined,+ ),+ );toast.error("Unable to load your saved invoice data. For your convenience, we've reset the form to default values. Please try creating a new invoice.",@@ -285,14 +286,14 @@ export function AppPageClient({// The ?template parameter provides a cleaner URL and better user experience// while ?data contains the actual invoice data including the template// ?template=" " has higher priority than ?data=" " =)- if (templateValidation.success) {- validatedDataFromURL.template = templateValidation.data;- }+ const selectedInvoiceData = templateValidation.success+ ? selectInvoiceTemplate(validatedDataFromURL, templateValidation.data)+ : validatedDataFromURL;- setInvoiceDataState(validatedDataFromURL);+ setInvoiceDataState(selectedInvoiceData);// Store the original URL invoice data for change detection- originalUrlInvoiceDataRef.current = validatedDataFromURL;+ originalUrlInvoiceDataRef.current = selectedInvoiceData;const appMetadata = getAppMetadata();@@ -417,7 +418,7 @@ export function AppPageClient({<p className="text-muted-foreground text-pretty leading-relaxed">Click{" "}<span className="font-semibold text-foreground">- 'Generate invoice link'+ 'Get link'</span>{" "}to create an updated shareable link.</p>@@ -476,7 +477,7 @@ export function AppPageClient({<p className="text-muted-foreground text-pretty leading-relaxed">Click{" "}<span className="font-semibold text-foreground">- 'Generate invoice link'+ 'Get link'</span>{" "}to create a new shareable link.</p>diff --git a/src/app/(app)/pdf-i18n-translations/pdf-translations.ts b/src/app/(app)/pdf-i18n-translations/pdf-translations.tsindex 4718231..08a34f5 100644--- a/src/app/(app)/pdf-i18n-translations/pdf-translations.ts+++ b/src/app/(app)/pdf-i18n-translations/pdf-translations.ts@@ -2,6 +2,7 @@ import { z } from "zod";import {SUPPORTED_LANGUAGES,type SupportedLanguages,+ type SupportedTemplates,} from "../../schema/index";// Schema for seller translations@@ -1128,3 +1129,22 @@ export const INVOICE_PDF_TRANSLATIONS = {},},} as const satisfies Record<SupportedLanguages, TranslationSchema>;++/**+ * Returns the editable invoice label used by the selected PDF template.+ *+ * The default template prints a label next to the invoice number, while the+ * Stripe template uses the same field as its document heading.+ */+export function getDefaultInvoiceNumberLabel(+ language: SupportedLanguages,+ template: SupportedTemplates,+) {+ const translation = INVOICE_PDF_TRANSLATIONS[language];++ if (template === "stripe") {+ return translation.stripe.invoice;+ }++ return `${translation.invoiceNumber}:` as const;+}diff --git a/src/app/(app)/utils/__tests__/select-invoice-template.test.ts b/src/app/(app)/utils/__tests__/select-invoice-template.test.tsnew file mode 100644index 0000000..c6eae3a--- /dev/null+++ b/src/app/(app)/utils/__tests__/select-invoice-template.test.ts@@ -0,0 +1,98 @@+import { describe, it, expect } from "vitest";+import { getInitialInvoiceData, INITIAL_INVOICE_DATA } from "@/app/constants";+import {+ getDefaultInvoiceNumberLabel,+ INVOICE_PDF_TRANSLATIONS,+} from "@/app/(app)/pdf-i18n-translations/pdf-translations";+import type { InvoiceData } from "@/app/schema";+import { selectInvoiceTemplate } from "../select-invoice-template";++describe("selectInvoiceTemplate", () => {+ it("updates the default-template label when switching to Stripe", () => {+ const invoiceData = getInitialInvoiceData("default");++ const result = selectInvoiceTemplate(invoiceData, "stripe");++ expect(result.template).toBe("stripe");+ expect(result.invoiceNumberObject?.label).toBe(+ getDefaultInvoiceNumberLabel("en", "stripe"),+ );+ expect(result.invoiceNumberObject?.value).toBe(+ invoiceData.invoiceNumberObject?.value,+ );+ });++ it("updates the Stripe default label when switching to the default template", () => {+ const invoiceData = getInitialInvoiceData("stripe");++ const result = selectInvoiceTemplate(invoiceData, "default");++ expect(result.template).toBe("default");+ expect(result.invoiceNumberObject?.label).toBe(+ getDefaultInvoiceNumberLabel("en", "default"),+ );+ });++ it("migrates older Stripe drafts that still store the default-template label", () => {+ const invoiceData = {+ ...getInitialInvoiceData("stripe"),+ invoiceNumberObject: {+ ...INITIAL_INVOICE_DATA.invoiceNumberObject,+ label: getDefaultInvoiceNumberLabel("en", "default"),+ },+ };++ const result = selectInvoiceTemplate(invoiceData, "stripe");++ expect(result.template).toBe("stripe");+ expect(result.invoiceNumberObject?.label).toBe(+ getDefaultInvoiceNumberLabel("en", "stripe"),+ );+ });++ it("preserves custom invoice number labels when switching templates", () => {+ const customLabel = "Custom invoice label";+ const invoiceData = {+ ...getInitialInvoiceData("default"),+ invoiceNumberObject: {+ ...getInitialInvoiceData("default").invoiceNumberObject,+ label: customLabel,+ },+ };++ const result = selectInvoiceTemplate(invoiceData, "stripe");++ expect(result.template).toBe("stripe");+ expect(result.invoiceNumberObject?.label).toBe(customLabel);+ });++ it("updates translated default labels when the invoice language changes", () => {+ const invoiceData = {+ ...getInitialInvoiceData("default"),+ language: "pl" as const,+ invoiceNumberObject: {+ ...getInitialInvoiceData("default").invoiceNumberObject,+ label: getDefaultInvoiceNumberLabel("pl", "default"),+ },+ };++ const result = selectInvoiceTemplate(invoiceData, "stripe");++ expect(result.template).toBe("stripe");+ expect(result.invoiceNumberObject?.label).toBe(+ INVOICE_PDF_TRANSLATIONS.pl.stripe.invoice,+ );+ });++ it("only updates the template when invoiceNumberObject is missing", () => {+ const invoiceData = {+ ...getInitialInvoiceData("default"),+ invoiceNumberObject: undefined,+ } as unknown as InvoiceData;++ const result = selectInvoiceTemplate(invoiceData, "stripe");++ expect(result.template).toBe("stripe");+ expect(result.invoiceNumberObject).toBeUndefined();+ });+});diff --git a/src/app/(app)/utils/select-invoice-template.ts b/src/app/(app)/utils/select-invoice-template.tsnew file mode 100644index 0000000..43e2f62--- /dev/null+++ b/src/app/(app)/utils/select-invoice-template.ts@@ -0,0 +1,42 @@+import { getDefaultInvoiceNumberLabel } from "@/app/(app)/pdf-i18n-translations/pdf-translations";+import {+ SUPPORTED_TEMPLATES,+ type InvoiceData,+ type SupportedTemplates,+} from "@/app/schema";++/**+ * Selects the invoice template and updates the invoice data accordingly.+ *+ * If the invoice number object label matches a known default label for any supported template,+ * updates the label to match the default for the newly selected template and the invoice's language.+ * Preserves custom labels.+ */+export function selectInvoiceTemplate(+ invoiceData: InvoiceData,+ template: SupportedTemplates,+) {+ const invoiceNumberObject = invoiceData.invoiceNumberObject;++ // Older Stripe drafts stored the default-template label because Stripe used+ // to ignore this field. Treat either template's translated value as a default+ // so those drafts receive the correct heading without changing custom text.+ const hasKnownDefaultInvoiceNumberLabel = SUPPORTED_TEMPLATES.some(+ (supportedTemplate) =>+ invoiceNumberObject?.label ===+ getDefaultInvoiceNumberLabel(invoiceData.language, supportedTemplate),+ );++ if (!invoiceNumberObject || !hasKnownDefaultInvoiceNumberLabel) {+ return { ...invoiceData, template } satisfies InvoiceData;+ }++ return {+ ...invoiceData,+ template,+ invoiceNumberObject: {+ ...invoiceNumberObject,+ label: getDefaultInvoiceNumberLabel(invoiceData.language, template),+ },+ } satisfies InvoiceData;+}diff --git a/src/app/constants/index.ts b/src/app/constants/index.tsindex eaad604..02139c3 100644--- a/src/app/constants/index.ts+++ b/src/app/constants/index.ts@@ -4,10 +4,14 @@ import {SUPPORTED_TEMPLATES,DEFAULT_DATE_FORMAT,type InvoiceData,+ type SupportedTemplates,type SellerData,type BuyerData,} from "../schema";-import { INVOICE_PDF_TRANSLATIONS } from "../(app)/pdf-i18n-translations/pdf-translations";+import {+ getDefaultInvoiceNumberLabel,+ INVOICE_PDF_TRANSLATIONS,+} from "../(app)/pdf-i18n-translations/pdf-translations";import dayjs from "dayjs";/**@@ -192,11 +196,18 @@ export const INITIAL_INVOICE_DATA = {* Returns initial invoice data with a freshly computed default invoice number.* Use when resetting form state at runtime (avoids stale month on long-lived tabs).*/-export function getInitialInvoiceData() {+export function getInitialInvoiceData(+ template: SupportedTemplates = DEFAULT_TEMPLATE,+) {return {...INITIAL_INVOICE_DATA,+ template,invoiceNumberObject: {...INITIAL_INVOICE_DATA.invoiceNumberObject,+ label: getDefaultInvoiceNumberLabel(+ INITIAL_INVOICE_DATA.language,+ template,+ ),value: getInvoiceDefaultNumberValue(),},} satisfies InvoiceData;diff --git a/src/app/schema/__tests__/max-invoice-items.test.ts b/src/app/schema/__tests__/max-invoice-items.test.tsnew file mode 100644index 0000000..364bfc5--- /dev/null+++ b/src/app/schema/__tests__/max-invoice-items.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";+import { MAX_INVOICE_ITEMS, invoiceSchema } from "@/app/schema";+import {+ MOCK_INVOICE_DATA,+ MOCK_INVOICE_ITEM_DATA,+} from "@/utils/__tests__/data";++function createInvoiceWithItemCount(itemCount: number) {+ return {+ ...MOCK_INVOICE_DATA,+ items: Array.from({ length: itemCount }, () => ({+ ...MOCK_INVOICE_ITEM_DATA,+ })),+ };+}++describe("invoiceSchema max invoice items", () => {+ it(`accepts invoices with up to ${MAX_INVOICE_ITEMS} items`, () => {+ const result = invoiceSchema.safeParse(+ createInvoiceWithItemCount(MAX_INVOICE_ITEMS),+ );++ expect(result.success).toBe(true);+ });++ it(`rejects invoices with more than ${MAX_INVOICE_ITEMS} items`, () => {+ const result = invoiceSchema.safeParse(+ createInvoiceWithItemCount(MAX_INVOICE_ITEMS + 1),+ );++ expect(result.success).toBe(false);++ if (result.success) {+ return;+ }++ expect(result.error.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ path: ["items"],+ message: `Invoices support at most ${MAX_INVOICE_ITEMS} line items`,+ }),+ ]),+ );+ });+});diff --git a/src/app/schema/index.ts b/src/app/schema/index.tsindex cb214c3..75ab771 100644--- a/src/app/schema/index.ts+++ b/src/app/schema/index.ts@@ -672,6 +672,8 @@ export const SUPPORTED_LANGUAGES = [] as const;export type SupportedLanguages = (typeof SUPPORTED_LANGUAGES)[number];+export const MAX_INVOICE_ITEMS = 100;+export const LANGUAGE_TO_LABEL = {en: "English",pl: "Polish",@@ -1153,7 +1155,13 @@ export const invoiceObjectSchema = z.object({seller: sellerSchema,buyer: buyerSchema,- items: z.array(invoiceItemSchema).min(1, "At least one item is required"),+ items: z+ .array(invoiceItemSchema)+ .min(1, "At least one item is required")+ .max(+ MAX_INVOICE_ITEMS,+ `Invoices support at most ${MAX_INVOICE_ITEMS} line items`,+ ),/*** Total (**calculated automatically** - read only field in the UI)diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsxindex d59ef5c..edbabbb 100644--- a/src/components/ui/button.tsx+++ b/src/components/ui/button.tsx@@ -5,7 +5,7 @@ import * as React from "react";import { cn } from "@/lib/utils";const buttonVariants = cva(- "inline-flex items-center justify-center whitespace-nowrap rounded-lg text-sm font-medium transition-colors outline-offset-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring/70 disabled:pointer-events-none disabled:opacity-50 disabled:cursor-not-allowed [&_svg]:pointer-events-none [&_svg]:shrink-0 [&[data-disabled=true]]:opacity-50 active:scale-[98%] active:transition-transform",+ "inline-flex items-center justify-center whitespace-nowrap rounded-lg text-sm font-medium transition-colors outline-offset-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring/70 disabled:opacity-50 disabled:cursor-not-allowed [&_svg]:pointer-events-none [&_svg]:shrink-0 [&[data-disabled=true]]:opacity-50 active:scale-[98%] active:transition-transform",{variants: {variant: {diff --git a/src/lib/sentry/__tests__/scrub-sensitive-url-params.test.ts b/src/lib/sentry/__tests__/scrub-sensitive-url-params.test.tsnew file mode 100644index 0000000..14f1209--- /dev/null+++ b/src/lib/sentry/__tests__/scrub-sensitive-url-params.test.ts@@ -0,0 +1,218 @@+import type { ErrorEvent, Event } from "@sentry/nextjs";+import { describe, expect, it } from "vitest";++import {+ scrubSensitiveUrlParamsBeforeBreadcrumb,+ scrubSensitiveUrlParamsFromEvent,+ scrubUrl,+} from "../scrub-sensitive-url-params";++describe("scrubUrl", () => {+ it("redacts the `data` param in an absolute url", () => {+ expect(scrubUrl("https://easyinvoicepdf.com/?data=N4IgtghgLg")).toBe(+ "https://easyinvoicepdf.com/?data=[Filtered]",+ );+ });++ it("redacts the `data` param in a relative url", () => {+ expect(scrubUrl("/en?data=N4IgtghgLg")).toBe("/en?data=[Filtered]");+ });++ it("keeps the other params and their order", () => {+ expect(scrubUrl("/?locale=pl&data=N4IgtghgLg¤cy=EUR")).toBe(+ "/?locale=pl&data=[Filtered]¤cy=EUR",+ );+ });++ it("keeps the hash", () => {+ expect(scrubUrl("/?data=N4IgtghgLg#invoice")).toBe(+ "/?data=[Filtered]#invoice",+ );+ expect(scrubUrl("/?locale=pl&data=N4IgtghgLg#invoice")).toBe(+ "/?locale=pl&data=[Filtered]#invoice",+ );+ });++ it("redacts an empty `data` param (corrupted invoice url)", () => {+ expect(scrubUrl("https://easyinvoicepdf.com/?data=")).toBe(+ "https://easyinvoicepdf.com/?data=[Filtered]",+ );+ });++ it("redacts every occurrence of the `data` param", () => {+ expect(scrubUrl("/?data=one&locale=pl&data=two")).toBe(+ "/?data=[Filtered]&locale=pl",+ );+ });++ it("leaves urls without sensitive params untouched", () => {+ expect(scrubUrl("https://easyinvoicepdf.com/about")).toBe(+ "https://easyinvoicepdf.com/about",+ );+ expect(scrubUrl("/api/generate-invoice?foo=a%20b&bar=%2B")).toBe(+ "/api/generate-invoice?foo=a%20b&bar=%2B",+ );+ expect(scrubUrl("")).toBe("");+ });++ it("does not treat a `?` inside the hash as a query string", () => {+ expect(scrubUrl("/en#section?data=N4IgtghgLg")).toBe(+ "/en#section?data=N4IgtghgLg",+ );+ });++ it("never leaks the invoice payload, whatever the url shape", () => {+ for (const url of [+ "https://easyinvoicepdf.com/?data=N4IgtghgLg",+ "/en?locale=pl&data=N4IgtghgLg#invoice",+ "/?data=N4IgtghgLg&data=N4IgtghgLg",+ ]) {+ expect(scrubUrl(url)).not.toContain("N4IgtghgLg");+ }+ });++ it("does not touch params that merely contain `data`", () => {+ expect(scrubUrl("/?metadata=keep&datax=keep")).toBe(+ "/?metadata=keep&datax=keep",+ );+ });+});++describe("scrubSensitiveUrlParamsFromEvent (errors)", () => {+ it("scrubs the request url, query string and referrer", () => {+ const event = {+ request: {+ url: "https://easyinvoicepdf.com/?data=N4IgtghgLg&locale=pl",+ query_string: "data=N4IgtghgLg&locale=pl",+ headers: {+ Referer: "https://easyinvoicepdf.com/?data=N4IgtghgLg",+ "User-Agent": "Mozilla/5.0",+ },+ },+ } as unknown as ErrorEvent;++ const scrubbed = scrubSensitiveUrlParamsFromEvent(event);++ expect(scrubbed.request?.url).toBe(+ "https://easyinvoicepdf.com/?data=[Filtered]&locale=pl",+ );+ expect(scrubbed.request?.query_string).toBe("data=[Filtered]&locale=pl");+ expect(scrubbed.request?.headers?.Referer).toBe(+ "https://easyinvoicepdf.com/?data=[Filtered]",+ );+ expect(scrubbed.request?.headers?.["User-Agent"]).toBe("Mozilla/5.0");+ });++ it("scrubs navigation and fetch breadcrumbs", () => {+ const event = {+ breadcrumbs: [+ {+ category: "navigation",+ data: { from: "/?data=N4IgtghgLg", to: "/en?data=N4IgtghgLg" },+ },+ {+ category: "fetch",+ data: {+ url: "https://easyinvoicepdf.com/api/generate-invoice?data=N4IgtghgLg",+ status_code: 500,+ },+ },+ ],+ } as unknown as ErrorEvent;++ const scrubbed = scrubSensitiveUrlParamsFromEvent(event);++ expect(scrubbed.breadcrumbs?.[0]?.data).toEqual({+ from: "/?data=[Filtered]",+ to: "/en?data=[Filtered]",+ });+ expect(scrubbed.breadcrumbs?.[1]?.data).toEqual({+ url: "https://easyinvoicepdf.com/api/generate-invoice?data=[Filtered]",+ status_code: 500,+ });+ });++ it("scrubs referer headers regardless of key casing", () => {+ const event = {+ request: {+ headers: {+ REFERER: "https://easyinvoicepdf.com/?data=N4IgtghgLg",+ ReFeReR: "https://easyinvoicepdf.com/?data=N4IgtghgLg&locale=pl",+ "User-Agent": "Mozilla/5.0",+ },+ },+ } as unknown as ErrorEvent;++ const scrubbed = scrubSensitiveUrlParamsFromEvent(event);++ expect(scrubbed.request?.headers?.REFERER).toBe(+ "https://easyinvoicepdf.com/?data=[Filtered]",+ );+ expect(scrubbed.request?.headers?.ReFeReR).toBe(+ "https://easyinvoicepdf.com/?data=[Filtered]&locale=pl",+ );+ expect(scrubbed.request?.headers?.["User-Agent"]).toBe("Mozilla/5.0");+ });++ it("returns events without request data unchanged", () => {+ const event = { message: "boom" } as unknown as ErrorEvent;++ expect(scrubSensitiveUrlParamsFromEvent(event)).toEqual({+ message: "boom",+ });+ });+});++describe("scrubSensitiveUrlParamsFromEvent (transactions)", () => {+ it("scrubs trace context and span attributes", () => {+ const event = {+ contexts: {+ trace: {+ data: {+ "http.url": "https://easyinvoicepdf.com/?data=N4IgtghgLg",+ "url.query": "data=N4IgtghgLg&locale=pl",+ },+ },+ },+ spans: [+ {+ data: {+ "http.url": "https://easyinvoicepdf.com/?data=N4IgtghgLg",+ "http.method": "GET",+ },+ },+ ],+ } as unknown as Event;++ const scrubbed = scrubSensitiveUrlParamsFromEvent(event);++ expect(scrubbed.contexts?.trace?.data).toEqual({+ "http.url": "https://easyinvoicepdf.com/?data=[Filtered]",+ "url.query": "data=[Filtered]&locale=pl",+ });+ expect(scrubbed.spans?.[0]?.data).toEqual({+ "http.url": "https://easyinvoicepdf.com/?data=[Filtered]",+ "http.method": "GET",+ });+ });+});++describe("scrubSensitiveUrlParamsBeforeBreadcrumb", () => {+ it("scrubs the breadcrumb url as it is recorded", () => {+ const breadcrumb = scrubSensitiveUrlParamsBeforeBreadcrumb({+ category: "navigation",+ data: { from: "/", to: "/?data=N4IgtghgLg" },+ });++ expect(breadcrumb.data).toEqual({ from: "/", to: "/?data=[Filtered]" });+ });++ it("keeps breadcrumbs without data", () => {+ const breadcrumb = scrubSensitiveUrlParamsBeforeBreadcrumb({+ category: "console",+ message: "hello",+ });++ expect(breadcrumb).toEqual({ category: "console", message: "hello" });+ });+});diff --git a/src/lib/sentry/scrub-sensitive-url-params.ts b/src/lib/sentry/scrub-sensitive-url-params.tsnew file mode 100644index 0000000..d5aae6d--- /dev/null+++ b/src/lib/sentry/scrub-sensitive-url-params.ts@@ -0,0 +1,195 @@+import type { Breadcrumb, Event } from "@sentry/nextjs";++/**+ * Query params that carry user data and must never reach Sentry.+ *+ * `data` holds the compressed invoice (seller/buyer details, addresses, VAT ids,+ * line items), see `src/utils/url-compression.ts`.+ */+const SENSITIVE_QUERY_PARAMS = ["data"] as const;++/**+ * Replaces the value of a sensitive param, so the event still tells us an invoice+ * URL was involved without carrying the invoice itself. Matches what Sentry's own+ * server-side scrubbing uses.+ */+const REDACTED_VALUE = "[Filtered]";++/** `URLSearchParams` percent-encodes the brackets, undo that so it stays readable in Sentry. */+const ENCODED_REDACTED_VALUE = encodeURIComponent(REDACTED_VALUE);++/** Span/context attribute keys that hold a full URL. */+const URL_ATTRIBUTE_KEYS = [+ "url",+ "url.full",+ "http.url",+ "http.target",+] as const;++/** Span/context attribute keys that hold a bare query string. */+const QUERY_ATTRIBUTE_KEYS = ["url.query", "http.query"] as const;++/** Breadcrumb data keys that hold a URL (`from`/`to` come from navigation breadcrumbs). */+const BREADCRUMB_URL_KEYS = ["url", "from", "to"] as const;++/**+ * Redact sensitive params in a bare query string (no leading `?`).+ *+ * Returns the input untouched when there is nothing to redact, so unrelated+ * params keep their original encoding.+ */+function scrubQueryString(queryString: string) {+ if (!queryString) {+ return queryString;+ }++ const hasLeadingQuestionMark = queryString.startsWith("?");+ const rawQuery = hasLeadingQuestionMark ? queryString.slice(1) : queryString;++ const params = new URLSearchParams(rawQuery);++ const hasSensitiveParam = SENSITIVE_QUERY_PARAMS.some((param) =>+ params.has(param),+ );++ if (!hasSensitiveParam) {+ return queryString;+ }++ for (const param of SENSITIVE_QUERY_PARAMS) {+ if (params.has(param)) {+ params.set(param, REDACTED_VALUE);+ }+ }++ const scrubbedQuery = params+ .toString()+ .replaceAll(ENCODED_REDACTED_VALUE, REDACTED_VALUE);++ return hasLeadingQuestionMark ? `?${scrubbedQuery}` : scrubbedQuery;+}++/**+ * Redact sensitive params in a URL, keeping everything else intact.+ *+ * Works with absolute URLs, relative paths and hashes:+ * `/en?data=abc&foo=1#bar` -> `/en?data=[Filtered]&foo=1#bar`+ */+export function scrubUrl(url: string) {+ if (!url?.includes("?")) {+ return url;+ }++ const hashIndex = url.indexOf("#");+ const hash = hashIndex === -1 ? "" : url.slice(hashIndex);+ const urlWithoutHash = hashIndex === -1 ? url : url.slice(0, hashIndex);++ const queryIndex = urlWithoutHash.indexOf("?");++ // The `?` we matched on lives inside the hash, nothing to scrub+ if (queryIndex === -1) {+ return url;+ }++ const base = urlWithoutHash.slice(0, queryIndex);+ const scrubbedQuery = scrubQueryString(urlWithoutHash.slice(queryIndex + 1));++ return scrubbedQuery ? `${base}?${scrubbedQuery}${hash}` : `${base}${hash}`;+}++function scrubAttributes(attributes: Record<string, unknown> | undefined) {+ if (!attributes) {+ return;+ }++ for (const key of URL_ATTRIBUTE_KEYS) {+ const value = attributes[key];++ if (typeof value === "string") {+ attributes[key] = scrubUrl(value);+ }+ }++ for (const key of QUERY_ATTRIBUTE_KEYS) {+ const value = attributes[key];++ if (typeof value === "string") {+ attributes[key] = scrubQueryString(value);+ }+ }+}++function scrubBreadcrumb(breadcrumb: Breadcrumb) {+ const data = breadcrumb.data;++ if (!data) {+ return;+ }++ for (const key of BREADCRUMB_URL_KEYS) {+ const value: unknown = data[key];++ if (typeof value === "string") {+ data[key] = scrubUrl(value);+ }+ }+}++/**+ * Redact sensitive query params in every place Sentry stores a URL on an event:+ * the request url/query string, the referrer header, breadcrumbs and span data.+ *+ * Used as the `beforeSend` and `beforeSendTransaction` hook. Mutates and returns+ * the event, as Sentry expects.+ */+export function scrubSensitiveUrlParamsFromEvent<T extends Event>(event: T): T {+ const request = event.request;++ if (request) {+ if (typeof request.url === "string") {+ request.url = scrubUrl(request.url);+ }++ if (typeof request.query_string === "string") {+ request.query_string = scrubQueryString(request.query_string);+ }++ const headers = request.headers;++ if (headers) {+ for (const [key, value] of Object.entries(headers)) {+ if (key.toLowerCase() === "referer" && typeof value === "string") {+ headers[key] = scrubUrl(value);+ }+ }+ }+ }++ if (event.breadcrumbs) {+ for (const breadcrumb of event.breadcrumbs) {+ scrubBreadcrumb(breadcrumb);+ }+ }++ scrubAttributes(event.contexts?.trace?.data);++ if (event.spans) {+ for (const span of event.spans) {+ scrubAttributes(span.data);+ }+ }++ return event;+}++/**+ * Sentry `beforeBreadcrumb` hook: scrubs URLs as breadcrumbs are recorded, so+ * they are already clean if they get attached to a later event.+ */+export function scrubSensitiveUrlParamsBeforeBreadcrumb(+ breadcrumb: Breadcrumb,+): Breadcrumb {+ scrubBreadcrumb(breadcrumb);++ return breadcrumb;+}