Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.
TypeScript fintechinvoiceinvoice-generatorinvoice-pdfinvoice-templateinvoicesnextjsopen-sourcequotesreactreact-pdf-rendererself-hostedshadcn-uitailwindcsstypescript
feat: regroup General Information, add a Stripe top line color, update Seller & Buyer designs (#291)
Vlad Sazonau021d61dfdf91
diff --git a/e2e/contacts-backup.test.ts b/e2e/contacts-backup.test.tsindex 86b2f4c..dfedf36 100644--- a/e2e/contacts-backup.test.ts+++ b/e2e/contacts-backup.test.ts@@ -154,10 +154,10 @@ test.describe("Sellers & buyers backup", () => {).toBeVisible();await expect(importDialog.getByRole("list", { name: "Sellers" }),- ).toContainText(SELLER.name);+ ).toContainText(`${SELLER.name}${SELLER.address}`);await expect(importDialog.getByRole("list", { name: "Buyers" }),- ).toContainText(BUYER.name);+ ).toContainText(`${BUYER.name}${BUYER.address}`);// Nothing is saved before the user confirmsawait expect(sellerDropdown).toBeHidden();@@ -209,7 +209,7 @@ test.describe("Sellers & buyers backup", () => {).toBeVisible();await expect(importDialog.getByRole("list", { name: "Sellers" }),- ).toContainText(`${SELLER.name}${SELLER.address}Already saved`);+ ).toContainText(`${SELLER.name}${SELLER.address}`);await expect(importDialog.getByRole("button", { name: /^Import/ }),).toBeHidden();diff --git a/e2e/default-invoice-template/default-invoice-template.test.ts b/e2e/default-invoice-template/default-invoice-template.test.tsindex a04f101..251a9f5 100644--- a/e2e/default-invoice-template/default-invoice-template.test.ts+++ b/e2e/default-invoice-template/default-invoice-template.test.ts@@ -59,8 +59,8 @@ test.describe("Default Invoice Template", () => {// the invoice number label follows the selected languageawait expect(page- .getByRole("group", { name: "Invoice Number" })- .getByRole("textbox", { name: "Label" }),+ .getByRole("group", { name: "Invoice details" })+ .getByRole("textbox", { name: "Invoice number label" }),).toHaveValue(`${INVOICE_PDF_TRANSLATIONS.pl.invoiceNumber}:`);const invoiceItemsSection = page.getByTestId("invoice-items-section");@@ -341,17 +341,19 @@ test.describe("Default Invoice Template", () => {// check that value is saved in the hidden inputawait expect(page.locator('input[name="currency"]')).toHaveValue("GBP");- const invoiceNumberFieldset = page.getByRole("group", {- name: "Invoice Number",+ const invoiceDetailsFieldset = page.getByRole("group", {+ name: "Invoice details",});- const invoiceNumberLabelInput = invoiceNumberFieldset.getByRole("textbox", {- name: "Label",- });+ const invoiceNumberLabelInput = invoiceDetailsFieldset.getByRole(+ "textbox",+ { name: "Invoice number label" },+ );- const invoiceNumberValueInput = invoiceNumberFieldset.getByRole("textbox", {- name: "Value",- });+ const invoiceNumberValueInput = invoiceDetailsFieldset.getByRole(+ "textbox",+ { name: "Invoice number", exact: true },+ );const INVOICE_NUMBER_LABEL = "INVOICE NUMBER MOBILE TEST:";@@ -516,17 +518,19 @@ test.describe("Default Invoice Template", () => {}) => {const generalInfoSection = page.getByTestId("general-information-section");- const invoiceNumberFieldset = generalInfoSection.getByRole("group", {- name: "Invoice Number",+ const invoiceDetailsFieldset = generalInfoSection.getByRole("group", {+ name: "Invoice details",});- const invoiceNumberLabelInput = invoiceNumberFieldset.getByRole("textbox", {- name: "Label",- });+ const invoiceNumberLabelInput = invoiceDetailsFieldset.getByRole(+ "textbox",+ { name: "Invoice number label" },+ );- const invoiceNumberValueInput = invoiceNumberFieldset.getByRole("textbox", {- name: "Value",- });+ const invoiceNumberValueInput = invoiceDetailsFieldset.getByRole(+ "textbox",+ { name: "Invoice number", exact: true },+ );await expect(invoiceNumberLabelInput).toHaveValue(INITIAL_INVOICE_DATA.invoiceNumberObject.label,@@ -591,11 +595,9 @@ test.describe("Default Invoice Template", () => {// Verify that the download PDF button is visible after page reloadawait expect(getDownloadPdfLink(page)).toBeVisible();- const newInvoiceNumberLabelInput = invoiceNumberFieldset.getByRole(+ const newInvoiceNumberLabelInput = invoiceDetailsFieldset.getByRole("textbox",- {- name: "Label",- },+ { name: "Invoice number label" },);// Verify that the invoice number is persisted after page reload@@ -763,7 +765,7 @@ test.describe("Default Invoice Template", () => {await expect(servicePeriodFieldset).toBeVisible();const dateOfServiceLabelInput = servicePeriodFieldset.getByRole("textbox", {- name: "Date of sales PDF label",+ name: "Date of sales label",});await expect(dateOfServiceLabelInput).toHaveValue(@@ -811,7 +813,7 @@ test.describe("Default Invoice Template", () => {const newDateOfServiceLabelInput = newServicePeriodFieldset.getByRole("textbox",{- name: "Date of sales PDF label",+ name: "Date of sales label",},);await expect(newDateOfServiceLabelInput).toHaveValue(diff --git a/e2e/generate-invoice-link.test.ts b/e2e/generate-invoice-link.test.tsindex cc0fc3b..92941b8 100644--- a/e2e/generate-invoice-link.test.ts+++ b/e2e/generate-invoice-link.test.ts@@ -57,15 +57,13 @@ test.describe("Generate Invoice Link (Get link)", () => {await expect(page.getByTestId("shared-invoice-badge")).toBeHidden();// Fill in some test data- const invoiceNumberFieldset = page.getByRole("group", {- name: "Invoice Number",+ const invoiceDetailsFieldset = page.getByRole("group", {+ name: "Invoice details",});- const invoiceNumberValueField = invoiceNumberFieldset.getByRole(+ const invoiceNumberValueField = invoiceDetailsFieldset.getByRole("textbox",- {- name: "Value",- },+ { name: "Invoice number", exact: true },);await invoiceNumberValueField.fill("SHARE-TEST-001");@@ -202,14 +200,17 @@ test.describe("Generate Invoice Link (Get link)", () => {await expect(newPage).toHaveURL(/\/\?data=/);// Get elements from the new page context- const newInvoiceNumberFieldset = newPage.getByRole("group", {- name: "Invoice Number",+ const newInvoiceDetailsFieldset = newPage.getByRole("group", {+ name: "Invoice details",});/* VERIFY DATA IS LOADED IN NEW TAB */await expect(- newInvoiceNumberFieldset.getByRole("textbox", { name: "Value" }),+ newInvoiceDetailsFieldset.getByRole("textbox", {+ name: "Invoice number",+ exact: true,+ }),).toHaveValue("SHARE-TEST-001");const newPageFinalSection = newPage.getByTestId(`final-section`);@@ -515,17 +516,22 @@ test.describe("Generate Invoice Link (Get link)", () => {).toHaveValue("stripe");// Invoice Number- const invoiceNumberFieldset = page.getByRole("group", {- name: "Invoice Number",+ const invoiceDetailsFieldset = page.getByRole("group", {+ name: "Invoice details",});// Old URLs load without ?template=, so the stored default-template label is kept.await expect(- invoiceNumberFieldset.getByRole("textbox", { name: "Label" }),+ invoiceDetailsFieldset.getByRole("textbox", {+ name: "Invoice number label",+ }),).toHaveValue("Faktura nr:");await expect(- invoiceNumberFieldset.getByRole("textbox", { name: "Value" }),+ invoiceDetailsFieldset.getByRole("textbox", {+ name: "Invoice number",+ exact: true,+ }),).toHaveValue("1/08-2025");// Verify seller information is loaded@@ -580,17 +586,22 @@ test.describe("Generate Invoice Link (Get link)", () => {).toHaveValue("stripe");// Invoice Number- const newInvoiceNumberFieldset = page.getByRole("group", {- name: "Invoice Number",+ const newInvoiceDetailsFieldset = page.getByRole("group", {+ name: "Invoice details",});// Compressed URLs include ?template=stripe, so the label migrates to the Stripe default.await expect(- newInvoiceNumberFieldset.getByRole("textbox", { name: "Label" }),+ newInvoiceDetailsFieldset.getByRole("textbox", {+ name: "Invoice number label",+ }),).toHaveValue("Faktura");await expect(- newInvoiceNumberFieldset.getByRole("textbox", { name: "Value" }),+ newInvoiceDetailsFieldset.getByRole("textbox", {+ name: "Invoice number",+ exact: true,+ }),).toHaveValue("1/08-2025");// Verify seller information is loaded@@ -640,13 +651,14 @@ test.describe("Generate Invoice Link (Get link)", () => {};// Fill in invoice number- const invoiceNumberFieldset = page.getByRole("group", {- name: "Invoice Number",+ const invoiceDetailsFieldset = page.getByRole("group", {+ name: "Invoice details",});- const invoiceNumberValueField = invoiceNumberFieldset.getByRole("textbox", {- name: "Value",- });+ const invoiceNumberValueField = invoiceDetailsFieldset.getByRole(+ "textbox",+ { name: "Invoice number", exact: true },+ );await invoiceNumberValueField.fill(INVOICE_TEST_DATA.invoiceNumber);@@ -713,15 +725,13 @@ test.describe("Generate Invoice Link (Get link)", () => {await expect(newPage).toHaveURL(/\/\?data=/);// Get the invoice number field from the new page- const newInvoiceNumberFieldset = newPage.getByRole("group", {- name: "Invoice Number",+ const newInvoiceDetailsFieldset = newPage.getByRole("group", {+ name: "Invoice details",});- const newInvoiceNumberValueField = newInvoiceNumberFieldset.getByRole(+ const newInvoiceNumberValueField = newInvoiceDetailsFieldset.getByRole("textbox",- {- name: "Value",- },+ { name: "Invoice number", exact: true },);/**@@ -794,12 +804,12 @@ test.describe("Generate Invoice Link (Get link)", () => {page,}) => {// Fill in invoice number- const invoiceNumberFieldset = page.getByRole("group", {- name: "Invoice Number",+ const invoiceDetailsFieldset = page.getByRole("group", {+ name: "Invoice details",});- await invoiceNumberFieldset- .getByRole("textbox", { name: "Label" })+ await invoiceDetailsFieldset+ .getByRole("textbox", { name: "Invoice number label" }).fill("URL-LIMIT-TEST-001");/**diff --git a/e2e/invoice-form.test.ts b/e2e/invoice-form.test.tsindex 080c0bb..e54fd07 100644--- a/e2e/invoice-form.test.ts+++ b/e2e/invoice-form.test.ts@@ -279,8 +279,8 @@ test.describe("Invoice Generator Page", () => {const NEW_INVOICE_NUMBER = "QUICK-TAB-SWITCH/2026";const invoiceNumberValueInput = page- .getByRole("group", { name: "Invoice Number" })- .getByRole("textbox", { name: "Value" });+ .getByRole("group", { name: "Invoice details" })+ .getByRole("textbox", { name: "Invoice number", exact: true });await expect(invoiceNumberValueInput).toHaveValue(INITIAL_INVOICE_DATA.invoiceNumberObject.value,@@ -354,8 +354,8 @@ test.describe("Invoice Generator Page", () => {await page.clock.pauseAt(new Date(pageTime + CLOCK_PAUSE_MARGIN));const invoiceNumberValueInput = page- .getByRole("group", { name: "Invoice Number" })- .getByRole("textbox", { name: "Value" });+ .getByRole("group", { name: "Invoice details" })+ .getByRole("textbox", { name: "Invoice number", exact: true });await invoiceNumberValueInput.fill(NEW_INVOICE_NUMBER);@@ -472,16 +472,21 @@ test.describe("Invoice Generator Page", () => {}// Invoice Number- const invoiceNumberFieldset = page.getByRole("group", {- name: "Invoice Number",+ const invoiceDetailsFieldset = page.getByRole("group", {+ name: "Invoice details",});await expect(- invoiceNumberFieldset.getByRole("textbox", { name: "Label" }),+ invoiceDetailsFieldset.getByRole("textbox", {+ name: "Invoice number label",+ }),).toHaveValue(INITIAL_INVOICE_DATA.invoiceNumberObject.label);await expect(- invoiceNumberFieldset.getByRole("textbox", { name: "Value" }),+ invoiceDetailsFieldset.getByRole("textbox", {+ name: "Invoice number",+ exact: true,+ }),).toHaveValue(INITIAL_INVOICE_DATA.invoiceNumberObject.value);// Date of Issue@@ -498,13 +503,13 @@ test.describe("Invoice Generator Page", () => {await expect(servicePeriodFieldset.getByRole("textbox", {- name: "Service period PDF label",+ name: "Service period label",}),).toHaveValue(INITIAL_INVOICE_DATA.servicePeriodLabelText);await expect(servicePeriodFieldset.getByRole("textbox", {- name: "Date of sales PDF label",+ name: "Date of sales label",}),).toHaveValue(INITIAL_INVOICE_DATA.dateOfServiceLabelText);@@ -520,11 +525,6 @@ test.describe("Invoice Generator Page", () => {}),).toHaveValue(INITIAL_INVOICE_DATA.dateOfService);- // Check that info icon is visible- await expect(- servicePeriodFieldset.getByTestId("service-period-end-info-icon"),- ).toBeVisible();-await expect(servicePeriodFieldset.getByRole("switch", {name: 'Show the "Service period" (Service period start and end) field in the PDF',@@ -546,11 +546,13 @@ test.describe("Invoice Generator Page", () => {}),).toBeEditable();+ // with the date of sales hidden, the end date is printed only in the service period,+ // so the helper that names the date of sales goes awayawait expect(- servicePeriodFieldset.getByRole("button", {- name: 'Shown on PDF as part of "Service period" and as "Date of sales/of executing the service"',+ servicePeriodFieldset.getByRole("textbox", {+ name: "Service period end",}),- ).toBeVisible();+ ).toHaveAccessibleDescription("");// Invoice Typeawait expect(@@ -832,10 +834,10 @@ test.describe("Invoice Generator Page", () => {});const servicePeriodLabelInput = servicePeriodFieldset.getByRole("textbox", {- name: "Service period PDF label",+ name: "Service period label",});const dateOfServiceLabelInput = servicePeriodFieldset.getByRole("textbox", {- name: "Date of sales PDF label",+ name: "Date of sales label",});await servicePeriodLabelInput.fill("Custom service period label");@@ -1150,13 +1152,14 @@ test.describe("Invoice Generator Page", () => {const dateOfIssue = dayjs().format("YYYY-MM-DD");- const invoiceNumberFieldset = page.getByRole("group", {- name: "Invoice Number",+ const invoiceDetailsFieldset = page.getByRole("group", {+ name: "Invoice details",});- const invoiceNumberValueField = invoiceNumberFieldset.getByRole("textbox", {- name: "Value",- });+ const invoiceNumberValueField = invoiceDetailsFieldset.getByRole(+ "textbox",+ { name: "Invoice number", exact: true },+ );await invoiceNumberValueField.fill("1/03-2025");@@ -1205,15 +1208,13 @@ test.describe("Invoice Generator Page", () => {},async ({ page }) => {// Fill in some data- const invoiceNumberFieldset = page.getByRole("group", {- name: "Invoice Number",+ const invoiceDetailsFieldset = page.getByRole("group", {+ name: "Invoice details",});- const invoiceNumberValueField = invoiceNumberFieldset.getByRole(+ const invoiceNumberValueField = invoiceDetailsFieldset.getByRole("textbox",- {- name: "Value",- },+ { name: "Invoice number", exact: true },);await invoiceNumberValueField.fill("TEST/2024");@@ -1253,15 +1254,13 @@ test.describe("Invoice Generator Page", () => {await page.reload();// Check if data persists in UI- const invoiceNumberFieldset2 = page.getByRole("group", {- name: "Invoice Number",+ const invoiceDetailsFieldset2 = page.getByRole("group", {+ name: "Invoice details",});- const invoiceNumberValueField2 = invoiceNumberFieldset2.getByRole(+ const invoiceNumberValueField2 = invoiceDetailsFieldset2.getByRole("textbox",- {- name: "Value",- },+ { name: "Invoice number", exact: true },);await expect(invoiceNumberValueField2).toHaveValue("TEST/2024");@@ -1747,9 +1746,11 @@ test.describe("Invoice Generator Page", () => {const dateOfIssueInput = generalInfoSection.getByLabel("Date of Issue");await dateOfIssueInput.fill("2024-01-15");- // Verify per-field "Date of issue is not today" inline helper message+ // Verify the per-field "Not today" warning and its fixawait expect(- generalInfoSection.getByText("Date of issue is not today"),+ generalInfoSection.getByRole("button", {+ name: /Set date of issue to today/,+ }),).toBeVisible();// Set service period end to a date that's not the last day of current month@@ -1764,38 +1765,52 @@ test.describe("Invoice Generator Page", () => {// Verify per-field service period start helper messageawait expect(- generalInfoSection.getByText(- "Service period start is not in the current month",- ),+ generalInfoSection.getByRole("button", {+ name: /Set service period start to/,+ }),).toBeVisible();// Verify per-field service period end helper messageawait expect(- generalInfoSection.getByText(- "Service period end is not the last day of the current month",- ),+ generalInfoSection.getByRole("button", {+ name: /Set service period end to/,+ }),).toBeVisible();// Set invoice number to an old month to trigger stale state- const invoiceNumberInput = generalInfoSection.getByLabel("Value");+ const invoiceNumberInput = generalInfoSection.getByLabel("Invoice number", {+ exact: true,+ });await invoiceNumberInput.fill("1/01-2024");- // Verify per-field "Invoice number does not match current month" inline helper message+ // Verify the per-field "Not current month" warning and its fixawait expect(- generalInfoSection.getByText(- "Invoice number does not match current month",- ),+ generalInfoSection.getByRole("button", {+ name: /Set invoice number to/,+ }),).toBeVisible();- // Set payment due to a stale date (date of issue + 1 day instead of + 14 days)+ // Due 1 day after issue: a payment term of its own, which "Update All Dates" keeps+ // without listing itconst paymentDueInput = page.getByLabel("Payment Due");await paymentDueInput.fill("2024-01-16");- const paymentDueBtn = page.getByRole("button", {- name: "Set payment due date to 2024-01-29 (14 days from issue date)",+ // a due date after the issue date gets no fix-it button, only the payment terms,+ // none of which it matches+ await expect(+ generalInfoSection.getByText("Due 1 day after issue"),+ ).toBeVisible();++ const paymentTerms = generalInfoSection.getByRole("group", {+ name: "Payment terms",});- await expect(paymentDueBtn).toBeVisible();- await expect(paymentDueBtn).toBeEnabled();+ await expect(+ paymentTerms.getByRole("button", { name: "14 days" }),+ ).toHaveAttribute("aria-pressed", "false");++ await expect(+ page.getByRole("button", { name: /set payment due date to/i }),+ ).toBeHidden();// Verify the OutOfDateDatesHelper component appears with the table-based UIconst outOfDateHelper = page.getByTestId("out-of-date-dates-helper");@@ -1803,7 +1818,7 @@ test.describe("Invoice Generator Page", () => {// Verify the header shows the correct count of stale fieldsawait expect(- outOfDateHelper.getByText("5 fields are out of date"),+ outOfDateHelper.getByText("4 fields are out of date"),).toBeVisible();// Verify each stale field appears as a row in the table@@ -1819,9 +1834,10 @@ test.describe("Invoice Generator Page", () => {await expect(outOfDateHelper.getByText("Invoice number", { exact: true }),).toBeVisible();+ // due after the date of issue, so it is a payment term, not an out-of-date fieldawait expect(outOfDateHelper.getByText("Payment due", { exact: true }),- ).toBeVisible();+ ).toBeHidden();// Verify the table shows old → new values per row (avoids strict mode when targets match)const dateOfIssueRow = outOfDateHelper@@ -1850,12 +1866,6 @@ test.describe("Invoice Generator Page", () => {await expect(invoiceNumberRow.getByText("1/01-2024")).toBeVisible();await expect(invoiceNumberRow.getByText("1/12-2025")).toBeVisible();- const paymentDueRow = outOfDateHelper- .getByRole("row")- .filter({ hasText: "Payment due" });- await expect(paymentDueRow.getByText("2024-01-16")).toBeVisible();- await expect(paymentDueRow.getByText("2025-12-15")).toBeVisible();-// Verify the "Update All Dates" button is visibleconst updateAllDatesButton = outOfDateHelper.getByRole("button", {name: "Update All Dates",@@ -1873,19 +1883,21 @@ test.describe("Invoice Generator Page", () => {page.getByText("All dates updated successfully"),).toBeVisible();- // Verify per-field inline helper messages are gone+ // Verify the per-field warnings are goneawait expect(- generalInfoSection.getByText("Date of issue is not today"),+ generalInfoSection.getByRole("button", {+ name: /Set date of issue to today/,+ }),).toBeHidden();await expect(- generalInfoSection.getByText(- "Service period end is not the last day of the current month",- ),+ generalInfoSection.getByRole("button", {+ name: /Set service period end to/,+ }),).toBeHidden();await expect(- generalInfoSection.getByText(- "Service period start is not in the current month",- ),+ generalInfoSection.getByRole("button", {+ name: /Set service period start to/,+ }),).toBeHidden();// Verify all fields were updated to correct values@@ -1893,7 +1905,7 @@ test.describe("Invoice Generator Page", () => {await expect(dateOfServiceStartInput).toHaveValue("2025-12-01");await expect(dateOfServiceInput).toHaveValue("2025-12-31");await expect(invoiceNumberInput).toHaveValue("1/12-2025");- await expect(paymentDueInput).toHaveValue("2025-12-15");+ await expect(paymentDueInput).toHaveValue("2025-12-02");});test("allows setting date of issue to today from inline helper", async ({@@ -1912,7 +1924,9 @@ test.describe("Invoice Generator Page", () => {await dateOfIssueInput.fill("2024-01-15");await expect(- generalInfoSection.getByText("Date of issue is not today"),+ generalInfoSection.getByRole("button", {+ name: /Set date of issue to today/,+ }),).toBeVisible();await generalInfoSection@@ -1921,7 +1935,9 @@ test.describe("Invoice Generator Page", () => {await expect(dateOfIssueInput).toHaveValue("2025-12-01");await expect(- generalInfoSection.getByText("Date of issue is not today"),+ generalInfoSection.getByRole("button", {+ name: /Set date of issue to today/,+ }),).toBeHidden();await expect(page.getByLabel("Payment Due")).toHaveValue("2025-12-15");});@@ -1936,7 +1952,7 @@ test.describe("Invoice Generator Page", () => {name: "Service period",});const servicePeriodLabelInput = servicePeriodFieldset.getByRole("textbox", {- name: "Service period PDF label",+ name: "Service period label",});const defaultLabel = INVOICE_PDF_TRANSLATIONS.en.servicePeriod;const resetToDefaultButton = servicePeriodFieldset.getByRole("button", {@@ -1963,7 +1979,7 @@ test.describe("Invoice Generator Page", () => {name: "Service period",});const dateOfServiceLabelInput = servicePeriodFieldset.getByRole("textbox", {- name: "Date of sales PDF label",+ name: "Date of sales label",});const defaultLabel = INVOICE_PDF_TRANSLATIONS.en.dateOfService;const resetToDefaultButton = servicePeriodFieldset.getByRole("button", {diff --git a/e2e/invoice-templates-common/shared-template-features.test.ts b/e2e/invoice-templates-common/shared-template-features.test.tsindex d070790..fb4a89e 100644--- a/e2e/invoice-templates-common/shared-template-features.test.ts+++ b/e2e/invoice-templates-common/shared-template-features.test.ts@@ -67,7 +67,7 @@ async function expectServicePeriodPdfLabels(expectedServicePeriodLabel: string,) {const servicePeriodLabelInput = servicePeriodFieldset.getByRole("textbox", {- name: "Service period PDF label",+ name: "Service period label",});if (template === "default") {@@ -80,7 +80,7 @@ async function expectServicePeriodPdfLabels(await expect(servicePeriodLabelInput).toBeHidden();await expect(servicePeriodFieldset.getByRole("textbox", {- name: "Date of sales PDF label",+ name: "Date of sales label",}),).toBeHidden();}@@ -99,7 +99,7 @@ async function fillCustomServicePeriodPdfLabel(}const servicePeriodLabelInput = servicePeriodFieldset.getByRole("textbox", {- name: "Service period PDF label",+ name: "Service period label",});await servicePeriodLabelInput.fill(customLabel);@@ -124,7 +124,7 @@ async function expectCustomServicePeriodPdfLabel(await expect(servicePeriodFieldset.getByRole("textbox", {- name: "Service period PDF label",+ name: "Service period label",}),).toHaveValue(customLabel);}@@ -671,7 +671,7 @@ test.describe("Invoice Template shared features", () => {const sellerEmailSwitchInDialog = manageSellerDialog.getByRole("switch",{- name: "Show Seller Email in PDF",+ name: "Show the 'Email' field in the PDF",},);await expect(sellerEmailSwitchInDialog).toBeVisible();@@ -710,7 +710,7 @@ test.describe("Invoice Template shared features", () => {// Verify email visibility switch is checked by default in dialogconst buyerEmailSwitchInDialog = manageBuyerDialog.getByRole("switch", {- name: "Show Buyer Email in PDF",+ name: "Show the 'Email' field in the PDF",});await expect(buyerEmailSwitchInDialog).toBeVisible();await expect(buyerEmailSwitchInDialog).toBeChecked();@@ -773,9 +773,10 @@ test.describe("Invoice Template shared features", () => {await page.goto("/");await expect(page).toHaveURL(buildInvoiceAppUrl({ template }));- const numberFormatSelect = page- .getByRole("group", { name: "Number Format" })- .getByRole("combobox", { name: "Format" });+ const numberFormatSelect = page.getByRole("combobox", {+ name: "Number Format",+ exact: true,+ });await waitForPdfRegeneration(page, async () => {await numberFormatSelect.selectOption("international");diff --git a/e2e/invoice-templates-common/template-languages.test.ts b/e2e/invoice-templates-common/template-languages.test.tsindex 4b2a909..c5ef0d6 100644--- a/e2e/invoice-templates-common/template-languages.test.ts+++ b/e2e/invoice-templates-common/template-languages.test.ts@@ -110,8 +110,8 @@ async function expectTranslatedInvoiceNumberLabel() {const invoiceNumberLabelInput = page.getByTestId("general-information-section")- .getByRole("group", { name: "Invoice Number" })- .getByRole("textbox", { name: "Label" });+ .getByRole("group", { name: "Invoice details" })+ .getByRole("textbox", { name: "Invoice number label" });await expect(invoiceNumberLabelInput).toHaveValue(getDefaultInvoiceNumberLabel(language, template),diff --git a/e2e/seller-buyer-management.test.ts b/e2e/seller-buyer-management.test.tsindex e51c893..28ee145 100644--- a/e2e/seller-buyer-management.test.ts+++ b/e2e/seller-buyer-management.test.ts@@ -145,10 +145,10 @@ async function toggleBankDetailsOff(dialog: Locator, party: Party) {}const accountNumberSwitch = dialog.getByRole("switch", {- name: "Show Seller Account Number in PDF",+ name: "Show the 'Account Number' field in the PDF",});const swiftBicSwitch = dialog.getByRole("switch", {- name: "Show Seller SWIFT/BIC in PDF",+ name: "Show the 'SWIFT/BIC' field in the PDF",});await expect(accountNumberSwitch).toBeChecked();@@ -175,41 +175,73 @@ async function expectBankDetailsInDialog(dialog: Locator, party: Party) {);await expect(- dialog.getByRole("switch", { name: "Show Seller Account Number in PDF" }),+ dialog.getByRole("switch", {+ name: "Show the 'Account Number' field in the PDF",+ }),).not.toBeChecked();await expect(- dialog.getByRole("switch", { name: "Show Seller SWIFT/BIC in PDF" }),+ dialog.getByRole("switch", {+ name: "Show the 'SWIFT/BIC' field in the PDF",+ }),).not.toBeChecked();}-/**- * Verifies the seller-only bank details in the (read-only) invoice form section;- * a no-op for buyers.- */-async function expectBankDetailsInForm(form: Locator, party: Party) {+interface ExpectCardFieldOptions {+ /** The row label, which for the tax number is the party's own label. */+ label: string;+ value: string;+ /** The field is filled in but left out of the PDF. */+ isHidden?: boolean;+}++/** Verifies one row of the saved party card, including its "Hidden on invoice" chip. */+async function expectCardField(+ card: Locator,+ { label, value, isHidden = false }: ExpectCardFieldOptions,+) {+ const row = card+ .locator("dl > div")+ .filter({ has: card.page().getByText(label, { exact: true }) });++ await expect(row.locator("dd")).toHaveText(+ isHidden ? `${value}Hidden on invoice` : value,+ );+}++interface ExpectCardHeaderOptions {+ name: string;+ address: string;+}++/** Verifies the name and address heading the saved party card, which are not list rows. */+async function expectCardHeader(+ card: Locator,+ { name, address }: ExpectCardHeaderOptions,+) {+ const header = card.locator("header");++ await expect(header.getByText(name, { exact: true })).toBeVisible();+ await expect(header.getByText(address, { exact: true })).toBeVisible();+}++/** Verifies the seller-only bank details in the saved party card; a no-op for buyers. */+async function expectBankDetailsInCard(card: Locator, party: Party) {const bankDetails = BANK_DETAILS[party];if (!bankDetails) {return;}- await expect(- form.getByRole("textbox", { name: "Account Number" }),- ).toHaveValue(bankDetails.accountNumber);-- const accountNumberSwitch = form.getByTestId(- `${party}AccountNumberFieldIsVisible`,- );- await expect(accountNumberSwitch).not.toBeChecked();- await expect(accountNumberSwitch).toBeDisabled();-- await expect(form.getByRole("textbox", { name: "SWIFT/BIC" })).toHaveValue(- bankDetails.swiftBic,- );-- const swiftBicSwitch = form.getByTestId(`${party}SwiftBicFieldIsVisible`);- await expect(swiftBicSwitch).not.toBeChecked();- await expect(swiftBicSwitch).toBeDisabled();+ await expectCardField(card, {+ label: "Account Number",+ value: bankDetails.accountNumber,+ isHidden: true,+ });+ await expectCardField(card, {+ label: "SWIFT/BIC",+ value: bankDetails.swiftBic,+ isHidden: true,+ });}async function expectStoredBankDetails(@@ -265,18 +297,16 @@ for (const party of PARTIES) {const manageDialog = getManagePartyDialog(page, party);- // Verify "Pre-fill with values from the current invoice form" switch is visible+ // Verify "Fill in from this invoice" switch is visibleconst prefillSwitch = manageDialog.getByRole("switch", {- name: `Pre-fill with values from the current invoice form`,+ name: `Fill in from this invoice`,});await expect(prefillSwitch).toBeVisible();await expect(prefillSwitch).not.toBeChecked();// Verify the label is visibleawait expect(- manageDialog.getByLabel(- "Pre-fill with values from the current invoice form",- ),+ manageDialog.getByLabel("Fill in from this invoice"),).toBeVisible();/*@@ -292,7 +322,7 @@ for (const party of PARTIES) {.getByRole("textbox", { name: "Address" }).fill(testData.address);- // Fill Tax Number fieldset (Label and Value)+ // Fill Tax Number fieldset (Label and Number)const vatNumberFieldset = manageDialog.getByRole("group", {name: `${label} Tax Number`,});@@ -302,7 +332,7 @@ for (const party of PARTIES) {.fill(testData.vatNoLabelText);await vatNumberFieldset- .getByRole("textbox", { name: "Value" })+ .getByRole("textbox", { name: "Number" }).fill(testData.vatNo);await manageDialog@@ -313,7 +343,7 @@ for (const party of PARTIES) {await fillBankDetails(manageDialog, party);const emailSwitchInDialogForm = manageDialog.getByRole("switch", {- name: `Show ${PARTY_CONFIG[party].label} Email in PDF`,+ name: `Show the 'Email' field in the PDF`,});const taxNumberSwitchInDialogForm = manageDialog.getByRole("switch", {@@ -349,10 +379,10 @@ for (const party of PARTIES) {// Verify notes visibility switch is CHECKED by defaultawait expect(notesSwitchInDialogForm).toBeChecked();- // Verify "Apply to Current Invoice" switch is checked by default+ // Verify "Use on this invoice" is checked by defaultawait expect(- manageDialog.getByRole("switch", {- name: "Apply to Current Invoice",+ manageDialog.getByRole("checkbox", {+ name: "Use on this invoice",}),).toBeChecked();@@ -403,68 +433,34 @@ for (const party of PARTIES) {testData.name,);- // Verify the locked banner is visible with correct text- const lockedBanner = partyForm.getByTestId(`${party}-locked-banner`);- await expect(lockedBanner).toBeVisible();- await expect(lockedBanner).toContainText(- `To modify ${party} details, click the Edit ${party} button (pencil icon) next to the dropdown above.`,- );-- // Name+ // A saved party shows as a read-only card of what the PDF prints, in place of+ // the form fields+ const savedCard = partyForm.getByTestId(`${party}-saved-card`);+ await expect(savedCard).toBeVisible();await expect(partyForm.getByRole("textbox", { name: "Name (Required)" }),- ).toHaveValue(testData.name);-- // Address- await expect(- partyForm.getByRole("textbox", { name: "Address (Required)" }),- ).toHaveValue(testData.address);+ ).toBeHidden();- // Tax Number- const partyVatFieldset = partyForm.getByRole("group", {- name: `${label} Tax Number`,+ await expectCardHeader(savedCard, {+ name: testData.name,+ address: testData.address,});-- await expect(- partyVatFieldset.getByRole("textbox", { name: "Label" }),- ).toHaveValue(testData.vatNoLabelText);-- await expect(- partyVatFieldset.getByRole("textbox", { name: "Value" }),- ).toHaveValue(testData.vatNo);-- const vatNumberSwitchNotInDialog = partyForm.getByTestId(- `${party}VatNoFieldIsVisible`,- );- // Verify Tax Number switch is not checked as we toggled it off- await expect(vatNumberSwitchNotInDialog).not.toBeChecked();- await expect(vatNumberSwitchNotInDialog).toBeDisabled();-- await expect(- partyForm.getByRole("textbox", { name: "Email" }),- ).toHaveValue(testData.email);-- const emailSwitchNotInDialog = partyForm.getByRole("switch", {- name: `Show the 'Email' field in the PDF`,+ // the tax number, email and bank details were hidden from the PDF in the dialog+ await expectCardField(savedCard, {+ label: testData.vatNoLabelText,+ value: testData.vatNo,+ isHidden: true,+ });+ await expectCardField(savedCard, {+ label: "Email",+ value: testData.email,+ isHidden: true,+ });+ await expectBankDetailsInCard(savedCard, party);+ await expectCardField(savedCard, {+ label: "Notes",+ value: testData.notes,});- // Verify Email switch is not checked as we toggled it off- await expect(emailSwitchNotInDialog).not.toBeChecked();- await expect(emailSwitchNotInDialog).toBeDisabled();-- // Bank details (sellers only)- await expectBankDetailsInForm(partyForm, party);-- // Notes- await expect(- partyForm.getByRole("textbox", { name: "Notes" }),- ).toHaveValue(testData.notes);-- const notesSwitchNotInDialog = partyForm.getByTestId(- `${party}NotesInvoiceFormFieldVisibilitySwitch`,- );- await expect(notesSwitchNotInDialog).toBeChecked();- await expect(notesSwitchNotInDialog).toBeDisabled();/** TEST EDIT FUNCTIONALITY IN PARTY MANAGEMENT DIALOG@@ -489,7 +485,7 @@ for (const party of PARTIES) {await expect(manageDialog.getByRole("group", { name: `${label} Tax Number` })- .getByRole("textbox", { name: "Value" }),+ .getByRole("textbox", { name: "Number" }),).toHaveValue(testData.vatNo);await expect(@@ -547,18 +543,24 @@ for (const party of PARTIES) {* TEST UPDATED INFORMATION IN INVOICE FORM AFTER UPDATING PARTY IN DIALOG*/+ // the card follows the edit: new name, email and tax number printed again,+ // notes now hiddenawait expect(- partyForm.getByRole("textbox", { name: "Name" }),- ).toHaveValue(updatedName);-- // Verify Email visibility is now enabled- await expect(emailSwitchNotInDialog).toBeChecked();-- // Verify Tax Number visibility is now enabled- await expect(vatNumberSwitchNotInDialog).toBeChecked();-- // Verify notes visibility switch is unchecked- await expect(notesSwitchNotInDialog).not.toBeChecked();+ savedCard.locator("header").getByText(updatedName, { exact: true }),+ ).toBeVisible();+ await expectCardField(savedCard, {+ label: "Email",+ value: testData.email,+ });+ await expectCardField(savedCard, {+ label: testData.vatNoLabelText,+ value: testData.vatNo,+ });+ await expectCardField(savedCard, {+ label: "Notes",+ value: testData.notes,+ isHidden: true,+ });});test(`add ${party} without applying to invoice`, async ({ page }) => {@@ -578,9 +580,9 @@ for (const party of PARTIES) {.getByRole("textbox", { name: "Email" }).fill(`unapplied@${party}.com`);- // Uncheck "Apply to Current Invoice" switch- const applyToInvoiceSwitch = manageDialog.getByRole("switch", {- name: "Apply to Current Invoice",+ // Uncheck "Use on this invoice"+ const applyToInvoiceSwitch = manageDialog.getByRole("checkbox", {+ name: "Use on this invoice",});await expect(applyToInvoiceSwitch).toBeChecked();@@ -609,7 +611,7 @@ for (const party of PARTIES) {});test(`switch and restore ${party} via dropdown`, async ({ page }) => {- // Add a party with "Apply to Current Invoice" checked (default)+ // Add a party with "Use on this invoice" checked (default)await openNewPartyDialog(page, party);const manageDialog = getManagePartyDialog(page, party);@@ -644,10 +646,8 @@ for (const party of PARTIES) {dropdownPartyName,);- // Verify locked banner is visible when a party is selected- await expect(- partyForm.getByTestId(`${party}-locked-banner`),- ).toBeVisible();+ // Verify the saved card is shown when a party is selected+ await expect(partyForm.getByTestId(`${party}-saved-card`)).toBeVisible();// Restore to default by selecting the empty optionawait partyDropdown.selectOption("");@@ -662,10 +662,8 @@ for (const party of PARTIES) {`No ${party} selected (default)`,);- // Verify locked banner is hidden after deselecting the party- await expect(- partyForm.getByTestId(`${party}-locked-banner`),- ).toBeHidden();+ // Verify the card gives way to the form after deselecting the party+ await expect(partyForm.getByTestId(`${party}-saved-card`)).toBeHidden();// Verify form reset to default valuesawait expectFormResetToDefaults(partyForm, party);@@ -685,21 +683,17 @@ for (const party of PARTIES) {dropdownPartyName,);- // Verify locked banner is visible again after reselecting the party- await expect(- partyForm.getByTestId(`${party}-locked-banner`),- ).toBeVisible();-- // Verify form fields are populated with the party's data- await expect(- partyForm.getByRole("textbox", { name: "Name" }),- ).toHaveValue(dropdownPartyName);- await expect(- partyForm.getByRole("textbox", { name: "Address" }),- ).toHaveValue(dropdownPartyAddress);- await expect(- partyForm.getByRole("textbox", { name: "Email" }),- ).toHaveValue(dropdownPartyEmail);+ // Verify the card is back, with the party's data+ const reselectedCard = partyForm.getByTestId(`${party}-saved-card`);+ await expect(reselectedCard).toBeVisible();+ await expectCardHeader(reselectedCard, {+ name: dropdownPartyName,+ address: dropdownPartyAddress,+ });+ await expectCardField(reselectedCard, {+ label: "Email",+ value: dropdownPartyEmail,+ });});test(`delete ${party}`, async ({ page }) => {@@ -802,18 +796,18 @@ for (const party of PARTIES) {const manageDialog = getManagePartyDialog(page, party);const prefillSwitch = manageDialog.getByRole("switch", {- name: "Pre-fill with values from the current invoice form",+ name: "Fill in from this invoice",});- const applyToInvoiceSwitch = manageDialog.getByRole("switch", {- name: "Apply to Current Invoice",+ const applyToInvoiceSwitch = manageDialog.getByRole("checkbox", {+ name: "Use on this invoice",});- // Pre-fill switch defaults to off; toggle it on+ // "Fill in from this invoice" defaults to off; toggle it onawait expect(prefillSwitch).not.toBeChecked();await prefillSwitch.click();await expect(prefillSwitch).toBeChecked();- // "Apply to Current Invoice" switch defaults to on; toggle it off+ // "Use on this invoice" defaults to on; turn it offawait expect(applyToInvoiceSwitch).toBeChecked();await applyToInvoiceSwitch.click();await expect(applyToInvoiceSwitch).not.toBeChecked();@@ -979,7 +973,7 @@ for (const party of PARTIES) {.fill(`Draft ${label}`);const prefillSwitch = manageDialog.getByRole("switch", {- name: "Pre-fill with values from the current invoice form",+ name: "Fill in from this invoice",});await expect(prefillSwitch).not.toBeChecked();@@ -991,7 +985,7 @@ for (const party of PARTIES) {// Switch has not changed yet — still OFF while dialog is openawait expect(getManagePartyDialog(page, party).getByRole("switch", {- name: "Pre-fill with values from the current invoice form",+ name: "Fill in from this invoice",includeHidden: true, // dialog is still open, but on one level deeper}),).not.toBeChecked();@@ -1014,7 +1008,7 @@ for (const party of PARTIES) {await nameInput.fill(`Draft ${label}`);const prefillSwitch = manageDialog.getByRole("switch", {- name: "Pre-fill with values from the current invoice form",+ name: "Fill in from this invoice",});await prefillSwitch.click();@@ -1050,7 +1044,7 @@ for (const party of PARTIES) {await nameInput.fill(`Draft ${label}`);const prefillSwitch = manageDialog.getByRole("switch", {- name: "Pre-fill with values from the current invoice form",+ name: "Fill in from this invoice",});await prefillSwitch.click();@@ -1078,7 +1072,7 @@ for (const party of PARTIES) {const manageDialog = getManagePartyDialog(page, party);const prefillSwitch = manageDialog.getByRole("switch", {- name: "Pre-fill with values from the current invoice form",+ name: "Fill in from this invoice",});// Enable pre-fill while form is clean@@ -1099,7 +1093,7 @@ for (const party of PARTIES) {// Switch remains ON while dialog is openawait expect(getManagePartyDialog(page, party).getByRole("switch", {- name: "Pre-fill with values from the current invoice form",+ name: "Fill in from this invoice",includeHidden: true, // dialog is still open, but on one level deeper}),).toBeChecked();@@ -1112,7 +1106,7 @@ for (const party of PARTIES) {const manageDialog = getManagePartyDialog(page, party);const prefillSwitch = manageDialog.getByRole("switch", {- name: "Pre-fill with values from the current invoice form",+ name: "Fill in from this invoice",});const nameInput = manageDialog.getByRole("textbox", {name: "Name",@@ -1154,7 +1148,7 @@ for (const party of PARTIES) {const manageDialog = getManagePartyDialog(page, party);const prefillSwitch = manageDialog.getByRole("switch", {- name: "Pre-fill with values from the current invoice form",+ name: "Fill in from this invoice",});const nameInput = manageDialog.getByRole("textbox", {name: "Name",diff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts b/e2e/stripe-invoice-template/stripe-invoice-template.test.tsindex 6f85e32..8d8f330 100644--- a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts+++ b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts@@ -47,12 +47,13 @@ test.describe("Stripe Invoice Template", () => {await page.goto("/stripe-template");const generalInfoSection = page.getByTestId("general-information-section");- const invoiceNumberFieldset = generalInfoSection.getByRole("group", {- name: "Invoice Number",- });- const invoiceNumberLabelInput = invoiceNumberFieldset.getByRole("textbox", {- name: "Label",+ const invoiceDetailsFieldset = generalInfoSection.getByRole("group", {+ name: "Invoice details",});+ const invoiceNumberLabelInput = invoiceDetailsFieldset.getByRole(+ "textbox",+ { name: "Invoice number label" },+ );await expect(invoiceNumberLabelInput).toHaveValue("Invoice");@@ -991,6 +992,60 @@ test.describe("Stripe Invoice Template", () => {});});+ test("colors the top line with the picked color and keeps it across a reload", async ({+ page,+ browserName,+ downloadDir,+ }) => {+ const generalInfoSection = page.getByTestId("general-information-section");++ // the color only belongs to the Stripe template+ await expect(generalInfoSection.getByText("Top line color")).toBeHidden();++ await generalInfoSection+ .getByRole("combobox", { name: "Invoice Template" })+ .selectOption("stripe");++ await expect(page).toHaveURL("/stripe-template");++ const topLineColor = generalInfoSection.getByTestId(+ "stripe-top-line-color",+ );++ await expect(+ topLineColor.getByRole("button", { name: "Amber (default)" }),+ ).toHaveAttribute("aria-pressed", "true");++ await waitForPdfRegeneration(page, async () => {+ await topLineColor.getByRole("button", { name: "Indigo" }).click();+ });++ await expect(+ topLineColor.getByRole("button", { name: "Indigo" }),+ ).toHaveAttribute("aria-pressed", "true");++ const storedData = (await page.evaluate((key) => {+ return localStorage.getItem(key);+ }, PDF_DATA_LOCAL_STORAGE_KEY)) as string;++ expect((JSON.parse(storedData) as InvoiceData).stripeTopLineColor).toBe(+ "#635bff",+ );++ await page.reload();+ await expect(page).toHaveURL("/stripe-template");++ await expect(+ topLineColor.getByRole("button", { name: "Indigo" }),+ ).toHaveAttribute("aria-pressed", "true");++ await expectPdfScreenshot(page, {+ downloadDir,+ browserName,+ name: "pdf-with-indigo-top-line-stripe-template.png",+ });+ });+/*** The Stripe template is the only one whose money cells carry a currency token, and some* locales render that token in more than one font run: `it` prints `123.400.000,00 USD`diff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/pdf-with-indigo-top-line-stripe-template-Desktop-Chrome-darwin.png b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/pdf-with-indigo-top-line-stripe-template-Desktop-Chrome-darwin.pngnew file mode 100644index 0000000..47ef0acBinary files /dev/null and b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/pdf-with-indigo-top-line-stripe-template-Desktop-Chrome-darwin.png differdiff --git a/package.json b/package.jsonindex daa8d33..012ab77 100644--- a/package.json+++ b/package.json@@ -97,6 +97,7 @@"pdfjs-dist": "5.4.296","qrcode": "1.5.4","react": "19.2.8",+ "react-colorful": "5.6.1","react-dom": "19.2.8","react-hook-form": "7.86.0","react-intersection-observer": "9.16.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 83cf6a0..ba4064f 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -166,6 +166,9 @@ importers:react:specifier: 19.2.8version: 19.2.8+ react-colorful:+ specifier: 5.6.1react-dom:specifier: 19.2.8version: 19.2.8([email protected])@@ -6393,6 +6396,12 @@ packages:resolution: {integrity: sha512-9G8cA+tuMS75+6G/TzW8OtLzmBDMo8p1JRxN5AZ+LAp8uxGA8V8GZm4GQ4/N5QNQEnLmg6SS7wyuSmbKepiKqA==}engines: {node: '>= 0.10'}+ resolution: {integrity: sha512-1exovf0uGTGyq5mXQT0zgQ80uvj2PCwvF8zY1RN9/vbJVSjSo3fsB/4L3ObbF7u70NduSiK4xu4Y6q1MHoUGEw==}+ peerDependencies:+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+resolution: {integrity: sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==}peerDependencies:@@ -13669,6 +13678,11 @@ snapshots:iconv-lite: 0.7.0unpipe: 1.0.0+ dependencies:+ react: 19.2.8+ react-dom: 19.2.8([email protected])+dependencies:react: 19.2.8diff --git a/src/app/(main)/(app)/components/invoice-form/__tests__/payment-due-helpers.test.tsx b/src/app/(main)/(app)/components/invoice-form/__tests__/payment-due-helpers.test.tsxindex b12634c..a291693 100644--- a/src/app/(main)/(app)/components/invoice-form/__tests__/payment-due-helpers.test.tsx+++ b/src/app/(main)/(app)/components/invoice-form/__tests__/payment-due-helpers.test.tsx@@ -1,6 +1,7 @@// @vitest-environment happy-dom-import { cleanup, render, screen } from "@testing-library/react";+import { cleanup, render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";import {afterAll,afterEach,@@ -110,12 +111,22 @@ describe("payment due helper texts", () => {).not.toBeInTheDocument();});+ // the 7/14/30 day payment terms cover any other spacing, so only a due date that comes+ // before the issue date gets a button of its own+ it("is hidden when the payment due date is after the issue date but not 14 days after it", () => {+ renderInvoiceForm({ paymentDue: "2026-09-20" });++ expect(+ screen.queryByRole("button", { name: /set payment due date to/i }),+ ).not.toBeInTheDocument();+ });+describe('"Set payment due date to <date>"', () => {it("renders the suggested date in English by default", () => {- renderInvoiceForm({ language: "en", paymentDue: "2026-09-20" });+ renderInvoiceForm({ language: "en", paymentDue: "2026-09-01" });expect(getSetPaymentDueButton()).toHaveTextContent(- "Set payment due date to September 29, 2026 (14 days from issue date)",+ "Use September 29, 2026",);});@@ -132,10 +143,10 @@ describe("payment due helper texts", () => {] as const)("renders the suggested date in the invoice PDF language (%s)",(language, expectedDate) => {- renderInvoiceForm({ language, paymentDue: "2026-09-20" });+ renderInvoiceForm({ language, paymentDue: "2026-09-01" });expect(getSetPaymentDueButton()).toHaveTextContent(- `Set payment due date to ${expectedDate} (14 days from issue date)`,+ `Use ${expectedDate}`,);},);@@ -144,37 +155,76 @@ describe("payment due helper texts", () => {renderInvoiceForm({language: "pl",dateFormat: "D MMM YYYY",- paymentDue: "2026-09-20",+ paymentDue: "2026-09-01",});- expect(getSetPaymentDueButton()).toHaveTextContent(- "Set payment due date to 29 wrz 2026 (14 days from issue date)",- );+ expect(getSetPaymentDueButton()).toHaveTextContent("Use 29 wrz 2026");});});- describe('"Payment due date is before date of issue"', () => {- it("renders the date of issue in the invoice PDF language", () => {- renderInvoiceForm({ language: "fr", paymentDue: "2026-09-01" });+ describe('"Before date of issue"', () => {+ it("sits under the payment due field", () => {+ renderInvoiceForm({ language: "en", paymentDue: "2026-09-01" });+ const paymentDueField = screen+ .getByLabelText("Payment due")+ .closest("div");+ expect(paymentDueField).not.toBeNull();expect(- screen.getByText(- /Payment due date is before date of issue \(septembre 15, 2026\)/,+ within(paymentDueField as HTMLElement).getByText(+ "Before date of issue",),).toBeVisible();- expect(getSetPaymentDueButton()).toHaveTextContent(- "Set payment due date to septembre 29, 2026 (14 days from issue date)",- );+ expect(+ within(paymentDueField as HTMLElement).getByRole("button", {+ name: "Set payment due date to September 29, 2026 (14 days after issue)",+ }),+ ).toBeVisible();});- it("renders the date of issue in English by default", () => {- renderInvoiceForm({ language: "en", paymentDue: "2026-09-01" });+ it("offers the payment terms in place of a term to name", () => {+ renderInvoiceForm({ paymentDue: "2026-09-01" });+ expect(screen.getByText("Pick a payment term")).toBeVisible();+ });++ it("sets the payment due date to 14 days after issue when clicked", async () => {+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });++ renderInvoiceForm({ paymentDue: "2026-09-01" });++ await user.click(getSetPaymentDueButton());++ expect(screen.getByLabelText("Payment due")).toHaveValue("2026-09-29");expect(- screen.getByText(- /Payment due date is before date of issue \(September 15, 2026\)/,- ),+ screen.queryByText("Before date of issue"),+ ).not.toBeInTheDocument();+ });+ });++ // a cleared date input, which the PDF would otherwise fill with 14 days from today+ describe('"Not set"', () => {+ it("sits under the payment due field", () => {+ renderInvoiceForm({ paymentDue: "" });++ const paymentDueField = screen+ .getByLabelText("Payment due")+ .closest("div");+ expect(paymentDueField).not.toBeNull();+ expect(+ within(paymentDueField as HTMLElement).getByText("Not set"),).toBeVisible();});++ it("sets the payment due date to 14 days after issue when clicked", async () => {+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });++ renderInvoiceForm({ paymentDue: "" });++ await user.click(getSetPaymentDueButton());++ expect(screen.getByLabelText("Payment due")).toHaveValue("2026-09-29");+ expect(screen.queryByText("Not set")).not.toBeInTheDocument();+ });});});diff --git a/src/app/(main)/(app)/components/invoice-form/common.tsx b/src/app/(main)/(app)/components/invoice-form/common.tsxindex 4840a69..4087e67 100644--- a/src/app/(main)/(app)/components/invoice-form/common.tsx+++ b/src/app/(main)/(app)/components/invoice-form/common.tsx@@ -6,6 +6,25 @@ export function inputErrorClassName(hasError?: boolean) {: "";}+/**+ * Fades the inputs of a field whose "Show in PDF" switch is off, so what the PDF leaves out+ * reads as such. Goes on a wrapper that holds the field's one switch and its inputs, and+ * follows the switch's `data-state` in CSS, so nothing re-renders. Browsers without+ * `:has()` (Safari before 15.4) just show no fade.+ */+export const FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME =+ "[&:has([role=switch][data-state=unchecked])_:is(input,textarea,select)]:border-dashed [&:has([role=switch][data-state=unchecked])_:is(input,textarea,select)]:bg-slate-50 [&:has([role=switch][data-state=unchecked])_:is(input,textarea,select)]:text-slate-500";++/**+ * The same fade for a field whose switch sits outside its wrapper (the item columns are+ * switched on the first item only) or that depends on more than one switch.+ */+export function hiddenInPdfClassName(isHidden: boolean) {+ return isHidden+ ? "[&_:is(input,textarea,select)]:border-dashed [&_:is(input,textarea,select)]:bg-slate-50 [&_:is(input,textarea,select)]:text-slate-500"+ : "";+}+export const ErrorMessage = ({ children }: { children: React.ReactNode }) => {return <p className="mt-1 text-xs text-red-600">{children}</p>;};diff --git a/src/app/(main)/(app)/components/invoice-form/index.tsx b/src/app/(main)/(app)/components/invoice-form/index.tsxindex 124b48d..ce26d5a 100644--- a/src/app/(main)/(app)/components/invoice-form/index.tsx+++ b/src/app/(main)/(app)/components/invoice-form/index.tsx@@ -12,7 +12,6 @@ import {setAppStorageItem,} from "@/app/(main)/(app)/utils/app-local-storage";import { formatAmount } from "@/app/(main)/(app)/utils/format-amount";-import { formatDateWithLocale } from "@/app/(main)/(app)/utils/format-date-with-locale";import { updateAppMetadata } from "@/app/(main)/(app)/utils/get-app-metadata";import {ACCORDION_STATE_LOCAL_STORAGE_KEY,@@ -30,7 +29,6 @@ import {AccordionItem,AccordionTrigger,} from "@/components/ui/accordion";-import { ButtonHelper } from "@/components/ui/button-helper";import { Input } from "@/components/ui/input";import { InputHelperMessage } from "@/components/ui/input-helper-message";import { Label } from "@/components/ui/label";@@ -39,10 +37,11 @@ import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { CustomTooltip } from "@/components/ui/tooltip";import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";+import { cn } from "@/lib/utils";import { zodResolverForOutput } from "@/lib/zod-resolver-for-output";import type { NonReadonly, Prettify } from "@/types";-import { AlertIcon, ErrorMessage } from "./common";+import { ErrorMessage, FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME } from "./common";import { ItemTotalsSync } from "./item-totals-sync";import { BuyerInformation } from "./sections/buyer-information";import { GeneralInformation } from "./sections/general-information";@@ -116,32 +115,7 @@ export const InvoiceForm = memo(function InvoiceForm({const currency = useWatch({ control, name: "currency" });const dateOfIssue = useWatch({ control, name: "dateOfIssue" });-- const paymentDue = useWatch({ control, name: "paymentDue" });const language = useWatch({ control, name: "language" });- const selectedDateFormat = useWatch({ control, name: "dateFormat" });-- const isPaymentDueBeforeDateOfIssue = dayjs(paymentDue).isBefore(- dayjs(dateOfIssue),- );-- // payment due date is 14 days after the date of issue or the same day- const isPaymentDue14DaysFromDateOfIssue =- dayjs(paymentDue).isAfter(dayjs(dateOfIssue).add(14, "days")) ||- dayjs(paymentDue).isSame(dayjs(dateOfIssue).add(14, "days"));-- // Helper texts quote dates back to the user, so they are formatted the way the- // PDF will render them: the invoice's date format AND its language.- const formattedDateOfIssue = formatDateWithLocale({- date: dateOfIssue,- selectedDateFormat,- language,- });- const formattedSuggestedPaymentDue = formatDateWithLocale({- date: dayjs(dateOfIssue).add(14, "days"),- selectedDateFormat,- language,- });const { fields, append } = useFieldArray({control,@@ -538,7 +512,7 @@ export const InvoiceForm = memo(function InvoiceForm({{/* Payment Method (Only show for default template) */}{template === "default" ? (- <div>+ <div className={FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME}><div className="relative mb-2 mt-6 flex items-center justify-between"><Label htmlFor={`paymentMethod`} className="">Payment Method@@ -593,82 +567,8 @@ export const InvoiceForm = memo(function InvoiceForm({</div>) : null}- {/* Payment Due */}- <div>- <div className="mb-6">- <Label htmlFor={`paymentDue`} className="mb-1">- Payment Due- </Label>- <Controller- name="paymentDue"- control={control}- render={({ field }) => {- return (- <Input- {...field}- id={`paymentDue`}- type="date"- className=""- />- );- }}- />- {errors.paymentDue ? (- <ErrorMessage>{errors.paymentDue.message}</ErrorMessage>- ) : null}- {!errors.paymentDue &&- isPaymentDueBeforeDateOfIssue &&- dateOfIssue ? (- <InputHelperMessage>- <span className="flex items-center text-balance text-amber-800">- <AlertIcon />- Payment due date is before date of issue (- {formattedDateOfIssue})- </span>- <ButtonHelper- onClick={() => {- const newPaymentDue = dayjs(dateOfIssue)- .add(14, "days")- .format("YYYY-MM-DD"); // default browser date input format is YYYY-MM-DD-- setValue("paymentDue", newPaymentDue);- }}- >- <span className="text-pretty">- Set payment due date to {formattedSuggestedPaymentDue} (14- days from issue date)- </span>- </ButtonHelper>- </InputHelperMessage>- ) : null}- {/* If there are no errors and the payment due date is not before the date of issue and the payment due date is not 14 days after the date of issue, show the button to set the payment due date to 14 days after the date of issue (probably a bit better UX) */}- {!errors.paymentDue &&- !isPaymentDueBeforeDateOfIssue &&- !isPaymentDue14DaysFromDateOfIssue &&- dateOfIssue ? (- <InputHelperMessage>- <ButtonHelper- className="whitespace-normal"- onClick={() => {- const newPaymentDue = dayjs(dateOfIssue)- .add(14, "days")- .format("YYYY-MM-DD");-- setValue("paymentDue", newPaymentDue);- }}- >- <span className="text-pretty">- Set payment due date to {formattedSuggestedPaymentDue} (14- days from issue date)- </span>- </ButtonHelper>- </InputHelperMessage>- ) : null}- </div>- </div>-{/* Notes */}- <div className="">+ <div className={FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME}><div className="relative mb-2 flex items-center justify-between"><Label htmlFor={`notes`} className="">Notes@@ -720,7 +620,12 @@ export const InvoiceForm = memo(function InvoiceForm({</div>{/* QR Code */}- <fieldset className="rounded-md border px-4 pb-4">+ <fieldset+ className={cn(+ "rounded-md border px-4 pb-4",+ FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME,+ )}+ ><legend className="text-base font-semibold lg:text-lg">QR Code</legend>@@ -817,7 +722,12 @@ export const InvoiceForm = memo(function InvoiceForm({*/}{invoiceData.template === "default" ? (<>- <fieldset className="rounded-md border px-4 pb-4">+ <fieldset+ className={cn(+ "rounded-md border px-4 pb-4",+ FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME,+ )}+ ><legend className="text-base font-semibold lg:text-lg">Person Authorized to Receive</legend>@@ -884,7 +794,12 @@ export const InvoiceForm = memo(function InvoiceForm({</div></fieldset>- <fieldset className="rounded-md border px-4 pb-4">+ <fieldset+ className={cn(+ "rounded-md border px-4 pb-4",+ FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME,+ )}+ ><legend className="text-base font-semibold lg:text-lg">Person Authorized to Issue</legend>diff --git a/src/app/(main)/(app)/components/invoice-form/sections/__tests__/general-information.test.tsx b/src/app/(main)/(app)/components/invoice-form/sections/__tests__/general-information.test.tsxindex 91ce6df..eaa62dd 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/__tests__/general-information.test.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/__tests__/general-information.test.tsx@@ -1,6 +1,12 @@// @vitest-environment happy-dom-import { cleanup, render, screen } from "@testing-library/react";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ within,+} from "@testing-library/react";import userEvent from "@testing-library/user-event";import { useForm, useWatch } from "react-hook-form";import {@@ -50,6 +56,14 @@ interface HarnessProps {/** Left out by default, like an invoice that has never picked a number format. */numberFormatLocale?: InvoiceData["numberFormatLocale"];preserveNumberFormatOnLanguageChange?: InvoiceData["preserveNumberFormatOnLanguageChange"];+ template?: InvoiceData["template"];+ paymentDue?: string;+ dateOfService?: string;+ dateOfServiceStart?: string;+ invoiceNumberValue?: string;+ servicePeriodFieldIsVisible?: boolean;+ dateOfServiceFieldIsVisible?: boolean;+ dateOfServiceLabelText?: string;}function GeneralInformationHarness({@@ -58,15 +72,41 @@ function GeneralInformationHarness({dateOfIssue = STALE_DATE_OF_ISSUE,numberFormatLocale,preserveNumberFormatOnLanguageChange,+ template = "default",+ paymentDue,+ dateOfService,+ dateOfServiceStart,+ invoiceNumberValue,+ servicePeriodFieldIsVisible = true,+ dateOfServiceFieldIsVisible = true,+ dateOfServiceLabelText,}: HarnessProps) {+ const initialInvoiceData = getInitialInvoiceData();+const { control, setValue } = useForm<InvoiceData>({defaultValues: {- ...getInitialInvoiceData(),+ ...initialInvoiceData,language,dateFormat,dateOfIssue,numberFormatLocale,preserveNumberFormatOnLanguageChange,+ template,+ // `""` is kept: it is a cleared date input+ ...(paymentDue === undefined ? {} : { paymentDue }),+ ...(dateOfService ? { dateOfService } : {}),+ ...(dateOfServiceStart ? { dateOfServiceStart } : {}),+ servicePeriodFieldIsVisible,+ dateOfServiceFieldIsVisible,+ ...(dateOfServiceLabelText ? { dateOfServiceLabelText } : {}),+ ...(invoiceNumberValue+ ? {+ invoiceNumberObject: {+ ...initialInvoiceData.invoiceNumberObject,+ value: invoiceNumberValue,+ },+ }+ : {}),},});@@ -74,6 +114,7 @@ function GeneralInformationHarness({// to `setValue` the same way they do in the app.const currentDateOfIssue = useWatch({ control, name: "dateOfIssue" });const currentPaymentDue = useWatch({ control, name: "paymentDue" });+ const currentTopLineColor = useWatch({ control, name: "stripeTopLineColor" });return (<TooltipProvider delayDuration={0}>@@ -85,6 +126,9 @@ function GeneralInformationHarness({isMobile={false}/><output data-testid="payment-due-readout">{currentPaymentDue}</output>+ <output data-testid="top-line-color-readout">+ {currentTopLineColor ?? "unset"}+ </output></TooltipProvider>);}@@ -98,7 +142,7 @@ function getSetDateOfIssueToTodayButton() {}function getNumberFormatSelect() {- return screen.getByLabelText("Format");+ return screen.getByLabelText("Number Format");}function getPreserveNumberFormatSwitch() {@@ -146,7 +190,7 @@ describe("GeneralInformation date helper texts", () => {renderGeneralInformation({ language: "en" });expect(getSetDateOfIssueToTodayButton()).toHaveTextContent(- "Set date of issue to today (September 15, 2026)",+ "Use September 15, 2026",);});@@ -166,7 +210,7 @@ describe("GeneralInformation date helper texts", () => {renderGeneralInformation({ language });expect(getSetDateOfIssueToTodayButton()).toHaveTextContent(- `Set date of issue to today (${expectedDate})`,+ `Use ${expectedDate}`,);},);@@ -175,7 +219,7 @@ describe("GeneralInformation date helper texts", () => {renderGeneralInformation({ language: "pl", dateFormat: "D MMM YYYY" });expect(getSetDateOfIssueToTodayButton()).toHaveTextContent(- "Set date of issue to today (15 wrz 2026)",+ "Use 15 wrz 2026",);});@@ -183,20 +227,21 @@ describe("GeneralInformation date helper texts", () => {renderGeneralInformation({ language: "ru", dateFormat: "YYYY-MM-DD" });expect(getSetDateOfIssueToTodayButton()).toHaveTextContent(- "Set date of issue to today (2026-09-15)",+ "Use 2026-09-15",);});- it("sets the date of issue and the payment due date when clicked", async () => {+ it("sets the date of issue and keeps the payment term when clicked", async () => {const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });- renderGeneralInformation();+ // due 7 days after issue+ renderGeneralInformation({ paymentDue: "2026-06-17" });await user.click(getSetDateOfIssueToTodayButton());- expect(screen.getByLabelText("Date of Issue")).toHaveValue("2026-09-15");+ expect(screen.getByLabelText("Date of issue")).toHaveValue("2026-09-15");expect(screen.getByTestId("payment-due-readout")).toHaveTextContent(- "2026-09-29",+ "2026-09-22",);expect(screen.queryByRole("button", { name: /set date of issue to today/i }),@@ -204,6 +249,100 @@ describe("GeneralInformation date helper texts", () => {});});+ describe("payment due and the date of issue", () => {+ it("moves the payment due date along with the date of issue, keeping its term", () => {+ // due 30 days after issue+ renderGeneralInformation({ paymentDue: "2026-07-10" });++ // a date picker hands over the whole date at once+ fireEvent.change(screen.getByLabelText("Date of issue"), {+ target: { value: "2026-08-01" },+ });++ expect(screen.getByTestId("payment-due-readout")).toHaveTextContent(+ "2026-08-31",+ );+ });++ it("does not call a payment term other than 14 days out of date", () => {+ renderGeneralInformation({+ dateOfIssue: "2026-09-15",+ // due 7 days after issue+ paymentDue: "2026-09-22",+ dateOfServiceStart: "2026-09-01",+ dateOfService: "2026-09-30",+ invoiceNumberValue: "1/09-2026",+ });++ expect(+ screen.queryByTestId("out-of-date-dates-helper"),+ ).not.toBeInTheDocument();+ });+ });++ describe("out-of-date field warnings", () => {+ it("offers this month's invoice number and applies it", async () => {+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });++ renderGeneralInformation({ invoiceNumberValue: "1/10-2025" });++ const fixButton = screen.getByRole("button", {+ name: "Set invoice number to 1/09-2026",+ });+ expect(fixButton).toHaveTextContent("Use 1/09-2026");++ await user.click(fixButton);++ expect(+ screen.getByRole("textbox", { name: "Invoice number" }),+ ).toHaveValue("1/09-2026");+ expect(fixButton).not.toBeInTheDocument();+ });++ it("keeps the same short message for a date from last year", () => {+ renderGeneralInformation({ dateOfServiceStart: "2025-09-01" });++ const startField = screen+ .getByLabelText("Service period start")+ .closest("div");+ expect(startField).not.toBeNull();+ expect(+ within(startField as HTMLElement).getByText("Not current month"),+ ).toBeInTheDocument();+ });++ it("moves the service period to the current month", async () => {+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });++ renderGeneralInformation({+ dateOfServiceStart: "2026-08-01",+ dateOfService: "2026-08-31",+ });++ await user.click(+ screen.getByRole("button", {+ name: "Set service period start to September 1, 2026",+ }),+ );+ await user.click(+ screen.getByRole("button", {+ name: "Set service period end to September 30, 2026",+ }),+ );++ expect(screen.getByLabelText("Service period start")).toHaveValue(+ "2026-09-01",+ );+ expect(screen.getByLabelText("Service period end")).toHaveValue(+ "2026-09-30",+ );+ expect(screen.queryByText("Not current month")).not.toBeInTheDocument();+ expect(+ screen.queryByText("Not end of current month"),+ ).not.toBeInTheDocument();+ });+ });+describe("date format preview", () => {it("previews each format in English by default", () => {renderGeneralInformation({ language: "en" });@@ -239,36 +378,34 @@ describe("GeneralInformation date helper texts", () => {});});- describe('"Keep format when language changes" switch', () => {+ describe('"Keep number format when changing language" switch', () => {it("is off on an invoice that has never turned it on", () => {renderGeneralInformation();expect(getPreserveNumberFormatSwitch()).not.toBeChecked();});- it("says under the switch whether the format follows the language", async () => {+ it("says under the switch what a language change does to the format", async () => {const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });renderGeneralInformation();expect(screen.getByText(- "By default, the number format follows the PDF language",+ "Changing the PDF language also changes the number format.",),).toBeInTheDocument();await user.click(getPreserveNumberFormatSwitch());expect(- screen.getByText(- "The number format stays as it is when you switch the PDF language",- ),+ screen.getByText("Changing the PDF language keeps the number format."),).toBeInTheDocument();});/*** No `aria-label` overriding it, so what a screen reader announces is the text on- * screen -- which is what lets someone say "keep format when language changes" to a+ * screen -- which is what lets someone say "keep number format when changing language" to a* voice control tool and have it hit this switch (WCAG 2.5.3).*/it("is named by its visible label", () => {@@ -276,7 +413,7 @@ describe("GeneralInformation date helper texts", () => {expect(screen.getByRole("switch", {- name: "Keep format when language changes",+ name: "Keep number format when changing language",}),).toBe(getPreserveNumberFormatSwitch());});@@ -287,7 +424,9 @@ describe("GeneralInformation date helper texts", () => {renderGeneralInformation();// the label is what a pointer lands on, so `htmlFor` has to reach the switch- await user.click(screen.getByText("Keep format when language changes"));+ await user.click(+ screen.getByText("Keep number format when changing language"),+ );expect(getPreserveNumberFormatSwitch()).toBeChecked();});@@ -345,7 +484,9 @@ describe("GeneralInformation date helper texts", () => {await selectInvoiceLanguage({ user, language: "pl" });- expect(screen.getByLabelText("Label")).toHaveValue("Faktura nr:");+ expect(screen.getByLabelText("Invoice number label")).toHaveValue(+ "Faktura nr:",+ );expect(getNumberFormatSelect()).toHaveValue("international");});});@@ -359,5 +500,156 @@ describe("GeneralInformation date helper texts", () => {expect(banner).toBeVisible();expect(banner).toHaveTextContent("settembre 15, 2026");});++ // every other date is current, so the cleared payment due date is the only trigger+ it("opens for a payment due date that is not set", () => {+ renderGeneralInformation({+ dateOfIssue: "2026-09-15",+ paymentDue: "",+ dateOfServiceStart: "2026-09-01",+ dateOfService: "2026-09-30",+ invoiceNumberValue: "1/09-2026",+ });++ expect(screen.getByTestId("out-of-date-dates-helper")).toBeVisible();+ });+ });++ describe("payment terms", () => {+ it("marks the term the payment due date already matches", () => {+ renderGeneralInformation({+ dateOfIssue: "2026-09-15",+ paymentDue: "2026-09-29",+ });++ const terms = screen.getByRole("group", { name: /payment terms/i });++ expect(+ within(terms).getByRole("button", { name: "14 days" }),+ ).toHaveAttribute("aria-pressed", "true");+ expect(screen.getByText("Due 14 days after issue")).toBeInTheDocument();+ });++ it("moves the payment due date to the picked term", async () => {+ const user = userEvent.setup();+ renderGeneralInformation({+ dateOfIssue: "2026-09-15",+ paymentDue: "2026-09-29",+ });++ await user.click(screen.getByRole("button", { name: "30 days" }));++ expect(screen.getByTestId("payment-due-readout")).toHaveTextContent(+ "2026-10-15",+ );+ expect(screen.getByText("Due 30 days after issue")).toBeInTheDocument();+ });+ });++ describe("top line color", () => {+ it("is not offered on the default template", () => {+ renderGeneralInformation({ template: "default" });++ expect(screen.queryByText("Top line color")).not.toBeInTheDocument();+ });++ it("writes the picked color to the form on the Stripe template", async () => {+ const user = userEvent.setup();+ renderGeneralInformation({ template: "stripe" });++ expect(screen.getByTestId("top-line-color-readout")).toHaveTextContent(+ "unset",+ );++ await user.click(screen.getByRole("button", { name: "Emerald" }));++ expect(screen.getByTestId("top-line-color-readout")).toHaveTextContent(+ "#10b981",+ );+ });+ });++ describe('"Service period end" helper', () => {+ // the last day of the frozen month, so the end date carries no warning+ const END_OF_MONTH = "2026-09-30";++ it("mentions the date of sales on the default template", () => {+ renderGeneralInformation({+ template: "default",+ dateOfService: END_OF_MONTH,+ });++ expect(+ screen.getByLabelText("Service period end"),+ ).toHaveAccessibleDescription(+ "Also printed as “Date of sales/of executing the service”",+ );+ });++ it("quotes the date of sales label the PDF prints", () => {+ renderGeneralInformation({+ template: "default",+ dateOfService: END_OF_MONTH,+ dateOfServiceLabelText: "Date of delivery",+ });++ expect(+ screen.getByLabelText("Service period end"),+ ).toHaveAccessibleDescription("Also printed as “Date of delivery”");+ });++ it("says the date is printed only once while the service period is hidden", () => {+ renderGeneralInformation({+ template: "default",+ dateOfService: END_OF_MONTH,+ servicePeriodFieldIsVisible: false,+ });++ expect(+ screen.getByLabelText("Service period end"),+ ).toHaveAccessibleDescription(+ "Printed as “Date of sales/of executing the service”",+ );+ });++ it("is not shown while the date of sales is hidden from the PDF", () => {+ renderGeneralInformation({+ template: "default",+ dateOfService: END_OF_MONTH,+ dateOfServiceFieldIsVisible: false,+ });++ expect(+ screen.getByLabelText("Service period end"),+ ).not.toHaveAccessibleDescription();+ });++ it("gives way to the warning when the end date is not the end of the month", () => {+ renderGeneralInformation({+ template: "default",+ dateOfService: "2026-09-20",+ });++ expect(+ screen.getByRole("button", {+ name: "Set service period end to September 30, 2026",+ }),+ ).toBeInTheDocument();+ expect(+ screen.getByLabelText("Service period end"),+ ).not.toHaveAccessibleDescription();+ });++ it("is not shown on the Stripe template, which prints no date of sales", () => {+ renderGeneralInformation({+ template: "stripe",+ dateOfService: END_OF_MONTH,+ });++ expect(+ screen.getByLabelText("Service period end"),+ ).not.toHaveAccessibleDescription();+ expect(screen.queryByText(/printed as/i)).not.toBeInTheDocument();+ });});});diff --git a/src/app/(main)/(app)/components/invoice-form/sections/buyer-information.tsx b/src/app/(main)/(app)/components/invoice-form/sections/buyer-information.tsxindex 3a8599e..9d38952 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/buyer-information.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/buyer-information.tsx@@ -1,6 +1,5 @@"use client";-import { Info } from "lucide-react";import { memo, useState } from "react";import {type Control,@@ -9,8 +8,12 @@ import {type UseFormSetValue,} from "react-hook-form";-import { inputErrorClassName } from "@/app/(main)/(app)/components/invoice-form/common";+import {+ FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME,+ inputErrorClassName,+} from "@/app/(main)/(app)/components/invoice-form/common";import { BuyerManagement } from "@/app/(main)/(app)/components/invoice-form/sections/components/buyer/buyer-management";+import { SavedContactCard } from "@/app/(main)/(app)/components/invoice-form/sections/components/contact-fields";import { type BuyerData, type InvoiceData } from "@/app/schema";import { AccordionContent } from "@/components/ui/accordion";import { Input } from "@/components/ui/input";@@ -68,277 +71,263 @@ export const BuyerInformation = memo(function BuyerInformation({/></div><AccordionContent className="">- <fieldset className="mt-5 space-y-4" disabled={isBuyerSelected}>- {isBuyerSelected ? (- <div- className="flex gap-2 rounded-md border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-800 shadow-md shadow-blue-200/10"- data-testid="buyer-locked-banner"- >- <Info className="mt-0.5 size-4 shrink-0" aria-hidden="true" />- <p className="">- To modify buyer details, click the{" "}- <span className="font-semibold">Edit buyer</span> button (pencil- icon) next to the dropdown above.- </p>+ {isBuyerSelected ? (+ <div className="mt-5">+ <SavedContactCard control={control} party="buyer" />+ </div>+ ) : (+ <fieldset className="mt-5 space-y-4">+ <div>+ <Label htmlFor="buyerName" className="mb-1">+ Name (Required)+ </Label>+ <Controller+ name="buyer.name"+ control={control}+ render={({ field }) => {+ return (+ <Textarea+ {...field}+ id="buyerName"+ rows={3}+ className={inputErrorClassName(!!errors.buyer?.name)}+ />+ );+ }}+ />+ {errors.buyer?.name ? (+ <ErrorMessage>{errors.buyer.name.message}</ErrorMessage>+ ) : null}</div>- ) : null}- <div>- <Label htmlFor="buyerName" className="mb-1">- Name (Required)- </Label>- <Controller- name="buyer.name"- control={control}- render={({ field }) => {- return (- <Textarea- {...field}- id="buyerName"- rows={3}- className={inputErrorClassName(!!errors.buyer?.name)}- />- );- }}- />- {errors.buyer?.name ? (- <ErrorMessage>{errors.buyer.name.message}</ErrorMessage>- ) : null}- </div>+ <div>+ <Label htmlFor="buyerAddress" className="mb-1">+ Address (Required)+ </Label>+ <Controller+ name="buyer.address"+ control={control}+ render={({ field }) => {+ return (+ <Textarea+ {...field}+ id="buyerAddress"+ rows={3}+ className={inputErrorClassName(!!errors.buyer?.address)}+ />+ );+ }}+ />+ {errors.buyer?.address ? (+ <ErrorMessage>{errors.buyer.address.message}</ErrorMessage>+ ) : null}+ </div>- <div>- <Label htmlFor="buyerAddress" className="mb-1">- Address (Required)- </Label>- <Controller- name="buyer.address"- control={control}- render={({ field }) => {- return (- <Textarea- {...field}- id="buyerAddress"- rows={3}- className={inputErrorClassName(!!errors.buyer?.address)}- />- );- }}- />- {errors.buyer?.address ? (- <ErrorMessage>{errors.buyer.address.message}</ErrorMessage>- ) : null}- </div>+ <div className={FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME}>+ <fieldset className="rounded-md border px-4 pb-4">+ <legend className="text-base font-semibold lg:text-lg">+ Buyer Tax Number+ </legend>++ <div className="mb-2 flex items-center justify-end">+ <div className="inline-flex items-center gap-2">+ <Controller+ name="buyer.vatNoFieldIsVisible"+ control={control}+ render={({ field: { value, onChange, ...field } }) => {+ return (+ <Switch+ {...field}+ id="buyerVatNoFieldIsVisible"+ checked={value}+ onCheckedChange={onChange}+ size="sm"+ data-testid="buyerVatNoFieldIsVisible"+ aria-label="Show the 'Buyer Tax Number' Field in the PDF"+ />+ );+ }}+ />+ <CustomTooltip+ trigger={+ <Label htmlFor="buyerVatNoFieldIsVisible">+ Show in PDF+ </Label>+ }+ content={"Show the 'Buyer Tax Number' Field in the PDF"}+ />+ </div>+ </div>++ <div className="space-y-4">+ <div>+ <Label htmlFor="buyerVatNoLabel">Label</Label>+ <Controller+ name="buyer.vatNoLabelText"+ control={control}+ render={({ field }) => {+ return (+ <Input+ {...field}+ type="text"+ id="buyerVatNoLabel"+ placeholder="Enter Tax number label"+ className={cn(+ "mt-1 block w-full",+ inputErrorClassName(+ !!errors.buyer?.vatNoLabelText,+ ),+ )}+ />+ );+ }}+ />+ {errors.buyer?.vatNoLabelText ? (+ <ErrorMessage>+ {errors.buyer.vatNoLabelText.message}+ </ErrorMessage>+ ) : null}+ {!errors.buyer?.vatNoLabelText ? (+ <InputHelperMessage>+ Set a custom label (e.g. VAT no, Tax no, etc.)+ </InputHelperMessage>+ ) : null}+ </div>++ <div>+ <Label htmlFor="buyerVatNo">Value</Label>+ <Controller+ name="buyer.vatNo"+ control={control}+ render={({ field }) => {+ return (+ <Input+ {...field}+ id="buyerVatNo"+ type="text"+ placeholder="Enter Tax number value"+ className={cn(+ "mt-1 block w-full",+ inputErrorClassName(!!errors.buyer?.vatNo),+ )}+ />+ );+ }}+ />+ {errors.buyer?.vatNo ? (+ <ErrorMessage>{errors.buyer.vatNo.message}</ErrorMessage>+ ) : null}+ </div>+ </div>+ </fieldset>+ </div>- <div>- <fieldset className="rounded-md border px-4 pb-4">- <legend className="text-base font-semibold lg:text-lg">- Buyer Tax Number- </legend>+ {/* Email */}+ <div className={FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME}>+ <div className="relative mb-2 flex items-center justify-between">+ <Label htmlFor="buyerEmail">Email</Label>- <div className="mb-2 flex items-center justify-end"><div className="inline-flex items-center gap-2"><Controller- name="buyer.vatNoFieldIsVisible"+ name="buyer.emailFieldIsVisible"control={control}render={({ field: { value, onChange, ...field } }) => {return (<Switch{...field}- id="buyerVatNoFieldIsVisible"+ id="buyerEmailFieldIsVisible"checked={value}onCheckedChange={onChange}size="sm"- data-testid="buyerVatNoFieldIsVisible"- aria-label="Show the 'Buyer Tax Number' Field in the PDF"+ data-testid="buyerEmailFieldIsVisible"+ aria-label="Show the 'Email' field in the PDF"/>);}}/><CustomTooltiptrigger={- <Label htmlFor="buyerVatNoFieldIsVisible">+ <Label htmlFor="buyerEmailFieldIsVisible">Show in PDF</Label>}- content={- isBuyerSelected- ? null- : "Show the 'Buyer Tax Number' Field in the PDF"- }+ content={"Show the 'Email' field in the PDF"}/></div></div>+ <Controller+ name="buyer.email"+ control={control}+ render={({ field }) => {+ return (+ <Input+ {...field}+ id="buyerEmail"+ type="email"+ className={inputErrorClassName(!!errors.buyer?.email)}+ />+ );+ }}+ />+ {errors.buyer?.email ? (+ <ErrorMessage>{errors.buyer.email.message}</ErrorMessage>+ ) : null}+ </div>- <div className="space-y-4">- <div>- <Label htmlFor="buyerVatNoLabel">Label</Label>- <Controller- name="buyer.vatNoLabelText"- control={control}- render={({ field }) => {- return (- <Input- {...field}- type="text"- id="buyerVatNoLabel"- placeholder="Enter Tax number label"- className={cn(- "mt-1 block w-full",- inputErrorClassName(!!errors.buyer?.vatNoLabelText),- )}- />- );- }}- />- {errors.buyer?.vatNoLabelText ? (- <ErrorMessage>- {errors.buyer.vatNoLabelText.message}- </ErrorMessage>- ) : null}- {!errors.buyer?.vatNoLabelText ? (- <InputHelperMessage>- Set a custom label (e.g. VAT no, Tax no, etc.)- </InputHelperMessage>- ) : null}- </div>+ {/* Notes */}+ <div className={FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME}>+ <div className="relative mb-2 flex items-center justify-between">+ <Label htmlFor="buyerNotes">Notes</Label>- <div>- <Label htmlFor="buyerVatNo">Value</Label>+ <div className="inline-flex items-center gap-2"><Controller- name="buyer.vatNo"+ name="buyer.notesFieldIsVisible"control={control}- render={({ field }) => {+ render={({ field: { value, onChange, ...field } }) => {return (- <Input+ <Switch{...field}- id="buyerVatNo"- type="text"- placeholder="Enter Tax number value"- className={cn(- "mt-1 block w-full",- inputErrorClassName(!!errors.buyer?.vatNo),- )}+ id="buyerNotesFieldIsVisible"+ checked={value}+ onCheckedChange={onChange}+ size="sm"+ data-testid="buyerNotesInvoiceFormFieldVisibilitySwitch"+ aria-label="Show the 'Notes' field in the PDF"/>);}}/>- {errors.buyer?.vatNo ? (- <ErrorMessage>{errors.buyer.vatNo.message}</ErrorMessage>- ) : null}+ <CustomTooltip+ trigger={+ <Label htmlFor="buyerNotesFieldIsVisible">+ Show in PDF+ </Label>+ }+ content={"Show the 'Notes' field in the PDF"}+ /></div></div>- </fieldset>- </div>-- {/* Email */}- <div>- <div className="relative mb-2 flex items-center justify-between">- <Label htmlFor="buyerEmail">Email</Label>-- <div className="inline-flex items-center gap-2">- <Controller- name="buyer.emailFieldIsVisible"- control={control}- render={({ field: { value, onChange, ...field } }) => {- return (- <Switch- {...field}- id="buyerEmailFieldIsVisible"- checked={value}- onCheckedChange={onChange}- size="sm"- data-testid="buyerEmailFieldIsVisible"- aria-label="Show the 'Email' field in the PDF"- />- );- }}- />- <CustomTooltip- trigger={- <Label htmlFor="buyerEmailFieldIsVisible">- Show in PDF- </Label>- }- content={- isBuyerSelected ? null : "Show the 'Email' field in the PDF"- }- />- </div>- </div>- <Controller- name="buyer.email"- control={control}- render={({ field }) => {- return (- <Input- {...field}- id="buyerEmail"- type="email"- className={inputErrorClassName(!!errors.buyer?.email)}- />- );- }}- />- {errors.buyer?.email ? (- <ErrorMessage>{errors.buyer.email.message}</ErrorMessage>- ) : null}- </div>-- {/* Notes */}- <div>- <div className="relative mb-2 flex items-center justify-between">- <Label htmlFor="buyerNotes">Notes</Label>- <div className="inline-flex items-center gap-2">- <Controller- name="buyer.notesFieldIsVisible"- control={control}- render={({ field: { value, onChange, ...field } }) => {- return (- <Switch- {...field}- id="buyerNotesFieldIsVisible"- checked={value}- onCheckedChange={onChange}- size="sm"- data-testid="buyerNotesInvoiceFormFieldVisibilitySwitch"- aria-label="Show the 'Notes' field in the PDF"- />- );- }}- />- <CustomTooltip- trigger={- <Label htmlFor="buyerNotesFieldIsVisible">- Show in PDF- </Label>- }- content={- isBuyerSelected ? null : "Show the 'Notes' field in the PDF"- }- />- </div>+ <Controller+ name="buyer.notes"+ control={control}+ render={({ field }) => {+ return (+ <Textarea+ {...field}+ id="buyerNotes"+ rows={3}+ className={inputErrorClassName(!!errors.buyer?.notes)}+ />+ );+ }}+ />+ {errors.buyer?.notes ? (+ <ErrorMessage>{errors.buyer.notes.message}</ErrorMessage>+ ) : null}</div>-- <Controller- name="buyer.notes"- control={control}- render={({ field }) => {- return (- <Textarea- {...field}- id="buyerNotes"- rows={3}- className={inputErrorClassName(!!errors.buyer?.notes)}- />- );- }}- />- {errors.buyer?.notes ? (- <ErrorMessage>{errors.buyer.notes.message}</ErrorMessage>- ) : null}- </div>- </fieldset>+ </fieldset>+ )}</AccordionContent></div>);diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/import-contacts-dialog.test.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/import-contacts-dialog.test.tsxindex f16f68a..52554d7 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/import-contacts-dialog.test.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/import-contacts-dialog.test.tsx@@ -47,6 +47,11 @@ function emptyResult<T extends SellerData | BuyerData>(};}+/** Radix tabs switch on `mousedown`, not `click`. */+function selectTab(dialog: HTMLElement, name: string) {+ fireEvent.mouseDown(within(dialog).getByRole("tab", { name }));+}+function renderDialog(state: ImportContactsDialogState) {render(<ImportContactsDialog@@ -65,6 +70,7 @@ describe("ImportContactsDialog preview", () => {it("lists what will be added, skipped and cannot be imported", () => {const dialog = renderDialog({step: "preview",+ reviewId: "1",fileName: "backup.json",sellers: emptyResult({added: [ACME],@@ -88,22 +94,115 @@ describe("ImportContactsDialog preview", () => {within(dialog).getByRole("heading", { name: "Review import" }),).toBeVisible();- const sellers = within(dialog).getByRole("list", { name: "Sellers" });+ // one tab per outcome the file has, opened on what will be added+ expect(+ within(dialog).getByRole("tab", { name: "To add 1", selected: true }),+ ).toBeVisible();+ expect(+ within(dialog).getByRole("list", { name: "Sellers" }),+ ).toHaveTextContent("Acme1 Main");+ // no buyers to add, so there is no Buyers list on this tab+ expect(+ within(dialog).queryByRole("list", { name: "Buyers" }),+ ).not.toBeInTheDocument();+ expect(+ within(dialog).getByRole("button", { name: "Import 1 seller" }),+ ).toBeVisible();++ // the footer link opens the problems+ fireEvent.click(+ within(dialog).getByRole("button", { name: "1 can’t be imported" }),+ );++ expect(+ within(dialog).getByRole("tab", {+ name: "Can’t import 1",+ selected: true,+ }),+ ).toBeVisible();+ expect(+ within(dialog).getByRole("list", { name: "Sellers" }),+ ).toHaveTextContent("InitechElsewhereName taken");+ expect(+ within(dialog).queryByRole("button", { name: "1 can’t be imported" }),+ ).not.toBeInTheDocument();++ selectTab(dialog, "Already saved 1");- expect(sellers).toHaveTextContent("Acme1 MainNew");- expect(sellers).toHaveTextContent("InitechElsewhereName taken");expect(within(dialog).getByRole("list", { name: "Buyers" }),- ).toHaveTextContent("Globex2 SideAlready saved");+ ).toHaveTextContent("Globex2 Side");+ expect(+ within(dialog).queryByRole("list", { name: "Sellers" }),+ ).not.toBeInTheDocument();+ });++ it("opens another file on its first tab, not the one picked for the last file", () => {+ function previewState(reviewId: string): ImportContactsDialogState {+ return {+ step: "preview",+ reviewId,+ fileName: "backup.json",+ sellers: emptyResult({ added: [ACME] }),+ buyers: emptyResult({ duplicates: [GLOBEX] }),+ };+ }++ const props = {+ isOpen: true,+ onOpenChange: vi.fn(),+ onFileSelected: vi.fn(),+ onConfirm: vi.fn(),+ };+ const { rerender } = render(+ <ImportContactsDialog {...props} state={previewState("1")} />,+ );+ const dialog = screen.getByTestId("import-contacts-dialog");++ selectTab(dialog, "Already saved 1");expect(- within(dialog).getByRole("button", { name: "Import 1 seller" }),+ within(dialog).getByRole("tab", {+ name: "Already saved 1",+ selected: true,+ }),+ ).toBeVisible();++ // the same outcomes again, from a newly picked file+ rerender(<ImportContactsDialog {...props} state={previewState("2")} />);++ expect(+ within(dialog).getByRole("tab", { name: "To add 1", selected: true }),+ ).toBeVisible();+ });++ it("shows no tabs when every entry has the same outcome", () => {+ const dialog = renderDialog({+ step: "preview",+ reviewId: "1",+ fileName: "backup.json",+ sellers: emptyResult({ added: [ACME] }),+ buyers: emptyResult({ added: [GLOBEX] }),+ });++ expect(within(dialog).queryByRole("tablist")).not.toBeInTheDocument();+ expect(+ within(dialog).getByRole("list", { name: "Sellers" }),+ ).toHaveTextContent("Acme1 Main");+ expect(+ within(dialog).getByRole("list", { name: "Buyers" }),+ ).toHaveTextContent("Globex2 Side");+ expect(+ within(dialog).getByRole("button", {+ name: "Import 1 seller and 1 buyer",+ }),).toBeVisible();});it("lists every filled-in field of a new or saved entry in a collapsed row", () => {const dialog = renderDialog({step: "preview",+ reviewId: "1",fileName: "backup.json",sellers: emptyResult({added: [@@ -118,7 +217,7 @@ describe("ImportContactsDialog preview", () => {}),],}),- buyers: emptyResult({ duplicates: [GLOBEX] }),+ buyers: emptyResult({ added: [GLOBEX] }),});const [acme, globex] = within(dialog).getAllByTestId(@@ -146,6 +245,7 @@ describe("ImportContactsDialog preview", () => {const dialog = renderDialog({step: "preview",+ reviewId: "1",fileName: "backup.json",sellers: emptyResult({added: [@@ -173,6 +273,7 @@ describe("ImportContactsDialog preview", () => {it("shows the entry as written in the file with the failing field highlighted", () => {const dialog = renderDialog({step: "preview",+ reviewId: "1",fileName: "backup.json",sellers: emptyResult({invalidEntries: [@@ -213,6 +314,7 @@ describe("ImportContactsDialog preview", () => {it("adds a line for a required field the entry does not have", () => {const dialog = renderDialog({step: "preview",+ reviewId: "1",fileName: "backup.json",sellers: emptyResult(),buyers: emptyResult({@@ -234,6 +336,7 @@ describe("ImportContactsDialog preview", () => {it("shows a problem with the entry as a whole above its value", () => {const dialog = renderDialog({step: "preview",+ reviewId: "1",fileName: "backup.json",sellers: emptyResult({invalidEntries: [@@ -315,6 +418,7 @@ describe("ImportContactsDialog drop", () => {const states: ImportContactsDialogState[] = [{step: "preview",+ reviewId: "1",fileName: "backup.json",sellers: emptyResult({ added: [ACME] }),buyers: emptyResult(),@@ -347,7 +451,7 @@ describe("ImportContactsDialog drop", () => {const textDrag = { types: ["text/plain"], files: [] };fireEvent.dragEnter(document.body, { dataTransfer: textDrag });- expect(getDropZone()).not.toHaveClass("border-slate-600");+ expect(getDropZone()).not.toHaveClass("border-slate-700");const drop = createEvent.drop(document.body, { dataTransfer: textDrag });fireEvent(document.body, drop);@@ -384,17 +488,17 @@ describe("ImportContactsDialog drop", () => {);fireEvent.dragEnter(document.body, { dataTransfer });- expect(getDropZone()).toHaveClass("border-slate-600");+ expect(getDropZone()).toHaveClass("border-slate-700");// Into a child: WebKit fires the `dragleave` for the element being left with a null// `relatedTarget`, which must not read as leaving the windowfireEvent.dragEnter(rule, { dataTransfer });fireEvent.dragLeave(document.body, { dataTransfer });- expect(getDropZone()).toHaveClass("border-slate-600");+ expect(getDropZone()).toHaveClass("border-slate-700");// Out of the windowfireEvent.dragLeave(rule, { dataTransfer });- expect(getDropZone()).not.toHaveClass("border-slate-600");+ expect(getDropZone()).not.toHaveClass("border-slate-700");});it("clears the highlight when Firefox enters the same element twice", () => {@@ -406,7 +510,7 @@ describe("ImportContactsDialog drop", () => {fireEvent.dragEnter(document.body, { dataTransfer });fireEvent.dragLeave(document.body, { dataTransfer });- expect(getDropZone()).not.toHaveClass("border-slate-600");+ expect(getDropZone()).not.toHaveClass("border-slate-700");});});diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/stale-dates-banner.test.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/stale-dates-banner.test.tsxindex 5905d00..a04cee1 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/stale-dates-banner.test.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/stale-dates-banner.test.tsx@@ -34,8 +34,8 @@ const STALE_PROPS = {dateOfService: "2026-06-30",dateOfServiceStart: "2026-06-01",invoiceNumberValue: "1/06-2026",- // Not 14 days after the date of issue, so it counts as stale too.- paymentDue: "2026-06-20",+ // Before the date of issue, the one way a payment due date counts as stale.+ paymentDue: "2026-06-05",selectedDateFormat: "MMMM D, YYYY",isMobile: false,};@@ -141,17 +141,41 @@ describe("StaleDatesBanner", () => {dateOfIssue: "2026-09-15",dateOfServiceStart: "2026-09-01",dateOfService: "2026-09-30",- invoiceNumberValue: "1/09-2026",- paymentDue: "2026-06-24",+ invoiceNumberValue: "1/08-2026",+ // due 30 days after a current date of issue: a choice, not out of date+ paymentDue: "2026-10-15",});expect(within(getBanner()).getByText("1 field is out of date"),).toBeVisible();- expect(getRow("Payment due")).toBeInTheDocument();+ expect(getRowLabels()).toEqual(["Invoice number"]);+ });++ it("suggests 14 days after issue for a payment due date before the date of issue", () => {+ renderBanner();++ const row = getRow("Payment due");++ expect(within(row).getByText("June 5, 2026")).toBeVisible();+ expect(within(row).getByText("September 29, 2026")).toBeVisible();+ expect(within(row).getByText("(date of issue + 14 days)")).toBeVisible();+ });++ it("leaves a payment due date after the date of issue out, but keeps its term on update", async () => {+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });+ const setValue = vi.fn();++ // due 10 days after the stale date of issue+ renderBanner({ paymentDue: "2026-06-20", setValue });+expect(- within(getBanner()).queryByRole("cell", { name: "Date of issue" }),+ within(getBanner()).queryByRole("cell", { name: "Payment due" }),).not.toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: /update all dates/i }));++ expect(setValue).toHaveBeenCalledWith("paymentDue", "2026-09-25");});it("falls back to a placeholder when a date is not set", () => {diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/stripe-top-line-color-picker.test.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/stripe-top-line-color-picker.test.tsxnew file mode 100644index 0000000..2f95a64--- /dev/null+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/stripe-top-line-color-picker.test.tsx@@ -0,0 +1,186 @@+// @vitest-environment happy-dom++import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, describe, expect, it, vi } from "vitest";+import "@testing-library/jest-dom/vitest";++import { StripeTopLineColorPicker } from "../stripe-top-line-color-picker";++function renderPicker({ value }: { value?: string } = {}) {+ const onChange = vi.fn();++ render(<StripeTopLineColorPicker value={value} onChange={onChange} />);++ return { onChange };+}++describe("StripeTopLineColorPicker", () => {+ afterEach(() => {+ cleanup();+ });++ it("marks the default amber as picked while the invoice has no color", () => {+ renderPicker();++ expect(+ screen.getByRole("button", { name: "Amber (default)" }),+ ).toHaveAttribute("aria-pressed", "true");+ expect(+ screen.queryByRole("button", { name: "Reset to default" }),+ ).not.toBeInTheDocument();+ });++ it("writes a preset's color when it is clicked", async () => {+ const user = userEvent.setup();+ const { onChange } = renderPicker();++ await user.click(screen.getByRole("button", { name: "Indigo" }));++ expect(onChange).toHaveBeenCalledWith("#635bff");+ });++ it("clears the field rather than writing the default color back", async () => {+ const user = userEvent.setup();+ const { onChange } = renderPicker({ value: "#635bff" });++ await user.click(screen.getByRole("button", { name: "Amber (default)" }));++ expect(onChange).toHaveBeenCalledWith(undefined);+ });++ it("resets a picked color to the default", async () => {+ const user = userEvent.setup();+ const { onChange } = renderPicker({ value: "#635bff" });++ await user.click(screen.getByRole("button", { name: "Reset to default" }));++ expect(onChange).toHaveBeenCalledWith(undefined);+ });++ it.each([+ ["a preset", "#635bff"],+ ["a custom", "#e11d48"],+ ])(+ "keeps the picker closed for %s color until the custom button is clicked",+ async (_kind, value) => {+ const user = userEvent.setup();+ renderPicker({ value });++ const customButton = screen.getByRole("button", { name: "Custom color" });++ expect(customButton).toHaveAttribute("aria-expanded", "false");+ expect(screen.queryByLabelText("Hex color")).not.toBeInTheDocument();++ await user.click(customButton);++ expect(customButton).toHaveAttribute("aria-expanded", "true");+ expect(+ screen.getByRole("dialog", { name: "Custom top line color" }),+ ).toBeInTheDocument();+ expect(screen.getByLabelText("Hex color")).toBeInTheDocument();+ },+ );++ it("closes the picker on Escape", async () => {+ const user = userEvent.setup();+ renderPicker();++ await user.click(screen.getByRole("button", { name: "Custom color" }));+ await user.keyboard("{Escape}");++ expect(screen.queryByLabelText("Hex color")).not.toBeInTheDocument();+ });++ it("names a color none of the presets match as custom", () => {+ renderPicker({ value: "#e11d48" });++ expect(screen.getByText("Custom ·", { exact: false })).toBeInTheDocument();+ });++ it("writes a typed hex color once typing settles", async () => {+ const user = userEvent.setup();+ const { onChange } = renderPicker({ value: "#635bff" });++ await user.click(screen.getByRole("button", { name: "Custom color" }));++ const hexField = screen.getByLabelText("Hex color");+ await user.clear(hexField);+ await user.type(hexField, "E11D48");++ // the caption follows the draft at once, the form does not+ expect(+ screen.getByText("#e11d48", { exact: false, ignore: "input" }),+ ).toBeInTheDocument();+ expect(onChange).not.toHaveBeenCalled();++ await waitFor(() => {+ expect(onChange).toHaveBeenLastCalledWith("#e11d48");+ });+ expect(onChange).toHaveBeenCalledTimes(1);+ });++ it("leaves a half-deleted value as typed instead of reading it as a shorthand", async () => {+ const user = userEvent.setup();+ const { onChange } = renderPicker({ value: "#fbbf24" });++ await user.click(screen.getByRole("button", { name: "Custom color" }));++ const hexField = screen.getByLabelText("Hex color");+ await user.click(hexField);+ await user.keyboard("{End}{Backspace}{Backspace}{Backspace}");++ expect(hexField).toHaveValue("FBB");++ // give a debounced write every chance to land+ await new Promise((resolve) => {+ setTimeout(resolve, 400);+ });++ expect(hexField).toHaveValue("FBB");+ expect(onChange).not.toHaveBeenCalled();+ });++ it("spells out a shorthand once the field loses focus", async () => {+ const user = userEvent.setup();+ const { onChange } = renderPicker({ value: "#635bff" });++ await user.click(screen.getByRole("button", { name: "Custom color" }));++ const hexField = screen.getByLabelText("Hex color");+ await user.clear(hexField);+ await user.type(hexField, "fa0");++ expect(hexField).toHaveValue("FA0");++ fireEvent.blur(hexField);++ expect(hexField).toHaveValue("FFAA00");+ await waitFor(() => {+ expect(onChange).toHaveBeenLastCalledWith("#ffaa00");+ });+ });++ it("writes the color still waiting when the picker closes", async () => {+ const user = userEvent.setup();+ const { onChange } = renderPicker({ value: "#635bff" });++ await user.click(screen.getByRole("button", { name: "Custom color" }));++ fireEvent.change(screen.getByLabelText("Hex color"), {+ target: { value: "e11d48" },+ });++ expect(onChange).not.toHaveBeenCalled();++ await user.keyboard("{Escape}");++ expect(onChange).toHaveBeenCalledWith("#e11d48");+ });+});diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/buyer/buyer-dialog.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/buyer/buyer-dialog.tsxindex 0ddf5c6..8595ada 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/components/buyer/buyer-dialog.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/buyer/buyer-dialog.tsx@@ -1,8 +1,13 @@import * as Sentry from "@sentry/nextjs";import { useState } from "react";-import { useForm } from "react-hook-form";+import { useForm, useWatch } from "react-hook-form";import { toast } from "sonner";+import {+ getPartyFieldClassName,+ PartyDialogSection,+ PdfVisibilityToggle,+} from "@/app/(main)/(app)/components/invoice-form/sections/components/party-dialog-fields";import { useConfirmDiscard } from "@/app/(main)/(app)/components/invoice-form/sections/hooks/use-confirm-discard";import {getAppStorageItem,@@ -31,11 +36,9 @@ import {FormMessage,} from "@/components/ui/form";import { Input } from "@/components/ui/input";-import { InputHelperMessage } from "@/components/ui/input-helper-message";import { Label } from "@/components/ui/label";import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";-import { CustomTooltip } from "@/components/ui/tooltip";import { zodResolverForOutput } from "@/lib/zod-resolver-for-output";import { ConfirmDiscardDialog } from "../confirm-discard-dialog";@@ -65,6 +68,8 @@ interface BuyerDialogProps {) => void;handleBuyerEdit?: (buyer: BuyerData) => void;initialData: BuyerData | null;+ /** The tax number label a new buyer starts with: the invoice language's, as in the form. */+ defaultVatNoLabelText: string;isEditMode: boolean;formValues?: Partial<BuyerData>;}@@ -90,6 +95,7 @@ export function BuyerDialog({handleBuyerAdd,handleBuyerEdit,initialData,+ defaultVatNoLabelText,isEditMode,formValues,}: BuyerDialogProps) {@@ -100,7 +106,7 @@ export function BuyerDialog({name: initialData?.name ?? "",address: initialData?.address ?? "",vatNo: initialData?.vatNo ?? "",- vatNoLabelText: initialData?.vatNoLabelText ?? "VAT no",+ vatNoLabelText: initialData?.vatNoLabelText ?? defaultVatNoLabelText,email: initialData?.email ?? "",emailFieldIsVisible: initialData?.emailFieldIsVisible ?? true,vatNoFieldIsVisible: initialData?.vatNoFieldIsVisible ?? true,@@ -109,7 +115,13 @@ export function BuyerDialog({},});- const { isDirty } = form.formState;+ const { isDirty, dirtyFields } = form.formState;++ // hidden fields are faded in the dialog, as they will be missing from the PDF+ const [isVatNoVisible, isEmailVisible, isNotesVisible] = useWatch({+ control: form.control,+ name: ["vatNoFieldIsVisible", "emailFieldIsVisible", "notesFieldIsVisible"],+ });const { isConfirmDiscardDialogOpen, setIsConfirmDiscardDialogOpen } =useConfirmDiscard();@@ -131,6 +143,11 @@ export function BuyerDialog({(() => void) | null>(null);+ /** Filled in from the invoice and not changed since, so it is tinted as copied. */+ function isPrefilled({ name, value }: IsPrefilledOptions) {+ return shouldApplyInlineFormValues && !dirtyFields[name] && Boolean(value);+ }+/*** Resets the dialog form to the buyer it was opened with, or to an empty* form when adding a new one.@@ -140,7 +157,12 @@ export function BuyerDialog({* pre-fill it would restore the pre-filled values instead of clearing them.*/function resetFormToInitialValues() {- form.reset(initialData ?? EMPTY_BUYER_FORM_VALUES);+ form.reset(+ initialData ?? {+ ...EMPTY_BUYER_FORM_VALUES,+ vatNoLabelText: defaultVatNoLabelText,+ },+ );}/**@@ -321,126 +343,128 @@ export function BuyerDialog({><DialogHeader className="border-b border-slate-200 px-6 py-4 dark:border-slate-800"><DialogTitle className="text-base">- {isEditMode ? "Edit Buyer" : "Add New Buyer"}+ {isEditMode ? "Edit buyer" : "New buyer"}</DialogTitle><DialogDescription>{isEditMode- ? "Edit the buyer details"- : "Add a new buyer to use later in your invoices"}+ ? "Changes apply to every invoice that uses this buyer."+ : "Saved in this browser, ready to pick on any invoice."}</DialogDescription></DialogHeader><div className="overflow-y-auto px-6 py-4">{/* Add Use Current Form Values switch */}{!isEditMode ? (- <div className="mb-4">- <div className="flex items-center gap-2">- <Switch- checked={shouldApplyInlineFormValues}- onCheckedChange={handlePrefillSwitchToggle}- id="apply-form-values-switch"- />+ <div className="mb-4 flex items-center gap-3 rounded-lg bg-neutral-100 px-4 py-3">+ <Switch+ checked={shouldApplyInlineFormValues}+ onCheckedChange={handlePrefillSwitchToggle}+ id="apply-form-values-switch"+ aria-describedby="apply-form-values-description"+ // the default track is too pale to read as "off" on the grey strip+ className="shrink-0 data-[state=unchecked]:bg-slate-300"+ />+ <div><LabelhtmlFor="apply-form-values-switch"- className="cursor-pointer"+ className="cursor-pointer text-sm font-semibold text-slate-900">- Pre-fill with values from the current invoice form+ Fill in from this invoice</Label>+ <p+ id="apply-form-values-description"+ className="mt-0.5 text-pretty text-sm text-slate-600"+ >+ Copies the buyer you typed into the invoice. You can still+ change it here.+ </p></div>- <span className="mt-1.5 inline-block text-xs text-slate-500">- When enabled, this will automatically fill in the buyer- details dialog with the information you've already- entered in your current invoice form.- </span></div>) : null}<Form {...form}><formonSubmit={form.handleSubmit(onSubmit)}- className="space-y-4"+ className="space-y-5"id={BUYER_FORM_ID}>- <FormField- control={form.control}- name="name"- render={({ field }) => {- return (- <FormItem>- <FormLabel>Name (Required)</FormLabel>- <FormControl>- <Textarea- {...field}- rows={3}- placeholder="Enter buyer name"- />- </FormControl>- <FormMessage />- </FormItem>- );- }}- />+ <PartyDialogSection title="Business">+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => {+ return (+ <FormItem>+ <FormLabel>Name (Required)</FormLabel>+ <FormControl>+ <Textarea+ {...field}+ rows={2}+ placeholder="Enter buyer name"+ className={getPartyFieldClassName({+ isPrefilled: isPrefilled({+ name: "name",+ value: field.value,+ }),+ })}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ );+ }}+ />+ <FormField+ control={form.control}+ name="address"+ render={({ field }) => {+ return (+ <FormItem>+ <FormLabel>Address (Required)</FormLabel>+ <FormControl>+ <Textarea+ {...field}+ rows={2}+ placeholder="Enter buyer address"+ className={getPartyFieldClassName({+ isPrefilled: isPrefilled({+ name: "address",+ value: field.value,+ }),+ })}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ );+ }}+ />+ </PartyDialogSection>- <FormField- control={form.control}- name="address"- render={({ field }) => {- return (- <FormItem>- <FormLabel>Address (Required)</FormLabel>- <FormControl>- <Textarea- {...field}- rows={3}- placeholder="Enter buyer address"+ <PartyDialogSection+ title="Tax number"+ action={+ <FormField+ control={form.control}+ name="vatNoFieldIsVisible"+ render={({ field }) => {+ return (+ <PdfVisibilityToggle+ id="vatNoFieldIsVisible"+ checked={field.value}+ onCheckedChange={field.onChange}+ fieldLabel="Tax Number"/>- </FormControl>- <FormMessage />- </FormItem>- );- }}- />-- {/* Tax Number */}- <fieldset className="rounded-md border px-4 pb-4">- <legend className="text-base font-semibold lg:text-lg">- Buyer Tax Number- </legend>-- <div className="mb-2 flex items-center justify-end">- {/* Show Tax Number Field in PDF */}- <div className="flex items-center gap-2">- <FormField- control={form.control}- name="vatNoFieldIsVisible"- render={({ field }) => {- return (- <FormItem>- <div className="flex items-center gap-2">- <Switch- checked={field.value}- onCheckedChange={field.onChange}- id="vatNoFieldIsVisible"- aria-label={`Show the 'Tax Number' field in the PDF`}- />- <CustomTooltip- trigger={- <Label htmlFor="vatNoFieldIsVisible">- Show in PDF- </Label>- }- content='Show the "Tax Number" field in the PDF'- className="z-[1000]"- />- </div>- </FormItem>- );- }}- />- </div>- </div>-- <div className="space-y-4">+ );+ }}+ />+ }+ >+ {/* a label of its own, so the PDF can say "VAT no", "Tax ID", ... */}+ <fieldset+ aria-label="Buyer tax number"+ className="grid min-w-0 grid-cols-[7rem_minmax(0,1fr)] gap-3"+ ><FormFieldcontrol={form.control}name="vatNoLabelText"@@ -451,37 +475,39 @@ export function BuyerDialog({<FormControl><Input{...field}- placeholder="Enter Tax number label"+ placeholder="e.g. VAT no"+ className={getPartyFieldClassName({+ isHidden: !isVatNoVisible,+ isPrefilled: isPrefilled({+ name: "vatNoLabelText",+ value: field.value,+ }),+ })}/></FormControl>-- {form.formState.errors.vatNoLabelText ? (- <FormMessage>- {form.formState.errors.vatNoLabelText.message}- </FormMessage>- ) : null}-- {!form.formState.errors.vatNoLabelText ? (- <InputHelperMessage>- Set a custom label (e.g. VAT no, Tax no, etc.)- </InputHelperMessage>- ) : null}+ <FormMessage /></FormItem>);}}/>-<FormFieldcontrol={form.control}name="vatNo"render={({ field }) => {return (<FormItem>- <FormLabel>Value</FormLabel>+ <FormLabel>Number</FormLabel><FormControl><Input{...field}- placeholder="Enter Tax number value"+ placeholder="e.g. PL1234567890"+ className={getPartyFieldClassName({+ isHidden: !isVatNoVisible,+ isPrefilled: isPrefilled({+ name: "vatNo",+ value: field.value,+ }),+ })}/></FormControl><FormMessage />@@ -489,25 +515,46 @@ export function BuyerDialog({);}}/>- </div>- </fieldset>+ </fieldset>+ </PartyDialogSection>- {/* Email */}- <div className="space-y-3 rounded-md border p-4">+ <PartyDialogSection title="Contact"><FormFieldcontrol={form.control}name="email"render={({ field }) => {return (<FormItem>- <FormLabel className="mb-2 font-medium">- </FormLabel>+ <div className="flex items-center justify-between gap-2">+ <FormLabel>Email</FormLabel>+ <FormField+ control={form.control}+ name="emailFieldIsVisible"+ render={({ field: visibilityField }) => {+ return (+ <PdfVisibilityToggle+ id="emailFieldIsVisible"+ checked={visibilityField.value}+ onCheckedChange={visibilityField.onChange}+ fieldLabel="Email"+ data-testid="buyerEmailDialogFieldVisibilitySwitch"+ />+ );+ }}+ />+ </div><FormControl><Input{...field}type="email"placeholder="[email protected]"+ className={getPartyFieldClassName({+ isHidden: !isEmailVisible,+ isPrefilled: isPrefilled({+ name: "email",+ value: field.value,+ }),+ })}/></FormControl><FormMessage />@@ -515,54 +562,49 @@ export function BuyerDialog({);}}/>- <FormField- control={form.control}- name="emailFieldIsVisible"- render={({ field }) => {- return (- <FormItem>- <div className="flex items-center gap-2">- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- id="emailFieldIsVisible"- data-testid={`buyerEmailDialogFieldVisibilitySwitch`}- />- </FormControl>- <CustomTooltip- trigger={- <Label htmlFor="emailFieldIsVisible">- Show Buyer Email in PDF- </Label>- }- content='Show the "Email" field in the PDF'- className="z-[1000]"- />- </div>- </FormItem>- );- }}- />- </div>+ </PartyDialogSection>- {/* Notes */}- <div className="space-y-3 rounded-md border p-4">+ <PartyDialogSection+ title="Notes"+ action={+ <FormField+ control={form.control}+ name="notesFieldIsVisible"+ render={({ field }) => {+ return (+ <PdfVisibilityToggle+ id="notes-field-visibility"+ checked={field.value}+ onCheckedChange={field.onChange}+ fieldLabel="Notes"+ data-testid="buyerNotesDialogFieldVisibilitySwitch"+ />+ );+ }}+ />+ }+ ><FormFieldcontrol={form.control}name="notes"render={({ field }) => {return (<FormItem>- <FormLabel className="mb-2 font-medium">- Notes- </FormLabel>+ {/* the section heading says it already */}+ <FormLabel className="sr-only">Notes</FormLabel><FormControl><Textarea{...field}- rows={3}+ rows={2}placeholder="Enter notes (max 750 characters)"maxLength={750}+ className={getPartyFieldClassName({+ isHidden: !isNotesVisible,+ isPrefilled: isPrefilled({+ name: "notes",+ value: field.value,+ }),+ })}/></FormControl><FormMessage />@@ -570,93 +612,78 @@ export function BuyerDialog({);}}/>- <FormField- control={form.control}- name="notesFieldIsVisible"- render={({ field }) => {- return (- <FormItem>- <div className="flex items-center gap-2">- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- id="notes-field-visibility"- data-testid={`buyerNotesDialogFieldVisibilitySwitch`}- />- </FormControl>- <CustomTooltip- trigger={- <Label htmlFor="notes-field-visibility">- Show Buyer Notes in PDF- </Label>- }- content="Show the notes field in the PDF"- className="z-[1000]"- />- </div>- </FormItem>- );- }}- />- </div>+ </PartyDialogSection></form></Form>-- {/* Apply to Current Invoice switch remains at bottom */}+ </div>+ <DialogFooter className="border-border gap-3 border-t px-6 py-4 sm:items-center sm:justify-between">+ {/* where the choice is made: next to Save, rather than at the end of the form */}{!isEditMode ? (- <div className="mt-4 flex flex-col gap-1 border-t pt-4">+ <div><div className="flex items-center gap-2">- <Switch- checked={shouldApplyNewBuyerToInvoice}- onCheckedChange={setShouldApplyNewBuyerToInvoice}+ <input+ type="checkbox"id="apply-buyer-to-current-invoice-switch"+ checked={shouldApplyNewBuyerToInvoice}+ onChange={(event) => {+ setShouldApplyNewBuyerToInvoice(event.target.checked);+ }}+ aria-describedby="apply-buyer-to-current-invoice-description"+ className="size-4 cursor-pointer accent-slate-900"/>+<LabelhtmlFor="apply-buyer-to-current-invoice-switch"- className="cursor-pointer"+ className="cursor-pointer font-normal">- Apply to Current Invoice+ Use on this invoice</Label></div>- <span className="mt-1.5 text-xs text-slate-500">- When enabled, the newly created buyer will be automatically- applied to your current invoice form and reflected in the- generated PDF.- </span>++ {/* says what Save will do with the current choice */}+ <p+ id="apply-buyer-to-current-invoice-description"+ className="ml-6 mt-0.5 max-w-64 text-pretty text-xs text-slate-500"+ >+ {shouldApplyNewBuyerToInvoice+ ? "Replaces the buyer on this invoice with this one."+ : "Only saved to your list. This invoice keeps its buyer."}+ </p></div>- ) : null}- </div>- <DialogFooter className="border-border border-t px-6 py-4">- <Button- type="button"- variant="outline"- onClick={() => {- // Handles the discard action by checking for unsaved changes.- // If there are unsaved changes (isDirty), opens the confirmation dialog.- // Otherwise, closes the dialog immediately.- if (isDirty) {- setPendingDiscardAction(() => {- return closeDialog;- });- setIsConfirmDiscardDialogOpen(true);- return;- }- closeDialog();- }}- >- Cancel- </Button>- <Button- type="button"- onClick={async () => {- // trigger validations and submit the form and handle errors- void form.handleSubmit(onSubmit)();- }}- form={BUYER_FORM_ID}- >- Save Buyer- </Button>+ ) : (+ <span aria-hidden />+ )}+ <div className="flex flex-col-reverse gap-2 sm:flex-row">+ <Button+ type="button"+ variant="outline"+ onClick={() => {+ // Handles the discard action by checking for unsaved changes.+ // If there are unsaved changes (isDirty), opens the confirmation dialog.+ // Otherwise, closes the dialog immediately.+ if (isDirty) {+ setPendingDiscardAction(() => {+ return closeDialog;+ });+ setIsConfirmDiscardDialogOpen(true);+ return;+ }+ closeDialog();+ }}+ >+ Cancel+ </Button>+ <Button+ type="button"+ onClick={async () => {+ // trigger validations and submit the form and handle errors+ void form.handleSubmit(onSubmit)();+ }}+ form={BUYER_FORM_ID}+ >+ Save buyer+ </Button>+ </div></DialogFooter></DialogContent></Dialog>@@ -672,3 +699,8 @@ export function BuyerDialog({</>);}++interface IsPrefilledOptions {+ name: keyof BuyerData;+ value: unknown;+}diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/buyer/buyer-management.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/buyer/buyer-management.tsxindex ea06100..256bcb2 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/components/buyer/buyer-management.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/buyer/buyer-management.tsx@@ -6,6 +6,7 @@ import { toast } from "sonner";import { ContactsBackupMenu } from "@/app/(main)/(app)/components/invoice-form/sections/components/contacts-backup-menu";import { usePartyActions } from "@/app/(main)/(app)/components/invoice-form/sections/hooks/use-party-actions";import { useSavedParties } from "@/app/(main)/(app)/components/invoice-form/sections/hooks/use-saved-parties";+import { INVOICE_PDF_TRANSLATIONS } from "@/app/(main)/(app)/pdf-i18n-translations/pdf-translations";import { type InvoiceData, type BuyerData } from "@/app/schema";import {AlertDialog,@@ -262,8 +263,9 @@ export function BuyerManagement({</div><BuyerDialog- // we need to rerender the dialog when the editingBuyer changes- key={editingBuyer?.id}+ // remount for another buyer to edit, and after a language change, so a new+ // buyer starts with that language's tax label (the form only reads its defaults once)+ key={`${editingBuyer?.id ?? "new"}-${invoiceData.language}`}isOpen={isBuyerDialogOpen}onClose={() => {setIsBuyerDialogOpen(false);@@ -284,6 +286,9 @@ export function BuyerManagement({initialData={editingBuyer}isEditMode={isEditMode}formValues={formValues}+ defaultVatNoLabelText={+ INVOICE_PDF_TRANSLATIONS[invoiceData.language].buyer.vatNo+ }/>{/* Delete alert buyer dialog */}diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/contact-fields.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/contact-fields.tsxnew file mode 100644index 0000000..d6ed211--- /dev/null+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/contact-fields.tsx@@ -0,0 +1,197 @@+import { Check, EyeOff, Info } from "lucide-react";+import { type Control, useWatch } from "react-hook-form";++import type { BuyerData, InvoiceData, SellerData } from "@/app/schema";+import { cn } from "@/lib/utils";++interface ContactFieldsProps {+ contact: SellerData | BuyerData;+}++/** Every filled-in field of the entry, with the ones hidden on the invoice marked so. */+export function ContactFields({ contact }: ContactFieldsProps) {+ const fields = getContactFields(contact);++ return (+ <dl className="space-y-1.5 border-t border-slate-200 bg-slate-50/60 px-3 py-2 text-xs">+ {fields.map(({ field, label, value, isHidden }) => {+ return (+ <div+ key={field}+ className="grid grid-cols-[7rem_minmax(0,1fr)] gap-2"+ >+ <dt className="text-slate-500">{label}</dt>+ <dd className="whitespace-pre-line break-words text-slate-700">+ {value}+ {isHidden ? (+ <span className="ml-1.5 text-slate-400">+ (hidden on invoice)+ </span>+ ) : null}+ </dd>+ </div>+ );+ })}+ </dl>+ );+}++interface ContactField {+ /** The schema key, used as the React key: labels can repeat, as the tax label is user-set. */+ field: keyof SellerData;+ label: string;+ value: string;+ /** The entry has the value but does not show it on the invoice. */+ isHidden: boolean;+}++function getContactFields(contact: SellerData | BuyerData): ContactField[] {+ const fields: (ContactField | null)[] = [+ { field: "name", label: "Name", value: contact.name, isHidden: false },+ {+ field: "address",+ label: "Address",+ value: contact.address,+ isHidden: false,+ },+ optionalField({+ field: "vatNo",+ label: contact.vatNoLabelText,+ value: contact.vatNo,+ isVisible: contact.vatNoFieldIsVisible,+ }),+ optionalField({+ field: "email",+ label: "Email",+ value: contact.email,+ isVisible: contact.emailFieldIsVisible,+ }),+ "accountNumber" in contact+ ? optionalField({+ field: "accountNumber",+ label: "Account Number",+ value: contact.accountNumber,+ isVisible: contact.accountNumberFieldIsVisible,+ })+ : null,+ "swiftBic" in contact+ ? optionalField({+ field: "swiftBic",+ label: "SWIFT/BIC",+ value: contact.swiftBic,+ isVisible: contact.swiftBicFieldIsVisible,+ })+ : null,+ optionalField({+ field: "notes",+ label: "Notes",+ value: contact.notes,+ isVisible: contact.notesFieldIsVisible,+ }),+ ];++ return fields.filter((field) => {+ return field !== null;+ });+}++interface OptionalFieldOptions {+ field: ContactField["field"];+ label: string;+ /** Left out of the list when empty. */+ value: string | undefined;+ /** The entry's `…FieldIsVisible` flag for this field. */+ isVisible: boolean;+}++function optionalField({+ field,+ label,+ value,+ isVisible,+}: OptionalFieldOptions): ContactField | null {+ return value ? { field, label, value, isHidden: !isVisible } : null;+}++interface SavedContactCardProps {+ control: Control<InvoiceData>;+ party: "seller" | "buyer";+}++/**+ * Stands in for the seller or buyer fields while a saved one is picked: what the PDF prints,+ * with the same fields the import preview lists and the ones it leaves out marked as hidden.+ * Changing them goes through the pencil next to the picker, so they are not editable here.+ */+export function SavedContactCard({ control, party }: SavedContactCardProps) {+ // the details on the invoice, which are the saved seller's or buyer's. The form's own+ // value, not `invoiceData`: that one only catches up after the form's debounce, so the+ // card would show the previous party for half a second after a pick. Watched here rather+ // than in the section, so typing in the section's own fields does not re-render it+ const contact = useWatch({ control, name: party });++ // the name and address head the card, so the list starts after them+ const fields = getContactFields(contact).filter(({ field }) => {+ return field !== "name" && field !== "address";+ });++ return (+ <section+ aria-label={`Saved ${party}`}+ className="overflow-hidden rounded-xl border border-slate-200 bg-white text-sm"+ data-testid={`${party}-saved-card`}+ >+ <header className="flex items-start justify-between gap-3 p-4">+ <div className="min-w-0">+ <p className="text-pretty break-words font-semibold text-slate-900">+ {contact.name}+ </p>+ <p className="mt-0.5 whitespace-pre-line break-words text-slate-500">+ {contact.address}+ </p>+ </div>+ <span className="inline-flex h-5 shrink-0 items-center gap-1 whitespace-nowrap rounded-full bg-emerald-50 px-2 text-xs font-medium text-emerald-700">+ <Check className="size-3" aria-hidden />+ Saved+ </span>+ </header>++ {fields.length > 0 ? (+ <dl className="space-y-2.5 border-t border-slate-200 px-4 pb-4 pt-3">+ {fields.map(({ field, label, value, isHidden }) => {+ return (+ // the value drops under its label once the card is too narrow for both+ <div key={field} className="flex flex-wrap gap-x-3 gap-y-0.5">+ <dt className="shrink-0 basis-[7.5rem] text-slate-500">+ {label}+ </dt>+ <dd className="flex min-w-40 flex-1 flex-wrap items-center gap-x-2 gap-y-1 break-words">+ <span+ className={cn(+ "min-w-0 whitespace-pre-line tabular-nums",+ isHidden ? "text-slate-400" : "text-slate-900",+ )}+ >+ {value}+ </span>+ {isHidden ? (+ <span className="inline-flex h-5 items-center gap-1 whitespace-nowrap rounded-full bg-slate-100 px-2 text-xs font-medium text-slate-500">+ <EyeOff className="size-3" aria-hidden />+ Hidden on invoice+ </span>+ ) : null}+ </dd>+ </div>+ );+ })}+ </dl>+ ) : null}++ <p className="flex items-start gap-2 text-pretty border-t border-slate-200 bg-slate-50 px-4 py-2.5 text-xs text-slate-500">+ <Info className="mt-px size-3.5 shrink-0" aria-hidden />+ Printed as listed. Use the pencil to change this {party} on every+ invoice that uses it.+ </p>+ </section>+ );+}diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/contacts-backup-menu.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/contacts-backup-menu.tsxindex b419873..6222c1e 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/components/contacts-backup-menu.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/contacts-backup-menu.tsx@@ -174,6 +174,7 @@ export function ContactsBackupMenu({ isMobile }: ContactsBackupMenuProps) {setImportState({step: "preview",+ reviewId: String(Date.now()),fileName: file.name,sellers,buyers,diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/import-contacts-dialog.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/import-contacts-dialog.tsxindex f80e996..55fe932 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/components/import-contacts-dialog.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/import-contacts-dialog.tsx@@ -18,9 +18,12 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";import { cn } from "@/lib/utils";+import { ContactFields } from "./contact-fields";+/** Longer values are cut short, so one long address does not push the problem off screen. */const MAX_VALUE_LENGTH = 120;@@ -35,6 +38,8 @@ export type ImportContactsDialogState =}| {step: "preview";+ /** A new value for each file read, so another file starts a fresh review. */+ reviewId: string;/** The name of the file being imported. */fileName: string;/** What importing the file would do to the saved sellers. */@@ -178,6 +183,9 @@ export function ImportContactsDialog({/>) : (<PreviewStep+ // another file picked from here starts on its first tab, not the one picked+ // for the previous file+ key={state.reviewId}fileName={state.fileName}sellers={state.sellers}buyers={state.buyers}@@ -213,15 +221,15 @@ function ChooseFileStep({<FilePickerLabelonFileSelected={onFileSelected}className={cn(- "flex cursor-pointer flex-col items-center gap-1 rounded-lg border border-dashed border-slate-300 px-4 py-6 text-center transition-colors focus-within:outline focus-within:outline-2 focus-within:outline-offset-2 hover:bg-slate-50",- isDraggingFile && "border-slate-600 bg-slate-100",+ "flex cursor-pointer flex-col items-center gap-1 rounded-lg border border-dashed border-slate-400 bg-slate-50 px-4 py-6 text-center transition-colors focus-within:outline focus-within:outline-2 focus-within:outline-offset-2 hover:border-slate-500 hover:bg-slate-100",+ isDraggingFile && "border-slate-700 bg-slate-200/70",)}>- <FileUp className="mb-1 size-5 text-slate-500" aria-hidden />+ <FileUp className="mb-1 size-5 text-slate-700" aria-hidden /><span className="text-sm font-medium text-slate-900">Drop a .json file here</span>- <span className="text-sm text-slate-500">+ <span className="text-sm text-slate-700">or <span className="underline underline-offset-2">choose a file</span></span></FilePickerLabel>@@ -337,6 +345,31 @@ function PreviewStep({? "Nothing can be imported": "Nothing new to import";+ const countByTab = {+ add: addedCount,+ problems: problemCount,+ saved: duplicateCount,+ } satisfies Record<PreviewTabValue, number>;++ // only outcomes the file has get a tab, in the order they matter+ const tabs = PREVIEW_TABS.filter(({ value }) => {+ return countByTab[value] > 0;+ });++ const [selectedTab, setSelectedTab] = useState<PreviewTabValue>("add");++ // a file without the selected outcome opens on its first+ const activeTab = tabs.some(({ value }) => {+ return value === selectedTab;+ })+ ? selectedTab+ : (tabs[0]?.value ?? "add");++ function selectTab(value: PreviewTabValue) {+ setSelectedTab(value);+ umamiTrackEvent("import_contacts_tab_changed", { data: { tab: value } });+ }+return (<><DialogHeader className="text-left">@@ -344,35 +377,74 @@ function PreviewStep({<DialogDescription className="break-all">{fileName}</DialogDescription></DialogHeader>- <dl className="grid grid-cols-3 gap-2">- <PreviewStat label="to add" count={addedCount} />- <PreviewStat label="already saved" count={duplicateCount} />- <PreviewStat- label="can’t import"- count={problemCount}- isProblem={problemCount > 0}- />- </dl>-- {problemCount > 0 ? (- <p className="text-pretty text-sm text-slate-600">- {addedCount > 0- ? "Fix the highlighted fields in the file and import it again, or import the rest now."- : "Fix the highlighted fields in the file and import it again."}- {nameConflictCount > 0- ? " For a name that’s already saved, rename it in the file or rename the saved one."- : null}- </p>- ) : null}-- <div className="-mx-6 min-h-0 flex-1 space-y-4 overflow-y-auto px-6">- <PartyPreview party="Sellers" result={sellers} />- <PartyPreview party="Buyers" result={buyers} />- </div>+ {tabs.length > 1 ? (+ <Tabs+ value={activeTab}+ onValueChange={(value) => {+ selectTab(value as PreviewTabValue);+ }}+ className="min-h-0 flex-1 gap-3"+ >+ <TabsList className="h-auto w-full justify-start gap-1 rounded-none border-b border-slate-200 bg-transparent p-0">+ {tabs.map(({ value, label }) => {+ return (+ <TabsTrigger+ key={value}+ value={value}+ className="-mb-px gap-1.5 rounded-none border-b-2 border-transparent px-2.5 py-2 font-normal text-slate-500 hover:bg-transparent data-[state=active]:border-slate-900 data-[state=active]:bg-transparent data-[state=active]:font-medium data-[state=active]:text-slate-900 data-[state=active]:shadow-none"+ >+ {label}+ <span+ className={cn(+ "inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-slate-100 px-1.5 text-xs tabular-nums text-slate-600",+ value === "problems" && "bg-red-100 text-red-700",+ )}+ >+ {countByTab[value]}+ </span>+ </TabsTrigger>+ );+ })}+ </TabsList>+ <TabsContent+ value={activeTab}+ className="-mx-6 min-h-0 overflow-y-auto px-6"+ >+ <PreviewTabPanel+ tab={activeTab}+ sellers={sellers}+ buyers={buyers}+ hasAddedEntries={addedCount > 0}+ hasNameConflicts={nameConflictCount > 0}+ />+ </TabsContent>+ </Tabs>+ ) : (+ <div className="-mx-6 min-h-0 flex-1 overflow-y-auto px-6">+ <PreviewTabPanel+ tab={activeTab}+ sellers={sellers}+ buyers={buyers}+ hasAddedEntries={addedCount > 0}+ hasNameConflicts={nameConflictCount > 0}+ />+ </div>+ )}<DialogFooter>{addedCount > 0 ? (<>+ {problemCount > 0 && activeTab !== "problems" ? (+ <button+ type="button"+ className="self-center text-sm text-slate-600 underline-offset-2 hover:text-slate-900 hover:underline sm:mr-auto"+ onClick={() => {+ selectTab("problems");+ }}+ >+ {problemCount} can’t be imported+ </button>+ ) : null}<DialogClose asChild><Button variant="outline" size="sm">Cancel@@ -409,94 +481,125 @@ function PreviewStep({);}-interface PreviewStatProps {- label: string;- count: number;- /** Highlights the count in red. */- isProblem?: boolean;+interface PreviewTabPanelProps {+ tab: PreviewTabValue;+ sellers: MergeImportedContactsResult<SellerData>;+ buyers: MergeImportedContactsResult<BuyerData>;+ /** Some entries can be imported, so the advice offers to import the rest now. */+ hasAddedEntries: boolean;+ hasNameConflicts: boolean;}-function PreviewStat({ label, count, isProblem = false }: PreviewStatProps) {+/**+ * The entries with one outcome, as a Sellers list and a Buyers list; a party with none is+ * left out. Problem rows are opened, so what to fix shows straight away.+ */+function PreviewTabPanel({+ tab,+ sellers,+ buyers,+ hasAddedEntries,+ hasNameConflicts,+}: PreviewTabPanelProps) {+ const parties = [+ { party: "Sellers", result: sellers },+ { party: "Buyers", result: buyers },+ ] as const;++ if (tab === "problems") {+ return (+ <div className="space-y-4">+ <p className="text-pretty text-sm text-slate-600">+ {hasAddedEntries+ ? "Fix the highlighted fields in the file and import it again, or import the rest now."+ : "Fix the highlighted fields in the file and import it again."}+ {hasNameConflicts+ ? " For a name that’s already saved, rename it in the file or rename the saved one."+ : null}+ </p>+ {parties.map(({ party, result }) => {+ return (+ <PartyList+ key={party}+ party={party}+ count={result.invalidEntries.length + result.nameConflicts.length}+ >+ {result.invalidEntries.map((invalidEntry, index) => {+ return (+ <ProblemRow+ key={`invalid-${index}`}+ invalidEntry={invalidEntry}+ badge={+ invalidEntry.issues.length === 1+ ? "1 problem"+ : `${invalidEntry.issues.length} problems`+ }+ />+ );+ })}+ {result.nameConflicts.map((invalidEntry, index) => {+ return (+ <ProblemRow+ key={`conflict-${index}`}+ invalidEntry={invalidEntry}+ badge="Name taken"+ />+ );+ })}+ </PartyList>+ );+ })}+ </div>+ );+ }++ const isSaved = tab === "saved";+return (- <div- className={cn(- "flex flex-col-reverse rounded-lg bg-slate-50 px-3 py-2",- isProblem && "bg-red-50 text-red-700",- )}- >- <dt className={cn("text-xs text-slate-500", isProblem && "text-red-700")}>- {label}- </dt>- <dd className="text-lg font-semibold tabular-nums">{count}</dd>+ <div className="space-y-4">+ {parties.map(({ party, result }) => {+ const contacts = isSaved ? result.duplicates : result.added;++ return (+ <PartyList key={party} party={party} count={contacts.length}>+ {contacts.map((contact, index) => {+ return (+ <PreviewRow key={index} contact={contact} isMuted={isSaved} />+ );+ })}+ </PartyList>+ );+ })}</div>);}-interface PartyPreviewProps {+interface PartyListProps {party: "Sellers" | "Buyers";- result: MergeImportedContactsResult<SellerData | BuyerData>;+ /** How many of the party's entries the list holds; with none, nothing is rendered. */+ count: number;+ children: React.ReactNode;}-/**- * One party's entries from the file: the new ones first, then the ones that cannot be- * imported (opened, so their problems show), then the ones already saved.- */-function PartyPreview({ party, result }: PartyPreviewProps) {- const { added, duplicates, invalidEntries, nameConflicts } = result;-- if (- added.length +- duplicates.length +- invalidEntries.length +- nameConflicts.length ===- 0- ) {+function PartyList({ party, count, children }: PartyListProps) {+ if (count === 0) {return null;}return (<section>- <h3 className="mb-1.5 text-xs font-medium text-slate-500">{party}</h3>+ <h3 className="mb-1.5 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-slate-500">+ {party}+ {/* the same badge as the tab counts */}+ <span className="inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-slate-100 px-1.5 text-xs font-medium normal-case tabular-nums tracking-normal text-slate-600">+ {count}+ </span>+ </h3><ulclassName="divide-y divide-slate-200 overflow-hidden rounded-lg border border-slate-200 text-sm"aria-label={party}>- {added.map((contact, index) => {- return (- <PreviewRow key={`added-${index}`} contact={contact}>- <StatusBadge tone="success">New</StatusBadge>- </PreviewRow>- );- })}- {invalidEntries.map((invalidEntry, index) => {- return (- <ProblemRow- key={`invalid-${index}`}- invalidEntry={invalidEntry}- badge={- invalidEntry.issues.length === 1- ? "1 problem"- : `${invalidEntry.issues.length} problems`- }- />- );- })}- {nameConflicts.map((invalidEntry, index) => {- return (- <ProblemRow- key={`conflict-${index}`}- invalidEntry={invalidEntry}- badge="Name taken"- />- );- })}- {duplicates.map((contact, index) => {- return (- <PreviewRow key={`duplicate-${index}`} contact={contact} isMuted>- <StatusBadge tone="neutral">Already saved</StatusBadge>- </PreviewRow>- );- })}+ {children}</ul></section>);@@ -506,15 +609,13 @@ interface PreviewRowProps {contact: SellerData | BuyerData;/** For entries that will be skipped. */isMuted?: boolean;- /** The status badge. */- children: React.ReactNode;}/*** Collapsed to the name and address by default; expanding it lists every other field the* entry has, so the user can check the details before importing.*/-function PreviewRow({ contact, isMuted = false, children }: PreviewRowProps) {+function PreviewRow({ contact, isMuted = false }: PreviewRowProps) {return (<li className={cn(isMuted && "text-slate-500")}><details@@ -533,13 +634,10 @@ function PreviewRow({ contact, isMuted = false, children }: PreviewRowProps) {<ContactName name={contact.name} /><ContactAddress address={contact.address} /></div>- <span className="flex shrink-0 items-center gap-1.5">- {children}- <ChevronDown- className="size-3.5 text-slate-500 transition-transform group-open:rotate-180"- aria-hidden- />- </span>+ <ChevronDown+ className="mt-1 size-3.5 shrink-0 text-slate-500 transition-transform group-open:rotate-180"+ aria-hidden+ /></summary><ContactFields contact={contact} />@@ -548,38 +646,6 @@ function PreviewRow({ contact, isMuted = false, children }: PreviewRowProps) {);}-interface ContactFieldsProps {- contact: SellerData | BuyerData;-}--/** Every filled-in field of the entry, with the ones hidden on the invoice marked so. */-function ContactFields({ contact }: ContactFieldsProps) {- const fields = getContactFields(contact);-- return (- <dl className="space-y-1.5 border-t border-slate-200 bg-slate-50/60 px-3 py-2 text-xs">- {fields.map(({ field, label, value, isHidden }) => {- return (- <div- key={field}- className="grid grid-cols-[7rem_minmax(0,1fr)] gap-2"- >- <dt className="text-slate-500">{label}</dt>- <dd className="whitespace-pre-line break-words text-slate-700">- {value}- {isHidden ? (- <span className="ml-1.5 text-slate-400">- (hidden on invoice)- </span>- ) : null}- </dd>- </div>- );- })}- </dl>- );-}-interface ContactNameProps {name: string;}@@ -628,7 +694,7 @@ function ProblemRow({ invalidEntry, badge }: ProblemRowProps) {{address ? <ContactAddress address={address} /> : null}</div><span className="flex shrink-0 items-center gap-1.5">- <StatusBadge tone="danger">{badge}</StatusBadge>+ <StatusBadge>{badge}</StatusBadge><ChevronDownclassName="size-3.5 text-slate-500 transition-transform group-open:rotate-180"aria-hidden@@ -653,19 +719,14 @@ function ProblemRow({ invalidEntry, badge }: ProblemRowProps) {}interface StatusBadgeProps {- tone: "success" | "neutral" | "danger";children: React.ReactNode;}-function StatusBadge({ tone, children }: StatusBadgeProps) {+/** What is wrong with an entry that cannot be imported. */+function StatusBadge({ children }: StatusBadgeProps) {return (<span- className={cn(- "shrink-0 whitespace-nowrap rounded-full px-2 py-0.5 text-xs font-medium",- tone === "success" && "bg-green-200/80 text-green-900",- tone === "neutral" && "bg-slate-100 text-slate-600",- tone === "danger" && "bg-red-200/80 text-red-900",- )}+ className="shrink-0 whitespace-nowrap rounded-full bg-red-200/80 px-2 py-0.5 text-xs font-medium text-red-900"data-testid="import-export-status-badge">{children}@@ -831,83 +892,6 @@ function EntryLine({ field, value, messages }: EntryLineProps) {);}-interface ContactField {- /** The schema key, used as the React key: labels can repeat, as the tax label is user-set. */- field: keyof SellerData;- label: string;- value: string;- /** The entry has the value but does not show it on the invoice. */- isHidden: boolean;-}--function getContactFields(contact: SellerData | BuyerData): ContactField[] {- const fields: (ContactField | null)[] = [- { field: "name", label: "Name", value: contact.name, isHidden: false },- {- field: "address",- label: "Address",- value: contact.address,- isHidden: false,- },- optionalField({- field: "vatNo",- label: contact.vatNoLabelText,- value: contact.vatNo,- isVisible: contact.vatNoFieldIsVisible,- }),- optionalField({- field: "email",- label: "Email",- value: contact.email,- isVisible: contact.emailFieldIsVisible,- }),- "accountNumber" in contact- ? optionalField({- field: "accountNumber",- label: "Account Number",- value: contact.accountNumber,- isVisible: contact.accountNumberFieldIsVisible,- })- : null,- "swiftBic" in contact- ? optionalField({- field: "swiftBic",- label: "SWIFT/BIC",- value: contact.swiftBic,- isVisible: contact.swiftBicFieldIsVisible,- })- : null,- optionalField({- field: "notes",- label: "Notes",- value: contact.notes,- isVisible: contact.notesFieldIsVisible,- }),- ];-- return fields.filter((field) => {- return field !== null;- });-}--interface OptionalFieldOptions {- field: ContactField["field"];- label: string;- /** Left out of the list when empty. */- value: string | undefined;- /** The entry's `…FieldIsVisible` flag for this field. */- isVisible: boolean;-}--function optionalField({- field,- label,- value,- isVisible,-}: OptionalFieldOptions): ContactField | null {- return value ? { field, label, value, isHidden: !isVisible } : null;-}-function formatValue(value: unknown): string {const text = JSON.stringify(value) ?? String(value);@@ -968,3 +952,11 @@ const EXPECTED_FILE_EXAMPLE = `{}]}`;++type PreviewTabValue = "add" | "problems" | "saved";++const PREVIEW_TABS = [+ { value: "add", label: "To add" },+ { value: "problems", label: "Can’t import" },+ { value: "saved", label: "Already saved" },+] as const satisfies readonly { value: PreviewTabValue; label: string }[];diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/party-dialog-fields.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/party-dialog-fields.tsxnew file mode 100644index 0000000..c5c885f--- /dev/null+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/party-dialog-fields.tsx@@ -0,0 +1,93 @@+import { useId } from "react";++import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";++interface PartyDialogSectionProps {+ title: string;+ /** Sits at the end of the heading row, e.g. the tax number's PDF toggle. */+ action?: React.ReactNode;+ children: React.ReactNode;+}++/** A titled group of fields in the seller or buyer dialog, divided from the one above it. */+export function PartyDialogSection({+ title,+ action,+ children,+}: PartyDialogSectionProps) {+ const headingId = useId();++ return (+ <section+ aria-labelledby={headingId}+ className="space-y-3 border-t border-slate-200 pt-4 first:border-t-0 first:pt-0"+ >+ <div className="flex min-h-[22px] items-center justify-between gap-2">+ <h3+ id={headingId}+ className="text-xs font-semibold uppercase tracking-wide text-slate-500"+ >+ {title}+ </h3>+ {action}+ </div>+ {children}+ </section>+ );+}++interface PdfVisibilityToggleProps {+ id: string;+ /** The field is printed on the invoice. */+ checked: boolean;+ onCheckedChange: (checked: boolean) => void;+ /** The field's name as the accessible name says it, e.g. `Email`. */+ fieldLabel: string;+ "data-testid"?: string;+}++/** Whether a field is printed: the same small "Show in PDF" switch as the invoice form. */+export function PdfVisibilityToggle({+ id,+ checked,+ onCheckedChange,+ fieldLabel,+ "data-testid": dataTestId,+}: PdfVisibilityToggleProps) {+ return (+ <div className="inline-flex shrink-0 items-center gap-2">+ <Switch+ id={id}+ checked={checked}+ onCheckedChange={onCheckedChange}+ size="sm"+ aria-label={`Show the '${fieldLabel}' field in the PDF`}+ data-testid={dataTestId}+ />+ <Label htmlFor={id} className="cursor-pointer">+ Show in PDF+ </Label>+ </div>+ );+}++interface GetPartyFieldClassNameOptions {+ /** The field is left out of the PDF. */+ isHidden?: boolean;+ /** The field was filled in from the invoice and not changed since. */+ isPrefilled?: boolean;+}++/** Fades fields the PDF leaves out, and tints the ones copied from the invoice. */+export function getPartyFieldClassName({+ isHidden = false,+ isPrefilled = false,+}: GetPartyFieldClassNameOptions) {+ // a hidden field is not printed, so whether it was copied matters less than that+ if (isHidden) {+ return "border-dashed bg-slate-50 text-slate-500";+ }++ return isPrefilled ? "border-green-300 bg-green-50/70" : "";+}diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-dialog.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-dialog.tsxindex 7a947d2..479800f 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-dialog.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-dialog.tsx@@ -1,8 +1,13 @@import * as Sentry from "@sentry/nextjs";import { useState } from "react";-import { useForm } from "react-hook-form";+import { useForm, useWatch } from "react-hook-form";import { toast } from "sonner";+import {+ getPartyFieldClassName,+ PartyDialogSection,+ PdfVisibilityToggle,+} from "@/app/(main)/(app)/components/invoice-form/sections/components/party-dialog-fields";import { useConfirmDiscard } from "@/app/(main)/(app)/components/invoice-form/sections/hooks/use-confirm-discard";import {getAppStorageItem,@@ -31,11 +36,9 @@ import {FormMessage,} from "@/components/ui/form";import { Input } from "@/components/ui/input";-import { InputHelperMessage } from "@/components/ui/input-helper-message";import { Label } from "@/components/ui/label";import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";-import { CustomTooltip } from "@/components/ui/tooltip";import { zodResolverForOutput } from "@/lib/zod-resolver-for-output";import { ConfirmDiscardDialog } from "../confirm-discard-dialog";@@ -71,6 +74,8 @@ interface SellerDialogProps {) => void;handleSellerEdit?: (seller: SellerData) => void;initialData: SellerData | null;+ /** The tax number label a new seller starts with: the invoice language's, as in the form. */+ defaultVatNoLabelText: string;isEditMode: boolean;formValues?: Partial<SellerData>;}@@ -97,6 +102,7 @@ export function SellerDialog({handleSellerAdd,handleSellerEdit,initialData,+ defaultVatNoLabelText,isEditMode,formValues,}: SellerDialogProps) {@@ -107,7 +113,7 @@ export function SellerDialog({name: initialData?.name ?? "",address: initialData?.address ?? "",vatNo: initialData?.vatNo ?? "",- vatNoLabelText: initialData?.vatNoLabelText ?? "VAT no",+ vatNoLabelText: initialData?.vatNoLabelText ?? defaultVatNoLabelText,email: initialData?.email ?? "",emailFieldIsVisible: initialData?.emailFieldIsVisible ?? true,accountNumber: initialData?.accountNumber ?? "",@@ -121,7 +127,25 @@ export function SellerDialog({},});- const { isDirty } = form.formState;+ const { isDirty, dirtyFields } = form.formState;++ // hidden fields are faded in the dialog, as they will be missing from the PDF+ const [+ isVatNoVisible,+ isEmailVisible,+ isAccountNumberVisible,+ isSwiftBicVisible,+ isNotesVisible,+ ] = useWatch({+ control: form.control,+ name: [+ "vatNoFieldIsVisible",+ "emailFieldIsVisible",+ "accountNumberFieldIsVisible",+ "swiftBicFieldIsVisible",+ "notesFieldIsVisible",+ ],+ });const { isConfirmDiscardDialogOpen, setIsConfirmDiscardDialogOpen } =useConfirmDiscard();@@ -143,6 +167,11 @@ export function SellerDialog({(() => void) | null>(null);+ /** Filled in from the invoice and not changed since, so it is tinted as copied. */+ function isPrefilled({ name, value }: IsPrefilledOptions) {+ return shouldApplyInlineFormValues && !dirtyFields[name] && Boolean(value);+ }+/*** Resets the dialog form to the seller it was opened with, or to an empty* form when adding a new one.@@ -152,7 +181,12 @@ export function SellerDialog({* pre-fill it would restore the pre-filled values instead of clearing them.*/function resetFormToInitialValues() {- form.reset(initialData ?? EMPTY_SELLER_FORM_VALUES);+ form.reset(+ initialData ?? {+ ...EMPTY_SELLER_FORM_VALUES,+ vatNoLabelText: defaultVatNoLabelText,+ },+ );}/**@@ -337,125 +371,128 @@ export function SellerDialog({><DialogHeader className="border-b border-slate-200 px-6 py-4 dark:border-slate-800"><DialogTitle className="text-base">- {isEditMode ? "Edit Seller" : "Add New Seller"}+ {isEditMode ? "Edit seller" : "New seller"}</DialogTitle><DialogDescription>{isEditMode- ? "Edit the seller details"- : "Add a new seller to use later in your invoices"}+ ? "Changes apply to every invoice that uses this seller."+ : "Saved in this browser, ready to pick on any invoice."}</DialogDescription></DialogHeader><div className="overflow-y-auto px-6 py-4">{/* Show Use Current Form Values switch only when creating new seller */}{!isEditMode ? (- <div className="mb-4">- <div className="flex items-center gap-2">- <Switch- checked={shouldApplyInlineFormValues}- onCheckedChange={handlePrefillSwitchToggle}- id="apply-form-values-switch"- />+ <div className="mb-4 flex items-center gap-3 rounded-lg bg-neutral-100 px-4 py-3">+ <Switch+ checked={shouldApplyInlineFormValues}+ onCheckedChange={handlePrefillSwitchToggle}+ id="apply-form-values-switch"+ aria-describedby="apply-form-values-description"+ // the default track is too pale to read as "off" on the grey strip+ className="shrink-0 data-[state=unchecked]:bg-slate-300"+ />+ <div><LabelhtmlFor="apply-form-values-switch"- className="cursor-pointer"+ className="cursor-pointer text-sm font-semibold text-slate-900">- Pre-fill with values from the current invoice form+ Fill in from this invoice</Label>+ <p+ id="apply-form-values-description"+ className="mt-0.5 text-pretty text-sm text-slate-600"+ >+ Copies the seller you typed into the invoice. You can still+ change it here.+ </p></div>- <span className="mt-1.5 inline-block text-xs text-slate-500">- When enabled, this will automatically fill in the seller- details dialog with the information you've already- entered in your current invoice form.- </span></div>) : null}<Form {...form}><formonSubmit={form.handleSubmit(onSubmit)}- className="space-y-4"+ className="space-y-5"id={SELLER_FORM_ID}>- <FormField- control={form.control}- name="name"- render={({ field }) => {- return (- <FormItem>- <FormLabel>Name (Required)</FormLabel>- <FormControl>- <Textarea- {...field}- rows={3}- placeholder="Enter seller name"- />- </FormControl>- <FormMessage />- </FormItem>- );- }}- />+ <PartyDialogSection title="Business">+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => {+ return (+ <FormItem>+ <FormLabel>Name (Required)</FormLabel>+ <FormControl>+ <Textarea+ {...field}+ rows={2}+ placeholder="Enter seller name"+ className={getPartyFieldClassName({+ isPrefilled: isPrefilled({+ name: "name",+ value: field.value,+ }),+ })}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ );+ }}+ />+ <FormField+ control={form.control}+ name="address"+ render={({ field }) => {+ return (+ <FormItem>+ <FormLabel>Address (Required)</FormLabel>+ <FormControl>+ <Textarea+ {...field}+ rows={2}+ placeholder="Enter seller address"+ className={getPartyFieldClassName({+ isPrefilled: isPrefilled({+ name: "address",+ value: field.value,+ }),+ })}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ );+ }}+ />+ </PartyDialogSection>- <FormField- control={form.control}- name="address"- render={({ field }) => {- return (- <FormItem>- <FormLabel>Address (Required)</FormLabel>- <FormControl>- <Textarea- {...field}- rows={3}- placeholder="Enter seller address"+ <PartyDialogSection+ title="Tax number"+ action={+ <FormField+ control={form.control}+ name="vatNoFieldIsVisible"+ render={({ field }) => {+ return (+ <PdfVisibilityToggle+ id="vatNoFieldIsVisible"+ checked={field.value}+ onCheckedChange={field.onChange}+ fieldLabel="Tax Number"/>- </FormControl>- <FormMessage />- </FormItem>- );- }}- />-- <fieldset className="rounded-md border px-4 pb-4">- <legend className="text-base font-semibold lg:text-lg">- Seller Tax Number- </legend>-- <div className="mb-2 flex items-center justify-end">- {/* Show Tax Number Field in PDF */}- <div className="flex items-center gap-2">- <FormField- control={form.control}- name="vatNoFieldIsVisible"- render={({ field }) => {- return (- <FormItem>- <div className="flex items-center gap-2">- <Switch- checked={field.value}- onCheckedChange={field.onChange}- id="vatNoFieldIsVisible"- aria-label={`Show the 'Tax Number' field in the PDF`}- />- <CustomTooltip- trigger={- <Label htmlFor="vatNoFieldIsVisible">- Show in PDF- </Label>- }- content='Show the "Tax Number" field in the PDF'- className="z-[1000]"- />- </div>- </FormItem>- );- }}- />- </div>- </div>-- <div className="space-y-4">+ );+ }}+ />+ }+ >+ {/* a label of its own, so the PDF can say "VAT no", "Tax ID", ... */}+ <fieldset+ aria-label="Seller tax number"+ className="grid min-w-0 grid-cols-[7rem_minmax(0,1fr)] gap-3"+ ><FormFieldcontrol={form.control}name="vatNoLabelText"@@ -466,36 +503,39 @@ export function SellerDialog({<FormControl><Input{...field}- placeholder="Enter Tax number label"+ placeholder="e.g. VAT no"+ className={getPartyFieldClassName({+ isHidden: !isVatNoVisible,+ isPrefilled: isPrefilled({+ name: "vatNoLabelText",+ value: field.value,+ }),+ })}/></FormControl>- {form.formState.errors.vatNoLabelText ? (- <FormMessage>- {form.formState.errors.vatNoLabelText.message}- </FormMessage>- ) : null}-- {!form.formState.errors.vatNoLabelText ? (- <InputHelperMessage>- Set a custom label (e.g. VAT no, Tax no, etc.)- </InputHelperMessage>- ) : null}+ <FormMessage /></FormItem>);}}/>-<FormFieldcontrol={form.control}name="vatNo"render={({ field }) => {return (<FormItem>- <FormLabel>Value</FormLabel>+ <FormLabel>Number</FormLabel><FormControl><Input{...field}- placeholder="Enter Tax number value"+ placeholder="e.g. PL1234567890"+ className={getPartyFieldClassName({+ isHidden: !isVatNoVisible,+ isPrefilled: isPrefilled({+ name: "vatNo",+ value: field.value,+ }),+ })}/></FormControl><FormMessage />@@ -503,25 +543,46 @@ export function SellerDialog({);}}/>- </div>- </fieldset>+ </fieldset>+ </PartyDialogSection>- {/* Email */}- <div className="space-y-3 rounded-md border p-4">+ <PartyDialogSection title="Contact & payment"><FormFieldcontrol={form.control}name="email"render={({ field }) => {return (<FormItem>- <FormLabel className="mb-2 font-medium">- </FormLabel>+ <div className="flex items-center justify-between gap-2">+ <FormLabel>Email</FormLabel>+ <FormField+ control={form.control}+ name="emailFieldIsVisible"+ render={({ field: visibilityField }) => {+ return (+ <PdfVisibilityToggle+ id="emailFieldIsVisible"+ checked={visibilityField.value}+ onCheckedChange={visibilityField.onChange}+ fieldLabel="Email"+ data-testid="sellerEmailDialogFieldVisibilitySwitch"+ />+ );+ }}+ />+ </div><FormControl><Input{...field}type="email"placeholder="[email protected]"+ className={getPartyFieldClassName({+ isHidden: !isEmailVisible,+ isPrefilled: isPrefilled({+ name: "email",+ value: field.value,+ }),+ })}/></FormControl><FormMessage />@@ -531,51 +592,39 @@ export function SellerDialog({/><FormFieldcontrol={form.control}- name="emailFieldIsVisible"+ name="accountNumber"render={({ field }) => {return (<FormItem>- <div className="flex items-center gap-2">- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- id="emailFieldIsVisible"- data-testid={`sellerEmailDialogFieldVisibilitySwitch`}- />- </FormControl>- <CustomTooltip- trigger={- <Label htmlFor="emailFieldIsVisible">- Show Seller Email in PDF- </Label>- }- content='Show the "Email" field in the PDF'- className="z-[1000]"+ <div className="flex items-center justify-between gap-2">+ <FormLabel>Account Number</FormLabel>+ <FormField+ control={form.control}+ name="accountNumberFieldIsVisible"+ render={({ field: visibilityField }) => {+ return (+ <PdfVisibilityToggle+ id="accountNumberFieldIsVisible"+ checked={visibilityField.value}+ onCheckedChange={visibilityField.onChange}+ fieldLabel="Account Number"+ />+ );+ }}/></div>- </FormItem>- );- }}- />- </div>-- {/* Account Number */}- <div className="space-y-3 rounded-md border p-4">- <FormField- control={form.control}- name="accountNumber"- render={({ field }) => {- return (- <FormItem>- <FormLabel className="mb-2 font-medium">- Account Number- </FormLabel><FormControl><Textarea{...field}- rows={3}+ rows={2}placeholder="Enter account number"+ className={getPartyFieldClassName({+ isHidden: !isAccountNumberVisible,+ isPrefilled: isPrefilled({+ name: "accountNumber",+ value: field.value,+ }),+ })}/></FormControl><FormMessage />@@ -585,48 +634,39 @@ export function SellerDialog({/><FormFieldcontrol={form.control}- name="accountNumberFieldIsVisible"+ name="swiftBic"render={({ field }) => {return (<FormItem>- <div className="flex items-center gap-2">- <Switch- checked={field.value}- onCheckedChange={field.onChange}- id="accountNumberFieldIsVisible"- />- <CustomTooltip- trigger={- <Label htmlFor="accountNumberFieldIsVisible">- Show Seller Account Number in PDF- </Label>- }- content='Show the "Account Number" field in the PDF'- className="z-[1000]"+ <div className="flex items-center justify-between gap-2">+ <FormLabel>SWIFT/BIC</FormLabel>+ <FormField+ control={form.control}+ name="swiftBicFieldIsVisible"+ render={({ field: visibilityField }) => {+ return (+ <PdfVisibilityToggle+ id="swiftBicFieldIsVisible"+ checked={visibilityField.value}+ onCheckedChange={visibilityField.onChange}+ fieldLabel="SWIFT/BIC"+ />+ );+ }}/></div>- </FormItem>- );- }}- />- </div>-- {/* SWIFT/BIC */}- <div className="space-y-3 rounded-md border p-4">- <FormField- control={form.control}- name="swiftBic"- render={({ field }) => {- return (- <FormItem>- <FormLabel className="mb-2 font-medium">- SWIFT/BIC- </FormLabel><FormControl><Textarea{...field}- rows={3}+ rows={2}placeholder="Enter SWIFT/BIC code"+ className={getPartyFieldClassName({+ isHidden: !isSwiftBicVisible,+ isPrefilled: isPrefilled({+ name: "swiftBic",+ value: field.value,+ }),+ })}/></FormControl><FormMessage />@@ -634,51 +674,49 @@ export function SellerDialog({);}}/>- <FormField- control={form.control}- name="swiftBicFieldIsVisible"- render={({ field }) => {- return (- <FormItem>- <div className="flex items-center gap-2">- <Switch- checked={field.value}- onCheckedChange={field.onChange}- id="swiftBicFieldIsVisible"- />- <CustomTooltip- trigger={- <Label htmlFor="swiftBicFieldIsVisible">- Show Seller SWIFT/BIC in PDF- </Label>- }- content='Show the "SWIFT/BIC" field in the PDF'- className="z-[1000]"- />- </div>- </FormItem>- );- }}- />- </div>+ </PartyDialogSection>- {/* Notes */}- <div className="space-y-3 rounded-md border p-4">+ <PartyDialogSection+ title="Notes"+ action={+ <FormField+ control={form.control}+ name="notesFieldIsVisible"+ render={({ field }) => {+ return (+ <PdfVisibilityToggle+ id="notes-field-visibility"+ checked={field.value}+ onCheckedChange={field.onChange}+ fieldLabel="Notes"+ data-testid="sellerNotesDialogFieldVisibilitySwitch"+ />+ );+ }}+ />+ }+ ><FormFieldcontrol={form.control}name="notes"render={({ field }) => {return (<FormItem>- <FormLabel className="mb-2 font-medium">- Notes- </FormLabel>+ {/* the section heading says it already */}+ <FormLabel className="sr-only">Notes</FormLabel><FormControl><Textarea{...field}- rows={3}+ rows={2}placeholder="Enter notes (max 750 characters)"maxLength={750}+ className={getPartyFieldClassName({+ isHidden: !isNotesVisible,+ isPrefilled: isPrefilled({+ name: "notes",+ value: field.value,+ }),+ })}/></FormControl><FormMessage />@@ -686,94 +724,79 @@ export function SellerDialog({);}}/>- <FormField- control={form.control}- name="notesFieldIsVisible"- render={({ field }) => {- return (- <FormItem>- <div className="flex items-center gap-2">- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- id="notes-field-visibility"- data-testid={`sellerNotesDialogFieldVisibilitySwitch`}- />- </FormControl>- <CustomTooltip- trigger={- <Label htmlFor="notes-field-visibility">- Show Seller Notes in PDF- </Label>- }- content="Show the notes field in the PDF"- className="z-[1000]"- />- </div>- </FormItem>- );- }}- />- </div>+ </PartyDialogSection></form></Form>-- {/* Apply to Current Invoice switch remains at the bottom */}+ </div>+ <DialogFooter className="border-border gap-3 border-t px-6 py-4 sm:items-center sm:justify-between">+ {/* where the choice is made: next to Save, rather than at the end of the form */}{!isEditMode ? (- <div className="mt-4 flex flex-col gap-1 border-t pt-4">+ <div><div className="flex items-center gap-2">- <Switch- checked={shouldApplyNewSellerToInvoice}- onCheckedChange={setShouldApplyNewSellerToInvoice}+ <input+ type="checkbox"id="apply-seller-to-current-invoice-switch"+ checked={shouldApplyNewSellerToInvoice}+ onChange={(event) => {+ setShouldApplyNewSellerToInvoice(event.target.checked);+ }}+ aria-describedby="apply-seller-to-current-invoice-description"+ className="size-4 cursor-pointer accent-slate-900"/>+<LabelhtmlFor="apply-seller-to-current-invoice-switch"- className="cursor-pointer"+ className="cursor-pointer font-normal">- Apply to Current Invoice+ Use on this invoice</Label></div>- <span className="mt-1.5 text-xs text-slate-500">- When enabled, the newly created seller will be automatically- applied to your current invoice form and reflected in the- generated PDF.- </span>++ {/* says what Save will do with the current choice */}+ <p+ id="apply-seller-to-current-invoice-description"+ className="ml-6 mt-0.5 max-w-64 text-pretty text-xs text-slate-500"+ >+ {shouldApplyNewSellerToInvoice+ ? "Replaces the seller on this invoice with this one."+ : "Only saved to your list. This invoice keeps its seller."}+ </p></div>- ) : null}- </div>- <DialogFooter className="border-border border-t px-6 py-4">- <Button- type="button"- variant="outline"- onClick={() => {- // check if the form has unsaved changes and open the confirm discard dialog- // If there are unsaved changes (isDirty), opens the confirmation dialog.- // Otherwise, closes the dialog immediately.- if (isDirty) {- setPendingDiscardAction(() => {- return closeDialog;- });- setIsConfirmDiscardDialogOpen(true);- return;- }- closeDialog();- }}- >- Cancel- </Button>- <Button- // we don't want to use type="submit" because it will cause unnecessary re-render of the invoice pdf preview- type="button"- onClick={async () => {- // trigger validations and submit the form- void form.handleSubmit(onSubmit)();- }}- form={SELLER_FORM_ID}- >- Save Seller- </Button>+ ) : (+ <span aria-hidden />+ )}+ <div className="flex flex-col-reverse gap-2 sm:flex-row">+ <Button+ type="button"+ variant="outline"+ onClick={() => {+ // check if the form has unsaved changes and open the confirm discard dialog+ // If there are unsaved changes (isDirty), opens the confirmation dialog.+ // Otherwise, closes the dialog immediately.+ if (isDirty) {+ setPendingDiscardAction(() => {+ return closeDialog;+ });+ setIsConfirmDiscardDialogOpen(true);+ return;+ }+ closeDialog();+ }}+ >+ Cancel+ </Button>+ <Button+ // we don't want to use type="submit" because it will cause unnecessary re-render of the invoice pdf preview+ type="button"+ onClick={async () => {+ // trigger validations and submit the form+ void form.handleSubmit(onSubmit)();+ }}+ form={SELLER_FORM_ID}+ >+ Save seller+ </Button>+ </div></DialogFooter></DialogContent></Dialog>@@ -789,3 +812,8 @@ export function SellerDialog({</>);}++interface IsPrefilledOptions {+ name: keyof SellerData;+ value: unknown;+}diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-management.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-management.tsxindex 71e267c..defba4c 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-management.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-management.tsx@@ -7,6 +7,7 @@ import { ContactsBackupMenu } from "@/app/(main)/(app)/components/invoice-form/simport { SellerDialog } from "@/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-dialog";import { usePartyActions } from "@/app/(main)/(app)/components/invoice-form/sections/hooks/use-party-actions";import { useSavedParties } from "@/app/(main)/(app)/components/invoice-form/sections/hooks/use-saved-parties";+import { INVOICE_PDF_TRANSLATIONS } from "@/app/(main)/(app)/pdf-i18n-translations/pdf-translations";import { type InvoiceData, type SellerData } from "@/app/schema";import {AlertDialog,@@ -262,8 +263,9 @@ export function SellerManagement({</div><SellerDialog- // we need to rerender the dialog when the editingSeller changes- key={editingSeller?.id}+ // remount for another seller to edit, and after a language change, so a new+ // seller starts with that language's tax label (the form only reads its defaults once)+ key={`${editingSeller?.id ?? "new"}-${invoiceData.language}`}isOpen={isSellerDialogOpen}onClose={() => {setIsSellerDialogOpen(false);@@ -284,6 +286,9 @@ export function SellerManagement({initialData={editingSeller}isEditMode={isEditMode}formValues={formValues}+ defaultVatNoLabelText={+ INVOICE_PDF_TRANSLATIONS[invoiceData.language].seller.vatNo+ }/>{/* Delete alert seller dialog */}diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/stale-dates-banner.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/stale-dates-banner.tsxindex 15f344a..bc7faae 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/components/stale-dates-banner.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/stale-dates-banner.tsx@@ -8,6 +8,10 @@ import {getCurrentMonthAndYear,isServicePeriodStartInCurrentMonth,} from "@/app/(main)/(app)/utils/format-service-period";+import {+ getPaymentDueForTerm,+ getPaymentTermDays,+} from "@/app/(main)/(app)/utils/payment-terms";import type { InvoiceData, SupportedLanguages } from "@/app/schema";import { Button } from "@/components/ui/button";@@ -69,19 +73,21 @@ export function StaleDatesBanner({const isInvoiceNumberStale = extractedMonthYear !== currentMonthAndYear;/**- * Checks if the payment due date is stale (outdated).- * A payment due date is considered stale if:- * - It's not set (empty/undefined), OR- * - It doesn't match the expected date (14 days after the date of issue)+ * Any due date on or after the date of issue is a payment term of its own ("Due 7 days+ * after issue"), so the payment due date is only listed when it is not set or falls+ * before the date of issue. "Update All Dates" still moves it along with the date of+ * issue, keeping its term.*/const isPaymentDueStale =- !paymentDue ||- !dayjs(paymentDue).isSame(dayjs(dateOfIssue).add(14, "days"), "day");+ !paymentDue || dayjs(paymentDue).isBefore(dayjs(dateOfIssue), "day");+ const paymentTermDays = getPaymentTermDays({ dateOfIssue, paymentDue });const targetToday = formatDate(dayjs());const targetEndOfMonth = formatDate(dayjs().endOf("month"));const targetStartOfMonth = formatDate(dayjs().startOf("month"));- const targetPaymentDue = formatDate(dayjs().add(14, "days"));+ const targetPaymentDue = formatDate(+ getPaymentDueForTerm({ dateOfIssue: dayjs(), paymentTermDays }),+ );const targetInvoiceNumber = `1/${currentMonthAndYear}`;@@ -131,7 +137,7 @@ export function StaleDatesBanner({label: "Payment due",oldValue: paymentDue ? formatDate(paymentDue) : fallbackValue,newValue: targetPaymentDue,- hint: "date of issue + 14 days",+ hint: `date of issue + ${paymentTermDays} ${paymentTermDays === 1 ? "day" : "days"}`,},];@@ -220,9 +226,10 @@ export function StaleDatesBanner({setValue("dateOfIssue", today);setValue("invoiceNumberObject.value", targetInvoiceNumber);- const newPaymentDue = dayjs(today)- .add(14, "days")- .format("YYYY-MM-DD");+ const newPaymentDue = getPaymentDueForTerm({+ dateOfIssue: today,+ paymentTermDays,+ });setValue("paymentDue", newPaymentDue);diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/stripe-top-line-color-picker.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/stripe-top-line-color-picker.tsxnew file mode 100644index 0000000..490069f--- /dev/null+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/stripe-top-line-color-picker.tsx@@ -0,0 +1,292 @@+import { useId, useState } from "react";+import { HexColorPicker } from "react-colorful";+import { useDebouncedCallback } from "use-debounce";++import { DEFAULT_STRIPE_TOP_LINE_COLOR } from "@/app/schema";+import { Label } from "@/components/ui/label";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { cn } from "@/lib/utils";++interface StripeTopLineColorPickerProps {+ /** The invoice's color, or `undefined` while it still uses the template's default. */+ value: string | undefined;+ /** Called with a lowercase `#rrggbb` color, or `undefined` to go back to the default. */+ onChange: (color: string | undefined) => void;+ hasError?: boolean;+}++export function StripeTopLineColorPicker({+ value,+ onChange,+ hasError = false,+}: StripeTopLineColorPickerProps) {+ const panelId = useId();+ const committedColor = value ?? DEFAULT_STRIPE_TOP_LINE_COLOR;++ // Dragging across the picker or typing a hex value fires on every move or key, and each+ // write would re-validate the form and queue another PDF render. The swatch, caption and+ // picker follow this draft straight away; the form only hears about it once things settle.+ const [color, setColor] = useState(committedColor);+ const [lastCommittedColor, setLastCommittedColor] = useState(committedColor);++ // a color that changes from outside the picker (a shared link, a template switch) wins+ // over the draft+ if (committedColor !== lastCommittedColor) {+ setLastCommittedColor(committedColor);+ setColor(committedColor);+ }++ const debouncedOnChange = useDebouncedCallback(+ onChange,+ COLOR_PICKER_DEBOUNCE_MS,+ );++ /** Presets and reset are single clicks, so they go to the form at once. */+ function commitColorNow(newColor: string | undefined) {+ debouncedOnChange.cancel();+ setColor(newColor ?? DEFAULT_STRIPE_TOP_LINE_COLOR);+ onChange(newColor);+ }++ function commitColorLater(newColor: string) {+ setColor(newColor);+ debouncedOnChange(newColor);+ }+ const preset = PRESET_COLORS.find((presetColor) => {+ return presetColor.hex === color;+ });++ const isDefaultColor = color === DEFAULT_STRIPE_TOP_LINE_COLOR;++ return (+ <div>+ <div className="mb-2 flex items-center justify-between">+ <Label id={`${panelId}-label`}>Top line color</Label>+ {isDefaultColor ? null : (+ <button+ type="button"+ className="text-xs text-zinc-600 underline underline-offset-2 hover:text-zinc-900"+ onClick={() => {+ commitColorNow(undefined);+ }}+ >+ Reset to default+ </button>+ )}+ </div>++ <div+ role="group"+ aria-labelledby={`${panelId}-label`}+ className="flex flex-wrap items-center gap-2.5"+ >+ {PRESET_COLORS.map((presetColor) => {+ const isSelected = presetColor.hex === color;++ return (+ <button+ key={presetColor.hex}+ type="button"+ aria-label={presetColor.name}+ aria-pressed={isSelected}+ title={presetColor.name}+ className={cn(+ "size-7 rounded-full border border-black/10 transition-shadow focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-900 focus-visible:ring-offset-2",+ isSelected ? "ring-2 ring-offset-2" : "",+ )}+ style={{+ backgroundColor: presetColor.hex,+ // the ring takes the swatch's own color, which reads as "this one" better+ // than a neutral outline does+ ["--tw-ring-color" as string]: isSelected+ ? presetColor.hex+ : undefined,+ }}+ onClick={() => {+ commitColorNow(+ presetColor.hex === DEFAULT_STRIPE_TOP_LINE_COLOR+ ? undefined+ : presetColor.hex,+ );+ }}+ />+ );+ })}++ <span aria-hidden className="h-5 w-px bg-zinc-200" />++ {/* the picker stays out of the way until asked for; Radix wires up aria-expanded,+ focus trapping and closing on Escape or an outside click */}+ <Popover+ onOpenChange={(isOpen) => {+ // closing the picker commits whatever is still waiting+ if (!isOpen) {+ debouncedOnChange.flush();+ }+ }}+ >+ <PopoverTrigger asChild>+ <button+ type="button"+ aria-label="Custom color"+ title="Custom color"+ className={cn(+ "size-7 rounded-full border border-black/10 bg-[conic-gradient(#f43f5e,#fbbf24,#10b981,#2563eb,#635bff,#f43f5e)] transition-shadow focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-900 focus-visible:ring-offset-2",+ // a color none of the presets match came from here, so this is the one marked+ preset ? "" : "ring-2 ring-zinc-400 ring-offset-2",+ )}+ />+ </PopoverTrigger>+ <PopoverContent+ align="end"+ className="w-64 space-y-3 p-3"+ aria-label="Custom top line color"+ >+ <HexColorPicker+ color={color}+ style={{ width: "100%", height: 160 }}+ onChange={(newColor) => {+ commitColorLater(newColor.toLowerCase());+ }}+ />+ <div className="flex items-center gap-2">+ <span+ aria-hidden+ className="size-9 shrink-0 rounded-md border border-black/10"+ style={{ backgroundColor: color }}+ />+ <div className="relative flex-1">+ <span+ aria-hidden+ className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 font-mono text-sm text-zinc-400"+ >+ #+ </span>+ <HexColorField+ id={`${panelId}-hex`}+ color={color}+ onColorChange={commitColorLater}+ hasError={hasError}+ />+ </div>+ </div>+ </PopoverContent>+ </Popover>+ </div>++ <p className="mt-1.5 text-xs text-zinc-700/90">+ {preset ? preset.name : "Custom"} ·{" "}+ <span className="font-mono uppercase">{color}</span>+ </p>+ </div>+ );+}++interface HexColorFieldProps {+ id: string;+ /** The color the picker shows, as a lowercase `#rrggbb`. */+ color: string;+ /** Called with a lowercase `#rrggbb` color once the typed text spells one. */+ onColorChange: (color: string) => void;+ hasError: boolean;+}++/**+ * The hex text box under the picker.+ *+ * It keeps its own text while focused, so what is typed is never rewritten under the+ * caret: half-typed values such as `FBB` (on the way from `FBBF24` to something else)+ * stay as typed instead of being read as a shorthand and expanded. A color is only+ * handed over once six digits are in, and a shorthand only on blur.+ */+function HexColorField({+ id,+ color,+ onColorChange,+ hasError,+}: HexColorFieldProps) {+ const [draftText, setDraftText] = useState<string | null>(null);+ const colorText = color.slice(1).toUpperCase();++ return (+ <input+ id={id}+ aria-label="Hex color"+ type="text"+ inputMode="text"+ autoComplete="off"+ spellCheck={false}+ maxLength={7}+ value={draftText ?? colorText}+ onFocus={() => {+ setDraftText(colorText);+ }}+ onChange={(event) => {+ const text = event.target.value+ .replace(/^#/, "")+ // oxlint-disable-next-line unicorn/prefer-string-replace-all -- `String#replaceAll` is Safari 13.1; `.browserslistrc` targets Safari 12, and SWC lowers syntax but never polyfills a built-in+ .replace(/[^\da-f]/gi, "")+ .slice(0, 6)+ .toUpperCase();++ setDraftText(text);++ if (text.length === 6) {+ onColorChange(`#${text.toLowerCase()}`);+ }+ }}+ onBlur={() => {+ const normalizedColor = draftText ? normalizeHexColor(draftText) : null;++ if (normalizedColor && normalizedColor !== color) {+ onColorChange(normalizedColor);+ }++ // anything that does not spell a color snaps back to the one on screen+ setDraftText(null);+ }}+ className={cn(+ "border-input focus-visible:ring-ring flex h-9 w-full rounded-md border bg-transparent py-1 pl-6 pr-3 font-mono text-sm uppercase shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1",+ hasError ? "border-red-500" : "",+ )}+ />+ );+}++/**+ * Accepts six digits and the three-digit shorthand (`fa0`), which the schema does not, so+ * it is spelled out to the six digits it does.+ */+function normalizeHexColor(color: string) {+ const digits = color.replace(/^#/, "").toLowerCase();++ if (/^[\da-f]{6}$/.test(digits)) {+ return `#${digits}`;+ }++ if (/^[\da-f]{3}$/.test(digits)) {+ const [red, green, blue] = [0, 1, 2].map((index) => {+ return digits.charAt(index);+ });++ return `#${red}${red}${green}${green}${blue}${blue}`;+ }++ return null;+}++/** How long the picker waits after the last drag or keystroke before writing to the form. */+const COLOR_PICKER_DEBOUNCE_MS = 250;++const PRESET_COLORS = [+ { name: "Amber (default)", hex: DEFAULT_STRIPE_TOP_LINE_COLOR },+ { name: "Indigo", hex: "#635bff" },+ { name: "Blue", hex: "#2563eb" },+ { name: "Emerald", hex: "#10b981" },+ { name: "Rose", hex: "#f43f5e" },+ { name: "Graphite", hex: "#111827" },+] as const satisfies readonly { name: string; hex: string }[];diff --git a/src/app/(main)/(app)/components/invoice-form/sections/general-information.tsx b/src/app/(main)/(app)/components/invoice-form/sections/general-information.tsxindex 2a352df..031be9f 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/general-information.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/general-information.tsx@@ -1,5 +1,5 @@import dayjs from "dayjs";-import { InfoIcon, Upload, X } from "lucide-react";+import { Upload, X } from "lucide-react";import { memo, useCallback, useRef } from "react";import {type Control,@@ -13,18 +13,28 @@ import { toast } from "sonner";import {AlertIcon,ErrorMessage,+ FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME,+ hiddenInPdfClassName,inputErrorClassName,} from "@/app/(main)/(app)/components/invoice-form/common";import {getDefaultInvoiceNumberLabel,INVOICE_PDF_TRANSLATIONS,} from "@/app/(main)/(app)/pdf-i18n-translations/pdf-translations";-import { formatTodayWithLocale } from "@/app/(main)/(app)/utils/format-date-with-locale";+import {+ formatDateWithLocale,+ formatTodayWithLocale,+} from "@/app/(main)/(app)/utils/format-date-with-locale";import { formatMoneyForTemplate } from "@/app/(main)/(app)/utils/format-money-for-template";import {getCurrentMonthAndYear,isServicePeriodStartInCurrentMonth,} from "@/app/(main)/(app)/utils/format-service-period";+import {+ DEFAULT_PAYMENT_TERM_DAYS,+ getPaymentDueForTerm,+ getPaymentTermDays,+} from "@/app/(main)/(app)/utils/payment-terms";import {type InvoiceData,LANGUAGE_TO_LABEL_WITH_REGION,@@ -52,6 +62,7 @@ import { cn } from "@/lib/utils";import { convertFileToBase64, validateImageSize } from "../utils/logo-upload";import { StaleDatesBanner } from "./components/stale-dates-banner";+import { StripeTopLineColorPicker } from "./components/stripe-top-line-color-picker";interface GeneralInformationProps {control: Control<InvoiceData>;@@ -130,6 +141,29 @@ export const GeneralInformation = memo(function GeneralInformation({!!dateOfServiceStart &&!isServicePeriodStartInCurrentMonth(dateOfServiceStart);+ const isServicePeriodFieldVisible = useWatch({+ control,+ name: "servicePeriodFieldIsVisible",+ });+ const isDateOfServiceFieldVisible = useWatch({+ control,+ name: "dateOfServiceFieldIsVisible",+ });+ const isEndDatePrintedAsDateOfSales =+ template === "default" && isDateOfServiceFieldVisible;++ // only the default template prints the end date a second time, as the date of sales,+ // and only while that field is shown; a warning takes the helper's place+ const isServicePeriodEndHelperVisible =+ template === "default" &&+ isDateOfServiceFieldVisible &&+ isDateOfServiceEndOfMonth &&+ !errors.dateOfService;++ // the label the PDF prints, so the helper quotes it exactly, edits and language included+ const printedDateOfServiceLabel =+ dateOfServiceLabelText || defaultDateOfServiceLabel;+const isDefaultInvoiceNumberLabel =invoiceNumberLabel === defaultInvoiceNumberLabel;@@ -141,6 +175,9 @@ export const GeneralInformation = memo(function GeneralInformation({const isInvoiceNumberInCurrentMonth =extractInvoiceMonthAndYear === getCurrentMonthAndYear();+ // the same value the stale dates banner moves the invoice number to+ const currentMonthInvoiceNumber = `1/${getCurrentMonthAndYear()}`;+// Logo upload handlersconst handleLogoUpload = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {@@ -196,27 +233,63 @@ export const GeneralInformation = memo(function GeneralInformation({});}, [isMobile, setValue]);- const isPaymentDueNotMatchingIssueDate =- !paymentDue ||- !dayjs(paymentDue).isSame(dayjs(dateOfIssue).add(14, "days"), "day");+ const isPaymentDueBeforeDateOfIssue = dayjs(paymentDue).isBefore(+ dayjs(dateOfIssue),+ );++ // a cleared date input; the PDF would otherwise quietly fall back to 14 days from today+ const isPaymentDueNotSet = !paymentDue;++ const paymentTermDays = dayjs(paymentDue).diff(dayjs(dateOfIssue), "day");++ // default browser date input format is YYYY-MM-DD+ const suggestedPaymentDue = getPaymentDueForTerm({+ dateOfIssue,+ paymentTermDays: DEFAULT_PAYMENT_TERM_DAYS,+ });++ // Helper texts quote dates back to the user, so they are formatted the way the+ // PDF will render them: the invoice's date format AND its language.+ const formattedToday = formatTodayWithLocale({+ selectedDateFormat,+ language,+ });+ const formattedStartOfMonth = formatDateWithLocale({+ date: dayjs().startOf("month"),+ selectedDateFormat,+ language,+ });+ const formattedEndOfMonth = formatDateWithLocale({+ date: dayjs().endOf("month"),+ selectedDateFormat,+ language,+ });+ const formattedSuggestedPaymentDue = formatDateWithLocale({+ date: suggestedPaymentDue,+ selectedDateFormat,+ language,+ });/*** Whether to show Stale Dates Banner.* Banner appears when any invoice date/number is out of sync with current month.* Triggers: service end not end of current month, service start not in current month,- * invoice number not for current month, issue date not today, payment due not 14 days after issue.+ * invoice number not for current month, issue date not today, payment due not set or before+ * the date of issue. Any due date on or after the date of issue is a payment term of its own, and it+ * moves along when the date of issue does.*/const canShowStaleDatesBanner =!isDateOfServiceEndOfMonth ||isServicePeriodStartOutsideCurrentMonth ||!isInvoiceNumberInCurrentMonth ||isDateOfIssueNotToday ||- isPaymentDueNotMatchingIssueDate;+ isPaymentDueNotSet ||+ (!!dateOfIssue && isPaymentDueBeforeDateOfIssue);return (- <div>- <div className="space-y-4">- {/* Invoice Template Selection */}+ <div className="space-y-5">+ {/* PDF SETTINGS */}+ <FormGroup title="PDF settings"><div><Label htmlFor={`template`} className="mb-1">Invoice Template@@ -299,372 +372,358 @@ export const GeneralInformation = memo(function GeneralInformation({/>{errors.template ? (<ErrorMessage>{errors.template.message}</ErrorMessage>- ) : (- <InputHelperMessage>- Select the design template for your invoice- </InputHelperMessage>- )}- </div>-- {/* Language PDF Select */}- <div>- <Label htmlFor={`language`} className="mb-1">- Invoice PDF Language- </Label>- <Controller- name="language"- control={control}- render={({ field }) => {- return (- <SelectNative- {...field}- id={`language`}- className={cn(- "block",- inputErrorClassName(!!errors.language),- )}- onChange={(e) => {- field.onChange(e);-- // IMPORTANT: for BETTER USER EXPERIENCE, when switching language, we update the invoice number and labels to the new language-- // Update INVOICE NUMBER and LABELS when language changes- const newLanguage = e.target- .value as keyof typeof INVOICE_PDF_TRANSLATIONS;-- umamiTrackEvent("invoice_language_changed", {- data: {- language: newLanguage,- previous_language: language,- invoice_template: template,- number_format_preserved:- !!preserveNumberFormatOnLanguageChange,- },- });-- // we need to keep the invoice number suffix (e.g. 1/MM-YYYY) for better user experience, when switching language- setValue(- "invoiceNumberObject.label",- getDefaultInvoiceNumberLabel(newLanguage, template),- );- setValue("invoiceNumberObject.value", invoiceNumberValue);-- // Update SELLER VAT NO (Account Number) LABEL TEXT when language changes- setValue(- "seller.vatNoLabelText",- INVOICE_PDF_TRANSLATIONS[newLanguage].seller.vatNo,- );-- // Update BUYER VAT NO (Account Number) LABEL TEXT when language changes- setValue(- "buyer.vatNoLabelText",- INVOICE_PDF_TRANSLATIONS[newLanguage].buyer.vatNo,- );-- const newTranslation =- INVOICE_PDF_TRANSLATIONS[newLanguage].invoiceItemsTable- .vat;-- // Update TAX LABEL TEXT (VAT/GST/etc.) when language changes- // This ensures the tax column header in the invoice items table- // displays the correct translation for the selected language- setValue("taxLabelText", newTranslation);-- // Update DATE FORMAT when language changes, so the spelled-out month- // the Stripe template prints reads the way the language writes it- setValue(- "dateFormat",- getDefaultDateFormat({ language: newLanguage, template }),- );-- // Update NUMBER FORMAT when language changes, so the amounts are- // punctuated the way the new language punctuates them. It stays a- // separate field because the two can legitimately differ -- a Polish- // issuer writing an English invoice may still want "10 000,00 EUR",- // which is what `preserveNumberFormatOnLanguageChange` is for.- //- // Preserving it has to write the resolved value rather than skip the- // write: an invoice that never picked a format carries none and falls- // back to its own language, so leaving it empty would let the format- // follow the language anyway. Pinning the language being left behind- // is what actually preserves what is on screen.- setValue(- "numberFormatLocale",- getNumberFormatLocaleAfterLanguageChange({- previousLanguage: language,- nextLanguage: newLanguage,- numberFormatLocale,- preserveNumberFormatOnLanguageChange,- }),- );-- setValue(- "servicePeriodLabelText",- INVOICE_PDF_TRANSLATIONS[newLanguage].servicePeriod,- );- setValue(- "dateOfServiceLabelText",- INVOICE_PDF_TRANSLATIONS[newLanguage].dateOfService,- );- }}- >- {SUPPORTED_INVOICE_PDF_LANGUAGES.map((lang) => {- const languageName = LANGUAGE_TO_LABEL_WITH_REGION[lang];-- if (!languageName) {- return null;- }-- return (- <option key={lang} value={lang}>- {languageName}- </option>- );- })}- </SelectNative>- );- }}- />- {errors.language ? (- <ErrorMessage>{errors.language.message}</ErrorMessage>- ) : (- <InputHelperMessage>- Select the language of the invoice- </InputHelperMessage>- )}- </div>-- {/* Currency Select */}- <div>- <Label htmlFor={`currency`} className="mb-1">- Currency- </Label>- <Controller- name="currency"- control={control}- render={({ field }) => {- return (- <CurrencyCombobox- id={`currency`}- value={field.value}- onChange={field.onChange}- hasError={!!errors.currency}- />- );- }}- />- {errors.currency ? (- <ErrorMessage>{errors.currency.message}</ErrorMessage>- ) : (- <InputHelperMessage>- Select the currency of the invoice- </InputHelperMessage>- )}- </div>-- {/* Date Format */}- <div>- <Label htmlFor={`dateFormat`} className="mb-1">- Date Format- </Label>- <Controller- name="dateFormat"- control={control}- render={({ field }) => {- return (- <SelectNative- {...field}- id={`dateFormat`}- className={cn(- "block",- inputErrorClassName(!!errors.dateFormat),- )}- >- {getDateFormatsForLanguage(language).map((format) => {- const preview = formatTodayWithLocale({- selectedDateFormat: format,- language,- });- // The marker follows the same resolver the form applies, so it- // points at the Stripe template's long date when that is what a- // reset would pick.- const isDefault =- format === getDefaultDateFormat({ language, template });-- // `[de]` is dayjs escape syntax for a literal. The brackets mean- // nothing to the reader, so the pattern is shown without them.- // oxlint-disable-next-line unicorn/prefer-string-replace-all -- `String#replaceAll` is Safari 13.1; `.browserslistrc` targets Safari 12, and SWC lowers syntax but never polyfills a built-in- const patternLabel = format.replace(/[[\]]/g, "");-- return (- <option key={format} value={format}>- {patternLabel} ({preview}){" "}- {isDefault ? "(default)" : ""}- </option>- );- })}- </SelectNative>- );- }}- />-- {errors.dateFormat ? (- <ErrorMessage>{errors.dateFormat.message}</ErrorMessage>- ) : (- <InputHelperMessage>- Select the date format of the invoice- </InputHelperMessage>- )}+ ) : null}</div>- {/* Number Format */}- <fieldset className="rounded-md border p-4">- <legend className="px-1 text-lg font-semibold text-gray-900">- Number Format- </legend>- <div>- <Label htmlFor={`numberFormatLocale`} className="mb-1">- Format+ <div className="space-y-4">+ {/* Language PDF Select */}+ <div className="min-w-0">+ <Label htmlFor={`language`} className="mb-1">+ Invoice PDF Language</Label><Controller- name="numberFormatLocale"+ name="language"control={control}render={({ field }) => {return (<SelectNative{...field}- // invoices saved before this setting existed carry no value, and they- // are written in their own language, which is what they fall back to- value={field.value ?? language}- id={`numberFormatLocale`}+ id={`language`}className={cn("block",- inputErrorClassName(!!errors.numberFormatLocale),+ inputErrorClassName(!!errors.language),)}onChange={(e) => {field.onChange(e);- // the previous value falls back the same way the rendered- // value does, so the event reports the format that was on- // screen rather than an empty one- umamiTrackEvent("invoice_number_format_changed", {+ // IMPORTANT: for BETTER USER EXPERIENCE, when switching language, we update the invoice number and labels to the new language++ // Update INVOICE NUMBER and LABELS when language changes+ const newLanguage = e.target+ .value as keyof typeof INVOICE_PDF_TRANSLATIONS;++ umamiTrackEvent("invoice_language_changed", {data: {- number_format_locale: e.target- .value as SupportedNumberFormatLocale,- previous_number_format_locale:- numberFormatLocale ?? language,- invoice_language: language,+ language: newLanguage,+ previous_language: language,invoice_template: template,+ number_format_preserved:+ !!preserveNumberFormatOnLanguageChange,},});++ // we need to keep the invoice number suffix (e.g. 1/MM-YYYY) for better user experience, when switching language+ setValue(+ "invoiceNumberObject.label",+ getDefaultInvoiceNumberLabel(newLanguage, template),+ );+ setValue("invoiceNumberObject.value", invoiceNumberValue);++ // Update SELLER VAT NO (Account Number) LABEL TEXT when language changes+ setValue(+ "seller.vatNoLabelText",+ INVOICE_PDF_TRANSLATIONS[newLanguage].seller.vatNo,+ );++ // Update BUYER VAT NO (Account Number) LABEL TEXT when language changes+ setValue(+ "buyer.vatNoLabelText",+ INVOICE_PDF_TRANSLATIONS[newLanguage].buyer.vatNo,+ );++ const newTranslation =+ INVOICE_PDF_TRANSLATIONS[newLanguage].invoiceItemsTable+ .vat;++ // Update TAX LABEL TEXT (VAT/GST/etc.) when language changes+ // This ensures the tax column header in the invoice items table+ // displays the correct translation for the selected language+ setValue("taxLabelText", newTranslation);++ // Update DATE FORMAT when language changes, so the spelled-out month+ // the Stripe template prints reads the way the language writes it+ setValue(+ "dateFormat",+ getDefaultDateFormat({+ language: newLanguage,+ template,+ }),+ );++ // Update NUMBER FORMAT when language changes, so the amounts are+ // punctuated the way the new language punctuates them. It stays a+ // separate field because the two can legitimately differ -- a Polish+ // issuer writing an English invoice may still want "10 000,00 EUR",+ // which is what `preserveNumberFormatOnLanguageChange` is for.+ //+ // Preserving it has to write the resolved value rather than skip the+ // write: an invoice that never picked a format carries none and falls+ // back to its own language, so leaving it empty would let the format+ // follow the language anyway. Pinning the language being left behind+ // is what actually preserves what is on screen.+ setValue(+ "numberFormatLocale",+ getNumberFormatLocaleAfterLanguageChange({+ previousLanguage: language,+ nextLanguage: newLanguage,+ numberFormatLocale,+ preserveNumberFormatOnLanguageChange,+ }),+ );++ setValue(+ "servicePeriodLabelText",+ INVOICE_PDF_TRANSLATIONS[newLanguage].servicePeriod,+ );+ setValue(+ "dateOfServiceLabelText",+ INVOICE_PDF_TRANSLATIONS[newLanguage].dateOfService,+ );}}>- {SUPPORTED_NUMBER_FORMAT_LOCALES.map(- (supportedNumberFormatLocale) => {- const label =- supportedNumberFormatLocale === "international"- ? "International"- : LANGUAGE_TO_LABEL_WITH_REGION[- supportedNumberFormatLocale- ];-- // the invoice's own total, written the way the selected template- // writes it, so the picker shows the number this invoice's reader- // will actually see- const preview = formatMoneyForTemplate({- amount: invoiceTotal,- currency,- numberFormatLocale: supportedNumberFormatLocale,- template,- });+ {SUPPORTED_INVOICE_PDF_LANGUAGES.map((lang) => {+ const languageName = LANGUAGE_TO_LABEL_WITH_REGION[lang];- // switching the invoice language moves the format with it, so the- // marker sits on the language the invoice is written in- const isDefault =- supportedNumberFormatLocale === language;+ if (!languageName) {+ return null;+ }- return (- <option- key={supportedNumberFormatLocale}- value={supportedNumberFormatLocale}- >- {label} ({preview}) {isDefault ? "(default)" : ""}- </option>- );- },- )}+ return (+ <option key={lang} value={lang}>+ {languageName}+ </option>+ );+ })}</SelectNative>);}}/>-- {errors.numberFormatLocale ? (- <ErrorMessage>{errors.numberFormatLocale.message}</ErrorMessage>- ) : (- <InputHelperMessage>- Choose the number format used in the PDF- </InputHelperMessage>- )}+ {errors.language ? (+ <ErrorMessage>{errors.language.message}</ErrorMessage>+ ) : null}</div>- {/** Keep the format when the PDF language changes */}- <div className="mt-5 inline-flex items-center gap-2">+ {/* Currency Select */}+ <div className="min-w-0">+ <Label htmlFor={`currency`} className="mb-1">+ Currency+ </Label><Controller- name="preserveNumberFormatOnLanguageChange"+ name="currency"control={control}- render={({ field: { value, onChange, ...field } }) => {+ render={({ field }) => {return (- <Switch- {...field}- id="preserveNumberFormatOnLanguageChange"- data-testid="preserveNumberFormatOnLanguageChange"- // the field is absent until someone turns it on, and absent is off- checked={!!value}- onCheckedChange={(checked) => {- onChange(checked);-- umamiTrackEvent(- "invoice_number_format_preserve_toggled",- {+ <CurrencyCombobox+ id={`currency`}+ value={field.value}+ onChange={field.onChange}+ hasError={!!errors.currency}+ />+ );+ }}+ />+ {errors.currency ? (+ <ErrorMessage>{errors.currency.message}</ErrorMessage>+ ) : null}+ </div>+ </div>++ {/* FORMATTING */}+ <SubGroup title="Formatting">+ <div className="space-y-4">+ {/* Date Format */}+ <div className="min-w-0">+ <Label htmlFor={`dateFormat`} className="mb-1">+ Date Format+ </Label>+ <Controller+ name="dateFormat"+ control={control}+ render={({ field }) => {+ return (+ <SelectNative+ {...field}+ id={`dateFormat`}+ className={cn(+ "block",+ inputErrorClassName(!!errors.dateFormat),+ )}+ >+ {getDateFormatsForLanguage(language).map((format) => {+ const preview = formatTodayWithLocale({+ selectedDateFormat: format,+ language,+ });+ // The marker follows the same resolver the form applies, so it+ // points at the Stripe template's long date when that is what a+ // reset would pick.+ const isDefault =+ format ===+ getDefaultDateFormat({ language, template });++ // `[de]` is dayjs escape syntax for a literal. The brackets mean+ // nothing to the reader, so the pattern is shown without them.+ // oxlint-disable-next-line unicorn/prefer-string-replace-all -- `String#replaceAll` is Safari 13.1; `.browserslistrc` targets Safari 12, and SWC lowers syntax but never polyfills a built-in+ const patternLabel = format.replace(/[[\]]/g, "");++ return (+ <option key={format} value={format}>+ {patternLabel} ({preview}){" "}+ {isDefault ? "(default)" : ""}+ </option>+ );+ })}+ </SelectNative>+ );+ }}+ />+ {errors.dateFormat ? (+ <ErrorMessage>{errors.dateFormat.message}</ErrorMessage>+ ) : null}+ </div>++ {/* Number Format */}+ <div className="min-w-0">+ <Label htmlFor={`numberFormatLocale`} className="mb-1">+ Number Format+ </Label>+ <Controller+ name="numberFormatLocale"+ control={control}+ render={({ field }) => {+ return (+ <SelectNative+ {...field}+ // invoices saved before this setting existed carry no value, and they+ // are written in their own language, which is what they fall back to+ value={field.value ?? language}+ id={`numberFormatLocale`}+ className={cn(+ "block",+ inputErrorClassName(!!errors.numberFormatLocale),+ )}+ onChange={(e) => {+ field.onChange(e);++ // the previous value falls back the same way the rendered+ // value does, so the event reports the format that was on+ // screen rather than an empty one+ umamiTrackEvent("invoice_number_format_changed", {data: {- preserve_number_format: checked,- number_format_locale:+ number_format_locale: e.target+ .value as SupportedNumberFormatLocale,+ previous_number_format_locale:numberFormatLocale ?? language,invoice_language: language,invoice_template: template,},+ });+ }}+ >+ {SUPPORTED_NUMBER_FORMAT_LOCALES.map(+ (supportedNumberFormatLocale) => {+ const label =+ supportedNumberFormatLocale === "international"+ ? "International"+ : LANGUAGE_TO_LABEL_WITH_REGION[+ supportedNumberFormatLocale+ ];++ // the invoice's own total, written the way the selected template+ // writes it, so the picker shows the number this invoice's reader+ // will actually see+ const preview = formatMoneyForTemplate({+ amount: invoiceTotal,+ currency,+ numberFormatLocale: supportedNumberFormatLocale,+ template,+ });++ // switching the invoice language moves the format with it, so the+ // marker sits on the language the invoice is written in+ const isDefault =+ supportedNumberFormatLocale === language;++ return (+ <option+ key={supportedNumberFormatLocale}+ value={supportedNumberFormatLocale}+ >+ {label} ({preview}) {isDefault ? "(default)" : ""}+ </option>+ );},- );- }}- size="sm"- />- );- }}- />- <CustomTooltip- trigger={- <Label htmlFor="preserveNumberFormatOnLanguageChange">- Keep format when language changes- </Label>- }- content="Turn on to keep your number format when the PDF language changes."- />+ )}+ </SelectNative>+ );+ }}+ />+ {errors.numberFormatLocale ? (+ <ErrorMessage>{errors.numberFormatLocale.message}</ErrorMessage>+ ) : null}+ </div></div>- <InputHelperMessage>- {preserveNumberFormatOnLanguageChange- ? "The number format stays as it is when you switch the PDF language"- : "By default, the number format follows the PDF language"}- </InputHelperMessage>- </fieldset>- {/* Invoice Number */}- <fieldset className="rounded-md border p-4">- <legend className="px-1 text-lg font-semibold text-gray-900">- Invoice Number- </legend>- <div className="space-y-4">- <div>- <Label htmlFor="invoiceNumberLabel">Label</Label>+ {/** Keep the format when the PDF language changes */}+ <div>+ <div className="inline-flex items-center gap-2">+ <Controller+ name="preserveNumberFormatOnLanguageChange"+ control={control}+ render={({ field: { value, onChange, ...field } }) => {+ return (+ <Switch+ {...field}+ id="preserveNumberFormatOnLanguageChange"+ data-testid="preserveNumberFormatOnLanguageChange"+ // the field is absent until someone turns it on, and absent is off+ checked={!!value}+ onCheckedChange={(checked) => {+ onChange(checked);++ umamiTrackEvent(+ "invoice_number_format_preserve_toggled",+ {+ data: {+ preserve_number_format: checked,+ number_format_locale:+ numberFormatLocale ?? language,+ invoice_language: language,+ invoice_template: template,+ },+ },+ );+ }}+ size="sm"+ />+ );+ }}+ />+ <CustomTooltip+ trigger={+ <Label htmlFor="preserveNumberFormatOnLanguageChange">+ Keep number format when changing language+ </Label>+ }+ content="Turn on to keep your number format when the PDF language changes."+ />+ </div>+ <InputHelperMessage>+ {preserveNumberFormatOnLanguageChange+ ? "Changing the PDF language keeps the number format."+ : "Changing the PDF language also changes the number format."}+ </InputHelperMessage>+ </div>+ </SubGroup>+ </FormGroup>++ {/* INVOICE DETAILS */}+ <FormGroup title="Invoice details">+ {/* Invoice number */}+ <div>+ <div className="grid grid-cols-2 gap-3">+ <div className="min-w-0">+ <Label htmlFor="invoiceNumberLabel">Invoice number label</Label><Controllername="invoiceNumberObject.label"control={control}@@ -706,9 +765,8 @@ export const GeneralInformation = memo(function GeneralInformation({</InputHelperMessage>) : null}</div>-- <div>- <Label htmlFor="invoiceNumberValue">Value</Label>+ <div className="min-w-0">+ <Label htmlFor="invoiceNumberValue">Invoice number</Label><Controllername="invoiceNumberObject.value"control={control}@@ -734,88 +792,191 @@ export const GeneralInformation = memo(function GeneralInformation({{errors.invoiceNumberObject.value.message}</ErrorMessage>) : null}-{!isInvoiceNumberInCurrentMonth &&!errors.invoiceNumberObject?.value ? (- <InputHelperMessage>- <span className="flex items-center text-amber-800">- <AlertIcon />- Invoice number does not match current month- </span>- </InputHelperMessage>+ <FieldWarning+ message="Not current month"+ fixValue={currentMonthInvoiceNumber}+ fixLabel={`Set invoice number to ${currentMonthInvoiceNumber}`}+ onFix={() => {+ setValue(+ "invoiceNumberObject.value",+ currentMonthInvoiceNumber,+ );+ }}+ />) : null}</div></div>- </fieldset>+ </div>- {/* Date of Issue */}+ {/* Date of issue and payment due */}<div>- <Label htmlFor={`dateOfIssue`} className="mb-1">- Date of Issue- </Label>- <Controller- name="dateOfIssue"- control={control}- render={({ field }) => {- return (- <Input- {...field}- type="date"- id={`dateOfIssue`}- className={inputErrorClassName(!!errors.dateOfIssue)}- onChange={(e) => {- field.onChange(e);-- const newDate = e.target.value;+ <div className="grid grid-cols-2 gap-3">+ {/* Date of Issue */}+ <div className="min-w-0">+ <Label htmlFor={`dateOfIssue`} className="mb-1">+ Date of issue+ </Label>+ <Controller+ name="dateOfIssue"+ control={control}+ render={({ field }) => {+ return (+ <Input+ {...field}+ type="date"+ id={`dateOfIssue`}+ className={inputErrorClassName(!!errors.dateOfIssue)}+ onChange={(e) => {+ // read before `field.onChange`, while it is still the old date+ const currentPaymentTermDays = getPaymentTermDays({+ dateOfIssue: field.value,+ paymentDue,+ });- // Automatically update payment due date to 14 days after the new date of issue for better UX- if (newDate) {- setValue(- "paymentDue",- dayjs(newDate).add(14, "days").format("YYYY-MM-DD"),- );- }+ field.onChange(e);++ const newDate = e.target.value;++ // the payment due date moves along with the date of issue, keeping+ // the payment term ("Due 7 days after issue") the invoice already has+ if (newDate) {+ setValue(+ "paymentDue",+ getPaymentDueForTerm({+ dateOfIssue: newDate,+ paymentTermDays: currentPaymentTermDays,+ }),+ );+ }+ }}+ />+ );+ }}+ />+ {errors.dateOfIssue ? (+ <ErrorMessage>{errors.dateOfIssue.message}</ErrorMessage>+ ) : null}+ {isDateOfIssueNotToday && !errors.dateOfIssue ? (+ <FieldWarning+ message="Not today"+ fixValue={formattedToday}+ fixLabel={`Set date of issue to today (${formattedToday})`}+ onFix={() => {+ const today = dayjs().format("YYYY-MM-DD");++ setValue("dateOfIssue", today);+ setValue(+ "paymentDue",+ getPaymentDueForTerm({+ dateOfIssue: today,+ paymentTermDays: getPaymentTermDays({+ dateOfIssue,+ paymentDue,+ }),+ }),+ );}}/>- );- }}- />- {errors.dateOfIssue ? (- <ErrorMessage>{errors.dateOfIssue.message}</ErrorMessage>- ) : null}- {isDateOfIssueNotToday && !errors.dateOfIssue ? (- <InputHelperMessage>- <span className="flex items-center text-amber-800">- <AlertIcon />- Date of issue is not today- </span>- <ButtonHelper- onClick={() => {- const today = dayjs().format("YYYY-MM-DD");-- setValue("dateOfIssue", today);- setValue(- "paymentDue",- dayjs(today).add(14, "days").format("YYYY-MM-DD"),+ ) : null}+ </div>++ {/* Payment Due */}+ <div className="min-w-0">+ <Label htmlFor={`paymentDue`} className="mb-1">+ Payment due+ </Label>+ <Controller+ name="paymentDue"+ control={control}+ render={({ field }) => {+ return (+ <Input+ {...field}+ id={`paymentDue`}+ type="date"+ className={inputErrorClassName(!!errors.paymentDue)}+ />);}}+ />+ {errors.paymentDue ? (+ <ErrorMessage>{errors.paymentDue.message}</ErrorMessage>+ ) : null}+ {!errors.paymentDue &&+ (isPaymentDueNotSet || isPaymentDueBeforeDateOfIssue) &&+ dateOfIssue ? (+ <FieldWarning+ message={+ isPaymentDueNotSet ? "Not set" : "Before date of issue"+ }+ fixValue={formattedSuggestedPaymentDue}+ fixLabel={`Set payment due date to ${formattedSuggestedPaymentDue} (14 days after issue)`}+ onFix={() => {+ setValue("paymentDue", suggestedPaymentDue);+ }}+ />+ ) : null}+ </div>+ </div>++ {/* Payment terms shortcuts */}+ {dateOfIssue && !errors.paymentDue ? (+ <div className="mt-4 flex flex-wrap items-center justify-between gap-2">+ <p className="text-xs text-zinc-700/90">+ {/* a due date before the date of issue has no term to name (the warning+ under the field says what is wrong), so the pills are offered as the way out */}+ {paymentTermDays >= 0+ ? `Due ${paymentTermDays} ${paymentTermDays === 1 ? "day" : "days"} after issue`+ : "Pick a payment term"}+ </p>+ <div+ role="group"+ aria-label="Payment terms"+ className="inline-flex gap-1">- <span className="text-pretty">- Set date of issue to today (- {formatTodayWithLocale({ selectedDateFormat, language })})- </span>- </ButtonHelper>- </InputHelperMessage>+ {PAYMENT_TERM_DAYS.map((days) => {+ const isSelected = days === paymentTermDays;++ return (+ <button+ key={days}+ type="button"+ aria-pressed={isSelected}+ className={cn(+ "h-6 rounded-full border px-2.5 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-900 focus-visible:ring-offset-1",+ isSelected+ ? "border-zinc-900 bg-zinc-900 text-white"+ : "border-zinc-200 bg-white text-zinc-700 hover:bg-zinc-50",+ )}+ onClick={() => {+ setValue(+ "paymentDue",+ dayjs(dateOfIssue)+ .add(days, "days")+ .format("YYYY-MM-DD"),+ );+ }}+ >+ {days} days+ </button>+ );+ })}+ </div>+ </div>) : null}</div>- <fieldset className="rounded-md border p-4">- <legend className="px-1 text-lg font-semibold text-gray-900">- Service period- </legend>+ {/* the legend is for assistive tech, the heading next to the switch is what is seen */}+ <fieldset className="min-w-0 space-y-4 border-t border-zinc-200 pt-4">+ <legend className="sr-only">Service period</legend>{/** Service period PDF visibility toggle */}- <div className="mb-5 flex flex-col items-start gap-2 sm:justify-end sm:gap-4">+ <div className="flex items-center justify-between gap-2">+ <h3 aria-hidden className="text-sm font-semibold">+ Service period+ </h3><div className="inline-flex items-center gap-2"><Controllername="servicePeriodFieldIsVisible"@@ -837,7 +998,7 @@ export const GeneralInformation = memo(function GeneralInformation({<CustomTooltiptrigger={<Label htmlFor="servicePeriodFieldIsVisible">- Show "Service period" in PDF+ Show in PDF</Label>}content='Show the "Service period" (Service period start and end) field in the PDF'@@ -845,9 +1006,60 @@ export const GeneralInformation = memo(function GeneralInformation({</div></div>+ {/** Service period PDF label - default template only */}+ {template === "default" ? (+ <div className={hiddenInPdfClassName(!isServicePeriodFieldVisible)}>+ <Label htmlFor="servicePeriodLabelText">+ Service period label+ </Label>+ <Controller+ name="servicePeriodLabelText"+ control={control}+ render={({ field }) => {+ return (+ <Textarea+ {...field}+ id="servicePeriodLabelText"+ rows={2}+ placeholder="Enter service period PDF label"+ className={cn(+ "mt-1 block w-full",+ inputErrorClassName(!!errors.servicePeriodLabelText),+ )}+ />+ );+ }}+ />+ {errors.servicePeriodLabelText ? (+ <ErrorMessage>+ {errors.servicePeriodLabelText.message}+ </ErrorMessage>+ ) : null}+ {!isDefaultServicePeriodLabel ? (+ <InputHelperMessage>+ <ButtonHelper+ onClick={() => {+ setValue(+ "servicePeriodLabelText",+ defaultServicePeriodLabel,+ );+ }}+ >+ Reset to default ("{defaultServicePeriodLabel}")+ </ButtonHelper>+ </InputHelperMessage>+ ) : null}+ </div>+ ) : null}+{/** Service period start and end inputs */}- <div className="space-y-4">- <div>+ <div className="grid grid-cols-2 gap-3">+ <div+ className={cn(+ "min-w-0",+ hiddenInPdfClassName(!isServicePeriodFieldVisible),+ )}+ ><Label htmlFor="dateOfServiceStart" className="mb-1">Service period start</Label>@@ -870,40 +1082,36 @@ export const GeneralInformation = memo(function GeneralInformation({{errors.dateOfServiceStart ? (<ErrorMessage>{errors.dateOfServiceStart.message}</ErrorMessage>) : null}-{isServicePeriodStartOutsideCurrentMonth &&!errors.dateOfServiceStart ? (- <InputHelperMessage>- <span className="flex items-center text-amber-800">- <AlertIcon />- Service period start is not in the current month- </span>- </InputHelperMessage>+ <FieldWarning+ message="Not current month"+ fixValue={formattedStartOfMonth}+ fixLabel={`Set service period start to ${formattedStartOfMonth}`}+ onFix={() => {+ setValue(+ "dateOfServiceStart",+ dayjs().startOf("month").format("YYYY-MM-DD"),+ );+ }}+ />) : null}</div>- <div>- <div className="mb-1 flex items-center">- <Label htmlFor="dateOfService">Service period end</Label>- <CustomTooltip- content='Shown on PDF as part of "Service period" and as "Date of sales/of executing the service"'- side="top"- popoverOnMobile- trigger={- <button- type="button"- className="ml-1 inline-flex cursor-pointer items-center align-middle"- aria-label='Shown on PDF as part of "Service period" and as "Date of sales/of executing the service"'- >- <InfoIcon- className="size-3"- aria-hidden- data-testid="service-period-end-info-icon"- />- </button>- }- />- </div>+ {/* the end date is also the "Date of sales" on the default template, so it is+ only left out when neither prints it */}+ <div+ className={cn(+ "min-w-0",+ hiddenInPdfClassName(+ !isServicePeriodFieldVisible &&+ !isEndDatePrintedAsDateOfSales,+ ),+ )}+ >+ <Label htmlFor="dateOfService" className="mb-1">+ Service period end+ </Label><Controllername="dateOfService"@@ -914,6 +1122,11 @@ export const GeneralInformation = memo(function GeneralInformation({{...field}type="date"id="dateOfService"+ aria-describedby={+ isServicePeriodEndHelperVisible+ ? "dateOfService-helper"+ : undefined+ }className={inputErrorClassName(!!errors.dateOfService)}/>);@@ -922,135 +1135,106 @@ export const GeneralInformation = memo(function GeneralInformation({{errors.dateOfService ? (<ErrorMessage>{errors.dateOfService.message}</ErrorMessage>) : null}-{!isDateOfServiceEndOfMonth && !errors.dateOfService ? (- <InputHelperMessage>- <span className="flex items-center text-amber-800">- <AlertIcon />- Service period end is not the last day of the current month- </span>- </InputHelperMessage>+ <FieldWarning+ message="Not end of current month"+ fixValue={formattedEndOfMonth}+ fixLabel={`Set service period end to ${formattedEndOfMonth}`}+ onFix={() => {+ setValue(+ "dateOfService",+ dayjs().endOf("month").format("YYYY-MM-DD"),+ );+ }}+ />+ ) : null}+ {/* only the default template also prints the end date as the "Date of sales",+ which is what the helper is there to say; a warning takes its place */}+ {isServicePeriodEndHelperVisible ? (+ <p+ id="dateOfService-helper"+ className="mt-1 text-pretty text-xs text-zinc-700/90"+ >+ {/* with the service period hidden, this date is printed only once */}+ {isServicePeriodFieldVisible ? "Also printed" : "Printed"} as+ “{printedDateOfServiceLabel}”+ </p>) : null}</div></div>- {/** Service period PDF label customization - default template only */}+ {/** "Date of sales" PDF label - default template only */}{template === "default" ? (- <div className="mt-5 space-y-5">- <div>- <Label htmlFor="servicePeriodLabelText">- Service period PDF label+ <div className={FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME}>+ <div className="relative mb-2 flex items-center justify-between">+ <Label htmlFor="dateOfServiceLabelText">+ Date of sales label</Label>- <Controller- name="servicePeriodLabelText"- control={control}- render={({ field }) => {- return (- <Textarea- {...field}- id="servicePeriodLabelText"- rows={2}- placeholder="Enter service period PDF label"- className={cn(- "mt-1 block w-full",- inputErrorClassName(!!errors.servicePeriodLabelText),- )}- />- );- }}- />- {errors.servicePeriodLabelText ? (- <ErrorMessage>- {errors.servicePeriodLabelText.message}- </ErrorMessage>- ) : null}- {!isDefaultServicePeriodLabel ? (- <InputHelperMessage>- <ButtonHelper- onClick={() => {- setValue(- "servicePeriodLabelText",- defaultServicePeriodLabel,- );- }}- >- Reset to default ("{defaultServicePeriodLabel}")- </ButtonHelper>- </InputHelperMessage>- ) : null}- </div>-- <div>- <div className="relative mb-2 flex items-center justify-between">- <Label htmlFor="dateOfServiceLabelText">- Date of sales PDF label- </Label>- <div className="inline-flex items-center gap-2">- <Controller- name="dateOfServiceFieldIsVisible"- control={control}- render={({ field: { value, onChange, ...field } }) => {- return (- <Switch- {...field}- id="dateOfServiceFieldIsVisible"- data-testid="dateOfServiceFieldIsVisible"- checked={value}- onCheckedChange={onChange}- size="sm"- aria-label='Show the "Date of sales/of executing the service" field in the PDF'- />- );- }}- />- <CustomTooltip- trigger={- <Label htmlFor="dateOfServiceFieldIsVisible">- Show in PDF- </Label>- }- content='Show the "Date of sales/of executing the service" field in the PDF'- />- </div>+ <div className="inline-flex items-center gap-2">+ <Controller+ name="dateOfServiceFieldIsVisible"+ control={control}+ render={({ field: { value, onChange, ...field } }) => {+ return (+ <Switch+ {...field}+ id="dateOfServiceFieldIsVisible"+ data-testid="dateOfServiceFieldIsVisible"+ checked={value}+ onCheckedChange={onChange}+ size="sm"+ aria-label='Show the "Date of sales/of executing the service" field in the PDF'+ />+ );+ }}+ />+ <CustomTooltip+ trigger={+ <Label htmlFor="dateOfServiceFieldIsVisible">+ Show in PDF+ </Label>+ }+ content='Show the "Date of sales/of executing the service" field in the PDF'+ /></div>- <Controller- name="dateOfServiceLabelText"- control={control}- render={({ field }) => {- return (- <Textarea- {...field}- id="dateOfServiceLabelText"- rows={2}- placeholder="Enter date of sales (Service period end) PDF label"- className={cn(- "block w-full",- inputErrorClassName(!!errors.dateOfServiceLabelText),- )}- />- );- }}- />- {errors.dateOfServiceLabelText ? (- <ErrorMessage>- {errors.dateOfServiceLabelText.message}- </ErrorMessage>- ) : null}- {!isDefaultDateOfServiceLabel ? (- <InputHelperMessage>- <ButtonHelper- onClick={() => {- setValue(- "dateOfServiceLabelText",- defaultDateOfServiceLabel,- );- }}- >- Reset to default ("{defaultDateOfServiceLabel}")- </ButtonHelper>- </InputHelperMessage>- ) : null}</div>+ <Controller+ name="dateOfServiceLabelText"+ control={control}+ render={({ field }) => {+ return (+ <Textarea+ {...field}+ id="dateOfServiceLabelText"+ rows={2}+ placeholder="Enter date of sales (Service period end) PDF label"+ className={cn(+ "block w-full",+ inputErrorClassName(!!errors.dateOfServiceLabelText),+ )}+ />+ );+ }}+ />+ {errors.dateOfServiceLabelText ? (+ <ErrorMessage>+ {errors.dateOfServiceLabelText.message}+ </ErrorMessage>+ ) : null}+ {!isDefaultDateOfServiceLabel ? (+ <InputHelperMessage>+ <ButtonHelper+ onClick={() => {+ setValue(+ "dateOfServiceLabelText",+ defaultDateOfServiceLabel,+ );+ }}+ >+ Reset to default ("{defaultDateOfServiceLabel}")+ </ButtonHelper>+ </InputHelperMessage>+ ) : null}</div>) : null}</fieldset>@@ -1069,9 +1253,12 @@ export const GeneralInformation = memo(function GeneralInformation({isMobile={isMobile}/>) : null}+ </FormGroup>+ {/* HEADER & BRANDING */}+ <FormGroup title="Header & Branding">{/* Header Notes - Purpose is to add a custom text to the header of the invoice */}- <div>+ <div className={FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME}><div className="relative mb-2 flex items-center justify-between"><Label htmlFor={`invoiceType`} className="">Header Notes@@ -1185,6 +1372,28 @@ export const GeneralInformation = memo(function GeneralInformation({) : null}</div>+ {/* Top line color - Only for Stripe template */}+ {template === "stripe" ? (+ <div data-testid="stripe-top-line-color">+ <Controller+ name="stripeTopLineColor"+ control={control}+ render={({ field }) => {+ return (+ <StripeTopLineColorPicker+ value={field.value}+ onChange={field.onChange}+ hasError={!!errors.stripeTopLineColor}+ />+ );+ }}+ />+ {errors.stripeTopLineColor ? (+ <ErrorMessage>{errors.stripeTopLineColor.message}</ErrorMessage>+ ) : null}+ </div>+ ) : null}+{/* Pay Online URL - Only for Stripe template */}{template === "stripe" ? (<div className="">@@ -1213,13 +1422,94 @@ export const GeneralInformation = memo(function GeneralInformation({<ErrorMessage>{errors.stripePayOnlineUrl.message}</ErrorMessage>) : (<InputHelperMessage>- Enter your payment URL. This adds a "Pay Online"- button to the PDF invoice.+ Adds a "Pay Online" button to the PDF.</InputHelperMessage>)}</div>) : null}- </div>+ </FormGroup></div>);});++interface FieldWarningProps {+ /** What is off, in two or three words ("Not today", "Before date of issue"). */+ message: string;+ /** The value the fix sets, as the PDF will show it. */+ fixValue: string;+ /** The fix button's accessible name, which also says which field it sets. */+ fixLabel: string;+ onFix: () => void;+}++/**+ * The amber line under a field that is out of date or out of order. The wording stays the+ * same however far off the value is (last month, last year, next month): the field shows+ * the old value and the fix button the new one, year included, so the message never has to.+ */+function FieldWarning({+ message,+ fixValue,+ fixLabel,+ onFix,+}: FieldWarningProps) {+ return (+ <InputHelperMessage>+ {/* stacked rather than side by side: in the half-width columns the fix would wrap+ onto its own line anyway, and a separator left hanging at the end reads worse */}+ <span className="flex items-center text-amber-800">+ <AlertIcon />+ {message}+ </span>+ <ButtonHelper+ aria-label={fixLabel}+ // tapped straight from the focused input above it, where Safari would otherwise+ // retarget the click; see the same note in `stale-dates-banner.tsx`+ onMouseDown={(event) => {+ event.preventDefault();+ }}+ onClick={onFix}+ >+ Use {fixValue}+ </ButtonHelper>+ </InputHelperMessage>+ );+}++/**+ * One titled group of the section. A `fieldset`, so assistive tech (and the e2e suite)+ * can address each group by its title.+ */+function FormGroup({+ title,+ children,+}: {+ title: string;+ children: React.ReactNode;+}) {+ return (+ <fieldset className="min-w-0 space-y-4 border-b border-zinc-200 pb-5 last:border-b-0 last:pb-0">+ <legend className="text-sm font-semibold text-zinc-900">{title}</legend>+ {children}+ </fieldset>+ );+}++/** A titled part of a {@link FormGroup}, set apart from what comes before it by a rule. */+function SubGroup({+ title,+ children,+}: {+ title: string;+ children: React.ReactNode;+}) {+ return (+ <div className="space-y-4 border-t border-zinc-200 pt-4">+ <h3 className="text-sm font-semibold text-zinc-900">{title}</h3>+ {children}+ </div>+ );+}++/** One-click payment terms offered under "Payment due", in days after the date of issue. */+const PAYMENT_TERM_DAYS = [7, 14, 30] as const;diff --git a/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsx b/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsxindex 6db92fc..ce0bf31 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsx@@ -8,9 +8,13 @@ import {type UseFieldArrayAppend,type UseFormGetValues,type UseFormSetValue,+ useWatch,} from "react-hook-form";-import { inputErrorClassName } from "@/app/(main)/(app)/components/invoice-form/common";+import {+ hiddenInPdfClassName,+ inputErrorClassName,+} from "@/app/(main)/(app)/components/invoice-form/common";import { DeleteIconButton } from "@/app/(main)/(app)/components/invoice-form/sections/components/delete-icon-button";import {DeleteInvoiceItemDialog,@@ -83,6 +87,53 @@ export const InvoiceItems = memo(function InvoiceItems({const deleteTriggerRef = useRef<HTMLButtonElement | null>(null);const hasReachedItemLimit = fields.length >= MAX_INVOICE_ITEMS;+ // the first item's switches show or hide a column for every item, so each item's field+ // is faded when its column is left out of the PDF+ const [+ isNameVisible,+ isTypeOfGTUVisible,+ isAmountVisible,+ isUnitVisible,+ isNetPriceVisible,+ isVatVisible,+ isNetAmountVisible,+ isVatAmountVisible,+ isPreTaxAmountVisible,+ ] = useWatch({+ control,+ name: [+ "items.0.nameFieldIsVisible",+ "items.0.typeOfGTUFieldIsVisible",+ "items.0.amountFieldIsVisible",+ "items.0.unitFieldIsVisible",+ "items.0.netPriceFieldIsVisible",+ "items.0.vatFieldIsVisible",+ "items.0.netAmountFieldIsVisible",+ "items.0.vatAmountFieldIsVisible",+ "items.0.preTaxAmountFieldIsVisible",+ ],+ });+ // most column switches exist on the default template only; the Stripe one prints them all+ const isDefaultTemplate = template === "default";++ const isNameHidden = isDefaultTemplate && !isNameVisible;++ const isTypeOfGTUHidden = isDefaultTemplate && !isTypeOfGTUVisible;++ const isAmountHidden = isDefaultTemplate && !isAmountVisible;++ const isUnitHidden = !isUnitVisible;++ const isNetPriceHidden = isDefaultTemplate && !isNetPriceVisible;++ const isVatHidden = !isVatVisible;++ const isNetAmountHidden = isDefaultTemplate && !isNetAmountVisible;++ const isVatAmountHidden = isDefaultTemplate && !isVatAmountVisible;++ const isPreTaxAmountHidden = isDefaultTemplate && !isPreTaxAmountVisible;+return (<>{fields.map((field, index) => {@@ -116,7 +167,7 @@ export const InvoiceItems = memo(function InvoiceItems({) : null}<Legend>Item {index + 1}</Legend><div className="relative mb-8 space-y-4">- <div>+ <div className={hiddenInPdfClassName(isNameHidden)}>{/* Invoice Item Name */}<div className="mb-2 flex items-center justify-between"><Label htmlFor={`itemName${index}`} className="">@@ -180,7 +231,7 @@ export const InvoiceItems = memo(function InvoiceItems({{/* Invoice Item Type of GTU - Only show for default template */}{template === "default" ? (- <div>+ <div className={hiddenInPdfClassName(isTypeOfGTUHidden)}><div className="mb-2 flex items-center justify-between"><Label htmlFor={`itemTypeOfGTU${index}`} className="">Type of GTU@@ -247,7 +298,7 @@ export const InvoiceItems = memo(function InvoiceItems({) : null}{/* Invoice Item Amount */}- <div>+ <div className={hiddenInPdfClassName(isAmountHidden)}><div className="mb-2 flex items-center justify-between"><Label htmlFor={`itemAmount${index}`} className="">Amount (Quantity)@@ -327,7 +378,7 @@ export const InvoiceItems = memo(function InvoiceItems({</div>{/* Invoice Item Unit */}- <div>+ <div className={hiddenInPdfClassName(isUnitHidden)}><div className="mb-2 flex items-center justify-between"><Label htmlFor={`itemUnit${index}`} className="">Unit@@ -389,7 +440,7 @@ export const InvoiceItems = memo(function InvoiceItems({</div>{/* Invoice Item Net Price */}- <div>+ <div className={hiddenInPdfClassName(isNetPriceHidden)}><div className="mb-2 flex items-center justify-between"><Label htmlFor={`itemNetPrice${index}`} className="">Net Price (Rate or Unit Price)@@ -502,7 +553,12 @@ export const InvoiceItems = memo(function InvoiceItems({/>{/* Invoice Item Tax Settings */}- <fieldset className="rounded-md border px-4 pb-4">+ <fieldset+ className={cn(+ "rounded-md border px-4 pb-4",+ hiddenInPdfClassName(isVatHidden),+ )}+ ><legend className="text-base font-semibold lg:text-lg">Tax Settings</legend>@@ -606,7 +662,7 @@ export const InvoiceItems = memo(function InvoiceItems({</fieldset>{/* Invoice Item Net Amount */}- <div>+ <div className={hiddenInPdfClassName(isNetAmountHidden)}><div className="mb-2 flex items-center justify-between"><Label htmlFor={`itemNetAmount${index}`} className="">Net Amount@@ -681,7 +737,7 @@ export const InvoiceItems = memo(function InvoiceItems({</div>{/* Invoice Item Tax Amount (calculated automatically - read only) */}- <div>+ <div className={hiddenInPdfClassName(isVatAmountHidden)}><div className="mb-2 flex items-center justify-between"><Label htmlFor={`itemVatAmount${index}`} className="">{taxLabelText} Amount@@ -756,7 +812,7 @@ export const InvoiceItems = memo(function InvoiceItems({</div>{/* Pre-tax Amount field (calculated automatically - read only) */}- <div>+ <div className={hiddenInPdfClassName(isPreTaxAmountHidden)}><div className="mb-2 flex items-center justify-between"><Label htmlFor={`itemPreTaxAmount${index}`} className="">Pre-tax Amountdiff --git a/src/app/(main)/(app)/components/invoice-form/sections/seller-information.tsx b/src/app/(main)/(app)/components/invoice-form/sections/seller-information.tsxindex 7d1b4c9..b2c6bcf 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/seller-information.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/seller-information.tsx@@ -1,4 +1,3 @@-import { Info } from "lucide-react";import { memo, useState } from "react";import {type Control,@@ -7,7 +6,11 @@ import {type UseFormSetValue,} from "react-hook-form";-import { inputErrorClassName } from "@/app/(main)/(app)/components/invoice-form/common";+import {+ FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME,+ inputErrorClassName,+} from "@/app/(main)/(app)/components/invoice-form/common";+import { SavedContactCard } from "@/app/(main)/(app)/components/invoice-form/sections/components/contact-fields";import { SellerManagement } from "@/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-management";import { type InvoiceData, type SellerData } from "@/app/schema";import { AccordionContent } from "@/components/ui/accordion";@@ -70,397 +73,371 @@ export const SellerInformation = memo(function SellerInformation({/></div><AccordionContent className="">- <fieldset className="mt-5 space-y-4" disabled={isSellerSelected}>- {isSellerSelected ? (- <div- className="flex gap-2 rounded-md border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-800 shadow-md shadow-blue-200/10"- data-testid="seller-locked-banner"- >- <Info className="mt-0.5 size-4 shrink-0" aria-hidden="true" />- <p className="">- To modify seller details, click the{" "}- <span className="font-semibold">Edit seller</span> button- (pencil icon) next to the dropdown above.- </p>+ {isSellerSelected ? (+ <div className="mt-5">+ <SavedContactCard control={control} party="seller" />+ </div>+ ) : (+ <fieldset className="mt-5 space-y-4">+ <div>+ <Label htmlFor="sellerName" className="mb-1">+ Name (Required)+ </Label>+ <Controller+ name="seller.name"+ control={control}+ render={({ field }) => {+ return (+ <Textarea+ {...field}+ id="sellerName"+ rows={3}+ className={inputErrorClassName(!!errors.seller?.name)}+ />+ );+ }}+ />+ {errors.seller?.name ? (+ <ErrorMessage>{errors.seller.name.message}</ErrorMessage>+ ) : null}</div>- ) : null}- <div>- <Label htmlFor="sellerName" className="mb-1">- Name (Required)- </Label>- <Controller- name="seller.name"- control={control}- render={({ field }) => {- return (- <Textarea- {...field}- id="sellerName"- rows={3}- className={inputErrorClassName(!!errors.seller?.name)}- />- );- }}- />- {errors.seller?.name ? (- <ErrorMessage>{errors.seller.name.message}</ErrorMessage>- ) : null}- </div>+ <div>+ <Label htmlFor="sellerAddress" className="mb-1">+ Address (Required)+ </Label>+ <Controller+ name="seller.address"+ control={control}+ render={({ field }) => {+ return (+ <Textarea+ {...field}+ id="sellerAddress"+ rows={3}+ className={inputErrorClassName(!!errors.seller?.address)}+ />+ );+ }}+ />+ {errors.seller?.address ? (+ <ErrorMessage>{errors.seller.address.message}</ErrorMessage>+ ) : null}+ </div>- <div>- <Label htmlFor="sellerAddress" className="mb-1">- Address (Required)- </Label>- <Controller- name="seller.address"- control={control}- render={({ field }) => {- return (- <Textarea- {...field}- id="sellerAddress"- rows={3}- className={inputErrorClassName(!!errors.seller?.address)}- />- );- }}- />- {errors.seller?.address ? (- <ErrorMessage>{errors.seller.address.message}</ErrorMessage>- ) : null}- </div>+ <div className={FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME}>+ <fieldset className="rounded-md border px-4 pb-4">+ <legend className="text-base font-semibold lg:text-lg">+ Seller Tax Number+ </legend>++ <div className="mb-2 flex items-center justify-end">+ <div className="inline-flex items-center gap-2">+ <Controller+ name="seller.vatNoFieldIsVisible"+ control={control}+ render={({ field: { value, onChange, ...field } }) => {+ return (+ <Switch+ {...field}+ id="sellerVatNoFieldIsVisible"+ checked={value}+ onCheckedChange={onChange}+ size="sm"+ data-testid="sellerVatNoFieldIsVisible"+ aria-label="Show the 'Seller Tax Number' Field in the PDF"+ />+ );+ }}+ />+ <CustomTooltip+ trigger={+ <Label htmlFor="sellerVatNoFieldIsVisible">+ Show in PDF+ </Label>+ }+ content={"Show the 'Seller Tax Number' Field in the PDF"}+ />+ </div>+ </div>- <div>- <fieldset className="rounded-md border px-4 pb-4">- <legend className="text-base font-semibold lg:text-lg">- Seller Tax Number- </legend>+ <div className="space-y-4">+ <div>+ <Label htmlFor="sellerVatNoLabel">Label</Label>+ <Controller+ name="seller.vatNoLabelText"+ control={control}+ render={({ field }) => {+ return (+ <Input+ {...field}+ type="text"+ id="sellerVatNoLabel"+ placeholder="Enter Tax number label"+ className={cn(+ "mt-1 block w-full",+ inputErrorClassName(+ !!errors.seller?.vatNoLabelText,+ ),+ )}+ />+ );+ }}+ />+ {errors.seller?.vatNoLabelText ? (+ <ErrorMessage>+ {errors.seller.vatNoLabelText.message}+ </ErrorMessage>+ ) : null}+ {!errors.seller?.vatNoLabelText ? (+ <InputHelperMessage>+ Set a custom label (e.g. VAT no, Tax no, etc.)+ </InputHelperMessage>+ ) : null}+ </div>++ <div>+ <Label htmlFor="sellerVatNo">Value</Label>+ <Controller+ name="seller.vatNo"+ control={control}+ render={({ field }) => {+ return (+ <Input+ {...field}+ id="sellerVatNo"+ type="text"+ placeholder="Enter Tax number value"+ className={cn(+ "mt-1 block w-full",+ inputErrorClassName(!!errors.seller?.vatNo),+ )}+ />+ );+ }}+ />+ {errors.seller?.vatNo ? (+ <ErrorMessage>{errors.seller.vatNo.message}</ErrorMessage>+ ) : null}+ </div>+ </div>+ </fieldset>+ </div>++ {/* Email */}+ <div className={FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME}>+ <div className="relative mb-2 flex items-center justify-between">+ <Label htmlFor="sellerEmail">Email</Label>- <div className="mb-2 flex items-center justify-end"><div className="inline-flex items-center gap-2"><Controller- name="seller.vatNoFieldIsVisible"+ name="seller.emailFieldIsVisible"control={control}render={({ field: { value, onChange, ...field } }) => {return (<Switch{...field}- id="sellerVatNoFieldIsVisible"+ id="sellerEmailFieldIsVisible"checked={value}onCheckedChange={onChange}size="sm"- data-testid="sellerVatNoFieldIsVisible"- aria-label="Show the 'Seller Tax Number' Field in the PDF"+ data-testid="sellerEmailFieldIsVisible"+ aria-label="Show the 'Email' field in the PDF"/>);}}/><CustomTooltiptrigger={- <Label htmlFor="sellerVatNoFieldIsVisible">+ <Label htmlFor="sellerEmailFieldIsVisible">Show in PDF</Label>}- content={- isSellerSelected- ? null- : "Show the 'Seller Tax Number' Field in the PDF"- }+ content={"Show the 'Email' field in the PDF"}/></div></div>+ <Controller+ name="seller.email"+ control={control}+ render={({ field }) => {+ return (+ <Input+ {...field}+ id="sellerEmail"+ type="email"+ className={inputErrorClassName(!!errors.seller?.email)}+ />+ );+ }}+ />+ {errors.seller?.email ? (+ <ErrorMessage>{errors.seller.email.message}</ErrorMessage>+ ) : null}+ </div>++ {/* Account Number */}+ <div className={FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME}>+ <div className="relative mb-2 flex items-center justify-between">+ <Label htmlFor="sellerAccountNumber">Account Number</Label>- <div className="space-y-4">- <div>- <Label htmlFor="sellerVatNoLabel">Label</Label>+ <div className="inline-flex items-center gap-2"><Controller- name="seller.vatNoLabelText"+ name="seller.accountNumberFieldIsVisible"control={control}- render={({ field }) => {+ render={({ field: { value, onChange, ...field } }) => {return (- <Input+ <Switch{...field}- type="text"- id="sellerVatNoLabel"- placeholder="Enter Tax number label"- className={cn(- "mt-1 block w-full",- inputErrorClassName(- !!errors.seller?.vatNoLabelText,- ),- )}+ id="sellerAccountNumberFieldIsVisible"+ checked={value}+ onCheckedChange={onChange}+ size="sm"+ data-testid="sellerAccountNumberFieldIsVisible"+ aria-label="Show the 'Account Number' Field in the PDF"/>);}}/>- {errors.seller?.vatNoLabelText ? (- <ErrorMessage>- {errors.seller.vatNoLabelText.message}- </ErrorMessage>- ) : null}- {!errors.seller?.vatNoLabelText ? (- <InputHelperMessage>- Set a custom label (e.g. VAT no, Tax no, etc.)- </InputHelperMessage>- ) : null}+ <CustomTooltip+ trigger={+ <Label htmlFor="sellerAccountNumberFieldIsVisible">+ Show in PDF+ </Label>+ }+ content={"Show the 'Account Number' Field in the PDF"}+ /></div>+ </div>+ <Controller+ name="seller.accountNumber"+ control={control}+ render={({ field }) => {+ return (+ <Textarea+ {...field}+ id="sellerAccountNumber"+ rows={3}+ className={inputErrorClassName(+ !!errors.seller?.accountNumber,+ )}+ />+ );+ }}+ />+ {errors.seller?.accountNumber ? (+ <ErrorMessage>+ {errors.seller.accountNumber.message}+ </ErrorMessage>+ ) : null}+ </div>++ {/* SWIFT/BIC */}+ <div className={FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME}>+ <div className="relative mb-2 flex items-center justify-between">+ <Label htmlFor="sellerSwiftBic">SWIFT/BIC</Label>- <div>- <Label htmlFor="sellerVatNo">Value</Label>+ <div className="inline-flex items-center gap-2"><Controller- name="seller.vatNo"+ name="seller.swiftBicFieldIsVisible"control={control}- render={({ field }) => {+ render={({ field: { value, onChange, ...field } }) => {return (- <Input+ <Switch{...field}- id="sellerVatNo"- type="text"- placeholder="Enter Tax number value"- className={cn(- "mt-1 block w-full",- inputErrorClassName(!!errors.seller?.vatNo),- )}+ id="sellerSwiftBicFieldIsVisible"+ checked={value}+ onCheckedChange={onChange}+ size="sm"+ data-testid="sellerSwiftBicFieldIsVisible"+ aria-label="Show the 'SWIFT/BIC' Field in the PDF"/>);}}/>- {errors.seller?.vatNo ? (- <ErrorMessage>{errors.seller.vatNo.message}</ErrorMessage>- ) : null}+ <CustomTooltip+ trigger={+ <Label htmlFor="sellerSwiftBicFieldIsVisible">+ Show in PDF+ </Label>+ }+ content={"Show the 'SWIFT/BIC' Field in the PDF"}+ /></div></div>- </fieldset>- </div>- {/* Email */}- <div>- <div className="relative mb-2 flex items-center justify-between">- <Label htmlFor="sellerEmail">Email</Label>-- <div className="inline-flex items-center gap-2">- <Controller- name="seller.emailFieldIsVisible"- control={control}- render={({ field: { value, onChange, ...field } }) => {- return (- <Switch- {...field}- id="sellerEmailFieldIsVisible"- checked={value}- onCheckedChange={onChange}- size="sm"- data-testid="sellerEmailFieldIsVisible"- aria-label="Show the 'Email' field in the PDF"- />- );- }}- />- <CustomTooltip- trigger={- <Label htmlFor="sellerEmailFieldIsVisible">- Show in PDF- </Label>- }- content={- isSellerSelected- ? null- : "Show the 'Email' field in the PDF"- }- />- </div>+ <Controller+ name="seller.swiftBic"+ control={control}+ render={({ field }) => {+ return (+ <Textarea+ {...field}+ id="sellerSwiftBic"+ rows={3}+ className={inputErrorClassName(!!errors.seller?.swiftBic)}+ />+ );+ }}+ />+ {errors.seller?.swiftBic ? (+ <ErrorMessage>{errors.seller.swiftBic.message}</ErrorMessage>+ ) : null}</div>- <Controller- name="seller.email"- control={control}- render={({ field }) => {- return (- <Input- {...field}- id="sellerEmail"- type="email"- className={inputErrorClassName(!!errors.seller?.email)}- />- );- }}- />- {errors.seller?.email ? (- <ErrorMessage>{errors.seller.email.message}</ErrorMessage>- ) : null}- </div>-- {/* Account Number */}- <div>- <div className="relative mb-2 flex items-center justify-between">- <Label htmlFor="sellerAccountNumber">Account Number</Label>- <div className="inline-flex items-center gap-2">- <Controller- name="seller.accountNumberFieldIsVisible"- control={control}- render={({ field: { value, onChange, ...field } }) => {- return (- <Switch- {...field}- id="sellerAccountNumberFieldIsVisible"- checked={value}- onCheckedChange={onChange}- size="sm"- data-testid="sellerAccountNumberFieldIsVisible"- aria-label="Show the 'Account Number' Field in the PDF"- />- );- }}- />- <CustomTooltip- trigger={- <Label htmlFor="sellerAccountNumberFieldIsVisible">- Show in PDF- </Label>- }- content={- isSellerSelected- ? null- : "Show the 'Account Number' Field in the PDF"- }- />- </div>- </div>- <Controller- name="seller.accountNumber"- control={control}- render={({ field }) => {- return (- <Textarea- {...field}- id="sellerAccountNumber"- rows={3}- className={inputErrorClassName(- !!errors.seller?.accountNumber,- )}+ {/* Notes */}+ <div className={FADE_WHEN_HIDDEN_IN_PDF_CLASS_NAME}>+ <div className="relative mb-2 flex items-center justify-between">+ <Label htmlFor="sellerNotes">Notes</Label>+ <div className="inline-flex items-center gap-2">+ <Controller+ name="seller.notesFieldIsVisible"+ control={control}+ render={({ field: { value, onChange, ...field } }) => {+ return (+ <Switch+ {...field}+ id="sellerNotesFieldIsVisible"+ checked={value}+ onCheckedChange={onChange}+ size="sm"+ data-testid="sellerNotesInvoiceFormFieldVisibilitySwitch"+ aria-label="Show the 'Notes' field in the PDF"+ />+ );+ }}/>- );- }}- />- {errors.seller?.accountNumber ? (- <ErrorMessage>{errors.seller.accountNumber.message}</ErrorMessage>- ) : null}- </div>-- {/* SWIFT/BIC */}- <div>- <div className="relative mb-2 flex items-center justify-between">- <Label htmlFor="sellerSwiftBic">SWIFT/BIC</Label>-- <div className="inline-flex items-center gap-2">- <Controller- name="seller.swiftBicFieldIsVisible"- control={control}- render={({ field: { value, onChange, ...field } }) => {- return (- <Switch- {...field}- id="sellerSwiftBicFieldIsVisible"- checked={value}- onCheckedChange={onChange}- size="sm"- data-testid="sellerSwiftBicFieldIsVisible"- aria-label="Show the 'SWIFT/BIC' Field in the PDF"- />- );- }}- />- <CustomTooltip- trigger={- <Label htmlFor="sellerSwiftBicFieldIsVisible">- Show in PDF- </Label>- }- content={- isSellerSelected- ? null- : "Show the 'SWIFT/BIC' Field in the PDF"- }- />- </div>- </div>-- <Controller- name="seller.swiftBic"- control={control}- render={({ field }) => {- return (- <Textarea- {...field}- id="sellerSwiftBic"- rows={3}- className={inputErrorClassName(!!errors.seller?.swiftBic)}+ <CustomTooltip+ trigger={+ <Label htmlFor="sellerNotesFieldIsVisible">+ Show in PDF+ </Label>+ }+ content={"Show the 'Notes' field in the PDF"}/>- );- }}- />- {errors.seller?.swiftBic ? (- <ErrorMessage>{errors.seller.swiftBic.message}</ErrorMessage>- ) : null}- </div>-- {/* Notes */}- <div>- <div className="relative mb-2 flex items-center justify-between">- <Label htmlFor="sellerNotes">Notes</Label>- <div className="inline-flex items-center gap-2">- <Controller- name="seller.notesFieldIsVisible"- control={control}- render={({ field: { value, onChange, ...field } }) => {- return (- <Switch- {...field}- id="sellerNotesFieldIsVisible"- checked={value}- onCheckedChange={onChange}- size="sm"- data-testid="sellerNotesInvoiceFormFieldVisibilitySwitch"- aria-label="Show the 'Notes' field in the PDF"- />- );- }}- />- <CustomTooltip- trigger={- <Label htmlFor="sellerNotesFieldIsVisible">- Show in PDF- </Label>- }- content={- isSellerSelected- ? null- : "Show the 'Notes' field in the PDF"- }- />+ </div></div>- </div>- <Controller- name="seller.notes"- control={control}- render={({ field }) => {- return (- <Textarea- {...field}- id="sellerNotes"- rows={3}- className={inputErrorClassName(!!errors.seller?.notes)}- />- );- }}- />- {errors.seller?.notes ? (- <ErrorMessage>{errors.seller.notes.message}</ErrorMessage>- ) : null}- </div>- </fieldset>+ <Controller+ name="seller.notes"+ control={control}+ render={({ field }) => {+ return (+ <Textarea+ {...field}+ id="sellerNotes"+ rows={3}+ className={inputErrorClassName(!!errors.seller?.notes)}+ />+ );+ }}+ />+ {errors.seller?.notes ? (+ <ErrorMessage>{errors.seller.notes.message}</ErrorMessage>+ ) : null}+ </div>+ </fieldset>+ )}</AccordionContent></div>);diff --git a/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-stripe-template/index.tsx b/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-stripe-template/index.tsxindex ddc61bf..2a063b3 100644--- a/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-stripe-template/index.tsx+++ b/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-stripe-template/index.tsx@@ -13,7 +13,11 @@ import dayjs from "dayjs";import { InvoiceQRCode } from "@/app/(main)/(app)/components/invoice-templates/common/invoice-qr-code";import { formatCurrencyChunks } from "@/app/(main)/(app)/utils/format-currency";-import { type InvoiceData, resolveNumberFormatLocale } from "@/app/schema";+import {+ DEFAULT_STRIPE_TOP_LINE_COLOR,+ type InvoiceData,+ resolveNumberFormatLocale,+} from "@/app/schema";import { INVOICE_PDF_FONTS } from "@/config";import { StripeDueAmount } from "./stripe-due-amount";@@ -71,9 +75,8 @@ export const STRIPE_TEMPLATE_STYLES = StyleSheet.create({paddingBottom: 30, // to fix overlapping issues with the fixed footer https://github.com/diegomura/react-pdf/issues/774#issuecomment-560069810},- // Yellow header bar+ // Header bar, its color comes from the invoice (`stripeTopLineColor`)headerBar: {- backgroundColor: "#fbbf24", // Yellow color matching screenshotheight: 4,width: "100%",},@@ -336,8 +339,16 @@ export function StripeInvoicePdfTemplate({return (<Document title={invoiceDocTitle}><Page size={"LETTER"} style={STRIPE_TEMPLATE_STYLES.page}>- {/* Yellow header bar */}- <View style={STRIPE_TEMPLATE_STYLES.headerBar} />+ {/* Header bar, amber unless the invoice picked a color of its own */}+ <View+ style={[+ STRIPE_TEMPLATE_STYLES.headerBar,+ {+ backgroundColor:+ invoiceData.stripeTopLineColor ?? DEFAULT_STRIPE_TOP_LINE_COLOR,+ },+ ]}+ />{/* Main content */}<View style={STRIPE_TEMPLATE_STYLES.content}>diff --git a/src/app/(main)/(app)/utils/payment-terms.ts b/src/app/(main)/(app)/utils/payment-terms.tsnew file mode 100644index 0000000..8d1a93d--- /dev/null+++ b/src/app/(main)/(app)/utils/payment-terms.ts@@ -0,0 +1,45 @@+import dayjs from "dayjs";++/** The payment term a new invoice starts with, and the fallback when none can be read. */+export const DEFAULT_PAYMENT_TERM_DAYS = 14;++interface GetPaymentTermDaysArgs {+ /** The invoice's date of issue, as `YYYY-MM-DD`. */+ dateOfIssue: string;+ /** The invoice's payment due date, as `YYYY-MM-DD`. */+ paymentDue: string | undefined;+}++/**+ * How many days after the date of issue the invoice is due ("Due 7 days after issue").+ *+ * Falls back to {@link DEFAULT_PAYMENT_TERM_DAYS} when there is no term to keep: no due+ * date, or one before the date of issue.+ */+export function getPaymentTermDays({+ dateOfIssue,+ paymentDue,+}: GetPaymentTermDaysArgs) {+ if (!paymentDue || !dateOfIssue) {+ return DEFAULT_PAYMENT_TERM_DAYS;+ }++ const days = dayjs(paymentDue).diff(dayjs(dateOfIssue), "day");++ return Number.isNaN(days) || days < 0 ? DEFAULT_PAYMENT_TERM_DAYS : days;+}++interface GetPaymentDueForTermArgs {+ /** The new date of issue, anything dayjs can parse. */+ dateOfIssue: dayjs.ConfigType;+ /** The payment term to keep, in days. */+ paymentTermDays: number;+}++/** The payment due date, as `YYYY-MM-DD`, for a date of issue and a payment term. */+export function getPaymentDueForTerm({+ dateOfIssue,+ paymentTermDays,+}: GetPaymentDueForTermArgs) {+ return dayjs(dateOfIssue).add(paymentTermDays, "days").format("YYYY-MM-DD");+}diff --git a/src/app/schema/__tests__/stripe-top-line-color.test.ts b/src/app/schema/__tests__/stripe-top-line-color.test.tsnew file mode 100644index 0000000..c10586c--- /dev/null+++ b/src/app/schema/__tests__/stripe-top-line-color.test.ts@@ -0,0 +1,48 @@+import { assert, describe, expect, it } from "vitest";++import { invoiceSchema } from "@/app/schema";+import { MOCK_INVOICE_DATA } from "@/utils/__tests__/data";++describe("invoiceSchema stripeTopLineColor", () => {+ it("leaves an invoice that never picked a color without one", () => {+ const result = invoiceSchema.safeParse({+ ...MOCK_INVOICE_DATA,+ stripeTopLineColor: undefined,+ });++ assert(result.success);+ expect(result.data.stripeTopLineColor).toBeUndefined();+ });++ it.each([+ ["#635bff", "#635bff"],+ ["#E11D48", "#e11d48"],+ // the default, spelled in uppercase, still matches the picker's amber preset+ ["#FBBF24", "#fbbf24"],+ ])("accepts the hex color %s as %s", (color, expectedColor) => {+ const result = invoiceSchema.safeParse({+ ...MOCK_INVOICE_DATA,+ stripeTopLineColor: color,+ });++ assert(result.success);+ expect(result.data.stripeTopLineColor).toBe(expectedColor);+ });++ it.each(["#fa0", "635bff", "red", "#12345g", "rgb(0, 0, 0)"])(+ "rejects %s",+ (color) => {+ const result = invoiceSchema.safeParse({+ ...MOCK_INVOICE_DATA,+ stripeTopLineColor: color,+ });++ assert(!result.success);+ expect(result.error.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ path: ["stripeTopLineColor"] }),+ ]),+ );+ },+ );+});diff --git a/src/app/schema/index.ts b/src/app/schema/index.tsindex fb70368..3c7f3e7 100644--- a/src/app/schema/index.ts+++ b/src/app/schema/index.ts@@ -662,6 +662,15 @@ export const TEMPLATE_TO_LABEL = {export type TemplateLabels =(typeof TEMPLATE_TO_LABEL)[keyof typeof TEMPLATE_TO_LABEL];+/**+ * The amber bar the Stripe template has always drawn across the top of the page, used+ * whenever an invoice has not picked a color of its own.+ */+export const DEFAULT_STRIPE_TOP_LINE_COLOR = "#fbbf24";++/** A six-digit `#rrggbb` hex color, the only shape the color picker writes. */+const HEX_COLOR_REGEX = /^#[\da-f]{6}$/i;+/*** Every language an invoice can be written in.*@@ -758,8 +767,10 @@ export const LANGUAGE_TO_LABEL = {*/export const LANGUAGE_TO_LABEL_WITH_REGION = {...LANGUAGE_TO_LABEL,- pt: "Portuguese (Portugal)",- "pt-BR": "Portuguese (Brazil)",+ // the region as its two-letter code, to keep the names short in the language and number+ // format pickers+ pt: "Portuguese (PT)",+ "pt-BR": "Portuguese (BR)",} as const satisfies Record<SupportedLanguages, string>;/**@@ -1630,6 +1641,26 @@ export const invoiceObjectSchema = z.object({.optional().describe("Stripe template specific field. URL field for payment link"),+ /**+ * Color of the bar across the top of the Stripe template's page.+ *+ * Deliberately not `.default()`ed, like `numberFormatLocale`: an invoice carries it only+ * once someone picks a color, so share links and `localStorage` entries that predate the+ * setting stay as they are, and the template falls back to+ * {@link DEFAULT_STRIPE_TOP_LINE_COLOR}.+ */+ stripeTopLineColor: z+ .string()+ .trim()+ // the picker and its presets speak lowercase, so `#FBBF24` from a hand-made link still+ // reads as the default amber rather than a custom color+ .toLowerCase()+ .regex(HEX_COLOR_REGEX, "Color must be a hex value like #fbbf24")+ .optional()+ .describe(+ "Stripe template specific field. Hex color of the line across the top of the page",+ ),+notes: z.string().max(3500, "Notes must not exceed 3500 characters")diff --git a/src/components/ui/input.tsx b/src/components/ui/input.tsxindex 6f9e3af..dee89df 100644--- a/src/components/ui/input.tsx+++ b/src/components/ui/input.tsx@@ -11,7 +11,10 @@ const Input = React.memo(autoComplete="off"className={cn("h-8 w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-slate-950 shadow-sm shadow-black/5 transition-shadow placeholder:text-slate-500/70 focus-visible:border-indigo-500 focus-visible:ring focus-visible:ring-indigo-200 focus-visible:ring-opacity-50 disabled:cursor-not-allowed disabled:text-black disabled:opacity-55 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-50 dark:placeholder:text-slate-400/70 dark:focus-visible:border-slate-300 dark:focus-visible:ring-slate-300/20 [&[aria-readonly=true]]:cursor-not-allowed [&[aria-readonly=true]]:bg-slate-50 [&[aria-readonly=true]]:opacity-50 [&[aria-readonly=true]]:dark:bg-slate-900",- type === "date" && "w-auto",+ // iOS Safari and Chrome draw a native date field that ignores `h-8`, centers the+ // date and keeps its own width; without that look it sizes like the other inputs+ type === "date" &&+ "min-w-0 appearance-none [&::-webkit-date-and-time-value]:text-left",type === "search" &&"[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none [&::-webkit-search-results-button]:appearance-none [&::-webkit-search-results-decoration]:appearance-none",type === "file" &&diff --git a/src/components/ui/switch.tsx b/src/components/ui/switch.tsxindex 699d0c8..8884ce7 100644--- a/src/components/ui/switch.tsx+++ b/src/components/ui/switch.tsx@@ -21,19 +21,23 @@ interface SwitchProps extends React.ComponentProps<* and on the first toggle after load one stale repaint sometimes reached the screen* just after the animation ended (knob already off, track still the dark checked color).* An `opacity` fade runs on the compositor with no repaint, like the thumb's transform.+ *+ * `sm` grows a little (36x22) below `md`, where it is tapped rather than clicked, and an+ * `after:` layer reaches 8px past the edge on every side (10px from inside the 2px border),+ * so a tap just beside it still lands.*/function Switch({ className, size = "default", ...props }: SwitchProps) {return (<SwitchPrimitives.Rootdata-size={size}className={cn(- "focus-visible:outline-ring/70 group/switch peer relative inline-flex h-6 w-10 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent bg-slate-200 outline-offset-2 before:absolute before:-inset-0.5 before:rounded-full before:bg-slate-900 before:opacity-0 before:transition-opacity before:duration-200 before:ease-out-strong focus-visible:outline focus-visible:outline-2 disabled:cursor-not-allowed disabled:opacity-50 data-[size=sm]:h-5 data-[size=sm]:w-8 data-[state=checked]:before:opacity-100 dark:bg-slate-800 dark:before:bg-slate-50",+ "focus-visible:outline-ring/70 group/switch peer relative inline-flex h-6 w-10 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent bg-slate-200 outline-offset-2 before:absolute before:-inset-0.5 before:rounded-full before:bg-slate-900 before:opacity-0 before:transition-opacity before:duration-200 before:ease-out-strong after:absolute after:-inset-2.5 focus-visible:outline focus-visible:outline-2 disabled:cursor-not-allowed disabled:opacity-50 data-[size=sm]:h-5 data-[size=sm]:w-8 data-[state=checked]:before:opacity-100 dark:bg-slate-800 dark:before:bg-slate-50 max-md:data-[size=sm]:h-[22px] max-md:data-[size=sm]:w-9",className,)}{...props}>{/* travel = thumb width minus the 2px border on each side, so it fits both sizes */}- <SwitchPrimitives.Thumb className="pointer-events-none relative block size-5 rounded-full bg-white shadow-sm shadow-black/5 ring-0 transition-transform duration-200 ease-out-strong data-[state=checked]:translate-x-[calc(100%-4px)] data-[state=unchecked]:translate-x-0 group-data-[size=sm]/switch:size-4 dark:bg-slate-950 rtl:data-[state=checked]:-translate-x-[calc(100%-4px)]" />+ <SwitchPrimitives.Thumb className="pointer-events-none relative block size-5 rounded-full bg-white shadow-sm shadow-black/5 ring-0 transition-transform duration-200 ease-out-strong data-[state=checked]:translate-x-[calc(100%-4px)] data-[state=unchecked]:translate-x-0 group-data-[size=sm]/switch:size-4 dark:bg-slate-950 max-md:group-data-[size=sm]/switch:size-[18px] rtl:data-[state=checked]:-translate-x-[calc(100%-4px)]" /></SwitchPrimitives.Root>);}diff --git a/src/utils/__tests__/data.ts b/src/utils/__tests__/data.tsindex 7f01b40..fefabda 100644--- a/src/utils/__tests__/data.ts+++ b/src/utils/__tests__/data.ts@@ -90,6 +90,7 @@ export const MOCK_INVOICE_DATA = {paymentMethodFieldIsVisible: true,paymentDue: "2024-01-29",stripePayOnlineUrl: "https://checkout.stripe.com/pay/cs_123",+ stripeTopLineColor: "#635bff",notes: "Thank you for your business",notesFieldIsVisible: true,diff --git a/src/utils/__tests__/url-compression.test.ts b/src/utils/__tests__/url-compression.test.tsindex 1b74879..42117e5 100644--- a/src/utils/__tests__/url-compression.test.ts+++ b/src/utils/__tests__/url-compression.test.ts@@ -67,6 +67,7 @@ describe("URL Compression Utilities", () => {"s","https://checkout.stripe.com/pay/cs_123",); // stripePayOnlineUrl+ expect(result).toHaveProperty("+", "#635bff"); // stripeTopLineColorexpect(result).toHaveProperty("t", "Thank you for your business"); // notesexpect(result).toHaveProperty("u", true); // notesFieldIsVisibleexpect(result).toHaveProperty("v", true); // personAuthorizedToReceiveFieldIsVisible@@ -250,6 +251,7 @@ describe("URL Compression Utilities", () => {"stripePayOnlineUrl","https://checkout.stripe.com/pay/cs_123",);+ expect(result).toHaveProperty("stripeTopLineColor", "#635bff");expect(result).toHaveProperty("notes", "Thank you for your business");expect(result).toHaveProperty("notesFieldIsVisible", true);expect(result).toHaveProperty(diff --git a/src/utils/url-compression.ts b/src/utils/url-compression.tsindex e31be97..d7f7fa9 100644--- a/src/utils/url-compression.ts+++ b/src/utils/url-compression.ts@@ -66,6 +66,7 @@ export const INVOICE_KEY_COMPRESSION_MAP = {paymentMethodFieldIsVisible: "q",paymentDue: "r",stripePayOnlineUrl: "s",+ stripeTopLineColor: "+",notes: "t",notesFieldIsVisible: "u",