Skip to content

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

feat: add cancel confirm dialog for seller/buyer dialog, update gh actions, added new script update-github-actions in package.json (#198)

Vlad Sazonau8047c8f0c42e
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index b8ad049..8667dfd 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -23,13 +23,13 @@ jobs:
- run: |
echo "Environment URL - ${{ github.event_name == 'deployment_status' && github.event.deployment_status.environment_url }}"
# we use pinned versions because there are safer to use: https://x.com/paulmillr/status/1900948425325031448
- - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
name: πŸ›ŽοΈ Checkout repository
- - uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0
+ - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
name: πŸ“¦ Setup pnpm
- - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # 4.3.0
+ - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
name: πŸ“š Setup Node.js
with:
node-version: lts/*
@@ -50,7 +50,7 @@ jobs:
continue-on-error: true
run: pnpm exec playwright test --reporter=html,list
- - uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 #4.6.1
+ - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
name: 🎲 Upload Playwright report
if: ${{ !cancelled() }}
with:
@@ -73,11 +73,12 @@ jobs:
- name: πŸ“§ Send email
if: always()
- uses: dawidd6/action-send-mail@611879133a9569642c41be66f4a323286e9b8a3b # v4
+ # https://github.com/dawidd6/action-send-mail
+ uses: dawidd6/action-send-mail@d38f3f7cd391cdebfe0d38efc3998b935e951c4f # v16
with:
server_address: smtp.gmail.com
server_port: 587
- from: GitHub Actions
+ from: "GitHub Actions (no-reply) <${{ secrets.EMAIL_USERNAME }}>"
to: ${{ secrets.EMAIL_USERNAME }}
username: ${{ secrets.EMAIL_USERNAME }}
password: ${{ secrets.EMAIL_PASSWORD }}
@@ -91,3 +92,7 @@ jobs:
- 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) }}
attachments: playwright-output/report/index.html
+
+ - name: ❌ Mark workflow failed on E2E Tests failure
+ if: steps.playwright.outcome == 'failure'
+ run: exit 1
diff --git a/.github/workflows/knip.yml b/.github/workflows/knip.yml
new file mode 100644
index 0000000..28a771b
--- /dev/null
+++ b/.github/workflows/knip.yml
@@ -0,0 +1,69 @@
+name: πŸ” Knip
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+
+jobs:
+ knip:
+ name: Run Knip
+ timeout-minutes: 5
+ runs-on: ubuntu-latest
+ steps:
+ # we use pinned versions because there are safer to use: https://x.com/paulmillr/status/1900948425325031448
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ name: πŸ›ŽοΈ Checkout repository
+
+ - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
+ name: πŸ“¦ Setup pnpm
+
+ - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
+ name: πŸ“š Setup Node.js
+ with:
+ node-version: lts/*
+ cache: "pnpm"
+
+ - name: 🚚 Install dependencies
+ run: pnpm install
+
+ - name: πŸ”Ž Run Knip
+ id: knip
+ continue-on-error: true
+ run: pnpm knip
+
+ - name: πŸ” Get PR URL
+ if: steps.knip.outcome == 'failure'
+ id: pr-url
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ PR_URL=$(curl -s \
+ -H "Authorization: Bearer $GITHUB_TOKEN" \
+ -H "Accept: application/vnd.github+json" \
+ "https://api.github.com/repos/${{ github.repository }}/pulls?head=${{ github.repository_owner }}:${{ github.ref_name }}" \
+ | jq -r '.[0].html_url // empty')
+ echo "pr_url=$PR_URL" >> "$GITHUB_OUTPUT"
+
+ - name: πŸ“§ Send email
+ if: steps.knip.outcome == 'failure'
+ # https://github.com/dawidd6/action-send-mail
+ uses: dawidd6/action-send-mail@d38f3f7cd391cdebfe0d38efc3998b935e951c4f # v16
+ with:
+ server_address: smtp.gmail.com
+ server_port: 587
+ from: "GitHub Actions (no-reply) <${{ secrets.EMAIL_USERNAME }}>"
+ to: ${{ secrets.EMAIL_USERNAME }}
+ username: ${{ secrets.EMAIL_USERNAME }}
+ password: ${{ secrets.EMAIL_PASSWORD }}
+ subject: ❌ Knip Failed for ${{ github.repository }}
+ body: |
+ Knip for ${{ github.repository }} has failed.
+
+ 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) }}
+
+ - name: ❌ Mark workflow failed on Knip failure
+ if: steps.knip.outcome == 'failure'
+ run: exit 1
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index a754a16..ca1bdc5 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -12,13 +12,13 @@ jobs:
runs-on: ubuntu-latest
steps:
# we use pinned versions because there are safer to use: https://x.com/paulmillr/status/1900948425325031448
- - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
name: πŸ›ŽοΈ Checkout repository
- - uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0
+ - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
name: πŸ“¦ Setup pnpm
- - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # 4.3.0
+ - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
name: πŸ“š Setup Node.js
with:
node-version: lts/*
@@ -42,16 +42,17 @@ jobs:
-H "Authorization: Bearer $GITHUB_TOKEN" \
-H "Accept: application/vnd.github+json" \
"https://api.github.com/repos/${{ github.repository }}/pulls?head=${{ github.repository_owner }}:${{ github.ref_name }}" \
- | jq -r '.[0].html_url')
+ | jq -r '.[0].html_url // empty')
echo "pr_url=$PR_URL" >> "$GITHUB_OUTPUT"
- name: πŸ“§ Send email
if: steps.lint.outcome == 'failure'
- uses: dawidd6/action-send-mail@611879133a9569642c41be66f4a323286e9b8a3b # v4
+ # https://github.com/dawidd6/action-send-mail
+ uses: dawidd6/action-send-mail@d38f3f7cd391cdebfe0d38efc3998b935e951c4f # v16
with:
server_address: smtp.gmail.com
server_port: 587
- from: GitHub Actions
+ from: "GitHub Actions (no-reply) <${{ secrets.EMAIL_USERNAME }}>"
to: ${{ secrets.EMAIL_USERNAME }}
username: ${{ secrets.EMAIL_USERNAME }}
password: ${{ secrets.EMAIL_PASSWORD }}
@@ -62,3 +63,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) }}
+
+ - name: ❌ Mark workflow failed on Linting failure
+ if: steps.lint.outcome == 'failure'
+ run: exit 1
diff --git a/.github/workflows/type-check.yml b/.github/workflows/type-check.yml
index fce01be..943ce62 100644
--- a/.github/workflows/type-check.yml
+++ b/.github/workflows/type-check.yml
@@ -12,13 +12,13 @@ jobs:
runs-on: ubuntu-latest
steps:
# we use pinned versions because there are safer to use: https://x.com/paulmillr/status/1900948425325031448
- - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
name: πŸ›ŽοΈ Checkout repository
- - uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0
+ - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
name: πŸ“¦ Setup pnpm
- - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # 4.3.0
+ - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
name: πŸ“š Setup Node.js
with:
node-version: lts/*
@@ -42,16 +42,17 @@ jobs:
-H "Authorization: Bearer $GITHUB_TOKEN" \
-H "Accept: application/vnd.github+json" \
"https://api.github.com/repos/${{ github.repository }}/pulls?head=${{ github.repository_owner }}:${{ github.ref_name }}" \
- | jq -r '.[0].html_url')
+ | jq -r '.[0].html_url // empty')
echo "pr_url=$PR_URL" >> "$GITHUB_OUTPUT"
- name: πŸ“§ Send email
if: steps.type-check.outcome == 'failure'
- uses: dawidd6/action-send-mail@611879133a9569642c41be66f4a323286e9b8a3b # v4
+ # https://github.com/dawidd6/action-send-mail
+ uses: dawidd6/action-send-mail@d38f3f7cd391cdebfe0d38efc3998b935e951c4f # v16
with:
server_address: smtp.gmail.com
server_port: 587
- from: GitHub Actions
+ from: "GitHub Actions (no-reply) <${{ secrets.EMAIL_USERNAME }}>"
to: ${{ secrets.EMAIL_USERNAME }}
username: ${{ secrets.EMAIL_USERNAME }}
password: ${{ secrets.EMAIL_PASSWORD }}
@@ -62,3 +63,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) }}
+
+ - name: ❌ Mark workflow failed on Type Check failure
+ if: steps.type-check.outcome == 'failure'
+ run: exit 1
diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml
index b456dbf..74d85f9 100644
--- a/.github/workflows/unit-tests.yml
+++ b/.github/workflows/unit-tests.yml
@@ -12,13 +12,13 @@ jobs:
runs-on: ubuntu-latest
steps:
# we use pinned versions because there are safer to use: https://x.com/paulmillr/status/1900948425325031448
- - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
name: πŸ›ŽοΈ Checkout repository
- - uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0
+ - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
name: πŸ“¦ Setup pnpm
- - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # 4.3.0
+ - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
name: πŸ“š Setup Node.js
with:
node-version: lts/*
@@ -42,16 +42,17 @@ jobs:
-H "Authorization: Bearer $GITHUB_TOKEN" \
-H "Accept: application/vnd.github+json" \
"https://api.github.com/repos/${{ github.repository }}/pulls?head=${{ github.repository_owner }}:${{ github.ref_name }}" \
- | jq -r '.[0].html_url')
+ | jq -r '.[0].html_url // empty')
echo "pr_url=$PR_URL" >> "$GITHUB_OUTPUT"
- name: πŸ“§ Send email
if: steps.vitest.outcome == 'failure'
- uses: dawidd6/action-send-mail@611879133a9569642c41be66f4a323286e9b8a3b # v4
+ # https://github.com/dawidd6/action-send-mail
+ uses: dawidd6/action-send-mail@d38f3f7cd391cdebfe0d38efc3998b935e951c4f # v16
with:
server_address: smtp.gmail.com
server_port: 587
- from: GitHub Actions
+ from: "GitHub Actions (no-reply) <${{ secrets.EMAIL_USERNAME }}>"
to: ${{ secrets.EMAIL_USERNAME }}
username: ${{ secrets.EMAIL_USERNAME }}
password: ${{ secrets.EMAIL_PASSWORD }}
@@ -62,3 +63,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) }}
+
+ - name: ❌ Mark workflow failed on Unit Tests failure
+ if: steps.vitest.outcome == 'failure'
+ run: exit 1
diff --git a/e2e/buyer.test.ts b/e2e/buyer.test.ts
index bb98138..942a8c8 100644
--- a/e2e/buyer.test.ts
+++ b/e2e/buyer.test.ts
@@ -161,7 +161,7 @@ test.describe("Buyer management", () => {
const buyerLockedBanner = buyerForm.getByTestId("buyer-locked-banner");
await expect(buyerLockedBanner).toBeVisible();
await expect(buyerLockedBanner).toContainText(
- 'To modify buyer details, click the "Edit buyer" button (pencil icon) next to the dropdown above.',
+ "To modify buyer details, click the Edit buyer button (pencil icon) next to the dropdown above.",
);
const nameInput = buyerForm.getByRole("textbox", {
@@ -219,10 +219,12 @@ test.describe("Buyer management", () => {
await expect(notesSwitchNotInDialog).toBeChecked();
await expect(notesSwitchNotInDialog).toBeDisabled();
- // Verify the buyer appears in the dropdown
+ // Verify the buyer is selected in dropdown
await expect(
- buyerForm.getByRole("combobox", { name: "Select Buyer" }),
- ).toContainText(TEST_BUYER_DATA.name);
+ buyerForm
+ .getByRole("combobox", { name: "Select Buyer" })
+ .locator("option:checked"),
+ ).toHaveText(TEST_BUYER_DATA.name);
/*
* TEST EDIT FUNCTIONALITY IN BUYER MANAGEMENT DIALOG
@@ -277,6 +279,7 @@ test.describe("Buyer management", () => {
// Update some data in edit mode
const updatedName = "Updated Client Corp";
+
await manageBuyerDialog
.getByRole("textbox", { name: "Name" })
.fill(updatedName);
@@ -298,6 +301,13 @@ test.describe("Buyer management", () => {
page.getByText("Buyer updated successfully", { exact: true }),
).toBeVisible();
+ // Verify buyer is selected in dropdown
+ await expect(
+ buyerForm
+ .getByRole("combobox", { name: "Select Buyer" })
+ .locator("option:checked"),
+ ).toHaveText(updatedName);
+
/*
* TEST UPDATED INFORMATION IN INVOICE FORM AFTER UPDATING BUYER IN DIALOG
*/
@@ -365,10 +375,18 @@ test.describe("Buyer management", () => {
const buyerForm = page.getByTestId(`buyer-information-section`);
+ // Verify buyer is not selected in dropdown
+ await expect(
+ buyerForm
+ .getByRole("combobox", { name: "Select Buyer" })
+ .locator("option:checked"),
+ ).toHaveText("No buyer selected (default)");
+
// Buyer should appear in dropdown options but not be selected
await expect(
buyerForm.getByRole("combobox", { name: "Select Buyer" }),
).toBeVisible();
+
await expect(
buyerForm.getByRole("combobox", { name: "Select Buyer" }),
).toHaveValue("");
@@ -427,7 +445,9 @@ test.describe("Buyer management", () => {
});
// Buyer is currently selected in dropdown
- await expect(buyerDropdown).not.toHaveValue("");
+ await expect(buyerDropdown.locator("option:checked")).toHaveText(
+ TEST_BUYER_DATA.name,
+ );
// Verify locked banner is visible when buyer is selected
await expect(buyerForm.getByTestId("buyer-locked-banner")).toBeVisible();
@@ -440,6 +460,11 @@ test.describe("Buyer management", () => {
page.getByText("Buyer restored to default", { exact: true }),
).toBeVisible();
+ // Verify buyer is not selected in dropdown
+ await expect(buyerDropdown.locator("option:checked")).toHaveText(
+ "No buyer selected (default)",
+ );
+
// Verify locked banner is hidden after deselecting buyer
await expect(buyerForm.getByTestId("buyer-locked-banner")).toBeHidden();
@@ -464,6 +489,11 @@ test.describe("Buyer management", () => {
}),
).toBeVisible();
+ // Verify buyer is selected in dropdown
+ await expect(buyerDropdown.locator("option:checked")).toHaveText(
+ TEST_BUYER_DATA.name,
+ );
+
// Verify locked banner is visible again after reselecting buyer
await expect(buyerForm.getByTestId("buyer-locked-banner")).toBeVisible();
@@ -564,6 +594,12 @@ test.describe("Buyer management", () => {
buyerForm.getByRole("combobox", { name: "Select Buyer" }),
).toBeHidden();
+ // Verify "New Buyer" button is visible after deletion
+ const newBuyerButton = buyerForm.getByRole("button", { name: "New Buyer" });
+
+ await expect(newBuyerButton).toBeVisible();
+ await expect(newBuyerButton).toBeEnabled();
+
// Verify form is reset to default values
await expect(buyerForm.getByRole("textbox", { name: "Name" })).toHaveValue(
DEFAULT_BUYER_DATA.name,
@@ -583,4 +619,137 @@ test.describe("Buyer management", () => {
.getByRole("textbox", { name: "Value" }),
).toHaveValue(DEFAULT_BUYER_DATA.vatNo);
});
+
+ test.describe("discard changes confirmation", () => {
+ test("clean form - Cancel closes without confirm", async ({ page }) => {
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ 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);
+ });
+
+ test("clean form - X button closes without confirm", async ({ page }) => {
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ 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);
+ });
+
+ test("dirty form - Cancel - accept discards changes and closes", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
+ await manageBuyerDialog
+ .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();
+
+ await expect(manageBuyerDialog).toBeHidden();
+ });
+
+ test("dirty form - Cancel - dismiss keeps dialog open with values intact", 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("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?",
+ );
+
+ // Dismiss the dialog to keep the form values intact
+ await dialog.dismiss();
+ });
+
+ await manageBuyerDialog.getByRole("button", { name: "Cancel" }).click();
+
+ await expect(manageBuyerDialog).toBeVisible();
+ await expect(nameInput).toHaveValue("Unsaved Buyer");
+ });
+
+ test("dirty form - X button - accept discards changes and closes", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
+ await manageBuyerDialog
+ .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();
+
+ await expect(manageBuyerDialog).toBeHidden();
+ });
+
+ test("dirty form - Escape - accept discards changes and closes", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Buyer" }).click();
+
+ const manageBuyerDialog = page.getByTestId("manage-buyer-dialog");
+ await manageBuyerDialog
+ .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");
+
+ await expect(manageBuyerDialog).toBeHidden();
+ });
+ });
});
diff --git a/e2e/seller.test.ts b/e2e/seller.test.ts
index 5154d0b..fa49b36 100644
--- a/e2e/seller.test.ts
+++ b/e2e/seller.test.ts
@@ -196,11 +196,21 @@ test.describe("Seller management", () => {
// Verify all saved details in the Seller Information section form
const sellerForm = page.getByTestId(`seller-information-section`);
+ // Verify the seller appears in the dropdown
+ const sellerDropdown = sellerForm.getByRole("combobox", {
+ name: "Select Seller",
+ });
+
+ // Verify the seller is selected in dropdown
+ await expect(sellerDropdown.locator("option:checked")).toHaveText(
+ TEST_SELLER_DATA.name,
+ );
+
// Verify the locked banner is visible with correct text
const sellerLockedBanner = sellerForm.getByTestId("seller-locked-banner");
await expect(sellerLockedBanner).toBeVisible();
await expect(sellerLockedBanner).toContainText(
- 'To modify seller details, click the "Edit seller" button (pencil icon) next to the dropdown above.',
+ "To modify seller details, click the Edit seller button (pencil icon) next to the dropdown above.",
);
// Seller Name
@@ -380,6 +390,7 @@ test.describe("Seller management", () => {
const applyToInvoiceSwitch = manageSellerDialog.getByRole("switch", {
name: "Apply to Current Invoice",
});
+
await expect(applyToInvoiceSwitch).toBeChecked();
await applyToInvoiceSwitch.click();
await expect(applyToInvoiceSwitch).not.toBeChecked();
@@ -395,13 +406,17 @@ test.describe("Seller management", () => {
const sellerForm = page.getByTestId(`seller-information-section`);
+ const sellerDropdown = sellerForm.getByRole("combobox", {
+ name: "Select Seller",
+ });
+
// Seller should appear in dropdown options but not be selected
- await expect(
- sellerForm.getByRole("combobox", { name: "Select Seller" }),
- ).toBeVisible();
- await expect(
- sellerForm.getByRole("combobox", { name: "Select Seller" }),
- ).toHaveValue("");
+ await expect(sellerDropdown).toBeVisible();
+
+ // Verify the seller is not selected in dropdown
+ await expect(sellerDropdown.locator("option:checked")).toHaveText(
+ "No seller selected (default)",
+ );
// Form fields should still contain default values (seller was not applied)
await expect(sellerForm.getByRole("textbox", { name: "Name" })).toHaveValue(
@@ -465,7 +480,9 @@ test.describe("Seller management", () => {
});
// Seller is currently selected in dropdown
- await expect(sellerDropdown).not.toHaveValue("");
+ await expect(sellerDropdown.locator("option:checked")).toHaveText(
+ TEST_SELLER_DATA.name,
+ );
// Verify locked banner is visible when seller is selected
await expect(sellerForm.getByTestId("seller-locked-banner")).toBeVisible();
@@ -478,6 +495,11 @@ test.describe("Seller management", () => {
page.getByText("Seller restored to default", { exact: true }),
).toBeVisible();
+ // Verify seller is not selected in dropdown
+ await expect(sellerDropdown.locator("option:checked")).toHaveText(
+ "No seller selected (default)",
+ );
+
// Verify locked banner is hidden after deselecting seller
await expect(sellerForm.getByTestId("seller-locked-banner")).toBeHidden();
@@ -502,6 +524,11 @@ test.describe("Seller management", () => {
}),
).toBeVisible();
+ // Verify seller is selected in dropdown
+ await expect(sellerDropdown.locator("option:checked")).toHaveText(
+ TEST_SELLER_DATA.name,
+ );
+
// Verify locked banner is visible again after reselecting seller
await expect(sellerForm.getByTestId("seller-locked-banner")).toBeVisible();
@@ -561,9 +588,14 @@ test.describe("Seller management", () => {
// Verify seller was added
const sellerForm = page.getByTestId(`seller-information-section`);
- await expect(
- sellerForm.getByRole("combobox", { name: "Select Seller" }),
- ).toContainText(testData.name);
+
+ const sellerDropdown = sellerForm.getByRole("combobox", {
+ name: "Select Seller",
+ });
+
+ await expect(sellerDropdown.locator("option:checked")).toHaveText(
+ testData.name,
+ );
// Click delete button
await sellerForm.getByRole("button", { name: "Delete seller" }).click();
@@ -606,6 +638,14 @@ test.describe("Seller management", () => {
sellerForm.getByRole("combobox", { name: "Select Seller" }),
).toBeHidden();
+ // Verify "New Seller" button is visible after deletion
+ const newSellerButton = sellerForm.getByRole("button", {
+ name: "New Seller",
+ });
+
+ await expect(newSellerButton).toBeVisible();
+ await expect(newSellerButton).toBeEnabled();
+
// Verify form is reset to default values
await expect(sellerForm.getByRole("textbox", { name: "Name" })).toHaveValue(
DEFAULT_SELLER_DATA.name,
@@ -638,4 +678,146 @@ test.describe("Seller management", () => {
sellerForm.getByRole("textbox", { name: "SWIFT/BIC" }),
).toHaveValue(DEFAULT_SELLER_DATA.swiftBic);
});
+
+ test.describe("discard changes confirmation", () => {
+ test("clean form - Cancel closes without confirm", async ({ page }) => {
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ 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);
+ });
+
+ test("clean form - X button closes without confirm", async ({ page }) => {
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ 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);
+ });
+
+ test("dirty form - Cancel - accept discards changes and closes", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ const manageSellerDialog = page.getByTestId("manage-seller-dialog");
+ await manageSellerDialog
+ .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");
+
+ // Verify the dialog shows the expected discard warning message
+ expect(dialog.message()).toBe(
+ "You have unsaved changes in seller details. Discard them?",
+ );
+
+ // Accept the dialog to confirm discarding changes
+ await dialog.accept();
+ });
+
+ // 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(manageSellerDialog).toBeHidden();
+ });
+
+ test("dirty form - Cancel - dismiss keeps dialog open with values intact", 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("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?",
+ );
+
+ // Dismiss the dialog to keep the form values intact
+ await dialog.dismiss();
+ });
+
+ await manageSellerDialog.getByRole("button", { name: "Cancel" }).click();
+
+ await expect(manageSellerDialog).toBeVisible();
+ await expect(nameInput).toHaveValue("Unsaved Seller");
+ });
+
+ test("dirty form - X button - accept discards changes and closes", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ const manageSellerDialog = page.getByTestId("manage-seller-dialog");
+ await manageSellerDialog
+ .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();
+
+ await expect(manageSellerDialog).toBeHidden();
+ });
+
+ test("dirty form - Escape - accept discards changes and closes", async ({
+ page,
+ }) => {
+ await page.getByRole("button", { name: "New Seller" }).click();
+
+ const manageSellerDialog = page.getByTestId("manage-seller-dialog");
+ await manageSellerDialog
+ .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");
+
+ await expect(manageSellerDialog).toBeHidden();
+ });
+ });
});
diff --git a/package.json b/package.json
index dbe5190..bf13fb6 100644
--- a/package.json
+++ b/package.json
@@ -31,7 +31,8 @@
"expose-to-internet": "pnpm dlx cloudflared tunnel --url http://localhost:3000",
"cloudflared:tunnel": "pnpm dlx cloudflared tunnel run easy-invoice-pdf-local-dev",
"corepack:enable": "corepack enable",
- "corepack:prepare": "corepack prepare pnpm@latest"
+ "corepack:prepare": "corepack prepare pnpm@latest",
+ "update-github-actions": "pnpm dlx actions-up"
},
"dependencies": {
"@hookform/resolvers": "3.9.0",
@@ -97,6 +98,7 @@
"@types/react": "18.3.12",
"@types/react-dom": "18.3.1",
"@typescript/native-preview": "7.0.0-dev.20260217.1",
+ "actions-up": "1.12.0",
"autoprefixer": "10.4.21",
"dotenv": "17.2.3",
"eslint": "9.33.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 257617e..58ff7c2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -192,6 +192,9 @@ importers:
'@typescript/native-preview':
specifier: 7.0.0-dev.20260217.1
version: 7.0.0-dev.20260217.1
+ actions-up:
+ specifier: 1.12.0
+ version: 1.12.0
autoprefixer:
specifier: 10.4.21
version: 10.4.21([email protected])
@@ -251,7 +254,7 @@ importers:
vitest:
specifier: 3.2.4
packages:
@@ -2910,6 +2913,11 @@ packages:
engines: {node: '>=0.4.0'}
hasBin: true
+ resolution: {integrity: sha512-EFAv3XX3gfjfWhy5e6Kw1PpC0DrTSuK4e77xoS27hqcrjf92C+yCs05tIsBPGFZv8+EichF8HMTtimuMj2sv+A==}
+ engines: {node: ^18.0.0 || >=20.0.0}
+ hasBin: true
+
resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}
engines: {node: '>= 6.0.0'}
@@ -2937,6 +2945,10 @@ packages:
resolution: {integrity: sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==}
+ resolution: {integrity: sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==}
engines: {node: '>=8'}
@@ -3606,6 +3618,10 @@ packages:
resolution: {integrity: sha512-d4lC8xfavMeBjzGr2vECC3fsGXziXZQyJxD868h2M/mBI3PwAuODxAkLkq5HYuvrPYcUtiLzsTo8U3PgX3Ocww==}
engines: {node: '>=10.13.0'}
+ resolution: {integrity: sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ==}
+ engines: {node: '>=8.6'}
+
resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}
engines: {node: '>=0.12'}
@@ -5065,6 +5081,9 @@ packages:
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
+ resolution: {integrity: sha512-Zt/AmG6qRU3e+WnzGGLuMCEAO/dAu45stNbHY223tUxldaDAeE+FxSPsd9Q+j+paejmm0ZbrNVs5Sraqy3dRxA==}
+
resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==}
@@ -5932,11 +5951,6 @@ packages:
resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
hasBin: true
- resolution: {integrity: sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==}
- engines: {node: '>=10'}
- hasBin: true
-
resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==}
engines: {node: '>=10'}
@@ -6792,6 +6806,11 @@ packages:
engines: {node: '>= 14'}
hasBin: true
+ resolution: {integrity: sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg==}
+ engines: {node: '>= 14.6'}
+ hasBin: true
+
resolution: {integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==}
engines: {node: '>=6'}
@@ -7811,7 +7830,7 @@ snapshots:
'@opentelemetry/instrumentation': 0.57.2(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.28.0
forwarded-parse: 2.1.2
- semver: 7.7.2
+ semver: 7.7.4
transitivePeerDependencies:
- supports-color
@@ -7936,7 +7955,7 @@ snapshots:
'@types/shimmer': 1.2.0
import-in-the-middle: 1.13.1
require-in-the-middle: 7.5.2
- semver: 7.7.2
+ semver: 7.7.4
shimmer: 1.2.1
transitivePeerDependencies:
- supports-color
@@ -9298,7 +9317,7 @@ snapshots:
fast-glob: 3.3.3
is-glob: 4.0.3
minimatch: 9.0.5
- semver: 7.7.2
+ semver: 7.7.4
ts-api-utils: 2.1.0([email protected])
typescript: 5.9.3
transitivePeerDependencies:
@@ -9469,14 +9488,14 @@ snapshots:
chai: 5.2.1
tinyrainbow: 2.0.0
dependencies:
'@vitest/spy': 3.2.4
estree-walker: 3.0.3
magic-string: 0.30.17
optionalDependencies:
'@vitest/[email protected]':
dependencies:
@@ -9606,6 +9625,15 @@ snapshots:
+ dependencies:
+ cac: 6.7.14
+ enquirer: 2.4.1
+ nanospinner: 1.2.2
+ picocolors: 1.1.1
+ semver: 7.7.4
+ yaml: 2.8.3
+
dependencies:
debug: 4.4.1
@@ -9637,6 +9665,8 @@ snapshots:
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
+
dependencies:
type-fest: 0.21.3
@@ -10282,6 +10312,11 @@ snapshots:
graceful-fs: 4.2.11
tapable: 2.2.2
+ dependencies:
+ ansi-colors: 4.1.3
+ strip-ansi: 6.0.1
+
@@ -11350,7 +11385,7 @@ snapshots:
dependencies:
- semver: 7.7.2
+ semver: 7.7.4
@@ -12276,6 +12311,10 @@ snapshots:
+ dependencies:
+ picocolors: 1.1.1
+
optional: true
@@ -12355,7 +12394,7 @@ snapshots:
dependencies:
- semver: 7.7.2
+ semver: 7.7.4
optional: true
@@ -13249,8 +13288,6 @@ snapshots:
-
@@ -13350,7 +13387,7 @@ snapshots:
dependencies:
color: 4.2.3
detect-libc: 2.0.3
- semver: 7.7.2
+ semver: 7.7.4
optionalDependencies:
'@img/sharp-darwin-arm64': 0.33.5
'@img/sharp-darwin-x64': 0.33.5
@@ -14077,13 +14114,13 @@ snapshots:
string_decoder: 1.3.0
util-deprecate: 1.0.2
dependencies:
cac: 6.7.14
debug: 4.4.1
es-module-lexer: 1.7.0
pathe: 2.0.3
transitivePeerDependencies:
- '@types/node'
- jiti
@@ -14098,7 +14135,7 @@ snapshots:
- tsx
- yaml
dependencies:
esbuild: 0.25.0
fdir: 6.4.4([email protected])
@@ -14112,13 +14149,13 @@ snapshots:
jiti: 2.4.2
terser: 5.43.1
tsx: 4.19.4
- yaml: 2.7.0
+ yaml: 2.8.3
dependencies:
'@types/chai': 5.2.2
'@vitest/expect': 3.2.4
'@vitest/pretty-format': 3.2.4
'@vitest/runner': 3.2.4
'@vitest/snapshot': 3.2.4
@@ -14136,8 +14173,8 @@ snapshots:
tinyglobby: 0.2.14
tinypool: 1.1.1
tinyrainbow: 2.0.0
why-is-node-running: 2.3.0
optionalDependencies:
'@types/debug': 4.1.12
@@ -14313,6 +14350,8 @@ snapshots:
+
dependencies:
camelcase: 5.3.1
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 d6f479e..b01ed4e 100644
--- a/src/app/(app)/components/invoice-form/sections/buyer-information.tsx
+++ b/src/app/(app)/components/invoice-form/sections/buyer-information.tsx
@@ -68,13 +68,14 @@ export const BuyerInformation = memo(function BuyerInformation({
<fieldset className="mt-5 space-y-4" disabled={isBuyerSelected}>
{isBuyerSelected ? (
<div
- className="flex gap-2 rounded-md border border-blue-200 bg-blue-50 px-3 py-2 text-sm text-blue-800"
+ className="flex gap-2 rounded-md border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-800 shadow-md shadow-blue-200/10"
data-testid="buyer-locked-banner"
>
<Info className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
<p className="">
- To modify buyer details, click the &quot;Edit buyer&quot; button
- (pencil icon) next to the dropdown above.
+ To modify buyer details, click the{" "}
+ <span className="font-semibold">Edit buyer</span> button (pencil
+ icon) next to the dropdown above.
</p>
</div>
) : null}
@@ -283,12 +284,7 @@ export const BuyerInformation = memo(function BuyerInformation({
name="buyer.notes"
control={control}
render={({ field }) => (
- <Textarea
- {...field}
- id="buyerNotes"
- rows={3}
- placeholder="Additional information about the buyer"
- />
+ <Textarea {...field} id="buyerNotes" rows={3} />
)}
/>
{errors.buyer?.notes && (
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 0b227b2..145d2ed 100644
--- a/src/app/(app)/components/invoice-form/sections/seller-information.tsx
+++ b/src/app/(app)/components/invoice-form/sections/seller-information.tsx
@@ -70,13 +70,14 @@ export const SellerInformation = memo(function SellerInformation({
<fieldset className="mt-5 space-y-4" disabled={isSellerSelected}>
{isSellerSelected ? (
<div
- className="flex gap-2 rounded-md border border-blue-200 bg-blue-50 px-3 py-2 text-sm text-blue-800"
+ className="flex gap-2 rounded-md border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-800 shadow-md shadow-blue-200/10"
data-testid="seller-locked-banner"
>
<Info className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
<p className="">
- To modify seller details, click the &quot;Edit seller&quot;
- button (pencil icon) next to the dropdown above.
+ To modify seller details, click the{" "}
+ <span className="font-semibold">Edit seller</span> button
+ (pencil icon) next to the dropdown above.
</p>
</div>
) : null}
diff --git a/src/components/buyer-dialog.tsx b/src/components/buyer-dialog.tsx
index f2134dd..3682696 100644
--- a/src/components/buyer-dialog.tsx
+++ b/src/components/buyer-dialog.tsx
@@ -1,7 +1,6 @@
import { Button } from "@/components/ui/button";
import {
Dialog,
- DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
@@ -46,6 +45,21 @@ interface BuyerDialogProps {
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,
@@ -71,6 +85,8 @@ export function BuyerDialog({
},
});
+ const { isDirty } = form.formState;
+
// by default, we want to apply the new buyer to the current invoice
const [shouldApplyNewBuyerToInvoice, setShouldApplyNewBuyerToInvoice] =
useState(true);
@@ -116,6 +132,32 @@ export function BuyerDialog({
}
}, [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();
+ onClose(false);
+ }
+
function onSubmit(formValues: BuyerData) {
try {
// **RUNNING SOME VALIDATIONS FIRST**
@@ -179,10 +221,7 @@ export function BuyerDialog({
}
// Close dialog
- onClose(false);
-
- // Reset form
- form.reset();
+ closeDialog();
} catch (error) {
console.error("Failed to save buyer:", error);
@@ -200,8 +239,19 @@ export function BuyerDialog({
open={isOpen}
onOpenChange={(open) => {
if (!open) {
- onClose(false);
- form.reset();
+ // 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();
}
}}
>
@@ -498,11 +548,28 @@ export function BuyerDialog({
)}
</div>
<DialogFooter className="border-border border-t px-6 py-4">
- <DialogClose asChild>
- <Button type="button" variant="outline">
- Cancel
- </Button>
- </DialogClose>
+ <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 () => {
diff --git a/src/components/buyer-management.tsx b/src/components/buyer-management.tsx
index 121dd88..79f8f98 100644
--- a/src/components/buyer-management.tsx
+++ b/src/components/buyer-management.tsx
@@ -287,7 +287,9 @@ export function BuyerManagement({
<div
className={cn(
"flex w-full flex-col gap-2",
- hasBuyers ? "rounded-md border p-4" : "mt-3",
+ hasBuyers
+ ? "rounded-md border p-4 shadow shadow-slate-400/10"
+ : "mt-3",
)}
>
{hasBuyers ? (
diff --git a/src/components/seller-dialog.tsx b/src/components/seller-dialog.tsx
index cea8973..bd94acf 100644
--- a/src/components/seller-dialog.tsx
+++ b/src/components/seller-dialog.tsx
@@ -2,7 +2,6 @@ import { sellerSchema, type SellerData } from "@/app/schema";
import { Button } from "@/components/ui/button";
import {
Dialog,
- DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
@@ -48,6 +47,22 @@ interface SellerDialogProps {
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,
@@ -78,6 +93,8 @@ export function SellerDialog({
},
});
+ const { isDirty } = form.formState;
+
// by default, we want to apply the new seller to the current invoice
const [shouldApplyNewSellerToInvoice, setShouldApplyNewSellerToInvoice] =
useState(true);
@@ -118,6 +135,32 @@ export function SellerDialog({
}
}, [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();
+ onClose(false);
+ }
+
function onSubmit(formValues: SellerData) {
try {
// **RUNNING SOME VALIDATIONS FIRST**
@@ -186,10 +229,7 @@ export function SellerDialog({
}
// Close dialog
- onClose(false);
-
- // Reset form
- form.reset();
+ closeDialog();
} catch (error) {
console.error("Failed to save seller:", error);
@@ -208,8 +248,19 @@ export function SellerDialog({
open={isOpen}
onOpenChange={(open) => {
if (!open) {
- onClose(false);
- form.reset();
+ // 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();
}
}}
>
@@ -600,11 +651,27 @@ export function SellerDialog({
)}
</div>
<DialogFooter className="border-border border-t px-6 py-4">
- <DialogClose asChild>
- <Button type="button" variant="outline">
- Cancel
- </Button>
- </DialogClose>
+ <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"
diff --git a/src/components/seller-management.tsx b/src/components/seller-management.tsx
index 241700b..ab63408 100644
--- a/src/components/seller-management.tsx
+++ b/src/components/seller-management.tsx
@@ -303,7 +303,9 @@ export function SellerManagement({
<div
className={cn(
"flex w-full flex-col gap-2",
- hasSellers ? "rounded-md border p-4" : "mt-3",
+ hasSellers
+ ? "rounded-md border p-4 shadow shadow-slate-400/10"
+ : "mt-3",
)}
>
{hasSellers ? (