Skip to content

Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.

feat: replaced window.confirm with alert discard dialog for buyer and seller management (#200)

Vlad Sazonauce1ea7169bd5
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index 8667dfd..af59371 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -8,6 +8,10 @@ concurrency:
group: e2e-${{ github.ref }}
cancel-in-progress: true
+permissions:
+ contents: read
+ pull-requests: read
+
jobs:
e2e:
# https://vercel.com/guides/how-can-i-run-end-to-end-tests-after-my-vercel-preview-deployment
@@ -91,6 +95,7 @@ jobs:
For more details, please check:
- GitHub Actions run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
${{ steps.pr-url.outputs.pr_url && format('- Pull Request: {0}', steps.pr-url.outputs.pr_url) }}
+ - Vercel deployment: ${{ github.event.deployment_status.environment_url }}
attachments: playwright-output/report/index.html
- name: ❌ Mark workflow failed on E2E Tests failure
diff --git a/.github/workflows/knip.yml b/.github/workflows/knip.yml
index 28a771b..b57918b 100644
--- a/.github/workflows/knip.yml
+++ b/.github/workflows/knip.yml
@@ -5,6 +5,10 @@ on:
pull_request:
branches: [main]
+permissions:
+ contents: read
+ pull-requests: read
+
jobs:
knip:
name: Run Knip
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index ca1bdc5..37f9f8c 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -5,6 +5,10 @@ on:
pull_request:
branches: [main]
+permissions:
+ contents: read
+ pull-requests: read
+
jobs:
lint:
name: Run linting
diff --git a/.github/workflows/type-check.yml b/.github/workflows/type-check.yml
index 943ce62..f149a51 100644
--- a/.github/workflows/type-check.yml
+++ b/.github/workflows/type-check.yml
@@ -5,6 +5,10 @@ on:
pull_request:
branches: [main]
+permissions:
+ contents: read
+ pull-requests: read
+
jobs:
type-check:
name: Run type check
diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml
index 74d85f9..8ff5d67 100644
--- a/.github/workflows/unit-tests.yml
+++ b/.github/workflows/unit-tests.yml
@@ -5,6 +5,10 @@ on:
pull_request:
branches: [main]
+permissions:
+ contents: read
+ pull-requests: read
+
jobs:
unit-tests:
name: Run unit tests
diff --git a/e2e/buyer.test.ts b/e2e/buyer.test.ts
index 9f93878..6449e79 100644
--- a/e2e/buyer.test.ts
+++ b/e2e/buyer.test.ts
@@ -620,7 +620,7 @@ test.describe("Buyer management", () => {
).toHaveValue(DEFAULT_BUYER_DATA.vatNo);
});
- test("pre-fill switch resets to off after dialog close and reopen", async ({
+ test("switches reset to defaults after dialog close and reopen", async ({
page,
}) => {
await page.getByRole("button", { name: "New Buyer" }).click();
@@ -629,11 +629,20 @@ test.describe("Buyer management", () => {
const prefillSwitch = manageBuyerDialog.getByRole("switch", {
name: "Pre-fill with values from the current invoice form",
});
+ const applyToInvoiceSwitch = manageBuyerDialog.getByRole("switch", {
+ name: "Apply to Current Invoice",
+ });
+ // Pre-fill switch defaults to off; toggle it on
await expect(prefillSwitch).not.toBeChecked();
await prefillSwitch.click();
await expect(prefillSwitch).toBeChecked();
+ // "Apply to Current Invoice" switch defaults to on; toggle it off
+ await expect(applyToInvoiceSwitch).toBeChecked();
+ await applyToInvoiceSwitch.click();
+ await expect(applyToInvoiceSwitch).not.toBeChecked();
+
// Close the dialog via Cancel
await manageBuyerDialog.getByRole("button", { name: "Cancel" }).click();
await expect(manageBuyerDialog).toBeHidden();
@@ -642,8 +651,9 @@ test.describe("Buyer management", () => {
await page.getByRole("button", { name: "New Buyer" }).click();
await expect(manageBuyerDialog).toBeVisible();
- // Pre-fill switch must be off and form must be empty
+ // Both switches must have reset to their defaults and form must be empty
await expect(prefillSwitch).not.toBeChecked();
+ await expect(applyToInvoiceSwitch).toBeChecked();
await expect(
manageBuyerDialog.getByRole("textbox", { name: "Name" }),
).toHaveValue("");
@@ -656,16 +666,12 @@ test.describe("Buyer management", () => {
const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
await expect(manageBuyerDialog).toBeVisible();
- // No changes made — Cancel should close immediately, no dialog fired
- let confirmFired = false;
- page.once("dialog", () => {
- confirmFired = true;
- });
-
await manageBuyerDialog.getByRole("button", { name: "Cancel" }).click();
await expect(manageBuyerDialog).toBeHidden();
- expect(confirmFired).toBe(false);
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeHidden();
});
test("clean form - X button closes without confirm", async ({ page }) => {
@@ -674,15 +680,13 @@ test.describe("Buyer management", () => {
const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
await expect(manageBuyerDialog).toBeVisible();
- let confirmFired = false;
- page.once("dialog", () => {
- confirmFired = true;
- });
-
await manageBuyerDialog.getByRole("button", { name: "Close" }).click();
await expect(manageBuyerDialog).toBeHidden();
- expect(confirmFired).toBe(false);
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+
+ await expect(confirmDialog).toBeHidden();
});
test("dirty form - Cancel - accept discards changes and closes", async ({
@@ -695,16 +699,28 @@ test.describe("Buyer management", () => {
.getByRole("textbox", { name: "Name" })
.fill("Unsaved Buyer");
- page.once("dialog", async (dialog) => {
- expect(dialog.type()).toBe("confirm");
- expect(dialog.message()).toBe(
- "You have unsaved changes in buyer details. Discard them?",
- );
- await dialog.accept();
- });
-
await manageBuyerDialog.getByRole("button", { name: "Cancel" }).click();
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ await expect(
+ confirmDialog.getByText("Discard changes to buyer?"),
+ ).toBeVisible();
+
+ await expect(
+ confirmDialog.getByText("You have unsaved changes. They will be lost."),
+ ).toBeVisible();
+
+ await expect(
+ confirmDialog.getByRole("button", { name: "Keep editing" }),
+ ).toBeVisible();
+
+ await confirmDialog
+ .getByRole("button", { name: "Discard changes" })
+ .click();
+
+ await expect(confirmDialog).toBeHidden();
await expect(manageBuyerDialog).toBeHidden();
});
@@ -719,17 +735,14 @@ test.describe("Buyer management", () => {
});
await nameInput.fill("Unsaved Buyer");
- page.once("dialog", async (dialog) => {
- expect(dialog.type()).toBe("confirm");
- expect(dialog.message()).toBe(
- "You have unsaved changes in buyer details. Discard them?",
- );
+ await manageBuyerDialog.getByRole("button", { name: "Cancel" }).click();
- // Dismiss the dialog to keep the form values intact
- await dialog.dismiss();
- });
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
- await manageBuyerDialog.getByRole("button", { name: "Cancel" }).click();
+ await confirmDialog.getByRole("button", { name: "Keep editing" }).click();
+
+ await expect(confirmDialog).toBeHidden();
await expect(manageBuyerDialog).toBeVisible();
await expect(nameInput).toHaveValue("Unsaved Buyer");
@@ -745,16 +758,16 @@ test.describe("Buyer management", () => {
.getByRole("textbox", { name: "Name" })
.fill("Unsaved Buyer");
- page.once("dialog", async (dialog) => {
- expect(dialog.type()).toBe("confirm");
- expect(dialog.message()).toBe(
- "You have unsaved changes in buyer details. Discard them?",
- );
- await dialog.accept();
- });
-
await manageBuyerDialog.getByRole("button", { name: "Close" }).click();
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ await confirmDialog
+ .getByRole("button", { name: "Discard changes" })
+ .click();
+
+ await expect(confirmDialog).toBeHidden();
await expect(manageBuyerDialog).toBeHidden();
});
@@ -768,17 +781,379 @@ test.describe("Buyer management", () => {
.getByRole("textbox", { name: "Name" })
.fill("Unsaved Buyer");
- page.once("dialog", async (dialog) => {
- expect(dialog.type()).toBe("confirm");
- expect(dialog.message()).toBe(
- "You have unsaved changes in buyer details. Discard them?",
- );
- await dialog.accept();
- });
-
await page.keyboard.press("Escape");
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+ await confirmDialog
+ .getByRole("button", { name: "Discard changes" })
+ .click();
+
+ await expect(confirmDialog).toBeHidden();
await expect(manageBuyerDialog).toBeHidden();
});
});
+
+ test.describe("pre-fill switch dirty guard", () => {
+ test("toggling switch ON with dirty form shows confirm dialog", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ // Dirty the form
+ const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
+ await manageBuyerDialog
+ .getByRole("textbox", { name: "Name" })
+ .fill("Draft Buyer");
+
+ const prefillSwitch = manageBuyerDialog.getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ });
+ await expect(prefillSwitch).not.toBeChecked();
+
+ await prefillSwitch.click();
+
+ // Verify confirm dialog is shown
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ // Switch has not changed yet — still OFF while dialog is open
+ await expect(
+ page.getByTestId("manage-buyer-dialog").getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ includeHidden: true, // dialog is still open, but on one level deeper
+ }),
+ ).not.toBeChecked();
+
+ // Dialog is still open
+ await expect(manageBuyerDialog).toBeVisible();
+ });
+
+ test("toggling switch ON with dirty form - confirm applies pre-fill and clears draft", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
+ const nameInput = manageBuyerDialog.getByRole("textbox", {
+ name: "Name",
+ });
+ await nameInput.fill("Draft Buyer");
+
+ const prefillSwitch = manageBuyerDialog.getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ });
+ await prefillSwitch.click();
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ await confirmDialog
+ .getByRole("button", { name: "Discard changes" })
+ .click();
+
+ await expect(confirmDialog).toBeHidden();
+
+ // Switch is now ON
+ await expect(prefillSwitch).toBeChecked();
+
+ // Dialog remains open (we only reset the form, not close the dialog)
+ await expect(manageBuyerDialog).toBeVisible();
+
+ // Draft text is gone — form was reset with pre-fill values
+ await expect(nameInput).not.toHaveValue("Draft Buyer");
+ await expect(nameInput).toHaveValue(DEFAULT_BUYER_DATA.name);
+ });
+
+ test("toggling switch ON with dirty form - Keep editing preserves draft and switch stays OFF", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
+ const nameInput = manageBuyerDialog.getByRole("textbox", {
+ name: "Name",
+ });
+ await nameInput.fill("Draft Buyer");
+
+ const prefillSwitch = manageBuyerDialog.getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ });
+ await prefillSwitch.click();
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ await confirmDialog.getByRole("button", { name: "Keep editing" }).click();
+
+ await expect(confirmDialog).toBeHidden();
+
+ // Switch remains OFF — the toggle was cancelled
+ await expect(prefillSwitch).not.toBeChecked();
+
+ // Dialog still open with draft intact
+ await expect(manageBuyerDialog).toBeVisible();
+ await expect(nameInput).toHaveValue("Draft Buyer");
+ });
+
+ test("toggling switch OFF (while ON + dirty) shows confirm dialog", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
+ const prefillSwitch = manageBuyerDialog.getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ });
+
+ // Enable pre-fill while form is clean
+ await prefillSwitch.click();
+ await expect(prefillSwitch).toBeChecked();
+
+ // Dirty the form
+ await manageBuyerDialog
+ .getByRole("textbox", { name: "Name" })
+ .fill("Edited after pre-fill");
+
+ // Toggle switch OFF while dirty
+ await prefillSwitch.click();
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ // Switch remains ON while dialog is open
+ await expect(
+ page.getByTestId("manage-buyer-dialog").getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ includeHidden: true, // dialog is still open, but on one level deeper
+ }),
+ ).toBeChecked();
+ });
+
+ test("toggling switch OFF with dirty form - confirm resets to empty form", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
+ const prefillSwitch = manageBuyerDialog.getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ });
+ const nameInput = manageBuyerDialog.getByRole("textbox", {
+ name: "Name",
+ });
+
+ // Enable pre-fill while form is clean
+ await prefillSwitch.click();
+ await expect(prefillSwitch).toBeChecked();
+
+ // Dirty the form
+ await nameInput.fill("Edited after pre-fill");
+
+ // Toggle switch OFF while dirty
+ await prefillSwitch.click();
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ await confirmDialog
+ .getByRole("button", { name: "Discard changes" })
+ .click();
+
+ await expect(confirmDialog).toBeHidden();
+
+ // Switch is now OFF
+ await expect(prefillSwitch).not.toBeChecked();
+
+ // Dialog remains open
+ await expect(manageBuyerDialog).toBeVisible();
+
+ // Form was reset to empty (no pre-fill values, no edited text)
+ await expect(nameInput).toHaveValue("");
+ });
+
+ test("toggling switch OFF with dirty form - Keep editing preserves draft and switch stays ON", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
+ const prefillSwitch = manageBuyerDialog.getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ });
+ const nameInput = manageBuyerDialog.getByRole("textbox", {
+ name: "Name",
+ });
+
+ // Enable pre-fill while form is clean
+ await prefillSwitch.click();
+ await expect(prefillSwitch).toBeChecked();
+
+ // Dirty the form
+ await nameInput.fill("Edited after pre-fill");
+
+ // Toggle switch OFF while dirty
+ await prefillSwitch.click();
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ await confirmDialog.getByRole("button", { name: "Keep editing" }).click();
+
+ await expect(confirmDialog).toBeHidden();
+
+ // Switch remains ON
+ await expect(prefillSwitch).toBeChecked();
+
+ // Dialog still open with draft intact
+ await expect(manageBuyerDialog).toBeVisible();
+ await expect(nameInput).toHaveValue("Edited after pre-fill");
+ });
+ });
+
+ test("trims whitespace from name and other fields before saving", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
+
+ await manageBuyerDialog
+ .getByRole("textbox", { name: "Name" })
+ .fill(" Globex Corp ");
+ await manageBuyerDialog
+ .getByRole("textbox", { name: "Address" })
+ .fill(" 99 Client Ave ");
+ await manageBuyerDialog
+ .getByRole("textbox", { name: "Email" })
+ .fill(" [email protected] ");
+
+ await manageBuyerDialog.getByRole("button", { name: "Save Buyer" }).click();
+
+ await expect(
+ page.getByText("Buyer added and applied to invoice", { exact: true }),
+ ).toBeVisible();
+
+ const storedData = (await page.evaluate(() =>
+ localStorage.getItem("EASY_INVOICE_PDF_BUYERS"),
+ )) as string;
+ const parsedData = JSON.parse(storedData) as BuyerData[];
+
+ expect(parsedData).toHaveLength(1);
+ expect(parsedData[0].name).toBe("Globex Corp");
+ expect(parsedData[0].address).toBe("99 Client Ave");
+ expect(parsedData[0].email).toBe("[email protected]");
+ });
+
+ test("rejects whitespace-padded name that duplicates an existing buyer", async ({
+ page,
+ }) => {
+ await page.addInitScript(() => {
+ const buyers = [
+ {
+ id: "existing-buyer-id",
+ name: "Globex Corp",
+ address: "1 Client Road",
+ email: "",
+ emailFieldIsVisible: true,
+ vatNo: "",
+ vatNoLabelText: "Tax Number",
+ vatNoFieldIsVisible: true,
+ notes: "",
+ notesFieldIsVisible: true,
+ },
+ ];
+ localStorage.setItem("EASY_INVOICE_PDF_BUYERS", JSON.stringify(buyers));
+ });
+
+ await page.goto("/?template=default");
+
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
+
+ await manageBuyerDialog
+ .getByRole("textbox", { name: "Name" })
+ .fill(" Globex Corp ");
+ await manageBuyerDialog
+ .getByRole("textbox", { name: "Address" })
+ .fill("2 Avenue");
+
+ await manageBuyerDialog.getByRole("button", { name: "Save Buyer" }).click();
+
+ await expect(
+ manageBuyerDialog.getByText("A buyer with this name already exists", {
+ exact: true,
+ }),
+ ).toBeVisible();
+
+ // Dialog should remain open
+ await expect(manageBuyerDialog).toBeVisible();
+
+ // Only the pre-seeded buyer should exist in localStorage
+ const storedData = (await page.evaluate(() =>
+ localStorage.getItem("EASY_INVOICE_PDF_BUYERS"),
+ )) as string;
+ const parsedData = JSON.parse(storedData) as BuyerData[];
+
+ expect(parsedData).toHaveLength(1);
+ expect(parsedData[0].name).toBe("Globex Corp");
+ });
+
+ test("drops invalid localStorage entries and preserves valid ones on save", async ({
+ page,
+ }) => {
+ // Seed: one valid + one corrupt buyer (component already mounted with empty localStorage,
+ // so "New Buyer" button is still visible — onSubmit reads localStorage fresh)
+ await page.addInitScript(() => {
+ const buyers = [
+ {
+ id: "pre-seeded-valid",
+ name: "Pre-seeded Valid Buyer",
+ address: "1 Valid Avenue",
+ email: "[email protected]",
+ emailFieldIsVisible: true,
+ vatNo: "VATPRE",
+ vatNoLabelText: "Tax Number",
+ vatNoFieldIsVisible: true,
+ notes: "",
+ notesFieldIsVisible: true,
+ },
+ { corrupt: true, notABuyer: 42 },
+ ];
+ localStorage.setItem("EASY_INVOICE_PDF_BUYERS", JSON.stringify(buyers));
+ });
+
+ await page.goto("/?template=default");
+ await expect(page).toHaveURL("/?template=default");
+
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
+ await manageBuyerDialog
+ .getByRole("textbox", { name: "Name" })
+ .fill("Brand New Buyer");
+ await manageBuyerDialog
+ .getByRole("textbox", { name: "Address" })
+ .fill("99 Fresh Boulevard");
+
+ await manageBuyerDialog.getByRole("button", { name: "Save Buyer" }).click();
+
+ // Submit succeeds — no error toast
+ await expect(
+ page.getByText("Buyer added and applied to invoice", { exact: true }),
+ ).toBeVisible();
+
+ // localStorage: valid entry preserved, corrupt entry dropped, new entry added
+ const storedData = (await page.evaluate(() =>
+ localStorage.getItem("EASY_INVOICE_PDF_BUYERS"),
+ )) as string;
+ const parsedData = JSON.parse(storedData) as BuyerData[];
+
+ expect(parsedData).toHaveLength(2);
+ expect(parsedData.some((b) => b.name === "Pre-seeded Valid Buyer")).toBe(
+ true,
+ );
+ expect(parsedData.some((b) => b.name === "Brand New Buyer")).toBe(true);
+ });
});
diff --git a/e2e/seller.test.ts b/e2e/seller.test.ts
index fadfb84..6da2fb8 100644
--- a/e2e/seller.test.ts
+++ b/e2e/seller.test.ts
@@ -679,7 +679,7 @@ test.describe("Seller management", () => {
).toHaveValue(DEFAULT_SELLER_DATA.swiftBic);
});
- test("pre-fill switch resets to off after dialog close and reopen", async ({
+ test("switches reset to defaults after dialog close and reopen", async ({
page,
}) => {
await page.getByRole("button", { name: "New Seller" }).click();
@@ -688,11 +688,20 @@ test.describe("Seller management", () => {
const prefillSwitch = manageSellerDialog.getByRole("switch", {
name: "Pre-fill with values from the current invoice form",
});
+ const applyToInvoiceSwitch = manageSellerDialog.getByRole("switch", {
+ name: "Apply to Current Invoice",
+ });
+ // Pre-fill switch defaults to off; toggle it on
await expect(prefillSwitch).not.toBeChecked();
await prefillSwitch.click();
await expect(prefillSwitch).toBeChecked();
+ // "Apply to Current Invoice" switch defaults to on; toggle it off
+ await expect(applyToInvoiceSwitch).toBeChecked();
+ await applyToInvoiceSwitch.click();
+ await expect(applyToInvoiceSwitch).not.toBeChecked();
+
// Close the dialog via Cancel
await manageSellerDialog.getByRole("button", { name: "Cancel" }).click();
await expect(manageSellerDialog).toBeHidden();
@@ -701,8 +710,9 @@ test.describe("Seller management", () => {
await page.getByRole("button", { name: "New Seller" }).click();
await expect(manageSellerDialog).toBeVisible();
- // Pre-fill switch must be off and form must be empty
+ // Both switches must have reset to their defaults and form must be empty
await expect(prefillSwitch).not.toBeChecked();
+ await expect(applyToInvoiceSwitch).toBeChecked();
await expect(
manageSellerDialog.getByRole("textbox", { name: "Name" }),
).toHaveValue("");
@@ -715,16 +725,12 @@ test.describe("Seller management", () => {
const manageSellerDialog = page.getByTestId("manage-seller-dialog");
await expect(manageSellerDialog).toBeVisible();
- // No changes made — Cancel should close immediately, no dialog fired
- let confirmFired = false;
- page.once("dialog", () => {
- confirmFired = true;
- });
-
await manageSellerDialog.getByRole("button", { name: "Cancel" }).click();
await expect(manageSellerDialog).toBeHidden();
- expect(confirmFired).toBe(false);
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeHidden();
});
test("clean form - X button closes without confirm", async ({ page }) => {
@@ -733,15 +739,12 @@ test.describe("Seller management", () => {
const manageSellerDialog = page.getByTestId("manage-seller-dialog");
await expect(manageSellerDialog).toBeVisible();
- let confirmFired = false;
- page.once("dialog", () => {
- confirmFired = true;
- });
-
await manageSellerDialog.getByRole("button", { name: "Close" }).click();
await expect(manageSellerDialog).toBeHidden();
- expect(confirmFired).toBe(false);
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeHidden();
});
test("dirty form - Cancel - accept discards changes and closes", async ({
@@ -754,25 +757,28 @@ test.describe("Seller management", () => {
.getByRole("textbox", { name: "Name" })
.fill("Unsaved Seller");
- // Set up a listener for the browser's native confirm dialog
- // This must be registered BEFORE the action that triggers it
- page.once("dialog", async (dialog) => {
- // Verify it's a confirmation dialog (not alert or prompt)
- expect(dialog.type()).toBe("confirm");
+ await manageSellerDialog.getByRole("button", { name: "Cancel" }).click();
- // Verify the dialog shows the expected discard warning message
- expect(dialog.message()).toBe(
- "You have unsaved changes in seller details. Discard them?",
- );
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
- // Accept the dialog to confirm discarding changes
- await dialog.accept();
- });
+ await expect(confirmDialog).toBeVisible();
+ await expect(
+ confirmDialog.getByText("Discard changes to seller?"),
+ ).toBeVisible();
- // Click Cancel button, which should trigger the confirm dialog
- // because the form has unsaved changes (is "dirty")
- await manageSellerDialog.getByRole("button", { name: "Cancel" }).click();
+ await expect(
+ confirmDialog.getByText("You have unsaved changes. They will be lost."),
+ ).toBeVisible();
+
+ await expect(
+ confirmDialog.getByRole("button", { name: "Discard changes" }),
+ ).toBeVisible();
+ await confirmDialog
+ .getByRole("button", { name: "Discard changes" })
+ .click();
+
+ await expect(confirmDialog).toBeHidden();
await expect(manageSellerDialog).toBeHidden();
});
@@ -787,17 +793,15 @@ test.describe("Seller management", () => {
});
await nameInput.fill("Unsaved Seller");
- page.once("dialog", async (dialog) => {
- expect(dialog.type()).toBe("confirm");
- expect(dialog.message()).toBe(
- "You have unsaved changes in seller details. Discard them?",
- );
+ await manageSellerDialog.getByRole("button", { name: "Cancel" }).click();
- // Dismiss the dialog to keep the form values intact
- await dialog.dismiss();
- });
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
- await manageSellerDialog.getByRole("button", { name: "Cancel" }).click();
+ await expect(confirmDialog).toBeVisible();
+
+ await confirmDialog.getByRole("button", { name: "Keep editing" }).click();
+
+ await expect(confirmDialog).toBeHidden();
await expect(manageSellerDialog).toBeVisible();
await expect(nameInput).toHaveValue("Unsaved Seller");
@@ -813,16 +817,15 @@ test.describe("Seller management", () => {
.getByRole("textbox", { name: "Name" })
.fill("Unsaved Seller");
- page.once("dialog", async (dialog) => {
- expect(dialog.type()).toBe("confirm");
- expect(dialog.message()).toBe(
- "You have unsaved changes in seller details. Discard them?",
- );
- await dialog.accept();
- });
-
await manageSellerDialog.getByRole("button", { name: "Close" }).click();
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+ await confirmDialog
+ .getByRole("button", { name: "Discard changes" })
+ .click();
+
+ await expect(confirmDialog).toBeHidden();
await expect(manageSellerDialog).toBeHidden();
});
@@ -836,17 +839,393 @@ test.describe("Seller management", () => {
.getByRole("textbox", { name: "Name" })
.fill("Unsaved Seller");
- page.once("dialog", async (dialog) => {
- expect(dialog.type()).toBe("confirm");
- expect(dialog.message()).toBe(
- "You have unsaved changes in seller details. Discard them?",
- );
- await dialog.accept();
- });
-
await page.keyboard.press("Escape");
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+ await confirmDialog
+ .getByRole("button", { name: "Discard changes" })
+ .click();
+
+ await expect(confirmDialog).toBeHidden();
await expect(manageSellerDialog).toBeHidden();
});
});
+
+ test.describe("pre-fill switch dirty guard", () => {
+ test("toggling switch ON with dirty form shows confirm dialog", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ const manageSellerDialog = page.getByTestId("manage-seller-dialog");
+ await manageSellerDialog
+ .getByRole("textbox", { name: "Name" })
+ .fill("Draft Seller");
+
+ const prefillSwitch = manageSellerDialog.getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ });
+ await expect(prefillSwitch).not.toBeChecked();
+
+ await prefillSwitch.click();
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ // Switch has not changed yet — still OFF while dialog is open
+ await expect(
+ page.getByTestId("manage-seller-dialog").getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ includeHidden: true, // dialog is still open, but on one level deeper
+ }),
+ ).not.toBeChecked();
+
+ // Dialog is still open
+ await expect(manageSellerDialog).toBeVisible();
+ });
+
+ test("toggling switch ON with dirty form - confirm applies pre-fill and clears draft", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ const manageSellerDialog = page.getByTestId("manage-seller-dialog");
+
+ // Dirty the form
+ const nameInput = manageSellerDialog.getByRole("textbox", {
+ name: "Name",
+ });
+ await nameInput.fill("Draft Seller");
+
+ const prefillSwitch = manageSellerDialog.getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ });
+ await prefillSwitch.click();
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ await confirmDialog
+ .getByRole("button", { name: "Discard changes" })
+ .click();
+
+ await expect(confirmDialog).toBeHidden();
+
+ // Switch is now ON
+ await expect(prefillSwitch).toBeChecked();
+
+ // Dialog remains open (we only reset the form, not close the dialog)
+ await expect(manageSellerDialog).toBeVisible();
+
+ // Draft text is gone — form was reset with pre-fill values
+ await expect(nameInput).not.toHaveValue("Draft Seller");
+ await expect(nameInput).toHaveValue(DEFAULT_SELLER_DATA.name);
+ });
+
+ test("toggling switch ON with dirty form - Keep editing preserves draft and switch stays OFF", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ const manageSellerDialog = page.getByTestId("manage-seller-dialog");
+ const nameInput = manageSellerDialog.getByRole("textbox", {
+ name: "Name",
+ });
+ await nameInput.fill("Draft Seller");
+
+ const prefillSwitch = manageSellerDialog.getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ });
+ await prefillSwitch.click();
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ await confirmDialog.getByRole("button", { name: "Keep editing" }).click();
+
+ await expect(confirmDialog).toBeHidden();
+
+ // Switch remains OFF — the toggle was cancelled
+ await expect(prefillSwitch).not.toBeChecked();
+
+ // Dialog still open with draft intact
+ await expect(manageSellerDialog).toBeVisible();
+ await expect(nameInput).toHaveValue("Draft Seller");
+ });
+
+ test("toggling switch OFF (while ON + dirty) shows confirm dialog", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ const manageSellerDialog = page.getByTestId("manage-seller-dialog");
+ const prefillSwitch = manageSellerDialog.getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ });
+
+ // Enable pre-fill while form is clean
+ await prefillSwitch.click();
+ await expect(prefillSwitch).toBeChecked();
+
+ // Dirty the form
+ await manageSellerDialog
+ .getByRole("textbox", { name: "Name" })
+ .fill("Edited after pre-fill");
+
+ // Toggle switch OFF while dirty
+ await prefillSwitch.click();
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ // Switch remains ON while dialog is open
+ await expect(
+ page.getByTestId("manage-seller-dialog").getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ includeHidden: true, // dialog is still open, but on one level deeper
+ }),
+ ).toBeChecked();
+ });
+
+ test("toggling switch OFF with dirty form - confirm resets to empty form", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ const manageSellerDialog = page.getByTestId("manage-seller-dialog");
+ const prefillSwitch = manageSellerDialog.getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ });
+ const nameInput = manageSellerDialog.getByRole("textbox", {
+ name: "Name",
+ });
+
+ // Enable pre-fill while form is clean
+ await prefillSwitch.click();
+ await expect(prefillSwitch).toBeChecked();
+
+ // Dirty the form
+ await nameInput.fill("Edited after pre-fill");
+
+ // Toggle switch OFF while dirty
+ await prefillSwitch.click();
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ await confirmDialog
+ .getByRole("button", { name: "Discard changes" })
+ .click();
+
+ await expect(confirmDialog).toBeHidden();
+
+ // Switch is now OFF
+ await expect(prefillSwitch).not.toBeChecked();
+
+ // Dialog remains open
+ await expect(manageSellerDialog).toBeVisible();
+
+ // Form was reset to empty (no pre-fill values, no edited text)
+ await expect(nameInput).toHaveValue("");
+ });
+
+ test("toggling switch OFF with dirty form - Keep editing preserves draft and switch stays ON", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ const manageSellerDialog = page.getByTestId("manage-seller-dialog");
+ const prefillSwitch = manageSellerDialog.getByRole("switch", {
+ name: "Pre-fill with values from the current invoice form",
+ });
+ const nameInput = manageSellerDialog.getByRole("textbox", {
+ name: "Name",
+ });
+
+ // Enable pre-fill while form is clean
+ await prefillSwitch.click();
+ await expect(prefillSwitch).toBeChecked();
+
+ // Dirty the form
+ await nameInput.fill("Edited after pre-fill");
+
+ // Toggle switch OFF while dirty
+ await prefillSwitch.click();
+
+ const confirmDialog = page.getByTestId("confirm-discard-dialog");
+ await expect(confirmDialog).toBeVisible();
+
+ await confirmDialog.getByRole("button", { name: "Keep editing" }).click();
+
+ await expect(confirmDialog).toBeHidden();
+
+ // Switch remains ON
+ await expect(prefillSwitch).toBeChecked();
+
+ // Dialog still open with draft intact
+ await expect(manageSellerDialog).toBeVisible();
+ await expect(nameInput).toHaveValue("Edited after pre-fill");
+ });
+ });
+
+ test("trims whitespace from name and other fields before saving", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ const manageSellerDialog = page.getByTestId("manage-seller-dialog");
+
+ await manageSellerDialog
+ .getByRole("textbox", { name: "Name" })
+ .fill(" Acme Corp ");
+ await manageSellerDialog
+ .getByRole("textbox", { name: "Address" })
+ .fill(" 123 Main St ");
+ await manageSellerDialog
+ .getByRole("textbox", { name: "Email" })
+ .fill(" [email protected] ");
+
+ await manageSellerDialog
+ .getByRole("button", { name: "Save Seller" })
+ .click();
+
+ await expect(
+ page.getByText("Seller added and applied to invoice", { exact: true }),
+ ).toBeVisible();
+
+ const storedData = (await page.evaluate(() =>
+ localStorage.getItem("EASY_INVOICE_PDF_SELLERS"),
+ )) as string;
+ const parsedData = JSON.parse(storedData) as SellerData[];
+
+ expect(parsedData).toHaveLength(1);
+ expect(parsedData[0].name).toBe("Acme Corp");
+ expect(parsedData[0].address).toBe("123 Main St");
+ expect(parsedData[0].email).toBe("[email protected]");
+ });
+
+ test("rejects whitespace-padded name that duplicates an existing seller", async ({
+ page,
+ }) => {
+ await page.addInitScript(() => {
+ const sellers = [
+ {
+ id: "existing-seller-id",
+ name: "Acme Corp",
+ address: "1 Road",
+ email: "",
+ emailFieldIsVisible: true,
+ vatNo: "",
+ vatNoLabelText: "Tax Number",
+ vatNoFieldIsVisible: true,
+ accountNumber: "",
+ accountNumberFieldIsVisible: true,
+ swiftBic: "",
+ swiftBicFieldIsVisible: true,
+ notes: "",
+ notesFieldIsVisible: true,
+ },
+ ];
+ localStorage.setItem("EASY_INVOICE_PDF_SELLERS", JSON.stringify(sellers));
+ });
+
+ await page.goto("/?template=default");
+
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ const manageSellerDialog = page.getByTestId("manage-seller-dialog");
+
+ await manageSellerDialog
+ .getByRole("textbox", { name: "Name" })
+ .fill(" Acme Corp ");
+ await manageSellerDialog
+ .getByRole("textbox", { name: "Address" })
+ .fill("2 Avenue");
+
+ await manageSellerDialog
+ .getByRole("button", { name: "Save Seller" })
+ .click();
+
+ await expect(
+ manageSellerDialog.getByText("A seller with this name already exists", {
+ exact: true,
+ }),
+ ).toBeVisible();
+
+ // Dialog should remain open
+ await expect(manageSellerDialog).toBeVisible();
+
+ // Only the pre-seeded seller should exist in localStorage
+ const storedData = (await page.evaluate(() =>
+ localStorage.getItem("EASY_INVOICE_PDF_SELLERS"),
+ )) as string;
+ const parsedData = JSON.parse(storedData) as SellerData[];
+
+ expect(parsedData).toHaveLength(1);
+ expect(parsedData[0].name).toBe("Acme Corp");
+ });
+
+ test("drops invalid localStorage entries and preserves valid ones on save", async ({
+ page,
+ }) => {
+ // Seed: one valid + one corrupt seller (component already mounted with empty localStorage,
+ // so "New Seller" button is still visible — onSubmit reads localStorage fresh)
+ await page.evaluate(() => {
+ const sellers = [
+ {
+ id: "pre-seeded-valid",
+ name: "Pre-seeded Valid Seller",
+ address: "1 Valid Road",
+ email: "[email protected]",
+ emailFieldIsVisible: true,
+ vatNo: "VATPRE",
+ vatNoLabelText: "Tax Number",
+ vatNoFieldIsVisible: true,
+ accountNumber: "ACCTPRE",
+ accountNumberFieldIsVisible: true,
+ swiftBic: "SWIFTPRE",
+ swiftBicFieldIsVisible: true,
+ notes: "",
+ notesFieldIsVisible: true,
+ },
+ { corrupt: true, notASeller: 42 },
+ ];
+ localStorage.setItem("EASY_INVOICE_PDF_SELLERS", JSON.stringify(sellers));
+ });
+
+ await page.goto("/?template=default");
+ await expect(page).toHaveURL("/?template=default");
+
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ const manageSellerDialog = page.getByTestId("manage-seller-dialog");
+ await manageSellerDialog
+ .getByRole("textbox", { name: "Name" })
+ .fill("Brand New Seller");
+ await manageSellerDialog
+ .getByRole("textbox", { name: "Address" })
+ .fill("99 Fresh Lane");
+
+ await manageSellerDialog
+ .getByRole("button", { name: "Save Seller" })
+ .click();
+
+ // Submit succeeds — no error toast
+ await expect(
+ page.getByText("Seller added and applied to invoice", { exact: true }),
+ ).toBeVisible();
+
+ // localStorage: valid entry preserved, corrupt entry dropped, new entry added
+ const storedData = (await page.evaluate(() =>
+ localStorage.getItem("EASY_INVOICE_PDF_SELLERS"),
+ )) as string;
+ const parsedData = JSON.parse(storedData) as SellerData[];
+
+ expect(parsedData).toHaveLength(2);
+ expect(parsedData.some((s) => s.name === "Pre-seeded Valid Seller")).toBe(
+ true,
+ );
+ expect(parsedData.some((s) => s.name === "Brand New Seller")).toBe(true);
+ });
});
diff --git a/package.json b/package.json
index 5e12142..6b8dd50 100644
--- a/package.json
+++ b/package.json
@@ -32,7 +32,7 @@
"cloudflared:tunnel": "pnpm dlx cloudflared tunnel run easy-invoice-pdf-local-dev",
"corepack:enable": "corepack enable",
"corepack:prepare": "corepack prepare pnpm@latest",
- "update-github-actions": "pnpm dlx actions-up --min-age=3"
+ "update-github-actions": "pnpm dlx actions-up --min-age=7"
},
"dependencies": {
"@hookform/resolvers": "3.9.0",
diff --git a/src/app/(app)/components/invoice-form/sections/buyer-information.tsx b/src/app/(app)/components/invoice-form/sections/buyer-information.tsx
index b01ed4e..4f6101c 100644
--- a/src/app/(app)/components/invoice-form/sections/buyer-information.tsx
+++ b/src/app/(app)/components/invoice-form/sections/buyer-information.tsx
@@ -1,7 +1,7 @@
"use client";
import { type BuyerData, type InvoiceData } from "@/app/schema";
-import { BuyerManagement } from "@/components/buyer-management";
+import { BuyerManagement } from "@/app/(app)/components/invoice-form/sections/components/buyer/buyer-management";
import { AccordionContent } from "@/components/ui/accordion";
import { Input } from "@/components/ui/input";
import { InputHelperMessage } from "@/components/ui/input-helper-message";
diff --git a/src/app/(app)/components/invoice-form/sections/components/buyer/buyer-dialog.tsx b/src/app/(app)/components/invoice-form/sections/components/buyer/buyer-dialog.tsx
new file mode 100644
index 0000000..7f0c5b9
--- /dev/null
+++ b/src/app/(app)/components/invoice-form/sections/components/buyer/buyer-dialog.tsx
@@ -0,0 +1,626 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Textarea } from "@/components/ui/textarea";
+import { buyerSchema, type BuyerData } from "@/app/schema";
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Switch } from "@/components/ui/switch";
+import { CustomTooltip } from "@/components/ui/tooltip";
+import { toast } from "sonner";
+import { ConfirmDiscardDialog } from "../confirm-discard-dialog";
+import { BUYERS_LOCAL_STORAGE_KEY } from "./buyer-management";
+import { useState, useEffect } from "react";
+import * as Sentry from "@sentry/nextjs";
+import { InputHelperMessage } from "../../../../../../../components/ui/input-helper-message";
+import { useConfirmDiscard } from "@/app/(app)/components/invoice-form/sections/hooks/use-confirm-discard";
+
+const BUYER_FORM_ID = "buyer-form";
+
+interface BuyerDialogProps {
+ isOpen: boolean;
+ onClose: React.Dispatch<React.SetStateAction<boolean>>;
+ handleBuyerAdd?: (
+ buyer: BuyerData,
+ { shouldApplyNewBuyerToInvoice }: { shouldApplyNewBuyerToInvoice: boolean },
+ ) => void;
+ handleBuyerEdit?: (buyer: BuyerData) => void;
+ initialData: BuyerData | null;
+ isEditMode: boolean;
+ formValues?: Partial<BuyerData>;
+}
+
+/**
+ * BuyerDialog component for adding or editing buyer information.
+ *
+ * This dialog provides a form interface for managing buyer data, including:
+ * - Basic information (name, address, VAT number)
+ * - Contact details (email)
+ * - Additional notes
+ *
+ * Features:
+ * - Pre-fill form with current invoice values (when creating new buyer)
+ * - Apply newly created buyer to current invoice
+ * - Validation for duplicate buyer names
+ * - Unsaved changes warning on dialog close
+ * - Field visibility toggles for optional information
+ */
+export function BuyerDialog({
+ isOpen,
+ onClose,
+ handleBuyerAdd,
+ handleBuyerEdit,
+ initialData,
+ isEditMode,
+ formValues,
+}: BuyerDialogProps) {
+ const form = useForm<BuyerData>({
+ resolver: zodResolver(buyerSchema),
+ defaultValues: {
+ id: initialData?.id ?? "",
+ name: initialData?.name ?? "",
+ address: initialData?.address ?? "",
+ vatNo: initialData?.vatNo ?? "",
+ vatNoLabelText: initialData?.vatNoLabelText ?? "VAT no",
+ email: initialData?.email ?? "",
+ emailFieldIsVisible: initialData?.emailFieldIsVisible ?? true,
+ vatNoFieldIsVisible: initialData?.vatNoFieldIsVisible ?? true,
+ notes: initialData?.notes ?? "",
+ notesFieldIsVisible: initialData?.notesFieldIsVisible ?? true,
+ },
+ });
+
+ const { isDirty } = form.formState;
+
+ const { isConfirmDiscardDialogOpen, setIsConfirmDiscardDialogOpen } =
+ useConfirmDiscard();
+
+ // by default, we want to apply the new buyer to the current invoice
+ const [shouldApplyNewBuyerToInvoice, setShouldApplyNewBuyerToInvoice] =
+ useState(true);
+
+ // should apply inline form values to the dialog form
+ const [shouldApplyInlineFormValues, setShouldApplyInlineFormValues] =
+ useState(false);
+
+ // Stores a pending action to execute after user confirms discard in the ConfirmDiscardDialog.
+ // Uses currying (() => () => void) because React state setters require a function that returns
+ // the new state value. When we call setPendingDiscardAction(() => closeDialog), we're storing
+ // a function that returns closeDialog, not calling closeDialog immediately. This prevents
+ // premature execution and allows us to defer the action until the user confirms.
+ const [pendingDiscardAction, setPendingDiscardAction] = useState<
+ (() => void) | null
+ >(null);
+
+ /**
+ * Synchronizes form values based on the "Use current invoice data" switch state.
+ *
+ * When creating a new buyer (not in edit mode):
+ * - If switch is ON: Populates the form with current invoice buyer data (formValues)
+ * to allow users to save the current invoice's buyer information as a new saved buyer.
+ * - If switch is OFF: Resets the form to empty/default values or initialData
+ * to allow users to enter completely new buyer information from scratch.
+ *
+ * This effect does not run in edit mode to prevent overwriting the buyer being edited.
+ */
+ useEffect(() => {
+ // Switch is ON: Pre-fill form with current invoice buyer data
+ if (shouldApplyInlineFormValues && formValues && !isEditMode) {
+ form.reset({
+ ...form.getValues(),
+ ...formValues,
+ });
+ }
+
+ // Switch is OFF: Reset form to empty state or initial data
+ else if (!shouldApplyInlineFormValues && !isEditMode) {
+ form.reset(
+ initialData ?? {
+ id: "",
+ name: "",
+ address: "",
+ vatNo: "",
+ vatNoLabelText: "VAT no",
+ email: "",
+ emailFieldIsVisible: true,
+ vatNoFieldIsVisible: true,
+ notes: "",
+ notesFieldIsVisible: true,
+ },
+ );
+ }
+ }, [shouldApplyInlineFormValues, formValues, initialData, isEditMode, form]);
+
+ /**
+ * Guards the pre-fill switch toggle against dirty form state.
+ *
+ * When the form has unsaved changes, opens the ConfirmDiscardDialog before
+ * applying the switch change. Only updates shouldApplyFormValues (and thus
+ * triggers form.reset via the effect above) after the user confirms discard.
+ */
+ function handlePrefillSwitchToggle(newValue: boolean) {
+ if (isDirty) {
+ setPendingDiscardAction(
+ () => () => setShouldApplyInlineFormValues(newValue),
+ );
+ setIsConfirmDiscardDialogOpen(true);
+ return;
+ }
+ setShouldApplyInlineFormValues(newValue);
+ }
+
+ /**
+ * Closes the buyer dialog and resets the form to its default state.
+ */
+ function closeDialog() {
+ form.reset();
+
+ // by default, we don't want to apply the inline form values to the dialog form
+ setShouldApplyInlineFormValues(false);
+ // by default, we want to apply the new buyer to the current invoice
+ setShouldApplyNewBuyerToInvoice(true);
+
+ onClose(false);
+ }
+
+ function onSubmit(formValues: BuyerData) {
+ try {
+ // **RUNNING SOME VALIDATIONS FIRST**
+
+ // Get existing buyers or initialize empty array
+ const buyers = localStorage.getItem(BUYERS_LOCAL_STORAGE_KEY);
+ const existingBuyers: unknown = buyers ? JSON.parse(buyers) : [];
+
+ const rawBuyers = Array.isArray(existingBuyers) ? existingBuyers : [];
+
+ const validBuyers: BuyerData[] = [];
+ let hadInvalidBuyers = false;
+
+ // Validate each buyer individually — drop only invalid items
+ for (const item of rawBuyers) {
+ const result = buyerSchema.safeParse(item);
+
+ if (result.success) {
+ validBuyers.push(result.data);
+ } else {
+ hadInvalidBuyers = true;
+
+ console.error(
+ "[buyer-dialog] Dropped invalid buyer entry:",
+ result.error,
+ );
+
+ Sentry.captureException(
+ new Error(
+ `[buyer-dialog] Invalid buyer data in localStorage: ${rawBuyers.length - validBuyers.length} items dropped`,
+ ),
+ );
+ }
+ }
+
+ // If we had invalid buyers, save the valid buyers back to localStorage
+ if (hadInvalidBuyers) {
+ localStorage.setItem(
+ BUYERS_LOCAL_STORAGE_KEY,
+ JSON.stringify(validBuyers),
+ );
+ }
+
+ // Validate buyer data against existing buyers
+ const isDuplicateName = validBuyers.some(
+ (buyer: BuyerData) =>
+ buyer.name === formValues.name && buyer.id !== formValues.id,
+ );
+
+ if (isDuplicateName) {
+ form.setError("name", {
+ type: "manual",
+ message: "A buyer with this name already exists",
+ });
+
+ // Focus on the name input field for user to fix the error
+ form.setFocus("name");
+
+ // Show error toast
+ toast.error("A buyer with this name already exists", {
+ richColors: true,
+ });
+
+ return;
+ }
+
+ if (isEditMode) {
+ // Edit buyer
+ handleBuyerEdit?.(formValues);
+ } else {
+ // Add new buyer
+ handleBuyerAdd?.(formValues, { shouldApplyNewBuyerToInvoice });
+ }
+
+ // Close dialog
+ closeDialog();
+ } catch (error) {
+ console.error("Failed to save buyer:", error);
+
+ toast.error("Failed to save buyer", {
+ description: "Please try again",
+ richColors: true,
+ });
+
+ Sentry.captureException(error);
+ }
+ }
+
+ return (
+ <>
+ <Dialog
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!open) {
+ // 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(() => closeDialog);
+ setIsConfirmDiscardDialogOpen(true);
+ return;
+ }
+ closeDialog();
+ }
+ }}
+ >
+ <DialogContent
+ className="flex flex-col gap-0 overflow-y-visible p-0 sm:max-w-lg [&>button:last-child]:top-3.5"
+ data-testid={`manage-buyer-dialog`}
+ >
+ <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"}
+ </DialogTitle>
+ <DialogDescription>
+ {isEditMode
+ ? "Edit the buyer details"
+ : "Add a new buyer to use later in your invoices"}
+ </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"
+ />
+ <Label
+ htmlFor="apply-form-values-switch"
+ className="cursor-pointer"
+ >
+ Pre-fill with values from the current invoice form
+ </Label>
+ </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&apos;ve already
+ entered in your current invoice form.
+ </span>
+ </div>
+ )}
+
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="space-y-4"
+ id={BUYER_FORM_ID}
+ >
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Name (Required)</FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter buyer name"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="address"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Address (Required)</FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter buyer address"
+ />
+ </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 }) => (
+ <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">
+ <FormField
+ control={form.control}
+ name="vatNoLabelText"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Label</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ placeholder="Enter Tax number label"
+ />
+ </FormControl>
+
+ {form.formState.errors.vatNoLabelText && (
+ <FormMessage>
+ {form.formState.errors.vatNoLabelText.message}
+ </FormMessage>
+ )}
+
+ {!form.formState.errors.vatNoLabelText && (
+ <InputHelperMessage>
+ Set a custom label (e.g. VAT no, Tax no, etc.)
+ </InputHelperMessage>
+ )}
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="vatNo"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Value</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ placeholder="Enter Tax number value"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ </fieldset>
+
+ {/* Email */}
+ <div className="space-y-3 rounded-md border p-4">
+ <FormField
+ control={form.control}
+ name="email"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="mb-2 font-medium">
+ Email
+ </FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ type="email"
+ placeholder="[email protected]"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="emailFieldIsVisible"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex items-center gap-2">
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ id="emailFieldIsVisible"
+ data-testid={`buyerEmailDialogFieldVisibilitySwitch`}
+ aria-label={`Show the 'Email' field in the PDF`}
+ />
+ </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>
+
+ {/* Notes */}
+ <div className="space-y-3 rounded-md border p-4">
+ <FormField
+ control={form.control}
+ name="notes"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="mb-2 font-medium">
+ Notes
+ </FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter notes (max 750 characters)"
+ maxLength={750}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="notesFieldIsVisible"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex items-center gap-2">
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ id="notes-field-visibility"
+ data-testid={`buyerNotesDialogFieldVisibilitySwitch`}
+ aria-label={`Show the 'Notes' field in the PDF`}
+ />
+ </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>
+ </form>
+ </Form>
+
+ {/* Apply to Current Invoice switch remains at bottom */}
+ {!isEditMode && (
+ <div className="mt-4 flex flex-col gap-1 border-t pt-4">
+ <div className="flex items-center gap-2">
+ <Switch
+ checked={shouldApplyNewBuyerToInvoice}
+ onCheckedChange={setShouldApplyNewBuyerToInvoice}
+ id="apply-buyer-to-current-invoice-switch"
+ />
+ <Label
+ htmlFor="apply-buyer-to-current-invoice-switch"
+ className="cursor-pointer"
+ >
+ Apply to Current 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>
+ </div>
+ )}
+ </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(() => 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>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ <ConfirmDiscardDialog
+ open={isConfirmDiscardDialogOpen}
+ onOpenChange={setIsConfirmDiscardDialogOpen}
+ onDiscard={() => {
+ pendingDiscardAction?.();
+ setPendingDiscardAction(null);
+ }}
+ entityName="buyer"
+ />
+ </>
+ );
+}
diff --git a/src/components/buyer-management.tsx b/src/app/(app)/components/invoice-form/sections/components/buyer/buyer-management.tsx
similarity index 90%
rename from src/components/buyer-management.tsx
rename to src/app/(app)/components/invoice-form/sections/components/buyer/buyer-management.tsx
index 79f8f98..1798097 100644
--- a/src/components/buyer-management.tsx
+++ b/src/app/(app)/components/invoice-form/sections/components/buyer/buyer-management.tsx
@@ -1,8 +1,8 @@
import { Plus, Trash2, Pencil, AlertCircleIcon } from "lucide-react";
import { useId, useState, useEffect } from "react";
-import { CustomTooltip } from "./ui/tooltip";
-import { SelectNative } from "./ui/select-native";
-import { Button } from "./ui/button";
+import { CustomTooltip } from "@/components/ui/tooltip";
+import { SelectNative } from "@/components/ui/select-native";
+import { Button } from "@/components/ui/button";
import { BuyerDialog } from "./buyer-dialog";
import {
AlertDialog,
@@ -13,13 +13,12 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
-} from "./ui/alert-dialog";
+} from "@/components/ui/alert-dialog";
import type { UseFormSetValue } from "react-hook-form";
import { buyerSchema, type InvoiceData, type BuyerData } from "@/app/schema";
-import { z } from "zod";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
-import { Label } from "./ui/label";
+import { Label } from "@/components/ui/label";
import { isLocalStorageAvailable } from "@/lib/check-local-storage";
import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
import * as Sentry from "@sentry/nextjs";
@@ -85,20 +84,50 @@ export function BuyerManagement({
const savedBuyers = localStorage.getItem(BUYERS_LOCAL_STORAGE_KEY);
const parsedBuyers: unknown = savedBuyers ? JSON.parse(savedBuyers) : [];
- // Validate buyers array with Zod
- const buyersSchema = z.array(buyerSchema);
- const validationResult = buyersSchema.safeParse(parsedBuyers);
+ const rawBuyers = Array.isArray(parsedBuyers) ? parsedBuyers : [];
- if (!validationResult.success) {
- console.error("Invalid buyers data:", validationResult.error);
- return;
+ const validBuyers: BuyerData[] = [];
+ const invalidBuyers: BuyerData[] = [];
+
+ // Validate each buyer individually — drop only invalid items
+ for (const item of rawBuyers) {
+ const result = buyerSchema.safeParse(item);
+ if (result.success) {
+ validBuyers.push(result.data);
+ } else {
+ invalidBuyers.push(item as BuyerData);
+
+ console.error(
+ "[buyer-management] Invalid buyer entry:",
+ result.error,
+ );
+ }
+ }
+
+ // If we have invalid buyers, drop them and save the valid buyers back to localStorage
+ if (invalidBuyers.length > 0) {
+ console.error(
+ `[buyer-management] Dropped ${invalidBuyers.length} invalid buyer entries:`,
+ invalidBuyers,
+ );
+
+ Sentry.captureException(
+ new Error(
+ `[buyer-management] Invalid buyer data in localStorage: ${rawBuyers.length - validBuyers.length} items dropped`,
+ ),
+ );
+
+ localStorage.setItem(
+ BUYERS_LOCAL_STORAGE_KEY,
+ JSON.stringify(validBuyers),
+ );
}
- const selectedBuyer = validationResult.data.find((buyer: BuyerData) => {
+ const selectedBuyer = validBuyers.find((buyer: BuyerData) => {
return buyer?.id === invoiceData?.buyer?.id;
});
- setBuyersSelectOptions(validationResult.data);
+ setBuyersSelectOptions(validBuyers);
setSelectedBuyerId(selectedBuyer?.id ?? "");
} catch (error) {
console.error("Failed to load buyers:", error);
diff --git a/src/app/(app)/components/invoice-form/sections/components/confirm-discard-dialog.tsx b/src/app/(app)/components/invoice-form/sections/components/confirm-discard-dialog.tsx
new file mode 100644
index 0000000..4f30eca
--- /dev/null
+++ b/src/app/(app)/components/invoice-form/sections/components/confirm-discard-dialog.tsx
@@ -0,0 +1,47 @@
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+
+interface ConfirmDiscardDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onDiscard: () => void;
+ entityName: string;
+}
+
+export function ConfirmDiscardDialog({
+ open,
+ onOpenChange,
+ onDiscard,
+ entityName,
+}: ConfirmDiscardDialogProps) {
+ return (
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
+ <AlertDialogContent data-testid="confirm-discard-dialog">
+ <AlertDialogHeader>
+ <AlertDialogTitle>Discard changes to {entityName}?</AlertDialogTitle>
+ <AlertDialogDescription className="">
+ You have <span className="font-semibold">unsaved changes</span>.
+ They will be lost.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep editing</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={onDiscard}
+ className="bg-red-500 text-red-50 hover:bg-red-500/90"
+ >
+ Discard changes
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/src/app/(app)/components/invoice-form/sections/components/seller/seller-dialog.tsx b/src/app/(app)/components/invoice-form/sections/components/seller/seller-dialog.tsx
new file mode 100644
index 0000000..0ed6a4b
--- /dev/null
+++ b/src/app/(app)/components/invoice-form/sections/components/seller/seller-dialog.tsx
@@ -0,0 +1,727 @@
+import { sellerSchema, type SellerData } from "@/app/schema";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+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 { zodResolver } from "@hookform/resolvers/zod";
+import * as Sentry from "@sentry/nextjs";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { ConfirmDiscardDialog } from "../confirm-discard-dialog";
+import { SELLERS_LOCAL_STORAGE_KEY } from "./seller-management";
+import { InputHelperMessage } from "../../../../../../../components/ui/input-helper-message";
+import { useConfirmDiscard } from "@/app/(app)/components/invoice-form/sections/hooks/use-confirm-discard";
+
+const SELLER_FORM_ID = "seller-form";
+
+interface SellerDialogProps {
+ isOpen: boolean;
+ onClose: React.Dispatch<React.SetStateAction<boolean>>;
+ handleSellerAdd?: (
+ seller: SellerData,
+ {
+ shouldApplyNewSellerToInvoice,
+ }: { shouldApplyNewSellerToInvoice: boolean },
+ ) => void;
+ handleSellerEdit?: (seller: SellerData) => void;
+ initialData: SellerData | null;
+ isEditMode: boolean;
+ formValues?: Partial<SellerData>;
+}
+
+/**
+ * SellerDialog component for adding or editing seller information.
+ *
+ * This dialog provides a form interface for managing seller data, including:
+ * - Basic information (name, address, VAT number)
+ * - Contact details (email)
+ * - Banking information (account number, SWIFT/BIC)
+ * - Additional notes
+ *
+ * Features:
+ * - Pre-fill form with current invoice values (when creating new seller)
+ * - Apply newly created seller to current invoice
+ * - Validation for duplicate seller names
+ * - Unsaved changes warning on dialog close
+ * - Field visibility toggles for optional information
+ */
+export function SellerDialog({
+ isOpen,
+ onClose,
+ handleSellerAdd,
+ handleSellerEdit,
+ initialData,
+ isEditMode,
+ formValues,
+}: SellerDialogProps) {
+ const form = useForm<SellerData>({
+ resolver: zodResolver(sellerSchema),
+ defaultValues: {
+ id: initialData?.id ?? "",
+ name: initialData?.name ?? "",
+ address: initialData?.address ?? "",
+ vatNo: initialData?.vatNo ?? "",
+ vatNoLabelText: initialData?.vatNoLabelText ?? "VAT no",
+ email: initialData?.email ?? "",
+ emailFieldIsVisible: initialData?.emailFieldIsVisible ?? true,
+ accountNumber: initialData?.accountNumber ?? "",
+ swiftBic: initialData?.swiftBic ?? "",
+ vatNoFieldIsVisible: initialData?.vatNoFieldIsVisible ?? true,
+ accountNumberFieldIsVisible:
+ initialData?.accountNumberFieldIsVisible ?? true,
+ swiftBicFieldIsVisible: initialData?.swiftBicFieldIsVisible ?? true,
+ notes: initialData?.notes ?? "",
+ notesFieldIsVisible: initialData?.notesFieldIsVisible ?? true,
+ },
+ });
+
+ const { isDirty } = form.formState;
+
+ const { isConfirmDiscardDialogOpen, setIsConfirmDiscardDialogOpen } =
+ useConfirmDiscard();
+
+ // by default, we want to apply the new seller to the current invoice
+ const [shouldApplyNewSellerToInvoice, setShouldApplyNewSellerToInvoice] =
+ useState(true);
+
+ // Add state for applying inline form values to dialog form
+ const [shouldApplyInlineFormValues, setShouldApplyInlineFormValues] =
+ useState(false);
+
+ // Stores a pending action to execute after user confirms discard in the ConfirmDiscardDialog.
+ // Uses currying (() => () => void) because React state setters require a function that returns
+ // the new state value. When we call setPendingDiscardAction(() => closeDialog), we're storing
+ // a function that returns closeDialog, not calling closeDialog immediately. This prevents
+ // premature execution and allows us to defer the action until the user confirms.
+ const [pendingDiscardAction, setPendingDiscardAction] = useState<
+ (() => void) | null
+ >(null);
+
+ // Effect to update form values when switch is toggled
+ useEffect(() => {
+ // if the switch is on and we have form values, we want to apply the form values to the form
+ if (shouldApplyInlineFormValues && formValues && !isEditMode) {
+ form.reset({
+ ...form.getValues(),
+ ...formValues,
+ });
+ }
+
+ // if the switch is off and we have initial data, we want to apply the initial data to the form
+ else if (!shouldApplyInlineFormValues && !isEditMode) {
+ form.reset(
+ initialData ?? {
+ id: "",
+ name: "",
+ address: "",
+ vatNo: "",
+ vatNoLabelText: "VAT no",
+ email: "",
+ emailFieldIsVisible: true,
+ accountNumber: "",
+ swiftBic: "",
+ vatNoFieldIsVisible: true,
+ accountNumberFieldIsVisible: true,
+ swiftBicFieldIsVisible: true,
+ notes: "",
+ notesFieldIsVisible: true,
+ },
+ );
+ }
+ }, [shouldApplyInlineFormValues, formValues, initialData, isEditMode, form]);
+
+ /**
+ * Guards the pre-fill switch toggle against dirty form state.
+ *
+ * When the form has unsaved changes, opens the ConfirmDiscardDialog before
+ * applying the switch change. Only updates shouldApplyFormValues (and thus
+ * triggers form.reset via the effect above) after the user confirms discard.
+ */
+ function handlePrefillSwitchToggle(newValue: boolean) {
+ if (isDirty) {
+ setPendingDiscardAction(
+ () => () => setShouldApplyInlineFormValues(newValue),
+ );
+ setIsConfirmDiscardDialogOpen(true);
+ return;
+ }
+ setShouldApplyInlineFormValues(newValue);
+ }
+
+ /**
+ * Closes the seller dialog and resets the form to its default state.
+ */
+ function closeDialog() {
+ form.reset();
+
+ // by default, we don't want to apply the inline form values to the dialog form
+ setShouldApplyInlineFormValues(false);
+ // by default, we want to apply the new seller to the current invoice
+ setShouldApplyNewSellerToInvoice(true);
+
+ onClose(false);
+ }
+
+ function onSubmit(formValues: SellerData) {
+ try {
+ // **RUNNING SOME VALIDATIONS FIRST**
+
+ // Get existing sellers or initialize empty array
+ const sellers = localStorage.getItem(SELLERS_LOCAL_STORAGE_KEY);
+ const existingSellers: unknown = sellers ? JSON.parse(sellers) : [];
+
+ const rawSellers = Array.isArray(existingSellers) ? existingSellers : [];
+
+ const validSellers: SellerData[] = [];
+ let hadInvalidSellers = false;
+
+ // Validate each seller individually — drop only invalid items
+ for (const item of rawSellers) {
+ const result = sellerSchema.safeParse(item);
+ if (result.success) {
+ validSellers.push(result.data);
+ } else {
+ hadInvalidSellers = true;
+
+ Sentry.captureException(
+ new Error(
+ `[seller-dialog] Invalid seller data in localStorage: ${rawSellers.length - validSellers.length} items dropped`,
+ ),
+ );
+
+ console.error(
+ "[seller-dialog] Dropped invalid seller entry:",
+ result.error,
+ );
+ }
+ }
+
+ // If we had invalid sellers, save the valid sellers back to localStorage
+ if (hadInvalidSellers) {
+ localStorage.setItem(
+ SELLERS_LOCAL_STORAGE_KEY,
+ JSON.stringify(validSellers),
+ );
+ }
+
+ // we don't need to validate the name if we are editing an existing seller
+
+ // Validate seller data against existing sellers
+ const isDuplicateName = validSellers.some(
+ (seller: SellerData) =>
+ seller.name === formValues.name && seller.id !== formValues.id,
+ );
+
+ if (isDuplicateName) {
+ form.setError("name", {
+ type: "manual",
+ message: "A seller with this name already exists",
+ });
+
+ // Focus on the name input field for user to fix the error
+ form.setFocus("name");
+
+ // Show error toast
+ toast.error("A seller with this name already exists", {
+ id: "seller-name-already-exists-error-toast",
+ richColors: true,
+ description: "Please try again",
+ });
+
+ return;
+ }
+
+ if (isEditMode) {
+ // Edit seller
+ handleSellerEdit?.(formValues);
+ } else {
+ // Add new seller
+ handleSellerAdd?.(formValues, { shouldApplyNewSellerToInvoice });
+ }
+
+ // Close dialog
+ closeDialog();
+ } catch (error) {
+ console.error("Failed to save seller:", error);
+
+ toast.error("Failed to save seller", {
+ id: "failed-to-save-seller-error-toast",
+ description: "Please try again",
+ richColors: true,
+ });
+
+ Sentry.captureException(error);
+ }
+ }
+
+ return (
+ <>
+ <Dialog
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!open) {
+ // 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(() => closeDialog);
+ setIsConfirmDiscardDialogOpen(true);
+ return;
+ }
+ closeDialog();
+ }
+ }}
+ >
+ <DialogContent
+ className="flex flex-col gap-0 overflow-y-visible p-0 sm:max-w-lg [&>button:last-child]:top-3.5"
+ data-testid={`manage-seller-dialog`}
+ >
+ <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"}
+ </DialogTitle>
+ <DialogDescription>
+ {isEditMode
+ ? "Edit the seller details"
+ : "Add a new seller to use later in your invoices"}
+ </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"
+ />
+ <Label
+ htmlFor="apply-form-values-switch"
+ className="cursor-pointer"
+ >
+ Pre-fill with values from the current invoice form
+ </Label>
+ </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&apos;ve already
+ entered in your current invoice form.
+ </span>
+ </div>
+ )}
+
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="space-y-4"
+ id={SELLER_FORM_ID}
+ >
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Name (Required)</FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter seller name"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="address"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Address (Required)</FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter seller address"
+ />
+ </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 }) => (
+ <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">
+ <FormField
+ control={form.control}
+ name="vatNoLabelText"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Label</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ placeholder="Enter Tax number label"
+ />
+ </FormControl>
+ {form.formState.errors.vatNoLabelText && (
+ <FormMessage>
+ {form.formState.errors.vatNoLabelText.message}
+ </FormMessage>
+ )}
+
+ {!form.formState.errors.vatNoLabelText && (
+ <InputHelperMessage>
+ Set a custom label (e.g. VAT no, Tax no, etc.)
+ </InputHelperMessage>
+ )}
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="vatNo"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Value</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ placeholder="Enter Tax number value"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ </fieldset>
+
+ {/* Email */}
+ <div className="space-y-3 rounded-md border p-4">
+ <FormField
+ control={form.control}
+ name="email"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="mb-2 font-medium">
+ Email
+ </FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ type="email"
+ placeholder="[email protected]"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="emailFieldIsVisible"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex items-center gap-2">
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ id="emailFieldIsVisible"
+ data-testid={`sellerEmailDialogFieldVisibilitySwitch`}
+ aria-label={`Show the 'Email' field in the PDF`}
+ />
+ </FormControl>
+ <CustomTooltip
+ trigger={
+ <Label htmlFor="emailFieldIsVisible">
+ Show Seller Email in PDF
+ </Label>
+ }
+ content='Show the "Email" field in the PDF'
+ className="z-[1000]"
+ />
+ </div>
+ </FormItem>
+ )}
+ />
+ </div>
+
+ {/* Account Number */}
+ <div className="space-y-3 rounded-md border p-4">
+ <FormField
+ control={form.control}
+ name="accountNumber"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="mb-2 font-medium">
+ Account Number
+ </FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter account number"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="accountNumberFieldIsVisible"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex items-center gap-2">
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ id="accountNumberFieldIsVisible"
+ aria-label={`Show the 'Account Number' field in the PDF`}
+ />
+ <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>
+ </FormItem>
+ )}
+ />
+ </div>
+
+ {/* SWIFT/BIC */}
+ <div className="space-y-3 rounded-md border p-4">
+ <FormField
+ control={form.control}
+ name="swiftBic"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="mb-2 font-medium">
+ SWIFT/BIC
+ </FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter SWIFT/BIC code"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="swiftBicFieldIsVisible"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex items-center gap-2">
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ id="swiftBicFieldIsVisible"
+ aria-label={`Show the 'SWIFT/BIC' field in the PDF`}
+ />
+ <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>
+
+ {/* Notes */}
+ <div className="space-y-3 rounded-md border p-4">
+ <FormField
+ control={form.control}
+ name="notes"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="mb-2 font-medium">
+ Notes
+ </FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter notes (max 750 characters)"
+ maxLength={750}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="notesFieldIsVisible"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex items-center gap-2">
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ id="notes-field-visibility"
+ data-testid={`sellerNotesDialogFieldVisibilitySwitch`}
+ aria-label={`Show the 'Notes' field in the PDF`}
+ />
+ </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>
+ </form>
+ </Form>
+
+ {/* Apply to Current Invoice switch remains at the bottom */}
+ {!isEditMode && (
+ <div className="mt-4 flex flex-col gap-1 border-t pt-4">
+ <div className="flex items-center gap-2">
+ <Switch
+ checked={shouldApplyNewSellerToInvoice}
+ onCheckedChange={setShouldApplyNewSellerToInvoice}
+ id="apply-seller-to-current-invoice-switch"
+ />
+ <Label
+ htmlFor="apply-seller-to-current-invoice-switch"
+ className="cursor-pointer"
+ >
+ Apply to Current 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>
+ </div>
+ )}
+ </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(() => 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>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ <ConfirmDiscardDialog
+ open={isConfirmDiscardDialogOpen}
+ onOpenChange={setIsConfirmDiscardDialogOpen}
+ onDiscard={() => {
+ pendingDiscardAction?.();
+ setPendingDiscardAction(null);
+ }}
+ entityName="seller"
+ />
+ </>
+ );
+}
diff --git a/src/components/seller-management.tsx b/src/app/(app)/components/invoice-form/sections/components/seller/seller-management.tsx
similarity index 89%
rename from src/components/seller-management.tsx
rename to src/app/(app)/components/invoice-form/sections/components/seller/seller-management.tsx
index ab63408..fc059b1 100644
--- a/src/components/seller-management.tsx
+++ b/src/app/(app)/components/invoice-form/sections/components/seller/seller-management.tsx
@@ -7,10 +7,9 @@ import {
type Dispatch,
type SetStateAction,
} from "react";
-import { CustomTooltip } from "./ui/tooltip";
-import { SelectNative } from "./ui/select-native";
-import { Button } from "./ui/button";
-import { SellerDialog } from "./seller-dialog";
+import { CustomTooltip } from "@/components/ui/tooltip";
+import { SelectNative } from "@/components/ui/select-native";
+import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
@@ -20,17 +19,17 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
-} from "./ui/alert-dialog";
+} from "@/components/ui/alert-dialog";
import type { UseFormSetValue } from "react-hook-form";
import { sellerSchema, type InvoiceData, type SellerData } from "@/app/schema";
-import { z } from "zod";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
-import { Label } from "./ui/label";
+import { Label } from "@/components/ui/label";
import { isLocalStorageAvailable } from "@/lib/check-local-storage";
import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
import * as Sentry from "@sentry/nextjs";
import { DEFAULT_SELLER_DATA } from "@/app/constants";
+import { SellerDialog } from "@/app/(app)/components/invoice-form/sections/components/seller/seller-dialog";
export const SELLERS_LOCAL_STORAGE_KEY = "EASY_INVOICE_PDF_SELLERS";
@@ -94,22 +93,50 @@ export function SellerManagement({
? JSON.parse(savedSellers)
: [];
- // Validate sellers array with Zod
- const sellersSchema = z.array(sellerSchema);
- const validationResult = sellersSchema.safeParse(parsedSellers);
+ const rawSellers = Array.isArray(parsedSellers) ? parsedSellers : [];
- if (!validationResult.success) {
- console.error("Invalid sellers data:", validationResult.error);
- return;
+ const validSellers: SellerData[] = [];
+ const invalidSellers: SellerData[] = [];
+
+ // Validate each seller individually — drop only invalid items
+ for (const item of rawSellers) {
+ const result = sellerSchema.safeParse(item);
+ if (result.success) {
+ validSellers.push(result.data);
+ } else {
+ invalidSellers.push(item as SellerData);
+
+ console.error(
+ "[seller-management] Invalid seller entry:",
+ result.error,
+ );
+ }
}
- const selectedSeller = validationResult.data.find(
- (seller: SellerData) => {
- return seller?.id === invoiceData?.seller?.id;
- },
- );
+ // If we have invalid sellers, drop them and save the valid sellers back to localStorage
+ if (invalidSellers.length > 0) {
+ console.error(
+ `[seller-management] Dropped ${invalidSellers.length} invalid seller entries:`,
+ invalidSellers,
+ );
+
+ Sentry.captureException(
+ new Error(
+ `[seller-management] Invalid seller data in localStorage: ${rawSellers.length - validSellers.length} items dropped`,
+ ),
+ );
+
+ localStorage.setItem(
+ SELLERS_LOCAL_STORAGE_KEY,
+ JSON.stringify(validSellers),
+ );
+ }
+
+ const selectedSeller = validSellers.find((seller: SellerData) => {
+ return seller?.id === invoiceData?.seller?.id;
+ });
- setSellersSelectOptions(validationResult.data);
+ setSellersSelectOptions(validSellers);
setSelectedSellerId(selectedSeller?.id ?? "");
} catch (error) {
console.error("Failed to load sellers:", error);
diff --git a/src/app/(app)/components/invoice-form/sections/hooks/use-confirm-discard.tsx b/src/app/(app)/components/invoice-form/sections/hooks/use-confirm-discard.tsx
new file mode 100644
index 0000000..480fe2f
--- /dev/null
+++ b/src/app/(app)/components/invoice-form/sections/hooks/use-confirm-discard.tsx
@@ -0,0 +1,14 @@
+import { useState } from "react";
+
+/**
+ * Hook to manage confirmation dialog when discarding unsaved changes
+ */
+export function useConfirmDiscard() {
+ const [isConfirmDiscardDialogOpen, setIsConfirmDiscardDialogOpen] =
+ useState(false);
+
+ return {
+ isConfirmDiscardDialogOpen,
+ setIsConfirmDiscardDialogOpen,
+ };
+}
diff --git a/src/app/(app)/components/invoice-form/sections/seller-information.tsx b/src/app/(app)/components/invoice-form/sections/seller-information.tsx
index 145d2ed..1b6f630 100644
--- a/src/app/(app)/components/invoice-form/sections/seller-information.tsx
+++ b/src/app/(app)/components/invoice-form/sections/seller-information.tsx
@@ -1,5 +1,5 @@
+import { SellerManagement } from "@/app/(app)/components/invoice-form/sections/components/seller/seller-management";
import { type InvoiceData, type SellerData } from "@/app/schema";
-import { SellerManagement } from "@/components/seller-management";
import { AccordionContent } from "@/components/ui/accordion";
import { Input } from "@/components/ui/input";
import { InputHelperMessage } from "@/components/ui/input-helper-message";
diff --git a/src/app/schema/index.ts b/src/app/schema/index.ts
index a26516c..b5d94bf 100644
--- a/src/app/schema/index.ts
+++ b/src/app/schema/index.ts
@@ -846,115 +846,125 @@ export const invoiceItemSchema = z
export type InvoiceItemData = z.infer<typeof invoiceItemSchema>;
-export const sellerSchema = z.object({
- id: z.string().optional(),
+export const sellerSchema = z
+ .object({
+ id: z.string().optional(),
- name: z
- .string()
- .min(1, "Seller name is required")
- .max(500, "Seller name must not exceed 500 characters")
- .trim(),
- address: z
- .string()
- .min(1, "Seller address is required")
- .max(500, "Seller address must not exceed 500 characters")
- .trim(),
+ name: z
+ .string()
+ .min(1, "Seller name is required")
+ .max(500, "Seller name must not exceed 500 characters")
+ .trim(),
+ address: z
+ .string()
+ .min(1, "Seller address is required")
+ .max(500, "Seller address must not exceed 500 characters")
+ .trim(),
- vatNo: z
- .string()
- .max(200, "VAT number must not exceed 200 characters")
- .trim()
- .optional(),
- // not really only a vatNo anymore, it's a more general tax number (but we keep the name for simplicity, for now)
- vatNoLabelText: z
- .string()
- .min(1, "Tax number label is required")
- .max(50, "Tax number label must not exceed 50 characters")
- .trim()
- .default("VAT no")
- .describe(
- "Customizable tax number label. Defaults to ‘VAT no’, but you can change it to any text (e.g. Tax no, VAT no, etc.)",
- ),
- vatNoFieldIsVisible: z.boolean().default(true),
+ vatNo: z
+ .string()
+ .max(200, "VAT number must not exceed 200 characters")
+ .trim()
+ .optional(),
+ // not really only a vatNo anymore, it's a more general tax number (but we keep the name for simplicity, for now)
+ vatNoLabelText: z
+ .string()
+ .min(1, "Tax number label is required")
+ .max(50, "Tax number label must not exceed 50 characters")
+ .trim()
+ .default("VAT no")
+ .describe(
+ "Customizable tax number label. Defaults to ‘VAT no’, but you can change it to any text (e.g. Tax no, VAT no, etc.)",
+ ),
+ vatNoFieldIsVisible: z.boolean().default(true),
- email: z
- .string()
- .trim()
- .refine((val) => val === "" || z.string().email().safeParse(val).success, {
- message: "Invalid email address",
- })
- .optional(),
- emailFieldIsVisible: z.boolean().default(true),
+ email: z
+ .string()
+ .trim()
+ .refine(
+ (val) => val === "" || z.string().email().safeParse(val).success,
+ {
+ message: "Invalid email address",
+ },
+ )
+ .optional(),
+ emailFieldIsVisible: z.boolean().default(true),
- accountNumber: z
- .string()
- .max(200, "Account number must not exceed 200 characters")
- .trim()
- .optional(),
- accountNumberFieldIsVisible: z.boolean().default(true),
+ accountNumber: z
+ .string()
+ .max(200, "Account number must not exceed 200 characters")
+ .trim()
+ .optional(),
+ accountNumberFieldIsVisible: z.boolean().default(true),
- swiftBic: z
- .string()
- .max(200, "SWIFT/BIC must not exceed 200 characters")
- .trim()
- .optional(),
- swiftBicFieldIsVisible: z.boolean().default(true),
+ swiftBic: z
+ .string()
+ .max(200, "SWIFT/BIC must not exceed 200 characters")
+ .trim()
+ .optional(),
+ swiftBicFieldIsVisible: z.boolean().default(true),
- notes: z
- .string()
- .max(750, "Notes must not exceed 750 characters")
- .trim()
- .optional(),
- notesFieldIsVisible: z.boolean().default(true),
-});
+ notes: z
+ .string()
+ .max(750, "Notes must not exceed 750 characters")
+ .trim()
+ .optional(),
+ notesFieldIsVisible: z.boolean().default(true),
+ })
+ .strict();
export type SellerData = z.infer<typeof sellerSchema>;
-export const buyerSchema = z.object({
- id: z.string().optional(),
+export const buyerSchema = z
+ .object({
+ id: z.string().optional(),
- name: z
- .string()
- .min(1, "Buyer name is required")
- .max(500, "Buyer name must not exceed 500 characters")
- .trim(),
- address: z
- .string()
- .min(1, "Buyer address is required")
- .max(500, "Buyer address must not exceed 500 characters")
- .trim(),
- vatNo: z
- .string()
- .max(200, "VAT number must not exceed 200 characters")
- .trim()
- .optional(),
- vatNoLabelText: z
- .string()
- .min(1, "Tax number label is required")
- .max(50, "Tax number label must not exceed 50 characters")
- .trim()
- .default("VAT no")
- .describe(
- "Customizable tax number label. Defaults to ‘VAT no’, but you can change it to any text (e.g. Tax no, VAT no, etc.)",
- ),
- vatNoFieldIsVisible: z.boolean().default(true),
+ name: z
+ .string()
+ .min(1, "Buyer name is required")
+ .max(500, "Buyer name must not exceed 500 characters")
+ .trim(),
+ address: z
+ .string()
+ .min(1, "Buyer address is required")
+ .max(500, "Buyer address must not exceed 500 characters")
+ .trim(),
+ vatNo: z
+ .string()
+ .max(200, "VAT number must not exceed 200 characters")
+ .trim()
+ .optional(),
+ vatNoLabelText: z
+ .string()
+ .min(1, "Tax number label is required")
+ .max(50, "Tax number label must not exceed 50 characters")
+ .trim()
+ .default("VAT no")
+ .describe(
+ "Customizable tax number label. Defaults to ‘VAT no’, but you can change it to any text (e.g. Tax no, VAT no, etc.)",
+ ),
+ vatNoFieldIsVisible: z.boolean().default(true),
- email: z
- .string()
- .trim()
- .refine((val) => val === "" || z.string().email().safeParse(val).success, {
- message: "Invalid email address",
- })
- .optional(),
- emailFieldIsVisible: z.boolean().default(true),
+ email: z
+ .string()
+ .trim()
+ .refine(
+ (val) => val === "" || z.string().email().safeParse(val).success,
+ {
+ message: "Invalid email address",
+ },
+ )
+ .optional(),
+ emailFieldIsVisible: z.boolean().default(true),
- notes: z
- .string()
- .max(750, "Notes must not exceed 750 characters")
- .trim()
- .optional(),
- notesFieldIsVisible: z.boolean().default(true),
-});
+ notes: z
+ .string()
+ .max(750, "Notes must not exceed 750 characters")
+ .trim()
+ .optional(),
+ notesFieldIsVisible: z.boolean().default(true),
+ })
+ .strict();
export type BuyerData = z.infer<typeof buyerSchema>;
diff --git a/src/components/buyer-dialog.tsx b/src/components/buyer-dialog.tsx
deleted file mode 100644
index 190d769..0000000
--- a/src/components/buyer-dialog.tsx
+++ /dev/null
@@ -1,594 +0,0 @@
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Textarea } from "@/components/ui/textarea";
-import { buyerSchema, type BuyerData } from "@/app/schema";
-import { useForm } from "react-hook-form";
-import { zodResolver } from "@hookform/resolvers/zod";
-import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@/components/ui/form";
-import { Switch } from "@/components/ui/switch";
-import { CustomTooltip } from "@/components/ui/tooltip";
-import { toast } from "sonner";
-import { BUYERS_LOCAL_STORAGE_KEY } from "./buyer-management";
-import { z } from "zod";
-import { useState, useEffect } from "react";
-import * as Sentry from "@sentry/nextjs";
-import { InputHelperMessage } from "./ui/input-helper-message";
-
-const BUYER_FORM_ID = "buyer-form";
-
-interface BuyerDialogProps {
- isOpen: boolean;
- onClose: React.Dispatch<React.SetStateAction<boolean>>;
- handleBuyerAdd?: (
- buyer: BuyerData,
- { shouldApplyNewBuyerToInvoice }: { shouldApplyNewBuyerToInvoice: boolean },
- ) => void;
- handleBuyerEdit?: (buyer: BuyerData) => void;
- initialData: BuyerData | null;
- isEditMode: boolean;
- formValues?: Partial<BuyerData>;
-}
-
-/**
- * BuyerDialog component for adding or editing buyer information.
- *
- * This dialog provides a form interface for managing buyer data, including:
- * - Basic information (name, address, VAT number)
- * - Contact details (email)
- * - Additional notes
- *
- * Features:
- * - Pre-fill form with current invoice values (when creating new buyer)
- * - Apply newly created buyer to current invoice
- * - Validation for duplicate buyer names
- * - Unsaved changes warning on dialog close
- * - Field visibility toggles for optional information
- */
-export function BuyerDialog({
- isOpen,
- onClose,
- handleBuyerAdd,
- handleBuyerEdit,
- initialData,
- isEditMode,
- formValues,
-}: BuyerDialogProps) {
- const form = useForm<BuyerData>({
- resolver: zodResolver(buyerSchema),
- defaultValues: {
- id: initialData?.id ?? "",
- name: initialData?.name ?? "",
- address: initialData?.address ?? "",
- vatNo: initialData?.vatNo ?? "",
- vatNoLabelText: initialData?.vatNoLabelText ?? "VAT no",
- email: initialData?.email ?? "",
- emailFieldIsVisible: initialData?.emailFieldIsVisible ?? true,
- vatNoFieldIsVisible: initialData?.vatNoFieldIsVisible ?? true,
- notes: initialData?.notes ?? "",
- notesFieldIsVisible: initialData?.notesFieldIsVisible ?? true,
- },
- });
-
- const { isDirty } = form.formState;
-
- // by default, we want to apply the new buyer to the current invoice
- const [shouldApplyNewBuyerToInvoice, setShouldApplyNewBuyerToInvoice] =
- useState(true);
-
- const [shouldApplyFormValues, setShouldApplyFormValues] = useState(false);
-
- /**
- * Synchronizes form values based on the "Use current invoice data" switch state.
- *
- * When creating a new buyer (not in edit mode):
- * - If switch is ON: Populates the form with current invoice buyer data (formValues)
- * to allow users to save the current invoice's buyer information as a new saved buyer.
- * - If switch is OFF: Resets the form to empty/default values or initialData
- * to allow users to enter completely new buyer information from scratch.
- *
- * This effect does not run in edit mode to prevent overwriting the buyer being edited.
- */
- useEffect(() => {
- // Switch is ON: Pre-fill form with current invoice buyer data
- if (shouldApplyFormValues && formValues && !isEditMode) {
- form.reset({
- ...form.getValues(),
- ...formValues,
- });
- }
-
- // Switch is OFF: Reset form to empty state or initial data
- else if (!shouldApplyFormValues && !isEditMode) {
- form.reset(
- initialData ?? {
- id: "",
- name: "",
- address: "",
- vatNo: "",
- vatNoLabelText: "VAT no",
- email: "",
- emailFieldIsVisible: true,
- vatNoFieldIsVisible: true,
- notes: "",
- notesFieldIsVisible: true,
- },
- );
- }
- }, [shouldApplyFormValues, formValues, initialData, isEditMode, form]);
-
- /**
- * Prevents accidental data loss by warning users before leaving the page with unsaved changes.
- *
- * This effect sets up a browser-level warning that triggers when:
- * - The form has unsaved changes (isDirty is true)
- * - The user attempts to navigate away, refresh, or close the tab/window
- */
- useEffect(() => {
- function handler(e: BeforeUnloadEvent) {
- if (!isDirty) return;
- e.preventDefault();
- e.returnValue = ""; // required for Chrome
- }
-
- window.addEventListener("beforeunload", handler);
- return () => window.removeEventListener("beforeunload", handler);
- }, [isDirty]);
-
- /**
- * Closes the buyer dialog and resets the form to its default state.
- */
- function closeDialog() {
- form.reset();
- setShouldApplyFormValues(false);
- onClose(false);
- }
-
- function onSubmit(formValues: BuyerData) {
- try {
- // **RUNNING SOME VALIDATIONS FIRST**
-
- // Get existing buyers or initialize empty array
- const buyers = localStorage.getItem(BUYERS_LOCAL_STORAGE_KEY);
- const existingBuyers: unknown = buyers ? JSON.parse(buyers) : [];
-
- // Validate existing buyers array with Zod
- const existingBuyersValidationResult = z
- .array(buyerSchema)
- .safeParse(existingBuyers);
-
- if (!existingBuyersValidationResult.success) {
- console.error(
- "Invalid existing buyers data:",
- existingBuyersValidationResult.error,
- );
-
- // Show error toast
- toast.error("Error loading existing buyers", {
- richColors: true,
- description: "Please try again",
- });
-
- // Reset localStorage if validation fails
- localStorage.setItem(BUYERS_LOCAL_STORAGE_KEY, JSON.stringify([]));
-
- return;
- }
-
- // Validate buyer data against existing buyers
- const isDuplicateName = existingBuyersValidationResult.data.some(
- (buyer: BuyerData) =>
- buyer.name === formValues.name && buyer.id !== formValues.id,
- );
-
- if (isDuplicateName) {
- form.setError("name", {
- type: "manual",
- message: "A buyer with this name already exists",
- });
-
- // Focus on the name input field for user to fix the error
- form.setFocus("name");
-
- // Show error toast
- toast.error("A buyer with this name already exists", {
- richColors: true,
- });
-
- return;
- }
-
- if (isEditMode) {
- // Edit buyer
- handleBuyerEdit?.(formValues);
- } else {
- // Add new buyer
- handleBuyerAdd?.(formValues, { shouldApplyNewBuyerToInvoice });
- }
-
- // Close dialog
- closeDialog();
- } catch (error) {
- console.error("Failed to save buyer:", error);
-
- toast.error("Failed to save buyer", {
- description: "Please try again",
- richColors: true,
- });
-
- Sentry.captureException(error);
- }
- }
-
- return (
- <Dialog
- open={isOpen}
- onOpenChange={(open) => {
- if (!open) {
- // When the user attempts to close the dialog, check if the form has unsaved changes.
- // If the form is dirty (has been modified), prompt the user with a confirmation dialog
- // to prevent accidental data loss. If the user cancels the confirmation, prevent the
- // dialog from closing by returning early.
- if (
- isDirty &&
- !window.confirm(
- "You have unsaved changes in buyer details. Discard them?",
- )
- ) {
- return;
- }
- closeDialog();
- }
- }}
- >
- <DialogContent
- className="flex flex-col gap-0 overflow-y-visible p-0 sm:max-w-lg [&>button:last-child]:top-3.5"
- data-testid={`manage-buyer-dialog`}
- >
- <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"}
- </DialogTitle>
- <DialogDescription>
- {isEditMode
- ? "Edit the buyer details"
- : "Add a new buyer to use later in your invoices"}
- </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={shouldApplyFormValues}
- onCheckedChange={setShouldApplyFormValues}
- id="apply-form-values-switch"
- />
- <Label
- htmlFor="apply-form-values-switch"
- className="cursor-pointer"
- >
- Pre-fill with values from the current invoice form
- </Label>
- </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&apos;ve already entered in your
- current invoice form.
- </span>
- </div>
- )}
-
- <Form {...form}>
- <form
- onSubmit={form.handleSubmit(onSubmit)}
- className="space-y-4"
- id={BUYER_FORM_ID}
- >
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Name (Required)</FormLabel>
- <FormControl>
- <Textarea
- {...field}
- rows={3}
- placeholder="Enter buyer name"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="address"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Address (Required)</FormLabel>
- <FormControl>
- <Textarea
- {...field}
- rows={3}
- placeholder="Enter buyer address"
- />
- </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 }) => (
- <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">
- <FormField
- control={form.control}
- name="vatNoLabelText"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Label</FormLabel>
- <FormControl>
- <Input
- {...field}
- placeholder="Enter Tax number label"
- />
- </FormControl>
-
- {form.formState.errors.vatNoLabelText && (
- <FormMessage>
- {form.formState.errors.vatNoLabelText.message}
- </FormMessage>
- )}
-
- {!form.formState.errors.vatNoLabelText && (
- <InputHelperMessage>
- Set a custom label (e.g. VAT no, Tax no, etc.)
- </InputHelperMessage>
- )}
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="vatNo"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Value</FormLabel>
- <FormControl>
- <Input
- {...field}
- placeholder="Enter Tax number value"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </fieldset>
-
- {/* Email */}
- <div className="space-y-3 rounded-md border p-4">
- <FormField
- control={form.control}
- name="email"
- render={({ field }) => (
- <FormItem>
- <FormLabel className="mb-2 font-medium">Email</FormLabel>
- <FormControl>
- <Input
- {...field}
- type="email"
- placeholder="[email protected]"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="emailFieldIsVisible"
- render={({ field }) => (
- <FormItem>
- <div className="flex items-center gap-2">
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- id="emailFieldIsVisible"
- data-testid={`buyerEmailDialogFieldVisibilitySwitch`}
- aria-label={`Show the 'Email' field in the PDF`}
- />
- </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>
-
- {/* Notes */}
- <div className="space-y-3 rounded-md border p-4">
- <FormField
- control={form.control}
- name="notes"
- render={({ field }) => (
- <FormItem>
- <FormLabel className="mb-2 font-medium">Notes</FormLabel>
- <FormControl>
- <Textarea
- {...field}
- rows={3}
- placeholder="Enter notes (max 750 characters)"
- maxLength={750}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="notesFieldIsVisible"
- render={({ field }) => (
- <FormItem>
- <div className="flex items-center gap-2">
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- id="notes-field-visibility"
- data-testid={`buyerNotesDialogFieldVisibilitySwitch`}
- aria-label={`Show the 'Notes' field in the PDF`}
- />
- </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>
- </form>
- </Form>
-
- {/* Apply to Current Invoice switch remains at bottom */}
- {!isEditMode && (
- <div className="mt-4 flex flex-col gap-1 border-t pt-4">
- <div className="flex items-center gap-2">
- <Switch
- checked={shouldApplyNewBuyerToInvoice}
- onCheckedChange={setShouldApplyNewBuyerToInvoice}
- id="apply-buyer-to-current-invoice-switch"
- />
- <Label
- htmlFor="apply-buyer-to-current-invoice-switch"
- className="cursor-pointer"
- >
- Apply to Current 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>
- </div>
- )}
- </div>
- <DialogFooter className="border-border border-t px-6 py-4">
- <Button
- type="button"
- variant="outline"
- onClick={() => {
- // Check if the form has been modified (isDirty flag from react-hook-form).
- // If there are unsaved changes, show a browser confirmation dialog to prevent
- // accidental data loss. If the user clicks "Cancel" in the confirmation dialog,
- // prevent the dialog from closing by returning early.
- if (
- isDirty &&
- !window.confirm(
- "You have unsaved changes in buyer details. Discard them?",
- )
- ) {
- return;
- }
-
- closeDialog();
- }}
- >
- Cancel
- </Button>
- <Button
- type="button"
- onClick={async () => {
- // Validate form and focus first error field
- const result = await form.trigger(undefined, {
- shouldFocus: true,
- });
- if (!result) return;
-
- // submit the form
- onSubmit(form.getValues());
- }}
- form={BUYER_FORM_ID}
- >
- Save Buyer
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/src/components/seller-dialog.tsx b/src/components/seller-dialog.tsx
deleted file mode 100644
index 614a25f..0000000
--- a/src/components/seller-dialog.tsx
+++ /dev/null
@@ -1,699 +0,0 @@
-import { sellerSchema, type SellerData } from "@/app/schema";
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@/components/ui/form";
-import { Input } from "@/components/ui/input";
-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 { zodResolver } from "@hookform/resolvers/zod";
-import * as Sentry from "@sentry/nextjs";
-import { useEffect, useState } from "react";
-import { useForm } from "react-hook-form";
-import { toast } from "sonner";
-import { z } from "zod";
-import { SELLERS_LOCAL_STORAGE_KEY } from "./seller-management";
-import { InputHelperMessage } from "./ui/input-helper-message";
-
-const SELLER_FORM_ID = "seller-form";
-
-interface SellerDialogProps {
- isOpen: boolean;
- onClose: React.Dispatch<React.SetStateAction<boolean>>;
- handleSellerAdd?: (
- seller: SellerData,
- {
- shouldApplyNewSellerToInvoice,
- }: { shouldApplyNewSellerToInvoice: boolean },
- ) => void;
- handleSellerEdit?: (seller: SellerData) => void;
- initialData: SellerData | null;
- isEditMode: boolean;
- formValues?: Partial<SellerData>;
-}
-
-/**
- * SellerDialog component for adding or editing seller information.
- *
- * This dialog provides a form interface for managing seller data, including:
- * - Basic information (name, address, VAT number)
- * - Contact details (email)
- * - Banking information (account number, SWIFT/BIC)
- * - Additional notes
- *
- * Features:
- * - Pre-fill form with current invoice values (when creating new seller)
- * - Apply newly created seller to current invoice
- * - Validation for duplicate seller names
- * - Unsaved changes warning on dialog close
- * - Field visibility toggles for optional information
- */
-export function SellerDialog({
- isOpen,
- onClose,
- handleSellerAdd,
- handleSellerEdit,
- initialData,
- isEditMode,
- formValues,
-}: SellerDialogProps) {
- const form = useForm<SellerData>({
- resolver: zodResolver(sellerSchema),
- defaultValues: {
- id: initialData?.id ?? "",
- name: initialData?.name ?? "",
- address: initialData?.address ?? "",
- vatNo: initialData?.vatNo ?? "",
- vatNoLabelText: initialData?.vatNoLabelText ?? "VAT no",
- email: initialData?.email ?? "",
- emailFieldIsVisible: initialData?.emailFieldIsVisible ?? true,
- accountNumber: initialData?.accountNumber ?? "",
- swiftBic: initialData?.swiftBic ?? "",
- vatNoFieldIsVisible: initialData?.vatNoFieldIsVisible ?? true,
- accountNumberFieldIsVisible:
- initialData?.accountNumberFieldIsVisible ?? true,
- swiftBicFieldIsVisible: initialData?.swiftBicFieldIsVisible ?? true,
- notes: initialData?.notes ?? "",
- notesFieldIsVisible: initialData?.notesFieldIsVisible ?? true,
- },
- });
-
- const { isDirty } = form.formState;
-
- // by default, we want to apply the new seller to the current invoice
- const [shouldApplyNewSellerToInvoice, setShouldApplyNewSellerToInvoice] =
- useState(true);
-
- // Add state for applying form values
- const [shouldApplyFormValues, setShouldApplyFormValues] = useState(false);
-
- // Effect to update form values when switch is toggled
- useEffect(() => {
- // if the switch is on and we have form values, we want to apply the form values to the form
- if (shouldApplyFormValues && formValues && !isEditMode) {
- form.reset({
- ...form.getValues(),
- ...formValues,
- });
- }
-
- // if the switch is off and we have initial data, we want to apply the initial data to the form
- else if (!shouldApplyFormValues && !isEditMode) {
- form.reset(
- initialData ?? {
- id: "",
- name: "",
- address: "",
- vatNo: "",
- vatNoLabelText: "VAT no",
- email: "",
- emailFieldIsVisible: true,
- accountNumber: "",
- swiftBic: "",
- vatNoFieldIsVisible: true,
- accountNumberFieldIsVisible: true,
- swiftBicFieldIsVisible: true,
- notes: "",
- notesFieldIsVisible: true,
- },
- );
- }
- }, [shouldApplyFormValues, formValues, initialData, isEditMode, form]);
-
- /**
- * Prevents accidental data loss by warning users before leaving the page with unsaved changes.
- *
- * This effect sets up a browser-level warning that triggers when:
- * - The form has unsaved changes (isDirty is true)
- * - The user attempts to navigate away, refresh, or close the tab/window
- */
- useEffect(() => {
- function handler(e: BeforeUnloadEvent) {
- if (!isDirty) return;
- e.preventDefault();
- e.returnValue = ""; // required for Chrome
- }
-
- window.addEventListener("beforeunload", handler);
- return () => window.removeEventListener("beforeunload", handler);
- }, [isDirty]);
-
- /**
- * Closes the seller dialog and resets the form to its default state.
- */
- function closeDialog() {
- form.reset();
- setShouldApplyFormValues(false);
- onClose(false);
- }
-
- function onSubmit(formValues: SellerData) {
- try {
- // **RUNNING SOME VALIDATIONS FIRST**
-
- // Get existing sellers or initialize empty array
- const sellers = localStorage.getItem(SELLERS_LOCAL_STORAGE_KEY);
- const existingSellers: unknown = sellers ? JSON.parse(sellers) : [];
-
- // Validate existing sellers array with Zod
- const existingSellersValidationResult = z
- .array(sellerSchema)
- .safeParse(existingSellers);
-
- if (!existingSellersValidationResult.success) {
- console.error(
- "Invalid existing sellers data:",
- existingSellersValidationResult.error,
- );
-
- // Show error toast
- toast.error("Error loading existing sellers", {
- id: "error-loading-existing-sellers-error-toast",
- richColors: true,
- description: "Please try again",
- });
-
- // Reset localStorage if validation fails
- localStorage.setItem(SELLERS_LOCAL_STORAGE_KEY, JSON.stringify([]));
-
- return;
- }
-
- // we don't need to validate the name if we are editing an existing seller
-
- // Validate seller data against existing sellers
- const isDuplicateName = existingSellersValidationResult.data.some(
- (seller: SellerData) =>
- seller.name === formValues.name && seller.id !== formValues.id,
- );
-
- if (isDuplicateName) {
- form.setError("name", {
- type: "manual",
- message: "A seller with this name already exists",
- });
-
- // Focus on the name input field for user to fix the error
- form.setFocus("name");
-
- // Show error toast
- toast.error("A seller with this name already exists", {
- id: "seller-name-already-exists-error-toast",
- richColors: true,
- description: "Please try again",
- });
-
- return;
- }
-
- if (isEditMode) {
- // Edit seller
- handleSellerEdit?.(formValues);
- } else {
- // Add new seller
- handleSellerAdd?.(formValues, { shouldApplyNewSellerToInvoice });
- }
-
- // Close dialog
- closeDialog();
- } catch (error) {
- console.error("Failed to save seller:", error);
-
- toast.error("Failed to save seller", {
- id: "failed-to-save-seller-error-toast",
- description: "Please try again",
- richColors: true,
- });
-
- Sentry.captureException(error);
- }
- }
-
- return (
- <Dialog
- open={isOpen}
- onOpenChange={(open) => {
- if (!open) {
- // When the user attempts to close the dialog, check if the form has unsaved changes.
- // If the form is dirty (has been modified), prompt the user with a confirmation dialog
- // to prevent accidental data loss. If the user cancels the confirmation, prevent the
- // dialog from closing by returning early.
- if (
- isDirty &&
- !window.confirm(
- "You have unsaved changes in seller details. Discard them?",
- )
- ) {
- return;
- }
- closeDialog();
- }
- }}
- >
- <DialogContent
- className="flex flex-col gap-0 overflow-y-visible p-0 sm:max-w-lg [&>button:last-child]:top-3.5"
- data-testid={`manage-seller-dialog`}
- >
- <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"}
- </DialogTitle>
- <DialogDescription>
- {isEditMode
- ? "Edit the seller details"
- : "Add a new seller to use later in your invoices"}
- </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={shouldApplyFormValues}
- onCheckedChange={setShouldApplyFormValues}
- id="apply-form-values-switch"
- />
- <Label
- htmlFor="apply-form-values-switch"
- className="cursor-pointer"
- >
- Pre-fill with values from the current invoice form
- </Label>
- </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&apos;ve already entered in your
- current invoice form.
- </span>
- </div>
- )}
-
- <Form {...form}>
- <form
- onSubmit={form.handleSubmit(onSubmit)}
- className="space-y-4"
- id={SELLER_FORM_ID}
- >
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Name (Required)</FormLabel>
- <FormControl>
- <Textarea
- {...field}
- rows={3}
- placeholder="Enter seller name"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="address"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Address (Required)</FormLabel>
- <FormControl>
- <Textarea
- {...field}
- rows={3}
- placeholder="Enter seller address"
- />
- </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 }) => (
- <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">
- <FormField
- control={form.control}
- name="vatNoLabelText"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Label</FormLabel>
- <FormControl>
- <Input
- {...field}
- placeholder="Enter Tax number label"
- />
- </FormControl>
- {form.formState.errors.vatNoLabelText && (
- <FormMessage>
- {form.formState.errors.vatNoLabelText.message}
- </FormMessage>
- )}
-
- {!form.formState.errors.vatNoLabelText && (
- <InputHelperMessage>
- Set a custom label (e.g. VAT no, Tax no, etc.)
- </InputHelperMessage>
- )}
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="vatNo"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Value</FormLabel>
- <FormControl>
- <Input
- {...field}
- placeholder="Enter Tax number value"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </fieldset>
-
- {/* Email */}
- <div className="space-y-3 rounded-md border p-4">
- <FormField
- control={form.control}
- name="email"
- render={({ field }) => (
- <FormItem>
- <FormLabel className="mb-2 font-medium">Email</FormLabel>
- <FormControl>
- <Input
- {...field}
- type="email"
- placeholder="[email protected]"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="emailFieldIsVisible"
- render={({ field }) => (
- <FormItem>
- <div className="flex items-center gap-2">
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- id="emailFieldIsVisible"
- data-testid={`sellerEmailDialogFieldVisibilitySwitch`}
- aria-label={`Show the 'Email' field in the PDF`}
- />
- </FormControl>
- <CustomTooltip
- trigger={
- <Label htmlFor="emailFieldIsVisible">
- Show Seller Email in PDF
- </Label>
- }
- content='Show the "Email" field in the PDF'
- className="z-[1000]"
- />
- </div>
- </FormItem>
- )}
- />
- </div>
-
- {/* Account Number */}
- <div className="space-y-3 rounded-md border p-4">
- <FormField
- control={form.control}
- name="accountNumber"
- render={({ field }) => (
- <FormItem>
- <FormLabel className="mb-2 font-medium">
- Account Number
- </FormLabel>
- <FormControl>
- <Textarea
- {...field}
- rows={3}
- placeholder="Enter account number"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="accountNumberFieldIsVisible"
- render={({ field }) => (
- <FormItem>
- <div className="flex items-center gap-2">
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- id="accountNumberFieldIsVisible"
- aria-label={`Show the 'Account Number' field in the PDF`}
- />
- <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>
- </FormItem>
- )}
- />
- </div>
-
- {/* SWIFT/BIC */}
- <div className="space-y-3 rounded-md border p-4">
- <FormField
- control={form.control}
- name="swiftBic"
- render={({ field }) => (
- <FormItem>
- <FormLabel className="mb-2 font-medium">
- SWIFT/BIC
- </FormLabel>
- <FormControl>
- <Textarea
- {...field}
- rows={3}
- placeholder="Enter SWIFT/BIC code"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="swiftBicFieldIsVisible"
- render={({ field }) => (
- <FormItem>
- <div className="flex items-center gap-2">
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- id="swiftBicFieldIsVisible"
- aria-label={`Show the 'SWIFT/BIC' field in the PDF`}
- />
- <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>
-
- {/* Notes */}
- <div className="space-y-3 rounded-md border p-4">
- <FormField
- control={form.control}
- name="notes"
- render={({ field }) => (
- <FormItem>
- <FormLabel className="mb-2 font-medium">Notes</FormLabel>
- <FormControl>
- <Textarea
- {...field}
- rows={3}
- placeholder="Enter notes (max 750 characters)"
- maxLength={750}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="notesFieldIsVisible"
- render={({ field }) => (
- <FormItem>
- <div className="flex items-center gap-2">
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- id="notes-field-visibility"
- data-testid={`sellerNotesDialogFieldVisibilitySwitch`}
- aria-label={`Show the 'Notes' field in the PDF`}
- />
- </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>
- </form>
- </Form>
-
- {/* Apply to Current Invoice switch remains at the bottom */}
- {!isEditMode && (
- <div className="mt-4 flex flex-col gap-1 border-t pt-4">
- <div className="flex items-center gap-2">
- <Switch
- checked={shouldApplyNewSellerToInvoice}
- onCheckedChange={setShouldApplyNewSellerToInvoice}
- id="apply-seller-to-current-invoice-switch"
- />
- <Label
- htmlFor="apply-seller-to-current-invoice-switch"
- className="cursor-pointer"
- >
- Apply to Current 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>
- </div>
- )}
- </div>
- <DialogFooter className="border-border border-t px-6 py-4">
- <Button
- type="button"
- variant="outline"
- onClick={() => {
- // Check if the form has been modified (isDirty flag from react-hook-form).
- // If there are unsaved changes, show a browser confirmation dialog to prevent
- // accidental data loss. If the user clicks "Cancel" in the confirmation dialog,
- // prevent the dialog from closing by returning early.
- if (
- isDirty &&
- !window.confirm(
- "You have unsaved changes in seller details. Discard them?",
- )
- ) {
- 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 () => {
- // we manually trigger the form validation and submit the form
-
- // Validate form and focus first error field
- const result = await form.trigger(undefined, {
- shouldFocus: true,
- });
- if (!result) return;
-
- // submit the form
- onSubmit(form.getValues());
- }}
- form={SELLER_FORM_ID}
- >
- Save Seller
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/src/components/ui/alert-dialog.tsx b/src/components/ui/alert-dialog.tsx
index d222fdb..b446927 100644
--- a/src/components/ui/alert-dialog.tsx
+++ b/src/components/ui/alert-dialog.tsx
@@ -18,7 +18,7 @@ const AlertDialogOverlay = React.forwardRef<
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
- "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
+ "fixed inset-0 z-[200] bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
@@ -36,7 +36,7 @@ const AlertDialogContent = React.forwardRef<
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
- "fixed left-1/2 top-1/2 z-50 grid max-h-[calc(100%-4rem)] w-full -translate-x-1/2 -translate-y-1/2 gap-4 overflow-y-auto border border-slate-200 bg-white p-6 shadow-lg shadow-black/5 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] dark:border-slate-800 dark:bg-slate-950 sm:max-w-[400px] sm:rounded-xl",
+ "fixed left-1/2 top-1/2 z-[200] grid max-h-[calc(100%-4rem)] w-full -translate-x-1/2 -translate-y-1/2 gap-4 overflow-y-auto border border-slate-200 bg-white p-6 shadow-lg shadow-black/5 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] dark:border-slate-800 dark:bg-slate-950 sm:max-w-[400px] sm:rounded-xl",
className,
)}
{...props}