Skip to content

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

feat: seller & buyer import/export (#276)

Vlad Sazonaud76331354544
diff --git a/e2e/contacts-backup.test.ts b/e2e/contacts-backup.test.ts
new file mode 100644
index 0000000..ebecf29
--- /dev/null
+++ b/e2e/contacts-backup.test.ts
@@ -0,0 +1,217 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import { type Page } from "@playwright/test";
+
+import {
+ BUYERS_LOCAL_STORAGE_KEY,
+ SELLERS_LOCAL_STORAGE_KEY,
+ type BuyerData,
+ type SellerData,
+} from "@/app/schema";
+
+import { expect, test } from "./utils/extended-playwright-test";
+
+const SELLER = {
+ id: "1700000000000",
+ name: "Backup Test Seller",
+ address: "1 Export Street\nBackup City",
+ vatNo: "PL1234567890",
+ vatNoLabelText: "VAT no",
+ email: "[email protected]",
+ accountNumber: "PL61 1090 1014 0000 0712 1981 2874",
+ swiftBic: "WBKPPLPP",
+ vatNoFieldIsVisible: true,
+ emailFieldIsVisible: true,
+ accountNumberFieldIsVisible: true,
+ swiftBicFieldIsVisible: false,
+ notesFieldIsVisible: true,
+} as const satisfies SellerData;
+
+const BUYER = {
+ id: "1700000000001",
+ name: "Backup Test Buyer",
+ address: "2 Import Road\nRestore Town",
+ vatNoLabelText: "Tax ID",
+ vatNoFieldIsVisible: true,
+ emailFieldIsVisible: false,
+ notesFieldIsVisible: true,
+} as const satisfies BuyerData;
+
+async function chooseBackupFile(
+ page: Page,
+ section: "seller" | "buyer",
+ filePath: string,
+) {
+ await openBackupMenu(page, section);
+ await page.getByRole("menuitem", { name: "Import from file…" }).click();
+
+ const fileChooserPromise = page.waitForEvent("filechooser");
+ await page
+ .getByTestId("import-contacts-dialog")
+ .getByText("choose a file", { exact: true })
+ .click();
+ const fileChooser = await fileChooserPromise;
+ await fileChooser.setFiles(filePath);
+}
+
+async function openBackupMenu(page: Page, section: "seller" | "buyer") {
+ await page
+ .getByTestId(`${section}-information-section`)
+ .getByRole("button", { name: "Import or export sellers & buyers" })
+ .click();
+}
+
+test.describe("Sellers & buyers backup", () => {
+ test("exports saved sellers and buyers and imports them back", async ({
+ page,
+ downloadDir,
+ }) => {
+ await page.goto("/?template=default");
+
+ await page.evaluate(
+ ({ sellersKey, buyersKey, sellers, buyers }) => {
+ localStorage.setItem(sellersKey, JSON.stringify(sellers));
+ localStorage.setItem(buyersKey, JSON.stringify(buyers));
+ },
+ {
+ sellersKey: SELLERS_LOCAL_STORAGE_KEY,
+ buyersKey: BUYERS_LOCAL_STORAGE_KEY,
+ sellers: [SELLER],
+ buyers: [BUYER],
+ },
+ );
+ await page.reload();
+
+ // Export from the seller section: the file holds both lists
+ await openBackupMenu(page, "seller");
+
+ const downloadPromise = page.waitForEvent("download");
+ await page
+ .getByRole("menuitem", { name: "Export sellers & buyers" })
+ .click();
+ const download = await downloadPromise;
+
+ expect(download.suggestedFilename()).toMatch(
+ /^easyinvoicepdf-contacts-\d{4}-\d{2}-\d{2}\.json$/,
+ );
+
+ const backupPath = path.join(downloadDir, download.suggestedFilename());
+ await download.saveAs(backupPath);
+
+ const backup = JSON.parse(fs.readFileSync(backupPath, "utf8")) as {
+ sellers: Record<string, unknown>[];
+ buyers: Record<string, unknown>[];
+ };
+
+ // Only hidden visibility flags are written out
+ expect(backup.sellers).toStrictEqual([
+ {
+ id: SELLER.id,
+ name: SELLER.name,
+ address: SELLER.address,
+ vatNo: SELLER.vatNo,
+ vatNoLabelText: SELLER.vatNoLabelText,
+ email: SELLER.email,
+ accountNumber: SELLER.accountNumber,
+ swiftBic: SELLER.swiftBic,
+ swiftBicFieldIsVisible: false,
+ },
+ ]);
+ expect(backup.buyers).toStrictEqual([
+ {
+ id: BUYER.id,
+ name: BUYER.name,
+ address: BUYER.address,
+ vatNoLabelText: BUYER.vatNoLabelText,
+ emailFieldIsVisible: false,
+ },
+ ]);
+
+ // Start from an empty browser: no saved sellers or buyers, so no dropdowns
+ await page.evaluate(() => {
+ localStorage.clear();
+ });
+ await page.reload();
+
+ const sellerDropdown = page
+ .getByTestId("seller-information-section")
+ .getByRole("combobox", { name: "Select Seller" });
+ const buyerDropdown = page
+ .getByTestId("buyer-information-section")
+ .getByRole("combobox", { name: "Select Buyer" });
+
+ await expect(sellerDropdown).toBeHidden();
+ await expect(buyerDropdown).toBeHidden();
+
+ // Import from the buyer section: both sections pick up the file
+ await chooseBackupFile(page, "buyer", backupPath);
+
+ const importDialog = page.getByTestId("import-contacts-dialog");
+
+ await expect(
+ importDialog.getByRole("heading", { name: "Review import" }),
+ ).toBeVisible();
+ await expect(
+ importDialog.getByRole("list", { name: "Sellers" }),
+ ).toContainText(SELLER.name);
+ await expect(
+ importDialog.getByRole("list", { name: "Buyers" }),
+ ).toContainText(BUYER.name);
+
+ // Nothing is saved before the user confirms
+ await expect(sellerDropdown).toBeHidden();
+
+ await importDialog
+ .getByRole("button", { name: "Import 1 seller and 1 buyer" })
+ .click();
+
+ await expect(importDialog).toBeHidden();
+ await expect(
+ page.getByText("Imported 1 seller and 1 buyer", { exact: true }),
+ ).toBeVisible();
+
+ await expect(
+ sellerDropdown.getByRole("option", { name: SELLER.name }),
+ ).toBeAttached();
+ await expect(
+ buyerDropdown.getByRole("option", { name: BUYER.name }),
+ ).toBeAttached();
+
+ // Nothing is lost on the way: hidden flags stay hidden, visible ones come back
+ const stored = await page.evaluate(
+ ({ sellersKey, buyersKey }) => {
+ const sellers: unknown = JSON.parse(
+ localStorage.getItem(sellersKey) ?? "[]",
+ );
+ const buyers: unknown = JSON.parse(
+ localStorage.getItem(buyersKey) ?? "[]",
+ );
+
+ return { sellers, buyers };
+ },
+ {
+ sellersKey: SELLERS_LOCAL_STORAGE_KEY,
+ buyersKey: BUYERS_LOCAL_STORAGE_KEY,
+ },
+ );
+
+ expect(stored).toStrictEqual({
+ sellers: [SELLER],
+ buyers: [BUYER],
+ });
+
+ // Importing the same file again adds nothing
+ await chooseBackupFile(page, "seller", backupPath);
+
+ await expect(
+ importDialog.getByRole("heading", { name: "Nothing new to import" }),
+ ).toBeVisible();
+ await expect(
+ importDialog.getByRole("list", { name: "Sellers" }),
+ ).toContainText(`${SELLER.name}${SELLER.address}Already saved`);
+ await expect(
+ importDialog.getByRole("button", { name: /^Import/ }),
+ ).toBeHidden();
+ });
+});
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/contacts-backup-menu.test.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/contacts-backup-menu.test.tsx
new file mode 100644
index 0000000..7df3a1f
--- /dev/null
+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/contacts-backup-menu.test.tsx
@@ -0,0 +1,180 @@
+// @vitest-environment happy-dom
+
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { toast } from "sonner";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { ContactsBackupMenu } from "@/app/(main)/(app)/components/invoice-form/sections/components/contacts-backup-menu";
+import {
+ BUYERS_LOCAL_STORAGE_KEY,
+ SELLERS_LOCAL_STORAGE_KEY,
+} from "@/app/schema";
+import "@testing-library/jest-dom/vitest";
+
+vi.mock("sonner", () => {
+ return {
+ toast: {
+ success: vi.fn(),
+ error: vi.fn(),
+ dismiss: vi.fn(),
+ },
+ };
+});
+
+vi.mock("@sentry/nextjs", () => {
+ return { captureException: vi.fn() };
+});
+
+vi.mock("@/lib/umami-analytics-track-event", () => {
+ return { umamiTrackEvent: vi.fn() };
+});
+
+beforeEach(() => {
+ localStorage.clear();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+interface ImportBackupOptions {
+ sellers?: unknown[];
+ buyers?: unknown[];
+}
+
+async function importBackup({
+ sellers = [],
+ buyers = [],
+}: ImportBackupOptions) {
+ const file = new File(
+ [JSON.stringify({ app: "easyinvoicepdf", version: 1, sellers, buyers })],
+ "backup.json",
+ { type: "application/json" },
+ );
+
+ fireEvent.keyDown(
+ screen.getByRole("button", { name: "Import or export sellers & buyers" }),
+ { key: "Enter" },
+ );
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: "Import from file…" }),
+ );
+ fireEvent.change(await screen.findByTestId("contacts-backup-file-input"), {
+ target: { files: [file] },
+ });
+
+ fireEvent.click(await screen.findByRole("button", { name: /^Import \d/ }));
+
+ await vi.waitFor(() => {
+ expect(
+ vi.mocked(toast.success).mock.calls.length +
+ vi.mocked(toast.error).mock.calls.length,
+ ).toBeGreaterThan(0);
+ });
+}
+
+function readStoredList(key: string): unknown {
+ return JSON.parse(localStorage.getItem(key) ?? "null");
+}
+
+describe("ContactsBackupMenu import", () => {
+ it("saves nothing until the preview is confirmed", async () => {
+ render(<ContactsBackupMenu isMobile={false} />);
+
+ fireEvent.keyDown(
+ screen.getByRole("button", { name: "Import or export sellers & buyers" }),
+ { key: "Enter" },
+ );
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: "Import from file…" }),
+ );
+ fireEvent.change(await screen.findByTestId("contacts-backup-file-input"), {
+ target: {
+ files: [
+ new File(
+ [
+ JSON.stringify({
+ app: "easyinvoicepdf",
+ version: 1,
+ sellers: [{ name: "Acme", address: "1 Main St" }],
+ }),
+ ],
+ "backup.json",
+ ),
+ ],
+ },
+ });
+
+ expect(
+ await screen.findByRole("button", { name: "Import 1 seller" }),
+ ).toBeVisible();
+ expect(localStorage.getItem(SELLERS_LOCAL_STORAGE_KEY)).toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
+
+ expect(localStorage.getItem(SELLERS_LOCAL_STORAGE_KEY)).toBeNull();
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
+ it("shows why a file that is not a backup cannot be imported", async () => {
+ render(<ContactsBackupMenu isMobile={false} />);
+
+ fireEvent.keyDown(
+ screen.getByRole("button", { name: "Import or export sellers & buyers" }),
+ { key: "Enter" },
+ );
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: "Import from file…" }),
+ );
+ fireEvent.change(await screen.findByTestId("contacts-backup-file-input"), {
+ target: { files: [new File(["not json {"], "notes.json")] },
+ });
+
+ expect(
+ await screen.findByRole("heading", {
+ name: "This file can’t be imported",
+ }),
+ ).toBeVisible();
+ expect(
+ screen.getByText(
+ /This file is not an EasyInvoicePDF sellers & buyers backup/,
+ ),
+ ).toBeVisible();
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it("recovers when a saved list is not valid JSON", async () => {
+ localStorage.setItem(SELLERS_LOCAL_STORAGE_KEY, "[{ truncated");
+
+ render(<ContactsBackupMenu isMobile={false} />);
+
+ await importBackup({
+ sellers: [{ id: "1", name: "Acme", address: "1 Main St" }],
+ });
+
+ expect(toast.error).not.toHaveBeenCalled();
+ expect(readStoredList(SELLERS_LOCAL_STORAGE_KEY)).toMatchObject([
+ { id: "1", name: "Acme" },
+ ]);
+ });
+
+ it("gives entries without an id distinct ids", async () => {
+ render(<ContactsBackupMenu isMobile={false} />);
+
+ await importBackup({
+ buyers: [
+ { name: "Globex", address: "2 Side Rd" },
+ { name: "Initech", address: "3 Other Rd" },
+ ],
+ });
+
+ const buyers = readStoredList(BUYERS_LOCAL_STORAGE_KEY) as {
+ id: string;
+ }[];
+
+ expect(buyers).toHaveLength(2);
+ expect(buyers[0]?.id).toBeTruthy();
+ expect(buyers[0]?.id).not.toBe(buyers[1]?.id);
+ });
+});
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/import-contacts-dialog.test.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/import-contacts-dialog.test.tsx
new file mode 100644
index 0000000..03dbfe7
--- /dev/null
+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/__tests__/import-contacts-dialog.test.tsx
@@ -0,0 +1,382 @@
+// @vitest-environment happy-dom
+
+import {
+ cleanup,
+ createEvent,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import {
+ ImportContactsDialog,
+ type ImportContactsDialogState,
+} from "@/app/(main)/(app)/components/invoice-form/sections/components/import-contacts-dialog";
+import type { MergeImportedContactsResult } from "@/app/(main)/(app)/utils/contacts-backup";
+import {
+ buyerSchema,
+ sellerSchema,
+ type BuyerData,
+ type SellerData,
+} from "@/app/schema";
+import "@testing-library/jest-dom/vitest";
+
+afterEach(() => {
+ cleanup();
+});
+
+const ACME = sellerSchema.parse({ id: "1", name: "Acme", address: "1 Main" });
+const GLOBEX = buyerSchema.parse({
+ id: "2",
+ name: "Globex",
+ address: "2 Side",
+});
+
+function emptyResult<T extends SellerData | BuyerData>(
+ overrides: Partial<MergeImportedContactsResult<T>> = {},
+): MergeImportedContactsResult<T> {
+ return {
+ contacts: [],
+ added: [],
+ duplicates: [],
+ invalidEntries: [],
+ nameConflicts: [],
+ ...overrides,
+ };
+}
+
+function renderDialog(state: ImportContactsDialogState) {
+ render(
+ <ImportContactsDialog
+ isOpen
+ onOpenChange={vi.fn()}
+ state={state}
+ onFileSelected={vi.fn()}
+ onConfirm={vi.fn()}
+ />,
+ );
+
+ return screen.getByTestId("import-contacts-dialog");
+}
+
+describe("ImportContactsDialog preview", () => {
+ it("lists what will be added, skipped and cannot be imported", () => {
+ const dialog = renderDialog({
+ step: "preview",
+ fileName: "backup.json",
+ sellers: emptyResult({
+ added: [ACME],
+ nameConflicts: [
+ {
+ label: "Initech",
+ entry: { name: "Initech", address: "Elsewhere" },
+ issues: [
+ {
+ field: "name",
+ message: "A seller with this name is already saved",
+ },
+ ],
+ },
+ ],
+ }),
+ buyers: emptyResult({ duplicates: [GLOBEX] }),
+ });
+
+ expect(
+ within(dialog).getByRole("heading", { name: "Review import" }),
+ ).toBeVisible();
+
+ const sellers = within(dialog).getByRole("list", { name: "Sellers" });
+
+ expect(sellers).toHaveTextContent("Acme1 MainNew");
+ expect(sellers).toHaveTextContent("InitechElsewhereName taken");
+ expect(
+ within(dialog).getByRole("list", { name: "Buyers" }),
+ ).toHaveTextContent("Globex2 SideAlready saved");
+
+ expect(
+ within(dialog).getByRole("button", { name: "Import 1 seller" }),
+ ).toBeVisible();
+ });
+
+ it("shows the entry as written in the file with the failing field highlighted", () => {
+ const dialog = renderDialog({
+ step: "preview",
+ fileName: "backup.json",
+ sellers: emptyResult({
+ invalidEntries: [
+ {
+ label: "Acme",
+ entry: {
+ name: "Acme",
+ address: "1 Main St",
+ email: "not-an-email",
+ },
+ issues: [{ field: "email", message: "Invalid email address" }],
+ },
+ ],
+ }),
+ buyers: emptyResult(),
+ });
+
+ expect(
+ within(dialog).getByRole("heading", { name: "Nothing can be imported" }),
+ ).toBeVisible();
+ expect(within(dialog).getByText("1 problem")).toBeVisible();
+ expect(within(dialog).getByText(/"1 Main St"/)).toBeVisible();
+
+ const invalidLines = dialog.querySelectorAll("[data-invalid-field]");
+
+ expect(invalidLines).toHaveLength(1);
+ expect(invalidLines[0]).toHaveAttribute("data-invalid-field", "email");
+ expect(invalidLines[0]).toHaveTextContent(
+ '"email": "not-an-email"↳ Invalid email address',
+ );
+
+ // Nothing to add, so there is nothing to confirm
+ expect(
+ within(dialog).queryByRole("button", { name: /^Import/ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("adds a line for a required field the entry does not have", () => {
+ const dialog = renderDialog({
+ step: "preview",
+ fileName: "backup.json",
+ sellers: emptyResult(),
+ buyers: emptyResult({
+ invalidEntries: [
+ {
+ label: "Entry #2",
+ entry: { address: "No name" },
+ issues: [{ field: "name", message: "Required" }],
+ },
+ ],
+ }),
+ });
+
+ expect(
+ dialog.querySelector('[data-invalid-field="name"]'),
+ ).toHaveTextContent('"name": missing↳ Required');
+ });
+
+ it("shows a problem with the entry as a whole above its value", () => {
+ const dialog = renderDialog({
+ step: "preview",
+ fileName: "backup.json",
+ sellers: emptyResult({
+ invalidEntries: [
+ {
+ label: "Entry #3",
+ entry: { name: "x".repeat(500), address: 1, vatNo: 2 },
+ issues: [
+ { field: "address", message: "Expected string" },
+ { field: "vatNo", message: "Expected string" },
+ ],
+ },
+ ],
+ }),
+ buyers: emptyResult({
+ invalidEntries: [
+ {
+ label: "Entry #1",
+ entry: "oops",
+ issues: [
+ { message: "Invalid input: expected object, received string" },
+ ],
+ },
+ ],
+ }),
+ });
+
+ expect(
+ within(dialog).getByText(
+ "Invalid input: expected object, received string",
+ ),
+ ).toBeVisible();
+ expect(within(dialog).getByText('"oops"')).toBeVisible();
+ expect(within(dialog).getByText("2 problems")).toBeVisible();
+
+ // Long values are cut short
+ expect(dialog).toHaveTextContent(`"${"x".repeat(119)}…`);
+ });
+});
+
+describe("ImportContactsDialog drop", () => {
+ it("takes a file dropped anywhere, not only on the drop zone", () => {
+ const onFileSelected = vi.fn();
+ renderDropDialog({ state: { step: "choose" }, onFileSelected });
+
+ const file = new File(["{}"], "backup.json");
+ // Outside the dashed box: on the rules list, and on the page behind the dialog
+ const targets = [
+ screen.getByText("The invoice you’re working on isn’t touched."),
+ document.body,
+ ];
+
+ for (const target of targets) {
+ const drop = createEvent.drop(target, {
+ dataTransfer: fileDataTransfer(file),
+ });
+ fireEvent(target, drop);
+
+ // Cancelled, so the browser does not open the file in the tab
+ expect(drop.defaultPrevented).toBe(true);
+ }
+
+ expect(onFileSelected).toHaveBeenCalledTimes(2);
+ expect(onFileSelected).toHaveBeenCalledWith(file);
+ });
+
+ it("leaves drops alone while closed", () => {
+ renderDropDialog({ isOpen: false, state: { step: "choose" } });
+
+ const drop = createEvent.drop(document.body, {
+ dataTransfer: fileDataTransfer(new File(["{}"], "backup.json")),
+ });
+ fireEvent(document.body, drop);
+
+ expect(drop.defaultPrevented).toBe(false);
+ });
+
+ it("cancels but ignores a file dropped after the choose step", () => {
+ const onFileSelected = vi.fn();
+ const states: ImportContactsDialogState[] = [
+ {
+ step: "preview",
+ fileName: "backup.json",
+ sellers: emptyResult({ added: [ACME] }),
+ buyers: emptyResult(),
+ },
+ { step: "error", fileName: "broken.json", error: "Not JSON" },
+ ];
+
+ for (const state of states) {
+ renderDropDialog({ state, onFileSelected });
+
+ const drop = createEvent.drop(document.body, {
+ dataTransfer: fileDataTransfer(new File(["{}"], "other.json")),
+ });
+ fireEvent(document.body, drop);
+
+ // Still cancelled, so the browser does not navigate away to the file
+ expect(drop.defaultPrevented).toBe(true);
+
+ cleanup();
+ }
+
+ // A stray drop does not swap the file under review
+ expect(onFileSelected).not.toHaveBeenCalled();
+ });
+
+ it("leaves drags that carry no file alone", () => {
+ const onFileSelected = vi.fn();
+ renderDropDialog({ state: { step: "choose" }, onFileSelected });
+
+ const textDrag = { types: ["text/plain"], files: [] };
+
+ fireEvent.dragEnter(document.body, { dataTransfer: textDrag });
+ expect(getDropZone()).not.toHaveClass("border-slate-600");
+
+ const drop = createEvent.drop(document.body, { dataTransfer: textDrag });
+ fireEvent(document.body, drop);
+
+ expect(drop.defaultPrevented).toBe(false);
+ expect(onFileSelected).not.toHaveBeenCalled();
+ });
+
+ it("takes a Chromium file drag that lists only text/plain in its types", () => {
+ const onFileSelected = vi.fn();
+ renderDropDialog({ state: { step: "choose" }, onFileSelected });
+
+ const file = new File(["{}"], "backup.json");
+ // The file shows up only as an item of kind `file` (react-dropzone#1409)
+ const dataTransfer = {
+ types: ["text/plain"],
+ items: [{ kind: "file" }],
+ files: [file],
+ };
+
+ const drop = createEvent.drop(document.body, { dataTransfer });
+ fireEvent(document.body, drop);
+
+ expect(drop.defaultPrevented).toBe(true);
+ expect(onFileSelected).toHaveBeenCalledWith(file);
+ });
+
+ it("keeps the drop zone highlighted while the drag moves between elements", () => {
+ renderDropDialog({ state: { step: "choose" } });
+
+ const dataTransfer = fileDataTransfer(new File(["{}"], "backup.json"));
+ const rule = screen.getByText(
+ "The invoice you’re working on isn’t touched.",
+ );
+
+ fireEvent.dragEnter(document.body, { dataTransfer });
+ expect(getDropZone()).toHaveClass("border-slate-600");
+
+ // Into a child: WebKit fires the `dragleave` for the element being left with a null
+ // `relatedTarget`, which must not read as leaving the window
+ fireEvent.dragEnter(rule, { dataTransfer });
+ fireEvent.dragLeave(document.body, { dataTransfer });
+ expect(getDropZone()).toHaveClass("border-slate-600");
+
+ // Out of the window
+ fireEvent.dragLeave(rule, { dataTransfer });
+ expect(getDropZone()).not.toHaveClass("border-slate-600");
+ });
+
+ it("clears the highlight when Firefox enters the same element twice", () => {
+ renderDropDialog({ state: { step: "choose" } });
+
+ const dataTransfer = fileDataTransfer(new File(["{}"], "backup.json"));
+
+ fireEvent.dragEnter(document.body, { dataTransfer });
+ fireEvent.dragEnter(document.body, { dataTransfer });
+ fireEvent.dragLeave(document.body, { dataTransfer });
+
+ expect(getDropZone()).not.toHaveClass("border-slate-600");
+ });
+});
+
+interface RenderDropDialogOptions {
+ /** Whether the dialog is open. */
+ isOpen?: boolean;
+ /** The dialog step to render. */
+ state: ImportContactsDialogState;
+ /** Receives the dropped file. */
+ onFileSelected?: (file: File) => void;
+}
+
+function renderDropDialog({
+ isOpen = true,
+ state,
+ onFileSelected = vi.fn(),
+}: RenderDropDialogOptions) {
+ render(
+ <ImportContactsDialog
+ isOpen={isOpen}
+ onOpenChange={vi.fn()}
+ state={state}
+ onFileSelected={onFileSelected}
+ onConfirm={vi.fn()}
+ />,
+ );
+}
+
+/** The `dataTransfer` of a drag carrying `file`, as the browser reports it. */
+function fileDataTransfer(file: File) {
+ return { types: ["Files"], files: [file] };
+}
+
+function getDropZone() {
+ const label = screen.getByText("Drop a .json file here").closest("label");
+
+ if (!label) {
+ throw new Error("Drop zone not found");
+ }
+
+ return label;
+}
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/buyer/buyer-management.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/buyer/buyer-management.tsx
index dba8d08..ea06100 100644
--- a/src/app/(main)/(app)/components/invoice-form/sections/components/buyer/buyer-management.tsx
+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/buyer/buyer-management.tsx
@@ -1,20 +1,12 @@
-import * as Sentry from "@sentry/nextjs";
import { Plus, Trash2, Pencil, AlertCircleIcon } from "lucide-react";
-import { useId, useState, useEffect } from "react";
+import { useId, useState } from "react";
import type { UseFormSetValue } from "react-hook-form";
import { toast } from "sonner";
-import {
- getAppStorageItem,
- setAppStorageItem,
-} from "@/app/(main)/(app)/utils/app-local-storage";
-import { DEFAULT_BUYER_DATA } from "@/app/constants";
-import {
- BUYERS_LOCAL_STORAGE_KEY,
- buyerSchema,
- type InvoiceData,
- type BuyerData,
-} from "@/app/schema";
+import { ContactsBackupMenu } from "@/app/(main)/(app)/components/invoice-form/sections/components/contacts-backup-menu";
+import { usePartyActions } from "@/app/(main)/(app)/components/invoice-form/sections/hooks/use-party-actions";
+import { useSavedParties } from "@/app/(main)/(app)/components/invoice-form/sections/hooks/use-saved-parties";
+import { type InvoiceData, type BuyerData } from "@/app/schema";
import {
AlertDialog,
AlertDialogAction,
@@ -29,7 +21,6 @@ import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { SelectNative } from "@/components/ui/select-native";
import { CustomTooltip } from "@/components/ui/tooltip";
-import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
import { useIsLocalStorageAvailable } from "@/lib/use-is-local-storage-available";
import { cn } from "@/lib/utils";
@@ -75,12 +66,7 @@ export function BuyerManagement({
const [isBuyerDialogOpen, setIsBuyerDialogOpen] = useState(false);
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
- // State to store the list of saved buyers for the dropdown selection.
- const [buyersSelectOptions, setBuyersSelectOptions] = useState<BuyerData[]>(
- [],
- );
-
- // State to track the buyer currently being edited (null if not editing).
+ // The saved buyer being edited in the dialog; `null` while adding a new one
const [editingBuyer, setEditingBuyer] = useState<BuyerData | null>(null);
const buyerSelectId = useId();
@@ -89,273 +75,30 @@ export function BuyerManagement({
const isEditMode = Boolean(editingBuyer);
- // Load buyers from localStorage on component mount
- useEffect(() => {
- try {
- const savedBuyers = getAppStorageItem(BUYERS_LOCAL_STORAGE_KEY);
- const parsedBuyers: unknown = savedBuyers ? JSON.parse(savedBuyers) : [];
-
- const rawBuyers = Array.isArray(parsedBuyers) ? parsedBuyers : [];
-
- 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`,
- ),
- );
-
- setAppStorageItem({
- key: BUYERS_LOCAL_STORAGE_KEY,
- value: JSON.stringify(validBuyers),
- });
- }
-
- const selectedBuyer = validBuyers.find((buyer: BuyerData) => {
- return buyer?.id === invoiceData?.buyer?.id;
- });
-
- // oxlint-disable-next-line react/set-state-in-effect react-you-might-not-need-an-effect/no-adjust-state-on-prop-change -- localStorage is an external system: the saved buyers cannot be derived during render, they have to be read after mount
- setBuyersSelectOptions(validBuyers);
- setSelectedBuyerId(selectedBuyer?.id ?? "");
- } catch (error) {
- console.error("Failed to load buyers:", error);
-
- Sentry.captureException(error);
- }
- }, [invoiceData?.buyer?.id, setSelectedBuyerId]);
-
- // Update buyers when a new one is added
- const handleBuyerAdd = (
- newBuyer: BuyerData,
- { shouldApplyNewBuyerToInvoice }: { shouldApplyNewBuyerToInvoice: boolean },
- ) => {
- try {
- const newBuyerWithId = {
- ...newBuyer,
- // Generate a unique ID for the new buyer (IMPORTANT!) =)
- id: Date.now().toString(),
- } satisfies BuyerData;
-
- const newBuyers = [...buyersSelectOptions, newBuyerWithId];
-
- // Save to localStorage
- const persisted = setAppStorageItem({
- key: BUYERS_LOCAL_STORAGE_KEY,
- value: JSON.stringify(newBuyers),
- });
-
- // Nothing to show the user later if the list could not be saved, so stop here
- // rather than reporting a success the next page load would contradict.
- if (!persisted) {
- showBuyerStorageErrorToast({
- message: "Failed to add buyer",
- id: "add_buyer_error_toast",
- isMobile,
- });
-
- return;
- }
-
- // Update the buyers state
- setBuyersSelectOptions(newBuyers);
-
- // Apply the new buyer to the invoice if the user wants to, otherwise just add it to the list and use it later if needed
- if (shouldApplyNewBuyerToInvoice) {
- setValue("buyer", newBuyerWithId);
- setSelectedBuyerId(newBuyerWithId?.id);
- }
-
- toast.success(
- shouldApplyNewBuyerToInvoice
- ? "Buyer added and applied to invoice"
- : "Buyer added successfully",
- {
- id: "add_buyer_success_toast",
- richColors: true,
- position: isMobile ? "top-center" : "bottom-right",
- },
- );
-
- // analytics track event
- umamiTrackEvent("add_buyer_success");
- } catch (error) {
- console.error("Failed to add buyer:", error);
-
- toast.error("Failed to add buyer", {
- id: "add_buyer_error_toast",
- description: "Please try again",
- closeButton: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
-
- Sentry.captureException(error);
- }
- };
-
- // Update buyers when edited
- const handleBuyerEdit = (editedBuyer: BuyerData) => {
- try {
- const updatedBuyers = buyersSelectOptions.map((buyer) => {
- return buyer.id === editedBuyer.id ? editedBuyer : buyer;
- });
-
- const persisted = setAppStorageItem({
- key: BUYERS_LOCAL_STORAGE_KEY,
- value: JSON.stringify(updatedBuyers),
- });
-
- if (!persisted) {
- showBuyerStorageErrorToast({
- message: "Failed to edit buyer",
- id: "edit_buyer_error_toast",
- isMobile,
- });
-
- return;
- }
-
- setBuyersSelectOptions(updatedBuyers);
- setValue("buyer", editedBuyer);
-
- // end edit mode
- setEditingBuyer(null);
-
- toast.success("Buyer updated successfully", {
- id: "edit_buyer_success_toast",
- richColors: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
-
- // analytics track event
- umamiTrackEvent("edit_buyer_success");
- } catch (error) {
- console.error("Failed to edit buyer:", error);
-
- toast.error("Failed to edit buyer", {
- id: "edit_buyer_error_toast",
- description: "Please try again",
- closeButton: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
-
- Sentry.captureException(error);
- }
- };
-
- const handleBuyerChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
- const id = event.target.value;
-
- if (id) {
- setSelectedBuyerId(id);
- const selectedBuyer = buyersSelectOptions.find((buyer) => {
- return buyer.id === id;
- });
-
- if (selectedBuyer) {
- setValue("buyer", selectedBuyer);
- toast.success(`Buyer "${selectedBuyer.name}" applied to invoice`, {
- id: "change_buyer_success_toast",
- richColors: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
- }
- } else {
- // Clear the buyer from the form if the user selects the empty option
- setSelectedBuyerId("");
- setValue("buyer", DEFAULT_BUYER_DATA);
-
- toast.success("Buyer restored to default", {
- id: "reset_buyer_success_toast",
- richColors: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
- }
-
- // analytics track event
- umamiTrackEvent("change_buyer");
- };
-
- const handleDeleteBuyer = () => {
- try {
- const updatedBuyers = buyersSelectOptions.filter((buyer) => {
- return buyer.id !== selectedBuyerId;
- });
-
- const persisted = setAppStorageItem({
- key: BUYERS_LOCAL_STORAGE_KEY,
- value: JSON.stringify(updatedBuyers),
- });
-
- if (!persisted) {
- showBuyerStorageErrorToast({
- message: "Failed to delete buyer",
- id: "delete_buyer_error_toast",
- isMobile,
- });
-
- return;
- }
-
- setBuyersSelectOptions(updatedBuyers);
- // Clear the selected buyer index
- setSelectedBuyerId("");
- // Clear the buyer from the form if it was selected
- setValue("buyer", DEFAULT_BUYER_DATA);
-
- // Close the delete dialog
- setIsDeleteDialogOpen(false);
-
- toast.success("Buyer deleted successfully", {
- id: "delete_buyer_success_toast",
- richColors: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
-
- // analytics track event
- umamiTrackEvent("delete_buyer_success");
- } catch (error) {
- console.error("Failed to delete buyer:", error);
-
- toast.error("Failed to delete buyer", {
- id: "delete_buyer_error_toast",
- description: "Please try again",
- closeButton: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
-
- Sentry.captureException(error);
- }
- };
+ const { savedParties: savedBuyers, saveParties } = useSavedParties({
+ party: "buyer",
+ invoicePartyId: invoiceData?.buyer?.id,
+ setSelectedId: setSelectedBuyerId,
+ });
- const activeBuyer = buyersSelectOptions.find((buyer) => {
+ const { addParty, editParty, deleteSelectedParty, selectParty } =
+ usePartyActions({
+ party: "buyer",
+ savedParties: savedBuyers,
+ saveParties,
+ selectedId: selectedBuyerId,
+ setSelectedId: setSelectedBuyerId,
+ applyToInvoice: (buyer) => {
+ setValue("buyer", buyer);
+ },
+ isMobile,
+ });
+
+ const activeBuyer = savedBuyers.find((buyer) => {
return buyer.id === selectedBuyerId;
});
- const hasBuyers = buyersSelectOptions.length > 0;
+ const hasBuyers = savedBuyers.length > 0;
return (
<>
@@ -381,12 +124,14 @@ export function BuyerManagement({
"block h-8 w-full text-[12px]",
!selectedBuyerId && "italic text-gray-700",
)}
- onChange={handleBuyerChange}
+ onChange={(event) => {
+ selectParty(event.target.value);
+ }}
value={selectedBuyerId}
title={activeBuyer?.name}
>
<option value="">No buyer selected (default)</option>
- {buyersSelectOptions.map((buyer) => {
+ {savedBuyers.map((buyer) => {
return (
<option key={buyer.id} value={buyer.id}>
{buyer.name}
@@ -444,70 +189,76 @@ export function BuyerManagement({
</div>
) : null}
- <CustomTooltip
- side="bottom"
- className={cn(!isLocalStorageAvailable && "bg-red-50")}
- trigger={
- <Button
- variant="default"
- size="sm"
- onClick={() => {
- if (isLocalStorageAvailable) {
- // dismiss any existing toast for better UX
- toast.dismiss();
-
- // open buyer dialog
- setIsBuyerDialogOpen(true);
- } else {
- toast.error("Unable to add buyer", {
- id: "unable-to-add-buyer-error-toast",
- description: (
- <>
- <p className="text-pretty text-xs leading-relaxed text-red-700">
- Local storage is not available in your browser. Please
- enable it or try another browser.
- </p>
- </>
- ),
- position: isMobile ? "top-center" : "bottom-right",
- });
- }
- }}
- aria-disabled={!isLocalStorageAvailable} // better UX than 'disabled'
- >
- New Buyer
- <Plus className="ml-1 size-3" />
- </Button>
- }
- content={
- isLocalStorageAvailable ? (
- <div className="flex items-center gap-3 p-2">
- <div className="space-y-1">
- <p className="text-sm font-semibold text-slate-900">
- Save Buyers for Quick Access
- </p>
- <p className="text-pretty text-xs leading-relaxed text-slate-700">
- Store multiple buyers to easily reuse their information in
- future invoices. All data is saved locally in your browser.
- </p>
+ <div className="flex gap-2">
+ <CustomTooltip
+ side="bottom"
+ className={cn(!isLocalStorageAvailable && "bg-red-50")}
+ trigger={
+ <Button
+ variant="default"
+ size="sm"
+ onClick={() => {
+ if (isLocalStorageAvailable) {
+ // dismiss any existing toast for better UX
+ toast.dismiss();
+
+ // open buyer dialog
+ setIsBuyerDialogOpen(true);
+ } else {
+ toast.error("Unable to add buyer", {
+ id: "unable-to-add-buyer-error-toast",
+ description: (
+ <>
+ <p className="text-pretty text-xs leading-relaxed text-red-700">
+ Local storage is not available in your browser.
+ Please enable it or try another browser.
+ </p>
+ </>
+ ),
+ position: isMobile ? "top-center" : "bottom-right",
+ });
+ }
+ }}
+ aria-disabled={!isLocalStorageAvailable} // better UX than 'disabled'
+ className="flex-1"
+ >
+ New Buyer
+ <Plus className="ml-1 size-3" />
+ </Button>
+ }
+ content={
+ isLocalStorageAvailable ? (
+ <div className="flex items-center gap-3 p-2">
+ <div className="space-y-1">
+ <p className="text-sm font-semibold text-slate-900">
+ Save Buyers for Quick Access
+ </p>
+ <p className="text-pretty text-xs leading-relaxed text-slate-700">
+ Store multiple buyers to easily reuse their information in
+ future invoices. All data is saved locally in your
+ browser.
+ </p>
+ </div>
</div>
- </div>
- ) : (
- <div className="flex items-center gap-3 bg-red-50 p-3">
- <AlertCircleIcon className="h-5 w-5 flex-shrink-0 fill-red-600 text-white" />
- <div className="space-y-1">
- <p className="text-sm font-semibold text-red-800">
- Storage Not Available
- </p>
- <p className="text-pretty text-xs leading-relaxed text-red-700">
- Local storage is not available in your browser. Please
- enable it or try another browser to save buyer information.
- </p>
+ ) : (
+ <div className="flex items-center gap-3 bg-red-50 p-3">
+ <AlertCircleIcon className="h-5 w-5 flex-shrink-0 fill-red-600 text-white" />
+ <div className="space-y-1">
+ <p className="text-sm font-semibold text-red-800">
+ Storage Not Available
+ </p>
+ <p className="text-pretty text-xs leading-relaxed text-red-700">
+ Local storage is not available in your browser. Please
+ enable it or try another browser to save buyer
+ information.
+ </p>
+ </div>
</div>
- </div>
- )
- }
- />
+ )
+ }
+ />
+ <ContactsBackupMenu isMobile={isMobile} />
+ </div>
</div>
<BuyerDialog
@@ -518,8 +269,18 @@ export function BuyerManagement({
setIsBuyerDialogOpen(false);
setEditingBuyer(null);
}}
- handleBuyerAdd={handleBuyerAdd}
- handleBuyerEdit={handleBuyerEdit}
+ handleBuyerAdd={(newBuyer, { shouldApplyNewBuyerToInvoice }) => {
+ addParty({
+ partyData: newBuyer,
+ shouldApplyToInvoice: shouldApplyNewBuyerToInvoice,
+ });
+ }}
+ handleBuyerEdit={(editedBuyer) => {
+ if (editParty(editedBuyer)) {
+ // end edit mode
+ setEditingBuyer(null);
+ }
+ }}
initialData={editingBuyer}
isEditMode={isEditMode}
formValues={formValues}
@@ -542,7 +303,11 @@ export function BuyerManagement({
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
- onClick={handleDeleteBuyer}
+ onClick={() => {
+ if (deleteSelectedParty()) {
+ setIsDeleteDialogOpen(false);
+ }
+ }}
className="bg-red-500 text-red-50 hover:bg-red-500/90"
>
Delete
@@ -553,31 +318,3 @@ export function BuyerManagement({
</>
);
}
-
-interface ShowBuyerStorageErrorToastOptions {
- /** What the user was trying to do, e.g. "Failed to add buyer". */
- message: string;
- /** Stable toast id, so repeated failures replace each other instead of stacking. */
- id: string;
- /** Mobile shows toasts at the top, desktop at the bottom right. */
- isMobile: boolean;
-}
-
-/**
- * Tells the user their buyer list could not be saved.
- *
- * A rejected write is not an application error — it is a full or disabled store — so it
- * is surfaced to the user and deliberately not reported to Sentry.
- */
-function showBuyerStorageErrorToast({
- message,
- id,
- isMobile,
-}: ShowBuyerStorageErrorToastOptions) {
- toast.error(message, {
- id,
- description: "Please try again",
- closeButton: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
-}
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/contacts-backup-menu.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/contacts-backup-menu.tsx
new file mode 100644
index 0000000..4e20d82
--- /dev/null
+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/contacts-backup-menu.tsx
@@ -0,0 +1,387 @@
+import * as Sentry from "@sentry/nextjs";
+import { Download, Ellipsis, Upload } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import type { z } from "zod";
+
+import {
+ ImportContactsDialog,
+ type ImportContactsDialogState,
+} from "@/app/(main)/(app)/components/invoice-form/sections/components/import-contacts-dialog";
+import {
+ getAppStorageItem,
+ setAppStorageItem,
+} from "@/app/(main)/(app)/utils/app-local-storage";
+import {
+ MAX_CONTACTS_BACKUP_FILE_BYTES,
+ buildContactsBackupFileName,
+ describeContactCounts,
+ formatCount,
+ mergeImportedContacts,
+ parseContactsBackup,
+ serializeContactsBackup,
+} from "@/app/(main)/(app)/utils/contacts-backup";
+import {
+ BUYERS_LOCAL_STORAGE_KEY,
+ SELLERS_LOCAL_STORAGE_KEY,
+ buyerSchema,
+ sellerSchema,
+ type LocalStorageKey,
+} from "@/app/schema";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
+import { useIsLocalStorageAvailable } from "@/lib/use-is-local-storage-available";
+
+/**
+ * Dispatched on `window` after an import has written new sellers or buyers, so both
+ * management sections re-read their lists, not just the one whose menu was used.
+ */
+export const SAVED_CONTACTS_IMPORTED_EVENT = "easy-invoice:contacts-imported";
+
+interface ContactsBackupMenuProps {
+ /** Mobile shows toasts at the top, desktop at the bottom right. */
+ isMobile: boolean;
+}
+
+/**
+ * The ⋯ menu next to "New Seller" / "New Buyer": exports every saved seller and buyer to
+ * one JSON file, and imports such a file back.
+ *
+ * Both sections render it and it does the same thing in both, since the file always
+ * holds both lists. An import only adds to the saved lists; it never changes which
+ * seller or buyer the current invoice uses.
+ */
+export function ContactsBackupMenu({ isMobile }: ContactsBackupMenuProps) {
+ const [hasSavedContacts, setHasSavedContacts] = useState(false);
+ const [isImportDialogOpen, setIsImportDialogOpen] = useState(false);
+ const [importState, setImportState] = useState<ImportContactsDialogState>({
+ step: "choose",
+ });
+
+ const isLocalStorageAvailable = useIsLocalStorageAvailable();
+ const toastPosition = isMobile ? "top-center" : "bottom-right";
+
+ const handleExport = () => {
+ try {
+ const sellers = readSavedContacts({
+ key: SELLERS_LOCAL_STORAGE_KEY,
+ schema: sellerSchema,
+ });
+ const buyers = readSavedContacts({
+ key: BUYERS_LOCAL_STORAGE_KEY,
+ schema: buyerSchema,
+ });
+
+ const exportedAt = new Date();
+ const blob = new Blob(
+ [serializeContactsBackup({ sellers, buyers, exportedAt })],
+ { type: "application/json" },
+ );
+ const url = URL.createObjectURL(blob);
+
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = buildContactsBackupFileName(exportedAt);
+ link.click();
+
+ // Safari starts the download asynchronously, so revoking right away can cancel it.
+ setTimeout(() => {
+ URL.revokeObjectURL(url);
+ }, 1000);
+
+ toast.success("Sellers & buyers exported", {
+ id: "export_contacts_success_toast",
+ description: `${formatCount({ count: sellers.length, noun: "seller" })} and ${formatCount({ count: buyers.length, noun: "buyer" })} saved to ${link.download}`,
+ richColors: true,
+ position: toastPosition,
+ });
+
+ umamiTrackEvent("export_contacts_success");
+ } catch (error) {
+ console.error("Failed to export sellers & buyers:", error);
+
+ toast.error("Failed to export sellers & buyers", {
+ id: "export_contacts_error_toast",
+ description: "Please try again",
+ closeButton: true,
+ position: toastPosition,
+ });
+
+ Sentry.captureException(error);
+ }
+ };
+
+ /**
+ * Reads the chosen file and works out what importing it would add and skip, without
+ * saving anything: the dialog shows that for the user to confirm.
+ */
+ const handleFileSelected = async (file: File) => {
+ const showFileError = (error: string) => {
+ setImportState({ step: "error", fileName: file.name, error });
+ };
+
+ if (file.size > MAX_CONTACTS_BACKUP_FILE_BYTES) {
+ showFileError("This file is too large to be a backup.");
+
+ return;
+ }
+
+ try {
+ // Not `file.text()`: it is missing before Safari 14, which `.browserslistrc` still
+ // targets, and Next does not polyfill it.
+ const parsed = parseContactsBackup(await new Response(file).text());
+
+ if (!parsed.success) {
+ showFileError(parsed.error);
+
+ return;
+ }
+
+ setImportState({
+ step: "preview",
+ fileName: file.name,
+ sellers: mergeImportedContacts({
+ existing: readSavedContacts({
+ key: SELLERS_LOCAL_STORAGE_KEY,
+ schema: sellerSchema,
+ }),
+ imported: parsed.sellers,
+ schema: sellerSchema,
+ createId: createContactId,
+ contactNoun: "seller",
+ }),
+ buyers: mergeImportedContacts({
+ existing: readSavedContacts({
+ key: BUYERS_LOCAL_STORAGE_KEY,
+ schema: buyerSchema,
+ }),
+ imported: parsed.buyers,
+ schema: buyerSchema,
+ createId: createContactId,
+ contactNoun: "buyer",
+ }),
+ });
+ } catch (error) {
+ console.error("Failed to read sellers & buyers backup:", error);
+
+ showFileError("Something went wrong while reading it. Please try again.");
+
+ Sentry.captureException(error);
+ }
+ };
+
+ const handleConfirmImport = () => {
+ if (importState.step !== "preview") {
+ return;
+ }
+
+ const { sellers, buyers } = importState;
+
+ const showImportError = (description: string) => {
+ toast.error("Could not import sellers & buyers", {
+ id: "import_contacts_error_toast",
+ description,
+ closeButton: true,
+ position: toastPosition,
+ });
+ };
+
+ try {
+ const previousSellersJson = getAppStorageItem(SELLERS_LOCAL_STORAGE_KEY);
+
+ const areSellersPersisted = setAppStorageItem({
+ key: SELLERS_LOCAL_STORAGE_KEY,
+ value: JSON.stringify(sellers.contacts),
+ });
+ const areBuyersPersisted =
+ areSellersPersisted &&
+ setAppStorageItem({
+ key: BUYERS_LOCAL_STORAGE_KEY,
+ value: JSON.stringify(buyers.contacts),
+ });
+
+ if (!areBuyersPersisted) {
+ // Put the sellers back if only they made it, so an import lands whole or not at all.
+ if (areSellersPersisted) {
+ setAppStorageItem({
+ key: SELLERS_LOCAL_STORAGE_KEY,
+ value: previousSellersJson ?? "[]",
+ });
+ }
+
+ showImportError(
+ "Your browser storage is full or unavailable. Nothing was imported.",
+ );
+
+ return;
+ }
+
+ window.dispatchEvent(new Event(SAVED_CONTACTS_IMPORTED_EVENT));
+
+ setIsImportDialogOpen(false);
+
+ toast.success(
+ `Imported ${describeContactCounts({
+ sellerCount: sellers.added.length,
+ buyerCount: buyers.added.length,
+ })}`,
+ {
+ id: "import_contacts_success_toast",
+ richColors: true,
+ position: toastPosition,
+ },
+ );
+
+ umamiTrackEvent("import_contacts_success", {
+ data: {
+ sellersAdded: sellers.added.length,
+ buyersAdded: buyers.added.length,
+ invalid: sellers.invalidEntries.length + buyers.invalidEntries.length,
+ nameConflicts:
+ sellers.nameConflicts.length + buyers.nameConflicts.length,
+ },
+ });
+ } catch (error) {
+ console.error("Failed to import sellers & buyers:", error);
+
+ showImportError("Please try again");
+
+ Sentry.captureException(error);
+ }
+ };
+
+ return (
+ <>
+ {/*
+ Not modal: a modal menu blocks the rest of the page, so with it open a tap on the
+ other section's ⋯ (or anything else) only closed the menu and needed a second tap.
+ */}
+ <DropdownMenu
+ modal={false}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) {
+ return;
+ }
+
+ // dismiss any existing toast for better UX
+ toast.dismiss();
+
+ // Read on open rather than during render: storage is not there on the server,
+ // and the other section may have just added or deleted an entry.
+ setHasSavedContacts(
+ readSavedContacts({
+ key: SELLERS_LOCAL_STORAGE_KEY,
+ schema: sellerSchema,
+ }).length > 0 ||
+ readSavedContacts({
+ key: BUYERS_LOCAL_STORAGE_KEY,
+ schema: buyerSchema,
+ }).length > 0,
+ );
+ }}
+ >
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="size-8 shrink-0 px-2"
+ aria-label="Import or export sellers & buyers"
+ >
+ <Ellipsis className="size-3.5" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" loop>
+ <DropdownMenuItem
+ disabled={!hasSavedContacts}
+ onSelect={handleExport}
+ >
+ <Download className="size-3.5" />
+ Export sellers & buyers
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={!isLocalStorageAvailable}
+ onSelect={() => {
+ setImportState({ step: "choose" });
+ setIsImportDialogOpen(true);
+ }}
+ >
+ <Upload className="size-3.5" />
+ Import from file…
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <ImportContactsDialog
+ isOpen={isImportDialogOpen}
+ onOpenChange={setIsImportDialogOpen}
+ state={importState}
+ onFileSelected={(file) => {
+ void handleFileSelected(file);
+ }}
+ onConfirm={handleConfirmImport}
+ />
+ </>
+ );
+}
+
+interface ReadSavedContactsOptions<T> {
+ /** The `localStorage` key holding the list. */
+ key: LocalStorageKey;
+ /** The schema each saved entry must pass. */
+ schema: z.ZodType<T>;
+}
+
+/**
+ * The saved list with invalid entries left out. The management sections already drop
+ * and report those when they load, so they are not reported again here.
+ *
+ * A value that is not JSON at all reads as an empty list, which is also what the
+ * management sections show for it. Throwing instead would make export and import fail
+ * for good, and importing a backup is exactly how the user gets the list back.
+ */
+function readSavedContacts<T>({
+ key,
+ schema,
+}: ReadSavedContactsOptions<T>): T[] {
+ const parsed = parseStoredJson(getAppStorageItem(key));
+
+ if (!Array.isArray(parsed)) {
+ return [];
+ }
+
+ return parsed.flatMap((entry) => {
+ const result = schema.safeParse(entry);
+
+ return result.success ? [result.data] : [];
+ });
+}
+
+/**
+ * Saved contacts use `Date.now()` ids, which would collide when a whole file is imported
+ * in the same millisecond, so imported entries without an id get a random suffix too.
+ *
+ * Not `crypto.randomUUID()`: it is missing before Safari 15.4, which `.browserslistrc`
+ * still targets, and Next does not polyfill it. The id only has to be unique within
+ * this browser's list, not unguessable.
+ */
+function createContactId(): string {
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
+}
+
+function parseStoredJson(saved: string | null): unknown {
+ if (!saved) {
+ return [];
+ }
+
+ try {
+ return JSON.parse(saved);
+ } catch {
+ return [];
+ }
+}
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/import-contacts-dialog.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/import-contacts-dialog.tsx
new file mode 100644
index 0000000..bdb39cb
--- /dev/null
+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/import-contacts-dialog.tsx
@@ -0,0 +1,852 @@
+import { Check, ChevronDown, FileUp, FileWarning } from "lucide-react";
+import { useEffect, useEffectEvent, useState } from "react";
+
+import {
+ describeContactCounts,
+ type ContactEntryIssue,
+ type InvalidContactEntry,
+ type MergeImportedContactsResult,
+} from "@/app/(main)/(app)/utils/contacts-backup";
+import type { BuyerData, SellerData } from "@/app/schema";
+import { Button, buttonVariants } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { cn } from "@/lib/utils";
+
+/** Longer values are cut short, so one long address does not push the problem off screen. */
+const MAX_VALUE_LENGTH = 120;
+
+export type ImportContactsDialogState =
+ | { step: "choose" }
+ | {
+ step: "error";
+ /** The name of the file that could not be read. */
+ fileName: string;
+ /** A user-facing explanation of why the file cannot be imported. */
+ error: string;
+ }
+ | {
+ step: "preview";
+ /** The name of the file being imported. */
+ fileName: string;
+ /** What importing the file would do to the saved sellers. */
+ sellers: MergeImportedContactsResult<SellerData>;
+ /** What importing the file would do to the saved buyers. */
+ buyers: MergeImportedContactsResult<BuyerData>;
+ };
+
+interface ImportContactsDialogProps {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ state: ImportContactsDialogState;
+ /** Called with the file the user picked or dropped. */
+ onFileSelected: (file: File) => void;
+ /** Saves the entries shown in the preview. */
+ onConfirm: () => void;
+}
+
+/**
+ * Import runs in one dialog: choose a file, then review what it would add and what it
+ * would skip (with the problems in each entry that cannot be imported) before anything
+ * is saved. A file that cannot be read at all shows why, and the shape we expect.
+ */
+export function ImportContactsDialog({
+ isOpen,
+ onOpenChange,
+ state,
+ onFileSelected,
+ onConfirm,
+}: ImportContactsDialogProps) {
+ const [isDraggingFile, setIsDraggingFile] = useState(false);
+
+ // An effect event, so the listeners below see the latest callback without
+ // re-subscribing on every render
+ const handleDroppedFile = useEffectEvent((file: File) => {
+ onFileSelected(file);
+ });
+
+ const isChoosingFile = state.step === "choose";
+
+ // The whole window takes the drop on the choose step, overlay included. A file released
+ // anywhere the page does not cancel `drop` gets the browser's default action, which
+ // opens it in the tab and navigates away from the app, so file drops are still cancelled
+ // on the other steps; they just import nothing, so a stray drop cannot swap the file
+ // under review. Drags that carry no file (selected text, links) are left alone.
+ useEffect(() => {
+ if (!isOpen) {
+ return;
+ }
+
+ // The elements the drag has entered and not yet left, as each child element the
+ // pointer crosses fires both events. `relatedTarget` cannot tell leaving the window
+ // from moving between children: WebKit leaves it null on every `dragleave`. A set
+ // rather than a count, because Firefox can fire `dragenter` more than once on the same
+ // element, which would leave a count above zero after the drag has left the window.
+ const enteredTargets = new Set<EventTarget>();
+
+ const handleDragEnter = (event: DragEvent) => {
+ if (!isChoosingFile || !isFileDrag(event) || !event.target) {
+ return;
+ }
+
+ enteredTargets.add(event.target);
+ setIsDraggingFile(true);
+ };
+
+ const handleDragLeave = (event: DragEvent) => {
+ if (!event.target) {
+ return;
+ }
+
+ enteredTargets.delete(event.target);
+
+ if (enteredTargets.size === 0) {
+ setIsDraggingFile(false);
+ }
+ };
+
+ const handleDragOver = (event: DragEvent) => {
+ if (!isFileDrag(event)) {
+ return;
+ }
+
+ event.preventDefault();
+
+ if (!isChoosingFile && event.dataTransfer) {
+ // Shows the "not allowed" cursor instead of suggesting the drop does something
+ event.dataTransfer.dropEffect = "none";
+ }
+ };
+
+ const handleDrop = (event: DragEvent) => {
+ if (!isFileDrag(event)) {
+ return;
+ }
+
+ event.preventDefault();
+ enteredTargets.clear();
+ setIsDraggingFile(false);
+
+ const file = event.dataTransfer?.files[0];
+
+ if (isChoosingFile && file) {
+ handleDroppedFile(file);
+ }
+ };
+
+ window.addEventListener("dragenter", handleDragEnter);
+ window.addEventListener("dragleave", handleDragLeave);
+ window.addEventListener("dragover", handleDragOver);
+ window.addEventListener("drop", handleDrop);
+
+ return () => {
+ window.removeEventListener("dragenter", handleDragEnter);
+ window.removeEventListener("dragleave", handleDragLeave);
+ window.removeEventListener("dragover", handleDragOver);
+ window.removeEventListener("drop", handleDrop);
+ setIsDraggingFile(false);
+ };
+ }, [isOpen, isChoosingFile]);
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent
+ // `dvh` is missing before Safari 15.4; without the `vh` fallback the dialog would
+ // have no height limit there, pushing its title and buttons off screen
+ className="flex max-h-[calc(100vh-2rem)] flex-col gap-4 supports-[height:100dvh]:max-h-[calc(100dvh-2rem)] sm:max-w-[520px]"
+ data-testid="import-contacts-dialog"
+ >
+ {state.step === "choose" ? (
+ <ChooseFileStep
+ isDraggingFile={isDraggingFile}
+ onFileSelected={onFileSelected}
+ />
+ ) : state.step === "error" ? (
+ <FileErrorStep
+ fileName={state.fileName}
+ error={state.error}
+ onFileSelected={onFileSelected}
+ />
+ ) : (
+ <PreviewStep
+ fileName={state.fileName}
+ sellers={state.sellers}
+ buyers={state.buyers}
+ onFileSelected={onFileSelected}
+ onConfirm={onConfirm}
+ />
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+interface ChooseFileStepProps {
+ /** A file is being dragged over the page, so the drop zone shows it will take it. */
+ isDraggingFile: boolean;
+ onFileSelected: (file: File) => void;
+}
+
+function ChooseFileStep({
+ isDraggingFile,
+ onFileSelected,
+}: ChooseFileStepProps) {
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>Import sellers & buyers</DialogTitle>
+ <DialogDescription className="text-pretty">
+ Choose a file made with “Export sellers & buyers”. You’ll review
+ everything in it before anything is saved.
+ </DialogDescription>
+ </DialogHeader>
+
+ <FilePickerLabel
+ onFileSelected={onFileSelected}
+ className={cn(
+ "flex cursor-pointer flex-col items-center gap-1 rounded-lg border border-dashed border-slate-300 px-4 py-6 text-center transition-colors focus-within:outline focus-within:outline-2 focus-within:outline-offset-2 hover:bg-slate-50",
+ isDraggingFile && "border-slate-600 bg-slate-100",
+ )}
+ >
+ <FileUp className="mb-1 size-5 text-slate-500" aria-hidden />
+ <span className="text-sm font-medium text-slate-900">
+ Drop a .json file here
+ </span>
+ <span className="text-sm text-slate-500">
+ or <span className="underline underline-offset-2">choose a file</span>
+ </span>
+ </FilePickerLabel>
+
+ <ul className="space-y-1.5 text-sm text-slate-600">
+ {IMPORT_RULES.map((rule) => {
+ return (
+ <li key={rule} className="flex gap-2">
+ <Check
+ className="mt-0.5 size-3.5 shrink-0 text-green-600"
+ aria-hidden
+ />
+ {rule}
+ </li>
+ );
+ })}
+ </ul>
+
+ <details className="group text-sm">
+ <summary className="flex cursor-pointer list-none items-center gap-1 text-slate-500 hover:text-slate-900 [&::-webkit-details-marker]:hidden">
+ <ChevronDown
+ className="size-3.5 transition-transform group-open:rotate-180"
+ aria-hidden
+ />
+ What does the file look like?
+ </summary>
+ <ExpectedFileShape />
+ </details>
+
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="outline" size="sm">
+ Cancel
+ </Button>
+ </DialogClose>
+ </DialogFooter>
+ </>
+ );
+}
+
+interface FileErrorStepProps {
+ fileName: string;
+ error: string;
+ onFileSelected: (file: File) => void;
+}
+
+function FileErrorStep({
+ fileName,
+ error,
+ onFileSelected,
+}: FileErrorStepProps) {
+ return (
+ <>
+ <DialogHeader className="text-left">
+ <div className="flex items-center gap-2">
+ <FileWarning className="size-5 shrink-0 text-red-600" aria-hidden />
+ <DialogTitle>This file can’t be imported</DialogTitle>
+ </div>
+ <DialogDescription className="text-pretty">
+ <span className="break-all font-medium text-slate-700">
+ {fileName}
+ </span>
+ : {error}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="text-sm">
+ <p className="text-slate-600">A backup file looks like this:</p>
+ <ExpectedFileShape />
+ </div>
+
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="outline" size="sm">
+ Cancel
+ </Button>
+ </DialogClose>
+ <FilePickerLabel
+ onFileSelected={onFileSelected}
+ className={buttonVariants({
+ size: "sm",
+ className:
+ "cursor-pointer focus-within:outline focus-within:outline-2",
+ })}
+ >
+ Choose another file
+ </FilePickerLabel>
+ </DialogFooter>
+ </>
+ );
+}
+
+interface PreviewStepProps {
+ fileName: string;
+ sellers: MergeImportedContactsResult<SellerData>;
+ buyers: MergeImportedContactsResult<BuyerData>;
+ onFileSelected: (file: File) => void;
+ onConfirm: () => void;
+}
+
+function PreviewStep({
+ fileName,
+ sellers,
+ buyers,
+ onFileSelected,
+ onConfirm,
+}: PreviewStepProps) {
+ const addedCount = sellers.added.length + buyers.added.length;
+ const duplicateCount = sellers.duplicates.length + buyers.duplicates.length;
+ const nameConflictCount =
+ sellers.nameConflicts.length + buyers.nameConflicts.length;
+ const problemCount =
+ sellers.invalidEntries.length +
+ buyers.invalidEntries.length +
+ nameConflictCount;
+
+ const title =
+ addedCount > 0
+ ? "Review import"
+ : problemCount > 0
+ ? "Nothing can be imported"
+ : "Nothing new to import";
+
+ return (
+ <>
+ <DialogHeader className="text-left">
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription className="break-all">{fileName}</DialogDescription>
+ </DialogHeader>
+
+ <dl className="grid grid-cols-3 gap-2">
+ <PreviewStat label="to add" count={addedCount} />
+ <PreviewStat label="already saved" count={duplicateCount} />
+ <PreviewStat
+ label="can’t import"
+ count={problemCount}
+ isProblem={problemCount > 0}
+ />
+ </dl>
+
+ {problemCount > 0 ? (
+ <p className="text-pretty text-sm text-slate-600">
+ {addedCount > 0
+ ? "Fix the highlighted fields in the file and import it again, or import the rest now."
+ : "Fix the highlighted fields in the file and import it again."}
+ {nameConflictCount > 0
+ ? " For a name that’s already saved, rename it in the file or rename the saved one."
+ : null}
+ </p>
+ ) : null}
+
+ <div className="-mx-6 min-h-0 flex-1 space-y-4 overflow-y-auto px-6">
+ <PartyPreview party="Sellers" result={sellers} />
+ <PartyPreview party="Buyers" result={buyers} />
+ </div>
+
+ <DialogFooter>
+ {addedCount > 0 ? (
+ <>
+ <DialogClose asChild>
+ <Button variant="outline" size="sm">
+ Cancel
+ </Button>
+ </DialogClose>
+ <Button size="sm" onClick={onConfirm}>
+ Import{" "}
+ {describeContactCounts({
+ sellerCount: sellers.added.length,
+ buyerCount: buyers.added.length,
+ })}
+ </Button>
+ </>
+ ) : (
+ <>
+ <FilePickerLabel
+ onFileSelected={onFileSelected}
+ className={buttonVariants({
+ variant: "outline",
+ size: "sm",
+ className:
+ "cursor-pointer focus-within:outline focus-within:outline-2",
+ })}
+ >
+ Choose another file
+ </FilePickerLabel>
+ <DialogClose asChild>
+ <Button size="sm">Close</Button>
+ </DialogClose>
+ </>
+ )}
+ </DialogFooter>
+ </>
+ );
+}
+
+interface PreviewStatProps {
+ label: string;
+ count: number;
+ /** Highlights the count in red. */
+ isProblem?: boolean;
+}
+
+function PreviewStat({ label, count, isProblem = false }: PreviewStatProps) {
+ return (
+ <div
+ className={cn(
+ "flex flex-col-reverse rounded-lg bg-slate-50 px-3 py-2",
+ isProblem && "bg-red-50 text-red-700",
+ )}
+ >
+ <dt className={cn("text-xs text-slate-500", isProblem && "text-red-700")}>
+ {label}
+ </dt>
+ <dd className="text-lg font-semibold tabular-nums">{count}</dd>
+ </div>
+ );
+}
+
+interface PartyPreviewProps {
+ party: "Sellers" | "Buyers";
+ result: MergeImportedContactsResult<SellerData | BuyerData>;
+}
+
+/**
+ * One party's entries from the file: the new ones first, then the ones that cannot be
+ * imported (opened, so their problems show), then the ones already saved.
+ */
+function PartyPreview({ party, result }: PartyPreviewProps) {
+ const { added, duplicates, invalidEntries, nameConflicts } = result;
+
+ if (
+ added.length +
+ duplicates.length +
+ invalidEntries.length +
+ nameConflicts.length ===
+ 0
+ ) {
+ return null;
+ }
+
+ return (
+ <section>
+ <h3 className="mb-1.5 text-xs font-medium text-slate-500">{party}</h3>
+ <ul
+ className="divide-y divide-slate-200 overflow-hidden rounded-lg border border-slate-200 text-sm"
+ aria-label={party}
+ >
+ {added.map((contact, index) => {
+ return (
+ <PreviewRow
+ key={`added-${index}`}
+ name={contact.name}
+ address={contact.address}
+ >
+ <StatusBadge tone="success">New</StatusBadge>
+ </PreviewRow>
+ );
+ })}
+ {invalidEntries.map((invalidEntry, index) => {
+ return (
+ <ProblemRow
+ key={`invalid-${index}`}
+ invalidEntry={invalidEntry}
+ badge={
+ invalidEntry.issues.length === 1
+ ? "1 problem"
+ : `${invalidEntry.issues.length} problems`
+ }
+ />
+ );
+ })}
+ {nameConflicts.map((invalidEntry, index) => {
+ return (
+ <ProblemRow
+ key={`conflict-${index}`}
+ invalidEntry={invalidEntry}
+ badge="Name taken"
+ />
+ );
+ })}
+ {duplicates.map((contact, index) => {
+ return (
+ <PreviewRow
+ key={`duplicate-${index}`}
+ name={contact.name}
+ address={contact.address}
+ isMuted
+ >
+ <StatusBadge tone="neutral">Already saved</StatusBadge>
+ </PreviewRow>
+ );
+ })}
+ </ul>
+ </section>
+ );
+}
+
+interface PreviewRowProps {
+ name: string;
+ /** Can span several lines, as typed in the address field. */
+ address: string;
+ /** For entries that will be skipped. */
+ isMuted?: boolean;
+ /** The status badge. */
+ children: React.ReactNode;
+}
+
+function PreviewRow({
+ name,
+ address,
+ isMuted = false,
+ children,
+}: PreviewRowProps) {
+ return (
+ <li
+ className={cn(
+ "flex items-start justify-between gap-2 px-3 py-2",
+ isMuted && "text-slate-500",
+ )}
+ >
+ <div className="min-w-0">
+ <p className="truncate">{name}</p>
+ <ContactAddress address={address} />
+ </div>
+ {children}
+ </li>
+ );
+}
+
+interface ContactAddressProps {
+ /** Can span several lines, as typed in the address field. */
+ address: string;
+}
+
+/** Kept to two lines, so one long address does not push the rest of the list down. */
+function ContactAddress({ address }: ContactAddressProps) {
+ return (
+ <p className="line-clamp-2 whitespace-pre-line break-words text-xs text-slate-500">
+ {address}
+ </p>
+ );
+}
+
+interface ProblemRowProps {
+ invalidEntry: InvalidContactEntry;
+ badge: string;
+}
+
+function ProblemRow({ invalidEntry, badge }: ProblemRowProps) {
+ const { label, entry, issues } = invalidEntry;
+
+ const entryIssues = issues.filter((issue) => {
+ return !issue.field;
+ });
+ const address =
+ isPlainObject(entry) && typeof entry.address === "string"
+ ? entry.address
+ : null;
+
+ return (
+ <li>
+ <details open className="group" data-testid="import-problem-entry">
+ <summary className="flex cursor-pointer list-none items-start justify-between gap-2 px-3 py-2 hover:bg-slate-50 [&::-webkit-details-marker]:hidden">
+ <div className="min-w-0">
+ <p className="truncate">{label}</p>
+ {address ? <ContactAddress address={address} /> : null}
+ </div>
+ <span className="flex shrink-0 items-center gap-1.5">
+ <StatusBadge tone="danger">{badge}</StatusBadge>
+ <ChevronDown
+ className="size-3.5 text-slate-500 transition-transform group-open:rotate-180"
+ aria-hidden
+ />
+ </span>
+ </summary>
+
+ <div className="border-t border-slate-200 bg-slate-50/60">
+ {entryIssues.length > 0 ? (
+ <ul className="space-y-0.5 px-3 pt-2 text-xs text-red-700">
+ {entryIssues.map((issue) => {
+ return <li key={issue.message}>{issue.message}</li>;
+ })}
+ </ul>
+ ) : null}
+
+ <EntrySource entry={entry} issues={issues} />
+ </div>
+ </details>
+ </li>
+ );
+}
+
+interface StatusBadgeProps {
+ tone: "success" | "neutral" | "danger";
+ children: React.ReactNode;
+}
+
+function StatusBadge({ tone, children }: StatusBadgeProps) {
+ return (
+ <span
+ className={cn(
+ "shrink-0 whitespace-nowrap rounded-full px-2 py-0.5 text-xs font-medium",
+ tone === "success" && "bg-green-200/80 text-green-900",
+ tone === "neutral" && "bg-slate-100 text-slate-600",
+ tone === "danger" && "bg-red-200/80 text-red-900",
+ )}
+ data-testid="import-export-status-badge"
+ >
+ {children}
+ </span>
+ );
+}
+
+interface FilePickerLabelProps extends Omit<
+ React.LabelHTMLAttributes<HTMLLabelElement>,
+ "htmlFor"
+> {
+ onFileSelected: (file: File) => void;
+}
+
+/**
+ * A <label> around a visually hidden file input, rather than a button calling
+ * `input.click()`: the tap itself opens the picker, with no programmatic click for the
+ * browser to refuse. Chrome on iOS ignores `input.click()` after the page has started a
+ * download (e.g. right after an export), while Safari does not. The input stays
+ * focusable, so keyboard users reach it with Tab and open it with Space.
+ */
+function FilePickerLabel({
+ onFileSelected,
+ children,
+ ...labelProps
+}: FilePickerLabelProps) {
+ return (
+ <label {...labelProps}>
+ {children}
+ <input
+ type="file"
+ accept="application/json,.json"
+ className="sr-only"
+ data-testid="contacts-backup-file-input"
+ onChange={(event) => {
+ const input = event.currentTarget;
+ const file = input.files?.[0];
+
+ // Clear the input so picking the same file again still fires `change`.
+ input.value = "";
+
+ if (file) {
+ onFileSelected(file);
+ }
+ }}
+ />
+ </label>
+ );
+}
+
+function ExpectedFileShape() {
+ return (
+ <>
+ <pre className="mt-2 overflow-x-auto rounded-lg bg-slate-50 px-3 py-2 font-mono text-[11px] leading-5 text-slate-700">
+ {EXPECTED_FILE_EXAMPLE}
+ </pre>
+ <p className="mt-2 text-pretty text-xs text-slate-500">
+ Every seller and buyer needs a <code>name</code> and an{" "}
+ <code>address</code>. Either list can be empty, and every other field is
+ optional.
+ </p>
+ </>
+ );
+}
+
+interface EntrySourceProps {
+ entry: unknown;
+ issues: ContactEntryIssue[];
+}
+
+/**
+ * The entry as JSON, one field per line. A field that failed is highlighted with its
+ * error under it; a required field the entry lacks is added as a "missing" line.
+ */
+function EntrySource({ entry, issues }: EntrySourceProps) {
+ const codeClassName =
+ "overflow-x-auto whitespace-pre-wrap break-all px-3 py-2 font-mono text-[11px] leading-5 text-slate-700";
+
+ if (!isPlainObject(entry)) {
+ return <pre className={codeClassName}>{formatValue(entry)}</pre>;
+ }
+
+ const messagesByField = new Map<string, string[]>();
+
+ for (const { field, message } of issues) {
+ if (!field) {
+ continue;
+ }
+
+ // `address.0` and the like still belong to the top-level field
+ const [key = field] = field.split(".");
+
+ messagesByField.set(key, [...(messagesByField.get(key) ?? []), message]);
+ }
+
+ const missingFields = [...messagesByField.keys()].filter((key) => {
+ return !Object.hasOwn(entry, key);
+ });
+
+ return (
+ <pre className={codeClassName}>
+ <span className="block">{"{"}</span>
+ {Object.entries(entry).map(([key, value]) => {
+ return (
+ <EntryLine
+ key={key}
+ field={key}
+ value={formatValue(value)}
+ messages={messagesByField.get(key)}
+ />
+ );
+ })}
+ {missingFields.map((key) => {
+ return (
+ <EntryLine
+ key={key}
+ field={key}
+ value={null}
+ messages={messagesByField.get(key)}
+ />
+ );
+ })}
+ <span className="block">{"}"}</span>
+ </pre>
+ );
+}
+
+interface EntryLineProps {
+ /** The field's key. */
+ field: string;
+ /** The formatted value, or `null` when the field is missing from the entry. */
+ value: string | null;
+ /** What is wrong with the field; absent when nothing is. */
+ messages?: string[];
+}
+
+function EntryLine({ field, value, messages }: EntryLineProps) {
+ const hasProblem = Boolean(messages?.length);
+
+ return (
+ <span
+ className={cn(
+ "-mx-3 block px-3",
+ hasProblem && "border-l-2 border-red-500 bg-red-50 text-red-900",
+ )}
+ data-invalid-field={hasProblem ? field : undefined}
+ >
+ {" "}
+ <span className="text-slate-500">{JSON.stringify(field)}:</span>{" "}
+ {value === null ? <span className="italic">missing</span> : value}
+ {messages?.map((message) => {
+ return (
+ <span
+ key={message}
+ className="block break-normal pl-4 font-sans text-xs font-medium text-red-700"
+ >
+ ↳ {message}
+ </span>
+ );
+ })}
+ </span>
+ );
+}
+
+function formatValue(value: unknown): string {
+ const text = JSON.stringify(value) ?? String(value);
+
+ return text.length > MAX_VALUE_LENGTH
+ ? `${text.slice(0, MAX_VALUE_LENGTH)}…`
+ : text;
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+/**
+ * Whether the drag carries files, as opposed to selected text or a link. Checked three
+ * ways, as react-dropzone does: some Chromium file drags list only `text/plain` in
+ * `types` but still have an item of kind `file` (react-dropzone#1409), and old Firefox
+ * reports `application/x-moz-file`. Missing one would leave that drop uncancelled, and
+ * the browser would open the file in the tab.
+ */
+function isFileDrag(event: DragEvent): boolean {
+ const dataTransfer = event.dataTransfer;
+
+ if (!dataTransfer) {
+ return false;
+ }
+
+ // `Array.from`: `types` was a `DOMStringList`, which has no `includes`, in older browsers
+ const types = Array.from(dataTransfer.types);
+
+ return (
+ types.includes("Files") ||
+ types.includes("application/x-moz-file") ||
+ Array.from(dataTransfer.items ?? []).some((item) => {
+ return item.kind === "file";
+ })
+ );
+}
+
+const IMPORT_RULES = [
+ "Only adds. Sellers and buyers you’ve saved are never changed.",
+ "Anything already saved is skipped, so nothing is added twice.",
+ "The invoice you’re working on isn’t touched.",
+] as const;
+
+const EXPECTED_FILE_EXAMPLE = `{
+ "app": "easyinvoicepdf",
+ "version": 1,
+ "sellers": [
+ {
+ "name": "Acme Ltd",
+ "address": "1 Main Street"
+ }
+ ],
+ "buyers": [
+ {
+ "name": "Globex GmbH",
+ "address": "2 Side Road"
+ }
+ ]
+}`;
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-management.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-management.tsx
index 7a4f31f..71e267c 100644
--- a/src/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-management.tsx
+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-management.tsx
@@ -1,27 +1,13 @@
-import * as Sentry from "@sentry/nextjs";
import { Plus, Trash2, Pencil, AlertCircleIcon } from "lucide-react";
-import {
- useId,
- useState,
- useEffect,
- type Dispatch,
- type SetStateAction,
-} from "react";
+import { useId, useState, type Dispatch, type SetStateAction } from "react";
import type { UseFormSetValue } from "react-hook-form";
import { toast } from "sonner";
+import { ContactsBackupMenu } from "@/app/(main)/(app)/components/invoice-form/sections/components/contacts-backup-menu";
import { SellerDialog } from "@/app/(main)/(app)/components/invoice-form/sections/components/seller/seller-dialog";
-import {
- getAppStorageItem,
- setAppStorageItem,
-} from "@/app/(main)/(app)/utils/app-local-storage";
-import { DEFAULT_SELLER_DATA } from "@/app/constants";
-import {
- SELLERS_LOCAL_STORAGE_KEY,
- sellerSchema,
- type InvoiceData,
- type SellerData,
-} from "@/app/schema";
+import { usePartyActions } from "@/app/(main)/(app)/components/invoice-form/sections/hooks/use-party-actions";
+import { useSavedParties } from "@/app/(main)/(app)/components/invoice-form/sections/hooks/use-saved-parties";
+import { type InvoiceData, type SellerData } from "@/app/schema";
import {
AlertDialog,
AlertDialogAction,
@@ -36,7 +22,6 @@ import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { SelectNative } from "@/components/ui/select-native";
import { CustomTooltip } from "@/components/ui/tooltip";
-import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
import { useIsLocalStorageAvailable } from "@/lib/use-is-local-storage-available";
import { cn } from "@/lib/utils";
@@ -80,12 +65,7 @@ export function SellerManagement({
const [isSellerDialogOpen, setIsSellerDialogOpen] = useState(false);
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
- // State to store the list of saved sellers for the dropdown selection.
- const [sellersSelectOptions, setSellersSelectOptions] = useState<
- SellerData[]
- >([]);
-
- // State to track the seller currently being edited (null if not editing).
+ // The saved seller being edited in the dialog; `null` while adding a new one
const [editingSeller, setEditingSeller] = useState<SellerData | null>(null);
const sellerSelectId = useId();
@@ -94,277 +74,30 @@ export function SellerManagement({
const isEditMode = Boolean(editingSeller);
- // Load sellers from localStorage on component mount
- useEffect(() => {
- try {
- const savedSellers = getAppStorageItem(SELLERS_LOCAL_STORAGE_KEY);
- const parsedSellers: unknown = savedSellers
- ? JSON.parse(savedSellers)
- : [];
-
- const rawSellers = Array.isArray(parsedSellers) ? parsedSellers : [];
-
- 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,
- );
- }
- }
-
- // 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`,
- ),
- );
-
- setAppStorageItem({
- key: SELLERS_LOCAL_STORAGE_KEY,
- value: JSON.stringify(validSellers),
- });
- }
-
- const selectedSeller = validSellers.find((seller: SellerData) => {
- return seller?.id === invoiceData?.seller?.id;
- });
-
- // oxlint-disable-next-line react/set-state-in-effect react-you-might-not-need-an-effect/no-adjust-state-on-prop-change -- localStorage is an external system: the saved sellers cannot be derived during render, they have to be read after mount
- setSellersSelectOptions(validSellers);
- setSelectedSellerId(selectedSeller?.id ?? "");
- } catch (error) {
- console.error("Failed to load sellers:", error);
-
- Sentry.captureException(error);
- }
- }, [invoiceData?.seller?.id, setSelectedSellerId]);
-
- // Update sellers when a new one is added
- const handleSellerAdd = (
- newSeller: SellerData,
- {
- shouldApplyNewSellerToInvoice,
- }: { shouldApplyNewSellerToInvoice: boolean },
- ) => {
- try {
- const newSellerWithId = {
- ...newSeller,
- // Generate a unique ID for the new seller (IMPORTANT!) =)
- id: Date.now().toString(),
- } satisfies SellerData;
-
- const newSellers = [...sellersSelectOptions, newSellerWithId];
-
- // Save to localStorage
- const persisted = setAppStorageItem({
- key: SELLERS_LOCAL_STORAGE_KEY,
- value: JSON.stringify(newSellers),
- });
-
- // Nothing to show the user later if the list could not be saved, so stop here
- // rather than reporting a success the next page load would contradict.
- if (!persisted) {
- showSellerStorageErrorToast({
- message: "Failed to add seller",
- id: "add_seller_error_toast",
- isMobile,
- });
-
- return;
- }
-
- // Update the sellers state
- setSellersSelectOptions(newSellers);
-
- // Apply the new seller to the invoice if the user wants to, otherwise just add it to the list and use it later if needed
- if (shouldApplyNewSellerToInvoice) {
- setValue("seller", newSellerWithId);
- setSelectedSellerId(newSellerWithId?.id);
- }
-
- toast.success(
- shouldApplyNewSellerToInvoice
- ? "Seller added and applied to invoice"
- : "Seller added successfully",
- {
- id: "add_seller_success_toast",
- richColors: true,
- position: isMobile ? "top-center" : "bottom-right",
- },
- );
-
- // analytics track event
- umamiTrackEvent("add_seller_success");
- } catch (error) {
- console.error("Failed to add seller:", error);
-
- toast.error("Failed to add seller", {
- id: "add_seller_error_toast",
- description: "Please try again",
- closeButton: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
-
- Sentry.captureException(error);
- }
- };
-
- // Update sellers when edited
- const handleSellerEdit = (editedSeller: SellerData) => {
- try {
- const updatedSellers = sellersSelectOptions.map((seller) => {
- return seller.id === editedSeller.id ? editedSeller : seller;
- });
-
- const persisted = setAppStorageItem({
- key: SELLERS_LOCAL_STORAGE_KEY,
- value: JSON.stringify(updatedSellers),
- });
-
- if (!persisted) {
- showSellerStorageErrorToast({
- message: "Failed to edit seller",
- id: "edit_seller_error_toast",
- isMobile,
- });
-
- return;
- }
-
- setSellersSelectOptions(updatedSellers);
- setValue("seller", editedSeller);
-
- // end edit mode
- setEditingSeller(null);
-
- toast.success("Seller updated successfully", {
- id: "edit_seller_success_toast",
- richColors: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
-
- // analytics track event
- umamiTrackEvent("edit_seller_success");
- } catch (error) {
- console.error("Failed to edit seller:", error);
-
- toast.error("Failed to edit seller", {
- id: "edit_seller_error_toast",
- description: "Please try again",
- closeButton: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
-
- Sentry.captureException(error);
- }
- };
-
- const handleSellerChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
- const id = event.target.value;
-
- if (id) {
- setSelectedSellerId(id);
- const selectedSeller = sellersSelectOptions.find((seller) => {
- return seller.id === id;
- });
-
- if (selectedSeller) {
- setValue("seller", selectedSeller);
- toast.success(`Seller "${selectedSeller.name}" applied to invoice`, {
- id: "change_seller_success_toast",
- richColors: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
- }
- } else {
- // Clear the seller from the form if the user selects the empty option
- setSelectedSellerId("");
- setValue("seller", DEFAULT_SELLER_DATA);
-
- toast.success("Seller restored to default", {
- id: "reset_seller_success_toast",
- richColors: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
- }
-
- // analytics track event
- umamiTrackEvent("change_seller");
- };
-
- const handleDeleteSeller = () => {
- try {
- const updatedSellers = sellersSelectOptions.filter((seller) => {
- return seller.id !== selectedSellerId;
- });
-
- const persisted = setAppStorageItem({
- key: SELLERS_LOCAL_STORAGE_KEY,
- value: JSON.stringify(updatedSellers),
- });
-
- if (!persisted) {
- showSellerStorageErrorToast({
- message: "Failed to delete seller",
- id: "delete_seller_error_toast",
- isMobile,
- });
-
- return;
- }
-
- setSellersSelectOptions(updatedSellers);
- // Clear the selected seller index
- setSelectedSellerId("");
- // Clear the seller from the form if it was selected
- setValue("seller", DEFAULT_SELLER_DATA);
-
- // Close the delete dialog
- setIsDeleteDialogOpen(false);
-
- toast.success("Seller deleted successfully", {
- id: "delete_seller_success_toast",
- richColors: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
-
- // analytics track event
- umamiTrackEvent("delete_seller_success");
- } catch (error) {
- console.error("Failed to delete seller:", error);
-
- toast.error("Failed to delete seller", {
- id: "delete_seller_error_toast",
- description: "Please try again",
- closeButton: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
-
- Sentry.captureException(error);
- }
- };
+ const { savedParties: savedSellers, saveParties } = useSavedParties({
+ party: "seller",
+ invoicePartyId: invoiceData?.seller?.id,
+ setSelectedId: setSelectedSellerId,
+ });
- const activeSeller = sellersSelectOptions.find((seller) => {
+ const { addParty, editParty, deleteSelectedParty, selectParty } =
+ usePartyActions({
+ party: "seller",
+ savedParties: savedSellers,
+ saveParties,
+ selectedId: selectedSellerId,
+ setSelectedId: setSelectedSellerId,
+ applyToInvoice: (seller) => {
+ setValue("seller", seller);
+ },
+ isMobile,
+ });
+
+ const activeSeller = savedSellers.find((seller) => {
return seller.id === selectedSellerId;
});
- const hasSellers = sellersSelectOptions.length > 0;
+ const hasSellers = savedSellers.length > 0;
return (
<>
@@ -390,12 +123,14 @@ export function SellerManagement({
"block h-8 w-full text-[12px]",
!selectedSellerId && "italic text-gray-700",
)}
- onChange={handleSellerChange}
+ onChange={(event) => {
+ selectParty(event.target.value);
+ }}
value={selectedSellerId}
title={activeSeller?.name}
>
<option value="">No seller selected (default)</option>
- {sellersSelectOptions.map((seller) => {
+ {savedSellers.map((seller) => {
return (
<option key={seller.id} value={seller.id}>
{seller.name}
@@ -453,71 +188,77 @@ export function SellerManagement({
</div>
) : null}
- <CustomTooltip
- side="bottom"
- className={cn(!isLocalStorageAvailable && "bg-red-50")}
- trigger={
- <Button
- variant="default"
- size="sm"
- onClick={() => {
- if (isLocalStorageAvailable) {
- // dismiss any existing toast for better UX
- toast.dismiss();
-
- // open seller dialog
- setIsSellerDialogOpen(true);
- } else {
- toast.error("Unable to add seller", {
- id: "unable-to-add-seller-error-toast",
- closeButton: true,
- description: (
- <>
- <p className="text-pretty text-xs leading-relaxed text-red-700">
- Local storage is not available in your browser. Please
- enable it or try another browser.
- </p>
- </>
- ),
- position: isMobile ? "top-center" : "bottom-right",
- });
- }
- }}
- aria-disabled={!isLocalStorageAvailable} // better UX than 'disabled'
- >
- New Seller
- <Plus className="ml-1 size-3" />
- </Button>
- }
- content={
- isLocalStorageAvailable ? (
- <div className="flex items-center gap-3 p-2">
- <div className="space-y-1">
- <p className="text-sm font-semibold text-slate-900">
- Save Sellers for Quick Access
- </p>
- <p className="text-pretty text-xs leading-relaxed text-slate-700">
- Store multiple sellers to easily reuse their information in
- future invoices. All data is saved locally in your browser.
- </p>
+ <div className="flex gap-2">
+ <CustomTooltip
+ side="bottom"
+ className={cn(!isLocalStorageAvailable && "bg-red-50")}
+ trigger={
+ <Button
+ variant="default"
+ size="sm"
+ onClick={() => {
+ if (isLocalStorageAvailable) {
+ // dismiss any existing toast for better UX
+ toast.dismiss();
+
+ // open seller dialog
+ setIsSellerDialogOpen(true);
+ } else {
+ toast.error("Unable to add seller", {
+ id: "unable-to-add-seller-error-toast",
+ closeButton: true,
+ description: (
+ <>
+ <p className="text-pretty text-xs leading-relaxed text-red-700">
+ Local storage is not available in your browser.
+ Please enable it or try another browser.
+ </p>
+ </>
+ ),
+ position: isMobile ? "top-center" : "bottom-right",
+ });
+ }
+ }}
+ aria-disabled={!isLocalStorageAvailable} // better UX than 'disabled'
+ className="flex-1"
+ >
+ New Seller
+ <Plus className="ml-1 size-3" />
+ </Button>
+ }
+ content={
+ isLocalStorageAvailable ? (
+ <div className="flex items-center gap-3 p-2">
+ <div className="space-y-1">
+ <p className="text-sm font-semibold text-slate-900">
+ Save Sellers for Quick Access
+ </p>
+ <p className="text-pretty text-xs leading-relaxed text-slate-700">
+ Store multiple sellers to easily reuse their information
+ in future invoices. All data is saved locally in your
+ browser.
+ </p>
+ </div>
</div>
- </div>
- ) : (
- <div className="flex items-center gap-3 bg-red-50 p-3">
- <AlertCircleIcon className="h-5 w-5 flex-shrink-0 fill-red-600 text-white" />
- <div className="space-y-1">
- <p className="text-sm font-semibold text-red-800">
- Storage Not Available
- </p>
- <p className="text-pretty text-xs leading-relaxed text-red-700">
- Local storage is not available in your browser. Please
- enable it or try another browser to save seller information.
- </p>
+ ) : (
+ <div className="flex items-center gap-3 bg-red-50 p-3">
+ <AlertCircleIcon className="h-5 w-5 flex-shrink-0 fill-red-600 text-white" />
+ <div className="space-y-1">
+ <p className="text-sm font-semibold text-red-800">
+ Storage Not Available
+ </p>
+ <p className="text-pretty text-xs leading-relaxed text-red-700">
+ Local storage is not available in your browser. Please
+ enable it or try another browser to save seller
+ information.
+ </p>
+ </div>
</div>
- </div>
- )
- }
- />
+ )
+ }
+ />
+ <ContactsBackupMenu isMobile={isMobile} />
+ </div>
</div>
<SellerDialog
@@ -528,8 +269,18 @@ export function SellerManagement({
setIsSellerDialogOpen(false);
setEditingSeller(null);
}}
- handleSellerAdd={handleSellerAdd}
- handleSellerEdit={handleSellerEdit}
+ handleSellerAdd={(newSeller, { shouldApplyNewSellerToInvoice }) => {
+ addParty({
+ partyData: newSeller,
+ shouldApplyToInvoice: shouldApplyNewSellerToInvoice,
+ });
+ }}
+ handleSellerEdit={(editedSeller) => {
+ if (editParty(editedSeller)) {
+ // end edit mode
+ setEditingSeller(null);
+ }
+ }}
initialData={editingSeller}
isEditMode={isEditMode}
formValues={formValues}
@@ -554,7 +305,11 @@ export function SellerManagement({
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
- onClick={handleDeleteSeller}
+ onClick={() => {
+ if (deleteSelectedParty()) {
+ setIsDeleteDialogOpen(false);
+ }
+ }}
className="bg-red-500 text-red-50 hover:bg-red-500/90"
>
Delete
@@ -565,31 +320,3 @@ export function SellerManagement({
</>
);
}
-
-interface ShowSellerStorageErrorToastOptions {
- /** What the user was trying to do, e.g. "Failed to add seller". */
- message: string;
- /** Stable toast id, so repeated failures replace each other instead of stacking. */
- id: string;
- /** Mobile shows toasts at the top, desktop at the bottom right. */
- isMobile: boolean;
-}
-
-/**
- * Tells the user their seller list could not be saved.
- *
- * A rejected write is not an application error — it is a full or disabled store — so it
- * is surfaced to the user and deliberately not reported to Sentry.
- */
-function showSellerStorageErrorToast({
- message,
- id,
- isMobile,
-}: ShowSellerStorageErrorToastOptions) {
- toast.error(message, {
- id,
- description: "Please try again",
- closeButton: true,
- position: isMobile ? "top-center" : "bottom-right",
- });
-}
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/hooks/__tests__/use-party-actions.test.ts b/src/app/(main)/(app)/components/invoice-form/sections/hooks/__tests__/use-party-actions.test.ts
new file mode 100644
index 0000000..9c8122e
--- /dev/null
+++ b/src/app/(main)/(app)/components/invoice-form/sections/hooks/__tests__/use-party-actions.test.ts
@@ -0,0 +1,332 @@
+// @vitest-environment happy-dom
+
+import * as Sentry from "@sentry/nextjs";
+import { act, renderHook } from "@testing-library/react";
+import { toast } from "sonner";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type {
+ Party,
+ PartyData,
+} from "@/app/(main)/(app)/components/invoice-form/sections/hooks/party-config";
+import { usePartyActions } from "@/app/(main)/(app)/components/invoice-form/sections/hooks/use-party-actions";
+import { DEFAULT_BUYER_DATA, DEFAULT_SELLER_DATA } from "@/app/constants";
+import { sellerSchema } from "@/app/schema";
+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
+
+vi.mock("sonner", () => {
+ return { toast: { success: vi.fn(), error: vi.fn() } };
+});
+
+vi.mock("@sentry/nextjs", () => {
+ return { captureException: vi.fn() };
+});
+
+vi.mock("@/lib/umami-analytics-track-event", () => {
+ return { umamiTrackEvent: vi.fn() };
+});
+
+const ACME = sellerSchema.parse({
+ id: "1",
+ name: "Acme",
+ address: "1 Main St",
+});
+
+const INITECH = sellerSchema.parse({
+ id: "2",
+ name: "Initech",
+ address: "2 Side Rd",
+});
+
+const NOW = 1_700_000_000_000;
+
+beforeEach(() => {
+ vi.spyOn(Date, "now").mockReturnValue(NOW);
+ vi.spyOn(console, "error").mockReturnValue(undefined);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+});
+
+interface RenderActionsOptions<P extends Party> {
+ party?: P;
+ savedParties?: PartyData<P>[];
+ selectedId?: string;
+ /** What `saveParties` reports: `false` stands for a rejected storage write. */
+ isSaveSuccessful?: boolean;
+}
+
+function renderActions<P extends Party = "seller">({
+ party = "seller" as P,
+ savedParties = [ACME, INITECH] as PartyData<P>[],
+ selectedId = "",
+ isSaveSuccessful = true,
+}: RenderActionsOptions<P> = {}) {
+ const saveParties = vi.fn(() => {
+ return isSaveSuccessful;
+ });
+ const setSelectedId = vi.fn();
+ const applyToInvoice = vi.fn();
+
+ const { result } = renderHook(() => {
+ return usePartyActions({
+ party,
+ savedParties,
+ saveParties,
+ selectedId,
+ setSelectedId,
+ applyToInvoice,
+ isMobile: false,
+ });
+ });
+
+ return {
+ actions: result.current,
+ saveParties,
+ setSelectedId,
+ applyToInvoice,
+ };
+}
+
+describe("usePartyActions", () => {
+ describe("addParty", () => {
+ const NEW_SELLER = sellerSchema.parse({
+ name: "Umbrella",
+ address: "4 Far Rd",
+ });
+
+ it("saves the new party with an id and puts it on the invoice when asked to", () => {
+ const { actions, saveParties, setSelectedId, applyToInvoice } =
+ renderActions();
+
+ let isAdded = false;
+
+ act(() => {
+ isAdded = actions.addParty({
+ partyData: NEW_SELLER,
+ shouldApplyToInvoice: true,
+ });
+ });
+
+ const savedSeller = { ...NEW_SELLER, id: String(NOW) };
+
+ expect(isAdded).toBe(true);
+ expect(saveParties).toHaveBeenCalledWith([ACME, INITECH, savedSeller]);
+ expect(applyToInvoice).toHaveBeenCalledWith(savedSeller);
+ expect(setSelectedId).toHaveBeenCalledWith(String(NOW));
+ expect(toast.success).toHaveBeenCalledWith(
+ "Seller added and applied to invoice",
+ expect.objectContaining({ id: "add_seller_success_toast" }),
+ );
+ expect(umamiTrackEvent).toHaveBeenCalledWith("add_seller_success");
+ });
+
+ it("only saves the new party when not asked to apply it", () => {
+ const { actions, applyToInvoice, setSelectedId } = renderActions();
+
+ act(() => {
+ actions.addParty({
+ partyData: NEW_SELLER,
+ shouldApplyToInvoice: false,
+ });
+ });
+
+ expect(applyToInvoice).not.toHaveBeenCalled();
+ expect(setSelectedId).not.toHaveBeenCalled();
+ expect(toast.success).toHaveBeenCalledWith(
+ "Seller added successfully",
+ expect.anything(),
+ );
+ });
+
+ it("tells the user and stops when storage rejects the write", () => {
+ const { actions, applyToInvoice } = renderActions({
+ isSaveSuccessful: false,
+ });
+
+ let isAdded = true;
+
+ act(() => {
+ isAdded = actions.addParty({
+ partyData: NEW_SELLER,
+ shouldApplyToInvoice: true,
+ });
+ });
+
+ expect(isAdded).toBe(false);
+ expect(applyToInvoice).not.toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(toast.error).toHaveBeenCalledWith(
+ "Failed to add seller",
+ expect.objectContaining({ id: "add_seller_error_toast" }),
+ );
+ // A full or disabled store is not a bug in the app
+ expect(Sentry.captureException).not.toHaveBeenCalled();
+ expect(umamiTrackEvent).not.toHaveBeenCalled();
+ });
+
+ it("reports an unexpected error and tells the user", () => {
+ const { actions, applyToInvoice } = renderActions();
+
+ applyToInvoice.mockImplementation(() => {
+ throw new Error("form exploded");
+ });
+
+ let isAdded = true;
+
+ act(() => {
+ isAdded = actions.addParty({
+ partyData: NEW_SELLER,
+ shouldApplyToInvoice: true,
+ });
+ });
+
+ expect(isAdded).toBe(false);
+ expect(toast.error).toHaveBeenCalledWith(
+ "Failed to add seller",
+ expect.anything(),
+ );
+ expect(Sentry.captureException).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe("editParty", () => {
+ it("replaces the party with the same id and updates the invoice", () => {
+ const { actions, saveParties, applyToInvoice } = renderActions();
+ const renamed = { ...INITECH, name: "Initech Inc" };
+
+ let isEdited = false;
+
+ act(() => {
+ isEdited = actions.editParty(renamed);
+ });
+
+ expect(isEdited).toBe(true);
+ expect(saveParties).toHaveBeenCalledWith([ACME, renamed]);
+ expect(applyToInvoice).toHaveBeenCalledWith(renamed);
+ expect(toast.success).toHaveBeenCalledWith(
+ "Seller updated successfully",
+ expect.anything(),
+ );
+ expect(umamiTrackEvent).toHaveBeenCalledWith("edit_seller_success");
+ });
+
+ it("keeps the invoice as it is when storage rejects the write", () => {
+ const { actions, applyToInvoice } = renderActions({
+ isSaveSuccessful: false,
+ });
+
+ let isEdited = true;
+
+ act(() => {
+ isEdited = actions.editParty({ ...INITECH, name: "Initech Inc" });
+ });
+
+ expect(isEdited).toBe(false);
+ expect(applyToInvoice).not.toHaveBeenCalled();
+ expect(toast.error).toHaveBeenCalledWith(
+ "Failed to edit seller",
+ expect.anything(),
+ );
+ });
+ });
+
+ describe("deleteSelectedParty", () => {
+ it("removes the selected party and puts the default details back on the invoice", () => {
+ const { actions, saveParties, setSelectedId, applyToInvoice } =
+ renderActions({ selectedId: "1" });
+
+ let isDeleted = false;
+
+ act(() => {
+ isDeleted = actions.deleteSelectedParty();
+ });
+
+ expect(isDeleted).toBe(true);
+ expect(saveParties).toHaveBeenCalledWith([INITECH]);
+ expect(setSelectedId).toHaveBeenCalledWith("");
+ expect(applyToInvoice).toHaveBeenCalledWith(DEFAULT_SELLER_DATA);
+ expect(toast.success).toHaveBeenCalledWith(
+ "Seller deleted successfully",
+ expect.anything(),
+ );
+ expect(umamiTrackEvent).toHaveBeenCalledWith("delete_seller_success");
+ });
+
+ it("keeps the selection when storage rejects the write", () => {
+ const { actions, setSelectedId } = renderActions({
+ selectedId: "1",
+ isSaveSuccessful: false,
+ });
+
+ act(() => {
+ actions.deleteSelectedParty();
+ });
+
+ expect(setSelectedId).not.toHaveBeenCalled();
+ expect(toast.error).toHaveBeenCalledWith(
+ "Failed to delete seller",
+ expect.anything(),
+ );
+ });
+ });
+
+ describe("selectParty", () => {
+ it("puts the picked party on the invoice", () => {
+ const { actions, setSelectedId, applyToInvoice, saveParties } =
+ renderActions();
+
+ act(() => {
+ actions.selectParty("2");
+ });
+
+ expect(setSelectedId).toHaveBeenCalledWith("2");
+ expect(applyToInvoice).toHaveBeenCalledWith(INITECH);
+ expect(toast.success).toHaveBeenCalledWith(
+ 'Seller "Initech" applied to invoice',
+ expect.anything(),
+ );
+ expect(umamiTrackEvent).toHaveBeenCalledWith("change_seller");
+ // Picking a party does not change the saved list
+ expect(saveParties).not.toHaveBeenCalled();
+ });
+
+ it("goes back to the default details for the empty option", () => {
+ const { actions, setSelectedId, applyToInvoice } = renderActions({
+ selectedId: "2",
+ });
+
+ act(() => {
+ actions.selectParty("");
+ });
+
+ expect(setSelectedId).toHaveBeenCalledWith("");
+ expect(applyToInvoice).toHaveBeenCalledWith(DEFAULT_SELLER_DATA);
+ expect(toast.success).toHaveBeenCalledWith(
+ "Seller restored to default",
+ expect.anything(),
+ );
+ });
+ });
+
+ it("words everything for buyers when managing buyers", () => {
+ const { actions, applyToInvoice } = renderActions({
+ party: "buyer",
+ savedParties: [],
+ selectedId: "",
+ });
+
+ act(() => {
+ actions.selectParty("");
+ });
+
+ expect(applyToInvoice).toHaveBeenCalledWith(DEFAULT_BUYER_DATA);
+ expect(toast.success).toHaveBeenCalledWith(
+ "Buyer restored to default",
+ expect.objectContaining({ id: "reset_buyer_success_toast" }),
+ );
+ expect(umamiTrackEvent).toHaveBeenCalledWith("change_buyer");
+ });
+});
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/hooks/__tests__/use-saved-parties.test.ts b/src/app/(main)/(app)/components/invoice-form/sections/hooks/__tests__/use-saved-parties.test.ts
new file mode 100644
index 0000000..ac47b55
--- /dev/null
+++ b/src/app/(main)/(app)/components/invoice-form/sections/hooks/__tests__/use-saved-parties.test.ts
@@ -0,0 +1,226 @@
+// @vitest-environment happy-dom
+
+import * as Sentry from "@sentry/nextjs";
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { SAVED_CONTACTS_IMPORTED_EVENT } from "@/app/(main)/(app)/components/invoice-form/sections/components/contacts-backup-menu";
+import { useSavedParties } from "@/app/(main)/(app)/components/invoice-form/sections/hooks/use-saved-parties";
+import {
+ BUYERS_LOCAL_STORAGE_KEY,
+ SELLERS_LOCAL_STORAGE_KEY,
+ buyerSchema,
+ sellerSchema,
+} from "@/app/schema";
+
+vi.mock("@sentry/nextjs", () => {
+ return { captureException: vi.fn() };
+});
+
+const ACME = sellerSchema.parse({
+ id: "1",
+ name: "Acme",
+ address: "1 Main St",
+});
+
+const INITECH = sellerSchema.parse({
+ id: "2",
+ name: "Initech",
+ address: "2 Side Rd",
+});
+
+const GLOBEX = buyerSchema.parse({
+ id: "3",
+ name: "Globex",
+ address: "3 Other Rd",
+});
+
+beforeEach(() => {
+ localStorage.clear();
+ // The hook logs what it drops; keep the test output readable
+ vi.spyOn(console, "error").mockReturnValue(undefined);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+});
+
+function storeSellers(value: unknown) {
+ localStorage.setItem(
+ SELLERS_LOCAL_STORAGE_KEY,
+ typeof value === "string" ? value : JSON.stringify(value),
+ );
+}
+
+function readStoredSellers(): unknown {
+ return JSON.parse(localStorage.getItem(SELLERS_LOCAL_STORAGE_KEY) ?? "null");
+}
+
+interface RenderSavedSellersOptions {
+ /** The seller id the invoice currently uses. */
+ invoicePartyId?: string;
+}
+
+function renderSavedSellers({
+ invoicePartyId,
+}: RenderSavedSellersOptions = {}) {
+ const setSelectedId = vi.fn();
+
+ const hook = renderHook(() => {
+ return useSavedParties({
+ party: "seller",
+ invoicePartyId,
+ setSelectedId,
+ });
+ });
+
+ return { ...hook, setSelectedId };
+}
+
+describe("useSavedParties", () => {
+ describe("loading", () => {
+ it("reads the saved list and selects nothing when the invoice uses none of it", () => {
+ storeSellers([ACME, INITECH]);
+
+ const { result, setSelectedId } = renderSavedSellers();
+
+ expect(result.current.savedParties).toStrictEqual([ACME, INITECH]);
+ expect(setSelectedId).toHaveBeenLastCalledWith("");
+ });
+
+ it("selects the saved party the invoice already uses", () => {
+ storeSellers([ACME, INITECH]);
+
+ const { setSelectedId } = renderSavedSellers({ invoicePartyId: "2" });
+
+ expect(setSelectedId).toHaveBeenLastCalledWith("2");
+ });
+
+ it("starts empty when nothing is saved", () => {
+ const { result, setSelectedId } = renderSavedSellers();
+
+ expect(result.current.savedParties).toStrictEqual([]);
+ expect(setSelectedId).toHaveBeenLastCalledWith("");
+ });
+
+ it("drops invalid entries, saves the cleaned list back and reports it", () => {
+ storeSellers([ACME, { name: "" }, "not a seller"]);
+
+ const { result } = renderSavedSellers();
+
+ expect(result.current.savedParties).toStrictEqual([ACME]);
+ expect(readStoredSellers()).toStrictEqual([ACME]);
+ expect(Sentry.captureException).toHaveBeenCalledTimes(1);
+ });
+
+ it("leaves a stored value that is not JSON alone and shows an empty list", () => {
+ storeSellers("[{ truncated");
+
+ const { result, setSelectedId } = renderSavedSellers();
+
+ expect(result.current.savedParties).toStrictEqual([]);
+ expect(setSelectedId).not.toHaveBeenCalled();
+ expect(localStorage.getItem(SELLERS_LOCAL_STORAGE_KEY)).toBe(
+ "[{ truncated",
+ );
+ expect(Sentry.captureException).toHaveBeenCalledTimes(1);
+ });
+
+ it("reads the buyers list for buyers", () => {
+ storeSellers([ACME]);
+ localStorage.setItem(BUYERS_LOCAL_STORAGE_KEY, JSON.stringify([GLOBEX]));
+
+ const { result } = renderHook(() => {
+ return useSavedParties({
+ party: "buyer",
+ invoicePartyId: undefined,
+ setSelectedId: vi.fn(),
+ });
+ });
+
+ expect(result.current.savedParties).toStrictEqual([GLOBEX]);
+ });
+ });
+
+ it("does not loop when given a new setSelectedId on every render", () => {
+ storeSellers([ACME]);
+
+ const { result } = renderHook(() => {
+ return useSavedParties({
+ party: "seller",
+ invoicePartyId: "1",
+ // A fresh function per render, as an inline callback would be
+ setSelectedId: vi.fn(),
+ });
+ });
+
+ expect(result.current.savedParties).toStrictEqual([ACME]);
+ });
+
+ describe("after a backup import", () => {
+ it("reloads the list", () => {
+ storeSellers([ACME]);
+
+ const { result } = renderSavedSellers();
+
+ storeSellers([ACME, INITECH]);
+
+ act(() => {
+ window.dispatchEvent(new Event(SAVED_CONTACTS_IMPORTED_EVENT));
+ });
+
+ expect(result.current.savedParties).toStrictEqual([ACME, INITECH]);
+ });
+
+ it("stops listening once unmounted", () => {
+ const removeEventListener = vi.spyOn(window, "removeEventListener");
+
+ const { unmount } = renderSavedSellers();
+
+ unmount();
+
+ expect(removeEventListener).toHaveBeenCalledWith(
+ SAVED_CONTACTS_IMPORTED_EVENT,
+ expect.any(Function),
+ );
+ });
+ });
+
+ describe("saveParties", () => {
+ it("writes the new list to storage and to state", () => {
+ storeSellers([ACME]);
+
+ const { result } = renderSavedSellers();
+
+ let isSaved = false;
+
+ act(() => {
+ isSaved = result.current.saveParties([ACME, INITECH]);
+ });
+
+ expect(isSaved).toBe(true);
+ expect(result.current.savedParties).toStrictEqual([ACME, INITECH]);
+ expect(readStoredSellers()).toStrictEqual([ACME, INITECH]);
+ });
+
+ it("changes nothing when storage rejects the write", () => {
+ storeSellers([ACME]);
+
+ const { result } = renderSavedSellers();
+
+ vi.spyOn(localStorage, "setItem").mockImplementation(() => {
+ throw new DOMException("Quota exceeded", "QuotaExceededError");
+ });
+
+ let isSaved = true;
+
+ act(() => {
+ isSaved = result.current.saveParties([ACME, INITECH]);
+ });
+
+ expect(isSaved).toBe(false);
+ expect(result.current.savedParties).toStrictEqual([ACME]);
+ });
+ });
+});
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/hooks/party-config.ts b/src/app/(main)/(app)/components/invoice-form/sections/hooks/party-config.ts
new file mode 100644
index 0000000..ecf78b9
--- /dev/null
+++ b/src/app/(main)/(app)/components/invoice-form/sections/hooks/party-config.ts
@@ -0,0 +1,51 @@
+import type { z } from "zod";
+
+import { DEFAULT_BUYER_DATA, DEFAULT_SELLER_DATA } from "@/app/constants";
+import {
+ BUYERS_LOCAL_STORAGE_KEY,
+ SELLERS_LOCAL_STORAGE_KEY,
+ buyerSchema,
+ sellerSchema,
+ type BuyerData,
+ type LocalStorageKey,
+ type SellerData,
+} from "@/app/schema";
+
+/**
+ * The two sides of an invoice. Sellers and buyers are saved, listed, edited and deleted
+ * the same way; everything that differs between them is in {@link PARTY_CONFIG}.
+ */
+export type Party = "seller" | "buyer";
+
+interface PartyDataMap {
+ seller: SellerData;
+ buyer: BuyerData;
+}
+
+export type PartyData<P extends Party> = PartyDataMap[P];
+
+interface PartyConfig<P extends Party> {
+ /** Capitalized name, as used in toasts: "Seller added successfully". */
+ label: string;
+ /** Where the saved list lives in `localStorage`. */
+ storageKey: LocalStorageKey;
+ /** Every saved entry must pass it; entries that do not are dropped on load. */
+ schema: z.ZodType<PartyData<P>>;
+ /** What the invoice shows when no saved party is selected. */
+ defaultData: PartyData<P>;
+}
+
+export const PARTY_CONFIG: { [P in Party]: PartyConfig<P> } = {
+ seller: {
+ label: "Seller",
+ storageKey: SELLERS_LOCAL_STORAGE_KEY,
+ schema: sellerSchema,
+ defaultData: DEFAULT_SELLER_DATA,
+ },
+ buyer: {
+ label: "Buyer",
+ storageKey: BUYERS_LOCAL_STORAGE_KEY,
+ schema: buyerSchema,
+ defaultData: DEFAULT_BUYER_DATA,
+ },
+};
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/hooks/use-party-actions.ts b/src/app/(main)/(app)/components/invoice-form/sections/hooks/use-party-actions.ts
new file mode 100644
index 0000000..2fa2c50
--- /dev/null
+++ b/src/app/(main)/(app)/components/invoice-form/sections/hooks/use-party-actions.ts
@@ -0,0 +1,209 @@
+import * as Sentry from "@sentry/nextjs";
+import { toast } from "sonner";
+
+import {
+ PARTY_CONFIG,
+ type Party,
+ type PartyData,
+} from "@/app/(main)/(app)/components/invoice-form/sections/hooks/party-config";
+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
+
+interface UsePartyActionsOptions<P extends Party> {
+ /** Which list the actions work on: the saved sellers or the saved buyers. */
+ party: P;
+ /** The saved list, from `useSavedParties`. */
+ savedParties: PartyData<P>[];
+ /** Persists a new version of the saved list, from `useSavedParties`. */
+ saveParties: (parties: PartyData<P>[]) => boolean;
+ /** The id of the party selected in the dropdown; `""` when none is. */
+ selectedId: string;
+ /** Selects a saved party in the dropdown by id; `""` selects none. */
+ setSelectedId: (id: string) => void;
+ /** Puts a party's details on the invoice (the seller or buyer section of the form). */
+ applyToInvoice: (partyData: PartyData<P>) => void;
+ /** Mobile shows toasts at the top, desktop at the bottom right. */
+ isMobile: boolean;
+}
+
+interface AddPartyOptions<P extends Party> {
+ /** The details entered in the "New Seller" / "New Buyer" dialog. */
+ partyData: PartyData<P>;
+ /** Whether to also put the new party on the invoice right away. */
+ shouldApplyToInvoice: boolean;
+}
+
+/**
+ * What the user can do with saved sellers or buyers: add, edit, pick one for the invoice,
+ * and delete the selected one.
+ *
+ * Every change is saved to storage first. If that fails, nothing else happens and the
+ * user is told, rather than shown a change the next page load would undo. Each action
+ * ends with a toast and an analytics event.
+ */
+export function usePartyActions<P extends Party>({
+ party,
+ savedParties,
+ saveParties,
+ selectedId,
+ setSelectedId,
+ applyToInvoice,
+ isMobile,
+}: UsePartyActionsOptions<P>) {
+ const { label, defaultData } = PARTY_CONFIG[party];
+ const position = isMobile ? "top-center" : "bottom-right";
+
+ /**
+ * Saves `nextParties`, then runs `onSaved` for the rest of the action.
+ *
+ * @returns whether the action went through.
+ */
+ const commit = ({
+ action,
+ nextParties,
+ onSaved,
+ }: CommitOptions<P>): boolean => {
+ const failureMessage = `Failed to ${action} ${party}`;
+
+ try {
+ if (!saveParties(nextParties)) {
+ // A full or disabled store, not an application error, so not sent to Sentry
+ toast.error(failureMessage, {
+ id: `${action}_${party}_error_toast`,
+ description: "Please try again",
+ closeButton: true,
+ position,
+ });
+
+ return false;
+ }
+
+ onSaved();
+ umamiTrackEvent(`${action}_${party}_success`);
+
+ return true;
+ } catch (error) {
+ console.error(`${failureMessage}:`, error);
+
+ toast.error(failureMessage, {
+ id: `${action}_${party}_error_toast`,
+ description: "Please try again",
+ closeButton: true,
+ position,
+ });
+
+ Sentry.captureException(error);
+
+ return false;
+ }
+ };
+
+ const addParty = ({
+ partyData,
+ shouldApplyToInvoice,
+ }: AddPartyOptions<P>) => {
+ // The id is what the dropdown, edit and delete go by (IMPORTANT!)
+ const newParty = { ...partyData, id: Date.now().toString() };
+
+ return commit({
+ action: "add",
+ nextParties: [...savedParties, newParty],
+ onSaved: () => {
+ if (shouldApplyToInvoice) {
+ applyToInvoice(newParty);
+ setSelectedId(newParty.id);
+ }
+
+ toast.success(
+ shouldApplyToInvoice
+ ? `${label} added and applied to invoice`
+ : `${label} added successfully`,
+ { id: `add_${party}_success_toast`, richColors: true, position },
+ );
+ },
+ });
+ };
+
+ const editParty = (editedParty: PartyData<P>) => {
+ return commit({
+ action: "edit",
+ nextParties: savedParties.map((savedParty) => {
+ return savedParty.id === editedParty.id ? editedParty : savedParty;
+ }),
+ onSaved: () => {
+ applyToInvoice(editedParty);
+
+ toast.success(`${label} updated successfully`, {
+ id: `edit_${party}_success_toast`,
+ richColors: true,
+ position,
+ });
+ },
+ });
+ };
+
+ const deleteSelectedParty = () => {
+ return commit({
+ action: "delete",
+ nextParties: savedParties.filter((savedParty) => {
+ return savedParty.id !== selectedId;
+ }),
+ onSaved: () => {
+ setSelectedId("");
+ applyToInvoice(defaultData);
+
+ toast.success(`${label} deleted successfully`, {
+ id: `delete_${party}_success_toast`,
+ richColors: true,
+ position,
+ });
+ },
+ });
+ };
+
+ /** Picks a saved party for the invoice; `""` goes back to the default details. */
+ const selectParty = (id: string) => {
+ umamiTrackEvent(`change_${party}`);
+
+ if (!id) {
+ setSelectedId("");
+ applyToInvoice(defaultData);
+
+ toast.success(`${label} restored to default`, {
+ id: `reset_${party}_success_toast`,
+ richColors: true,
+ position,
+ });
+
+ return;
+ }
+
+ setSelectedId(id);
+
+ const selectedParty = savedParties.find((savedParty) => {
+ return savedParty.id === id;
+ });
+
+ if (!selectedParty) {
+ return;
+ }
+
+ applyToInvoice(selectedParty);
+
+ toast.success(`${label} "${selectedParty.name}" applied to invoice`, {
+ id: `change_${party}_success_toast`,
+ richColors: true,
+ position,
+ });
+ };
+
+ return { addParty, editParty, deleteSelectedParty, selectParty };
+}
+
+interface CommitOptions<P extends Party> {
+ /** Names the action in toasts and analytics: "Failed to add seller", `add_seller_success`. */
+ action: "add" | "edit" | "delete";
+ /** The saved list as it should be after the action. */
+ nextParties: PartyData<P>[];
+ /** The rest of the action, run only once the list is saved. */
+ onSaved: () => void;
+}
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/hooks/use-saved-parties.ts b/src/app/(main)/(app)/components/invoice-form/sections/hooks/use-saved-parties.ts
new file mode 100644
index 0000000..ae21200
--- /dev/null
+++ b/src/app/(main)/(app)/components/invoice-form/sections/hooks/use-saved-parties.ts
@@ -0,0 +1,166 @@
+import * as Sentry from "@sentry/nextjs";
+import { useEffect, useEffectEvent, useState } from "react";
+
+import { SAVED_CONTACTS_IMPORTED_EVENT } from "@/app/(main)/(app)/components/invoice-form/sections/components/contacts-backup-menu";
+import {
+ PARTY_CONFIG,
+ type Party,
+ type PartyData,
+} from "@/app/(main)/(app)/components/invoice-form/sections/hooks/party-config";
+import {
+ getAppStorageItem,
+ setAppStorageItem,
+} from "@/app/(main)/(app)/utils/app-local-storage";
+
+interface UseSavedPartiesOptions<P extends Party> {
+ /** Which list to manage: the saved sellers or the saved buyers. */
+ party: P;
+ /**
+ * The id of the party the invoice currently uses. When it is one of the saved ones, it
+ * is selected in the dropdown after the list loads.
+ */
+ invoicePartyId: string | undefined;
+ /** Selects a saved party in the dropdown by id; `""` selects none. */
+ setSelectedId: (id: string) => void;
+}
+
+interface UseSavedPartiesResult<P extends Party> {
+ /** The saved sellers or buyers, in the order they were added. */
+ savedParties: PartyData<P>[];
+ /**
+ * Replaces the saved list, in storage first and in state only if that worked.
+ *
+ * @returns `false` when storage rejected the write (full or unavailable), in which
+ * case nothing changed.
+ */
+ saveParties: (parties: PartyData<P>[]) => boolean;
+}
+
+/**
+ * The saved sellers or buyers, kept in sync with `localStorage`.
+ *
+ * Reads the list when the component mounts, when the invoice switches to a different
+ * party, and after a backup import has added to it.
+ */
+export function useSavedParties<P extends Party>({
+ party,
+ invoicePartyId,
+ setSelectedId,
+}: UseSavedPartiesOptions<P>): UseSavedPartiesResult<P> {
+ const [savedParties, setSavedParties] = useState<PartyData<P>[]>([]);
+
+ // An effect event, so `setSelectedId` can be any callback, even a new one per render,
+ // without re-running the effect below (which would set state and render again, forever)
+ const showLoadedParties = useEffectEvent(
+ ({ parties, selectedPartyId }: ShowLoadedPartiesOptions<P>) => {
+ const selectedParty = parties.find((savedParty) => {
+ return savedParty.id === selectedPartyId;
+ });
+
+ setSavedParties(parties);
+ setSelectedId(selectedParty?.id ?? "");
+ },
+ );
+
+ useEffect(() => {
+ const reload = () => {
+ const parties = loadSavedParties(party);
+
+ // Storage could not be read at all: keep what is on screen
+ if (parties) {
+ showLoadedParties({ parties, selectedPartyId: invoicePartyId });
+ }
+ };
+
+ reload();
+
+ window.addEventListener(SAVED_CONTACTS_IMPORTED_EVENT, reload);
+
+ return () => {
+ window.removeEventListener(SAVED_CONTACTS_IMPORTED_EVENT, reload);
+ };
+ }, [party, invoicePartyId]);
+
+ const saveParties = (parties: PartyData<P>[]) => {
+ const isPersisted = setAppStorageItem({
+ key: PARTY_CONFIG[party].storageKey,
+ value: JSON.stringify(parties),
+ });
+
+ if (isPersisted) {
+ setSavedParties(parties);
+ }
+
+ return isPersisted;
+ };
+
+ return { savedParties, saveParties };
+}
+
+interface ShowLoadedPartiesOptions<P extends Party> {
+ /** The list as just read from storage. */
+ parties: PartyData<P>[];
+ /** The party to select if it is in the list: the one the invoice uses. */
+ selectedPartyId: string | undefined;
+}
+
+/**
+ * Reads the saved list and keeps only the entries that pass the schema.
+ *
+ * Invalid entries are dropped for good: the cleaned list is written back and the drop is
+ * reported to Sentry, since the app itself should never have saved them.
+ *
+ * @returns `null` when the stored value is not JSON, so the caller can leave the list
+ * as it is instead of showing it as empty.
+ */
+function loadSavedParties<P extends Party>(party: P): PartyData<P>[] | null {
+ const { storageKey, schema } = PARTY_CONFIG[party];
+ const logPrefix = `[${party}-management]`;
+
+ let stored: unknown;
+
+ try {
+ const saved = getAppStorageItem(storageKey);
+ stored = saved ? JSON.parse(saved) : [];
+ } catch (error) {
+ console.error(`${logPrefix} Failed to load saved ${party}s:`, error);
+ Sentry.captureException(error);
+
+ return null;
+ }
+
+ const entries = Array.isArray(stored) ? stored : [];
+ const validParties: PartyData<P>[] = [];
+ const invalidEntries: unknown[] = [];
+
+ for (const entry of entries) {
+ const result = schema.safeParse(entry);
+
+ if (result.success) {
+ validParties.push(result.data);
+ } else {
+ invalidEntries.push(entry);
+ console.error(`${logPrefix} Invalid ${party} entry:`, result.error);
+ }
+ }
+
+ if (invalidEntries.length > 0) {
+ console.error(
+ `${logPrefix} Dropped ${invalidEntries.length} invalid ${party} entries:`,
+ invalidEntries,
+ );
+
+ Sentry.captureException(
+ new Error(
+ `${logPrefix} Invalid ${party} data in localStorage: ${invalidEntries.length} items dropped`,
+ ),
+ );
+
+ setAppStorageItem({
+ key: storageKey,
+ value: JSON.stringify(validParties),
+ });
+ }
+
+ return validParties;
+}
diff --git a/src/app/(main)/(app)/utils/__tests__/contacts-backup.test.ts b/src/app/(main)/(app)/utils/__tests__/contacts-backup.test.ts
new file mode 100644
index 0000000..a593487
--- /dev/null
+++ b/src/app/(main)/(app)/utils/__tests__/contacts-backup.test.ts
@@ -0,0 +1,435 @@
+import { assert, describe, expect, it } from "vitest";
+
+import {
+ buildContactsBackupFileName,
+ describeContactCounts,
+ mergeImportedContacts,
+ parseContactsBackup,
+ serializeContactsBackup,
+} from "@/app/(main)/(app)/utils/contacts-backup";
+import {
+ buyerSchema,
+ sellerSchema,
+ type BuyerData,
+ type SellerData,
+} from "@/app/schema";
+
+const SELLER = sellerSchema.parse({
+ id: "1700000000000",
+ name: "Acme Ltd",
+ address: "1 Main Street\nSpringfield",
+ vatNo: "PL1234567890",
+ email: "[email protected]",
+ accountNumber: "PL61 1090 1014 0000 0712 1981 2874",
+ swiftBic: "WBKPPLPP",
+ swiftBicFieldIsVisible: false,
+});
+
+const BUYER = buyerSchema.parse({
+ id: "1700000000001",
+ name: "Globex",
+ address: "2 Side Road",
+ vatNoLabelText: "Tax ID",
+ notesFieldIsVisible: false,
+});
+
+const EXPORTED_AT = new Date("2026-09-26T10:00:00.000Z");
+
+let nextId = 0;
+
+function createId() {
+ nextId += 1;
+
+ return `generated-${nextId}`;
+}
+
+interface BackupFileOptions {
+ sellers?: unknown[];
+ buyers?: unknown[];
+}
+
+function backupFile({ sellers = [], buyers = [] }: BackupFileOptions) {
+ return JSON.stringify({ app: "easyinvoicepdf", version: 1, sellers, buyers });
+}
+
+describe("serializeContactsBackup", () => {
+ it("leaves out visible flags and keeps hidden ones", () => {
+ const backup = JSON.parse(
+ serializeContactsBackup({
+ sellers: [SELLER],
+ buyers: [BUYER],
+ exportedAt: EXPORTED_AT,
+ }),
+ ) as { sellers: unknown[]; buyers: unknown[] };
+
+ expect(backup).toMatchObject({
+ app: "easyinvoicepdf",
+ version: 1,
+ exportedAt: "2026-09-26T10:00:00.000Z",
+ });
+
+ expect(backup.sellers[0]).toStrictEqual({
+ id: "1700000000000",
+ name: "Acme Ltd",
+ address: "1 Main Street\nSpringfield",
+ vatNo: "PL1234567890",
+ vatNoLabelText: "VAT no",
+ email: "[email protected]",
+ accountNumber: "PL61 1090 1014 0000 0712 1981 2874",
+ swiftBic: "WBKPPLPP",
+ swiftBicFieldIsVisible: false,
+ });
+
+ expect(backup.buyers[0]).toStrictEqual({
+ id: "1700000000001",
+ name: "Globex",
+ address: "2 Side Road",
+ vatNoLabelText: "Tax ID",
+ notesFieldIsVisible: false,
+ });
+ });
+
+ it("round trips through parse and merge without losing anything", () => {
+ const text = serializeContactsBackup({
+ sellers: [SELLER],
+ buyers: [BUYER],
+ exportedAt: EXPORTED_AT,
+ });
+
+ const parsed = parseContactsBackup(text);
+
+ assert(parsed.success, "the backup should parse");
+
+ const sellers = mergeImportedContacts({
+ existing: [],
+ imported: parsed.sellers,
+ schema: sellerSchema,
+ contactNoun: "seller",
+ createId,
+ });
+ const buyers = mergeImportedContacts({
+ existing: [],
+ imported: parsed.buyers,
+ schema: buyerSchema,
+ contactNoun: "buyer",
+ createId,
+ });
+
+ expect(sellers.contacts).toStrictEqual([SELLER]);
+ expect(buyers.contacts).toStrictEqual([BUYER]);
+ });
+
+ it.each([
+ ["seller", sellerSchema.shape],
+ ["buyer", buyerSchema.shape],
+ ] as const)(
+ "is only lossless while every %s visibility flag defaults to true",
+ (_party, shape) => {
+ const visibilityFlags = Object.entries(shape).filter(([key]) => {
+ return key.endsWith("FieldIsVisible");
+ });
+
+ expect(visibilityFlags.length).toBeGreaterThan(0);
+
+ for (const [key, flagSchema] of visibilityFlags) {
+ expect({ key, default: flagSchema.parse(undefined) }).toStrictEqual({
+ key,
+ default: true,
+ });
+ }
+ },
+ );
+});
+
+describe("buildContactsBackupFileName", () => {
+ it("dates the file", () => {
+ expect(buildContactsBackupFileName(new Date(2026, 8, 26, 23, 59))).toBe(
+ "easyinvoicepdf-contacts-2026-09-26.json",
+ );
+ });
+});
+
+describe("parseContactsBackup", () => {
+ it.each([
+ ["text that is not JSON", "not json {"],
+ ["an array", "[]"],
+ ["another app's JSON", JSON.stringify({ app: "other", version: 1 })],
+ [
+ "a version that is not a number",
+ JSON.stringify({ app: "easyinvoicepdf", version: "1" }),
+ ],
+ [
+ "a list that is not an array",
+ JSON.stringify({ app: "easyinvoicepdf", version: 1, sellers: {} }),
+ ],
+ ])("rejects %s", (_description, text) => {
+ expect(parseContactsBackup(text)).toStrictEqual({
+ success: false,
+ error: "This file is not an EasyInvoicePDF sellers & buyers backup.",
+ });
+ });
+
+ it("rejects a backup from a newer version", () => {
+ const result = parseContactsBackup(
+ JSON.stringify({ app: "easyinvoicepdf", version: 2, sellers: [SELLER] }),
+ );
+
+ expect(result).toStrictEqual({
+ success: false,
+ error:
+ "This backup was made by a newer version of EasyInvoicePDF. Reload the page and try again.",
+ });
+ });
+
+ it("rejects a backup with nothing in it", () => {
+ expect(parseContactsBackup(backupFile({}))).toStrictEqual({
+ success: false,
+ error: "This backup has no sellers or buyers in it.",
+ });
+ });
+
+ it("accepts a backup with only one of the two lists", () => {
+ const result = parseContactsBackup(
+ JSON.stringify({ app: "easyinvoicepdf", version: 1, buyers: [BUYER] }),
+ );
+
+ expect(result).toStrictEqual({
+ success: true,
+ sellers: [],
+ buyers: [BUYER],
+ });
+ });
+});
+
+describe("mergeImportedContacts", () => {
+ it("adds new entries after the existing ones", () => {
+ const newSeller = { ...SELLER, id: "2", name: "Initech" };
+
+ const result = mergeImportedContacts({
+ existing: [SELLER],
+ imported: [newSeller],
+ schema: sellerSchema,
+ contactNoun: "seller",
+ createId,
+ });
+
+ expect(result).toStrictEqual({
+ contacts: [SELLER, newSeller],
+ added: [newSeller],
+ duplicates: [],
+ invalidEntries: [],
+ nameConflicts: [],
+ });
+ });
+
+ it("keeps the saved entry when an imported one has the same id", () => {
+ const editedHere = { ...SELLER, name: "Acme Ltd (renamed)" };
+
+ const result = mergeImportedContacts({
+ existing: [editedHere],
+ imported: [SELLER],
+ schema: sellerSchema,
+ contactNoun: "seller",
+ createId,
+ });
+
+ expect(result.contacts).toStrictEqual([editedHere]);
+ expect(result.duplicates).toHaveLength(1);
+ });
+
+ it("skips an entry with the same details under a different id", () => {
+ const result = mergeImportedContacts({
+ existing: [SELLER],
+ imported: [{ ...SELLER, id: "saved-in-another-browser" }],
+ schema: sellerSchema,
+ contactNoun: "seller",
+ createId,
+ });
+
+ expect(result.contacts).toStrictEqual([SELLER]);
+ expect(result.duplicates).toHaveLength(1);
+ });
+
+ it("compares details after defaults and trimming are applied", () => {
+ const result = mergeImportedContacts<BuyerData>({
+ existing: [{ ...BUYER, vatNoLabelText: "VAT no" }],
+ imported: [
+ {
+ ...BUYER,
+ id: undefined,
+ vatNoLabelText: undefined,
+ name: " Globex ",
+ },
+ ],
+ schema: buyerSchema,
+ contactNoun: "buyer",
+ createId,
+ });
+
+ expect(result.added).toStrictEqual([]);
+ expect(result.duplicates).toHaveLength(1);
+ });
+
+ it("skips duplicates within the file itself", () => {
+ const result = mergeImportedContacts({
+ existing: [],
+ imported: [SELLER, SELLER, { ...SELLER, id: undefined }],
+ schema: sellerSchema,
+ contactNoun: "seller",
+ createId,
+ });
+
+ expect(result.contacts).toStrictEqual([SELLER]);
+ expect(result.added).toHaveLength(1);
+ expect(result.duplicates).toHaveLength(2);
+ });
+
+ it("gives an entry without an id a new one", () => {
+ const result = mergeImportedContacts<BuyerData>({
+ existing: [],
+ imported: [{ ...BUYER, id: undefined }],
+ schema: buyerSchema,
+ contactNoun: "buyer",
+ createId: () => {
+ return "fresh-id";
+ },
+ });
+
+ expect(result.contacts).toStrictEqual([{ ...BUYER, id: "fresh-id" }]);
+ });
+
+ it("does not add a different contact under a name that is already saved", () => {
+ const sameNameElsewhere = {
+ ...SELLER,
+ id: "2",
+ address: "5 New Road",
+ };
+
+ const result = mergeImportedContacts({
+ existing: [SELLER],
+ imported: [sameNameElsewhere],
+ schema: sellerSchema,
+ contactNoun: "seller",
+ createId,
+ });
+
+ expect(result).toStrictEqual({
+ contacts: [SELLER],
+ added: [],
+ duplicates: [],
+ invalidEntries: [],
+ nameConflicts: [
+ {
+ label: "Acme Ltd",
+ entry: sameNameElsewhere,
+ issues: [
+ {
+ field: "name",
+ message: "A seller with this name is already saved",
+ },
+ ],
+ },
+ ],
+ });
+ });
+
+ it("compares names the way the add dialog does: trimmed, case-sensitive", () => {
+ const result = mergeImportedContacts<SellerData>({
+ existing: [SELLER],
+ imported: [
+ { ...SELLER, id: "2", name: " Acme Ltd ", address: "Elsewhere" },
+ { ...SELLER, id: "3", name: "ACME LTD", address: "Elsewhere" },
+ ],
+ schema: sellerSchema,
+ contactNoun: "seller",
+ createId,
+ });
+
+ expect(result.nameConflicts).toHaveLength(1);
+ expect(result.added).toHaveLength(1);
+ });
+
+ it("adds only the first of two different contacts sharing a name in the file", () => {
+ const base = { ...BUYER, id: undefined };
+
+ const result = mergeImportedContacts<BuyerData>({
+ existing: [],
+ imported: [
+ { ...base, address: "Road 1" },
+ { ...base, address: "Road 2" },
+ ],
+ schema: buyerSchema,
+ contactNoun: "buyer",
+ createId,
+ });
+
+ expect(result.added).toHaveLength(1);
+ expect(result.contacts[0]?.address).toBe("Road 1");
+ expect(result.nameConflicts[0]?.issues).toStrictEqual([
+ { field: "name", message: "A buyer with this name is already saved" },
+ ]);
+ });
+
+ it("imports the valid entries and reports the invalid ones", () => {
+ const result = mergeImportedContacts<SellerData>({
+ existing: [],
+ imported: [
+ { ...SELLER, email: "not-an-email" },
+ SELLER,
+ { address: "No name" },
+ "not even an object",
+ ],
+ schema: sellerSchema,
+ contactNoun: "seller",
+ createId,
+ });
+
+ expect(result.contacts).toStrictEqual([SELLER]);
+ expect(result.invalidEntries).toStrictEqual([
+ {
+ label: "Acme Ltd",
+ entry: { ...SELLER, email: "not-an-email" },
+ issues: [{ field: "email", message: "Invalid email address" }],
+ },
+ {
+ label: "Entry #3",
+ entry: { address: "No name" },
+ issues: [{ field: "name", message: "Required" }],
+ },
+ {
+ label: "Entry #4",
+ entry: "not even an object",
+ issues: [
+ { message: "Invalid input: expected object, received string" },
+ ],
+ },
+ ]);
+ });
+
+ it("reports every problem with an entry, not just the first", () => {
+ const result = mergeImportedContacts<BuyerData>({
+ existing: [],
+ imported: [{ email: "nope", notes: 42 }],
+ schema: buyerSchema,
+ contactNoun: "buyer",
+ createId,
+ });
+
+ expect(
+ result.invalidEntries[0]?.issues.map(({ field }) => {
+ return field;
+ }),
+ ).toStrictEqual(["name", "address", "email", "notes"]);
+ });
+});
+
+describe("describeContactCounts", () => {
+ it("names only the lists that have any", () => {
+ expect(describeContactCounts({ sellerCount: 0, buyerCount: 1 })).toBe(
+ "1 buyer",
+ );
+ expect(describeContactCounts({ sellerCount: 2, buyerCount: 1 })).toBe(
+ "2 sellers and 1 buyer",
+ );
+ });
+});
diff --git a/src/app/(main)/(app)/utils/contacts-backup.ts b/src/app/(main)/(app)/utils/contacts-backup.ts
new file mode 100644
index 0000000..62b89cc
--- /dev/null
+++ b/src/app/(main)/(app)/utils/contacts-backup.ts
@@ -0,0 +1,405 @@
+import dayjs from "dayjs";
+import { z } from "zod";
+
+import type { BuyerData, SellerData } from "@/app/schema";
+
+/**
+ * Identifies a file as ours, so importing some unrelated JSON fails with a clear message
+ * instead of a list of "invalid entries".
+ */
+const CONTACTS_BACKUP_APP_ID = "easyinvoicepdf";
+
+/**
+ * Bump when the file shape changes in a way an older app cannot read, and teach
+ * {@link parseContactsBackup} to upgrade the previous versions.
+ */
+const CONTACTS_BACKUP_VERSION = 1;
+
+/**
+ * Upper bound for an imported file. A backup of a few hundred sellers and buyers is tens
+ * of kilobytes, and `localStorage` caps out around 5 MB anyway.
+ */
+export const MAX_CONTACTS_BACKUP_FILE_BYTES = 1_000_000;
+
+/**
+ * Only the envelope is checked here. Entries are kept as `unknown` and validated one by
+ * one while merging, so one bad entry does not throw away the rest of the file.
+ */
+const contactsBackupSchema = z.object({
+ app: z.literal(CONTACTS_BACKUP_APP_ID),
+ version: z.number().int().positive(),
+ sellers: z.array(z.unknown()).default([]),
+ buyers: z.array(z.unknown()).default([]),
+});
+
+const NOT_A_BACKUP_ERROR =
+ "This file is not an EasyInvoicePDF sellers & buyers backup.";
+
+interface SerializeContactsBackupOptions {
+ /** Saved sellers, as read from `localStorage`. */
+ sellers: SellerData[];
+ /** Saved buyers, as read from `localStorage`. */
+ buyers: BuyerData[];
+ /** When the backup was made, recorded in the file for the user's benefit. */
+ exportedAt: Date;
+}
+
+/**
+ * Turns the saved sellers and buyers into the contents of a backup file.
+ *
+ * Visibility flags that are `true` are left out: that is their schema default, so they
+ * come back on import, and the file stays readable. Hidden (`false`) flags are kept, so
+ * a field someone chose to hide stays hidden after a restore.
+ */
+export function serializeContactsBackup({
+ sellers,
+ buyers,
+ exportedAt,
+}: SerializeContactsBackupOptions): string {
+ const backup = {
+ app: CONTACTS_BACKUP_APP_ID,
+ version: CONTACTS_BACKUP_VERSION,
+ exportedAt: exportedAt.toISOString(),
+ sellers: sellers.map((seller) => {
+ return omitDefaultVisibilityFlags(seller);
+ }),
+ buyers: buyers.map((buyer) => {
+ return omitDefaultVisibilityFlags(buyer);
+ }),
+ };
+
+ return JSON.stringify(backup, null, 2);
+}
+
+/**
+ * `easyinvoicepdf-contacts-2026-09-26.json`, dated in the user's local time zone.
+ */
+export function buildContactsBackupFileName(date: Date): string {
+ return `${CONTACTS_BACKUP_APP_ID}-contacts-${dayjs(date).format("YYYY-MM-DD")}.json`;
+}
+
+type ParseContactsBackupResult =
+ | {
+ success: true;
+ /** Raw seller entries, still to be validated by {@link mergeImportedContacts}. */
+ sellers: unknown[];
+ /** Raw buyer entries, still to be validated by {@link mergeImportedContacts}. */
+ buyers: unknown[];
+ }
+ | {
+ success: false;
+ /** A user-facing explanation of why the file cannot be imported. */
+ error: string;
+ };
+
+/**
+ * Reads the text of an uploaded backup file and checks it is one of ours.
+ */
+export function parseContactsBackup(text: string): ParseContactsBackupResult {
+ let json: unknown;
+
+ try {
+ json = JSON.parse(text);
+ } catch {
+ return { success: false, error: NOT_A_BACKUP_ERROR };
+ }
+
+ const result = contactsBackupSchema.safeParse(json);
+
+ if (!result.success) {
+ return { success: false, error: NOT_A_BACKUP_ERROR };
+ }
+
+ const { version, sellers, buyers } = result.data;
+
+ if (version > CONTACTS_BACKUP_VERSION) {
+ return {
+ success: false,
+ error:
+ "This backup was made by a newer version of EasyInvoicePDF. Reload the page and try again.",
+ };
+ }
+
+ if (sellers.length === 0 && buyers.length === 0) {
+ return {
+ success: false,
+ error: "This backup has no sellers or buyers in it.",
+ };
+ }
+
+ return { success: true, sellers, buyers };
+}
+
+/** A saved seller or buyer: all the merge needs is an id and a name. */
+interface SavedContact {
+ id?: string;
+ name: string;
+}
+
+export interface InvalidContactEntry {
+ /** The entry's name when it has one, otherwise its position in the file. */
+ label: string;
+ /** The entry exactly as it is in the file, so the user can see what to fix. */
+ entry: unknown;
+ /** Every validation problem with the entry, not just the first. */
+ issues: ContactEntryIssue[];
+}
+
+export interface ContactEntryIssue {
+ /**
+ * The key of the field that failed, as written in the file (e.g. `email`), so the user
+ * can find it there. Absent when the entry as a whole is wrong, e.g. not an object.
+ */
+ field?: string;
+ /** What is wrong with it, e.g. "Invalid email address". */
+ message: string;
+}
+
+interface MergeImportedContactsOptions<T extends SavedContact> {
+ /** The contacts already saved in this browser. They are never changed or removed. */
+ existing: T[];
+ /** Raw entries from the backup file. */
+ imported: unknown[];
+ /** `sellerSchema` or `buyerSchema`, applied to each imported entry. */
+ schema: z.ZodType<T>;
+ /** Makes an id for an imported entry that has none. */
+ createId: () => string;
+ /** "seller" or "buyer", for the message about a name that is already taken. */
+ contactNoun: string;
+}
+
+export interface MergeImportedContactsResult<T extends SavedContact> {
+ /** The existing contacts followed by the newly added ones. */
+ contacts: T[];
+ /** The imported entries that were added, with the ids they were saved under. */
+ added: T[];
+ /** Imported entries skipped because the same id or the same details are already saved. */
+ duplicates: T[];
+ /** Imported entries skipped because they failed validation. */
+ invalidEntries: InvalidContactEntry[];
+ /**
+ * Imported entries skipped because a different contact already uses their name. The
+ * add/edit dialog does not allow two contacts with one name (the dropdown lists only
+ * names, and the pair could no longer be edited), so import does not either.
+ */
+ nameConflicts: InvalidContactEntry[];
+}
+
+/**
+ * Adds the imported entries that are valid and new to the saved list.
+ *
+ * An entry counts as already saved when its id matches a saved one (the same contact,
+ * possibly edited here since the backup was made, and the local edit wins) or when all
+ * its details match one (the same contact saved twice, e.g. in two browsers). An entry
+ * with new details but a name that is already saved is a conflict and is not added.
+ * Nothing already saved is ever changed or removed.
+ */
+export function mergeImportedContacts<T extends SavedContact>({
+ existing,
+ imported,
+ schema,
+ createId,
+ contactNoun,
+}: MergeImportedContactsOptions<T>): MergeImportedContactsResult<T> {
+ const contacts = [...existing];
+ const knownIds = new Set(
+ existing.flatMap((contact) => {
+ return contact.id ? [contact.id] : [];
+ }),
+ );
+ const knownFingerprints = new Set(
+ existing.map((contact) => {
+ return fingerprintContact(contact);
+ }),
+ );
+ // Compared exactly as the add/edit dialog does: trimmed (by the schema), case-sensitive
+ const knownNames = new Set(
+ existing.map((contact) => {
+ return contact.name;
+ }),
+ );
+
+ const added: T[] = [];
+ const duplicates: T[] = [];
+ const invalidEntries: InvalidContactEntry[] = [];
+ const nameConflicts: InvalidContactEntry[] = [];
+
+ for (const [index, entry] of imported.entries()) {
+ const result = schema.safeParse(entry);
+
+ if (!result.success) {
+ invalidEntries.push({
+ label: labelInvalidEntry({ entry, index }),
+ entry,
+ issues: result.error.issues.map((issue) => {
+ return describeIssue({ entry, issue });
+ }),
+ });
+
+ continue;
+ }
+
+ const contact = result.data;
+ const fingerprint = fingerprintContact(contact);
+ const isDuplicate =
+ (contact.id !== undefined && knownIds.has(contact.id)) ||
+ knownFingerprints.has(fingerprint);
+
+ if (isDuplicate) {
+ duplicates.push(contact);
+
+ continue;
+ }
+
+ if (knownNames.has(contact.name)) {
+ nameConflicts.push({
+ label: labelInvalidEntry({ entry, index }),
+ entry,
+ issues: [
+ {
+ field: "name",
+ message: `A ${contactNoun} with this name is already saved`,
+ },
+ ],
+ });
+
+ continue;
+ }
+
+ const contactWithId = { ...contact, id: contact.id || createId() };
+
+ contacts.push(contactWithId);
+ knownIds.add(contactWithId.id);
+ knownFingerprints.add(fingerprint);
+ knownNames.add(contactWithId.name);
+ added.push(contactWithId);
+ }
+
+ return {
+ contacts,
+ added,
+ duplicates,
+ invalidEntries,
+ nameConflicts,
+ };
+}
+
+function omitDefaultVisibilityFlags(
+ contact: SellerData | BuyerData,
+): Record<string, unknown> {
+ return Object.fromEntries(
+ Object.entries(contact).filter(([key, value]) => {
+ return !(key.endsWith("FieldIsVisible") && value === true);
+ }),
+ );
+}
+
+/**
+ * The contact's details without its id, with keys sorted so that two entries with the
+ * same details but a different key order compare equal.
+ */
+function fingerprintContact(contact: SavedContact): string {
+ const details = Object.entries(contact)
+ .filter(([key, value]) => {
+ return key !== "id" && value !== undefined;
+ })
+ // Not `toSorted()`: it is missing before Safari 16, which `.browserslistrc` still
+ // targets, and Next does not polyfill it. `filter` already returned a copy.
+ .sort(([a], [b]) => {
+ return a.localeCompare(b);
+ });
+
+ return JSON.stringify(details);
+}
+
+interface DescribeIssueOptions {
+ /** The raw entry that failed validation. */
+ entry: unknown;
+ /** One of the problems zod found with it. */
+ issue: z.core.$ZodIssue;
+}
+
+/**
+ * zod reports a missing field as "Invalid input: expected string, received undefined",
+ * which reads as jargon, so a field absent from the entry is reported as "Required".
+ */
+function describeIssue({
+ entry,
+ issue,
+}: DescribeIssueOptions): ContactEntryIssue {
+ const field = issue.path.join(".");
+
+ if (!field) {
+ return { message: issue.message };
+ }
+
+ const [key] = issue.path;
+ const isMissing =
+ issue.code === "invalid_type" &&
+ typeof entry === "object" &&
+ entry !== null &&
+ typeof key === "string" &&
+ !Object.hasOwn(entry, key);
+
+ return { field, message: isMissing ? "Required" : issue.message };
+}
+
+interface LabelInvalidEntryOptions {
+ /** The raw entry that failed validation. */
+ entry: unknown;
+ /** Its zero-based position in the file's list. */
+ index: number;
+}
+
+function labelInvalidEntry({ entry, index }: LabelInvalidEntryOptions): string {
+ const name =
+ typeof entry === "object" && entry !== null && "name" in entry
+ ? entry.name
+ : undefined;
+
+ return typeof name === "string" && name.trim()
+ ? name.trim()
+ : `Entry #${index + 1}`;
+}
+
+interface DescribeContactCountsOptions {
+ sellerCount: number;
+ buyerCount: number;
+}
+
+/**
+ * `2 sellers and 1 buyer`, `1 buyer`: only the lists that have any, for the import
+ * button and the toast after it.
+ */
+export function describeContactCounts({
+ sellerCount,
+ buyerCount,
+}: DescribeContactCountsOptions): string {
+ return [
+ sellerCount > 0
+ ? formatCount({ count: sellerCount, noun: "seller" })
+ : null,
+ buyerCount > 0 ? formatCount({ count: buyerCount, noun: "buyer" }) : null,
+ ]
+ .filter((part) => {
+ return part !== null;
+ })
+ .join(" and ");
+}
+
+interface FormatCountOptions {
+ count: number;
+ /** Singular form, e.g. "seller". */
+ noun: string;
+ /** Plural form, when it is not just `noun` + "s". */
+ plural?: string;
+}
+
+/** `1 seller`, `3 sellers`. */
+export function formatCount({
+ count,
+ noun,
+ plural = `${noun}s`,
+}: FormatCountOptions): string {
+ return `${count} ${count === 1 ? noun : plural}`;
+}