Skip to content

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

feat: add notes for seller and buyer, seo improvements and other stuff (#95)

Vlad Sazonauf73d166469f9
diff --git a/.cursor/rules/error-handling.mdc b/.cursor/rules/error-handling.mdc
new file mode 100644
index 0000000..27f1857
--- /dev/null
+++ b/.cursor/rules/error-handling.mdc
@@ -0,0 +1,91 @@
+---
+description:
+globs:
+alwaysApply: false
+---
+Error Handling and Validation Guidelines
+
+Key Principles:
+- Handle errors and edge cases early using guard clauses
+- Model expected errors as return values in Server Actions
+- Use error boundaries for unexpected errors
+- Implement proper error logging with meaningful messages
+- Provide user-friendly error feedback
+
+Form Validation:
+- Use Zod for form validation and type inference
+- Define reusable validation schemas
+- Implement client-side validation for immediate feedback
+- Add server-side validation as a safety net
+
+Error Types and Handling:
+- Expected errors (form validation, API responses):
+ - Handle with try/catch and return typed error objects
+ - Display user-friendly messages
+ - Log only when necessary for debugging
+- Unexpected errors (runtime errors, network issues):
+ - Catch with error boundaries
+ - Log comprehensively
+ - Show generic user-friendly fallback UI
+ - Include error reporting (if configured)
+
+Server Action Error Pattern:
+```typescript
+interface ActionResponse<T> {
+ data?: T;
+ error?: {
+ code: string;
+ message: string;
+ field?: string;
+ };
+}
+
+// Example usage
+async function handleSubmit(): Promise<ActionResponse<User>> {
+ try {
+ // ... logic
+ return { data: user };
+ } catch (e) {
+ return {
+ error: {
+ code: 'USER_CREATE_ERROR',
+ message: 'Failed to create user'
+ }
+ };
+ }
+}
+```
+
+Form Validation Pattern:
+```typescript
+import { z } from 'zod';
+
+const userSchema = z.object({
+ email: z.string().email(),
+ password: z.string().min(8),
+});
+
+type UserFormData = z.infer<typeof userSchema>;
+```
+
+Error Boundary Usage:
+```typescript
+import { ErrorBoundary } from 'react-error-boundary';
+
+function ErrorFallback({ error }: { error: Error }) {
+ return (
+ <div className="p-4 rounded-md bg-red-50">
+ <h2 className="text-red-800">Something went wrong</h2>
+ <pre className="text-sm text-red-600">{error.message}</pre>
+ </div>
+ );
+}
+
+export function Layout({ children }: { children: React.ReactNode }) {
+ return (
+ <ErrorBoundary FallbackComponent={ErrorFallback}>
+ {children}
+ </ErrorBoundary>
+ );
+}
+```
diff --git a/.cursor/rules/project-structure.mdc b/.cursor/rules/project-structure.mdc
new file mode 100644
index 0000000..f5f381a
--- /dev/null
+++ b/.cursor/rules/project-structure.mdc
@@ -0,0 +1,79 @@
+---
+description:
+globs:
+alwaysApply: false
+---
+Project Structure and Architecture Guidelines
+
+Directory Structure:
+```
+├── app/ # Next.js App Router directory
+│ ├── (auth)/ # Auth-related routes (grouped)
+│ ├── api/ # API routes
+│ └── layout.tsx # Root layout
+├── components/ # Reusable components
+│ ├── ui/ # Shadcn UI components
+│ └── [feature]/ # Feature-specific components
+├── lib/ # Shared utilities
+│ ├── utils.ts # General utilities
+│ └── validations.ts # Zod schemas
+├── hooks/ # Custom React hooks
+├── styles/ # Global styles
+└── types/ # TypeScript types
+```
+
+Component Organization:
+- Group related components in feature directories
+- Keep components small and focused
+- Extract reusable logic into custom hooks
+- Place shared types in dedicated files
+
+File Naming:
+- Use kebab-case for directories and files
+- Components: PascalCase.tsx
+- Utilities: camelCase.ts
+- Types: PascalCase.types.ts
+
+Component Structure:
+```typescript
+// types.ts
+interface Props {
+ // ... props interface
+}
+
+// helpers.ts
+function helperFunction() {
+ // ... helper logic
+}
+
+// Component.tsx
+import { type Props } from './types';
+import { helperFunction } from './helpers';
+
+export function Component({ prop1, prop2 }: Props) {
+ // ... component logic
+}
+```
+
+Data Fetching:
+- Use Server Components for data fetching
+- Implement proper caching strategies
+- Handle loading and error states
+- Use React Suspense boundaries
+
+Route Organization:
+- Group related routes in directories
+- Use route groups (parentheses) for organization
+- Keep page components lean
+- Extract business logic to separate files
+
+State Management:
+- Use Server Components when possible
+- Keep client state minimal
+- Use React Context sparingly
+
+API Structure:
+- Organize by feature/resource
+- Use consistent error handling
+- Implement proper validation
+- Follow RESTful conventions
diff --git a/.cursor/rules/testing.mdc b/.cursor/rules/testing.mdc
new file mode 100644
index 0000000..9d306ab
--- /dev/null
+++ b/.cursor/rules/testing.mdc
@@ -0,0 +1,80 @@
+---
+description:
+globs:
+alwaysApply: false
+---
+Testing Guidelines
+
+Testing Stack:
+- Vitest for unit and integration tests
+- Playwright for E2E testing
+- React Testing Library for component testing
+- MSW for API mocking
+
+Test Organization:
+- Place tests next to implementation files
+- Use descriptive test names
+- Group related tests in describe blocks
+- Follow AAA pattern (Arrange, Act, Assert)
+
+Naming Conventions:
+- Test files: `*.test.ts` or `*.test.tsx`
+- Test suites: describe('ComponentName', () => {})
+- Test cases: it('should do something specific', () => {})
+
+Component Testing Pattern:
+```typescript
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { Component } from './Component';
+
+describe('Component', () => {
+ it('should render successfully', () => {
+ render(<Component />);
+ expect(screen.getByRole('button')).toBeInTheDocument();
+ });
+
+ it('should handle user interaction', async () => {
+ const user = userEvent.setup();
+ render(<Component />);
+
+ await user.click(screen.getByRole('button'));
+ expect(screen.getByText('Clicked')).toBeInTheDocument();
+ });
+});
+```
+
+API Mocking Pattern:
+```typescript
+import { rest } from 'msw';
+import { setupServer } from 'msw/node';
+
+const server = setupServer(
+ rest.get('/api/data', (req, res, ctx) => {
+ return res(ctx.json({ data: 'mocked' }));
+ })
+);
+
+beforeAll(() => server.listen());
+afterEach(() => server.resetHandlers());
+afterAll(() => server.close());
+```
+
+Testing Guidelines:
+- Test behavior, not implementation
+- Use meaningful assertions
+- Mock external dependencies
+- Test error cases
+- Keep tests isolated
+- Use test data factories
+
+Coverage Requirements:
+- Unit tests: 80% coverage
+- Integration tests: Key user flows
+- E2E tests: Critical paths
+
+Performance Testing:
+- Use Lighthouse CI
+- Monitor Core Web Vitals
+- Test on slow networks
+- Test with different viewport sizes
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index 6773c1f..74a9c71 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -59,6 +59,8 @@ jobs:
echo "duration_formatted=${minutes}m ${seconds}s" >> "$GITHUB_OUTPUT"
env:
BASE_URL: ${{ github.event_name == 'deployment_status' && github.event.deployment_status.environment_url }}
+ NEXT_PUBLIC_SENTRY_DSN: ""
+ NEXT_PUBLIC_VERCEL_ENV: "test"
continue-on-error: true
- uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 #4.6.1
diff --git a/e2e/buyer.test.ts b/e2e/buyer.test.ts
index ef66c98..a71f48d 100644
--- a/e2e/buyer.test.ts
+++ b/e2e/buyer.test.ts
@@ -20,8 +20,12 @@ test.describe("Buyer management", () => {
vatNo: "987654321",
+
+ notesFieldIsVisible: true,
+ notes: "This is a test note",
} as const satisfies BuyerData;
+ // ------- TEST BUYER MANAGEMENT DIALOG FORM -------
const manageBuyerDialog = page.getByTestId(`manage-buyer-dialog`);
// Fill in form fields
@@ -49,6 +53,20 @@ test.describe("Buyer management", () => {
.nth(0)
.click(); // Toggle VAT Number visibility
+ // Fill in notes field
+ await manageBuyerDialog
+ .getByRole("textbox", { name: "Notes" })
+ .fill(testData.notes);
+
+ const notesSwitch = manageBuyerDialog.getByTestId(
+ `buyerNotesDialogFieldVisibilitySwitch`
+ );
+
+ await expect(notesSwitch).toHaveRole("switch");
+
+ // Verify notes visibility switch is CHECKED by default
+ await expect(notesSwitch).toBeChecked();
+
// Verify "Apply to Current Invoice" switch is checked by default
await expect(
manageBuyerDialog.getByRole("switch", {
@@ -85,8 +103,12 @@ test.describe("Buyer management", () => {
vatNoFieldIsVisible: false,
email: testData.email,
+
+ notes: testData.notes,
+ notesFieldIsVisible: true,
} satisfies BuyerData);
+ // ------- TEST SAVED DETAILS IN INVOICE FORM -------
// Verify all saved details in the Buyer Information section form
const buyerForm = page.getByTestId(`buyer-information-section`);
@@ -116,7 +138,7 @@ test.describe("Buyer management", () => {
const nameInput = buyerForm.getByRole("textbox", { name: "Name" });
await expect(nameInput).toHaveAttribute(
"title",
- "Buyer details are locked. Click the edit buyer button to modify."
+ "Buyer details are locked. Click the Edit Buyer button (Pencil icon) to modify."
);
// Buyer Name
@@ -152,12 +174,27 @@ test.describe("Buyer management", () => {
testData.email
);
+ // Buyer Notes
+ await expect(
+ buyerForm.getByRole("textbox", { name: "Notes" })
+ ).toHaveAttribute("aria-readonly", "true");
+
+ await expect(buyerForm.getByRole("textbox", { name: "Notes" })).toHaveValue(
+ testData.notes
+ );
+
+ const notesInvoiceFormSwitch = buyerForm.getByTestId(
+ `buyerNotesInvoiceFormFieldVisibilitySwitch`
+ );
+ await expect(notesInvoiceFormSwitch).toBeChecked();
+ await expect(notesInvoiceFormSwitch).toBeDisabled();
+
// Verify the buyer appears in the dropdown
await expect(
buyerForm.getByRole("combobox", { name: "Select Buyer" })
).toContainText(testData.name);
- // Test edit functionality
+ // ------- TEST EDIT FUNCTIONALITY -------
await buyerForm.getByRole("button", { name: "Edit buyer" }).click();
// Verify all fields are populated in edit dialog
@@ -179,6 +216,22 @@ test.describe("Buyer management", () => {
manageBuyerDialog.getByRole("switch", { name: "Show in PDF" }).nth(0)
).not.toBeChecked();
+ // Verify notes text
+ await expect(
+ manageBuyerDialog.getByRole("textbox", { name: "Notes" })
+ ).toHaveValue(testData.notes);
+
+ // Verify notes visibility switch is checked
+ const notesDialogFormSwitch = manageBuyerDialog.getByTestId(
+ `buyerNotesDialogFieldVisibilitySwitch`
+ );
+
+ await expect(notesDialogFormSwitch).toHaveRole("switch");
+ await expect(notesDialogFormSwitch).toHaveAccessibleName("Show in PDF");
+
+ await expect(notesDialogFormSwitch).toBeChecked();
+ await expect(notesDialogFormSwitch).toBeEnabled();
+
// Update some data in edit mode
const updatedName = "Updated Client Corp";
await manageBuyerDialog
@@ -191,6 +244,9 @@ test.describe("Buyer management", () => {
.nth(0)
.click();
+ // Uncheck notes visibility switch in edit dialog
+ await notesDialogFormSwitch.click();
+
// Save updated buyer
await manageBuyerDialog.getByRole("button", { name: "Save Buyer" }).click();
@@ -199,6 +255,7 @@ test.describe("Buyer management", () => {
page.getByText("Buyer updated successfully", { exact: true })
).toBeVisible();
+ // ------- TEST UPDATED INFORMATION IN INVOICE FORM -------
// Verify updated information is displayed
await expect(buyerForm.getByRole("textbox", { name: "Name" })).toHaveValue(
updatedName
@@ -208,6 +265,9 @@ test.describe("Buyer management", () => {
await expect(
buyerForm.getByTestId(`buyerVatNoFieldIsVisible`)
).toBeChecked();
+
+ // Verify notes visibility switch is unchecked
+ await expect(notesInvoiceFormSwitch).not.toBeChecked();
});
test("delete buyer", async ({ page }) => {
@@ -221,6 +281,9 @@ test.describe("Buyer management", () => {
vatNoFieldIsVisible: true,
vatNo: "123456789",
+
+ notesFieldIsVisible: true,
+ notes: "This is a test note",
} as const satisfies BuyerData;
const manageBuyerDialog = page.getByTestId(`manage-buyer-dialog`);
diff --git a/e2e/invoice-form.test.ts b/e2e/invoice-form.test.ts
index fcadc6f..5cb3c4c 100644
--- a/e2e/invoice-form.test.ts
+++ b/e2e/invoice-form.test.ts
@@ -2,6 +2,7 @@ import {
ACCORDION_STATE_LOCAL_STORAGE_KEY,
CURRENCY_SYMBOLS,
LANGUAGE_TO_LABEL,
+ PDF_DATA_LOCAL_STORAGE_KEY,
SUPPORTED_CURRENCIES,
SUPPORTED_DATE_FORMATS,
SUPPORTED_LANGUAGES,
@@ -18,6 +19,9 @@ test.describe("Invoice Generator Page", () => {
});
test("displays correct buttons and links in header", async ({ page }) => {
+ // Check URL is correct
+ await expect(page).toHaveURL("/en/app");
+
// Check title and branding
await expect(page).toHaveTitle(
"Invoice PDF Generator with Live Preview | No Sign-Up"
@@ -287,9 +291,13 @@ test.describe("Invoice Generator Page", () => {
await expect(
buyerSection.getByRole("textbox", { name: "VAT Number" })
).toHaveValue(INITIAL_INVOICE_DATA.buyer.vatNo);
- await expect(
- buyerSection.getByRole("switch", { name: /Show in PDF/i })
- ).toBeChecked();
+
+ const buyerVatNoFieldIsVisibleSwitch = buyerSection.getByTestId(
+ `buyerVatNoFieldIsVisible`
+ );
+
+ await expect(buyerVatNoFieldIsVisibleSwitch).toHaveRole("switch");
+ await expect(buyerVatNoFieldIsVisibleSwitch).toBeChecked();
// Email field
await expect(
@@ -582,7 +590,9 @@ test.describe("Invoice Generator Page", () => {
await invoiceNumberValueField.fill("TEST/2024");
- await page
+ const finalSection = page.getByTestId(`final-section`);
+
+ await finalSection
.getByRole("textbox", { name: "Notes", exact: true })
.fill("Test note");
@@ -591,9 +601,10 @@ test.describe("Invoice Generator Page", () => {
await page.waitForTimeout(500);
// Verify data is actually saved in localStorage
- const storedData = (await page.evaluate(() => {
- return localStorage.getItem("EASY_INVOICE_PDF_DATA");
- })) as string;
+ const storedData = (await page.evaluate((key) => {
+ return localStorage.getItem(key);
+ }, PDF_DATA_LOCAL_STORAGE_KEY)) as string;
+
expect(storedData).toBeTruthy();
const parsedData = JSON.parse(storedData) as InvoiceData;
@@ -622,7 +633,7 @@ test.describe("Invoice Generator Page", () => {
await expect(invoiceNumberValueField2).toHaveValue("TEST/2024");
await expect(
- page.getByRole("textbox", { name: "Notes", exact: true })
+ finalSection.getByRole("textbox", { name: "Notes", exact: true })
).toHaveValue("Test note");
});
@@ -1039,7 +1050,9 @@ test.describe("Invoice Generator Page", () => {
await invoiceNumberValueField.fill("SHARE-TEST-001");
- await page
+ const finalSection = page.getByTestId(`final-section`);
+
+ await finalSection
.getByRole("textbox", { name: "Notes", exact: true })
.fill("Test note for sharing");
@@ -1094,8 +1107,10 @@ test.describe("Invoice Generator Page", () => {
invoiceNumberFieldset.getByRole("textbox", { name: "Value" })
).toHaveValue("SHARE-TEST-001");
+ const newPageFinalSection = newPage.getByTestId(`final-section`);
+
await expect(
- newPage.getByRole("textbox", { name: "Notes", exact: true })
+ newPageFinalSection.getByRole("textbox", { name: "Notes", exact: true })
).toHaveValue("Test note for sharing");
// Verify seller information
@@ -1129,4 +1144,36 @@ test.describe("Invoice Generator Page", () => {
// Close the new page
await newPage.close();
});
+
+ test("shows notification when invoice link is broken", async ({ page }) => {
+ // Navigate to page with invalid data parameter
+ await page.goto("/en/app?data=invalid-data-string");
+
+ // Verify error toast appears
+ await expect(
+ page.getByText("The shared invoice URL appears to be incorrect")
+ ).toBeVisible();
+
+ // Verify error description is shown
+ await expect(
+ page.getByText(
+ "Please verify that you have copied the complete invoice URL. The link may be truncated or corrupted."
+ )
+ ).toBeVisible();
+
+ // Verify clear URL button is present
+ await expect(page.getByRole("button", { name: "Clear URL" })).toBeVisible();
+
+ // Click clear URL button
+ await page.getByRole("button", { name: "Clear URL" }).click();
+
+ // Verify toast is dismissed
+ await expect(
+ page.getByText("The shared invoice URL appears to be incorrect")
+ ).toBeHidden();
+
+ // Verify URL is cleared
+ expect(page.url()).toContain("/en/app");
+ expect(page.url()).not.toContain("?data=");
+ });
});
diff --git a/e2e/pdf.test.ts b/e2e/pdf.test.ts
index 222408c..f6f64b3 100644
--- a/e2e/pdf.test.ts
+++ b/e2e/pdf.test.ts
@@ -15,6 +15,11 @@ const getDownloadDir = ({ browserName }: { browserName: string }) => {
};
const CURRENT_MONTH_AND_YEAR = dayjs().format("MM-YYYY");
+const TODAY = dayjs().format("YYYY-MM-DD");
+const LAST_DAY_OF_CURRENT_MONTH = dayjs().endOf("month").format("YYYY-MM-DD");
+
+// Payment date is 14 days from today (by default)
+const PAYMENT_DATE = dayjs().add(14, "day").format("YYYY-MM-DD");
/**
* We can't test the PDF preview because it's not supported in Playwright.
@@ -101,18 +106,52 @@ test.describe("PDF Preview", () => {
expect(pdfData.text).toContain("Seller");
expect(pdfData.text).toContain("Buyer");
- const lastDayOfCurrentMonth = dayjs().endOf("month").format("YYYY-MM-DD");
-
+ // Check invoice header details
expect(pdfData.text).toContain(
- `Date of sales/of executing the service: ${lastDayOfCurrentMonth}`
+ `Invoice No. of: 1/${CURRENT_MONTH_AND_YEAR}`
+ );
+ expect(pdfData.text).toContain("Reverse Charge");
+ expect(pdfData.text).toContain(`Date of issue: ${TODAY}`);
+ expect(pdfData.text).toContain(
+ `Date of sales/of executing the service: ${LAST_DAY_OF_CURRENT_MONTH}`
);
- expect(pdfData.text).toContain(`To pay: 0.00 EUR
-Paid: 0.00 EUR
-Left to pay: 0.00 EUR
-Amount in words: zero EUR 00/100`);
- expect(pdfData.text).toContain(`Reverse charge
-Created with https://easyinvoicepdf.com`);
+ // Check seller details
+ expect(pdfData.text).toContain("Seller name");
+ expect(pdfData.text).toContain("Seller address");
+ expect(pdfData.text).toContain("VAT no: Seller vat number");
+ expect(pdfData.text).toContain("e-mail: [email protected]");
+ expect(pdfData.text).toContain("Account Number - Seller account number");
+ expect(pdfData.text).toContain("SWIFT/BIC number: Seller swift bic");
+
+ // Check buyer details
+ expect(pdfData.text).toContain("Buyer name");
+ expect(pdfData.text).toContain("Buyer address");
+ expect(pdfData.text).toContain("VAT no: Buyer vat number");
+ expect(pdfData.text).toContain("e-mail: [email protected]");
+
+ // Check invoice item details
+ expect(pdfData.text).toContain("Item name");
+ expect(pdfData.text).toContain("1");
+ expect(pdfData.text).toContain("service");
+ expect(pdfData.text).toContain("0.00");
+
+ // Check payment details
+ expect(pdfData.text).toContain("Payment method: wire transfer");
+ expect(pdfData.text).toContain(`Payment date: ${PAYMENT_DATE}`);
+
+ // Check totals
+ expect(pdfData.text).toContain("To pay: 0.00 EUR");
+ expect(pdfData.text).toContain("Paid: 0.00 EUR");
+ expect(pdfData.text).toContain("Left to pay: 0.00 EUR");
+ expect(pdfData.text).toContain("Amount in words: zero EUR 00/100");
+
+ // Check footer
+ expect(pdfData.text).toContain("Person authorized to receive");
+ expect(pdfData.text).toContain("Person authorized to issue");
+ expect(pdfData.text).toContain("Reverse charge");
+ expect(pdfData.text).toContain("Created with https://easyinvoicepdf.com");
+ expect(pdfData.text).toContain("1/1");
});
test("downloads PDF in Polish and verifies translated content", async ({
@@ -179,13 +218,15 @@ Kwota słownie: zero EUR 00/100`);
page,
browserName,
}) => {
+ const DATE_FORMAT = "MMMM D, YYYY";
+
// Switch to another currency
await page.getByRole("combobox", { name: "Currency" }).selectOption("GBP");
// Switch to another date format
await page
.getByRole("combobox", { name: "Date format" })
- .selectOption("MMMM D, YYYY");
+ .selectOption(DATE_FORMAT);
await page
.getByRole("textbox", { name: "Invoice Type" })
@@ -216,6 +257,19 @@ Kwota słownie: zero EUR 00/100`);
.nth(2)
.click();
+ // update notes
+ await sellerSection
+ .getByRole("textbox", { name: "Notes" })
+ .fill("PLAYWRIGHT SELLER NOTES TEST");
+
+ // Toggle notes visibility on
+ const sellerNotesSwitch = sellerSection.getByTestId(
+ `sellerNotesInvoiceFormFieldVisibilitySwitch`
+ );
+
+ await expect(sellerNotesSwitch).toHaveRole("switch");
+ await expect(sellerNotesSwitch).toBeChecked();
+
const buyerSection = page.getByTestId(`buyer-information-section`);
// Name field
@@ -233,6 +287,19 @@ Kwota słownie: zero EUR 00/100`);
.getByRole("textbox", { name: "Email" })
+ // update notes
+ await buyerSection
+ .getByRole("textbox", { name: "Notes" })
+ .fill("PLAYWRIGHT BUYER NOTES TEST");
+
+ // Toggle notes visibility on
+ const buyerNotesSwitch = buyerSection.getByTestId(
+ `buyerNotesInvoiceFormFieldVisibilitySwitch`
+ );
+
+ await expect(buyerNotesSwitch).toHaveRole("switch");
+ await expect(buyerNotesSwitch).toBeChecked();
+
const invoiceSection = page.getByTestId(`invoice-items-section`);
// Amount field
@@ -286,38 +353,59 @@ Kwota słownie: zero EUR 00/100`);
const dataBuffer = await fs.promises.readFile(tmpPath);
const pdfData = await pdf(dataBuffer);
- const lastDayOfCurrentMonth = dayjs().endOf("month").format("MMMM D, YYYY");
+ const today = dayjs().format(DATE_FORMAT);
+ const lastDayOfCurrentMonth = dayjs().endOf("month").format(DATE_FORMAT);
+ const paymentDate = dayjs().add(14, "day").format(DATE_FORMAT);
// Verify PDF content
+ // Check invoice header details
+ expect(pdfData.text).toContain(
+ `Invoice No. of: 1/${CURRENT_MONTH_AND_YEAR}`
+ );
+ expect(pdfData.text).toContain("HELLO FROM PLAYWRIGHT TEST!");
+ expect(pdfData.text).toContain(`Date of issue: ${today}`);
expect(pdfData.text).toContain(
`Date of sales/of executing the service: ${lastDayOfCurrentMonth}`
);
- expect(pdfData.text).toContain("HELLO FROM PLAYWRIGHT TEST!");
+ // Check seller details
expect(pdfData.text).toContain("PLAYWRIGHT SELLER TEST");
- expect(pdfData.text).toContain(`PLAYWRIGHT BUYER TEST`);
- expect(pdfData.text).toContain(`PLAYWRIGHT BUYER ADDRESS TEST`);
- expect(pdfData.text).toContain(`[email protected]`);
-
- // Check that the PDF does NOT contain the seller's VAT number, account number, or SWIFT/BIC number
- // because we toggled the visibility off
- expect(pdfData.text).not.toContain(`VAT no: Seller vat number
-Account Number - Seller account number
-SWIFT/BIC number: Seller swift bic`);
-
- // Check that the PDF does NOT contain the VAT table summary
- // because we toggled the visibility off
- expect(pdfData.text).not.toContain(`VAT rateNetVATPre-tax
-NP3 000.000.003 000.00
-Total3 000.000.003 000.00`);
-
- expect(pdfData.text).toContain(`To pay: 3 000.00 GBP
-Paid: 0.00 GBP
-Left to pay: 3 000.00 GBP
-Amount in words: three thousand GBP 00/100`);
-
- expect(pdfData.text).toContain(`Reverse charge
-Created with https://easyinvoicepdf.com`);
+ expect(pdfData.text).toContain("Seller address");
+ expect(pdfData.text).toContain("[email protected]");
+ expect(pdfData.text).toContain("PLAYWRIGHT SELLER NOTES TEST");
+
+ // Check buyer details
+ expect(pdfData.text).toContain("PLAYWRIGHT BUYER TEST");
+ expect(pdfData.text).toContain("PLAYWRIGHT BUYER ADDRESS TEST");
+ expect(pdfData.text).toContain("Buyer vat number");
+ expect(pdfData.text).toContain("[email protected]");
+ expect(pdfData.text).toContain("PLAYWRIGHT BUYER NOTES TEST");
+
+ // Check invoice item details
+ expect(pdfData.text).toContain("Item name");
+ expect(pdfData.text).toContain("3");
+ expect(pdfData.text).toContain("service");
+ expect(pdfData.text).toContain("1 000.00");
+ expect(pdfData.text).toContain("3 000.00");
+
+ // Check payment details
+ expect(pdfData.text).toContain("Payment method: wire transfer");
+ expect(pdfData.text).toContain(`Payment date: ${paymentDate}`);
+
+ // Check totals
+ expect(pdfData.text).toContain("To pay: 3 000.00 GBP");
+ expect(pdfData.text).toContain("Paid: 0.00 GBP");
+ expect(pdfData.text).toContain("Left to pay: 3 000.00 GBP");
+ expect(pdfData.text).toContain(
+ "Amount in words: three thousand GBP 00/100"
+ );
+
+ // Check footer
+ expect(pdfData.text).toContain("Person authorized to receive");
+ expect(pdfData.text).toContain("Person authorized to issue");
+ expect(pdfData.text).toContain("Reverse charge");
+ expect(pdfData.text).toContain("Created with https://easyinvoicepdf.com");
+ expect(pdfData.text).toContain("1/1");
});
test("completes full invoice flow on mobile: tabs navigation, form editing and PDF download in French", async ({
@@ -363,7 +451,8 @@ Created with https://easyinvoicepdf.com`);
await invoiceNumberLabelInput.fill("MOBILE-TEST-001:");
await invoiceNumberValueInput.fill("2/05-2024");
- await page
+ const finalSection = page.getByTestId("final-section");
+ await finalSection
.getByRole("textbox", { name: "Notes", exact: true })
.fill("Mobile test note");
@@ -477,7 +566,7 @@ Montant en lettres: cent quatre-vingt-quatre GBP 50/100`);
await expect(invoiceNumberValueInput).toHaveValue("2/05-2024");
await expect(
- page.getByRole("textbox", { name: "Notes", exact: true })
+ finalSection.getByRole("textbox", { name: "Notes", exact: true })
).toHaveValue("Mobile test note");
// Verify seller information persists
diff --git a/e2e/seller.test.ts b/e2e/seller.test.ts
index 4bf1a11..2f660a5 100644
--- a/e2e/seller.test.ts
+++ b/e2e/seller.test.ts
@@ -25,10 +25,14 @@ test.describe("Seller management", () => {
swiftBicFieldIsVisible: true,
swiftBic: "TESTBICX",
+
+ notesFieldIsVisible: true,
+ notes: "This is a SELLER test note",
} as const satisfies SellerData;
const manageSellerDialog = page.getByTestId(`manage-seller-dialog`);
+ // ------- TEST SELLER MANAGEMENT DIALOG FORM -------
// Fill in form fields
await manageSellerDialog
.getByRole("textbox", { name: "Name" })
@@ -70,6 +74,20 @@ test.describe("Seller management", () => {
.nth(2)
.click(); // Toggle SWIFT/BIC visibility
+ // Fill in notes field
+ await manageSellerDialog
+ .getByRole("textbox", { name: "Notes" })
+ .fill(testData.notes);
+
+ const notesSellerSwitch = manageSellerDialog.getByTestId(
+ `sellerNotesDialogFieldVisibilitySwitch`
+ );
+
+ await expect(notesSellerSwitch).toHaveRole("switch");
+
+ // Verify notes visibility switch is CHECKED by default
+ await expect(notesSellerSwitch).toBeChecked();
+
// Verify "Apply to Current Invoice" switch is checked by default
await expect(
manageSellerDialog.getByRole("switch", {
@@ -109,6 +127,9 @@ test.describe("Seller management", () => {
swiftBic: testData.swiftBic,
swiftBicFieldIsVisible: false,
+
+ notes: testData.notes,
+ notesFieldIsVisible: true,
} satisfies SellerData);
// Verify success toast message is visible
@@ -116,6 +137,7 @@ test.describe("Seller management", () => {
page.getByText("Seller added successfully", { exact: true })
).toBeVisible();
+ // ------- TEST SAVED DETAILS IN INVOICE FORM -------
// Verify all saved details in the Seller Information section form
const sellerForm = page.getByTestId(`seller-information-section`);
@@ -123,7 +145,7 @@ test.describe("Seller management", () => {
const nameInput = sellerForm.getByRole("textbox", { name: "Name" });
await expect(nameInput).toHaveAttribute(
"title",
- "Seller details are locked. Click the edit seller button to modify."
+ "Seller details are locked. Click the Edit Seller button (Pencil icon) to modify."
);
// Seller Name
@@ -189,6 +211,21 @@ test.describe("Seller management", () => {
await expect(swiftBicSwitch).not.toBeChecked();
await expect(swiftBicSwitch).toBeDisabled();
+ // Seller Notes
+ await expect(
+ sellerForm.getByRole("textbox", { name: "Notes" })
+ ).toHaveAttribute("aria-readonly", "true");
+ await expect(
+ sellerForm.getByRole("textbox", { name: "Notes" })
+ ).toHaveValue(testData.notes);
+
+ const notesSwitch = sellerForm.getByTestId(
+ `sellerNotesInvoiceFormFieldVisibilitySwitch`
+ );
+ // Verify Notes switch is visible
+ await expect(notesSwitch).toBeChecked();
+ await expect(notesSwitch).toBeDisabled();
+
// Verify the seller appears in the dropdown
await expect(
sellerForm.getByRole("combobox", { name: "Select Seller" })
@@ -197,6 +234,7 @@ test.describe("Seller management", () => {
// Test edit functionality
await sellerForm.getByRole("button", { name: "Edit seller" }).click();
+ // ------- TEST EDIT FUNCTIONALITY IN SELLER MANAGEMENT DIALOG -------
// Verify all fields are populated in edit dialog
await expect(
manageSellerDialog.getByRole("textbox", { name: "Name" })
@@ -227,6 +265,19 @@ test.describe("Seller management", () => {
await expect(
manageSellerDialog.getByRole("switch", { name: "Show in PDF" }).nth(2)
).not.toBeChecked();
+
+ // Verify notes text
+ await expect(
+ manageSellerDialog.getByRole("textbox", { name: "Notes" })
+ ).toHaveValue(testData.notes);
+
+ // Verify notes visibility switch is checked
+ const notesManageSellerDialogFormSwitch = manageSellerDialog.getByTestId(
+ `sellerNotesDialogFieldVisibilitySwitch`
+ );
+
+ await expect(notesManageSellerDialogFormSwitch).toBeChecked();
+ await expect(notesManageSellerDialogFormSwitch).toBeEnabled();
});
test("delete seller", async ({ page }) => {
@@ -246,6 +297,9 @@ test.describe("Seller management", () => {
swiftBicFieldIsVisible: true,
swiftBic: "123456789",
+
+ notesFieldIsVisible: true,
+ notes: "This is a test note",
} as const satisfies SellerData;
const manageSellerDialog = page.getByTestId(`manage-seller-dialog`);
diff --git a/messages/de.json b/messages/de.json
index f2ce3f2..d08bada 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -1,9 +1,9 @@
{
"Metadata": {
"about": {
- "title": "Über uns | PDF-Rechnungsgenerator mit Live-Vorschau | Keine Anmeldung",
- "description": "Erstellen und laden Sie professionelle PDF-Rechnungen sofort mit Echtzeit-Vorschau herunter. Kostenlos und Open-Source. Keine Anmeldung erforderlich.",
- "keywords": "Rechnungstool, kostenloser Rechnungsgenerator, PDF-Rechnungen, Rechnungsersteller, Fakturierungssoftware"
+ "title": "Über | Kostenloser Rechnungsgenerator – Live-Vorschau, Keine Anmeldung",
+ "description": "Erstellen und laden Sie professionelle Rechnungen sofort mit Echtzeit-Vorschau herunter. Kostenlos und Open-Source. Keine Anmeldung erforderlich.",
+ "keywords": "Rechnungstool, kostenloser Rechnungsgenerator, PDF-Rechnungen, Rechnungsersteller, Abrechnungssoftware"
}
},
"NotFound": {
diff --git a/messages/en.json b/messages/en.json
index 7964cad..4340bcd 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -1,6 +1,6 @@
{
"About": {
- "tagline": "Invoice PDF generator with live preview",
+ "tagline": "Free Invoice Generator with Live PDF Preview",
"hero": {
"title": "Create professional invoices in seconds",
"description": "EasyInvoicePDF is a free, open-source tool that lets you create, customize, and download professional PDF invoices with real-time preview.",
@@ -44,7 +44,7 @@
"noSignup": "No sign-up required. 100% free and open-source."
},
"footer": {
- "description": "A free, open-source tool for creating professional PDF invoices with real-time preview.",
+ "description": "A free, open-source tool for creating professional invoices with real-time preview.",
"product": "Product",
"links": {
"features": "Features",
@@ -86,8 +86,8 @@
},
"Metadata": {
"about": {
- "title": "About | Invoice PDF Generator with Live Preview | No Sign-Up",
- "description": "Create and download professional PDF invoices instantly with real-time preview. Free and open-source. No signup required.",
+ "title": "About | Free Invoice Generator – Live Preview, No Sign-Up",
+ "description": "Create and download professional invoices instantly with real-time preview. Free and open-source. No signup required.",
"keywords": "invoice tool, free invoice generator, PDF invoices, invoice creator, billing software"
}
},
@@ -98,7 +98,7 @@
"items": {
"whatIs": {
"question": "What is EasyInvoicePDF?",
- "answer": "EasyInvoicePDF is a free, open-source tool that helps you create professional PDF invoices instantly. It features a live preview, customizable templates, and supports multiple languages and currencies."
+ "answer": "EasyInvoicePDF is a free, open-source tool that helps you create professional invoices instantly. It features a live preview, customizable templates, and supports multiple languages and currencies."
},
"isFree": {
"question": "Is it really free?",
diff --git a/messages/es.json b/messages/es.json
index 3ffa42b..743d8c2 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -14,8 +14,8 @@
},
"Metadata": {
"about": {
- "title": "Acerca de | Generador de Facturas PDF con Vista Previa en Vivo | Sin Registro",
- "description": "Crea y descarga facturas PDF profesionales al instante con vista previa en tiempo real. Gratis y de código abierto. No requiere registro.",
+ "title": "Acerca de | Generador de Facturas Gratuito – Vista Previa en Vivo, Sin Registro",
+ "description": "Crea y descarga facturas profesionales al instante con vista previa en tiempo real. Gratuito y de código abierto. No requiere registro.",
"keywords": "herramienta de facturación, generador de facturas gratuito, facturas PDF, creador de facturas, software de facturación"
}
},
diff --git a/messages/fr.json b/messages/fr.json
index 632c98c..533a3f9 100644
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -85,8 +85,8 @@
},
"Metadata": {
"about": {
- "title": "À propos | Générateur de Factures PDF avec Aperçu en Direct | Sans Inscription",
- "description": "Créez et téléchargez des factures PDF professionnelles instantanément avec aperçu en temps réel. Gratuit et open-source. Aucune inscription requise.",
+ "title": "À propos | Générateur de Factures Gratuit – Aperçu en Direct, Sans Inscription",
+ "description": "Créez et téléchargez des factures professionnelles instantanément avec aperçu en temps réel. Gratuit et open-source. Aucune inscription requise.",
"keywords": "outil de facturation, générateur de factures gratuit, factures PDF, créateur de factures, logiciel de facturation"
}
},
diff --git a/messages/it.json b/messages/it.json
index 4bf5a6d..c27dc33 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -85,9 +85,9 @@
},
"Metadata": {
"about": {
- "title": "Chi siamo | Generatore di Fatture PDF con Anteprima in Tempo Reale | Senza Registrazione",
- "description": "Crea e scarica fatture PDF professionali istantaneamente con anteprima in tempo reale. Gratuito e open-source. Nessuna registrazione richiesta.",
- "keywords": "strumento fatturazione, generatore fatture gratis, fatture PDF, creatore fatture, software fatturazione"
+ "title": "Chi Siamo | Generatore di Fatture Gratuito – Anteprima in Tempo Reale, Nessuna Registrazione",
+ "description": "Crea e scarica fatture professionali istantaneamente con anteprima in tempo reale. Gratuito e open-source. Nessuna registrazione richiesta.",
+ "keywords": "strumento per fatture, generatore di fatture gratuito, fatture PDF, creatore di fatture, software di fatturazione"
}
},
"FAQ": {
diff --git a/messages/nl.json b/messages/nl.json
index 92ae582..177be35 100644
--- a/messages/nl.json
+++ b/messages/nl.json
@@ -85,8 +85,8 @@
},
"Metadata": {
"about": {
- "title": "Over ons | PDF Factuur Generator met Live Voorbeeld | Geen Registratie",
- "description": "Maak en download direct professionele PDF-facturen met realtime voorbeeld. Gratis en open-source. Geen registratie vereist.",
+ "title": "Over | Gratis Factuur Generator – Live Voorbeeld, Geen Registratie",
+ "description": "Maak en download direct professionele facturen met realtime voorbeeld. Gratis en open-source. Geen registratie vereist.",
"keywords": "factuurtool, gratis factuur generator, PDF facturen, factuur maker, facturatie software"
}
},
diff --git a/messages/pl.json b/messages/pl.json
index 38735dc..40ba3eb 100644
--- a/messages/pl.json
+++ b/messages/pl.json
@@ -1,9 +1,9 @@
{
"Metadata": {
"about": {
- "title": "O nas | Generator Faktur PDF z Podglądem na Żywo | Bez Rejestracji",
- "description": "Twórz i pobieraj profesjonalne faktury PDF natychmiast z podglądem w czasie rzeczywistym. Darmowe i open-source. Bez wymaganej rejestracji.",
- "keywords": "narzędzie do fakturowania, darmowy generator faktur, faktury PDF, kreator faktur, oprogramowanie do fakturowania"
+ "title": "O nas | Darmowy Generator Faktur – Podgląd na Żywo, Bez Rejestracji",
+ "description": "Twórz i pobieraj profesjonalne faktury natychmiast z podglądem w czasie rzeczywistym. Darmowy i open-source. Bez wymaganej rejestracji.",
+ "keywords": "narzędzie do faktur, darmowy generator faktur, faktury PDF, kreator faktur, oprogramowanie do fakturowania"
}
},
"NotFound": {
diff --git a/messages/pt.json b/messages/pt.json
index 9f7dfef..c50ad1d 100644
--- a/messages/pt.json
+++ b/messages/pt.json
@@ -1,9 +1,9 @@
{
"Metadata": {
"about": {
- "title": "Sobre | Gerador de Faturas PDF com Pré-visualização ao Vivo | Sem Cadastro",
- "description": "Crie e baixe faturas PDF profissionais instantaneamente com pré-visualização em tempo real. Gratuito e de código aberto. Não é necessário cadastro.",
- "keywords": "ferramenta de faturamento, gerador de faturas grátis, faturas PDF, criador de faturas, software de faturamento"
+ "title": "Sobre | Gerador de Invoices Gratuito – Pré-visualização em Tempo Real, Sem Registro",
+ "description": "Crie e baixe invoices profissionais instantaneamente com pré-visualização em tempo real. Gratuito e código aberto. Sem necessidade de registro.",
+ "keywords": "ferramenta de invoice, gerador de invoices gratuito, invoices PDF, criador de invoices, software de faturamento"
}
},
"NotFound": {
diff --git a/messages/ru.json b/messages/ru.json
index 45b05ba..d05c5e6 100644
--- a/messages/ru.json
+++ b/messages/ru.json
@@ -1,9 +1,9 @@
{
"Metadata": {
"about": {
- "title": "О нас | Генератор PDF-инвойсов с предпросмотром | Без регистрации",
- "description": "Создавайте и скачивайте PDF-инвойсы мгновенно с предпросмотром в реальном времени. Бесплатно и без регистрации.",
- "keywords": "инструмент для инвойсов, бесплатный генератор инвойсов, PDF инвойсы, создание инвойсов, программа для выставления инвойсов"
+ "title": "О нас | Бесплатный Генератор Инвойсов – Предпросмотр в Реальном Времени, Без Регистрации",
+ "description": "Создавайте и скачивайте инвойсы мгновенно с предпросмотром в реальном времени. Бесплатно и с открытым исходным кодом. Без регистрации.",
+ "keywords": "инструмент для выставления инвойсов, бесплатный генератор инвойсов, PDF инвойсы, создание инвойсов, программа для выставления инвойсов"
}
},
"NotFound": {
diff --git a/messages/uk.json b/messages/uk.json
index 6a86874..46df377 100644
--- a/messages/uk.json
+++ b/messages/uk.json
@@ -14,9 +14,9 @@
},
"Metadata": {
"about": {
- "title": "Про нас | Генератор рахунків-фактур PDF з попереднім переглядом | Без реєстрації",
- "description": "Створюйте та завантажуйте професійні PDF-рахунки миттєво з попереднім переглядом у реальному часі. Безкоштовно та з відкритим кодом. Реєстрація не потрібна.",
- "keywords": "інструмент для рахунків, безкоштовний генератор рахунків, PDF рахунки, створення рахунків, програма для виставлення рахунків"
+ "title": "Про нас | Безкоштовний Генератор Інвойсів – Попередній Перегляд у Реальному Часі, Без Реєстрації",
+ "description": "Створюйте та завантажуйте професійні інвойси миттєво з попереднім переглядом у реальному часі. Безкоштовно та з відкритим кодом. Без необхідності реєстрації.",
+ "keywords": "інструмент для виставлення інвойсів, безкоштовний генератор інвойсів, PDF інвойси, створення інвойсів, програма для виставлення інвойсів"
}
},
"About": {
diff --git a/sentry.client.config.ts b/sentry.client.config.ts
index 503c422..e198f0e 100644
--- a/sentry.client.config.ts
+++ b/sentry.client.config.ts
@@ -4,17 +4,18 @@
import * as Sentry from "@sentry/nextjs";
+// we use NEXT_PUBLIC_VERCEL_ENV to check if we are in production because VERCEL_ENV is only available on the server
+const isVercelProd = process.env.NEXT_PUBLIC_VERCEL_ENV === "production";
+
Sentry.init({
- dsn:
- process.env.NEXT_PUBLIC_SENTRY_DSN ||
- "https://70cc01ec3353cbe140250b9c1568f270@o4508904709750784.ingest.de.sentry.io/4508904711651408",
+ dsn: isVercelProd ? process.env.NEXT_PUBLIC_SENTRY_DSN : "",
+ enabled: isVercelProd,
// Adjust sampling in production for better performance/cost balance
tracesSampleRate: 0.15, // Sample 15% of transactions
// Recommended production settings
debug: false,
- enabled: process.env.NODE_ENV === "production",
// Performance settings
replaysSessionSampleRate: 0.1, // Sample 10% of sessions
diff --git a/sentry.edge.config.ts b/sentry.edge.config.ts
index b51f9ee..917b00d 100644
--- a/sentry.edge.config.ts
+++ b/sentry.edge.config.ts
@@ -5,17 +5,17 @@
import * as Sentry from "@sentry/nextjs";
+const isVercelProd = process.env.VERCEL_ENV === "production";
+
Sentry.init({
- dsn:
- process.env.NEXT_PUBLIC_SENTRY_DSN ||
- "https://70cc01ec3353cbe140250b9c1568f270@o4508904709750784.ingest.de.sentry.io/4508904711651408",
+ dsn: isVercelProd ? process.env.NEXT_PUBLIC_SENTRY_DSN : "",
+ enabled: isVercelProd,
// Adjust sampling in production for better performance/cost balance
tracesSampleRate: 0.15, // Sample 15% of transactions
// Recommended production settings
debug: false,
- enabled: process.env.NODE_ENV === "production",
// Performance settings
replaysSessionSampleRate: 0.1, // Sample 10% of sessions
diff --git a/sentry.server.config.ts b/sentry.server.config.ts
index eca6e71..5207333 100644
--- a/sentry.server.config.ts
+++ b/sentry.server.config.ts
@@ -4,17 +4,17 @@
import * as Sentry from "@sentry/nextjs";
+const isVercelProd = process.env.VERCEL_ENV === "production";
+
Sentry.init({
- dsn:
- process.env.NEXT_PUBLIC_SENTRY_DSN ||
- "https://70cc01ec3353cbe140250b9c1568f270@o4508904709750784.ingest.de.sentry.io/4508904711651408",
+ dsn: isVercelProd ? process.env.NEXT_PUBLIC_SENTRY_DSN : "",
+ enabled: isVercelProd,
// Adjust sampling in production for better performance/cost balance
tracesSampleRate: 0.15, // Sample 15% of transactions
// Recommended production settings
debug: false,
- enabled: process.env.NODE_ENV === "production",
// Performance settings
replaysSessionSampleRate: 0.1, // Sample 10% of sessions
diff --git a/src/app/[locale]/app/error.tsx b/src/app/[locale]/app/error.tsx
index 39eae51..ecbdc27 100644
--- a/src/app/[locale]/app/error.tsx
+++ b/src/app/[locale]/app/error.tsx
@@ -3,11 +3,11 @@
import { Button } from "@/components/ui/button";
import { useEffect } from "react";
import { toast } from "sonner";
-import { PDF_DATA_LOCAL_STORAGE_KEY } from "../../components/invoice-form";
import { INITIAL_INVOICE_DATA } from "../../constants";
import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
import * as Sentry from "@sentry/nextjs";
import { ErrorMessage } from "@/components/etc/error-message";
+import { PDF_DATA_LOCAL_STORAGE_KEY } from "@/app/schema";
export default function Error({
error,
diff --git a/src/app/[locale]/app/page.client.tsx b/src/app/[locale]/app/page.client.tsx
index 817951e..7a5c192 100644
--- a/src/app/[locale]/app/page.client.tsx
+++ b/src/app/[locale]/app/page.client.tsx
@@ -2,6 +2,7 @@
import {
invoiceSchema,
+ PDF_DATA_LOCAL_STORAGE_KEY,
SUPPORTED_LANGUAGES,
type InvoiceData,
} from "@/app/schema";
@@ -18,7 +19,6 @@ import {
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
-import { PDF_DATA_LOCAL_STORAGE_KEY } from "@/app/components/invoice-form";
import { InvoicePDFDownloadLink } from "@/app/components/invoice-pdf-download-link";
import { INITIAL_INVOICE_DATA } from "@/app/constants";
import { useDeviceContext } from "@/contexts/device-context";
@@ -164,7 +164,7 @@ export function AppPageClient({ params }: { params: { locale: Locale } }) {
toast.error(
"Unable to load your saved invoice data. For your convenience, we've reset the form to default values. Please try creating a new invoice.",
{
- duration: 7000,
+ duration: 20000,
closeButton: true,
richColors: true,
}
diff --git a/src/app/components/invoice-form/index.tsx b/src/app/components/invoice-form/index.tsx
index 7a3e6e2..96fa6dc 100644
--- a/src/app/components/invoice-form/index.tsx
+++ b/src/app/components/invoice-form/index.tsx
@@ -5,6 +5,7 @@ import {
accordionSchema,
invoiceItemSchema,
invoiceSchema,
+ PDF_DATA_LOCAL_STORAGE_KEY,
type AccordionState,
type InvoiceData,
type InvoiceItemData,
@@ -42,7 +43,6 @@ import { GeneralInformation } from "./sections/general-information";
import { InvoiceItems } from "./sections/invoice-items";
import { SellerInformation } from "./sections/seller-information";
-export const PDF_DATA_LOCAL_STORAGE_KEY = "EASY_INVOICE_PDF_DATA";
export const LOADING_BUTTON_TIMEOUT = 400;
export const LOADING_BUTTON_TEXT = "Generating Document...";
const DEBOUNCE_TIMEOUT = 500;
diff --git a/src/app/components/invoice-form/sections/buyer-information.tsx b/src/app/components/invoice-form/sections/buyer-information.tsx
index ef1da6c..f14921d 100644
--- a/src/app/components/invoice-form/sections/buyer-information.tsx
+++ b/src/app/components/invoice-form/sections/buyer-information.tsx
@@ -19,7 +19,7 @@ const ErrorMessage = ({ children }: { children: React.ReactNode }) => {
};
const BUYER_TOOLTIP_CONTENT =
- "Buyer details are locked. Click the edit button next to the 'Select Buyer' dropdown to modify buyer details. Any changes will be automatically saved.";
+ "Buyer details are locked. Click the Edit Buyer button (Pencil icon) next to the 'Select Buyer' dropdown to modify buyer details. Any changes will be automatically saved.";
interface BuyerInformationProps {
control: Control<InvoiceData>;
@@ -38,7 +38,7 @@ export const BuyerInformation = memo(function BuyerInformation({
const isBuyerSelected = !!selectedBuyerId;
const HTML_TITLE_CONTENT = isBuyerSelected
- ? "Buyer details are locked. Click the edit buyer button to modify."
+ ? "Buyer details are locked. Click the Edit Buyer button (Pencil icon) to modify."
: "";
// Get current form values to pass to BuyerManagement
@@ -48,6 +48,8 @@ export const BuyerInformation = memo(function BuyerInformation({
vatNo: invoiceData.buyer.vatNo,
email: invoiceData.buyer.email,
vatNoFieldIsVisible: invoiceData.buyer.vatNoFieldIsVisible,
+ notes: invoiceData.buyer.notes,
+ notesFieldIsVisible: invoiceData.buyer.notesFieldIsVisible,
} satisfies Partial<BuyerData>;
return (
@@ -228,6 +230,80 @@ export const BuyerInformation = memo(function BuyerInformation({
<ErrorMessage>{errors.buyer.email.message}</ErrorMessage>
)}
</div>
+
+ {/* Notes */}
+ <div>
+ <div className="relative mb-2 flex items-center justify-between">
+ {isBuyerSelected ? (
+ <LabelWithEditIcon
+ htmlFor={`buyerNotes`}
+ content={BUYER_TOOLTIP_CONTENT}
+ >
+ Notes
+ </LabelWithEditIcon>
+ ) : (
+ <Label htmlFor={`buyerNotes`} className="">
+ Notes
+ </Label>
+ )}
+
+ {/* Show/hide Notes field in PDF switch */}
+ <div
+ className="inline-flex items-center gap-2"
+ title={HTML_TITLE_CONTENT}
+ >
+ <Controller
+ name={`buyer.notesFieldIsVisible`}
+ control={control}
+ render={({ field: { value, onChange, ...field } }) => (
+ <Switch
+ {...field}
+ id={`buyerNotesFieldIsVisible`}
+ checked={value}
+ onCheckedChange={onChange}
+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"
+ disabled={isBuyerSelected}
+ data-testid={`buyerNotesInvoiceFormFieldVisibilitySwitch`}
+ />
+ )}
+ />
+ <CustomTooltip
+ trigger={
+ <Label htmlFor={`buyerNotesFieldIsVisible`}>
+ Show in PDF
+ </Label>
+ }
+ content={
+ isBuyerSelected
+ ? null
+ : "Show/Hide the 'Notes' Field in the PDF"
+ }
+ />
+ </div>
+ </div>
+
+ <Controller
+ name="buyer.notes"
+ control={control}
+ render={({ field }) => {
+ return (
+ <Textarea
+ {...field}
+ id={`buyerNotes`}
+ rows={3}
+ className=""
+ readOnly={isBuyerSelected}
+ aria-readonly={isBuyerSelected}
+ title={HTML_TITLE_CONTENT}
+ placeholder="Additional information about the buyer"
+ />
+ );
+ }}
+ />
+ {errors.buyer?.notes && (
+ <ErrorMessage>{errors.buyer.notes.message}</ErrorMessage>
+ )}
+ </div>
</fieldset>
</div>
);
diff --git a/src/app/components/invoice-form/sections/seller-information.tsx b/src/app/components/invoice-form/sections/seller-information.tsx
index 3cf78b9..059aa9a 100644
--- a/src/app/components/invoice-form/sections/seller-information.tsx
+++ b/src/app/components/invoice-form/sections/seller-information.tsx
@@ -19,7 +19,7 @@ const ErrorMessage = ({ children }: { children: React.ReactNode }) => {
};
const SELLER_TOOLTIP_CONTENT =
- "Seller details are locked. Click the edit button next to the 'Select Seller' dropdown to modify seller details.";
+ "Seller details are locked. Click the Edit Seller button (Pencil icon) next to the 'Select Seller' dropdown to modify seller details.";
interface SellerInformationProps {
control: Control<InvoiceData>;
@@ -38,7 +38,7 @@ export const SellerInformation = memo(function SellerInformation({
const isSellerSelected = !!selectedSellerId;
const HTML_TITLE_CONTENT = isSellerSelected
- ? "Seller details are locked. Click the edit seller button to modify."
+ ? "Seller details are locked. Click the Edit Seller button (Pencil icon) to modify."
: "";
// Get current form values to pass to SellerManagement
@@ -52,6 +52,8 @@ export const SellerInformation = memo(function SellerInformation({
vatNoFieldIsVisible: invoiceData.seller.vatNoFieldIsVisible,
accountNumberFieldIsVisible: invoiceData.seller.accountNumberFieldIsVisible,
swiftBicFieldIsVisible: invoiceData.seller.swiftBicFieldIsVisible,
+ notes: invoiceData.seller.notes,
+ notesFieldIsVisible: invoiceData.seller.notesFieldIsVisible,
} satisfies Partial<SellerData>;
return (
@@ -378,6 +380,80 @@ export const SellerInformation = memo(function SellerInformation({
<ErrorMessage>{errors.seller.swiftBic.message}</ErrorMessage>
)}
</div>
+
+ {/* Notes */}
+ <div>
+ <div className="relative mb-2 flex items-center justify-between">
+ {isSellerSelected ? (
+ <LabelWithEditIcon
+ htmlFor={`sellerNotes`}
+ content={SELLER_TOOLTIP_CONTENT}
+ >
+ Notes
+ </LabelWithEditIcon>
+ ) : (
+ <Label htmlFor={`sellerNotes`} className="">
+ Notes
+ </Label>
+ )}
+
+ {/* Show/hide Notes field in PDF switch */}
+ <div
+ className="inline-flex items-center gap-2"
+ title={HTML_TITLE_CONTENT}
+ >
+ <Controller
+ name={`seller.notesFieldIsVisible`}
+ control={control}
+ render={({ field: { value, onChange, ...field } }) => (
+ <Switch
+ {...field}
+ id={`sellerNotesFieldIsVisible`}
+ checked={value}
+ onCheckedChange={onChange}
+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"
+ disabled={isSellerSelected}
+ data-testid={`sellerNotesInvoiceFormFieldVisibilitySwitch`}
+ />
+ )}
+ />
+ <CustomTooltip
+ trigger={
+ <Label htmlFor={`sellerNotesFieldIsVisible`}>
+ Show in PDF
+ </Label>
+ }
+ content={
+ isSellerSelected
+ ? null
+ : "Show/Hide the 'Notes' Field in the PDF"
+ }
+ />
+ </div>
+ </div>
+
+ <Controller
+ name="seller.notes"
+ control={control}
+ render={({ field }) => {
+ return (
+ <Textarea
+ {...field}
+ id={`sellerNotes`}
+ rows={3}
+ className=""
+ readOnly={isSellerSelected}
+ aria-readonly={isSellerSelected}
+ title={HTML_TITLE_CONTENT}
+ placeholder="Additional information about the seller"
+ />
+ );
+ }}
+ />
+ {errors.seller?.notes && (
+ <ErrorMessage>{errors.seller.notes.message}</ErrorMessage>
+ )}
+ </div>
</fieldset>
</div>
);
diff --git a/src/app/components/invoice-pdf-template/invoice-seller-buyer-info.tsx b/src/app/components/invoice-pdf-template/invoice-seller-buyer-info.tsx
index 4eeed4e..86319aa 100644
--- a/src/app/components/invoice-pdf-template/invoice-seller-buyer-info.tsx
+++ b/src/app/components/invoice-pdf-template/invoice-seller-buyer-info.tsx
@@ -16,6 +16,8 @@ export function InvoiceSellerBuyerInfo({
const buyerVatNoFieldIsVisible = invoiceData.buyer.vatNoFieldIsVisible;
const sellerAccountNumberFieldIsVisible =
invoiceData.seller.accountNumberFieldIsVisible;
+ const sellerNotesFieldIsVisible = invoiceData.seller.notesFieldIsVisible;
+ const buyerNotesFieldIsVisible = invoiceData.buyer.notesFieldIsVisible;
return (
<View
@@ -73,6 +75,13 @@ export function InvoiceSellerBuyerInfo({
</Text>
</Text>
)}
+ {sellerNotesFieldIsVisible && invoiceData?.seller.notes && (
+ <View style={{ marginTop: 10 }}>
+ <Text style={[styles.fontSize8]}>
+ {invoiceData?.seller.notes}
+ </Text>
+ </View>
+ )}
</View>
</View>
@@ -104,6 +113,12 @@ export function InvoiceSellerBuyerInfo({
</Text>
</Text>
</View>
+
+ {buyerNotesFieldIsVisible && invoiceData?.buyer.notes && (
+ <View style={{ marginTop: 20 }}>
+ <Text style={[styles.fontSize8]}>{invoiceData?.buyer.notes}</Text>
+ </View>
+ )}
</View>
</View>
);
diff --git a/src/app/constants/index.ts b/src/app/constants/index.ts
index 00a5da0..deda29d 100644
--- a/src/app/constants/index.ts
+++ b/src/app/constants/index.ts
@@ -37,6 +37,10 @@ export const DEFAULT_SELLER_DATA = {
swiftBic: "Seller swift bic",
swiftBicFieldIsVisible: true,
+
+ // field for additional notes about the seller (not visible by default)
+ notes: "",
+ notesFieldIsVisible: true,
} as const satisfies Omit<SellerData, "id">;
/**
@@ -52,6 +56,10 @@ export const DEFAULT_BUYER_DATA = {
vatNoFieldIsVisible: true,
+
+ // field for additional notes about the buyer (not visible by default)
+ notes: "",
+ notesFieldIsVisible: true,
} as const satisfies Omit<BuyerData, "id">;
/**
diff --git a/src/app/schema/index.ts b/src/app/schema/index.ts
index d70736e..5a0e955 100644
--- a/src/app/schema/index.ts
+++ b/src/app/schema/index.ts
@@ -213,6 +213,13 @@ export const sellerSchema = z
.trim()
.optional(),
swiftBicFieldIsVisible: z.boolean().default(true),
+
+ notes: z
+ .string()
+ .max(750, "Notes must not exceed 750 characters")
+ .trim()
+ .optional(),
+ notesFieldIsVisible: z.boolean().default(true),
})
.strict();
@@ -240,6 +247,13 @@ export const buyerSchema = z
vatNoFieldIsVisible: z.boolean().default(true),
email: z.string().email("Invalid email address").trim(),
+
+ notes: z
+ .string()
+ .max(750, "Notes must not exceed 750 characters")
+ .trim()
+ .optional(),
+ notesFieldIsVisible: z.boolean().default(true),
})
.strict();
@@ -309,6 +323,8 @@ export const invoiceSchema = z.object({
export type InvoiceData = z.infer<typeof invoiceSchema>;
+export const PDF_DATA_LOCAL_STORAGE_KEY = "EASY_INVOICE_PDF_DATA";
+
/**
* Accordion state schema
*
diff --git a/src/components/buyer-dialog.tsx b/src/components/buyer-dialog.tsx
index 0fea866..f5c1ea1 100644
--- a/src/components/buyer-dialog.tsx
+++ b/src/components/buyer-dialog.tsx
@@ -1,5 +1,3 @@
-"use client";
-
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -65,6 +63,8 @@ export function BuyerDialog({
vatNo: initialData?.vatNo ?? "",
email: initialData?.email ?? "",
vatNoFieldIsVisible: initialData?.vatNoFieldIsVisible ?? true,
+ notes: initialData?.notes ?? "",
+ notesFieldIsVisible: initialData?.notesFieldIsVisible ?? true,
},
});
@@ -94,6 +94,8 @@ export function BuyerDialog({
vatNo: "",
email: "",
vatNoFieldIsVisible: true,
+ notes: "",
+ notesFieldIsVisible: true,
}
);
}
@@ -333,6 +335,61 @@ export function BuyerDialog({
</FormItem>
)}
/>
+
+ {/* Notes */}
+ <div className="space-y-4">
+ <div className="flex items-end justify-between">
+ <FormField
+ control={form.control}
+ name="notes"
+ render={({ field }) => (
+ <FormItem className="flex-1">
+ <FormLabel>Notes</FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter notes (max 750 characters)"
+ maxLength={750}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* Show/Hide Notes Field in PDF */}
+ <div className="ml-4 flex items-center gap-2">
+ <FormField
+ control={form.control}
+ name="notesFieldIsVisible"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex items-center gap-2">
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ id="notes-field-visibility"
+ data-testid={`buyerNotesDialogFieldVisibilitySwitch`}
+ />
+ </FormControl>
+ <CustomTooltip
+ trigger={
+ <Label htmlFor="notes-field-visibility">
+ Show in PDF
+ </Label>
+ }
+ content="Show/Hide the notes field in the PDF"
+ className="z-[1000]"
+ />
+ </div>
+ </FormItem>
+ )}
+ />
+ </div>
+ </div>
+ </div>
</form>
</Form>
@@ -368,9 +425,11 @@ export function BuyerDialog({
<Button
type="button"
onClick={async () => {
- // validate the form
- const isValid = await form.trigger();
- if (!isValid) return;
+ // Validate form and focus first error field
+ const result = await form.trigger(undefined, {
+ shouldFocus: true,
+ });
+ if (!result) return;
// submit the form
onSubmit(form.getValues());
diff --git a/src/components/buyer-management.tsx b/src/components/buyer-management.tsx
index 14c4364..9074d73 100644
--- a/src/components/buyer-management.tsx
+++ b/src/components/buyer-management.tsx
@@ -1,5 +1,3 @@
-"use client";
-
import { Plus, Trash2, Pencil } from "lucide-react";
import { useId, useState, useEffect } from "react";
import { CustomTooltip } from "./ui/tooltip";
diff --git a/src/components/seller-dialog.tsx b/src/components/seller-dialog.tsx
index 6306dfd..cc396c5 100644
--- a/src/components/seller-dialog.tsx
+++ b/src/components/seller-dialog.tsx
@@ -1,5 +1,3 @@
-"use client";
-
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -72,6 +70,8 @@ export function SellerDialog({
accountNumberFieldIsVisible:
initialData?.accountNumberFieldIsVisible ?? true,
swiftBicFieldIsVisible: initialData?.swiftBicFieldIsVisible ?? true,
+ notes: initialData?.notes ?? "",
+ notesFieldIsVisible: initialData?.notesFieldIsVisible ?? true,
},
});
@@ -106,6 +106,8 @@ export function SellerDialog({
vatNoFieldIsVisible: true,
accountNumberFieldIsVisible: true,
swiftBicFieldIsVisible: true,
+ notes: "",
+ notesFieldIsVisible: true,
}
);
}
@@ -443,6 +445,61 @@ export function SellerDialog({
</div>
</div>
</div>
+
+ {/* Notes */}
+ <div className="space-y-4">
+ <div className="flex items-end justify-between">
+ <FormField
+ control={form.control}
+ name="notes"
+ render={({ field }) => (
+ <FormItem className="flex-1">
+ <FormLabel>Notes</FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter notes (max 750 characters)"
+ maxLength={750}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* Show/Hide Notes Field in PDF */}
+ <div className="ml-4 flex items-center gap-2">
+ <FormField
+ control={form.control}
+ name="notesFieldIsVisible"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex items-center gap-2">
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ id="notes-field-visibility"
+ data-testid={`sellerNotesDialogFieldVisibilitySwitch`}
+ />
+ </FormControl>
+ <CustomTooltip
+ trigger={
+ <Label htmlFor="notes-field-visibility">
+ Show in PDF
+ </Label>
+ }
+ content="Show/Hide the notes field in the PDF"
+ className="z-[1000]"
+ />
+ </div>
+ </FormItem>
+ )}
+ />
+ </div>
+ </div>
+ </div>
</form>
</Form>
@@ -481,9 +538,11 @@ export function SellerDialog({
onClick={async () => {
// we manually trigger the form validation and submit the form
- // validate the form
- const isValid = await form.trigger();
- if (!isValid) return;
+ // Validate form and focus first error field
+ const result = await form.trigger(undefined, {
+ shouldFocus: true,
+ });
+ if (!result) return;
// submit the form
onSubmit(form.getValues());