Skip to content

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

feat: enhance invoice form calculations, add more test coverage and other improvements (#245)

Vlad Sazonau046d34b708ff
diff --git a/.github/workflows/pnpm-policy.yml b/.github/workflows/pnpm-policy.yml
index 19ce779..ea64ee0 100644
--- a/.github/workflows/pnpm-policy.yml
+++ b/.github/workflows/pnpm-policy.yml
@@ -7,6 +7,7 @@ on:
permissions:
contents: read
+ pull-requests: read
jobs:
pnpm-policy:
@@ -32,6 +33,8 @@ jobs:
run: corepack install
- name: Verify pnpm supply-chain config
+ id: pnpm-policy
+ continue-on-error: true
shell: bash
run: |
set -euo pipefail
@@ -66,3 +69,42 @@ jobs:
verify_config minimum-release-age 7200
verify_config block-exotic-subdeps true
verify_config trust-policy no-downgrade
+
+ - name: πŸ” Get PR URL
+ if: steps.pnpm-policy.outcome == 'failure'
+ id: pr-url
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ GH_REPOSITORY: ${{ github.repository }}
+ GH_REPOSITORY_OWNER: ${{ github.repository_owner }}
+ GH_REF_NAME: ${{ github.ref_name }}
+ run: |
+ PR_URL=$(curl -s \
+ -H "Authorization: Bearer $GITHUB_TOKEN" \
+ -H "Accept: application/vnd.github+json" \
+ "https://api.github.com/repos/$GH_REPOSITORY/pulls?head=$GH_REPOSITORY_OWNER:$GH_REF_NAME" \
+ | jq -r '.[0].html_url // empty')
+ echo "pr_url=$PR_URL" >> "$GITHUB_OUTPUT"
+
+ - name: πŸ“§ Send email
+ if: steps.pnpm-policy.outcome == 'failure'
+ # https://github.com/dawidd6/action-send-mail
+ uses: dawidd6/action-send-mail@d38f3f7cd391cdebfe0d38efc3998b935e951c4f # v16
+ with:
+ server_address: smtp.gmail.com
+ server_port: 587
+ from: "GitHub Actions (no-reply) <${{ secrets.EMAIL_USERNAME }}>"
+ to: ${{ secrets.EMAIL_USERNAME }}
+ username: ${{ secrets.EMAIL_USERNAME }}
+ password: ${{ secrets.EMAIL_PASSWORD }}
+ subject: ❌ pnpm Supply-Chain Policy Failed for ${{ github.repository }}
+ body: |
+ pnpm supply-chain policy verification for ${{ github.repository }} has failed.
+
+ For more details, please check:
+ - GitHub Actions run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
+ ${{ steps.pr-url.outputs.pr_url && format('- Pull Request: {0}', steps.pr-url.outputs.pr_url) }}
+
+ - name: ❌ Mark workflow failed on pnpm policy failure
+ if: steps.pnpm-policy.outcome == 'failure'
+ run: exit 1
diff --git a/README.md b/README.md
index 8c962e5..8666a10 100644
--- a/README.md
+++ b/README.md
@@ -35,12 +35,12 @@
<img src="https://github.com/user-attachments/assets/450fcdc8-32fc-4f41-bc4b-54d6ac96e03c" width="1440" alt="EasyInvoicePDF demo">
</div>
-## ✨ Key Features of EasyInvoicePDF:
+## ✨ Feature Highlights
- πŸ“Ί **Instant PDF generation** with live preview
- πŸš€ **No sign-up required** - start immediately
- πŸŽ‰ **Ad-free experience**
-- πŸ‘€ **Saved profiles** - reuse seller & buyer details
+- πŸ‘€ **Save Seller & Buyer Profiles** - reuse seller & buyer details for future invoices
- 🎨 **Multiple fully customizable templates** including modern Stripe-style design
- 🧾 **Smart invoicing tools** - VAT, GST, sales tax & custom tax support with automatic calculations
- 🏷️ **Logo support** for custom branding
diff --git a/e2e/invoice-form.test.ts b/e2e/invoice-form.test.ts
index d8ab326..1b6c994 100644
--- a/e2e/invoice-form.test.ts
+++ b/e2e/invoice-form.test.ts
@@ -1886,4 +1886,50 @@ test.describe("Invoice Generator Page", () => {
await expect(servicePeriodStartInput).toHaveValue("2025-05-11");
await expect(servicePeriodSwitch).toBeChecked();
});
+
+ test("validates service period start is on or before end date", async ({
+ page,
+ }) => {
+ const generalInfoSection = page.getByRole("region", {
+ name: "General Information",
+ });
+ const servicePeriodFieldset = generalInfoSection.getByRole("group", {
+ name: "Service period",
+ });
+ const servicePeriodStartInput = servicePeriodFieldset.getByRole("textbox", {
+ name: "Service period start",
+ });
+ const servicePeriodEndInput = servicePeriodFieldset.getByRole("textbox", {
+ name: "Service period end",
+ });
+
+ const errorMessage =
+ "Service period start must be on or before the end date";
+ const notifications = page.getByLabel("Notifications alt+T");
+
+ await servicePeriodEndInput.fill("2025-06-15");
+ await servicePeriodStartInput.fill("2025-06-20");
+
+ await expect(
+ servicePeriodFieldset.getByText(errorMessage, { exact: true }),
+ ).toBeVisible();
+
+ await expect(
+ notifications.getByText("Please fix the following errors:"),
+ ).toBeVisible();
+
+ await expect(notifications.getByText(errorMessage)).toBeVisible();
+
+ await servicePeriodStartInput.fill("2025-06-15");
+
+ await expect(
+ servicePeriodFieldset.getByText(errorMessage, { exact: true }),
+ ).toBeHidden();
+
+ await expect(
+ notifications.getByText("Please fix the following errors:"),
+ ).toBeHidden();
+
+ await expect(notifications.getByText(errorMessage)).toBeHidden();
+ });
});
diff --git a/e2e/server-render-pdf/server-render-pdf.test.ts b/e2e/server-render-pdf/server-render-pdf.test.ts
new file mode 100644
index 0000000..ed3209c
--- /dev/null
+++ b/e2e/server-render-pdf/server-render-pdf.test.ts
@@ -0,0 +1,106 @@
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import { test, expect } from "@playwright/test";
+import { renderPdfOnCanvas } from "../utils/render-pdf-on-canvas";
+
+/**
+ * Spawn child process to render invoice PDF on server, for a given language.
+ * Uses Vitest to run export-server-pdf.test.ts, which writes PDF to temp file.
+ * Returns Buffer of generated PDF. Deletes temp file after reading.
+ * Throws error if process fails or PDF not created.
+ */
+function spawnServerPdfRender(language: "en" | "pl"): Buffer {
+ // Generate unique temp file path
+ const tmpFile = path.join(
+ os.tmpdir(),
+ `server-pdf-${language}-${process.pid}-${Date.now()}.pdf`,
+ );
+
+ // Run vitest test that generates PDF, passing env vars for output and language
+ const result = spawnSync(
+ "pnpm",
+ [
+ "vitest",
+ "run",
+ "src/app/api/generate-invoice/__tests__/export-server-pdf.test.ts",
+ ],
+ {
+ cwd: process.cwd(),
+ env: {
+ ...process.env,
+ PDF_EXPORT_PATH: tmpFile, // test will write PDF here
+ PDF_EXPORT_LANG: language, // test will use this language
+ },
+ stdio: "pipe",
+ encoding: "utf-8",
+ },
+ );
+
+ // If test failed, throw error with stdout/stderr for debugging
+ if (result.status !== 0) {
+ throw new Error(
+ `Server PDF render failed (${language}):\n${result.stdout}\n${result.stderr}`,
+ );
+ }
+
+ // Check that temp PDF file was created
+ if (!fs.existsSync(tmpFile)) {
+ throw new Error(`Server PDF file was not created: ${tmpFile}`);
+ }
+
+ // Read and return PDF buffer, ensure temp file is deleted afterwards
+ try {
+ return fs.readFileSync(tmpFile);
+ } finally {
+ fs.rmSync(tmpFile, { force: true });
+ }
+}
+
+test.describe("Server-side PDF rendering", () => {
+ test.describe.configure({ mode: "serial" });
+
+ test.beforeEach(({}, testInfo) => {
+ // eslint-disable-next-line playwright/no-skipped-test -- visual snapshots are Desktop Chrome only
+ test.skip(
+ testInfo.project.name !== "Desktop Chrome",
+ "Server PDF snapshots are Desktop Chrome only",
+ );
+ });
+
+ test("renders English server PDF on canvas", async ({ page }) => {
+ const buffer = spawnServerPdfRender("en");
+
+ await page.goto("about:blank");
+ await renderPdfOnCanvas(page, new Uint8Array(buffer));
+
+ await page.waitForFunction(
+ () =>
+ (window as unknown as { __PDF_RENDERED__: boolean })
+ .__PDF_RENDERED__ === true,
+ );
+
+ await expect(page.locator("canvas")).toHaveScreenshot(
+ "server-en-invoice.png",
+ );
+ });
+
+ test("renders Polish server PDF on canvas", async ({ page }) => {
+ const buffer = spawnServerPdfRender("pl");
+
+ await page.goto("about:blank");
+ await renderPdfOnCanvas(page, new Uint8Array(buffer));
+
+ await page.waitForFunction(
+ () =>
+ (window as unknown as { __PDF_RENDERED__: boolean })
+ .__PDF_RENDERED__ === true,
+ );
+
+ await expect(page.locator("canvas")).toHaveScreenshot(
+ "server-pl-invoice.png",
+ );
+ });
+});
diff --git a/e2e/server-render-pdf/server-render-pdf.test.ts-snapshots/server-en-invoice-Desktop-Chrome-darwin.png b/e2e/server-render-pdf/server-render-pdf.test.ts-snapshots/server-en-invoice-Desktop-Chrome-darwin.png
new file mode 100644
index 0000000..52180f2
Binary files /dev/null and b/e2e/server-render-pdf/server-render-pdf.test.ts-snapshots/server-en-invoice-Desktop-Chrome-darwin.png differ
diff --git a/e2e/server-render-pdf/server-render-pdf.test.ts-snapshots/server-pl-invoice-Desktop-Chrome-darwin.png b/e2e/server-render-pdf/server-render-pdf.test.ts-snapshots/server-pl-invoice-Desktop-Chrome-darwin.png
new file mode 100644
index 0000000..42206df
Binary files /dev/null and b/e2e/server-render-pdf/server-render-pdf.test.ts-snapshots/server-pl-invoice-Desktop-Chrome-darwin.png differ
diff --git a/package.json b/package.json
index e558bfd..b1aa23b 100644
--- a/package.json
+++ b/package.json
@@ -96,6 +96,9 @@
"@eslint/eslintrc": "3.3.1",
"@next/eslint-plugin-next": "15.2.3",
"@playwright/test": "1.60.0",
+ "@testing-library/jest-dom": "6.9.1",
+ "@testing-library/react": "16.3.2",
+ "@testing-library/user-event": "14.6.1",
"@types/file-saver": "2.0.7",
"@types/node": "22.8.1",
"@types/react": "18.3.12",
@@ -108,6 +111,7 @@
"eslint-config-next": "15.2.3",
"eslint-plugin-playwright": "2.2.0",
"eslint-plugin-react-you-might-not-need-an-effect": "0.0.39",
+ "happy-dom": "20.10.6",
"husky": "9.1.7",
"knip": "5.85.0",
"lint-staged": "15.5.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0e5f5ba..735c4a9 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -183,6 +183,15 @@ importers:
'@playwright/test':
specifier: 1.60.0
version: 1.60.0
+ '@testing-library/jest-dom':
+ specifier: 6.9.1
+ version: 6.9.1
+ '@testing-library/react':
+ specifier: 16.3.2
+ '@testing-library/user-event':
+ specifier: 14.6.1
+ version: 14.6.1(@testing-library/[email protected])
'@types/file-saver':
specifier: 2.0.7
version: 2.0.7
@@ -219,6 +228,9 @@ importers:
eslint-plugin-react-you-might-not-need-an-effect:
specifier: 0.0.39
+ happy-dom:
+ specifier: 20.10.6
+ version: 20.10.6
husky:
specifier: 9.1.7
version: 9.1.7
@@ -257,10 +269,13 @@ importers:
vitest:
specifier: 3.2.4
packages:
+ '@adobe/[email protected]':
+ resolution: {integrity: sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==}
+
resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}
engines: {node: '>=10'}
@@ -2376,6 +2391,35 @@ packages:
peerDependencies:
tailwindcss: '>=3.0.0 || insiders || >=4.0.0-alpha.20 || >=4.0.0-beta.1'
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}
+ engines: {node: '>=18'}
+
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==}
+ engines: {node: '>=14', npm: '>=6', yarn: '>=1'}
+
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@testing-library/dom': ^10.0.0
+ '@types/react': ^18.0.0 || ^19.0.0
+ '@types/react-dom': ^18.0.0 || ^19.0.0
+ react: ^18.0.0 || ^19.0.0
+ react-dom: ^18.0.0 || ^19.0.0
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-vq7fv0rnt+QTXgPxr5Hjc210p6YKq2kmdziLgnsZGgLJ9e6VAShx1pACLuRjd/AS/sr7phAR58OIIpf0LlmQNw==}
+ engines: {node: '>=12', npm: '>=6'}
+ peerDependencies:
+ '@testing-library/dom': '>=7.21.4'
+
'@ts-morph/[email protected]':
resolution: {integrity: sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ==}
@@ -2385,6 +2429,9 @@ packages:
resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==}
+
resolution: {integrity: sha512-8kB30R7Hwqf40JPiKhVzodJs2Qc1ZJ5zuT3uzw5Hq/dhNCl3G3l83jfpdI1e20BP348+fV7VIL/+FxaXkqBmWg==}
@@ -2484,6 +2531,12 @@ packages:
resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
+
'@typescript-eslint/[email protected]':
resolution: {integrity: sha512-w/EboPlBwnmOBtRbiOvzjD+wdiZdgFeo17lkltrtn7X37vagKKWJABvyfsJXTlHe6XBzugmYgd4A4nW+k8Mixw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -2957,6 +3010,10 @@ packages:
resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==}
engines: {node: '>=12'}
@@ -2982,6 +3039,9 @@ packages:
resolution: {integrity: sha512-y+CcFFwelSXpLZk/7fMB2mUbGtX9lKycf1MWJ7CaTIERyitVlyQx6C+sxcROU2BAJ24OiZyK+8wj2i8AlBoS3A==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==}
+
resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==}
engines: {node: '>= 0.4'}
@@ -3123,6 +3183,10 @@ packages:
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
+ resolution: {integrity: sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==}
+ engines: {node: '>=4.0'}
+
resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}
@@ -3374,6 +3438,9 @@ packages:
resolution: {integrity: sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==}
+ resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}
+
resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}
engines: {node: '>=4'}
@@ -3536,6 +3603,12 @@ packages:
resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
+
+ resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==}
+
resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}
@@ -3613,6 +3686,10 @@ packages:
resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}
engines: {node: '>=0.12'}
+ resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
+ engines: {node: '>=0.12'}
+
resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}
engines: {node: '>=6'}
@@ -4220,6 +4297,10 @@ packages:
resolution: {integrity: sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==}
engines: {node: '>=14.0.0'}
+ resolution: {integrity: sha512-6QD0ilzDDt93tX44y8tbmZdAcdTRYDhUP+Asgi6pC8Pp5IA3cvaZGyoVN/EGtlq9ziT65iPuBBn3ASLr6hCgVw==}
+ engines: {node: '>=20.0.0'}
+
resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==}
engines: {node: '>= 0.4'}
@@ -4340,6 +4421,10 @@ packages:
resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}
engines: {node: '>=0.8.19'}
+ resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
@@ -5017,6 +5102,10 @@ packages:
resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-IPZ167aShDZZUMdRk66cyQAW3qr0WzbHkPdMYa8bzZhlHhO3jALbKdxcaak7W9FfT2rZNpQuUu4Od7ILEpXSaw==}
engines: {node: 20 || >=22}
@@ -5607,6 +5696,10 @@ packages:
engines: {node: '>=14'}
hasBin: true
+ resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==}
+ engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0}
+
resolution: {integrity: sha512-4yf0QO/sllf/1zbZWYnvWw3NxCQwLXKzIj0G849LSufP15BXKM0rbD2Z3wVnkMfjdn/CB0Dpp444gYAACdsplg==}
engines: {node: '>=18'}
@@ -5700,6 +5793,9 @@ packages:
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
+ resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==}
+
resolution: {integrity: sha512-AJt0lAIkItWEZRA5d/mO+Om4nPCuTiQ0saA+qItO967DTjmGjnhmF+Bi2tL286mOTfBlF5CyLzJ35KTMaDoH+A==}
peerDependencies:
@@ -5791,6 +5887,10 @@ packages:
resolution: {integrity: sha512-cjwII1MdIIVloKvC9ErQ+OgAtwHBmcZ0Bg4ciz78FtbT8In39aAYbaA7zvxQ61xVMSPE8WxhLwLbhif4Js2C+g==}
+ resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==}
engines: {node: '>= 0.4'}
@@ -6193,6 +6293,10 @@ packages:
resolution: {integrity: sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==}
engines: {node: '>=0.10.0'}
@@ -6697,6 +6801,10 @@ packages:
webpack-cli:
optional: true
+ resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}
@@ -6769,6 +6877,18 @@ packages:
utf-8-validate:
optional: true
+ resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==}
+ engines: {node: '>=10.0.0'}
+ peerDependencies:
+ bufferutil: ^4.0.1
+ utf-8-validate: '>=5.0.2'
+ peerDependenciesMeta:
+ bufferutil:
+ optional: true
+ utf-8-validate:
+ optional: true
+
resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
engines: {node: '>=0.4'}
@@ -6845,6 +6965,8 @@ packages:
snapshots:
+ '@adobe/[email protected]': {}
+
'@alloc/[email protected]': {}
'@ampproject/[email protected]':
@@ -9018,6 +9140,40 @@ snapshots:
postcss-selector-parser: 6.0.10
tailwindcss: 3.4.14
+ '@testing-library/[email protected]':
+ dependencies:
+ '@babel/code-frame': 7.27.1
+ '@babel/runtime': 7.26.9
+ '@types/aria-query': 5.0.4
+ aria-query: 5.3.0
+ dom-accessibility-api: 0.5.16
+ lz-string: 1.5.0
+ picocolors: 1.1.1
+ pretty-format: 27.5.1
+
+ '@testing-library/[email protected]':
+ dependencies:
+ '@adobe/css-tools': 4.5.0
+ aria-query: 5.3.2
+ css.escape: 1.5.1
+ dom-accessibility-api: 0.6.3
+ picocolors: 1.1.1
+ redent: 3.0.0
+
+ dependencies:
+ '@babel/runtime': 7.26.9
+ '@testing-library/dom': 10.4.1
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.12
+ '@types/react-dom': 18.3.1
+
+ '@testing-library/[email protected](@testing-library/[email protected])':
+ dependencies:
+ '@testing-library/dom': 10.4.1
+
'@ts-morph/[email protected]':
dependencies:
fast-glob: 3.3.3
@@ -9034,6 +9190,8 @@ snapshots:
tslib: 2.8.1
optional: true
+ '@types/[email protected]': {}
+
dependencies:
'@types/deep-eql': 4.0.2
@@ -9142,6 +9300,12 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.8.1
+
dependencies:
'@eslint-community/regexpp': 4.12.1
@@ -9645,6 +9809,8 @@ snapshots:
dependencies:
color-convert: 2.0.1
+
@@ -9664,6 +9830,10 @@ snapshots:
dependencies:
tslib: 2.8.1
+ dependencies:
+ dequal: 2.0.3
+
@@ -9840,6 +10010,10 @@ snapshots:
+ dependencies:
+ '@types/node': 22.8.1
+
dependencies:
base64-js: 1.5.1
@@ -10071,6 +10245,8 @@ snapshots:
+
@@ -10188,6 +10364,10 @@ snapshots:
dependencies:
esutils: 2.0.3
+
+
dependencies:
domelementtype: 2.3.0
@@ -10276,6 +10456,8 @@ snapshots:
+
@@ -11133,6 +11315,19 @@ snapshots:
- encoding
- supports-color
+ dependencies:
+ '@types/node': 22.8.1
+ '@types/whatwg-mimetype': 3.0.2
+ '@types/ws': 8.18.1
+ buffer-image-size: 0.6.4
+ entities: 7.0.1
+ whatwg-mimetype: 3.0.0
+ ws: 8.21.0
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
+
@@ -11289,6 +11484,8 @@ snapshots:
+
@@ -12209,6 +12406,8 @@ snapshots:
optional: true
+
dependencies:
'@isaacs/brace-expansion': 5.0.0
@@ -12762,6 +12961,12 @@ snapshots:
+ dependencies:
+ ansi-regex: 5.0.1
+ ansi-styles: 5.2.0
+ react-is: 17.0.2
+
dependencies:
parse-ms: 4.0.0
@@ -12882,6 +13087,8 @@ snapshots:
+
dependencies:
clsx: 2.1.1
@@ -13007,6 +13214,11 @@ snapshots:
unified: 11.0.5
vfile: 6.0.3
+ dependencies:
+ indent-string: 4.0.0
+ strip-indent: 3.0.0
+
dependencies:
call-bind: 1.0.8
@@ -13599,6 +13811,10 @@ snapshots:
+ dependencies:
+ min-indent: 1.0.1
+
optional: true
@@ -14087,7 +14303,7 @@ snapshots:
tsx: 4.19.4
yaml: 2.9.0
dependencies:
'@types/chai': 5.2.2
'@vitest/expect': 3.2.4
@@ -14115,6 +14331,7 @@ snapshots:
optionalDependencies:
'@types/debug': 4.1.12
'@types/node': 22.8.1
+ happy-dom: 20.10.6
transitivePeerDependencies:
- jiti
- less
@@ -14182,6 +14399,8 @@ snapshots:
- esbuild
- uglify-js
+
dependencies:
tr46: 0.0.3
@@ -14273,6 +14492,8 @@ snapshots:
+
diff --git a/src/app/(app)/components/__tests__/invoice-pdf-download-link.test.tsx b/src/app/(app)/components/__tests__/invoice-pdf-download-link.test.tsx
new file mode 100644
index 0000000..fd9731c
--- /dev/null
+++ b/src/app/(app)/components/__tests__/invoice-pdf-download-link.test.tsx
@@ -0,0 +1,332 @@
+// @vitest-environment happy-dom
+
+import { getInitialInvoiceData } from "@/app/constants";
+import { CTAToastProvider } from "@/app/(app)/contexts/cta-toast-context";
+import { CTA_TOAST_TIMEOUT } from "@/app/(app)/components/cta-toasts";
+import { LOADING_BUTTON_TEXT } from "@/app/(app)/components/invoice-form";
+import { DeviceContextProvider } from "@/contexts/device-context";
+import type { InvoiceData } from "@/app/schema";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import "@testing-library/jest-dom/vitest";
+
+const { mockUpdatePdfInstance, mockPdfStateRef, resetMockPdfState } =
+ vi.hoisted(() => {
+ const mockUpdatePdfInstance = vi.fn();
+
+ const mockPdfStateRef = {
+ current: {
+ loading: false,
+ url: "blob:http://localhost/fake-pdf" as string | null,
+ error: null as Error | null,
+ },
+ };
+
+ const resetMockPdfState = () => {
+ mockPdfStateRef.current = {
+ loading: false,
+ url: "blob:http://localhost/fake-pdf",
+ error: null,
+ };
+ };
+
+ return { mockUpdatePdfInstance, mockPdfStateRef, resetMockPdfState };
+ });
+
+vi.mock("@react-pdf/renderer/lib/react-pdf.browser", async (importOriginal) => {
+ const actual = await importOriginal();
+
+ return {
+ ...(actual as object),
+ usePDF: () => [mockPdfStateRef.current, mockUpdatePdfInstance],
+ };
+});
+
+vi.mock("@/lib/umami-analytics-track-event", () => ({
+ umamiTrackEvent: vi.fn(),
+}));
+
+vi.mock("@sentry/nextjs", () => ({
+ captureException: vi.fn(),
+}));
+
+vi.mock("@/utils/is-telegram-in-app-browser", () => ({
+ isTelegramInAppBrowser: vi.fn(() => false),
+}));
+
+vi.mock("@/app/(app)/utils/get-app-metadata", () => ({
+ updateAppMetadata: vi.fn(),
+}));
+
+vi.mock("@/app/(app)/components/cta-toasts", async () => {
+ const actual = await vi.importActual("@/app/(app)/components/cta-toasts");
+
+ return {
+ ...(actual as object),
+ showRandomCTAToast: vi.fn(),
+ };
+});
+
+vi.mock("@/lib/haptic", () => ({
+ haptic: vi.fn(),
+}));
+
+vi.mock("@/components/ui/toasts/error-generating-pdf-toast", () => ({
+ ErrorGeneratingPdfToast: vi.fn(),
+}));
+
+vi.mock("sonner", () => ({
+ toast: Object.assign(vi.fn(), {
+ error: vi.fn(),
+ info: vi.fn(),
+ dismiss: vi.fn(),
+ }),
+}));
+
+import { InvoicePDFDownloadLink } from "../invoice-pdf-download-link";
+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
+import * as Sentry from "@sentry/nextjs";
+import { isTelegramInAppBrowser } from "@/utils/is-telegram-in-app-browser";
+import { updateAppMetadata } from "@/app/(app)/utils/get-app-metadata";
+import { showRandomCTAToast } from "@/app/(app)/components/cta-toasts";
+import { haptic } from "@/lib/haptic";
+import { ErrorGeneratingPdfToast } from "@/components/ui/toasts/error-generating-pdf-toast";
+import { toast } from "sonner";
+
+interface RenderOptions {
+ invoiceData?: InvoiceData;
+ errorWhileGeneratingPdfIsShown?: boolean;
+ setErrorWhileGeneratingPdfIsShown?: (error: boolean) => void;
+ qrCodeDataUrl?: string;
+ isMobile?: boolean;
+ inAppInfo?: { isInApp: boolean; name: string | null };
+}
+
+function renderInvoicePDFDownloadLink({
+ invoiceData = getInitialInvoiceData(),
+ errorWhileGeneratingPdfIsShown = false,
+ setErrorWhileGeneratingPdfIsShown = vi.fn(),
+ qrCodeDataUrl = "data:image/png;base64,abc",
+ isMobile = false,
+ inAppInfo = { isInApp: false, name: null },
+}: RenderOptions = {}) {
+ return render(
+ <TooltipProvider delayDuration={0}>
+ <DeviceContextProvider
+ isDesktop
+ isAndroid={false}
+ isMobile={isMobile}
+ inAppInfo={inAppInfo}
+ >
+ <CTAToastProvider>
+ <InvoicePDFDownloadLink
+ invoiceData={invoiceData}
+ errorWhileGeneratingPdfIsShown={errorWhileGeneratingPdfIsShown}
+ setErrorWhileGeneratingPdfIsShown={
+ setErrorWhileGeneratingPdfIsShown
+ }
+ qrCodeDataUrl={qrCodeDataUrl}
+ isMobile={isMobile}
+ />
+ </CTAToastProvider>
+ </DeviceContextProvider>
+ </TooltipProvider>,
+ );
+}
+
+function getDownloadLink() {
+ return screen.getByRole("link", { name: /Download PDF in/i });
+}
+
+describe("InvoicePDFDownloadLink", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetMockPdfState();
+ vi.mocked(isTelegramInAppBrowser).mockReturnValue(false);
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ });
+
+ it("should render download link with language label when PDF is ready", () => {
+ renderInvoicePDFDownloadLink();
+
+ expect(getDownloadLink()).toHaveTextContent("Download PDF in English");
+ });
+
+ it("should call updatePdfInstance when document mounts", () => {
+ renderInvoicePDFDownloadLink();
+
+ expect(mockUpdatePdfInstance).toHaveBeenCalledTimes(1);
+ });
+
+ it("should show loading state while PDF is generating", () => {
+ mockPdfStateRef.current = {
+ loading: true,
+ url: null,
+ error: null,
+ };
+
+ renderInvoicePDFDownloadLink();
+
+ const link = screen.getByRole("link", { name: LOADING_BUTTON_TEXT });
+
+ expect(within(link).getByText(LOADING_BUTTON_TEXT)).toBeInTheDocument();
+ expect(link).toHaveClass("pointer-events-none");
+ });
+
+ it("should set href and download attributes when PDF url is available", () => {
+ const invoiceData = {
+ ...getInitialInvoiceData(),
+ invoiceNumberObject: {
+ ...getInitialInvoiceData().invoiceNumberObject,
+ value: "01/2025",
+ },
+ };
+
+ renderInvoicePDFDownloadLink({ invoiceData });
+
+ const link = getDownloadLink();
+
+ expect(link).toHaveAttribute("href", "blob:http://localhost/fake-pdf");
+ expect(link).toHaveAttribute("download", "invoice-EN-01-2025.pdf");
+ });
+
+ it("should track download_invoice on successful click", async () => {
+ vi.useFakeTimers();
+
+ renderInvoicePDFDownloadLink();
+
+ fireEvent.click(getDownloadLink());
+
+ expect(haptic).toHaveBeenCalledTimes(1);
+ expect(umamiTrackEvent).toHaveBeenCalledWith("download_invoice", {
+ data: {
+ invoice_template: "default",
+ },
+ });
+ expect(updateAppMetadata).toHaveBeenCalledTimes(1);
+ expect(toast.dismiss).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(CTA_TOAST_TIMEOUT);
+
+ expect(showRandomCTAToast).toHaveBeenCalledTimes(1);
+ });
+
+ it("should show error toast when url is missing on click", async () => {
+ mockPdfStateRef.current = {
+ loading: false,
+ url: null,
+ error: null,
+ };
+
+ const user = userEvent.setup();
+
+ renderInvoicePDFDownloadLink();
+
+ await user.click(getDownloadLink());
+
+ expect(toast.error).toHaveBeenCalledWith(
+ "File not available. Please try again in different browser.",
+ expect.objectContaining({
+ id: "file-not-available-error-toast",
+ }),
+ );
+ expect(umamiTrackEvent).not.toHaveBeenCalled();
+ });
+
+ it("should block download inside in-app browser", async () => {
+ const user = userEvent.setup();
+
+ renderInvoicePDFDownloadLink({
+ inAppInfo: { isInApp: true, name: "Instagram" },
+ });
+
+ await user.click(getDownloadLink());
+
+ expect(toast).toHaveBeenCalledWith(
+ "Downloads are blocked inside Instagram. Open in your browser to save.",
+ expect.objectContaining({
+ id: "downloads-blocked-inside-app-toast",
+ }),
+ );
+ expect(umamiTrackEvent).not.toHaveBeenCalled();
+ });
+
+ it("should block download inside Telegram preview browser", async () => {
+ vi.mocked(isTelegramInAppBrowser).mockReturnValue(true);
+
+ const user = userEvent.setup();
+
+ renderInvoicePDFDownloadLink();
+
+ await user.click(getDownloadLink());
+
+ expect(toast).toHaveBeenCalledWith(
+ "Downloads are blocked inside Telegram. Open in your browser to save.",
+ expect.objectContaining({
+ id: "downloads-blocked-inside-telegram-toast",
+ }),
+ );
+ expect(umamiTrackEvent).not.toHaveBeenCalled();
+ });
+
+ it("should show in-app browser info toast on mount", () => {
+ renderInvoicePDFDownloadLink({
+ inAppInfo: { isInApp: true, name: "Facebook" },
+ });
+
+ expect(toast.info).toHaveBeenCalledWith(
+ "In-App Browser Detected",
+ expect.objectContaining({
+ id: "in-app-browser-toast",
+ }),
+ );
+ });
+
+ it("should show error generating PDF toast when PDF error occurs", () => {
+ const setErrorWhileGeneratingPdfIsShown = vi.fn();
+ const pdfError = new Error("PDF generation failed");
+
+ mockPdfStateRef.current = {
+ loading: false,
+ url: null,
+ error: pdfError,
+ };
+
+ renderInvoicePDFDownloadLink({
+ errorWhileGeneratingPdfIsShown: false,
+ setErrorWhileGeneratingPdfIsShown,
+ });
+
+ expect(ErrorGeneratingPdfToast).toHaveBeenCalledTimes(1);
+ expect(setErrorWhileGeneratingPdfIsShown).toHaveBeenCalledWith(true);
+ expect(umamiTrackEvent).toHaveBeenCalledWith(
+ "error_generating_document_link",
+ { data: { error: pdfError } },
+ );
+ expect(Sentry.captureException).toHaveBeenCalledWith(pdfError);
+ });
+
+ it("should show responsibility tooltip on hover", async () => {
+ const user = userEvent.setup();
+
+ renderInvoicePDFDownloadLink();
+
+ await user.hover(getDownloadLink());
+
+ expect(await screen.findByRole("tooltip")).toHaveTextContent(
+ "Your Responsibility",
+ );
+ });
+});
diff --git a/src/app/(app)/components/invoice-form/__tests__/calculate-item-totals.test.ts b/src/app/(app)/components/invoice-form/__tests__/calculate-item-totals.test.ts
new file mode 100644
index 0000000..c94a093
--- /dev/null
+++ b/src/app/(app)/components/invoice-form/__tests__/calculate-item-totals.test.ts
@@ -0,0 +1,301 @@
+import { describe, it, expect } from "vitest";
+import type { InvoiceItemData } from "@/app/schema";
+import { MOCK_INVOICE_ITEM_DATA } from "@/utils/__tests__/data";
+import { calculateItemTotals } from "../utils/calculate-item-totals";
+
+function createItem(overrides: Partial<InvoiceItemData> = {}): InvoiceItemData {
+ return {
+ ...MOCK_INVOICE_ITEM_DATA,
+ ...overrides,
+ };
+}
+
+describe("calculateItemTotals", () => {
+ describe("null / guard", () => {
+ it("returns null when item is null", () => {
+ expect(calculateItemTotals(null)).toBeNull();
+ });
+ });
+
+ describe("basic net amount", () => {
+ it("calculates netAmount as amount * netPrice", () => {
+ const result = calculateItemTotals(
+ createItem({ amount: 2, netPrice: 100.5, vat: 0 }),
+ );
+
+ expect(result?.netAmount).toBe(201);
+ expect(result?.vatAmount).toBe(0);
+ expect(result?.preTaxAmount).toBe(201);
+ });
+
+ it("coerces string amount and netPrice via Number()", () => {
+ const result = calculateItemTotals(
+ createItem({
+ amount: "3" as unknown as number,
+ netPrice: "10.50" as unknown as number,
+ vat: 0,
+ }),
+ );
+
+ expect(result?.netAmount).toBe(31.5);
+ expect(result?.vatAmount).toBe(0);
+ expect(result?.preTaxAmount).toBe(31.5);
+ });
+
+ it("falls back to 0 when amount is empty string", () => {
+ const result = calculateItemTotals(
+ createItem({
+ amount: "" as unknown as number,
+ netPrice: 100,
+ vat: 0,
+ }),
+ );
+
+ expect(result?.netAmount).toBe(0);
+ expect(result?.vatAmount).toBe(0);
+ expect(result?.preTaxAmount).toBe(0);
+ });
+
+ it("falls back to 0 when netPrice is empty string", () => {
+ const result = calculateItemTotals(
+ createItem({
+ amount: 5,
+ netPrice: "" as unknown as number,
+ vat: 0,
+ }),
+ );
+
+ expect(result?.netAmount).toBe(0);
+ expect(result?.vatAmount).toBe(0);
+ expect(result?.preTaxAmount).toBe(0);
+ });
+
+ it("falls back to 0 when amount and netPrice are invalid", () => {
+ const result = calculateItemTotals(
+ createItem({
+ amount: "abc" as unknown as number,
+ netPrice: "xyz" as unknown as number,
+ vat: 0,
+ }),
+ );
+
+ expect(result?.netAmount).toBe(0);
+ expect(result?.vatAmount).toBe(0);
+ expect(result?.preTaxAmount).toBe(0);
+ });
+ });
+
+ describe("VAT β€” numeric rates", () => {
+ it("calculates standard 23% VAT", () => {
+ const result = calculateItemTotals(
+ createItem({ amount: 2, netPrice: 100.5, vat: 23 }),
+ );
+
+ expect(result?.netAmount).toBe(201);
+ expect(result?.vatAmount).toBe(46.23);
+ expect(result?.preTaxAmount).toBe(247.23);
+ });
+
+ it("returns zero VAT for 0% rate as number", () => {
+ const result = calculateItemTotals(
+ createItem({ amount: 2, netPrice: 100, vat: 0 }),
+ );
+
+ expect(result?.netAmount).toBe(200);
+ expect(result?.vatAmount).toBe(0);
+ expect(result?.preTaxAmount).toBe(200);
+ });
+
+ it("returns zero VAT for 0% rate as string", () => {
+ const result = calculateItemTotals(
+ createItem({
+ amount: 2,
+ netPrice: 100,
+ vat: "0" as unknown as number,
+ }),
+ );
+
+ expect(result?.netAmount).toBe(200);
+ expect(result?.vatAmount).toBe(0);
+ expect(result?.preTaxAmount).toBe(200);
+ });
+
+ it("calculates 100% VAT", () => {
+ const result = calculateItemTotals(
+ createItem({ amount: 1, netPrice: 50, vat: 100 }),
+ );
+
+ expect(result?.netAmount).toBe(50);
+ expect(result?.vatAmount).toBe(50);
+ expect(result?.preTaxAmount).toBe(100);
+ });
+
+ it("accepts string numeric VAT", () => {
+ const result = calculateItemTotals(
+ createItem({
+ amount: 2,
+ netPrice: 100.5,
+ vat: "23" as unknown as number,
+ }),
+ );
+
+ expect(result?.netAmount).toBe(201);
+ expect(result?.vatAmount).toBe(46.23);
+ expect(result?.preTaxAmount).toBe(247.23);
+ });
+
+ it("accepts number VAT", () => {
+ const result = calculateItemTotals(
+ createItem({ amount: 1, netPrice: 100, vat: 23 }),
+ );
+
+ expect(result?.netAmount).toBe(100);
+ expect(result?.vatAmount).toBe(23);
+ expect(result?.preTaxAmount).toBe(123);
+ });
+ });
+
+ describe("VAT β€” non-numeric / exempt codes", () => {
+ it.each(["NP", "OO", "ZW", "EXEMPT"])(
+ "returns zero VAT for exempt code %s",
+ (vatCode) => {
+ const result = calculateItemTotals(
+ createItem({
+ amount: 2,
+ netPrice: 100,
+ vat: vatCode as unknown as number,
+ }),
+ );
+
+ expect(result?.netAmount).toBe(200);
+ expect(result?.vatAmount).toBe(0);
+ expect(result?.preTaxAmount).toBe(200);
+ },
+ );
+
+ it("returns zero VAT for empty string vat", () => {
+ const result = calculateItemTotals(
+ createItem({
+ amount: 2,
+ netPrice: 100,
+ vat: "" as unknown as number,
+ }),
+ );
+
+ expect(result?.netAmount).toBe(200);
+ expect(result?.vatAmount).toBe(0);
+ expect(result?.preTaxAmount).toBe(200);
+ });
+ });
+
+ describe("rounding", () => {
+ it("rounds netAmount to two decimal places", () => {
+ const result = calculateItemTotals(
+ createItem({ amount: 3, netPrice: 33.33, vat: 0 }),
+ );
+
+ expect(result?.netAmount).toBe(99.99);
+ });
+
+ it("rounds vatAmount to two decimal places", () => {
+ const result = calculateItemTotals(
+ createItem({ amount: 3, netPrice: 33.33, vat: 7 }),
+ );
+
+ expect(result?.netAmount).toBe(99.99);
+ expect(result?.vatAmount).toBe(7);
+ expect(result?.preTaxAmount).toBe(106.99);
+ });
+
+ it("rounds preTaxAmount from sum of rounded net and vat amounts", () => {
+ const result = calculateItemTotals(
+ createItem({ amount: 1, netPrice: 10.005, vat: 23 }),
+ );
+
+ expect(result?.netAmount).toBe(10.01);
+ expect(result?.vatAmount).toBe(2.3);
+ expect(result?.preTaxAmount).toBe(12.31);
+ });
+
+ it("handles floating-point multiplication edge cases", () => {
+ const result = calculateItemTotals(
+ createItem({ amount: 0.1, netPrice: 0.2, vat: 23 }),
+ );
+
+ expect(result?.netAmount).toBe(0.02);
+ expect(result?.vatAmount).toBe(0);
+ expect(result?.preTaxAmount).toBe(0.02);
+ });
+
+ it("rounds awkward VAT percentage on large net amount", () => {
+ const result = calculateItemTotals(
+ createItem({ amount: 7, netPrice: 14.29, vat: 8.5 }),
+ );
+
+ expect(result?.netAmount).toBe(100.03);
+ expect(result?.vatAmount).toBe(8.5);
+ expect(result?.preTaxAmount).toBe(108.53);
+ });
+ });
+
+ describe("field preservation", () => {
+ it("preserves unrelated item fields", () => {
+ const item = createItem({
+ name: "Custom Product",
+ unit: "kg",
+ typeOfGTU: "GTU_12",
+ nameFieldIsVisible: false,
+ amount: 1,
+ netPrice: 10,
+ vat: 23,
+ });
+
+ const result = calculateItemTotals(item);
+
+ expect(result?.name).toBe("Custom Product");
+ expect(result?.unit).toBe("kg");
+ expect(result?.typeOfGTU).toBe("GTU_12");
+ expect(result?.nameFieldIsVisible).toBe(false);
+ expect(result?.invoiceItemNumberIsVisible).toBe(true);
+ });
+
+ it("overwrites stale computed fields with recalculated values", () => {
+ const result = calculateItemTotals(
+ createItem({
+ amount: 2,
+ netPrice: 100.5,
+ vat: 23,
+ netAmount: 999,
+ vatAmount: 999,
+ preTaxAmount: 999,
+ }),
+ );
+
+ expect(result?.netAmount).toBe(201);
+ expect(result?.vatAmount).toBe(46.23);
+ expect(result?.preTaxAmount).toBe(247.23);
+ });
+ });
+
+ describe("integration-style case", () => {
+ it("matches MOCK_INVOICE_ITEM_DATA expected totals", () => {
+ const result = calculateItemTotals(createItem());
+
+ expect(result?.netAmount).toBe(201);
+ expect(result?.vatAmount).toBe(46.23);
+ expect(result?.preTaxAmount).toBe(247.23);
+ });
+
+ it("returns full item shape with all original fields plus computed totals", () => {
+ const item = createItem();
+ const result = calculateItemTotals(item);
+
+ expect(result).toEqual({
+ ...item,
+ netAmount: 201,
+ vatAmount: 46.23,
+ preTaxAmount: 247.23,
+ });
+ });
+ });
+});
diff --git a/src/app/(app)/components/invoice-form/__tests__/form-errors-to-toast.test.tsx b/src/app/(app)/components/invoice-form/__tests__/form-errors-to-toast.test.tsx
new file mode 100644
index 0000000..f07e574
--- /dev/null
+++ b/src/app/(app)/components/invoice-form/__tests__/form-errors-to-toast.test.tsx
@@ -0,0 +1,156 @@
+// @vitest-environment happy-dom
+
+import type { InvoiceData } from "@/app/schema";
+import type { FieldErrors } from "react-hook-form";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { render, screen } from "@testing-library/react";
+import type { ReactElement } from "react";
+import "@testing-library/jest-dom/vitest";
+
+vi.mock("sonner", () => ({
+ toast: Object.assign(vi.fn(), {
+ error: vi.fn(),
+ }),
+}));
+
+import { toast } from "sonner";
+import { formErrorsToToast } from "../utils/form-errors-to-toast";
+
+function renderToastContent(content: unknown) {
+ render(content as ReactElement);
+}
+
+describe("formErrorsToToast", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.resetAllMocks();
+ });
+
+ it("does not call toast.error when errors object is empty", () => {
+ formErrorsToToast({ errors: {}, isMobile: false });
+
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it("shows flat field error messages", () => {
+ const errors = {
+ notes: { type: "required", message: "Notes are required" },
+ } satisfies FieldErrors<InvoiceData>;
+
+ formErrorsToToast({ errors, isMobile: false });
+
+ expect(toast.error).toHaveBeenCalledTimes(1);
+
+ const [content, options] = vi.mocked(toast.error).mock.calls[0];
+
+ renderToastContent(content);
+
+ expect(
+ screen.getByText("Please fix the following errors:"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Notes are required")).toBeInTheDocument();
+ expect(options).toEqual({
+ id: "form-errors-error-toast",
+ duration: 15_000,
+ position: "bottom-right",
+ });
+ });
+
+ it("shows nested object field error messages", () => {
+ const errors = {
+ seller: {
+ name: { type: "required", message: "Seller name is required" },
+ vatNo: { type: "required", message: "Seller VAT number is required" },
+ },
+ } satisfies FieldErrors<InvoiceData>;
+
+ formErrorsToToast({ errors, isMobile: false });
+
+ const [content] = vi.mocked(toast.error).mock.calls[0];
+ renderToastContent(content);
+
+ expect(screen.getByText("Seller name is required")).toBeInTheDocument();
+ expect(
+ screen.getByText("Seller VAT number is required"),
+ ).toBeInTheDocument();
+ });
+
+ it("shows array item field error messages", () => {
+ const errors = {
+ items: [
+ {
+ name: { type: "required", message: "Item name is required" },
+ amount: { type: "min", message: "Amount must be positive" },
+ },
+ {
+ netPrice: { type: "required", message: "Net price is required" },
+ },
+ ],
+ } satisfies FieldErrors<InvoiceData>;
+
+ formErrorsToToast({ errors, isMobile: false });
+
+ const [content] = vi.mocked(toast.error).mock.calls[0];
+ renderToastContent(content);
+
+ expect(screen.getByText("Item name is required")).toBeInTheDocument();
+ expect(screen.getByText("Amount must be positive")).toBeInTheDocument();
+ expect(screen.getByText("Net price is required")).toBeInTheDocument();
+ });
+
+ it("falls back to Unknown error when message is missing", () => {
+ const errors = {
+ notes: { type: "required" },
+ seller: {
+ name: { type: "required" },
+ },
+ items: [
+ {
+ name: { type: "required" },
+ },
+ ],
+ } as FieldErrors<InvoiceData>;
+
+ formErrorsToToast({ errors, isMobile: false });
+
+ const [content] = vi.mocked(toast.error).mock.calls[0];
+ renderToastContent(content);
+
+ expect(screen.getAllByText("Unknown error")).toHaveLength(3);
+ });
+
+ it("uses top-center position on mobile", () => {
+ const errors = {
+ notes: { type: "required", message: "Required" },
+ } as const satisfies FieldErrors<InvoiceData>;
+
+ formErrorsToToast({ errors, isMobile: true });
+
+ const [, options] = vi.mocked(toast.error).mock.calls[0];
+
+ expect(options).toEqual(
+ expect.objectContaining({
+ position: "top-center",
+ }),
+ );
+ });
+
+ it("uses bottom-right position on desktop", () => {
+ const errors = {
+ notes: { type: "required", message: "Required" },
+ } as const satisfies FieldErrors<InvoiceData>;
+
+ formErrorsToToast({ errors, isMobile: false });
+
+ const [, options] = vi.mocked(toast.error).mock.calls[0];
+
+ expect(options).toEqual(
+ expect.objectContaining({
+ position: "bottom-right",
+ }),
+ );
+ });
+});
diff --git a/src/app/(app)/components/invoice-form/__tests__/has-item-totals-changed.test.ts b/src/app/(app)/components/invoice-form/__tests__/has-item-totals-changed.test.ts
new file mode 100644
index 0000000..41e9ea9
--- /dev/null
+++ b/src/app/(app)/components/invoice-form/__tests__/has-item-totals-changed.test.ts
@@ -0,0 +1,103 @@
+import { describe, it, expect } from "vitest";
+import type { InvoiceItemData } from "@/app/schema";
+import { MOCK_INVOICE_ITEM_DATA } from "@/utils/__tests__/data";
+import {
+ hasAnyItemTotalsChanged,
+ hasItemTotalsChanged,
+} from "../utils/has-item-totals-changed";
+
+function createItem(overrides: Partial<InvoiceItemData> = {}) {
+ return {
+ ...MOCK_INVOICE_ITEM_DATA,
+ ...overrides,
+ } as const satisfies InvoiceItemData;
+}
+
+describe("hasItemTotalsChanged", () => {
+ it("returns false when item totals match calculated values", () => {
+ expect(hasItemTotalsChanged(createItem())).toBe(false);
+ });
+
+ it("returns true when netAmount is stale", () => {
+ expect(
+ hasItemTotalsChanged(
+ createItem({
+ netAmount: 999,
+ }),
+ ),
+ ).toBe(true);
+ });
+
+ it("returns true when vatAmount is stale", () => {
+ expect(
+ hasItemTotalsChanged(
+ createItem({
+ vatAmount: 999,
+ }),
+ ),
+ ).toBe(true);
+ });
+
+ it("returns true when preTaxAmount is stale", () => {
+ expect(
+ hasItemTotalsChanged(
+ createItem({
+ preTaxAmount: 999,
+ }),
+ ),
+ ).toBe(true);
+ });
+
+ it("returns true when input fields changed but totals were not recalculated", () => {
+ expect(
+ hasItemTotalsChanged(
+ createItem({
+ amount: 5,
+ netPrice: 100,
+ vat: 23,
+ netAmount: 201,
+ vatAmount: 46.23,
+ preTaxAmount: 247.23,
+ }),
+ ),
+ ).toBe(true);
+ });
+
+ it("returns true when vat changed but totals were not recalculated", () => {
+ expect(
+ hasItemTotalsChanged(
+ createItem({
+ vat: 8,
+ netAmount: 201,
+ vatAmount: 46.23,
+ preTaxAmount: 247.23,
+ }),
+ ),
+ ).toBe(true);
+ });
+});
+
+describe("hasAnyItemTotalsChanged", () => {
+ it("returns false for empty array", () => {
+ expect(hasAnyItemTotalsChanged([])).toBe(false);
+ });
+
+ it("returns false when all items are up to date", () => {
+ expect(hasAnyItemTotalsChanged([createItem(), createItem()])).toBe(false);
+ });
+
+ it("returns true when one item in a multi-item array is stale", () => {
+ expect(
+ hasAnyItemTotalsChanged([createItem(), createItem({ netAmount: 999 })]),
+ ).toBe(true);
+ });
+
+ it("returns true when all items are stale", () => {
+ expect(
+ hasAnyItemTotalsChanged([
+ createItem({ netAmount: 999 }),
+ createItem({ vatAmount: 999 }),
+ ]),
+ ).toBe(true);
+ });
+});
diff --git a/src/app/(app)/components/invoice-form/index.tsx b/src/app/(app)/components/invoice-form/index.tsx
index c2db2ce..ad4ee09 100644
--- a/src/app/(app)/components/invoice-form/index.tsx
+++ b/src/app/(app)/components/invoice-form/index.tsx
@@ -27,11 +27,14 @@ import { Textarea } from "@/components/ui/textarea";
import { CustomTooltip } from "@/components/ui/tooltip";
import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
import type { NonReadonly, Prettify } from "@/types";
+import { calculateItemTotals } from "./utils/calculate-item-totals";
+import { formErrorsToToast } from "./utils/form-errors-to-toast";
+import { hasAnyItemTotalsChanged } from "./utils/has-item-totals-changed";
import { zodResolver } from "@hookform/resolvers/zod";
import * as Sentry from "@sentry/nextjs";
import dayjs from "dayjs";
-import React, {
+import {
memo,
useCallback,
useEffect,
@@ -39,23 +42,17 @@ import React, {
type Dispatch,
type SetStateAction,
} from "react";
-import {
- Controller,
- useFieldArray,
- useForm,
- useWatch,
- type FieldErrors,
-} from "react-hook-form";
+import { Controller, useFieldArray, useForm, useWatch } from "react-hook-form";
import { toast } from "sonner";
import { useDebouncedCallback } from "use-debounce";
import { z } from "zod";
+import { updateAppMetadata } from "@/app/(app)/utils/get-app-metadata";
import { AlertIcon, ErrorMessage } from "./common";
import { BuyerInformation } from "./sections/buyer-information";
import { GeneralInformation } from "./sections/general-information";
import { InvoiceItems } from "./sections/invoice-items";
import { SellerInformation } from "./sections/seller-information";
-import { updateAppMetadata } from "@/app/(app)/utils/get-app-metadata";
export const LOADING_BUTTON_TIMEOUT = 400;
export const LOADING_BUTTON_TEXT = "Generating Document...";
@@ -159,16 +156,8 @@ export const InvoiceForm = memo(function InvoiceForm({
// Skip rest of calculations if no items
if (!invoiceItems?.length) return;
- // Check if any relevant values have changed
- const hasChanges = invoiceItems.some((item) => {
- const calculated = calculateItemTotals(item);
- return (
- calculated?.netAmount !== item.netAmount ||
- calculated?.vatAmount !== item.vatAmount ||
- calculated?.preTaxAmount !== item.preTaxAmount
- );
- });
- if (!hasChanges) return;
+ // if no item totals changed (netAmount, vatAmount, preTaxAmount), skip the rest of the calculations
+ if (!hasAnyItemTotalsChanged(invoiceItems)) return;
// Only update if there are actual changes
const updatedItems = invoiceItems
@@ -455,7 +444,7 @@ export const InvoiceForm = memo(function InvoiceForm({
{/* Final section */}
<div className="space-y-4" data-testid={`final-section`}>
<div className="">
- {/* Total field (with currency) */}
+ {/* Total field (with currency) (calculated automatically - read only field in the UI) */}
<div className="mt-5" />
<Label htmlFor={`total`} className="mb-1">
Total
@@ -884,102 +873,3 @@ export const InvoiceForm = memo(function InvoiceForm({
</form>
);
});
-
-const calculateItemTotals = (item: InvoiceItemData | null) => {
- if (!item) return null;
-
- const amount = Number(item.amount) || 0;
- const netPrice = Number(item.netPrice) || 0;
- const calculatedNetAmount = amount * netPrice;
- const formattedNetAmount = Number(calculatedNetAmount.toFixed(2));
-
- let vatAmount = 0;
-
- // item.vat always come as a string, so we need to convert it to a number ("23" -> 23) to calculate the VAT amount
- // it also can be not a number (e.g. "NP", "OO", etc), in this case we don't calculate the VAT amount and set it to 0
- if (item?.vat) {
- const vatValue = Number(item.vat);
- const isVatValueANumber = !Number.isNaN(vatValue);
-
- if (isVatValueANumber) {
- vatAmount = (formattedNetAmount * vatValue) / 100;
- }
- }
-
- const formattedVatAmount = Number(vatAmount.toFixed(2));
- const formattedPreTaxAmount = Number(
- (formattedNetAmount + formattedVatAmount).toFixed(2),
- );
-
- return {
- ...item,
- netAmount: formattedNetAmount,
- vatAmount: formattedVatAmount,
- preTaxAmount: formattedPreTaxAmount,
- };
-};
-
-const formErrorsToToast = ({
- errors,
- isMobile,
-}: {
- errors: FieldErrors<InvoiceData>;
- isMobile: boolean;
-}) => {
- // Return early if there are no errors
- if (!errors || Object.keys(errors).length === 0) {
- return;
- }
- toast.error(
- <div>
- <p className="font-semibold">Please fix the following errors:</p>
- <ul className="mt-1 list-inside list-disc">
- {Object.entries(errors)
- .map(([key, error]) => {
- // Handle nested errors (e.g., seller.name, items[0].name)
- if (error && typeof error === "object" && "message" in error) {
- return (
- <li key={key} className="text-sm">
- {error?.message || "Unknown error"}
- </li>
- );
- }
-
- // Handle array errors (e.g., items array)
- if (Array.isArray(error)) {
- return error.map((item, index) =>
- Object.entries(
- item as { [key: string]: { message?: string } },
- ).map(([fieldName, fieldError]) => (
- <li key={`${key}.${index}.${fieldName}`} className="text-sm">
- {fieldError?.message || "Unknown error"}
- </li>
- )),
- );
- }
-
- // Handle nested object errors
- if (error && typeof error === "object") {
- return Object.entries(
- error as { [key: string]: { message?: string } },
- ).map(([nestedKey, nestedError]) => {
- return (
- <li key={`${key}.${nestedKey}`} className="text-sm">
- {nestedError?.message || "Unknown error"}
- </li>
- );
- });
- }
-
- return null;
- })
- .flat(Infinity)}
- </ul>
- </div>,
- {
- id: "form-errors-error-toast",
- duration: 15_000,
- position: isMobile ? "top-center" : "bottom-right",
- },
- );
-};
diff --git a/src/app/(app)/components/invoice-form/sections/invoice-items.tsx b/src/app/(app)/components/invoice-form/sections/invoice-items.tsx
index 2ba3ead..f4a4379 100644
--- a/src/app/(app)/components/invoice-form/sections/invoice-items.tsx
+++ b/src/app/(app)/components/invoice-form/sections/invoice-items.tsx
@@ -594,7 +594,7 @@ export const InvoiceItems = memo(function InvoiceItems({
) : null}
</div>
- {/* Invoice Item Net Amount (calculated automatically) */}
+ {/* Invoice Item Net Amount (calculated automatically - read only) */}
<Controller
name={`items.${index}.netAmount`}
control={control}
@@ -628,7 +628,7 @@ export const InvoiceItems = memo(function InvoiceItems({
)}
</div>
- {/* Invoice Item Tax Amount (calculated automatically) */}
+ {/* Invoice Item Tax Amount (calculated automatically - read only) */}
<div>
<div className="mb-2 flex items-center justify-between">
<Label htmlFor={`itemVatAmount${index}`} className="">
@@ -701,7 +701,7 @@ export const InvoiceItems = memo(function InvoiceItems({
)}
</div>
- {/* Pre-tax Amount field */}
+ {/* Pre-tax Amount field (calculated automatically - read only) */}
<div>
<div className="mb-2 flex items-center justify-between">
<Label htmlFor={`itemPreTaxAmount${index}`} className="">
diff --git a/src/app/(app)/components/invoice-form/utils/calculate-item-totals.ts b/src/app/(app)/components/invoice-form/utils/calculate-item-totals.ts
new file mode 100644
index 0000000..cb3ceee
--- /dev/null
+++ b/src/app/(app)/components/invoice-form/utils/calculate-item-totals.ts
@@ -0,0 +1,54 @@
+import type { InvoiceItemData } from "@/app/schema";
+
+/**
+ * Calculates netAmount, vatAmount, and preTaxAmount for invoice item.
+ *
+ * - If item.vat is numeric (e.g. "23"), computes VAT as (netAmount * vat / 100).
+ * - If item.vat is not a number (e.g. "NP", "OO"), sets vatAmount to 0.
+ * - Rounds all computed amounts to two decimal places.
+ *
+ * @param item Invoice item to calculate totals for. Can be null.
+ * @returns InvoiceItemData with totals, or null if input is null.
+ */
+export function calculateItemTotals(
+ item: InvoiceItemData | null,
+): InvoiceItemData | null {
+ if (!item) return null;
+
+ const amount = Number(item.amount) || 0;
+ const netPrice = Number(item.netPrice) || 0;
+ const calculatedNetAmount = amount * netPrice;
+ const formattedNetAmount = Number(calculatedNetAmount.toFixed(2));
+
+ let vatAmount = 0;
+
+ // item.vat comes as a string, so we need to convert it to a number ("23" -> 23) to calculate the VAT amount
+ // it also can be not a number (e.g. "NP", "OO", etc), in this case we don't calculate the VAT amount and set it to 0
+ // If item.vat exists, check if numeric. If numeric, compute VAT as percent of net amount.
+ // Else, leave vatAmount as 0.
+ if (item?.vat) {
+ // Try to convert vat value to number (e.g., "23" -> 23)
+ const vatValue = Number(item.vat);
+
+ // Number.isNaN(vatValue) false means it's a valid number, true means non-number like "NP"
+ const isVatValueNumeric = !Number.isNaN(vatValue);
+
+ if (isVatValueNumeric) {
+ // Calculate VAT: net amount * (vat percentage / 100)
+ vatAmount = (formattedNetAmount * vatValue) / 100;
+ }
+ // If vat is not numeric ("NP", "OO"), VAT stays 0
+ }
+
+ const formattedVatAmount = Number(vatAmount.toFixed(2));
+ const formattedPreTaxAmount = Number(
+ (formattedNetAmount + formattedVatAmount).toFixed(2),
+ );
+
+ return {
+ ...item,
+ netAmount: formattedNetAmount,
+ vatAmount: formattedVatAmount,
+ preTaxAmount: formattedPreTaxAmount,
+ };
+}
diff --git a/src/app/(app)/components/invoice-form/utils/form-errors-to-toast.tsx b/src/app/(app)/components/invoice-form/utils/form-errors-to-toast.tsx
new file mode 100644
index 0000000..28b7475
--- /dev/null
+++ b/src/app/(app)/components/invoice-form/utils/form-errors-to-toast.tsx
@@ -0,0 +1,71 @@
+import type { InvoiceData } from "@/app/schema";
+import type { FieldErrors } from "react-hook-form";
+import { toast } from "sonner";
+
+/**
+ * Show toast listing form validation errors.
+ *
+ * @param errors - FieldErrors object from react-hook-form for InvoiceData
+ * @param isMobile - If true, UI adapted for mobile (unused here, but passed in)
+ */
+export function formErrorsToToast({
+ errors,
+ isMobile,
+}: {
+ errors: FieldErrors<InvoiceData>;
+ isMobile: boolean;
+}) {
+ if (!errors || Object.keys(errors).length === 0) {
+ return;
+ }
+
+ toast.error(
+ <div>
+ <p className="font-semibold">Please fix the following errors:</p>
+ <ul className="mt-1 list-inside list-disc">
+ {Object.entries(errors)
+ .map(([key, error]) => {
+ if (error && typeof error === "object" && "message" in error) {
+ return (
+ <li key={key} className="text-sm">
+ {error?.message || "Unknown error"}
+ </li>
+ );
+ }
+
+ if (Array.isArray(error)) {
+ return error.map((item, index) =>
+ Object.entries(
+ item as { [key: string]: { message?: string } },
+ ).map(([fieldName, fieldError]) => (
+ <li key={`${key}.${index}.${fieldName}`} className="text-sm">
+ {fieldError?.message || "Unknown error"}
+ </li>
+ )),
+ );
+ }
+
+ if (error && typeof error === "object") {
+ return Object.entries(
+ error as { [key: string]: { message?: string } },
+ ).map(([nestedKey, nestedError]) => {
+ return (
+ <li key={`${key}.${nestedKey}`} className="text-sm">
+ {nestedError?.message || "Unknown error"}
+ </li>
+ );
+ });
+ }
+
+ return null;
+ })
+ .flat(Infinity)}
+ </ul>
+ </div>,
+ {
+ id: "form-errors-error-toast",
+ duration: 15_000,
+ position: isMobile ? "top-center" : "bottom-right",
+ },
+ );
+}
diff --git a/src/app/(app)/components/invoice-form/utils/has-item-totals-changed.ts b/src/app/(app)/components/invoice-form/utils/has-item-totals-changed.ts
new file mode 100644
index 0000000..f37baaf
--- /dev/null
+++ b/src/app/(app)/components/invoice-form/utils/has-item-totals-changed.ts
@@ -0,0 +1,31 @@
+import type { InvoiceItemData } from "@/app/schema";
+import { calculateItemTotals } from "./calculate-item-totals";
+
+/**
+ * Check if calculated item totals (netAmount, vatAmount, preTaxAmount)
+ * differ from existing item's values.
+ *
+ * @param item InvoiceItemData to check for changes
+ * @returns true if any total value differs, false otherwise
+ */
+export function hasItemTotalsChanged(item: InvoiceItemData): boolean {
+ const calculated = calculateItemTotals(item);
+
+ return (
+ calculated?.netAmount !== item.netAmount ||
+ calculated?.vatAmount !== item.vatAmount ||
+ calculated?.preTaxAmount !== item.preTaxAmount
+ );
+}
+
+/**
+ * Check if any item in array has changed totals (netAmount, vatAmount, preTaxAmount).
+ *
+ * If any item has changed totals, we need to recalculate the totals for all items.
+ *
+ * @param items Array of InvoiceItemData
+ * @returns true if any item has changed totals, false otherwise
+ */
+export function hasAnyItemTotalsChanged(items: InvoiceItemData[]): boolean {
+ return items.some(hasItemTotalsChanged);
+}
diff --git a/src/app/(app)/error.tsx b/src/app/(app)/error.tsx
index f06bb99..59c0b8b 100644
--- a/src/app/(app)/error.tsx
+++ b/src/app/(app)/error.tsx
@@ -14,7 +14,7 @@ import {
} from "@/components/ui/alert-dialog";
import { useEffect } from "react";
import { toast } from "sonner";
-import { INITIAL_INVOICE_DATA } from "../constants";
+import { getInitialInvoiceData } from "../constants";
import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
import * as Sentry from "@sentry/nextjs";
import { ErrorMessage } from "@/components/etc/error-message";
@@ -97,7 +97,7 @@ export default function Error({
try {
localStorage.setItem(
PDF_DATA_LOCAL_STORAGE_KEY,
- JSON.stringify(INITIAL_INVOICE_DATA),
+ JSON.stringify(getInitialInvoiceData()),
);
localStorage.setItem(
diff --git a/src/app/(app)/page.client.tsx b/src/app/(app)/page.client.tsx
index 1332b60..899a684 100644
--- a/src/app/(app)/page.client.tsx
+++ b/src/app/(app)/page.client.tsx
@@ -1,6 +1,6 @@
"use client";
-import { INITIAL_INVOICE_DATA } from "@/app/constants";
+import { getInitialInvoiceData } from "@/app/constants";
import {
invoiceSchema,
METADATA_LOCAL_STORAGE_KEY,
@@ -210,19 +210,19 @@ export function AppPageClient({
if (templateValidation.success) {
// if no data in local storage and template is in url, set initial data with template from url
setInvoiceDataState({
- ...INITIAL_INVOICE_DATA,
+ ...getInitialInvoiceData(),
template: templateValidation.data,
});
} else {
// if no data in local storage, set initial data
- setInvoiceDataState(INITIAL_INVOICE_DATA);
+ setInvoiceDataState(getInitialInvoiceData());
}
}
} catch (error) {
console.error("Failed to load saved invoice data:", error);
// fallback to initial data on error
- setInvoiceDataState(INITIAL_INVOICE_DATA);
+ setInvoiceDataState(getInitialInvoiceData());
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.",
diff --git a/src/app/api/generate-invoice/__tests__/export-server-pdf.test.ts b/src/app/api/generate-invoice/__tests__/export-server-pdf.test.ts
new file mode 100644
index 0000000..ccf10c9
--- /dev/null
+++ b/src/app/api/generate-invoice/__tests__/export-server-pdf.test.ts
@@ -0,0 +1,59 @@
+// @vitest-environment node
+
+import fs from "node:fs";
+
+import { describe, expect, it, vi } from "vitest";
+
+import { SERVER_PDF_MOCK_INVOICE_DATA } from "./pdf-test-utils";
+
+vi.mock("@/env", () => ({
+ env: {
+ AUTH_TOKEN: "test-auth-token",
+ RESEND_API_KEY: "re_test_123",
+ UPSTASH_REDIS_REST_URL: "https://redis.test",
+ UPSTASH_REDIS_REST_TOKEN: "redis-token",
+ TELEGRAM_BOT_TOKEN: "telegram-token",
+ TELEGRAM_CHAT_ID: "telegram-chat-id",
+ SELLER_NAME: "Test Seller",
+ SELLER_ADDRESS: "Seller Address",
+ SELLER_VAT_NO: "SELLER-VAT",
+ SELLER_EMAIL: "[email protected]",
+ SELLER_ACCOUNT_NUMBER: "123456789",
+ SELLER_SWIFT_BIC: "TESTBIC",
+ BUYER_NAME: "Test Buyer",
+ BUYER_ADDRESS: "Buyer Address",
+ BUYER_VAT_NO: "BUYER-VAT",
+ BUYER_EMAIL: "[email protected]",
+ INVOICE_NET_PRICE: "1000",
+ INVOICE_EMAIL_RECIPIENT: "[email protected]",
+ INVOICE_EMAIL_COMPANY_TO: "[email protected]",
+ GOOGLE_DRIVE_PARENT_FOLDER_ID: "folder-123",
+ GOOGLE_DRIVE_CLIENT_EMAIL: "[email protected]",
+ GOOGLE_DRIVE_PRIVATE_KEY: "private-key",
+ GITHUB_TOKEN: "github-token",
+ NEXT_PUBLIC_SENTRY_DSN: "https://sentry.test",
+ },
+}));
+
+import {
+ getPolishInvoiceRealData,
+ renderInvoicePdfBuffer,
+} from "../render-pdf-on-server";
+
+const exportPath = process.env.PDF_EXPORT_PATH;
+const exportLanguage = process.env.PDF_EXPORT_LANG === "pl" ? "pl" : "en";
+
+// we run this test only on e2e (e2e/server-render-pdf.test.ts)
+describe.skipIf(!exportPath)("export server PDF for e2e", () => {
+ it("writes PDF buffer to disk", async () => {
+ const invoiceData =
+ exportLanguage === "pl"
+ ? getPolishInvoiceRealData(SERVER_PDF_MOCK_INVOICE_DATA)
+ : SERVER_PDF_MOCK_INVOICE_DATA;
+
+ const buffer = await renderInvoicePdfBuffer({ invoiceData });
+
+ expect(buffer.byteLength).toBeGreaterThan(0);
+ fs.writeFileSync(exportPath!, buffer);
+ });
+});
diff --git a/src/app/api/generate-invoice/__tests__/generate-invoice.test.ts b/src/app/api/generate-invoice/__tests__/generate-invoice.test.ts
new file mode 100644
index 0000000..46d743c
--- /dev/null
+++ b/src/app/api/generate-invoice/__tests__/generate-invoice.test.ts
@@ -0,0 +1,676 @@
+import { describe, it, expect, vi } from "vitest";
+import {
+ generateInvoice,
+ type GenerateInvoiceDeps,
+ type GenerateInvoiceInput,
+ type GenerateInvoiceReport,
+} from "../generate-invoice";
+import { MOCK_INVOICE_DATA } from "@/utils/__tests__/data";
+import type { Attachment } from "resend";
+
+// No vi.mock() here β€” all external boundaries are injected via deps.
+
+const EN_BUFFER = Buffer.from("en-pdf-content");
+const PL_BUFFER = Buffer.from("pl-pdf-content");
+
+const MOCK_GOOGLE_DRIVE = {};
+
+const MOCK_FOLDER = {
+ id: "folder-abc",
+ webViewLink: "https://drive.google.com/drive/folders/folder-abc",
+} as const;
+
+const MOCK_FOLDER_RESULT = {
+ folderToUploadInvoices: MOCK_FOLDER,
+ googleDriveFolderPath: "/2026/03.2026/invoices",
+} as const;
+
+const MOCK_UPLOADED_FILE = {
+ id: "file-123",
+ name: "invoice.pdf",
+ mimeType: "application/pdf",
+} as const;
+
+const MOCK_INPUT = {
+ shouldSendEmail: true,
+ shouldUploadToGoogleDrive: true,
+ parentFolderId: "parent-folder-id",
+ invoiceEmailCompanyTo: "[email protected]",
+ invoiceEmailRecipient: "[email protected]",
+ englishInvoiceData: MOCK_INVOICE_DATA,
+ polishInvoiceData: { ...MOCK_INVOICE_DATA, language: "pl" },
+} as const satisfies GenerateInvoiceInput;
+
+/**
+ * Factory function to build mocked dependencies for generateInvoice tests.
+ * Creates a complete set of mock functions with sensible defaults.
+ *
+ * @param overrides - Partial overrides to customize mock behavior for specific test cases
+ * @returns A fully typed GenerateInvoiceDeps object with all mocks configured
+ */
+function buildDeps(
+ overrides: Partial<GenerateInvoiceDeps> = {},
+): GenerateInvoiceDeps {
+ return {
+ renderEnInvoice: vi.fn().mockResolvedValue(EN_BUFFER),
+ renderPlInvoice: vi.fn().mockResolvedValue(PL_BUFFER),
+ initializeGoogleDrive: vi.fn().mockResolvedValue(MOCK_GOOGLE_DRIVE),
+ createOrFindInvoiceFolder: vi.fn().mockResolvedValue(MOCK_FOLDER_RESULT),
+ uploadFile: vi.fn().mockResolvedValue(MOCK_UPLOADED_FILE),
+ sendTelegramMessage: vi.fn().mockResolvedValue({ success: true }),
+ sendEmail: vi.fn().mockResolvedValue({ id: "email-123" }),
+ ...overrides,
+ };
+}
+
+describe("generateInvoice", () => {
+ describe("full success", () => {
+ it("should return ok:true when all steps succeed", async () => {
+ const deps = buildDeps();
+ const result = await generateInvoice(deps, MOCK_INPUT);
+
+ expect(result).toEqual(expect.objectContaining({ ok: true }));
+ });
+
+ it("should include a report with all fields true on full success", async () => {
+ const deps = buildDeps();
+ const result = await generateInvoice(deps, MOCK_INPUT);
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ ok: true,
+ report: {
+ invoiceENgeneratedSuccessfully: true,
+ invoicePLgeneratedSuccessfully: true,
+ savedToGoogleDrive: true,
+ notifiedByTelegram: true,
+ notifiedByEmail: true,
+ totalTimeTook: expect.any(
+ String,
+ ) as GenerateInvoiceReport["totalTimeTook"],
+ },
+ }),
+ );
+ });
+
+ it("should render both EN and PL invoices", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, MOCK_INPUT);
+
+ expect(deps.renderEnInvoice).toHaveBeenCalledTimes(1);
+ expect(deps.renderPlInvoice).toHaveBeenCalledTimes(1);
+ });
+
+ it("should upload both invoices to Google Drive with correct args", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, MOCK_INPUT);
+
+ expect(deps.uploadFile).toHaveBeenCalledTimes(2);
+ expect(deps.uploadFile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ googleDrive: MOCK_GOOGLE_DRIVE,
+ folderId: MOCK_FOLDER.id,
+ fileName: expect.stringMatching(/^invoice-EN-.+\.pdf$/) as string,
+ fileContent: expect.any(Buffer) as Buffer,
+ }),
+ );
+ expect(deps.uploadFile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ folderId: MOCK_FOLDER.id,
+ fileName: expect.stringMatching(/^invoice-PL-.+\.pdf$/) as string,
+ fileContent: expect.any(Buffer) as Buffer,
+ }),
+ );
+ });
+
+ it("should pass correct parentFolderId when finding the Drive folder", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, MOCK_INPUT);
+
+ expect(deps.createOrFindInvoiceFolder).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parentFolderId: MOCK_INPUT.parentFolderId,
+ month: expect.stringMatching(/^\d{2}$/) as string,
+ year: expect.stringMatching(/^\d{4}$/) as string,
+ }),
+ );
+ });
+
+ it("should send Telegram notification with 2 file attachments", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, MOCK_INPUT);
+
+ expect(deps.sendTelegramMessage).toHaveBeenCalledTimes(1);
+ const call = vi.mocked(deps.sendTelegramMessage).mock.calls[0][0];
+ expect(call.message).toContain("Invoices for");
+ expect(call.files).toHaveLength(2);
+ expect(call.files![0]).toMatchObject({
+ filename: expect.stringMatching(/^invoice-EN-.+\.pdf$/) as string,
+ buffer: expect.any(Buffer) as Buffer,
+ });
+ });
+
+ it("should send email with correct recipient and 2 attachments", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, MOCK_INPUT);
+
+ expect(deps.sendEmail).toHaveBeenCalledTimes(1);
+ expect(deps.sendEmail).toHaveBeenCalledWith(
+ expect.objectContaining({
+ to: MOCK_INPUT.invoiceEmailRecipient,
+ attachments: expect.arrayContaining([
+ expect.objectContaining({
+ filename: expect.stringMatching(/^invoice-EN-.+\.pdf$/) as string,
+ }),
+ expect.objectContaining({
+ filename: expect.stringMatching(/^invoice-PL-.+\.pdf$/) as string,
+ }),
+ ]) as Attachment[],
+ }),
+ );
+ expect(
+ vi.mocked(deps.sendEmail).mock.calls[0][0].attachments,
+ ).toHaveLength(2);
+ });
+
+ it("should upload before sending notifications (ordering guarantee)", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, MOCK_INPUT);
+
+ // Get call order numbers for each uploadFile invocation
+ const uploadCalls = vi.mocked(deps.uploadFile).mock.invocationCallOrder;
+
+ // Last uploadFile() invocation (want to ensure all uploads precede notifications)
+ const lastUploadOrder = uploadCalls[uploadCalls.length - 1];
+
+ // Get call order numbers for the first sendTelegramMessage and sendEmail calls
+ const telegramOrder = vi.mocked(deps.sendTelegramMessage).mock
+ .invocationCallOrder[0];
+ const emailOrder = vi.mocked(deps.sendEmail).mock.invocationCallOrder[0];
+
+ // Assert each notification happens after all PDF uploads
+ expect(lastUploadOrder).toBeLessThan(telegramOrder);
+ expect(lastUploadOrder).toBeLessThan(emailOrder);
+ });
+ });
+
+ describe("sendEmail=false", () => {
+ it("should skip email but still send Telegram", async () => {
+ const deps = buildDeps();
+ const result = await generateInvoice(deps, {
+ ...MOCK_INPUT,
+ shouldSendEmail: false,
+ });
+
+ expect(result).toEqual(expect.objectContaining({ ok: true }));
+ expect(deps.sendEmail).not.toHaveBeenCalled();
+ expect(deps.sendTelegramMessage).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe("shouldUploadToGoogleDrive=false", () => {
+ it("should return ok:true without touching Google Drive", async () => {
+ const deps = buildDeps();
+ const result = await generateInvoice(deps, {
+ ...MOCK_INPUT,
+ shouldUploadToGoogleDrive: false,
+ });
+
+ expect(result).toEqual(expect.objectContaining({ ok: true }));
+ expect(deps.initializeGoogleDrive).not.toHaveBeenCalled();
+ expect(deps.createOrFindInvoiceFolder).not.toHaveBeenCalled();
+ expect(deps.uploadFile).not.toHaveBeenCalled();
+ });
+
+ it("should still render both PDFs", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, {
+ ...MOCK_INPUT,
+ shouldUploadToGoogleDrive: false,
+ });
+
+ expect(deps.renderEnInvoice).toHaveBeenCalledTimes(1);
+ expect(deps.renderPlInvoice).toHaveBeenCalledTimes(1);
+ });
+
+ it("should still send Telegram with attachments", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, {
+ ...MOCK_INPUT,
+ shouldUploadToGoogleDrive: false,
+ });
+
+ expect(deps.sendTelegramMessage).toHaveBeenCalledTimes(1);
+ const call = vi.mocked(deps.sendTelegramMessage).mock.calls[0][0];
+ expect(call.files).toHaveLength(2);
+ });
+
+ it("should omit Google Drive link from Telegram message", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, {
+ ...MOCK_INPUT,
+ shouldUploadToGoogleDrive: false,
+ });
+
+ const call = vi.mocked(deps.sendTelegramMessage).mock.calls[0][0];
+ expect(call.message).not.toContain("View in Google Drive");
+ expect(call.message).not.toContain("drive.google.com");
+ });
+
+ it("should still send email when shouldSendEmail=true", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, {
+ ...MOCK_INPUT,
+ shouldUploadToGoogleDrive: false,
+ });
+
+ expect(deps.sendEmail).toHaveBeenCalledTimes(1);
+ });
+
+ it("should omit Google Drive link from email HTML", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, {
+ ...MOCK_INPUT,
+ shouldUploadToGoogleDrive: false,
+ });
+
+ const emailCall = vi.mocked(deps.sendEmail).mock.calls[0][0];
+ expect(emailCall.html).not.toContain("View in Google Drive");
+ expect(emailCall.html).not.toContain("drive.google.com");
+ });
+
+ it("should skip email and Drive upload independently", async () => {
+ const deps = buildDeps();
+ const result = await generateInvoice(deps, {
+ ...MOCK_INPUT,
+ shouldSendEmail: false,
+ shouldUploadToGoogleDrive: false,
+ });
+
+ expect(result).toEqual(expect.objectContaining({ ok: true }));
+ expect(deps.uploadFile).not.toHaveBeenCalled();
+ expect(deps.sendEmail).not.toHaveBeenCalled();
+ expect(deps.sendTelegramMessage).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe("partial render failure", () => {
+ it("should succeed with 1 attachment when PL render fails", async () => {
+ const deps = buildDeps({
+ renderEnInvoice: vi.fn().mockResolvedValue(EN_BUFFER),
+ renderPlInvoice: vi
+ .fn()
+ .mockRejectedValueOnce(new Error("PL render failed")),
+ });
+ const result = await generateInvoice(deps, MOCK_INPUT);
+
+ expect(result).toEqual(expect.objectContaining({ ok: true }));
+ });
+
+ it("should upload only the EN invoice when PL render fails", async () => {
+ const deps = buildDeps({
+ renderEnInvoice: vi.fn().mockResolvedValue(EN_BUFFER),
+ renderPlInvoice: vi
+ .fn()
+ .mockRejectedValueOnce(new Error("PL render failed")),
+ });
+ await generateInvoice(deps, MOCK_INPUT);
+
+ expect(deps.uploadFile).toHaveBeenCalledTimes(1);
+ expect(deps.uploadFile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ fileName: expect.stringMatching(/^invoice-EN-.+\.pdf$/) as string,
+ }),
+ );
+ });
+
+ it("should send Telegram with 1 file when PL render fails", async () => {
+ const deps = buildDeps({
+ renderEnInvoice: vi.fn().mockResolvedValue(EN_BUFFER),
+ renderPlInvoice: vi
+ .fn()
+ .mockRejectedValueOnce(new Error("PL render failed")),
+ });
+ await generateInvoice(deps, MOCK_INPUT);
+
+ const call = vi.mocked(deps.sendTelegramMessage).mock.calls[0][0];
+ expect(call.files).toHaveLength(1);
+ });
+
+ it("should send email with 1 attachment when PL render fails", async () => {
+ const deps = buildDeps({
+ renderEnInvoice: vi.fn().mockResolvedValue(EN_BUFFER),
+ renderPlInvoice: vi
+ .fn()
+ .mockRejectedValueOnce(new Error("PL render failed")),
+ });
+ await generateInvoice(deps, MOCK_INPUT);
+
+ const emailCall = vi.mocked(deps.sendEmail).mock.calls[0][0];
+ expect(emailCall.attachments).toHaveLength(1);
+ });
+
+ it("should succeed with 1 attachment when EN render fails", async () => {
+ const deps = buildDeps({
+ renderEnInvoice: vi
+ .fn()
+ .mockRejectedValueOnce(new Error("EN render failed")),
+ renderPlInvoice: vi.fn().mockResolvedValue(PL_BUFFER),
+ });
+ const result = await generateInvoice(deps, MOCK_INPUT);
+
+ expect(result).toEqual(expect.objectContaining({ ok: true }));
+ expect(deps.uploadFile).toHaveBeenCalledTimes(1);
+ expect(deps.uploadFile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ fileName: expect.stringMatching(/^invoice-PL-.+\.pdf$/) as string,
+ }),
+ );
+ });
+ });
+
+ describe("all renders fail", () => {
+ it("should return no_attachments when both renders fail", async () => {
+ const deps = buildDeps({
+ renderEnInvoice: vi.fn().mockRejectedValueOnce(new Error("EN failed")),
+ renderPlInvoice: vi.fn().mockRejectedValueOnce(new Error("PL failed")),
+ });
+ const result = await generateInvoice(deps, MOCK_INPUT);
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ ok: false,
+ kind: "no_attachments",
+ error: expect.stringContaining("No attachments found") as string,
+ }),
+ );
+ });
+
+ it("should not call uploadFile when there are no attachments", async () => {
+ const deps = buildDeps({
+ renderEnInvoice: vi.fn().mockRejectedValueOnce(new Error("EN failed")),
+ renderPlInvoice: vi.fn().mockRejectedValueOnce(new Error("PL failed")),
+ });
+ await generateInvoice(deps, MOCK_INPUT);
+
+ expect(deps.uploadFile).not.toHaveBeenCalled();
+ expect(deps.sendTelegramMessage).not.toHaveBeenCalled();
+ expect(deps.sendEmail).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("upload failure", () => {
+ it("should return upload_failed when Google Drive initialization fails", async () => {
+ const deps = buildDeps({
+ initializeGoogleDrive: vi
+ .fn()
+ .mockRejectedValueOnce(new Error("Auth failed")),
+ });
+ const result = await generateInvoice(deps, MOCK_INPUT);
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ ok: false,
+ kind: "upload_failed",
+ error: expect.stringContaining(
+ "Failed to initialize Google Drive",
+ ) as string,
+ }),
+ );
+ expect(deps.uploadFile).not.toHaveBeenCalled();
+ expect(deps.sendTelegramMessage).not.toHaveBeenCalled();
+ expect(deps.sendEmail).not.toHaveBeenCalled();
+ });
+
+ it("should return upload_failed when folder creation fails", async () => {
+ const deps = buildDeps({
+ createOrFindInvoiceFolder: vi
+ .fn()
+ .mockRejectedValueOnce(new Error("Folder creation failed")),
+ });
+ const result = await generateInvoice(deps, MOCK_INPUT);
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ ok: false,
+ kind: "upload_failed",
+ error: expect.stringContaining(
+ "Failed to initialize Google Drive",
+ ) as string,
+ }),
+ );
+ expect(deps.uploadFile).not.toHaveBeenCalled();
+ expect(deps.sendTelegramMessage).not.toHaveBeenCalled();
+ expect(deps.sendEmail).not.toHaveBeenCalled();
+ });
+ it("should return upload_failed when one upload fails", async () => {
+ const deps = buildDeps({
+ uploadFile: vi
+ .fn()
+ .mockResolvedValueOnce(MOCK_UPLOADED_FILE)
+ .mockRejectedValueOnce(new Error("Upload failed")),
+ });
+ const result = await generateInvoice(deps, MOCK_INPUT);
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ ok: false,
+ kind: "upload_failed",
+ error: expect.stringContaining(
+ "Failed to upload invoices to Google Drive",
+ ) as string,
+ }),
+ );
+ });
+
+ it("should return upload_failed when all uploads fail", async () => {
+ const deps = buildDeps({
+ uploadFile: vi.fn().mockRejectedValue(new Error("Upload failed")),
+ });
+ const result = await generateInvoice(deps, MOCK_INPUT);
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ ok: false,
+ kind: "upload_failed",
+ error: expect.stringContaining(
+ "Failed to upload invoices to Google Drive",
+ ) as string,
+ }),
+ );
+ });
+
+ it("should not send notifications when uploads fail", async () => {
+ const deps = buildDeps({
+ uploadFile: vi.fn().mockRejectedValue(new Error("Upload failed")),
+ });
+ await generateInvoice(deps, MOCK_INPUT);
+
+ expect(deps.sendTelegramMessage).not.toHaveBeenCalled();
+ expect(deps.sendEmail).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("notification failure", () => {
+ it("should return notification_failed when Telegram fails", async () => {
+ const deps = buildDeps({
+ sendTelegramMessage: vi
+ .fn()
+ .mockRejectedValueOnce(new Error("Telegram error"))
+ .mockResolvedValue({ success: true }),
+ });
+ const result = await generateInvoice(deps, MOCK_INPUT);
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ ok: false,
+ kind: "notification_failed",
+ error: expect.stringContaining(
+ "Failed to generate and send invoice",
+ ) as string,
+ }),
+ );
+ });
+
+ it("should return notification_failed when email fails", async () => {
+ const deps = buildDeps({
+ sendEmail: vi.fn().mockRejectedValueOnce(new Error("Email error")),
+ });
+ const result = await generateInvoice(deps, MOCK_INPUT);
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ ok: false,
+ kind: "notification_failed",
+ error: expect.stringContaining(
+ "Failed to generate and send invoice",
+ ) as string,
+ }),
+ );
+ });
+
+ it("should send an error notification to Telegram when notifications fail", async () => {
+ const deps = buildDeps({
+ sendEmail: vi.fn().mockRejectedValueOnce(new Error("Email error")),
+ sendTelegramMessage: vi
+ .fn()
+ .mockResolvedValueOnce({ success: true }) // normal notification succeeds
+ .mockResolvedValueOnce({ success: true }), // error notification succeeds
+ });
+ await generateInvoice(deps, MOCK_INPUT);
+
+ // First call = normal notification, second = error notification
+ expect(deps.sendTelegramMessage).toHaveBeenCalledTimes(2);
+ const errorCall = vi.mocked(deps.sendTelegramMessage).mock.calls[1][0];
+ expect(errorCall.message).toContain("Error in generate-invoice");
+ });
+
+ it("should still return notification_failed even when error Telegram also fails", async () => {
+ const deps = buildDeps({
+ sendEmail: vi.fn().mockRejectedValueOnce(new Error("Email error")),
+ sendTelegramMessage: vi
+ .fn()
+ .mockResolvedValueOnce({ success: true })
+ .mockRejectedValueOnce(new Error("Error notification also failed")),
+ });
+ const result = await generateInvoice(deps, MOCK_INPUT);
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ ok: false,
+ kind: "notification_failed",
+ error: expect.stringContaining(
+ "Failed to generate and send invoice",
+ ) as string,
+ }),
+ );
+ });
+ });
+
+ describe("notification message content", () => {
+ it("should include updated links and Important section on full success", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, MOCK_INPUT);
+
+ const telegramCall = vi.mocked(deps.sendTelegramMessage).mock.calls[0][0];
+ expect(telegramCall.message).toContain("View invoice online");
+ expect(telegramCall.message).toContain("Submit to KSEF");
+ expect(telegramCall.message).toContain("Important - Don't forget to");
+ expect(telegramCall.message).toContain(
+ MOCK_FOLDER_RESULT.googleDriveFolderPath,
+ );
+ expect(telegramCall.message).toContain(MOCK_FOLDER.webViewLink);
+ expect(telegramCall.message).not.toContain("Test mode warning");
+ expect(telegramCall.message).not.toContain("Test mode warning ends here");
+
+ const emailCall = vi.mocked(deps.sendEmail).mock.calls[0][0];
+ expect(emailCall.html).toContain("View invoice online");
+ expect(emailCall.html).toContain("Submit to KSEF");
+ expect(emailCall.html).toContain(
+ MOCK_FOLDER_RESULT.googleDriveFolderPath,
+ );
+ expect(emailCall.html).not.toContain("Test mode warning");
+ });
+
+ it("should prepend test mode warning to Telegram when sendEmail=false", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, {
+ ...MOCK_INPUT,
+ shouldSendEmail: false,
+ });
+
+ const telegramCall = vi.mocked(deps.sendTelegramMessage).mock.calls[0][0];
+ expect(telegramCall.message).toContain("*Test mode warning:*");
+ expect(telegramCall.message).toContain("Test mode warning ends here");
+ expect(telegramCall.message).toContain("sendEmail=false");
+ expect(telegramCall.message).not.toContain("uploadToGoogleDrive=false");
+ });
+
+ it("should prepend test mode warning to Telegram when uploadToGoogleDrive=false", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, {
+ ...MOCK_INPUT,
+ shouldUploadToGoogleDrive: false,
+ });
+
+ const telegramCall = vi.mocked(deps.sendTelegramMessage).mock.calls[0][0];
+ expect(telegramCall.message).toContain("*Test mode warning:*");
+ expect(telegramCall.message).toContain("Test mode warning ends here");
+ expect(telegramCall.message).toContain("uploadToGoogleDrive=false");
+ expect(telegramCall.message).not.toContain("sendEmail=false");
+
+ const emailCall = vi.mocked(deps.sendEmail).mock.calls[0][0];
+ expect(emailCall.html).toContain("Test mode warning");
+ expect(emailCall.html).toContain("uploadToGoogleDrive=false");
+ expect(emailCall.html).not.toContain("Test mode warning ends here");
+ });
+
+ it("should include both test mode warnings when both flags are false", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, {
+ ...MOCK_INPUT,
+ shouldSendEmail: false,
+ shouldUploadToGoogleDrive: false,
+ });
+
+ const telegramCall = vi.mocked(deps.sendTelegramMessage).mock.calls[0][0];
+ expect(telegramCall.message).toContain("sendEmail=false");
+ expect(telegramCall.message).toContain("uploadToGoogleDrive=false");
+ expect(telegramCall.message).toContain("Test mode warning ends here");
+ });
+ });
+
+ describe("invoice filename format", () => {
+ it("should use englishInvoiceData invoice number in filename", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, MOCK_INPUT);
+
+ const formattedNumber =
+ MOCK_INVOICE_DATA.invoiceNumberObject.value.replace(/\//g, "-");
+
+ for (const call of vi.mocked(deps.uploadFile).mock.calls) {
+ expect(call[0].fileName).toContain(formattedNumber);
+ expect(call[0].fileName).not.toContain("/");
+ }
+ });
+
+ it("should replace slashes in invoice number with dashes in filename", async () => {
+ const deps = buildDeps();
+ await generateInvoice(deps, {
+ ...MOCK_INPUT,
+ englishInvoiceData: {
+ ...MOCK_INVOICE_DATA,
+ invoiceNumberObject: {
+ ...MOCK_INVOICE_DATA.invoiceNumberObject,
+ value: "1/07-2026",
+ },
+ },
+ });
+
+ for (const call of vi.mocked(deps.uploadFile).mock.calls) {
+ expect(call[0].fileName).toMatch(/invoice-(EN|PL)-1-07-2026\.pdf$/);
+ expect(call[0].fileName).not.toContain("/");
+ }
+ });
+ });
+});
diff --git a/src/app/api/generate-invoice/__tests__/pdf-test-utils.ts b/src/app/api/generate-invoice/__tests__/pdf-test-utils.ts
new file mode 100644
index 0000000..4116612
--- /dev/null
+++ b/src/app/api/generate-invoice/__tests__/pdf-test-utils.ts
@@ -0,0 +1,61 @@
+import { createRequire } from "node:module";
+import { pathToFileURL } from "node:url";
+
+import type { InvoiceData } from "@/app/schema";
+import { MOCK_INVOICE_DATA } from "@/utils/__tests__/data";
+import { pdfjs } from "react-pdf";
+import { expect } from "vitest";
+
+const require = createRequire(import.meta.url);
+
+pdfjs.GlobalWorkerOptions.workerSrc = pathToFileURL(
+ require.resolve("pdfjs-dist/build/pdf.worker.mjs"),
+).href;
+
+/** Invoice fixture for render-pdf-on-server.test.tsx β€” no logo. */
+export const SERVER_PDF_MOCK_INVOICE_DATA = {
+ ...MOCK_INVOICE_DATA,
+ logo: "",
+ invoiceType: "Reverse Charge",
+ notes: "Reverse Charge",
+ items: MOCK_INVOICE_DATA.items.map((item) => ({
+ ...item,
+ typeOfGTUFieldIsVisible: false,
+ invoiceItemNumberIsVisible: true,
+ name: "Software Development",
+ nameFieldIsVisible: true,
+ amount: 1,
+ amountFieldIsVisible: true,
+ unit: "service",
+ unitFieldIsVisible: true,
+ netPrice: 10000,
+ netPriceFieldIsVisible: true,
+ vat: "NP",
+ vatFieldIsVisible: true,
+ netAmount: 10000,
+ netAmountFieldIsVisible: true,
+ vatAmount: 0,
+ vatAmountFieldIsVisible: true,
+ preTaxAmount: 10000,
+ preTaxAmountFieldIsVisible: true,
+ })),
+ total: 10000,
+} satisfies InvoiceData;
+
+export function assertValidPdfBuffer(buffer: Buffer) {
+ expect(buffer.byteLength).toBeGreaterThan(1_000);
+ expect(buffer.subarray(0, 5).toString("ascii")).toBe("%PDF-");
+ expect(buffer.toString("ascii")).toContain("%%EOF");
+}
+
+export async function extractPdfText(buffer: Buffer): Promise<string> {
+ const doc = await pdfjs.getDocument({
+ data: new Uint8Array(buffer),
+ useWorkerFetch: false,
+ isEvalSupported: false,
+ }).promise;
+ const page = await doc.getPage(1);
+ const content = await page.getTextContent();
+
+ return content.items.map((item) => ("str" in item ? item.str : "")).join(" ");
+}
diff --git a/src/app/api/generate-invoice/__tests__/render-pdf-on-server.test.tsx b/src/app/api/generate-invoice/__tests__/render-pdf-on-server.test.tsx
new file mode 100644
index 0000000..ab4df3e
--- /dev/null
+++ b/src/app/api/generate-invoice/__tests__/render-pdf-on-server.test.tsx
@@ -0,0 +1,125 @@
+// @vitest-environment node
+
+import { INVOICE_PDF_TRANSLATIONS } from "@/app/(app)/pdf-i18n-translations/pdf-translations";
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ getPolishInvoiceRealData,
+ renderInvoicePdfBuffer,
+} from "../render-pdf-on-server";
+import {
+ assertValidPdfBuffer,
+ extractPdfText,
+ SERVER_PDF_MOCK_INVOICE_DATA,
+} from "./pdf-test-utils";
+
+vi.mock("@/env", () => ({
+ env: {
+ AUTH_TOKEN: "test-auth-token",
+ RESEND_API_KEY: "re_test_123",
+ UPSTASH_REDIS_REST_URL: "https://redis.test",
+ UPSTASH_REDIS_REST_TOKEN: "redis-token",
+ TELEGRAM_BOT_TOKEN: "telegram-token",
+ TELEGRAM_CHAT_ID: "telegram-chat-id",
+ SELLER_NAME: "Test Seller",
+ SELLER_ADDRESS: "Seller Address",
+ SELLER_VAT_NO: "SELLER-VAT",
+ SELLER_EMAIL: "[email protected]",
+ SELLER_ACCOUNT_NUMBER: "123456789",
+ SELLER_SWIFT_BIC: "TESTBIC",
+ BUYER_NAME: "Test Buyer",
+ BUYER_ADDRESS: "Buyer Address",
+ BUYER_VAT_NO: "BUYER-VAT",
+ BUYER_EMAIL: "[email protected]",
+ INVOICE_NET_PRICE: "1000",
+ INVOICE_EMAIL_RECIPIENT: "[email protected]",
+ INVOICE_EMAIL_COMPANY_TO: "[email protected]",
+ GOOGLE_DRIVE_PARENT_FOLDER_ID: "folder-123",
+ GOOGLE_DRIVE_CLIENT_EMAIL: "[email protected]",
+ GOOGLE_DRIVE_PRIVATE_KEY: "private-key",
+ GITHUB_TOKEN: "github-token",
+ NEXT_PUBLIC_SENTRY_DSN: "https://sentry.test",
+ },
+}));
+
+describe("renderInvoicePdfBuffer", () => {
+ it("should produce a valid English PDF buffer", async () => {
+ const buffer = await renderInvoicePdfBuffer({
+ invoiceData: SERVER_PDF_MOCK_INVOICE_DATA,
+ });
+
+ assertValidPdfBuffer(buffer);
+ });
+
+ it("should embed English invoice content in the PDF", async () => {
+ const buffer = await renderInvoicePdfBuffer({
+ invoiceData: SERVER_PDF_MOCK_INVOICE_DATA,
+ });
+ const text = await extractPdfText(buffer);
+
+ expect(text).toContain("ACME Corp");
+ expect(text).toContain("XYZ Ltd");
+ expect(text).toContain("INV-2024-001");
+ expect(text).toContain("Software Development");
+ });
+
+ it("should produce a valid Polish PDF buffer", async () => {
+ const polishInvoiceData = getPolishInvoiceRealData(
+ SERVER_PDF_MOCK_INVOICE_DATA,
+ );
+ const buffer = await renderInvoicePdfBuffer({
+ invoiceData: polishInvoiceData,
+ });
+
+ assertValidPdfBuffer(buffer);
+ });
+
+ it("should embed Polish invoice content in the PDF", async () => {
+ const polishInvoiceData = getPolishInvoiceRealData(
+ SERVER_PDF_MOCK_INVOICE_DATA,
+ );
+ const buffer = await renderInvoicePdfBuffer({
+ invoiceData: polishInvoiceData,
+ });
+ const text = await extractPdfText(buffer);
+
+ expect(text).toContain("ACME Corp");
+ expect(text).toContain("INV-2024-001");
+ expect(text).toContain("Odwrotne obciΔ…ΕΌenie");
+ expect(text).toContain("NIP");
+ });
+});
+
+describe("getPolishInvoiceRealData", () => {
+ it("should override language, invoice type, labels, and VAT fields", () => {
+ const polishInvoiceData = getPolishInvoiceRealData(
+ SERVER_PDF_MOCK_INVOICE_DATA,
+ );
+
+ expect(polishInvoiceData.language).toBe("pl");
+ expect(polishInvoiceData.invoiceType).toBe("Odwrotne obciΔ…ΕΌenie");
+ expect(polishInvoiceData.invoiceNumberObject?.label).toBe(
+ `${INVOICE_PDF_TRANSLATIONS.pl.invoiceNumber}:`,
+ );
+ expect(polishInvoiceData.invoiceNumberObject?.value).toBe("INV-2024-001");
+ expect(polishInvoiceData.buyer.vatNoLabelText).toBe("NIP");
+ expect(polishInvoiceData.seller.vatNoLabelText).toBe("NIP");
+ });
+
+ it("should preserve other invoice fields from English data", () => {
+ const polishInvoiceData = getPolishInvoiceRealData(
+ SERVER_PDF_MOCK_INVOICE_DATA,
+ );
+
+ expect(polishInvoiceData.seller.name).toBe(
+ SERVER_PDF_MOCK_INVOICE_DATA.seller.name,
+ );
+ expect(polishInvoiceData.buyer.name).toBe(
+ SERVER_PDF_MOCK_INVOICE_DATA.buyer.name,
+ );
+ expect(polishInvoiceData.items).toEqual(SERVER_PDF_MOCK_INVOICE_DATA.items);
+ expect(polishInvoiceData.dateOfIssue).toBe(
+ SERVER_PDF_MOCK_INVOICE_DATA.dateOfIssue,
+ );
+ });
+});
diff --git a/src/app/api/generate-invoice/__tests__/route.test.ts b/src/app/api/generate-invoice/__tests__/route.test.ts
new file mode 100644
index 0000000..a898ba6
--- /dev/null
+++ b/src/app/api/generate-invoice/__tests__/route.test.ts
@@ -0,0 +1,283 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+import type {
+ GenerateInvoiceResult,
+ GenerateInvoiceReport,
+} from "@/app/api/generate-invoice/generate-invoice";
+
+const MOCK_REPORT = {
+ invoiceENgeneratedSuccessfully: true,
+ invoicePLgeneratedSuccessfully: true,
+ savedToGoogleDrive: true,
+ notifiedByTelegram: true,
+ notifiedByEmail: true,
+ totalTimeTook: "1.23s",
+} as const satisfies GenerateInvoiceReport;
+
+const TEST_AUTH_TOKEN = "test-auth-token";
+
+const MOCK_ENV = {
+ AUTH_TOKEN: TEST_AUTH_TOKEN,
+ GOOGLE_DRIVE_PARENT_FOLDER_ID: "folder-123",
+ INVOICE_EMAIL_COMPANY_TO: "[email protected]",
+ INVOICE_EMAIL_RECIPIENT: "[email protected]",
+ RESEND_API_KEY: "re_test_123",
+ UPSTASH_REDIS_REST_URL: "https://redis.test",
+ UPSTASH_REDIS_REST_TOKEN: "redis-token",
+} as const;
+
+const mockRunProduction = vi.fn();
+const mockIpLimiterLimit = vi.fn();
+
+vi.mock("@/env", () => ({ env: { ...MOCK_ENV } }));
+
+vi.mock("../run-production-generate-invoice", () => ({
+ runProductionGenerateMonthlyInvoice: (...args: unknown[]) =>
+ mockRunProduction(...args) as unknown as Promise<GenerateInvoiceResult>,
+}));
+
+vi.mock("@/lib/rate-limit", () => ({
+ ipLimiter: {
+ limit: (...args: unknown[]) =>
+ mockIpLimiterLimit(...args) as unknown as Promise<{ success: boolean }>,
+ },
+}));
+
+function createRequest({
+ authToken,
+ searchParams,
+ forwardedFor,
+}: {
+ authToken?: string;
+ searchParams?: Record<string, string>;
+ forwardedFor?: string;
+} = {}) {
+ const url = new URL("http://localhost:3000/api/generate-invoice");
+ if (searchParams) {
+ for (const [key, value] of Object.entries(searchParams)) {
+ url.searchParams.set(key, value);
+ }
+ }
+ const headers = new Headers();
+ if (authToken) headers.set("Authorization", `Bearer ${authToken}`);
+ if (forwardedFor) headers.set("x-forwarded-for", forwardedFor);
+ return new NextRequest(url, { headers });
+}
+
+describe("GET /api/generate-invoice β€” HTTP layer", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe("authentication", () => {
+ it("should return 401 when Authorization header is missing", async () => {
+ const { GET } = await import("../route");
+ const response = await GET(createRequest());
+
+ expect(response.status).toBe(401);
+ expect(await response.text()).toBe("Unauthorized");
+ });
+
+ it("should return 401 when token is wrong", async () => {
+ const { GET } = await import("../route");
+ const response = await GET(createRequest({ authToken: "wrong-token" }));
+
+ expect(response.status).toBe(401);
+ expect(await response.text()).toBe("Unauthorized");
+ });
+
+ it("should not call runProductionGenerateMonthlyInvoice when unauthorized", async () => {
+ const { GET } = await import("../route");
+ await GET(createRequest());
+
+ expect(mockRunProduction).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("rate limiting", () => {
+ it("should return 429 when rate limit is exceeded", async () => {
+ mockIpLimiterLimit.mockResolvedValue({ success: false });
+
+ const { GET } = await import("../route");
+ const response = await GET(createRequest({ authToken: TEST_AUTH_TOKEN }));
+
+ expect(response.status).toBe(429);
+
+ const body = (await response.json()) as unknown as { error: string };
+
+ expect(body.error).toBe("Too many requests.");
+ });
+
+ it("should pass the x-forwarded-for IP to the rate limiter", async () => {
+ mockIpLimiterLimit.mockResolvedValue({ success: false });
+
+ const { GET } = await import("../route");
+ await GET(
+ createRequest({
+ authToken: TEST_AUTH_TOKEN,
+ forwardedFor: "203.0.113.42",
+ }),
+ );
+
+ expect(mockIpLimiterLimit).toHaveBeenCalledWith("203.0.113.42");
+ });
+
+ it("should fall back to 127.0.0.1 when x-forwarded-for is absent", async () => {
+ mockIpLimiterLimit.mockResolvedValue({ success: false });
+
+ const { GET } = await import("../route");
+ await GET(createRequest({ authToken: TEST_AUTH_TOKEN }));
+
+ expect(mockIpLimiterLimit).toHaveBeenCalledWith("127.0.0.1");
+ });
+
+ it("should not call runProductionGenerateMonthlyInvoice when rate limited", async () => {
+ mockIpLimiterLimit.mockResolvedValue({ success: false });
+
+ const { GET } = await import("../route");
+ await GET(createRequest({ authToken: TEST_AUTH_TOKEN }));
+
+ expect(mockRunProduction).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("response mapping", () => {
+ beforeEach(() => {
+ mockIpLimiterLimit.mockResolvedValue({ success: true });
+ });
+
+ it("should return 200 with success message and full report when runProductionGenerateMonthlyInvoice succeeds", async () => {
+ mockRunProduction.mockResolvedValue({ ok: true, report: MOCK_REPORT });
+
+ const { GET } = await import("../route");
+ const response = await GET(createRequest({ authToken: TEST_AUTH_TOKEN }));
+
+ expect(response.status).toBe(200);
+
+ const body = (await response.json()) as {
+ message: string;
+ report: GenerateInvoiceReport;
+ };
+
+ expect(body.message).toBe("Invoice generated and sent successfully");
+ expect(body.report).toEqual(MOCK_REPORT);
+ });
+
+ it("should return 400 when runProductionGenerateMonthlyInvoice returns no_attachments", async () => {
+ mockRunProduction.mockResolvedValue({
+ ok: false,
+ kind: "no_attachments",
+ error: "[generate-invoice] No attachments found",
+ report: MOCK_REPORT,
+ });
+
+ const { GET } = await import("../route");
+ const response = await GET(createRequest({ authToken: TEST_AUTH_TOKEN }));
+
+ expect(response.status).toBe(400);
+ const body = (await response.json()) as unknown as { error: string };
+ expect(body.error).toContain("No attachments found");
+ });
+
+ it("should return 500 when runProductionGenerateMonthlyInvoice returns upload_failed", async () => {
+ mockRunProduction.mockResolvedValue({
+ ok: false,
+ kind: "upload_failed",
+ error: "[generate-invoice] Failed to upload invoices to Google Drive",
+ report: MOCK_REPORT,
+ });
+
+ const { GET } = await import("../route");
+ const response = await GET(createRequest({ authToken: TEST_AUTH_TOKEN }));
+
+ expect(response.status).toBe(500);
+ const body = (await response.json()) as unknown as { error: string };
+ expect(body.error).toContain("Failed to upload invoices to Google Drive");
+ });
+
+ it("should return 500 when runProductionGenerateMonthlyInvoice returns notification_failed", async () => {
+ mockRunProduction.mockResolvedValue({
+ ok: false,
+ kind: "notification_failed",
+ error: "[generate-invoice] Failed to generate and send invoice",
+ report: MOCK_REPORT,
+ });
+
+ const { GET } = await import("../route");
+ const response = await GET(createRequest({ authToken: TEST_AUTH_TOKEN }));
+
+ expect(response.status).toBe(500);
+ const body = (await response.json()) as unknown as { error: string };
+ expect(body.error).toContain("Failed to generate and send invoice");
+ });
+
+ it("should return 500 when runProductionGenerateMonthlyInvoice throws unexpectedly", async () => {
+ mockRunProduction.mockRejectedValueOnce(new Error("Unexpected crash"));
+
+ const { GET } = await import("../route");
+ const response = await GET(createRequest({ authToken: TEST_AUTH_TOKEN }));
+
+ expect(response.status).toBe(500);
+ const body = (await response.json()) as unknown as { error: string };
+ expect(body.error).toContain("Failed to generate and send invoice");
+ });
+
+ it("should pass shouldSendEmail=false when query param is set", async () => {
+ mockRunProduction.mockResolvedValue({ ok: true, report: MOCK_REPORT });
+
+ const { GET } = await import("../route");
+ await GET(
+ createRequest({
+ authToken: TEST_AUTH_TOKEN,
+ searchParams: { sendEmail: "false" },
+ }),
+ );
+
+ const callOptions = mockRunProduction.mock.calls[0][0] as unknown as {
+ shouldSendEmail: boolean;
+ };
+ expect(callOptions.shouldSendEmail).toBe(false);
+ });
+
+ it("should pass shouldSendEmail=true by default", async () => {
+ mockRunProduction.mockResolvedValue({ ok: true, report: MOCK_REPORT });
+
+ const { GET } = await import("../route");
+ await GET(createRequest({ authToken: TEST_AUTH_TOKEN }));
+
+ const callOptions = mockRunProduction.mock.calls[0][0] as unknown as {
+ shouldSendEmail: boolean;
+ };
+ expect(callOptions.shouldSendEmail).toBe(true);
+ });
+
+ it("should pass shouldUploadToGoogleDrive=false when query param is set", async () => {
+ mockRunProduction.mockResolvedValue({ ok: true, report: MOCK_REPORT });
+
+ const { GET } = await import("../route");
+ await GET(
+ createRequest({
+ authToken: TEST_AUTH_TOKEN,
+ searchParams: { uploadToGoogleDrive: "false" },
+ }),
+ );
+
+ const callOptions = mockRunProduction.mock.calls[0][0] as {
+ shouldUploadToGoogleDrive: boolean;
+ };
+ expect(callOptions.shouldUploadToGoogleDrive).toBe(false);
+ });
+
+ it("should pass shouldUploadToGoogleDrive=true by default", async () => {
+ mockRunProduction.mockResolvedValue({ ok: true, report: MOCK_REPORT });
+
+ const { GET } = await import("../route");
+ await GET(createRequest({ authToken: TEST_AUTH_TOKEN }));
+
+ const callOptions = mockRunProduction.mock.calls[0][0] as {
+ shouldUploadToGoogleDrive: boolean;
+ };
+ expect(callOptions.shouldUploadToGoogleDrive).toBe(true);
+ });
+ });
+});
diff --git a/src/app/api/generate-invoice/generate-invoice.ts b/src/app/api/generate-invoice/generate-invoice.ts
new file mode 100644
index 0000000..bd4fbc8
--- /dev/null
+++ b/src/app/api/generate-invoice/generate-invoice.ts
@@ -0,0 +1,537 @@
+import { invoiceSchema, type InvoiceData } from "@/app/schema";
+import type { InvoiceFolderResult } from "@/lib/google-drive";
+import { compressInvoiceData } from "@/utils/url-compression";
+import dayjs from "dayjs";
+import type { drive_v3 } from "googleapis";
+import { compressToEncodedURIComponent } from "lz-string";
+import type { Attachment, CreateEmailResponse } from "resend";
+
+/**
+ * Formats milliseconds into a human-readable duration string.
+ * @param ms - Duration in milliseconds
+ * @returns Formatted string: "Xms" for durations under 1 second, or "X.XXs" for 1 second or more
+ * @example
+ * formatDuration(500) // "500ms"
+ * formatDuration(1234) // "1.23s"
+ */
+function formatDuration(ms: number): string {
+ if (ms < 1000) return `${Math.round(ms)}ms`;
+ return `${(ms / 1000).toFixed(2)}s`;
+}
+
+/**
+ * Per-step outcome summary returned alongside every `generateInvoice` result.
+ * `totalTimeTook` is a human-friendly duration string (e.g. "125ms" or "1.23s").
+ */
+export interface GenerateInvoiceReport {
+ invoiceENgeneratedSuccessfully: boolean;
+ invoicePLgeneratedSuccessfully: boolean;
+ savedToGoogleDrive: boolean;
+ notifiedByTelegram: boolean;
+ notifiedByEmail: boolean;
+ totalTimeTook: string;
+}
+
+/**
+ * Discriminated union representing all possible outcomes of `generateInvoice`.
+ *
+ * - `{ ok: true }` β€” everything succeeded.
+ * - `{ ok: false, kind: "no_attachments" }` β€” both PDF renders failed; nothing to send.
+ * - `{ ok: false, kind: "upload_failed" }` β€” at least one Google Drive upload failed.
+ * - `{ ok: false, kind: "notification_failed" }` β€” Telegram/email dispatch failed.
+ *
+ * Every variant includes a `report` with per-step outcomes and elapsed time.
+ */
+export type GenerateInvoiceResult =
+ | { ok: true; report: GenerateInvoiceReport }
+ | {
+ ok: false;
+ kind: "no_attachments";
+ error: string;
+ report: GenerateInvoiceReport;
+ }
+ | {
+ ok: false;
+ kind: "upload_failed";
+ error: string;
+ report: GenerateInvoiceReport;
+ }
+ | {
+ ok: false;
+ kind: "notification_failed";
+ error: string;
+ report: GenerateInvoiceReport;
+ };
+
+/**
+ * External side-effects injected into `generateInvoice`.
+ * Keeping them as explicit dependencies makes the function fully unit-testable
+ * without touching real Google Drive, Telegram, or Resend APIs.
+ */
+export interface GenerateInvoiceDeps {
+ /** Renders the English invoice PDF and resolves to its raw buffer. */
+ renderEnInvoice: () => Promise<Buffer>;
+ /** Renders the Polish invoice PDF and resolves to its raw buffer. */
+ renderPlInvoice: () => Promise<Buffer>;
+ /** Authenticates and returns an initialised Google Drive client. */
+ initializeGoogleDrive: () => Promise<drive_v3.Drive>;
+ /**
+ * Looks up or creates a month/year sub-folder inside `parentFolderId`.
+ * Idempotent β€” safe to call if the folder already exists.
+ */
+ createOrFindInvoiceFolder: (args: {
+ googleDrive: drive_v3.Drive;
+ parentFolderId: string;
+ month: string;
+ year: string;
+ }) => Promise<InvoiceFolderResult>;
+ /** Uploads a single file buffer to the given Drive folder. */
+ uploadFile: (args: {
+ googleDrive: drive_v3.Drive;
+ fileName: string;
+ fileContent: Buffer;
+ folderId: string;
+ }) => Promise<drive_v3.Schema$File>;
+ /**
+ * Sends a Telegram message, optionally attaching PDF files.
+ * Used both for the happy-path summary and for error alerts.
+ */
+ sendTelegramMessage: (args: {
+ message: string;
+ files?: Array<{ filename: string; buffer: Buffer }>;
+ }) => Promise<{ success: boolean }>;
+ /** Sends a Resend email with the invoice PDFs as attachments. */
+ sendEmail: (args: {
+ from: string;
+ to: string;
+ subject: string;
+ html: string;
+ attachments: Attachment[];
+ }) => Promise<CreateEmailResponse>;
+}
+
+/**
+ * Runtime configuration values passed to `generateInvoice` by the API route.
+ * Separating config from deps keeps the function signature clean and avoids
+ * leaking environment variables into tests.
+ */
+export interface GenerateInvoiceInput {
+ /** When `false`, the email step is skipped (useful for dry-run calls). */
+ shouldSendEmail: boolean;
+ /** When `false`, the Google Drive upload step is skipped (useful for dry-run calls). */
+ shouldUploadToGoogleDrive: boolean;
+ /** Google Drive folder ID that acts as the root for all invoice sub-folders. */
+ parentFolderId: string;
+ /** Email address of the client company β€” used to pre-fill the Outlook deeplink. */
+ invoiceEmailCompanyTo: string;
+ /** Personal email address that receives the invoice summary with attachments. */
+ invoiceEmailRecipient: string;
+ /** Validated invoice data for the English PDF (also used to build the preview URL). */
+ englishInvoiceData: InvoiceData;
+ /** Validated invoice data for the Polish PDF. */
+ polishInvoiceData: InvoiceData;
+}
+
+/**
+ * Core invoice generation pipeline.
+ *
+ * Orchestrates the full workflow in five sequential stages:
+ *
+ * 1. **Render PDFs** β€” generate EN and PL invoice buffers in parallel.
+ * 2. **Build attachments** β€” collect successful renders; abort if none succeeded.
+ * 3. **Upload to Google Drive** β€” store both PDFs in the current month's folder.
+ * 4. **Dispatch notifications** β€” send Telegram message (always) and email (optional).
+ * 5. **Return result** β€” resolve with `{ ok: true }` or a typed error variant.
+ *
+ * All side-effects are injected via `deps`, making the function fully testable.
+ *
+ * @param deps - Injectable side-effects (rendering, storage, messaging).
+ * @param input - Runtime configuration (flags, IDs, invoice data).
+ * @returns A discriminated-union result β€” never throws.
+ */
+export async function generateInvoice(
+ deps: GenerateInvoiceDeps,
+ input: GenerateInvoiceInput,
+): Promise<GenerateInvoiceResult> {
+ const startTime = performance.now();
+
+ const {
+ renderEnInvoice,
+ renderPlInvoice,
+ initializeGoogleDrive,
+ createOrFindInvoiceFolder,
+ uploadFile,
+ sendTelegramMessage,
+ sendEmail,
+ } = deps;
+
+ const {
+ shouldSendEmail,
+ shouldUploadToGoogleDrive,
+ parentFolderId,
+ invoiceEmailCompanyTo,
+ invoiceEmailRecipient,
+ englishInvoiceData,
+ } = input;
+
+ // ─── Step 1: Render PDFs ──────────────────────────────────────────────────
+ // Run both renders concurrently. `allSettled` ensures a failure in one
+ // language does not block the other β€” we can still send a partial result.
+ const renderStartTime = performance.now();
+
+ const renderedInvoices = await Promise.allSettled([
+ renderEnInvoice()
+ .then((buf) => ({ language: "en", document: buf }))
+ .catch((err) => {
+ console.error(
+ "[generate-invoice] Error during `renderToBuffer` for ENGLISH invoice:",
+ err,
+ );
+ throw err;
+ }),
+ renderPlInvoice()
+ .then((buf) => ({ language: "pl", document: buf }))
+ .catch((err) => {
+ console.error(
+ "[generate-invoice] Error during `renderToBuffer` for POLISH invoice:",
+ err,
+ );
+ throw err;
+ }),
+ ]);
+
+ console.log(
+ "[generate-invoice] PDF rendering completed in",
+ formatDuration(performance.now() - renderStartTime),
+ );
+
+ const invoiceENgeneratedSuccessfully =
+ renderedInvoices[0].status === "fulfilled";
+ const invoicePLgeneratedSuccessfully =
+ renderedInvoices[1].status === "fulfilled";
+
+ // Collect only the renders that succeeded; log and discard the rest.
+ const fulfilledInvoices: Array<{ language: string; document: Buffer }> = [];
+ for (const invoice of renderedInvoices) {
+ if (invoice.status === "fulfilled") {
+ fulfilledInvoices.push(invoice.value);
+ } else {
+ console.error(
+ "[generate-invoice] Error rendering invoice:",
+ invoice.reason ?? "Unknown error",
+ );
+ }
+ }
+
+ // ─── Step 2: Build email/Telegram attachments ─────────────────────────────
+ // Derive a filesystem-safe invoice number (replace "/" with "-").
+ // Falls back to "MM-YYYY" if invoice number is not provided in input data.
+ const invoiceNumber =
+ englishInvoiceData?.invoiceNumberObject?.value?.trim() || "";
+ const formattedInvoiceNumber = invoiceNumber
+ ? invoiceNumber.replace(/\//g, "-")
+ : dayjs().format("MM-YYYY");
+
+ const attachments = fulfilledInvoices.map((doc) => {
+ const fileName = `invoice-${doc.language.toUpperCase()}-${formattedInvoiceNumber}.pdf`;
+ return {
+ filename: fileName,
+ content: doc.document,
+ contentType: "application/pdf",
+ } satisfies Attachment;
+ });
+
+ // Guard: if every render failed, there is nothing to upload or send.
+ if (!attachments.length) {
+ return {
+ ok: false,
+ kind: "no_attachments",
+ error: "[generate-invoice] No attachments found",
+ report: {
+ invoiceENgeneratedSuccessfully,
+ invoicePLgeneratedSuccessfully,
+ savedToGoogleDrive: false,
+ notifiedByTelegram: false,
+ notifiedByEmail: false,
+ totalTimeTook: formatDuration(performance.now() - startTime),
+ },
+ };
+ }
+
+ // Build the shareable preview URL by compressing the validated invoice data
+ // into a URI-safe string understood by the easyinvoicepdf.com frontend.
+ const newInvoiceDataValidated = invoiceSchema.parse(englishInvoiceData);
+ const compressedKeys = compressInvoiceData(newInvoiceDataValidated);
+ const compressedJson = JSON.stringify(compressedKeys);
+ const compressedData = compressToEncodedURIComponent(compressedJson);
+ const invoiceUrl = `https://easyinvoicepdf.com/?template=${newInvoiceDataValidated.template}&data=${compressedData}`;
+
+ const monthAndYear = dayjs().format("MMMM YYYY");
+ const invoiceNumberValue = englishInvoiceData?.invoiceNumberObject?.value;
+
+ // ─── Step 3: Upload PDFs to Google Drive ─────────────────────────────────
+ let driveWebViewLink: string | null = null;
+ let googleDriveFolderPath: string | null = null;
+ let savedToGoogleDrive = false;
+
+ if (shouldUploadToGoogleDrive) {
+ try {
+ // Authenticate, then resolve (or create) the month/year folder in Drive.
+ const googleDrive = await initializeGoogleDrive();
+
+ const currentMonth = dayjs().format("MM");
+ const currentYear = dayjs().format("YYYY");
+
+ const folderResult = await createOrFindInvoiceFolder({
+ googleDrive,
+ parentFolderId,
+ month: currentMonth,
+ year: currentYear,
+ });
+
+ const { folderToUploadInvoices, googleDriveFolderPath: folderPath } =
+ folderResult;
+
+ driveWebViewLink = folderToUploadInvoices.webViewLink;
+ googleDriveFolderPath = folderPath;
+
+ // Upload all attachments in parallel; treat any failure as a hard error
+ // since missing files in Drive would break the audit trail.
+ const uploadStartTime = performance.now();
+
+ const uploadResults = await Promise.allSettled(
+ attachments.map((attachment) =>
+ uploadFile({
+ googleDrive,
+ fileName: attachment.filename,
+ fileContent: Buffer.from(attachment.content),
+ folderId: folderToUploadInvoices.id,
+ }),
+ ),
+ );
+
+ console.log(
+ "[generate-invoice] PDF uploading to Google Drive completed in",
+ formatDuration(performance.now() - uploadStartTime),
+ );
+
+ const failedUploads = uploadResults.filter(
+ (r): r is PromiseRejectedResult => r.status === "rejected",
+ );
+
+ if (failedUploads.length > 0) {
+ console.error(
+ "[generate-invoice] Some files failed to upload to Google Drive:",
+ failedUploads,
+ );
+ return {
+ ok: false,
+ kind: "upload_failed",
+ error: "[generate-invoice] Failed to upload invoices to Google Drive",
+ report: {
+ invoiceENgeneratedSuccessfully,
+ invoicePLgeneratedSuccessfully,
+ savedToGoogleDrive: false,
+ notifiedByTelegram: false,
+ notifiedByEmail: false,
+ totalTimeTook: formatDuration(performance.now() - startTime),
+ },
+ };
+ }
+
+ savedToGoogleDrive = true;
+ } catch (err) {
+ console.error("[generate-invoice] Google Drive setup failed:", err);
+
+ return {
+ ok: false,
+ kind: "upload_failed",
+ error: `[generate-invoice] Failed to initialize Google Drive: ${
+ err instanceof Error ? err.message : "Unknown error"
+ }`,
+ report: {
+ invoiceENgeneratedSuccessfully,
+ invoicePLgeneratedSuccessfully,
+ savedToGoogleDrive: false,
+ notifiedByTelegram: false,
+ notifiedByEmail: false,
+ totalTimeTook: formatDuration(performance.now() - startTime),
+ },
+ };
+ }
+ }
+
+ // ─── Step 4: Dispatch notifications ──────────────────────────────────────
+ // Pre-build an Outlook deeplink so the Telegram/email message contains a
+ // one-click shortcut to forward the invoice to the client company.
+ const companyEmailLink =
+ `https://outlook.office.com/mail/deeplink/compose` +
+ `?to=${encodeURIComponent(invoiceEmailCompanyTo)}` +
+ `&subject=${encodeURIComponent(`Invoice for ${monthAndYear}`)}` +
+ `&body=${encodeURIComponent(`Hello,\nThe invoice for ${monthAndYear} is in the attachment.\n\nHave a nice day.`)}`;
+
+ const testModeWarnings: string[] = [];
+
+ if (!shouldSendEmail) {
+ testModeWarnings.push("πŸ‘‰ Email sending *disabled* (`sendEmail=false`)");
+ }
+
+ if (!shouldUploadToGoogleDrive) {
+ testModeWarnings.push(
+ "πŸ‘‰ Google Drive upload *disabled* (`uploadToGoogleDrive=false`)",
+ );
+ }
+
+ const testModeWarningBlock =
+ testModeWarnings.length > 0
+ ? `\n\n⚠️⚠️⚠️ *Test mode warning:* ⚠️⚠️⚠️\n\n${testModeWarnings
+ .map((w) => `- ${w}`)
+ .join("\n")}\n\n⚠️⚠️⚠️ *Test mode warning ends here* ⚠️⚠️⚠️\n\n`
+ : "";
+
+ const telegramDriveSection =
+ driveWebViewLink && googleDriveFolderPath
+ ? `\n[View in Google Drive](${driveWebViewLink}) path: *${googleDriveFolderPath}*`
+ : "";
+
+ const emailDriveSection =
+ driveWebViewLink && googleDriveFolderPath
+ ? `<br/>\n <a href="${driveWebViewLink}">View in Google Drive</a> path: <b>${googleDriveFolderPath}</b>`
+ : "";
+
+ const emailGoogleDriveWarningHtml = !shouldUploadToGoogleDrive
+ ? `<p><b>⚠️ Test mode warning:</b> Google Drive upload disabled (<code>uploadToGoogleDrive=false</code>)</p><br/>`
+ : "";
+
+ // Telegram is always sent; email is conditional on the `shouldSendEmail` flag.
+ const notifications: Promise<unknown>[] = [
+ sendTelegramMessage({
+ message: `${testModeWarningBlock}πŸ“ *Invoices for ${monthAndYear}*
+
+Invoice No. of: *${invoiceNumberValue}*
+Date: *${dayjs().format("MMMM D, YYYY")}*
+
+The generated invoices are included in the attachments. Please check them carefully.
+
+[View invoice online](${invoiceUrl})${telegramDriveSection}
+
+*☝️ Important - Don't forget to:*
+- [Send email to company](${companyEmailLink})
+- [Submit to KSEF](https://ap.ksef.mf.gov.pl/web/)
+
+Have a nice day!
+
+Best regards,
+EasyInvoicePDF.com`,
+ files: attachments.map((attachment) => ({
+ filename: attachment.filename,
+ buffer: Buffer.from(attachment.content),
+ })),
+ }),
+ ];
+
+ if (shouldSendEmail) {
+ notifications.push(
+ sendEmail({
+ from: "Vlad from EasyInvoicePDF.com <[email protected]>",
+ to: invoiceEmailRecipient,
+ subject: `πŸ“ Invoices for ${monthAndYear}`,
+ html: `${emailGoogleDriveWarningHtml}<p>Hello,</p>
+ <span>Invoice No. of: <b>${invoiceNumberValue}</b><br/>
+ Date: <b>${dayjs().format("MMMM D, YYYY")}</b>
+ <br/>
+ <br/>
+
+ The generated invoices are included in the attachments. Please check them carefully.
+ <br/>
+ <br/>
+
+ <a href="${invoiceUrl}">View invoice online</a>${emailDriveSection}
+ <br/>
+ <br/>
+
+ <b>☝️ Important - Don't forget to:</b><br/>
+ - <a href="${companyEmailLink}"><b>Send these invoices via email to the company</b></a> for processing and payment<br/>
+ - <a href="https://ap.ksef.mf.gov.pl/web/"><b>Submit to KSEF</b></a>
+ <br/>
+ <br/>
+
+ Have a nice day!<br/><br/>
+ Best regards,<br/>EasyInvoicePDF.com</span>`,
+ attachments,
+ }),
+ );
+ }
+
+ // ─── Step 5: Handle notification failures ─────────────────────────────────
+ // Run all notifications concurrently. If any fail, send a Telegram error
+ // alert as a best-effort fallback before returning the error result.
+ const notificationStartTime = performance.now();
+
+ const notificationResults = await Promise.allSettled(notifications);
+
+ console.log(
+ "[generate-invoice] Notifications sending completed in",
+ formatDuration(performance.now() - notificationStartTime),
+ );
+
+ // notifications[0] is always Telegram; notifications[1] is email (when shouldSendEmail).
+ const notifiedByTelegram = notificationResults[0].status === "fulfilled";
+ const notifiedByEmail = shouldSendEmail
+ ? notificationResults[1]?.status === "fulfilled"
+ : false;
+
+ const failedNotifications = notificationResults.filter(
+ (r): r is PromiseRejectedResult => r.status === "rejected",
+ );
+
+ if (failedNotifications.length > 0) {
+ const errorMessage = `Some notifications failed to send:\n${JSON.stringify(
+ failedNotifications,
+ null,
+ 2,
+ )}`;
+
+ console.error(
+ "[generate-invoice] Error in generate-invoice:",
+ errorMessage,
+ );
+
+ try {
+ await sendTelegramMessage({
+ message: `🚨 Error in generate-invoice API route\n\n${errorMessage}`,
+ });
+ } catch (telegramError) {
+ console.error(
+ "Failed to send error notification to Telegram:",
+ telegramError,
+ );
+ }
+
+ return {
+ ok: false,
+ kind: "notification_failed",
+ error: "[generate-invoice] Failed to generate and send invoice",
+ report: {
+ invoiceENgeneratedSuccessfully,
+ invoicePLgeneratedSuccessfully,
+ savedToGoogleDrive,
+ notifiedByTelegram,
+ notifiedByEmail,
+ totalTimeTook: formatDuration(performance.now() - startTime),
+ },
+ };
+ }
+
+ return {
+ ok: true,
+ report: {
+ invoiceENgeneratedSuccessfully,
+ invoicePLgeneratedSuccessfully,
+ savedToGoogleDrive,
+ notifiedByTelegram,
+ notifiedByEmail,
+ totalTimeTook: formatDuration(performance.now() - startTime),
+ },
+ };
+}
diff --git a/src/app/api/generate-invoice/render-pdf-on-server.tsx b/src/app/api/generate-invoice/render-pdf-on-server.tsx
index 3301e59..1430af2 100644
--- a/src/app/api/generate-invoice/render-pdf-on-server.tsx
+++ b/src/app/api/generate-invoice/render-pdf-on-server.tsx
@@ -1,20 +1,15 @@
import { PDF_DEFAULT_TEMPLATE_STYLES } from "@/app/(app)/components/invoice-templates/invoice-pdf-default-template";
import { InvoiceBody } from "@/app/(app)/components/invoice-templates/invoice-pdf-default-template/invoice-body";
import { INVOICE_PDF_TRANSLATIONS } from "@/app/(app)/pdf-i18n-translations/pdf-translations";
-import {
- INVOICE_DEFAULT_NUMBER_VALUE,
- FIRST_DAY_OF_MONTH,
- LAST_DAY_OF_MONTH,
- PAYMENT_DUE,
- TODAY,
-} from "@/app/constants";
+import { getInvoiceDefaultNumberValue } from "@/app/constants";
import { type InvoiceData, type SupportedLanguages } from "@/app/schema";
import { INVOICE_PDF_FONTS } from "@/config";
import { env } from "@/env";
+import dayjs from "dayjs";
-// IMPORTANT: we use @react-pdf/renderer directly here, because we need to render the PDF on the server, not the client
+// IMPORTANT: it's fine to use this import directly on server side
// eslint-disable-next-line no-restricted-imports
-import { Document, Font, Page } from "@react-pdf/renderer";
+import { Document, Font, Page, renderToBuffer } from "@react-pdf/renderer";
// Open sans seems to be working fine with EN and PL
const fontFamily = "Open Sans";
@@ -38,7 +33,7 @@ Font.register({
*
* It is used to generate the PDF file for the invoice and is DUPLICATED from the frontend component (/invoice-pdf-template/index.tsx), due to technical limitations.
*/
-export const InvoicePdfTemplateToRenderOnBackend = ({
+const InvoicePdfTemplateToRenderOnBackend = ({
invoiceData,
}: {
invoiceData: InvoiceData;
@@ -63,6 +58,35 @@ export const InvoicePdfTemplateToRenderOnBackend = ({
);
};
+/**
+ * Renders invoice data to a PDF buffer for server-side (backend) usage.
+ *
+ * @param invoiceData - Data for invoice to be rendered.
+ */
+export function renderInvoicePdfBuffer({
+ invoiceData,
+}: {
+ invoiceData: InvoiceData;
+}) {
+ return renderToBuffer(
+ <InvoicePdfTemplateToRenderOnBackend invoiceData={invoiceData} />,
+ );
+}
+
+/**
+ * Returns translated invoice number label based on language.
+ *
+ * Example:
+ * ```typescript
+ * const invoiceNumberLabel = translateInvoiceNumberLabel({ language: "en" });
+ * // Returns: "Invoice Number:"
+ *
+ * const invoiceNumberLabel = translateInvoiceNumberLabel({ language: "pl" });
+ * // Returns: "Numer faktury:"
+ * ```
+ *
+ * @param language - Supported language key.
+ */
const translateInvoiceNumberLabel = ({
language,
}: {
@@ -75,24 +99,33 @@ const translateInvoiceNumberLabel = ({
const INVOICE_NET_PRICE = Number(env.INVOICE_NET_PRICE) || 0;
-export const ENGLISH_INVOICE_REAL_DATA = {
+/** Recomputed each call so warm servers do not reuse module-load dates. (to avoid outdated dates in the PDF) */
+function getInvoiceDefaultDates(): Pick<
+ InvoiceData,
+ "dateOfIssue" | "dateOfService" | "paymentDue" | "dateOfServiceStart"
+> {
+ const now = dayjs();
+ const lastDayOfMonth = now.endOf("month").format("YYYY-MM-DD");
+ const firstDayOfMonth = now.startOf("month").format("YYYY-MM-DD");
+
+ return {
+ dateOfIssue: now.format("YYYY-MM-DD"),
+ dateOfServiceStart: firstDayOfMonth,
+ dateOfService: lastDayOfMonth,
+ // Same as date of service: last day of the month as the default payment due date
+ paymentDue: lastDayOfMonth,
+ };
+}
+
+const ENGLISH_INVOICE_PROD_DATA_BASE = {
language: "en",
dateFormat: "YYYY-MM-DD",
currency: "EUR",
- invoiceNumberObject: {
- label: "Invoice No. of:",
- value: INVOICE_DEFAULT_NUMBER_VALUE,
- },
-
- dateOfIssue: TODAY,
- dateOfServiceStart: FIRST_DAY_OF_MONTH,
- dateOfService: LAST_DAY_OF_MONTH,
servicePeriodFieldIsVisible: false,
dateOfServiceFieldIsVisible: true,
servicePeriodLabelText: "Service period",
dateOfServiceLabelText: "Date of sales/of executing the service",
- paymentDue: PAYMENT_DUE,
invoiceType: "Reverse Charge",
invoiceTypeFieldIsVisible: true,
@@ -168,21 +201,65 @@ export const ENGLISH_INVOICE_REAL_DATA = {
template: "default",
taxLabelText: "VAT",
-} as const satisfies InvoiceData;
-
-export const POLISH_INVOICE_REAL_DATA = {
- ...ENGLISH_INVOICE_REAL_DATA,
- language: "pl",
- invoiceNumberObject: {
- label: translateInvoiceNumberLabel({ language: "pl" }),
- value: INVOICE_DEFAULT_NUMBER_VALUE,
- },
- buyer: {
- ...ENGLISH_INVOICE_REAL_DATA.buyer,
- vatNoLabelText: "NIP", // on polish invoices, we use "NIP" instead of "VAT"
- },
- seller: {
- ...ENGLISH_INVOICE_REAL_DATA.seller,
- vatNoLabelText: "NIP", // on polish invoices, we use "NIP" instead of "VAT"
- },
-} as const satisfies InvoiceData;
+} satisfies Omit<
+ InvoiceData,
+ | "dateOfIssue"
+ | "dateOfService"
+ | "paymentDue"
+ | "dateOfServiceStart"
+ | "invoiceNumberObject"
+>;
+
+/**
+ * **NOTE: Used only on server side**
+ *
+ * Returns **English invoice data** with current default dates.
+ *
+ * Spreads ENGLISH_INVOICE_PROD_DATA_BASE and injects freshly computed date fields
+ * using getInvoiceDefaultDates() on each call, ensuring no stale data due to
+ * serverless warm starts.
+ */
+export function getEnglishInvoiceRealData() {
+ return {
+ ...ENGLISH_INVOICE_PROD_DATA_BASE,
+ ...getInvoiceDefaultDates(), // IMPORTANT: recomputed each call so warm servers do not reuse module-load dates (to avoid outdated dates in the PDF)
+ invoiceNumberObject: {
+ label: "Invoice No. of:",
+ value: getInvoiceDefaultNumberValue(),
+ },
+ } as const satisfies InvoiceData;
+}
+
+/**
+ * **NOTE: Used only on server side**
+ *
+ * Returns **Polish invoice data** with current default dates.
+ *
+ * Spreads English invoice data and injects freshly computed **date fields**
+ * using getInvoiceDefaultDates() on each call, ensuring no stale data due to
+ * serverless warm starts.
+ *
+ * @param englishInvoiceData - English invoice data to spread.
+ */
+export function getPolishInvoiceRealData(englishInvoiceData: InvoiceData) {
+ return {
+ ...englishInvoiceData,
+ language: "pl",
+ // INFO: below we override some field translations for the Polish invoice data
+ invoiceType: "Odwrotne obciΔ…ΕΌenie",
+ invoiceNumberObject: {
+ label: translateInvoiceNumberLabel({ language: "pl" }),
+ value:
+ englishInvoiceData.invoiceNumberObject?.value ??
+ getInvoiceDefaultNumberValue(),
+ },
+ buyer: {
+ ...englishInvoiceData.buyer,
+ vatNoLabelText: "NIP",
+ },
+ seller: {
+ ...englishInvoiceData.seller,
+ vatNoLabelText: "NIP",
+ },
+ } as const satisfies InvoiceData;
+}
diff --git a/src/app/api/generate-invoice/route.tsx b/src/app/api/generate-invoice/route.tsx
index 07f8e85..d08f6c0 100644
--- a/src/app/api/generate-invoice/route.tsx
+++ b/src/app/api/generate-invoice/route.tsx
@@ -1,368 +1,66 @@
-import { INVOICE_DEFAULT_NUMBER_VALUE } from "@/app/constants";
-import { invoiceSchema } from "@/app/schema";
-import {
- createOrFindInvoiceFolder,
- initializeGoogleDrive,
- uploadFile,
- type GoogleDriveFile,
-} from "@/lib/google-drive";
-import { resend } from "@/lib/resend";
-import { sendTelegramMessage } from "@/lib/telegram";
-
-// eslint-disable-next-line no-restricted-imports
-import { renderToBuffer } from "@react-pdf/renderer";
-import dayjs from "dayjs";
-import { compressToEncodedURIComponent } from "lz-string";
import { NextResponse, type NextRequest } from "next/server";
-import type { Attachment } from "resend";
-
-import {
- ENGLISH_INVOICE_REAL_DATA,
- InvoicePdfTemplateToRenderOnBackend,
- POLISH_INVOICE_REAL_DATA,
-} from "./render-pdf-on-server";
import { env } from "@/env";
import { ipLimiter } from "@/lib/rate-limit";
-import { compressInvoiceData } from "@/utils/url-compression";
+import { runProductionGenerateMonthlyInvoice } from "./run-production-generate-invoice";
export const dynamic = "force-dynamic";
-// serverless function can run for max 30 seconds
-export const maxDuration = 30; // Set to 30 seconds
+// maxTimeout for the serverless function on vercel (30 seconds), max timeout is 300 seconds (5 minutes) atm per their docs
+// https://vercel.com/docs/functions/configuring-functions/duration
+export const maxDuration = 30;
export async function GET(req: NextRequest) {
try {
- // Check if the request is authorized
if (req.headers.get("Authorization") !== `Bearer ${env.AUTH_TOKEN}`) {
return new NextResponse("Unauthorized", { status: 401 });
}
- // Rate limiting
- const ip = req.headers.get("x-forwarded-for") || "127.0.0.1";
-
+ const ip = req.headers.get("x-forwarded-for") ?? "127.0.0.1";
const rateLimitResult = await ipLimiter.limit(ip);
if (!rateLimitResult.success) {
- console.log(`Rate limit exceeded for IP: ${ip}`);
-
- return new NextResponse(
- JSON.stringify({
- error: "Too many requests.",
- }),
- {
- status: 429,
- headers: {
- "Content-Type": "application/json",
- },
- },
- );
+ console.error(`Rate limit exceeded for IP: ${ip}`);
+ return new NextResponse(JSON.stringify({ error: "Too many requests." }), {
+ status: 429,
+ headers: { "Content-Type": "application/json" },
+ });
}
- /**
- * Determines if email notifications should be sent.
- * Defaults to true for backwards compatibility.
- * Can be disabled by passing ?sendEmail=false query parameter for testing.
- */
+ // Parse query parameters to control invoice generation behavior
+ // Both default to true (enabled) unless explicitly set to "false"
+ // This allows the endpoint to be used for testing without side effects
const shouldSendEmail =
req.nextUrl.searchParams.get("sendEmail") !== "false";
- /**
- * Determines if invoices should be saved to Google Drive.
- * Defaults to true for backwards compatibility.
- * Can be disabled by passing ?saveToGoogleDrive=false query parameter for testing.
- */
- const shouldSaveToGoogleDrive =
- req.nextUrl.searchParams.get("saveToGoogleDrive") !== "false";
-
- const testModeWarnings: string[] = [];
-
- if (!shouldSendEmail) {
- testModeWarnings.push("πŸ‘‰ Email sending *disabled* (`sendEmail=false`)");
- }
-
- if (!shouldSaveToGoogleDrive) {
- testModeWarnings.push(
- "πŸ‘‰ Google Drive upload *disabled* (`saveToGoogleDrive=false`)",
- );
- }
-
- const testModeWarningBlock =
- testModeWarnings.length > 0
- ? `\n\n⚠️⚠️⚠️ *Test mode warning:* ⚠️⚠️⚠️\n\n${testModeWarnings
- .map((w) => `- ${w}`)
- .join("\n")}\n\n------------------------------------\n`
- : "";
-
- const GENERATED_ENGLISH_INVOICE_PDF_DOCUMENT = renderToBuffer(
- <InvoicePdfTemplateToRenderOnBackend
- invoiceData={ENGLISH_INVOICE_REAL_DATA}
- />,
- ).catch((err) => {
- console.error(
- "\n\n_________________________[generate-invoice] Error during `renderToBuffer` for ENGLISH invoice:",
- err,
- );
-
- throw err;
- });
-
- const GENERATED_POLISH_INVOICE_PDF_DOCUMENT = renderToBuffer(
- <InvoicePdfTemplateToRenderOnBackend
- invoiceData={POLISH_INVOICE_REAL_DATA}
- />,
- ).catch((err) => {
- console.error(
- "\n\n_________________________[generate-invoice] Error during `renderToBuffer` for POLISH invoice:",
- err,
- );
+ const shouldUploadToGoogleDrive =
+ req.nextUrl.searchParams.get("uploadToGoogleDrive") !== "false";
- throw err;
+ const result = await runProductionGenerateMonthlyInvoice({
+ shouldSendEmail,
+ shouldUploadToGoogleDrive,
});
- const GENERATED_INVOICES =
- (await Promise.allSettled([
- GENERATED_ENGLISH_INVOICE_PDF_DOCUMENT.then((buf) => ({
- language: "en",
- document: buf,
- })),
- GENERATED_POLISH_INVOICE_PDF_DOCUMENT.then((buf) => ({
- language: "pl",
- document: buf,
- })),
- ]).catch((err) => {
- console.error(
- "\n\n_________________________Error during `Promise.allSettled`:",
- err,
- );
- })) || [];
+ // eslint-disable-next-line no-console
+ console.log("[generate-invoice] Report:", result.report);
- const fulfilledInvoices = [];
-
- for (const invoice of GENERATED_INVOICES) {
- if (invoice.status === "fulfilled") {
- fulfilledInvoices.push({
- language: invoice.value.language,
- document: invoice.value.document,
- });
- } else if (invoice.status === "rejected") {
- console.error(
- "\n\n_________________________Error in generate-invoice route:",
- invoice?.reason || "Unknown error",
- );
- }
- }
-
- // // Replace all slashes with dashes (e.g. 01/2025 -> 01-2025)
- const formattedInvoiceNumber = INVOICE_DEFAULT_NUMBER_VALUE
- ? INVOICE_DEFAULT_NUMBER_VALUE?.replace(/\//g, "-")
- : dayjs().format("MM-YYYY"); // Fallback to current month and year if no invoice number
-
- const ATTACHMENTS = fulfilledInvoices.map((document) => {
- const fileName = `invoice-${document.language.toUpperCase()}-${formattedInvoiceNumber}.pdf`;
-
- return {
- filename: fileName,
- content: document.document,
- contentType: "application/pdf",
- } satisfies Attachment;
- });
-
- if (!ATTACHMENTS.length) {
+ if (!result.ok) {
+ const status = result.kind === "no_attachments" ? 400 : 500;
return NextResponse.json(
- { error: "[generate-invoice] No attachments found" },
- { status: 400 },
+ { error: result.error, report: result.report },
+ { status },
);
}
- const newInvoiceDataValidated = invoiceSchema.parse(
- ENGLISH_INVOICE_REAL_DATA,
- );
-
- // Compress JSON keys before stringifying to reduce URL size
- const compressedKeys = compressInvoiceData(newInvoiceDataValidated);
- const compressedJson = JSON.stringify(compressedKeys);
-
- const compressedData = compressToEncodedURIComponent(compressedJson);
-
- const invoiceUrl = `https://easyinvoicepdf.com/?template=${newInvoiceDataValidated.template}&data=${compressedData}`;
-
- const monthAndYear = dayjs().format("MMMM YYYY");
-
- // *___________UPLOAD INVOICES TO GOOGLE DRIVE___________*
-
- let folderToUploadInvoices: GoogleDriveFile | null = null;
- let googleDriveFolderPath = "";
-
- if (shouldSaveToGoogleDrive) {
- // Initialize Google Drive
- const googleDrive = await initializeGoogleDrive();
-
- const currentMonth = dayjs().format("MM");
- const currentYear = dayjs().format("YYYY");
-
- // Create the month folder (this will automatically create/find the year folder)
- const result = await createOrFindInvoiceFolder({
- googleDrive,
- parentFolderId: env.GOOGLE_DRIVE_PARENT_FOLDER_ID,
- month: currentMonth,
- year: currentYear,
- });
-
- folderToUploadInvoices = result.folderToUploadInvoices;
- googleDriveFolderPath = result.googleDriveFolderPath;
-
- // Upload each invoice to Google Drive
- const uploadPromises = ATTACHMENTS.map((attachment) =>
- uploadFile({
- googleDrive,
- fileName: attachment.filename,
- fileContent: Buffer.from(attachment.content),
- folderId: folderToUploadInvoices!.id,
- }),
- );
-
- const uploadResults = await Promise.allSettled(uploadPromises);
- const failedUploads = uploadResults.filter(
- (result): result is PromiseRejectedResult =>
- result.status === "rejected",
- );
-
- if (failedUploads.length > 0) {
- console.error(
- "[generate-invoice] Some files failed to upload to Google Drive:",
- failedUploads,
- );
-
- return NextResponse.json(
- {
- error:
- "[generate-invoice] Failed to upload invoices to Google Drive",
- },
- { status: 500 },
- );
- }
- }
-
- const companyEmailLink =
- `https://outlook.office.com/mail/deeplink/compose` +
- `?to=${encodeURIComponent(env.INVOICE_EMAIL_COMPANY_TO)}` +
- `&subject=${encodeURIComponent(`Invoice for ${monthAndYear}`)}` +
- `&body=${encodeURIComponent(`Hello,\nThe invoice for ${monthAndYear} is in the attachment.\n\nHave a nice day.`)}`;
-
- // we only need the value of the invoice number e.g. 1/05.2025
- const invoiceNumberValue =
- ENGLISH_INVOICE_REAL_DATA?.invoiceNumberObject?.value;
-
- // *___________SEND NOTIFICATIONS___________*
-
- // Send notifications in parallel
- const notifications: Promise<unknown>[] = [
- sendTelegramMessage({
- message: `${testModeWarningBlock}πŸ“ *Invoices for ${monthAndYear}*
-
-Invoice No. of: *${invoiceNumberValue}*
-Date: *${dayjs().format("MMMM D, YYYY")}*
-
-The generated invoices are included in the attachments. Please check them carefully.
-
-[View invoice online](${invoiceUrl})${
- folderToUploadInvoices
- ? `\n[View in Google Drive](${folderToUploadInvoices.webViewLink}) path: *${googleDriveFolderPath}*`
- : ""
- }
-
-*☝️ Important - Don't forget to:*
-- [Send email to company](${companyEmailLink})
-- [Submit to KSEF](https://ap.ksef.mf.gov.pl/web/)
-
-Have a nice day!
-
-Best regards,
-EasyInvoicePDF.com`,
- files: ATTACHMENTS.map((attachment) => ({
- filename: attachment.filename,
- buffer: Buffer.from(attachment.content),
- })),
- }),
- ];
-
- if (shouldSendEmail) {
- notifications.push(
- resend.emails.send({
- from: "Vlad from EasyInvoicePDF.com <[email protected]>",
- to: env.INVOICE_EMAIL_RECIPIENT,
- subject: `πŸ“ Invoices for ${monthAndYear}`,
- html: `<p>Hello,</p>
- <span>Invoice No. of: <b>${invoiceNumberValue}</b><br/>
- Date: <b>${dayjs().format("MMMM D, YYYY")}</b>
- <br/>
- <br/>
-
- The generated invoices are included in the attachments. Please check them carefully.
- <br/>
- <br/>
-
- <a href="${invoiceUrl}">View invoice online</a>${
- folderToUploadInvoices
- ? `<br/>\n <a href="${folderToUploadInvoices.webViewLink}">View in Google Drive</a> path: <b>${googleDriveFolderPath}</b>`
- : ""
- }<br/>
- <br/>
- <br/>
-
- <b>☝️ Important - Don't forget to:</b><br/>
- - <a href="${companyEmailLink}"><b>Send these invoices via email to the company</b></a> for processing and payment<br/>
- - <a href="https://ap.ksef.mf.gov.pl/web/"><b>Submit to KSEF</b></a>
- <br/>
- <br/>
-
- Have a nice day!<br/><br/>
- Best regards,<br/>EasyInvoicePDF.com</span>`,
- attachments: ATTACHMENTS,
- }),
- );
- }
-
- const notificationResults = await Promise.allSettled(notifications);
-
- const failedNotifications = notificationResults.filter(
- (result): result is PromiseRejectedResult => result.status === "rejected",
- );
-
- if (failedNotifications.length > 0) {
- const errorMessage = `Some notifications failed to send:\n${JSON.stringify(
- failedNotifications,
- null,
- 2,
- )}`;
-
- console.error("[generate-invoice] Error in route:", errorMessage);
-
- // Send error to Telegram
- try {
- await sendTelegramMessage({
- message: `🚨 Error in generate-invoice API route\n\n${errorMessage}`,
- });
- } catch (telegramError) {
- console.error(
- "Failed to send error notification to Telegram:",
- telegramError,
- );
- }
-
- throw new Error("[generate-invoice] Failed to send notifications", {
- cause: errorMessage,
- });
- }
-
return NextResponse.json(
- { message: "Invoice sent successfully" },
+ {
+ message: "Invoice generated and sent successfully",
+ report: result.report,
+ },
{ status: 200 },
);
} catch (error) {
console.error("[generate-invoice] Error in route:", error);
-
return NextResponse.json(
{ error: "[generate-invoice] Failed to generate and send invoice" },
{ status: 500 },
diff --git a/src/app/api/generate-invoice/run-production-generate-invoice.ts b/src/app/api/generate-invoice/run-production-generate-invoice.ts
new file mode 100644
index 0000000..02ffd6c
--- /dev/null
+++ b/src/app/api/generate-invoice/run-production-generate-invoice.ts
@@ -0,0 +1,67 @@
+import type { InvoiceData } from "@/app/schema";
+import { env } from "@/env";
+import {
+ createOrFindInvoiceFolder,
+ initializeGoogleDrive,
+ uploadFile,
+} from "@/lib/google-drive";
+import { resend } from "@/lib/resend";
+import { sendTelegramMessage } from "@/lib/telegram";
+
+import {
+ generateInvoice,
+ type GenerateInvoiceDeps,
+ type GenerateInvoiceResult,
+} from "./generate-invoice";
+import {
+ getEnglishInvoiceRealData,
+ getPolishInvoiceRealData,
+ renderInvoicePdfBuffer,
+} from "./render-pdf-on-server";
+
+function buildGenerateInvoiceDeps(
+ englishInvoiceData: InvoiceData,
+ polishInvoiceData: InvoiceData,
+): GenerateInvoiceDeps {
+ return {
+ renderEnInvoice: () =>
+ renderInvoicePdfBuffer({ invoiceData: englishInvoiceData }),
+ renderPlInvoice: () =>
+ renderInvoicePdfBuffer({ invoiceData: polishInvoiceData }),
+ initializeGoogleDrive,
+
+ createOrFindInvoiceFolder,
+ uploadFile,
+ sendTelegramMessage,
+ sendEmail: (args) => resend.emails.send(args),
+ };
+}
+
+/**
+ * Runs production invoice generation pipeline.
+ *
+ * Orchestrates rendering PDFs, uploads to Google Drive, sends notifications.
+ *
+ * @param options.shouldSendEmail - Set true to send invoice email to recipient.
+ * @param options.shouldUploadToGoogleDrive - Set true to upload invoices to Google Drive.
+ */
+export async function runProductionGenerateMonthlyInvoice(options: {
+ shouldSendEmail: boolean;
+ shouldUploadToGoogleDrive: boolean;
+}): Promise<GenerateInvoiceResult> {
+ const englishInvoiceData = getEnglishInvoiceRealData();
+ const polishInvoiceData = getPolishInvoiceRealData(englishInvoiceData);
+
+ return generateInvoice(
+ buildGenerateInvoiceDeps(englishInvoiceData, polishInvoiceData),
+ {
+ shouldSendEmail: options.shouldSendEmail,
+ shouldUploadToGoogleDrive: options.shouldUploadToGoogleDrive,
+ parentFolderId: env.GOOGLE_DRIVE_PARENT_FOLDER_ID,
+ invoiceEmailCompanyTo: env.INVOICE_EMAIL_COMPANY_TO,
+ invoiceEmailRecipient: env.INVOICE_EMAIL_RECIPIENT,
+ englishInvoiceData,
+ polishInvoiceData,
+ },
+ );
+}
diff --git a/src/app/api/telegram-webhook/__tests__/route.test.ts b/src/app/api/telegram-webhook/__tests__/route.test.ts
new file mode 100644
index 0000000..e8cdb6c
--- /dev/null
+++ b/src/app/api/telegram-webhook/__tests__/route.test.ts
@@ -0,0 +1,282 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { NextRequest } from "next/server";
+import type {
+ GenerateInvoiceResult,
+ GenerateInvoiceReport,
+} from "@/app/api/generate-invoice/generate-invoice";
+
+const ALLOWED_CHAT_ID = 12345;
+const CHAT_ID = 67890;
+
+const MOCK_REPORT = {
+ invoiceENgeneratedSuccessfully: true,
+ invoicePLgeneratedSuccessfully: true,
+ savedToGoogleDrive: true,
+ notifiedByTelegram: true,
+ notifiedByEmail: true,
+ totalTimeTook: "1.23s",
+} as const satisfies GenerateInvoiceReport;
+
+const MOCK_ENV = {
+ TELEGRAM_CHAT_ID: String(ALLOWED_CHAT_ID),
+ TELEGRAM_BOT_TOKEN: "test-bot-token",
+} as const;
+
+const mockRunProduction = vi.fn();
+const mockSendTelegramMessage = vi.fn();
+const mockQueueInvoiceGeneration = vi.fn();
+const mockClearQueuedJob = vi.fn();
+
+const waitUntilPromises: Promise<unknown>[] = [];
+
+vi.mock("@/env", () => ({ env: { ...MOCK_ENV } }));
+
+vi.mock("@vercel/functions", () => ({
+ waitUntil: (promise: Promise<unknown>) => {
+ waitUntilPromises.push(promise);
+ },
+}));
+
+vi.mock("@/app/api/generate-invoice/run-production-generate-invoice", () => ({
+ runProductionGenerateMonthlyInvoice: (...args: unknown[]) =>
+ mockRunProduction(...args) as unknown as Promise<GenerateInvoiceResult>,
+}));
+
+vi.mock("@/lib/telegram", () => ({
+ sendTelegramMessage: (...args: unknown[]) =>
+ mockSendTelegramMessage(...args) as unknown as Promise<void>,
+}));
+
+vi.mock("@/app/api/telegram-webhook/lib/telegram-queue", () => ({
+ queueInvoiceGeneration: (...args: unknown[]) =>
+ mockQueueInvoiceGeneration(...args) as unknown as Promise<boolean>,
+ clearQueuedJob: (...args: unknown[]) =>
+ mockClearQueuedJob(...args) as unknown as Promise<void>,
+}));
+
+function createValidUpdate({
+ senderId = ALLOWED_CHAT_ID,
+ chatId = CHAT_ID,
+ text = "/generate",
+}: {
+ senderId?: number;
+ chatId?: number;
+ text?: string;
+} = {}) {
+ return {
+ update_id: 1,
+ message: {
+ message_id: 1,
+ from: {
+ id: senderId,
+ is_bot: false,
+ first_name: "Test",
+ },
+ chat: {
+ id: chatId,
+ type: "private",
+ },
+ date: 1_234_567_890,
+ text,
+ },
+ };
+}
+
+function createRequest(body: unknown) {
+ return new NextRequest("http://localhost:3000/api/telegram-webhook", {
+ method: "POST",
+ body: typeof body === "string" ? body : JSON.stringify(body),
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+async function flushWaitUntil() {
+ await Promise.all(waitUntilPromises);
+ waitUntilPromises.length = 0;
+}
+
+describe("POST /api/telegram-webhook β€” HTTP layer", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ waitUntilPromises.length = 0;
+
+ mockSendTelegramMessage.mockResolvedValue(undefined);
+ mockQueueInvoiceGeneration.mockResolvedValue(true);
+ mockClearQueuedJob.mockResolvedValue(undefined);
+ mockRunProduction.mockResolvedValue({ ok: true, report: MOCK_REPORT });
+
+ delete process.env.VERCEL_ENV;
+ });
+
+ afterEach(() => {
+ delete process.env.VERCEL_ENV;
+ });
+
+ describe("payload validation", () => {
+ it("should return 200 and notify when payload is invalid", async () => {
+ const { POST } = await import("../route");
+ const response = await POST(createRequest({ update_id: 1 }));
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ ok: true });
+ expect(mockSendTelegramMessage).toHaveBeenCalledWith({
+ message: "❌ Invalid webhook payload.",
+ });
+ expect(mockQueueInvoiceGeneration).not.toHaveBeenCalled();
+ });
+
+ it("should return 200 and notify when command is not /generate", async () => {
+ const { POST } = await import("../route");
+ const response = await POST(
+ createRequest(createValidUpdate({ text: "/help" })),
+ );
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ ok: true });
+ expect(mockSendTelegramMessage).toHaveBeenCalledWith({
+ message: "❌ Invalid webhook payload.",
+ });
+ });
+
+ it("should return 200 and notify when body is not valid JSON", async () => {
+ const { POST } = await import("../route");
+ const response = await POST(createRequest("{not-json"));
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ ok: true });
+ const call = mockSendTelegramMessage.mock.calls[0][0] as {
+ message: string;
+ };
+ expect(call.message).toContain("Webhook error:");
+ });
+ });
+
+ describe("authorization", () => {
+ it("should return 200 and notify when sender is unauthorized", async () => {
+ const { POST } = await import("../route");
+ const response = await POST(
+ createRequest(createValidUpdate({ senderId: 99999 })),
+ );
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ ok: true });
+ expect(mockSendTelegramMessage).toHaveBeenCalledWith({
+ message: "❌ You are not authorized to use this command.",
+ });
+ expect(mockQueueInvoiceGeneration).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("queue deduplication", () => {
+ it("should return 200 and notify when job is already queued", async () => {
+ mockQueueInvoiceGeneration.mockResolvedValue(false);
+
+ const { POST } = await import("../route");
+ const response = await POST(createRequest(createValidUpdate()));
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ ok: true });
+ expect(mockQueueInvoiceGeneration).toHaveBeenCalledWith(CHAT_ID);
+ expect(mockSendTelegramMessage).toHaveBeenCalledWith({
+ message: "⏳ Job already queued for this chat, ignoring retry",
+ });
+ expect(waitUntilPromises).toHaveLength(0);
+ });
+ });
+
+ describe("successful enqueue", () => {
+ it("should return 200 and schedule background invoice generation", async () => {
+ const { POST } = await import("../route");
+ const response = await POST(createRequest(createValidUpdate()));
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ ok: true });
+ expect(mockQueueInvoiceGeneration).toHaveBeenCalledWith(CHAT_ID);
+ expect(waitUntilPromises).toHaveLength(1);
+ });
+ });
+
+ describe("background invoice generation", () => {
+ it("should send progress message and run generation in non-production", async () => {
+ const { POST } = await import("../route");
+ await POST(createRequest(createValidUpdate()));
+ await flushWaitUntil();
+
+ expect(mockSendTelegramMessage).toHaveBeenCalledWith({
+ message: "⏳ Generating invoices... Please wait.",
+ });
+ expect(mockRunProduction).toHaveBeenCalledWith({
+ shouldSendEmail: false,
+ shouldUploadToGoogleDrive: false,
+ });
+ expect(mockClearQueuedJob).toHaveBeenCalledWith(CHAT_ID);
+ });
+
+ it("should complete production background generation without failure notification", async () => {
+ process.env.VERCEL_ENV = "production";
+
+ const { POST } = await import("../route");
+ await POST(createRequest(createValidUpdate()));
+ await flushWaitUntil();
+
+ expect(mockRunProduction).toHaveBeenCalledWith({
+ shouldSendEmail: true,
+ shouldUploadToGoogleDrive: true,
+ });
+ expect(mockSendTelegramMessage).toHaveBeenCalledTimes(1);
+ expect(mockSendTelegramMessage).toHaveBeenCalledWith({
+ message: "⏳ Generating invoices... Please wait.",
+ });
+ expect(mockClearQueuedJob).toHaveBeenCalledWith(CHAT_ID);
+ });
+
+ it("should notify on generation failure when kind is not notification_failed", async () => {
+ mockRunProduction.mockResolvedValue({
+ ok: false,
+ kind: "upload_failed",
+ error: "Upload failed",
+ report: MOCK_REPORT,
+ });
+
+ const { POST } = await import("../route");
+ await POST(createRequest(createValidUpdate()));
+ await flushWaitUntil();
+
+ expect(mockSendTelegramMessage).toHaveBeenCalledWith({
+ message: "❌ Failed to generate invoices.\n\nUpload failed",
+ });
+ expect(mockClearQueuedJob).toHaveBeenCalledWith(CHAT_ID);
+ });
+
+ it("should not send failure message when kind is notification_failed", async () => {
+ mockRunProduction.mockResolvedValue({
+ ok: false,
+ kind: "notification_failed",
+ error: "Notification failed",
+ report: MOCK_REPORT,
+ });
+
+ const { POST } = await import("../route");
+ await POST(createRequest(createValidUpdate()));
+ await flushWaitUntil();
+
+ expect(mockSendTelegramMessage).toHaveBeenCalledTimes(1);
+ expect(mockSendTelegramMessage).toHaveBeenCalledWith({
+ message: "⏳ Generating invoices... Please wait.",
+ });
+ });
+
+ it("should notify when background generation throws", async () => {
+ mockRunProduction.mockRejectedValue(new Error("Unexpected crash"));
+
+ const { POST } = await import("../route");
+ await POST(createRequest(createValidUpdate()));
+ await flushWaitUntil();
+
+ expect(mockSendTelegramMessage).toHaveBeenCalledWith({
+ message: "🚨 Error: Unexpected crash",
+ });
+ expect(mockClearQueuedJob).toHaveBeenCalledWith(CHAT_ID);
+ });
+ });
+});
diff --git a/src/app/api/telegram-webhook/route.ts b/src/app/api/telegram-webhook/route.ts
index 2a114b5..dc2e180 100644
--- a/src/app/api/telegram-webhook/route.ts
+++ b/src/app/api/telegram-webhook/route.ts
@@ -1,3 +1,4 @@
+import { runProductionGenerateMonthlyInvoice } from "@/app/api/generate-invoice/run-production-generate-invoice";
import {
clearQueuedJob,
queueInvoiceGeneration,
@@ -121,33 +122,31 @@ async function handleInvoiceGenerate({ chatId }: { chatId: number }) {
message: "⏳ Generating invoices... Please wait.",
});
- const BASE_URL = process.env.VERCEL_PROJECT_PRODUCTION_URL
- ? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`
- : "http://localhost:3000";
-
- const response = await fetch(`${BASE_URL}/api/generate-invoice`, {
- method: "GET",
- headers: {
- Authorization: `Bearer ${env.AUTH_TOKEN}`,
- "Content-Type": "application/json",
- "Cache-Control": "no-cache, no-store, must-revalidate",
- Pragma: "no-cache",
- Expires: "0",
- },
- cache: "no-store",
- signal: AbortSignal.timeout(25_000), // abort after 25 seconds if the request takes too long
+ // IMPORTANT: for local development, we *DON'T* want to send emails and upload to Google Drive
+ const isProduction = process.env.VERCEL_ENV === "production";
+
+ const result = await runProductionGenerateMonthlyInvoice({
+ shouldSendEmail: isProduction,
+ shouldUploadToGoogleDrive: isProduction,
});
- if (!response.ok) {
- const errorText = await response.text();
+ // eslint-disable-next-line no-console
+ console.log("[telegram-webhook] Report:", result.report);
+
+ if (!result.ok) {
console.error(
- `[telegram-webhook] Failed to generate invoice: ${response.status} ${errorText}`,
+ `[telegram-webhook] Failed to generate invoice (${result.kind}):`,
+ result.error,
);
- await sendTelegramMessage({
- message: `❌ Failed to generate invoices.\n\nStatus: ${response.status}`,
- });
- return;
+ // Only send failure notification if notification itself did not fail.
+ // If result.kind is "notification_failed", previous notification (email or Telegram) already failed,
+ // so suppress further Telegram failure message to avoid recursion or spam.
+ if (result.kind !== "notification_failed") {
+ await sendTelegramMessage({
+ message: `❌ Failed to generate invoices.\n\n${result.error}`,
+ });
+ }
}
} catch (error) {
console.error("[telegram-webhook] handleInvoiceGenerate error:", error);
diff --git a/src/app/constants/index.ts b/src/app/constants/index.ts
index 03d8963..eaad604 100644
--- a/src/app/constants/index.ts
+++ b/src/app/constants/index.ts
@@ -10,17 +10,47 @@ import {
import { INVOICE_PDF_TRANSLATIONS } from "../(app)/pdf-i18n-translations/pdf-translations";
import dayjs from "dayjs";
-export const TODAY = dayjs().format("YYYY-MM-DD");
-export const FIRST_DAY_OF_MONTH = dayjs().startOf("month").format("YYYY-MM-DD");
-export const LAST_DAY_OF_MONTH = dayjs().endOf("month").format("YYYY-MM-DD");
-export const PAYMENT_DUE = dayjs(TODAY).add(14, "days").format("YYYY-MM-DD");
-const INVOICE_CURRENT_MONTH_AND_YEAR = dayjs().format("MM-YYYY");
+/**
+ * Current date in YYYY-MM-DD format
+ *
+ * Used as default **date of issue**
+ */
+const TODAY = dayjs().format("YYYY-MM-DD");
+
+/**
+ * First day of current month in YYYY-MM-DD format
+ *
+ * Used as default date of **service period start**
+ */
+const FIRST_DAY_OF_MONTH = dayjs().startOf("month").format("YYYY-MM-DD");
+
+/**
+ * Last day of current month in YYYY-MM-DD format
+ *
+ * Used as default date of **service period end** and **date of service**
+ */
+const LAST_DAY_OF_MONTH = dayjs().endOf("month").format("YYYY-MM-DD");
+
+/**
+ * Payment due date (14 days from today) in YYYY-MM-DD format
+ *
+ * Used as default **payment due date**
+ */
+const PAYMENT_DUE = dayjs(TODAY).add(14, "days").format("YYYY-MM-DD");
const EUR = SUPPORTED_CURRENCIES[0];
const EN = SUPPORTED_LANGUAGES[0];
const DEFAULT_TEMPLATE = SUPPORTED_TEMPLATES[0];
-export const INVOICE_DEFAULT_NUMBER_VALUE = `1/${INVOICE_CURRENT_MONTH_AND_YEAR}`;
+/**
+ * Default invoice number value computed at call time.
+ * Format: 1/MM-YYYY (e.g., 1/03-2024)
+ *
+ * Used as default **invoice number** when creating a new invoice
+ */
+export function getInvoiceDefaultNumberValue() {
+ return `1/${dayjs().format("MM-YYYY")}` as const;
+}
/**
* Default seller data
@@ -85,7 +115,7 @@ export const INITIAL_INVOICE_DATA = {
invoiceNumberObject: {
label: `${INVOICE_PDF_TRANSLATIONS[EN].invoiceNumber}:`,
- value: INVOICE_DEFAULT_NUMBER_VALUE,
+ value: getInvoiceDefaultNumberValue(),
},
dateOfIssue: TODAY,
@@ -157,3 +187,17 @@ export const INITIAL_INVOICE_DATA = {
taxLabelText: "VAT",
} as const satisfies InvoiceData;
+
+/**
+ * Returns initial invoice data with a freshly computed default invoice number.
+ * Use when resetting form state at runtime (avoids stale month on long-lived tabs).
+ */
+export function getInitialInvoiceData() {
+ return {
+ ...INITIAL_INVOICE_DATA,
+ invoiceNumberObject: {
+ ...INITIAL_INVOICE_DATA.invoiceNumberObject,
+ value: getInvoiceDefaultNumberValue(),
+ },
+ } satisfies InvoiceData;
+}
diff --git a/src/app/schema/index.ts b/src/app/schema/index.ts
index 26f7e9b..3103fb6 100644
--- a/src/app/schema/index.ts
+++ b/src/app/schema/index.ts
@@ -830,12 +830,21 @@ export const invoiceItemSchema = z.object({
vatFieldIsVisible: z.boolean().default(true),
+ /**
+ * Net Amount (**calculated automatically** - read only field in the UI)
+ */
netAmount: z.coerce.number().nonnegative("Net amount must be non-negative"),
netAmountFieldIsVisible: z.boolean().default(true),
+ /**
+ * VAT Amount (**calculated automatically** - read only field in the UI)
+ */
vatAmount: z.coerce.number().nonnegative("VAT amount must be non-negative"),
vatAmountFieldIsVisible: z.boolean().default(true),
+ /**
+ * Pre-tax Amount (**calculated automatically** - read only field in the UI)
+ */
preTaxAmount: z.coerce
.number()
.nonnegative("Pre-tax amount must be non-negative"),
@@ -1105,7 +1114,7 @@ export const invoiceObjectSchema = z.object({
),
/**
- * Renamed from "Invoice Type" to "Header Notes" on UI to better reflect its purpose
+ * Field "Invoice Type" renamed to "Header Notes" in **UI** for clarity; stores invoice header notes.
*/
invoiceType: z
.string()
@@ -1113,7 +1122,7 @@ export const invoiceObjectSchema = z.object({
.trim()
.optional(),
/**
- * Renamed to "Header Notes" on UI to better reflect its purpose
+ * Field "Invoice Type" renamed to "Header Notes" in **UI** for clarity; toggles visibility of the field in the PDF.
*/
invoiceTypeFieldIsVisible: z.boolean().default(true),
@@ -1121,6 +1130,10 @@ export const invoiceObjectSchema = z.object({
buyer: buyerSchema,
items: z.array(invoiceItemSchema).min(1, "At least one item is required"),
+
+ /**
+ * Total (**calculated automatically** - read only field in the UI)
+ */
total: z.coerce.number().nonnegative("Total must be non-negative"),
// Show/hide VAT Table Summary on PDF
diff --git a/src/components/__tests__/github-star-cta.test.tsx b/src/components/__tests__/github-star-cta.test.tsx
new file mode 100644
index 0000000..f2abce6
--- /dev/null
+++ b/src/components/__tests__/github-star-cta.test.tsx
@@ -0,0 +1,124 @@
+// @vitest-environment happy-dom
+
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { cleanup, render, screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import "@testing-library/jest-dom/vitest";
+
+import { GITHUB_URL } from "@/config";
+import { GitHubStarCTA } from "../github-star-cta";
+import { TooltipProvider } from "../ui/tooltip";
+
+vi.mock("@/lib/umami-analytics-track-event", () => ({
+ umamiTrackEvent: vi.fn(),
+}));
+
+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
+
+function renderGitHubStarCTA(githubStarsCount: number) {
+ return render(
+ <TooltipProvider delayDuration={0}>
+ <GitHubStarCTA githubStarsCount={githubStarsCount} />
+ </TooltipProvider>,
+ );
+}
+
+describe("GitHubStarCTA", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("should render external GitHub link with accessible label", () => {
+ renderGitHubStarCTA(100);
+
+ const link = screen.getByTestId("github-star-cta-button");
+
+ expect(link).toHaveAttribute("href", GITHUB_URL);
+ expect(link).toHaveAttribute("target", "_blank");
+ expect(link).toHaveAttribute("rel", "noopener noreferrer");
+ expect(link).toHaveAttribute("aria-label", "Star project on GitHub");
+ });
+
+ it("should show lowercase formatted star count when count is greater than 0", () => {
+ const githubStarsCount = 1500;
+
+ renderGitHubStarCTA(githubStarsCount);
+
+ const link = screen.getByTestId("github-star-cta-button");
+
+ expect(within(link).getByText("1.5k")).toBeInTheDocument();
+
+ expect(within(link).queryByText("Star on GitHub")).not.toBeInTheDocument();
+ });
+
+ it("should show two-decimal compact star count for values like 2350", () => {
+ const githubStarsCount = 2350;
+
+ renderGitHubStarCTA(githubStarsCount);
+
+ const link = screen.getByTestId("github-star-cta-button");
+
+ expect(within(link).getByText("2.35k")).toBeInTheDocument();
+
+ expect(within(link).queryByText("Star on GitHub")).not.toBeInTheDocument();
+ });
+
+ it("should show unabbreviated star count for three-digit values", () => {
+ const githubStarsCount = 969;
+
+ renderGitHubStarCTA(githubStarsCount);
+
+ const link = screen.getByTestId("github-star-cta-button");
+
+ expect(within(link).getByText("969")).toBeInTheDocument();
+
+ expect(within(link).queryByText("Star on GitHub")).not.toBeInTheDocument();
+ });
+
+ it("should show lowercase formatted star count when count is over 10k", () => {
+ const githubStarsCount = 15000;
+
+ renderGitHubStarCTA(githubStarsCount);
+
+ const link = screen.getByTestId("github-star-cta-button");
+
+ expect(within(link).getByText("15k")).toBeInTheDocument();
+
+ expect(within(link).queryByText("Star on GitHub")).not.toBeInTheDocument();
+ });
+
+ it("should show Star on GitHub label in button when count is 0", () => {
+ renderGitHubStarCTA(0);
+
+ const link = screen.getByTestId("github-star-cta-button");
+
+ expect(within(link).getByText("Star on GitHub")).toBeInTheDocument();
+ });
+
+ it("should track github_star_cta_clicked on click", async () => {
+ const user = userEvent.setup();
+
+ renderGitHubStarCTA(42);
+
+ await user.click(screen.getByTestId("github-star-cta-button"));
+
+ expect(umamiTrackEvent).toHaveBeenCalledWith("github_star_cta_clicked");
+ expect(umamiTrackEvent).toHaveBeenCalledTimes(1);
+ });
+
+ it("should show Star on GitHub tooltip on hover", async () => {
+ const user = userEvent.setup();
+
+ renderGitHubStarCTA(250);
+
+ await user.hover(screen.getByTestId("github-star-cta-button"));
+
+ expect(await screen.findByRole("tooltip")).toHaveTextContent(
+ "Star on GitHub",
+ );
+ });
+});
diff --git a/src/lib/google-drive.ts b/src/lib/google-drive.ts
index efd96fa..8eb359f 100644
--- a/src/lib/google-drive.ts
+++ b/src/lib/google-drive.ts
@@ -1,22 +1,39 @@
+import { env } from "@/env";
+import type { drive_v3 } from "googleapis";
import { google } from "googleapis";
-import { z } from "zod";
import { Readable } from "node:stream";
-import { env } from "@/env";
+import { z } from "zod";
-export interface GoogleDriveFile {
+type GoogleDriveFile = drive_v3.Schema$File;
+
+export interface DriveFolderRef {
id: string;
- name: string;
- mimeType: string;
- webViewLink?: string;
+ webViewLink: string;
}
-interface Success {
- status: "success";
- folderToUploadInvoices: GoogleDriveFile;
+export interface InvoiceFolderResult {
+ folderToUploadInvoices: DriveFolderRef;
googleDriveFolderPath: string;
}
-type CreateOrFindInvoiceFolderResult = Success;
+/**
+ * Convert Google Drive File object to DriveFolderRef.
+ * Throws if file missing required fields.
+ *
+ * @param file - Google Drive file (should be a folder)
+ * @returns DriveFolderRef with id and webViewLink
+ */
+function toDriveFolderRef(file: GoogleDriveFile): DriveFolderRef {
+ if (!file.id) {
+ throw new Error("Google Drive folder is missing id");
+ }
+
+ if (!file.webViewLink) {
+ throw new Error("Google Drive folder is missing webViewLink");
+ }
+
+ return { id: file.id, webViewLink: file.webViewLink };
+}
const FolderInputSchema = z.object({
parentFolderId: z.string().min(1),
@@ -28,7 +45,7 @@ const FolderInputSchema = z.object({
type FolderInput = z.infer<typeof FolderInputSchema>;
-let cachedDrive: ReturnType<typeof google.drive> | undefined;
+let cachedDrive: drive_v3.Drive | undefined;
export async function initializeGoogleDrive() {
if (cachedDrive) {
@@ -51,7 +68,7 @@ export async function initializeGoogleDrive() {
}
async function createFolder(
- drive: ReturnType<typeof google.drive>,
+ drive: drive_v3.Drive,
folderName: string,
parentFolderId?: string,
): Promise<GoogleDriveFile> {
@@ -70,7 +87,7 @@ async function createFolder(
throw new Error("Failed to create folder");
}
- return response.data as GoogleDriveFile;
+ return response.data;
}
/**
@@ -86,7 +103,7 @@ export async function uploadFile({
fileContent,
folderId,
}: {
- googleDrive: ReturnType<typeof google.drive>;
+ googleDrive: drive_v3.Drive;
fileName: string;
fileContent: Buffer;
folderId: string;
@@ -111,15 +128,15 @@ export async function uploadFile({
throw new Error("Failed to upload file");
}
- return response.data as GoogleDriveFile;
+ return response.data;
}
export async function createOrFindInvoiceFolder({
googleDrive,
...input
}: {
- googleDrive: ReturnType<typeof google.drive>;
-} & FolderInput): Promise<CreateOrFindInvoiceFolderResult> {
+ googleDrive: drive_v3.Drive;
+} & FolderInput): Promise<InvoiceFolderResult> {
// Validate input
const validatedInput = FolderInputSchema.parse(input);
@@ -139,7 +156,7 @@ export async function createOrFindInvoiceFolder({
if (yearFolderResponse.data.files?.length) {
// if the year folder already exists, use it
- yearFolder = yearFolderResponse.data.files[0] as GoogleDriveFile;
+ yearFolder = yearFolderResponse.data.files[0];
} else {
// if the year folder does not exist, create it
yearFolder = await createFolder(
@@ -165,7 +182,7 @@ export async function createOrFindInvoiceFolder({
if (monthFolderResponse.data.files?.length) {
// if the month folder already exists, use it
- monthFolder = monthFolderResponse.data.files[0] as GoogleDriveFile;
+ monthFolder = monthFolderResponse.data.files[0];
// eslint-disable-next-line no-console
console.log(
@@ -176,6 +193,12 @@ export async function createOrFindInvoiceFolder({
);
} else {
// if the month folder does not exist (new month), create it
+ if (!yearFolder?.id) {
+ throw new Error(
+ "[createOrFindInvoiceFolder] Google Drive year folder is missing id",
+ );
+ }
+
monthFolder = await createFolder(
googleDrive,
monthFolderName,
@@ -197,10 +220,15 @@ export async function createOrFindInvoiceFolder({
if (invoicesFolderResponse.data.files?.length) {
// if the invoices folder already exists, use it
- folderToUploadInvoices = invoicesFolderResponse.data
- .files[0] as GoogleDriveFile;
+ folderToUploadInvoices = invoicesFolderResponse.data.files[0];
} else {
// if the invoices folder does not exist, create it
+ if (!monthFolder?.id) {
+ throw new Error(
+ "[createOrFindInvoiceFolder] Google Drive month folder is missing id",
+ );
+ }
+
folderToUploadInvoices = await createFolder(
googleDrive,
"invoices",
@@ -217,9 +245,10 @@ export async function createOrFindInvoiceFolder({
"\n\n",
);
+ const folderToUploadInvoicesRef = toDriveFolderRef(folderToUploadInvoices);
+
return {
- status: "success",
- folderToUploadInvoices,
+ folderToUploadInvoices: folderToUploadInvoicesRef,
googleDriveFolderPath,
};
}
diff --git a/src/utils/number-formatter.ts b/src/utils/number-formatter.ts
index d520b45..12f2342 100644
--- a/src/utils/number-formatter.ts
+++ b/src/utils/number-formatter.ts
@@ -4,9 +4,11 @@
*
* @example
* githubStarCountFormatter.format(1500); // "1.5K"
+ * githubStarCountFormatter.format(2350); // "2.35K"
* githubStarCountFormatter.format(1000000); // "1M"
*/
export const githubStarCountFormatter = new Intl.NumberFormat("en-US", {
notation: "compact",
compactDisplay: "short",
+ maximumFractionDigits: 2,
});
diff --git a/vitest.config.ts b/vitest.config.ts
index a5ba8da..b47b31b 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -2,9 +2,13 @@ import { defineConfig } from "vitest/config";
import path from "node:path";
export default defineConfig({
+ esbuild: {
+ jsx: "automatic",
+ },
test: {
dir: "./src",
exclude: ["**/e2e/**"],
+ silent: true, // suppress console.log output in test output
},
resolve: {
alias: {