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
feat: improvements to tg webhook (#228)
Vlad Sazonaub12ca4b7cb88
diff --git a/README.md b/README.mdindex 8ac174e..8489628 100644--- a/README.md+++ b/README.md@@ -15,9 +15,7 @@<a href="#self-host">Self-host</a></p>- <a href="https://github.com/VladSez/easy-invoice-pdf" title="Star EasyInvoicePDF on GitHub - free & open-source invoice generator">- <strong>⭐ Like the project? Star it on GitHub</strong>- </a>+<strong>⭐ Like the project? <a href="https://github.com/VladSez/easy-invoice-pdf" title="Star EasyInvoicePDF on GitHub - free & open-source invoice generator">Star it on GitHub</a></strong><p>Built by <a href="https://vladsazon.com?ref=github"><strong>Vlad Sazonau</strong></a>diff --git a/e2e/buyer.test.ts b/e2e/buyer.test.tsindex 93fcfd0..ca523bc 100644--- a/e2e/buyer.test.ts+++ b/e2e/buyer.test.ts@@ -4,7 +4,8 @@ import { expect, test } from "@playwright/test";test.describe("Buyer management", () => {test.beforeEach(async ({ page }) => {- await page.goto("/");+ await page.goto("/?template=default");+ await expect(page).toHaveURL("/?template=default");});test("create/edit buyer", async ({ page }) => {@@ -1067,6 +1068,7 @@ test.describe("Buyer management", () => {});await page.goto("/?template=default");+ await expect(page).toHaveURL("/?template=default");await page.getByRole("button", { name: "New Buyer" }).click();diff --git a/e2e/invoice-form.test.ts b/e2e/invoice-form.test.tsindex 6ce7991..1cb3877 100644--- a/e2e/invoice-form.test.ts+++ b/e2e/invoice-form.test.ts@@ -22,7 +22,8 @@ import {test.describe("Invoice Generator Page", () => {test.beforeEach(async ({ page }) => {- await page.goto("/");+ await page.goto("/?template=default");+ await expect(page).toHaveURL("/?template=default");});test("returns permanent redirect from /:locale/app to /", async ({diff --git a/e2e/seller.test.ts b/e2e/seller.test.tsindex 3bec405..1604f8b 100644--- a/e2e/seller.test.ts+++ b/e2e/seller.test.ts@@ -4,7 +4,7 @@ import { expect, test } from "@playwright/test";test.describe("Seller management", () => {test.beforeEach(async ({ page }) => {- await page.goto("/");+ await page.goto("/?template=default");await expect(page).toHaveURL("/?template=default");});@@ -1131,6 +1131,7 @@ test.describe("Seller management", () => {});await page.goto("/?template=default");+ await expect(page).toHaveURL("/?template=default");await page.getByRole("button", { name: "New Seller" }).click();diff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts b/e2e/stripe-invoice-template/stripe-invoice-template.test.tsindex 966bbe3..cd9c9d8 100644--- a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts+++ b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts@@ -101,9 +101,6 @@ test.describe("Stripe Invoice Template", () => {.getByRole("combobox", { name: "Invoice Template" }).selectOption("stripe");- // Wait for URL to be updated- await page.waitForURL("/?template=stripe");-await expect(page).toHaveURL("/?template=stripe");// Logo section should still be visible on Stripe template@@ -397,7 +394,6 @@ test.describe("Stripe Invoice Template", () => {test("Signature fields only appears for default template", async ({page,}) => {- // Verify default template is selected by defaultawait expect(page).toHaveURL("/?template=default");const finalSection = page.getByTestId("final-section");diff --git a/package.json b/package.jsonindex 77eb565..5ee5293 100644--- a/package.json+++ b/package.json@@ -5,7 +5,8 @@"packageManager": "[email protected]+sha512.3590e550d5384caa39bd5c7c739f72270234b2f6059e13018f975c313b1eb9fefcc09714048765d4d9efe961382c312e624572c0420762bdc5d5940cdf9be73a","pnpm": {"minimumReleaseAge": 4320,- "trustPolicy": "no-downgrade"+ "trustPolicy": "no-downgrade",+ "blockExoticSubdeps": true},"scripts": {"dev": "next dev",@@ -61,6 +62,7 @@"@types/ua-parser-js": "0.7.39","@upstash/ratelimit": "2.0.5","@upstash/redis": "1.34.6",+ "@vercel/functions": "3.5.1","@vercel/speed-insights": "1.2.0","class-variance-authority": "0.7.1","clsx": "2.1.1",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4c7eda0..a42075a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -80,6 +80,9 @@ importers:'@upstash/redis':specifier: 1.34.6version: 1.34.6+ '@vercel/functions':+ specifier: 3.5.1+ version: 3.5.1'@vercel/speed-insights':specifier: 1.2.0version: 1.2.0([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])@@ -2787,6 +2790,19 @@ packages:'@upstash/[email protected]':resolution: {integrity: sha512-/ic+NszsXyIl2P8aExL7xETxgmzyhn6txG4senGDgd524bypGEJs1TMzLDeOV+PFVuacc10wZVJLIj6aRZZNaw==}+ '@vercel/[email protected]':+ resolution: {integrity: sha512-ndh5v+uhWqGA8033oD0i0KHvqUHcLlLCOaLOw5L+xx5zVsWUSQcZPKEYk2nm51aisnKhcnTylxnOmhx+w4UCRA==}+ engines: {node: '>= 20'}+ peerDependencies:+ '@aws-sdk/credential-provider-web-identity': '*'+ peerDependenciesMeta:+ '@aws-sdk/credential-provider-web-identity':+ optional: true++ '@vercel/[email protected]':+ resolution: {integrity: sha512-H6B+/ig/GoahccL3WZjiHayHw1H5KhvTJNceqYulwfK9kkz5iul2hTmYzcJ7tTCQzyd0dutuL9xYFZCyLUqsog==}+ engines: {node: '>= 20'}+'@vercel/[email protected]':resolution: {integrity: sha512-y9GVzrUJ2xmgtQlzFP2KhVRoCglwfRQgjyfY607aU0hh0Un6d0OUyrJkjuAlsV18qR4zfoFPs/BiIj9YDS6Wzw==}peerDependencies:@@ -9512,6 +9528,12 @@ snapshots:dependencies:crypto-js: 4.2.0+ '@vercel/[email protected]':+ dependencies:+ '@vercel/oidc': 3.4.1++ '@vercel/[email protected]': {}+'@vercel/[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])':optionalDependencies:next: 14.2.15(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])diff --git a/src/app/api/generate-invoice/route.tsx b/src/app/api/generate-invoice/route.tsxindex c52d635..d916b1d 100644--- a/src/app/api/generate-invoice/route.tsx+++ b/src/app/api/generate-invoice/route.tsx@@ -4,6 +4,7 @@ import {createOrFindInvoiceFolder,initializeGoogleDrive,uploadFile,+ type GoogleDriveFile,} from "@/lib/google-drive";import { resend } from "@/lib/resend";import { sendTelegramMessage } from "@/lib/telegram";@@ -58,10 +59,22 @@ export async function GET(req: NextRequest) {);}- // only send email if the query parameter "sendEmail" is not "false" (for backwards compatibility), we want to send email by default, but allow to disable it for testing purposes+ /**+ * Determines if email notifications should be sent.+ * Defaults to true for backwards compatibility.+ * Can be disabled by passing ?sendEmail=false query parameter for testing.+ */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 GENERATED_ENGLISH_INVOICE_PDF_DOCUMENT = renderToBuffer(<InvoicePdfTemplateToRenderOnBackendinvoiceData={ENGLISH_INVOICE_REAL_DATA}@@ -159,49 +172,57 @@ export async function GET(req: NextRequest) {// *___________UPLOAD INVOICES TO GOOGLE DRIVE___________*- // Initialize Google Drive- const googleDrive = await initializeGoogleDrive();-- const currentMonth = dayjs().format("MM");- const currentYear = dayjs().format("YYYY");+ let folderToUploadInvoices: GoogleDriveFile | null = null;+ let googleDriveFolderPath = "";- // 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,- });+ if (shouldSaveToGoogleDrive) {+ // Initialize Google Drive+ const googleDrive = await initializeGoogleDrive();- const { folderToUploadInvoices, googleDriveFolderPath } = result;+ const currentMonth = dayjs().format("MM");+ const currentYear = dayjs().format("YYYY");- // Upload each invoice to Google Drive- const uploadPromises = ATTACHMENTS.map((attachment) =>- uploadFile({+ // Create the month folder (this will automatically create/find the year folder)+ const result = await createOrFindInvoiceFolder({googleDrive,- fileName: attachment.filename,- fileContent: Buffer.from(attachment.content),- folderId: folderToUploadInvoices.id,- }),- );+ parentFolderId: env.GOOGLE_DRIVE_PARENT_FOLDER_ID,+ month: currentMonth,+ year: currentYear,+ });- const uploadResults = await Promise.allSettled(uploadPromises);- const failedUploads = uploadResults.filter(- (result): result is PromiseRejectedResult => result.status === "rejected",- );+ folderToUploadInvoices = result.folderToUploadInvoices;+ googleDriveFolderPath = result.googleDriveFolderPath;- if (failedUploads.length > 0) {- console.error(- "[generate-invoice] Some files failed to upload to Google Drive:",- failedUploads,+ // Upload each invoice to Google Drive+ const uploadPromises = ATTACHMENTS.map((attachment) =>+ uploadFile({+ googleDrive,+ fileName: attachment.filename,+ fileContent: Buffer.from(attachment.content),+ folderId: folderToUploadInvoices!.id,+ }),);- return NextResponse.json(- {- error: "[generate-invoice] Failed to upload invoices to Google Drive",- },- { status: 500 },+ 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 =@@ -226,8 +247,11 @@ Date: *${dayjs().format("MMMM D, YYYY")}*The generated invoices are included in the attachments. Please check them carefully.-[View invoice online](${invoiceUrl})-[View in Google Drive](${folderToUploadInvoices.webViewLink}) path: *${googleDriveFolderPath}*+[View invoice online](${invoiceUrl})${+ folderToUploadInvoices+ ? `\n[View in Google Drive](${folderToUploadInvoices.webViewLink}) path: *${googleDriveFolderPath}*`+ : ""+ }*☝️ Important - Don't forget to:*- [Send email to company](${companyEmailLink})@@ -260,8 +284,11 @@ EasyInvoicePDF.com`,<br/><br/>- <a href="${invoiceUrl}">View invoice online</a><br/>- <a href="${folderToUploadInvoices.webViewLink}">View in Google Drive</a> path: <b>${googleDriveFolderPath}</b>+ <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/>diff --git a/src/app/api/telegram-webhook/route.ts b/src/app/api/telegram-webhook/route.tsindex 37b9dcb..13f60aa 100644--- a/src/app/api/telegram-webhook/route.ts+++ b/src/app/api/telegram-webhook/route.ts@@ -1,7 +1,9 @@import { telegramUpdateSchema } from "@/app/api/telegram-webhook/schema/telegram-schema";import { env } from "@/env";import { sendTelegramMessage } from "@/lib/telegram";+import { clearQueuedJob, queueInvoiceGeneration } from "@/lib/telegram-queue";+import { waitUntil } from "@vercel/functions";import { NextResponse, type NextRequest } from "next/server";export const dynamic = "force-dynamic";@@ -27,6 +29,11 @@ export async function POST(req: NextRequest) {"[telegram-webhook] Invalid webhook payload:",parseResult.error.errors,);++ await sendTelegramMessage({+ message: "❌ Invalid webhook payload.",+ });+return new NextResponse(JSON.stringify({ ok: true }), {status: 200,headers: { "Content-Type": "application/json" },@@ -51,40 +58,17 @@ export async function POST(req: NextRequest) {});}- console.error(- "[telegram-webhook] Authorized user triggered /generate command",- );-- await sendTelegramMessage({- message: "⏳ Generating invoices... Please wait.",- });-- const BASE_URL =- `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}` ||- "http://localhost:3000";-- const API_URL = `${BASE_URL}/api/generate-invoice`;-- const response = await fetch(API_URL, {- 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",- });+ const chatId = update.message.chat.id;- if (!response.ok) {- const errorText = await response.text();+ // Check if already processing - prevents duplicate invoices from Telegram retries+ const queued = await queueInvoiceGeneration(chatId);+ if (!queued) {console.error(- `[telegram-webhook] Failed to generate invoice: ${response.status} ${errorText}`,+ `[telegram-webhook] Job already queued for chat ${chatId}, ignoring retry`,);await sendTelegramMessage({- message: `❌ Failed to generate invoices.\n\nStatus: ${response.status}\nError: ${errorText}`,+ message: "⏳ Job already queued for this chat, ignoring retry",});return new NextResponse(JSON.stringify({ ok: true }), {@@ -93,16 +77,14 @@ export async function POST(req: NextRequest) {});}- return new NextResponse(- JSON.stringify({- ok: true,- message: "[telegram-webhook] Invoices generated and sent successfully!",- }),- {- status: 200,- headers: { "Content-Type": "application/json" },- },- );+ // Fire-and-forget invoice generation: don't await the background work+ // https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package#waituntil+ waitUntil(handleInvoiceGenerate({ chatId }));++ return new NextResponse(JSON.stringify({ ok: true }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });} catch (error) {console.error("[telegram-webhook] Error in webhook:", error);@@ -123,3 +105,57 @@ export async function POST(req: NextRequest) {});}}++/**+ * Handles the invoice generation request triggered via Telegram.+ * Sends status updates to the user and manages the generation queue.+ *+ * @param chatId - The Telegram chat ID to send status messages to+ */+async function handleInvoiceGenerate({ chatId }: { chatId: number }) {+ try {+ await sendTelegramMessage({+ 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+ });++ if (!response.ok) {+ const errorText = await response.text();+ console.error(+ `[telegram-webhook] Failed to generate invoice: ${response.status} ${errorText}`,+ );++ await sendTelegramMessage({+ message: `❌ Failed to generate invoices.\n\nStatus: ${response.status}`,+ });+ return;+ }+ } catch (error) {+ console.error("[telegram-webhook] handleInvoiceGenerate error:", error);+ try {+ await sendTelegramMessage({+ message: `🚨 Error: ${error instanceof Error ? error.message : "Unknown error"}`,+ });+ } catch (e) {+ console.error("[telegram-webhook] Failed to send error message:", e);+ }+ } finally {+ await clearQueuedJob(chatId);+ }+}diff --git a/src/app/api/telegram-webhook/schema/telegram-schema.ts b/src/app/api/telegram-webhook/schema/telegram-schema.tsindex 5507b04..b811e7c 100644--- a/src/app/api/telegram-webhook/schema/telegram-schema.ts+++ b/src/app/api/telegram-webhook/schema/telegram-schema.ts@@ -3,19 +3,15 @@ import { z } from "zod";const telegramMessageSchema = z.object({message_id: z.number().int(),- from: z- .object({- id: z.number().int(),- is_bot: z.boolean(),- first_name: z.string(),- })- .strict(),- chat: z- .object({- id: z.number().int(),- type: z.string(),- })- .strict(),+ from: z.object({+ id: z.number().int(),+ is_bot: z.boolean(),+ first_name: z.string(),+ }),+ chat: z.object({+ id: z.number().int(),+ type: z.string(),+ }),date: z.number().int().nonnegative(),text: z.string()@@ -26,13 +22,11 @@ const telegramMessageSchema = z.optional(),entities: z.array(- z- .object({- offset: z.number().int().nonnegative(),- length: z.number().int().positive(),- type: z.string(),- })- .strict(),+ z.object({+ offset: z.number().int().nonnegative(),+ length: z.number().int().positive(),+ type: z.string(),+ }),).optional(),})diff --git a/src/app/schema/index.ts b/src/app/schema/index.tsindex b5d94bf..8c90aca 100644--- a/src/app/schema/index.ts+++ b/src/app/schema/index.ts@@ -722,249 +722,237 @@ export const APP_VERSION = "1.0.0";*/export const SCHEMA_VERSION = "1.0.0";-export const invoiceItemSchema = z- .object({- // Show/hide Number column on PDF- invoiceItemNumberIsVisible: z.boolean().default(true),-- name: z- .string()- .max(500, "Item name must not exceed 500 characters")- .trim()- .optional(),- nameFieldIsVisible: z.boolean().default(true),-- typeOfGTU: z- .string()- .max(50, "Type of GTU must not exceed 50 characters")- .trim()- .optional()- .default(""),- typeOfGTUFieldIsVisible: z.boolean().default(true),-- amount: z- .any()- .refine((val) => val !== "", {- message: "Amount is required",- })- .transform(Number)- .refine((val) => val > 0, {- message: "Amount must be positive",- })- .refine((val) => val <= 9_999_999_999.99, {- message: "Amount must not exceed 9 999 999 999.99",- }),- amountFieldIsVisible: z.boolean().default(true),-- unit: z.string().trim().optional(),- unitFieldIsVisible: z.boolean().default(true),-- netPrice: z- .any()- .refine((val) => val !== "", {- message: "Net price is required",- })- .transform(Number)- .refine((val) => val >= 0, {- message: "Net price must be >= 0",- })- .refine((val) => val <= 100_000_000_000, {- message: "Net price must not exceed 100 billion",- }),- netPriceFieldIsVisible: z.boolean().default(true),-- // Tax rate. Accepts numbers 0-100 or any text string (i.e. NP, OO, etc)- // Valid inputs and their outputs:- // - "23" -> 23 (number)- // - "100" -> 100 (number)- // - "NP" -> "NP" (string)- vat: z- .preprocess(- // z.preprocess runs before Zod does any validation, parsing, or type checking on the schema it wraps.- (raw) => {- // Handle null/undefined by returning empty string for validation- if (raw == null) return "";-- // Trim whitespace from string inputs, pass through other types as-is- const val = typeof raw === "string" ? raw.trim() : raw;-- // Empty strings should fail the required validation- if (val === "") return "";-- // Attempt to convert to number- const num = Number(val);-- // If conversion succeeds, return as number (for 0-100 validation)- // Otherwise, return as string (for text values like "NP", "OO", etc)- return Number.isNaN(num) ? val : num;+export const invoiceItemSchema = z.object({+ // Show/hide Number column on PDF+ invoiceItemNumberIsVisible: z.boolean().default(true),++ name: z+ .string()+ .max(500, "Item name must not exceed 500 characters")+ .trim()+ .optional(),+ nameFieldIsVisible: z.boolean().default(true),++ typeOfGTU: z+ .string()+ .max(50, "Type of GTU must not exceed 50 characters")+ .trim()+ .optional()+ .default(""),+ typeOfGTUFieldIsVisible: z.boolean().default(true),++ amount: z+ .any()+ .refine((val) => val !== "", {+ message: "Amount is required",+ })+ .transform(Number)+ .refine((val) => val > 0, {+ message: "Amount must be positive",+ })+ .refine((val) => val <= 9_999_999_999.99, {+ message: "Amount must not exceed 9 999 999 999.99",+ }),+ amountFieldIsVisible: z.boolean().default(true),++ unit: z.string().trim().optional(),+ unitFieldIsVisible: z.boolean().default(true),++ netPrice: z+ .any()+ .refine((val) => val !== "", {+ message: "Net price is required",+ })+ .transform(Number)+ .refine((val) => val >= 0, {+ message: "Net price must be >= 0",+ })+ .refine((val) => val <= 100_000_000_000, {+ message: "Net price must not exceed 100 billion",+ }),+ netPriceFieldIsVisible: z.boolean().default(true),++ // Tax rate. Accepts numbers 0-100 or any text string (i.e. NP, OO, etc)+ // Valid inputs and their outputs:+ // - "23" -> 23 (number)+ // - "100" -> 100 (number)+ // - "NP" -> "NP" (string)+ vat: z+ .preprocess(+ // z.preprocess runs before Zod does any validation, parsing, or type checking on the schema it wraps.+ (raw) => {+ // Handle null/undefined by returning empty string for validation+ if (raw == null) return "";++ // Trim whitespace from string inputs, pass through other types as-is+ const val = typeof raw === "string" ? raw.trim() : raw;++ // Empty strings should fail the required validation+ if (val === "") return "";++ // Attempt to convert to number+ const num = Number(val);++ // If conversion succeeds, return as number (for 0-100 validation)+ // Otherwise, return as string (for text values like "NP", "OO", etc)+ return Number.isNaN(num) ? val : num;+ },+ z.union(+ [+ z+ .number()+ .min(+ 0,+ `Tax rate must be a number between 0-100 or any text (i.e. NP, OO, etc).`,+ )+ .max(+ 100,+ `Tax rate must be a number between 0-100 or any text (i.e. NP, OO, etc).`,+ ),+ z+ .string()+ .min(+ 1,+ `Tax rate is required. Enter a number (0-100) or any text (i.e. NP, OO, etc).`,+ ),+ ],+ {+ errorMap: () => ({+ message:+ "Tax rate is required. Enter a number (0-100) or any text (i.e. NP, OO, etc).",+ }),},- z.union(- [- z- .number()- .min(- 0,- `Tax rate must be a number between 0-100 or any text (i.e. NP, OO, etc).`,- )- .max(- 100,- `Tax rate must be a number between 0-100 or any text (i.e. NP, OO, etc).`,- ),- z- .string()- .min(- 1,- `Tax rate is required. Enter a number (0-100) or any text (i.e. NP, OO, etc).`,- ),- ],- {- errorMap: () => ({- message:- "Tax rate is required. Enter a number (0-100) or any text (i.e. NP, OO, etc).",- }),- },- ),- )- .describe(- "Tax rate. Accepts numbers 0-100 or any text (i.e. NP, OO, etc).",),+ )+ .describe(+ "Tax rate. Accepts numbers 0-100 or any text (i.e. NP, OO, etc).",+ ),- vatFieldIsVisible: z.boolean().default(true),+ vatFieldIsVisible: z.boolean().default(true),- netAmount: z.coerce.number().nonnegative("Net amount must be non-negative"),- netAmountFieldIsVisible: z.boolean().default(true),+ netAmount: z.coerce.number().nonnegative("Net amount must be non-negative"),+ netAmountFieldIsVisible: z.boolean().default(true),- vatAmount: z.coerce.number().nonnegative("VAT amount must be non-negative"),- vatAmountFieldIsVisible: z.boolean().default(true),+ vatAmount: z.coerce.number().nonnegative("VAT amount must be non-negative"),+ vatAmountFieldIsVisible: z.boolean().default(true),- preTaxAmount: z.coerce- .number()- .nonnegative("Pre-tax amount must be non-negative"),- preTaxAmountFieldIsVisible: z.boolean().default(true),- })- .strict();+ preTaxAmount: z.coerce+ .number()+ .nonnegative("Pre-tax amount must be non-negative"),+ preTaxAmountFieldIsVisible: z.boolean().default(true),+});export type InvoiceItemData = z.infer<typeof invoiceItemSchema>;-export const sellerSchema = z- .object({- id: z.string().optional(),-- name: z- .string()- .min(1, "Seller name is required")- .max(500, "Seller name must not exceed 500 characters")- .trim(),- address: z- .string()- .min(1, "Seller address is required")- .max(500, "Seller address must not exceed 500 characters")- .trim(),-- vatNo: z- .string()- .max(200, "VAT number must not exceed 200 characters")- .trim()- .optional(),- // not really only a vatNo anymore, it's a more general tax number (but we keep the name for simplicity, for now)- vatNoLabelText: z- .string()- .min(1, "Tax number label is required")- .max(50, "Tax number label must not exceed 50 characters")- .trim()- .default("VAT no")- .describe(- "Customizable tax number label. Defaults to ‘VAT no’, but you can change it to any text (e.g. Tax no, VAT no, etc.)",- ),- vatNoFieldIsVisible: z.boolean().default(true),+export const sellerSchema = z.object({+ id: z.string().optional(),- email: z- .string()- .trim()- .refine(- (val) => val === "" || z.string().email().safeParse(val).success,- {- message: "Invalid email address",- },- )- .optional(),- emailFieldIsVisible: z.boolean().default(true),-- accountNumber: z- .string()- .max(200, "Account number must not exceed 200 characters")- .trim()- .optional(),- accountNumberFieldIsVisible: z.boolean().default(true),-- swiftBic: z- .string()- .max(200, "SWIFT/BIC must not exceed 200 characters")- .trim()- .optional(),- swiftBicFieldIsVisible: z.boolean().default(true),-- notes: z- .string()- .max(750, "Notes must not exceed 750 characters")- .trim()- .optional(),- notesFieldIsVisible: z.boolean().default(true),- })- .strict();+ name: z+ .string()+ .min(1, "Seller name is required")+ .max(500, "Seller name must not exceed 500 characters")+ .trim(),+ address: z+ .string()+ .min(1, "Seller address is required")+ .max(500, "Seller address must not exceed 500 characters")+ .trim(),++ vatNo: z+ .string()+ .max(200, "VAT number must not exceed 200 characters")+ .trim()+ .optional(),+ // not really only a vatNo anymore, it's a more general tax number (but we keep the name for simplicity, for now)+ vatNoLabelText: z+ .string()+ .min(1, "Tax number label is required")+ .max(50, "Tax number label must not exceed 50 characters")+ .trim()+ .default("VAT no")+ .describe(+ "Customizable tax number label. Defaults to ‘VAT no’, but you can change it to any text (e.g. Tax no, VAT no, etc.)",+ ),+ vatNoFieldIsVisible: z.boolean().default(true),++ email: z+ .string()+ .trim()+ .refine((val) => val === "" || z.string().email().safeParse(val).success, {+ message: "Invalid email address",+ })+ .optional(),+ emailFieldIsVisible: z.boolean().default(true),++ accountNumber: z+ .string()+ .max(200, "Account number must not exceed 200 characters")+ .trim()+ .optional(),+ accountNumberFieldIsVisible: z.boolean().default(true),++ swiftBic: z+ .string()+ .max(200, "SWIFT/BIC must not exceed 200 characters")+ .trim()+ .optional(),+ swiftBicFieldIsVisible: z.boolean().default(true),++ notes: z+ .string()+ .max(750, "Notes must not exceed 750 characters")+ .trim()+ .optional(),+ notesFieldIsVisible: z.boolean().default(true),+});export type SellerData = z.infer<typeof sellerSchema>;-export const buyerSchema = z- .object({- id: z.string().optional(),-- name: z- .string()- .min(1, "Buyer name is required")- .max(500, "Buyer name must not exceed 500 characters")- .trim(),- address: z- .string()- .min(1, "Buyer address is required")- .max(500, "Buyer address must not exceed 500 characters")- .trim(),- vatNo: z- .string()- .max(200, "VAT number must not exceed 200 characters")- .trim()- .optional(),- vatNoLabelText: z- .string()- .min(1, "Tax number label is required")- .max(50, "Tax number label must not exceed 50 characters")- .trim()- .default("VAT no")- .describe(- "Customizable tax number label. Defaults to ‘VAT no’, but you can change it to any text (e.g. Tax no, VAT no, etc.)",- ),- vatNoFieldIsVisible: z.boolean().default(true),+export const buyerSchema = z.object({+ id: z.string().optional(),- email: z- .string()- .trim()- .refine(- (val) => val === "" || z.string().email().safeParse(val).success,- {- message: "Invalid email address",- },- )- .optional(),- emailFieldIsVisible: z.boolean().default(true),-- notes: z- .string()- .max(750, "Notes must not exceed 750 characters")- .trim()- .optional(),- notesFieldIsVisible: z.boolean().default(true),- })- .strict();+ name: z+ .string()+ .min(1, "Buyer name is required")+ .max(500, "Buyer name must not exceed 500 characters")+ .trim(),+ address: z+ .string()+ .min(1, "Buyer address is required")+ .max(500, "Buyer address must not exceed 500 characters")+ .trim(),+ vatNo: z+ .string()+ .max(200, "VAT number must not exceed 200 characters")+ .trim()+ .optional(),+ vatNoLabelText: z+ .string()+ .min(1, "Tax number label is required")+ .max(50, "Tax number label must not exceed 50 characters")+ .trim()+ .default("VAT no")+ .describe(+ "Customizable tax number label. Defaults to ‘VAT no’, but you can change it to any text (e.g. Tax no, VAT no, etc.)",+ ),+ vatNoFieldIsVisible: z.boolean().default(true),++ email: z+ .string()+ .trim()+ .refine((val) => val === "" || z.string().email().safeParse(val).success, {+ message: "Invalid email address",+ })+ .optional(),+ emailFieldIsVisible: z.boolean().default(true),++ notes: z+ .string()+ .max(750, "Notes must not exceed 750 characters")+ .trim()+ .optional(),+ notesFieldIsVisible: z.boolean().default(true),+});export type BuyerData = z.infer<typeof buyerSchema>;diff --git a/src/lib/google-drive.ts b/src/lib/google-drive.tsindex 1d53a3c..efd96fa 100644--- a/src/lib/google-drive.ts+++ b/src/lib/google-drive.ts@@ -3,7 +3,7 @@ import { z } from "zod";import { Readable } from "node:stream";import { env } from "@/env";-interface GoogleDriveFile {+export interface GoogleDriveFile {id: string;name: string;mimeType: string;diff --git a/src/lib/telegram-queue.ts b/src/lib/telegram-queue.tsnew file mode 100644index 0000000..dae5ec5--- /dev/null+++ b/src/lib/telegram-queue.ts@@ -0,0 +1,38 @@+import { Redis } from "@upstash/redis";+import { env } from "@/env";++const redis = new Redis({+ url: env.UPSTASH_REDIS_REST_URL,+ token: env.UPSTASH_REDIS_REST_TOKEN,+});++/**+ * Queues an invoice generation job for a specific Telegram chat.+ * Prevents duplicate invoice generation from Telegram webhook retries by checking+ * if a job is already in progress for this chat.+ * @param chatId - Telegram chat ID to queue the job for+ * @returns Promise<boolean> - true if job was successfully queued, false if already queued+ */+export async function queueInvoiceGeneration(chatId: number): Promise<boolean> {+ const key = `telegram:job:${chatId}` as const;++ // Atomically set key only if it doesn't exist, with 10-minutes TTL+ // Returns "OK" on success, null if key already existed (preventing race conditions)+ const result = await redis.set(+ key,+ JSON.stringify({ createdAt: new Date().toISOString() }),+ { nx: true, ex: 600 }, // nx: only set if key doesn't exist, ex: 10 minutes TTL+ );++ return result === "OK";+}++/**+ * Clears a queued invoice generation job for a specific Telegram chat.+ * Should be called after invoice generation completes or fails.+ * @param chatId - Telegram chat ID to clear the job for+ * @returns Promise<void>+ */+export async function clearQueuedJob(chatId: number): Promise<void> {+ await redis.del(`telegram:job:${chatId}`);+}