Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.
TypeScript fintechinvoiceinvoice-generatorinvoice-pdfinvoice-templateinvoicesnextjsopen-sourcequotesreactreact-pdf-rendererself-hostedshadcn-uitailwindcsstypescript
refactor: centralize Warsaw time handling for invoice generation (#262)
Vlad Sazonaub439cde66fb6
diff --git a/README.md b/README.mdindex 7a3df48..5527506 100644--- a/README.md+++ b/README.md@@ -128,6 +128,19 @@ _**Add payment QR codes** with any invoice-related information (payment links, U## π’ What's New+### EasyInvoicePDF v1.0.4 - Faster PDF Preview & Mobile Polish (September 4, 2026)++- **Faster, flicker-free preview** - the invoice PDF is generated **once** and shared by the desktop preview, the mobile viewer and the download button+- **Redesigned mobile tabs** - a pill-shaped track with a single indicator that slides between the invoice form and the preview+- **Dates in the form now match the PDF** - helper texts and the out-of-date banner use the invoice's own language and date format+- **Fixed PDFs missing the first characters of labels** - `Cobrar de` no longer renders as `obrar de` in rare cases++https://github.com/user-attachments/assets/3c87d026-a1c3-4d69-b161-f7d72616c394++[Full release notes for v1.0.4](https://github.com/VladSez/easy-invoice-pdf/releases/tag/v1.0.4)++---+### EasyInvoicePDF v1.0.3 β Seller & Buyer Improvements (March 29, 2026)- **Seller & Buyer Email visibility toggle** β control whether email addresses appear in the generated PDFdiff --git a/next.config.mjs b/next.config.mjsindex 487a5f0..aa61663 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -146,8 +146,30 @@ const nextConfig = {fullUrl: true,},},- webpack: (config) => {+ // `react-pdf` imports the bare `pdfjs-dist` specifier, which resolves to pdf.js's+ // *modern* build. That build calls `URL.parse()` (Safari 18.4+) and+ // `Promise.withResolvers()` (Safari 17.4+) unguarded, so the mobile PDF viewer dies+ // with "URL.parse is not a function" on any slightly older iOS Safari.+ //+ // pdf.js ships a `legacy/` build for exactly this: same API, plus the core-js+ // polyfills. We point the browser bundle at it (the worker is imported by its+ // legacy path directly in `mobile-pdf-viewer.tsx`).+ //+ // Turbopack powers `next dev`, webpack powers `next build`, so both need the alias.+ turbopack: {+ resolveAlias: {+ "pdfjs-dist": { browser: "pdfjs-dist/legacy/build/pdf.mjs" },+ },+ },+ webpack: (config, { isServer }) => {config.resolve.alias.canvas = false;++ if (!isServer) {+ // `$` = exact match only, so deep imports (`pdfjs-dist/legacy/build/...`) are+ // left alone.+ config.resolve.alias["pdfjs-dist$"] = "pdfjs-dist/legacy/build/pdf.mjs";+ }+return config;},async rewrites() {diff --git a/src/app/(app)/components/invoice-pdf-preview/desktop-pdf-viewer.tsx b/src/app/(app)/components/invoice-pdf-preview/desktop-pdf-viewer.tsxindex d645276..12b5315 100644--- a/src/app/(app)/components/invoice-pdf-preview/desktop-pdf-viewer.tsx+++ b/src/app/(app)/components/invoice-pdf-preview/desktop-pdf-viewer.tsx@@ -12,7 +12,7 @@ export function DesktopInvoicePDFViewer() {<div className="text-center"><p className="text-red-600">Error generating PDF preview</p><p className="mx-6 mt-2 max-w-xl text-balance text-sm text-gray-600">- Something went wrong.+ <b>Something went wrong.</b><br /> Please try refreshing the page or using the{" "}<span className="font-bold">Chrome</span> browser. If the issuepersists, please fill a bug report{" "}diff --git a/src/app/(app)/components/invoice-pdf-preview/mobile-pdf-viewer.tsx b/src/app/(app)/components/invoice-pdf-preview/mobile-pdf-viewer.tsxindex a8ace65..b72b5df 100644--- a/src/app/(app)/components/invoice-pdf-preview/mobile-pdf-viewer.tsx+++ b/src/app/(app)/components/invoice-pdf-preview/mobile-pdf-viewer.tsx@@ -8,7 +8,13 @@ import { BUG_REPORT_URL } from "@/config";// This import registers the PDF.js worker globally so that react-pdf can render PDFs in the browser.// https://github.com/wojtekmaj/react-pdf/issues/1824#issuecomment-2266150831// https://github.com/wojtekmaj/react-pdf?tab=readme-ov-file#configure-pdfjs-worker-import "pdfjs-dist/build/pdf.worker.min.mjs";+//+// `legacy/` (rather than `build/`) on purpose: the modern pdf.js build calls+// `URL.parse()` and `Promise.withResolvers()`, which iOS Safari only gained in 18.4+// and 17.4. The legacy build is the same code plus core-js polyfills, and it keeps+// the viewer alive on older iPhones. `next.config.mjs` aliases the matching+// main-thread build that `react-pdf` itself imports.+import "pdfjs-dist/legacy/build/pdf.worker.min.mjs";/*** Mobile PDF viewer.@@ -41,7 +47,7 @@ export const MobileInvoicePDFViewer = () => {<div className="text-center"><p className="text-red-600">Error generating PDF preview</p><p className="mx-6 mt-2 text-balance text-sm text-gray-600">- Something went wrong.+ <b>Something went wrong.</b><br /> Please try refreshing the page or using the{" "}<span className="font-bold">Chrome</span> browser. If the issuepersists, please fill a bug report{" "}diff --git a/src/app/(app)/error.tsx b/src/app/(app)/error.tsxindex a2714b3..4f0f098 100644--- a/src/app/(app)/error.tsx+++ b/src/app/(app)/error.tsx@@ -52,7 +52,7 @@ export default function Error({<div className="flex h-dvh flex-col items-center justify-center gap-4"><div className="flex flex-col items-center justify-center gap-4"><ErrorMessage>- Something went wrong.+ <b>Something went wrong.</b><br /> Please try refreshing the page or using the Chrome browser.</ErrorMessage><ErrorMessage>diff --git a/src/app/api/generate-invoice/__tests__/generate-invoice.test.ts b/src/app/api/generate-invoice/__tests__/generate-invoice.test.tsindex 87091a9..ceda5a5 100644--- a/src/app/api/generate-invoice/__tests__/generate-invoice.test.ts+++ b/src/app/api/generate-invoice/__tests__/generate-invoice.test.ts@@ -9,6 +9,7 @@ import {type GenerateInvoiceInput,type GenerateInvoiceReport,} from "../generate-invoice";+import { nowInTimeZone } from "../invoice-time-zone";// No vi.mock() here β all external boundaries are injected via deps.@@ -41,6 +42,8 @@ const MOCK_INPUT = {invoiceEmailRecipient: "[email protected]",englishInvoiceData: MOCK_INVOICE_DATA,polishInvoiceData: { ...MOCK_INVOICE_DATA, language: "pl" },+ timeZone: "Europe/Warsaw",+ now: nowInTimeZone("Europe/Warsaw"),} as const satisfies GenerateInvoiceInput;/**@@ -90,6 +93,7 @@ describe("generateInvoice", () => {totalTimeTook: expect.any(String,) as GenerateInvoiceReport["totalTimeTook"],+ timeZone: MOCK_INPUT.timeZone,},}),);@@ -146,6 +150,9 @@ describe("generateInvoice", () => {const deps = buildDeps();await generateInvoice(deps, {...MOCK_INPUT,+ // Built after the clock is faked: `generateInvoice` no longer reads the+ // clock itself, the caller hands it the invoice's timestamp.+ now: nowInTimeZone(MOCK_INPUT.timeZone),englishInvoiceData: {...MOCK_INPUT.englishInvoiceData,invoiceNumberObject: {@@ -175,6 +182,51 @@ describe("generateInvoice", () => {}});+ it("should date everything from the passed timestamp, not the clock at send time", async () => {+ vi.useFakeTimers({ toFake: ["Date"] });+ // 23:59 in Warsaw (CEST, UTC+2) on the last day of August.+ vi.setSystemTime(new Date("2026-08-31T21:59:00.000Z"));++ try {+ const now = nowInTimeZone(MOCK_INPUT.timeZone);++ // The run straddles local midnight: rendering and uploading finish when+ // Warsaw is already in September. Everything must still say August,+ // matching the dates the caller printed on the PDF.+ vi.setSystemTime(new Date("2026-08-31T22:01:00.000Z"));++ const deps = buildDeps();+ await generateInvoice(deps, {+ ...MOCK_INPUT,+ now,+ englishInvoiceData: {+ ...MOCK_INPUT.englishInvoiceData,+ invoiceNumberObject: {+ label: "Invoice Number",+ value: "",+ },+ },+ });++ expect(deps.createOrFindInvoiceFolder).toHaveBeenCalledWith(+ expect.objectContaining({ month: "08", year: "2026" }),+ );+ expect(deps.uploadFile).toHaveBeenCalledWith(+ expect.objectContaining({ fileName: "invoice-EN-08-2026.pdf" }),+ );++ const telegramCall = vi.mocked(deps.sendTelegramMessage).mock+ .calls[0][0];+ expect(telegramCall.message).toContain("Invoices for August 2026");+ expect(telegramCall.message).toContain("Date: *August 31, 2026*");++ const emailCall = vi.mocked(deps.sendEmail).mock.calls[0][0];+ expect(emailCall.subject).toBe("π Invoices for August 2026");+ } finally {+ vi.useRealTimers();+ }+ });+it("should send Telegram notification with 2 file attachments", async () => {const deps = buildDeps();await generateInvoice(deps, MOCK_INPUT);@@ -189,6 +241,21 @@ describe("generateInvoice", () => {});});+ it("should name the invoice timezone in the Telegram message", async () => {+ const deps = buildDeps();+ await generateInvoice(deps, {+ ...MOCK_INPUT,+ timeZone: "America/New_York",+ now: nowInTimeZone("America/New_York"),+ });++ const call = vi.mocked(deps.sendTelegramMessage).mock.calls[0][0];+ // Backticks, not bare text: Telegram parses the message as legacy Markdown,+ // where the underscore in a name like `America/New_York` would open an+ // unclosed italic span and the whole send would fail with a parse error.+ expect(call.message).toContain("(`America/New_York`)");+ });+it("should send email with correct recipient and 2 attachments", async () => {const deps = buildDeps();await generateInvoice(deps, MOCK_INPUT);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.tsxindex 2a603ba..2171a62 100644--- 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@@ -1,10 +1,12 @@// @vitest-environment node-import { describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { INVOICE_PDF_TRANSLATIONS } from "@/app/(app)/pdf-i18n-translations/pdf-translations";+import { nowInTimeZone } from "../invoice-time-zone";import {+ getEnglishInvoiceRealData,getPolishInvoiceRealData,renderInvoicePdfBuffer,} from "../render-pdf-on-server";@@ -105,3 +107,67 @@ describe("getPolishInvoiceRealData", () => {);});});++describe("getEnglishInvoiceRealData", () => {+ const originalTimeZone = process.env.TZ;++ beforeEach(() => {+ // Vercel runs the route in UTC. Pinning it here means the assertions below+ // also catch the regression on a machine that already sits in Warsaw time.+ process.env.TZ = "UTC";+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();++ if (originalTimeZone === undefined) {+ delete process.env.TZ;+ } else {+ process.env.TZ = originalTimeZone;+ }+ });++ it("dates the invoice in the given timezone, not the process timezone (CEST, UTC+2)", () => {+ // 23:30 UTC on June 30th is already 01:30 on July 1st in Warsaw+ vi.setSystemTime(new Date("2025-06-30T23:30:00Z"));++ const invoiceData = getEnglishInvoiceRealData({+ now: nowInTimeZone("Europe/Warsaw"),+ });++ expect(invoiceData.dateOfIssue).toBe("2025-07-01");+ expect(invoiceData.dateOfServiceStart).toBe("2025-07-01");+ expect(invoiceData.dateOfService).toBe("2025-07-31");+ expect(invoiceData.paymentDue).toBe("2025-07-31");+ expect(invoiceData.invoiceNumberObject.value).toBe("1/07-2025");+ });++ it("dates the invoice in the given timezone across a year boundary (CET, UTC+1)", () => {+ // 23:30 UTC on December 31st is already 00:30 on January 1st in Warsaw+ vi.setSystemTime(new Date("2025-12-31T23:30:00Z"));++ const invoiceData = getEnglishInvoiceRealData({+ now: nowInTimeZone("Europe/Warsaw"),+ });++ expect(invoiceData.dateOfIssue).toBe("2026-01-01");+ expect(invoiceData.dateOfServiceStart).toBe("2026-01-01");+ expect(invoiceData.dateOfService).toBe("2026-01-31");+ expect(invoiceData.invoiceNumberObject.value).toBe("1/01-2026");+ });++ it("dates the invoice behind UTC when the timezone is behind UTC", () => {+ // 00:30 UTC on July 1st is still 20:30 on June 30th in New York (EDT, UTC-4)+ vi.setSystemTime(new Date("2025-07-01T00:30:00Z"));++ const invoiceData = getEnglishInvoiceRealData({+ now: nowInTimeZone("America/New_York"),+ });++ expect(invoiceData.dateOfIssue).toBe("2025-06-30");+ expect(invoiceData.dateOfServiceStart).toBe("2025-06-01");+ expect(invoiceData.dateOfService).toBe("2025-06-30");+ expect(invoiceData.invoiceNumberObject.value).toBe("1/06-2025");+ });+});diff --git a/src/app/api/generate-invoice/__tests__/route.test.ts b/src/app/api/generate-invoice/__tests__/route.test.tsindex 1a3e435..bfbcfd9 100644--- a/src/app/api/generate-invoice/__tests__/route.test.ts+++ b/src/app/api/generate-invoice/__tests__/route.test.ts@@ -13,6 +13,7 @@ const MOCK_REPORT = {notifiedByTelegram: true,notifiedByEmail: true,totalTimeTook: "1.23s",+ timeZone: "Europe/Warsaw",} as const satisfies GenerateInvoiceReport;const TEST_AUTH_TOKEN = "test-auth-token";@@ -357,5 +358,50 @@ describe("GET /api/generate-invoice β HTTP layer", () => {};expect(callOptions.shouldUploadToGoogleDrive).toBe(true);});++ it("should default the timezone to Europe/Warsaw", 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 {+ timeZone: string;+ };+ expect(callOptions.timeZone).toBe("Europe/Warsaw");+ });++ it("should pass the timezone query param through", async () => {+ mockRunProduction.mockResolvedValue({ ok: true, report: MOCK_REPORT });++ const { GET } = await import("../route");+ await GET(+ createRequest({+ authToken: TEST_AUTH_TOKEN,+ searchParams: { timezone: "America/New_York" },+ }),+ );++ const callOptions = mockRunProduction.mock.calls[0][0] as {+ timeZone: string;+ };+ expect(callOptions.timeZone).toBe("America/New_York");+ });++ it("should return 400 and generate nothing for an unknown timezone", async () => {+ const { GET } = await import("../route");+ const response = await GET(+ createRequest({+ authToken: TEST_AUTH_TOKEN,+ searchParams: { timezone: "Mars/Olympus_Mons" },+ }),+ );++ expect(response.status).toBe(400);+ expect(((await response.json()) as { error: string }).error).toContain(+ "Mars/Olympus_Mons",+ );+ expect(mockRunProduction).not.toHaveBeenCalled();+ });});});diff --git a/src/app/api/generate-invoice/generate-invoice.ts b/src/app/api/generate-invoice/generate-invoice.tsindex 2c9420e..006e151 100644--- a/src/app/api/generate-invoice/generate-invoice.ts+++ b/src/app/api/generate-invoice/generate-invoice.ts@@ -1,6 +1,4 @@-import dayjs from "dayjs";-import timezone from "dayjs/plugin/timezone";-import utc from "dayjs/plugin/utc";+import type dayjs from "dayjs";import type { drive_v3 } from "googleapis";import { compressToEncodedURIComponent } from "lz-string";import type { Attachment, CreateEmailResponse } from "resend";@@ -9,11 +7,6 @@ import { invoiceSchema, type InvoiceData } from "@/app/schema";import type { InvoiceFolderResult } from "@/lib/google-drive";import { compressInvoiceData } from "@/utils/url-compression";-dayjs.extend(utc);-dayjs.extend(timezone);--const WARSAW_TIME_ZONE = "Europe/Warsaw";-/*** Formats milliseconds into a human-readable duration string.* @param ms - Duration in milliseconds@@ -38,6 +31,9 @@ export interface GenerateInvoiceReport {notifiedByTelegram: boolean;notifiedByEmail: boolean;totalTimeTook: string;+ /** IANA timezone the invoice was dated in β echoed back so a caller can tell+ * which timezone produced the dates printed on the PDF. */+ timeZone: string;}/**@@ -138,6 +134,19 @@ export interface GenerateInvoiceInput {englishInvoiceData: InvoiceData;/** Validated invoice data for the Polish PDF. */polishInvoiceData: InvoiceData;+ /**+ * IANA timezone the invoice is dated in β the Drive folder, the file names and+ * the notification dates all follow it, so they cannot drift from the dates+ * printed inside the PDF.+ */+ timeZone: string;+ /**+ * The single timestamp the whole invoice is dated by, already in `timeZone`+ * (see `nowInTimeZone`). It is captured once by the caller and reused for the+ * PDF dates, the Drive folder, the file names and the notification text, so a+ * run that straddles local midnight cannot mix two calendar days.+ */+ now: dayjs.Dayjs;}/**@@ -162,7 +171,6 @@ export async function generateInvoice(input: GenerateInvoiceInput,): Promise<GenerateInvoiceResult> {const startTime = performance.now();- const warsawNow = dayjs().tz(WARSAW_TIME_ZONE);const {renderEnInvoice,@@ -181,6 +189,8 @@ export async function generateInvoice(invoiceEmailCompanyTo,invoiceEmailRecipient,englishInvoiceData,+ timeZone,+ now,} = input;// βββ Step 1: Render PDFs ββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -243,7 +253,7 @@ export async function generateInvoice(englishInvoiceData?.invoiceNumberObject?.value?.trim() || "";const formattedInvoiceNumber = invoiceNumber? invoiceNumber.replaceAll("/", "-")- : warsawNow.format("MM-YYYY");+ : now.format("MM-YYYY");const attachments = fulfilledInvoices.map((doc) => {const fileName = `invoice-${doc.language.toUpperCase()}-${formattedInvoiceNumber}.pdf`;@@ -267,6 +277,7 @@ export async function generateInvoice(notifiedByTelegram: false,notifiedByEmail: false,totalTimeTook: formatDuration(performance.now() - startTime),+ timeZone,},};}@@ -279,7 +290,7 @@ export async function generateInvoice(const compressedData = compressToEncodedURIComponent(compressedJson);const invoiceUrl = `https://easyinvoicepdf.com/?template=${newInvoiceDataValidated.template}&data=${compressedData}`;- const monthAndYear = warsawNow.format("MMMM YYYY");+ const monthAndYear = now.format("MMMM YYYY");const invoiceNumberValue = englishInvoiceData?.invoiceNumberObject?.value;// βββ Step 3: Upload PDFs to Google Drive βββββββββββββββββββββββββββββββββ@@ -292,8 +303,8 @@ export async function generateInvoice(// Authenticate, then resolve (or create) the month/year folder in Drive.const googleDrive = await initializeGoogleDrive();- const currentMonth = warsawNow.format("MM");- const currentYear = warsawNow.format("YYYY");+ const currentMonth = now.format("MM");+ const currentYear = now.format("YYYY");const folderResult = await createOrFindInvoiceFolder({googleDrive,@@ -350,6 +361,7 @@ export async function generateInvoice(notifiedByTelegram: false,notifiedByEmail: false,totalTimeTook: formatDuration(performance.now() - startTime),+ timeZone,},};}@@ -371,6 +383,7 @@ export async function generateInvoice(notifiedByTelegram: false,notifiedByEmail: false,totalTimeTook: formatDuration(performance.now() - startTime),+ timeZone,},};}@@ -426,7 +439,7 @@ export async function generateInvoice(message: `${testModeWarningBlock}π *Invoices for ${monthAndYear}*Invoice No. of: *${invoiceNumberValue}*-Date: *${warsawNow.format("MMMM D, YYYY")}*+Date: *${now.format("MMMM D, YYYY")}* (\`${timeZone}\`)The generated invoices are included in the attachments. Please check them carefully.@@ -457,7 +470,7 @@ EasyInvoicePDF.com`,subject: `π Invoices for ${monthAndYear}`,html: `${emailGoogleDriveWarningHtml}<p>Hello,</p><span>Invoice No. of: <b>${invoiceNumberValue}</b><br/>- Date: <b>${warsawNow.format("MMMM D, YYYY")}</b>+ Date: <b>${now.format("MMMM D, YYYY")}</b><br/><br/>@@ -540,6 +553,7 @@ EasyInvoicePDF.com`,notifiedByTelegram,notifiedByEmail,totalTimeTook: formatDuration(performance.now() - startTime),+ timeZone,},};}@@ -553,6 +567,7 @@ EasyInvoicePDF.com`,notifiedByTelegram,notifiedByEmail,totalTimeTook: formatDuration(performance.now() - startTime),+ timeZone,},};}diff --git a/src/app/api/generate-invoice/invoice-time-zone.ts b/src/app/api/generate-invoice/invoice-time-zone.tsnew file mode 100644index 0000000..f350b0c--- /dev/null+++ b/src/app/api/generate-invoice/invoice-time-zone.ts@@ -0,0 +1,42 @@+import dayjs from "dayjs";+import timezone from "dayjs/plugin/timezone";+import utc from "dayjs/plugin/utc";++dayjs.extend(utc);+dayjs.extend(timezone);++/**+ * Wall-clock timezone every server-generated invoice is dated in unless the+ * caller asks for another one via the `timezone` query param.+ */+export const DEFAULT_INVOICE_TIME_ZONE = "Europe/Warsaw";++/**+ * `dayjs()` in the given IANA timezone's wall time.+ *+ * The process timezone is UTC on Vercel, so a plain `dayjs()` dates the invoice+ * a day behind Warsaw between midnight and 01:00 (02:00 during CEST), and the+ * invoice number lands in the previous month on the 1st.+ *+ * @param timeZone - IANA timezone name, already validated by {@link isValidTimeZone}.+ */+export function nowInTimeZone(timeZone: string) {+ return dayjs().tz(timeZone);+}++/**+ * Whether the runtime recognises `value` as an IANA timezone name.+ *+ * `Intl.DateTimeFormat` throws a `RangeError` on anything it cannot resolve,+ * which is the only check that stays in sync with the platform's tz database.+ */+export function isValidTimeZone(value: string): boolean {+ try {+ // constructing it *is* the check - `no-new` has no allowlist for built-ins+ // eslint-disable-next-line no-new+ new Intl.DateTimeFormat("en-US", { timeZone: value });+ return true;+ } catch {+ return false;+ }+}diff --git a/src/app/api/generate-invoice/render-pdf-on-server.tsx b/src/app/api/generate-invoice/render-pdf-on-server.tsxindex 59b2736..c124ec5 100644--- a/src/app/api/generate-invoice/render-pdf-on-server.tsx+++ b/src/app/api/generate-invoice/render-pdf-on-server.tsx@@ -1,7 +1,7 @@// IMPORTANT: it's fine to use this import directly on server side// eslint-disable-next-line no-restricted-importsimport { Document, Font, Page, renderToBuffer } from "@react-pdf/renderer";-import dayjs from "dayjs";+import type dayjs from "dayjs";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";@@ -11,6 +11,8 @@ import { type InvoiceData, type SupportedLanguages } from "@/app/schema";import { INVOICE_PDF_FONTS } from "@/config";import { env } from "@/env";+import { DEFAULT_INVOICE_TIME_ZONE, nowInTimeZone } from "./invoice-time-zone";+// Open sans seems to be working fine with EN and PLconst fontFamily = "Open Sans";@@ -99,12 +101,17 @@ const translateInvoiceNumberLabel = ({const INVOICE_NET_PRICE = Number(env.INVOICE_NET_PRICE) || 0;-/** Recomputed each call so warm servers do not reuse module-load dates. (to avoid outdated dates in the PDF) */-function getInvoiceDefaultDates(): Pick<+/**+ * Recomputed each call so warm servers do not reuse module-load dates. (to avoid outdated dates in the PDF)+ *+ * @param now - Current time in the invoice's timezone, see {@link nowInTimeZone}.+ */+function getInvoiceDefaultDates(+ now: dayjs.Dayjs,+): 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");@@ -218,14 +225,19 @@ const ENGLISH_INVOICE_PROD_DATA_BASE = {* 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.+ *+ * @param now - The run's single timestamp, already in the invoice's timezone+ * (see {@link nowInTimeZone}). Taken as an argument rather than read here so+ * the PDF dates, the Drive folder and the notification text all come from the+ * same instant, even when the run straddles local midnight.*/-export function getEnglishInvoiceRealData() {+export function getEnglishInvoiceRealData({ now }: { now: dayjs.Dayjs }) {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)+ ...getInvoiceDefaultDates(now), // 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(),+ value: getInvoiceDefaultNumberValue(now),},} as const satisfies InvoiceData;}@@ -251,7 +263,8 @@ export function getPolishInvoiceRealData(englishInvoiceData: InvoiceData) {label: translateInvoiceNumberLabel({ language: "pl" }),value:englishInvoiceData.invoiceNumberObject?.value ??- getInvoiceDefaultNumberValue(),+ // Defensive fallback: `getEnglishInvoiceRealData` always sets this.+ getInvoiceDefaultNumberValue(nowInTimeZone(DEFAULT_INVOICE_TIME_ZONE)),},buyer: {...englishInvoiceData.buyer,diff --git a/src/app/api/generate-invoice/route.tsx b/src/app/api/generate-invoice/route.tsxindex 988b317..6f8ad51 100644--- a/src/app/api/generate-invoice/route.tsx+++ b/src/app/api/generate-invoice/route.tsx@@ -3,6 +3,10 @@ import { NextResponse, type NextRequest } from "next/server";import { env } from "@/env";import { ipLimiter } from "@/lib/rate-limit";+import {+ DEFAULT_INVOICE_TIME_ZONE,+ isValidTimeZone,+} from "./invoice-time-zone";import { runProductionGenerateMonthlyInvoice } from "./run-production-generate-invoice";export const dynamic = "force-dynamic";@@ -11,6 +15,16 @@ export const dynamic = "force-dynamic";// https://vercel.com/docs/functions/configuring-functions/durationexport const maxDuration = 30;+/**+ * Generates the monthly invoice, then uploads and sends it.+ *+ * Query params:+ * - `sendEmail` β "false" skips the email step. Defaults to on in production, off locally.+ * - `uploadToGoogleDrive` β "false" skips the Drive upload. Defaults to on in production, off locally.+ * - `timezone` β IANA name (e.g. "America/New_York") the invoice is dated in.+ * Defaults to `DEFAULT_INVOICE_TIME_ZONE`; the process timezone is UTC on+ * Vercel and is never used, so the dates do not shift around midnight.+ */export async function GET(req: NextRequest) {try {if (req.headers.get("Authorization") !== `Bearer ${env.AUTH_TOKEN}`) {@@ -46,9 +60,22 @@ export async function GET(req: NextRequest) {? isProduction: uploadToGoogleDriveParam !== "false";+ const timeZone =+ req.nextUrl.searchParams.get("timezone") ?? DEFAULT_INVOICE_TIME_ZONE;++ if (!isValidTimeZone(timeZone)) {+ return NextResponse.json(+ {+ error: `Unknown timezone "${timeZone}". Expected an IANA name, e.g. "${DEFAULT_INVOICE_TIME_ZONE}".`,+ },+ { status: 400 },+ );+ }+const result = await runProductionGenerateMonthlyInvoice({shouldSendEmail,shouldUploadToGoogleDrive,+ timeZone,});console.info("[generate-invoice] Report:", result.report);diff --git a/src/app/api/generate-invoice/run-production-generate-invoice.ts b/src/app/api/generate-invoice/run-production-generate-invoice.tsindex 223662d..6d53367 100644--- a/src/app/api/generate-invoice/run-production-generate-invoice.ts+++ b/src/app/api/generate-invoice/run-production-generate-invoice.ts@@ -13,6 +13,7 @@ import {type GenerateInvoiceDeps,type GenerateInvoiceResult,} from "./generate-invoice";+import { nowInTimeZone } from "./invoice-time-zone";import {getEnglishInvoiceRealData,getPolishInvoiceRealData,@@ -48,12 +49,20 @@ function buildGenerateInvoiceDeps(** @param options.shouldSendEmail - Set true to send invoice email to recipient.* @param options.shouldUploadToGoogleDrive - Set true to upload invoices to Google Drive.+ * @param options.timeZone - IANA timezone the invoice is dated in.*/export async function runProductionGenerateMonthlyInvoice(options: {shouldSendEmail: boolean;shouldUploadToGoogleDrive: boolean;+ timeZone: string;}): Promise<GenerateInvoiceResult> {- const englishInvoiceData = getEnglishInvoiceRealData();+ // Captured once for the whole run: the PDF dates, the Drive month/year folder,+ // the file names and the notification text all derive from this single+ // instant, so a run that straddles local midnight cannot date the PDF one day+ // and file it under the next.+ const now = nowInTimeZone(options.timeZone);++ const englishInvoiceData = getEnglishInvoiceRealData({ now });const polishInvoiceData = getPolishInvoiceRealData(englishInvoiceData);return await generateInvoice(@@ -66,6 +75,8 @@ export async function runProductionGenerateMonthlyInvoice(options: {invoiceEmailRecipient: env.INVOICE_EMAIL_RECIPIENT,englishInvoiceData,polishInvoiceData,+ timeZone: options.timeZone,+ now,},);}diff --git a/src/app/api/telegram-webhook/__tests__/route.test.ts b/src/app/api/telegram-webhook/__tests__/route.test.tsindex aa65acf..9dad516 100644--- a/src/app/api/telegram-webhook/__tests__/route.test.ts+++ b/src/app/api/telegram-webhook/__tests__/route.test.ts@@ -16,6 +16,7 @@ const MOCK_REPORT = {notifiedByTelegram: true,notifiedByEmail: true,totalTimeTook: "1.23s",+ timeZone: "Europe/Warsaw",} as const satisfies GenerateInvoiceReport;const MOCK_ENV = {@@ -225,6 +226,7 @@ describe("POST /api/telegram-webhook β HTTP layer", () => {expect(mockRunProduction).toHaveBeenCalledWith({shouldSendEmail: false,shouldUploadToGoogleDrive: false,+ timeZone: "Europe/Warsaw",});expect(mockClearQueuedJob).toHaveBeenCalledWith(CHAT_ID);});@@ -239,6 +241,7 @@ describe("POST /api/telegram-webhook β HTTP layer", () => {expect(mockRunProduction).toHaveBeenCalledWith({shouldSendEmail: true,shouldUploadToGoogleDrive: true,+ timeZone: "Europe/Warsaw",});expect(mockSendTelegramMessage).toHaveBeenCalledTimes(1);expect(mockSendTelegramMessage).toHaveBeenCalledWith({diff --git a/src/app/api/telegram-webhook/route.ts b/src/app/api/telegram-webhook/route.tsindex fb046d2..7b3a6c5 100644--- a/src/app/api/telegram-webhook/route.ts+++ b/src/app/api/telegram-webhook/route.ts@@ -1,6 +1,7 @@import { waitUntil } from "@vercel/functions";import { NextResponse, type NextRequest } from "next/server";+import { DEFAULT_INVOICE_TIME_ZONE } from "@/app/api/generate-invoice/invoice-time-zone";import { runProductionGenerateMonthlyInvoice } from "@/app/api/generate-invoice/run-production-generate-invoice";import {clearQueuedJob,@@ -128,6 +129,7 @@ async function handleInvoiceGenerate({ chatId }: { chatId: number }) {const result = await runProductionGenerateMonthlyInvoice({shouldSendEmail: isProduction,shouldUploadToGoogleDrive: isProduction,+ timeZone: DEFAULT_INVOICE_TIME_ZONE,});console.info("[telegram-webhook] Report:", result.report);diff --git a/src/app/constants/index.ts b/src/app/constants/index.tsindex 6d10d80..20d820a 100644--- a/src/app/constants/index.ts+++ b/src/app/constants/index.ts@@ -52,9 +52,12 @@ const DEFAULT_TEMPLATE = SUPPORTED_TEMPLATES[0];* Format: 1/MM-YYYY (e.g., 1/03-2024)** Used as default **invoice number** when creating a new invoice+ *+ * @param date - Instant the number is derived from. Defaults to `dayjs()`, which+ * follows the process timezone β server callers pass an explicit zoned instant.*/-export function getInvoiceDefaultNumberValue() {- return `1/${dayjs().format("MM-YYYY")}` as const;+export function getInvoiceDefaultNumberValue(date: dayjs.Dayjs = dayjs()) {+ return `1/${date.format("MM-YYYY")}` as const;}/**