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: save invoice to google drive and tg notification (#113)
Vlad Sazonaud6a8e5cafbe3
diff --git a/e2e/invoice-form.test.ts b/e2e/invoice-form.test.tsindex 9316515..00d6bdf 100644--- a/e2e/invoice-form.test.ts+++ b/e2e/invoice-form.test.ts@@ -1,6 +1,7 @@import {ACCORDION_STATE_LOCAL_STORAGE_KEY,CURRENCY_SYMBOLS,+ CURRENCY_TO_LABEL,LANGUAGE_TO_LABEL,PDF_DATA_LOCAL_STORAGE_KEY,SUPPORTED_CURRENCIES,@@ -165,7 +166,10 @@ test.describe("Invoice Generator Page", () => {// Verify all supported currencies are available as options with correct labelsfor (const currency of SUPPORTED_CURRENCIES) {const currencySymbol = CURRENCY_SYMBOLS[currency];- const expectedLabel = `${currency} ${currencySymbol}`.trim();+ const currencyFullName = CURRENCY_TO_LABEL[currency];++ const expectedLabel =+ `${currency} ${currencySymbol} ${currencyFullName}`.trim();await expect(currencySelect.locator(`option[value="${currency}"]`)diff --git a/eslint.config.mjs b/eslint.config.mjsindex a0ecc6e..8a930bb 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -50,6 +50,14 @@ export default tseslint.config(message:"Please use @react-pdf/renderer/lib/react-pdf.browser instead. Check https://github.com/diegomura/react-pdf/issues/2890#issuecomment-2443831013 for more details.",},+ {+ name: "node:process",+ message: "Please use @/env.ts instead.",+ },+ {+ name: "process",+ message: "Please use @/env.ts instead.",+ },],},],diff --git a/next.config.mjs b/next.config.mjsindex fdac273..f6bf906 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -10,8 +10,12 @@ import fs from "node:fs";const loadTsFileViaJiti = createJiti(fileURLToPath(import.meta.url));-// Validate translations object against schema, that is used to translate pdf fields-async function validateTranslations() {+// Import ENV file here to validate during build. Using jiti@^1 we can import .ts files :)+loadTsFileViaJiti("./src/env");++// Validate all i18n files, that are used to translate the /about page+async function validatei18nAndTranslationFiles() {+ // Validate our custom translations object against schema, that is used to translate pdf fieldstry {// Import the translations schema using jiti// @ts-ignore@@ -20,6 +24,7 @@ async function validateTranslations() {);const result = translationsSchema.safeParse(TRANSLATIONS);+if (!result.success) {console.error("❌ Invalid translations:", result.error.message);process.exit(1);@@ -28,15 +33,9 @@ async function validateTranslations() {console.error("❌ Error validating translations:", error);process.exit(1);}-}-// Validate all i18n files, that are used to translate the /about page-async function validatei18n() {const messagesDir = path.join(process.cwd(), "messages");- // Validate translations first- await validateTranslations();-// Import the messages schema using jiti// @ts-ignoreconst { messagesSchema } = await loadTsFileViaJiti.import(@@ -103,7 +102,7 @@ async function validatei18n() {}// Since the function is now async, we need to handle it properly-validatei18n().catch((error) => {+validatei18nAndTranslationFiles().catch((error) => {console.error("❌ Fatal error during validation:", error);process.exit(1);});diff --git a/package.json b/package.jsonindex 315c27e..f43567b 100644--- a/package.json+++ b/package.json@@ -42,6 +42,7 @@"@react-email/tailwind": "1.0.4","@react-pdf/renderer": "4.3.0","@sentry/nextjs": "9.3.0",+ "@t3-oss/env-nextjs": "0.13.4","@types/ua-parser-js": "0.7.39","@upstash/ratelimit": "2.0.5","@upstash/redis": "1.34.6",@@ -52,6 +53,7 @@"dayjs": "1.11.13","eslint-plugin-react-hooks": "5.2.0","file-saver": "2.0.5",+ "googleapis": "148.0.0","jiti": "2.4.2","jszip": "3.10.1","lucide-react": "0.477.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8572fb1..8abca64 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -55,6 +55,9 @@ importers:"@sentry/nextjs":specifier: 9.3.0version: 9.3.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])+ "@t3-oss/env-nextjs":+ specifier: 0.13.4"@types/ua-parser-js":specifier: 0.7.39version: 0.7.39@@ -85,6 +88,9 @@ importers:file-saver:specifier: 2.0.5version: 2.0.5+ googleapis:+ specifier: 148.0.0+ version: 148.0.0jiti:specifier: 2.4.2version: 2.4.2@@ -231,6 +237,18 @@ packages:}engines: { node: ">=6.0.0" }+ "@ark/[email protected]":+ resolution:+ {+ integrity: sha512-c2UQdKgP2eqqDArfBqQIJppxJHvNNXuQPeuSPlDML4rjw+f1cu0qAlzOG4b8ujgm9ctIDWwhpyw6gjG5ledIVQ==,+ }++ "@ark/[email protected]":+ resolution:+ {+ integrity: sha512-JPy/NGWn/lvf1WmGCPw2VGpBg5utZraE84I7wli18EDF3p3zc/e9WolT35tINeZO3l7C77SjqRJeAUoT0CvMRg==,+ }+"@babel/[email protected]":resolution:{@@ -3741,6 +3759,41 @@ packages:integrity: sha512-KGYxvIOXcceOAbEk4bi/dVLEK9z8sZ0uBB3Il5b1rhfClSpcX0yfRO0KmTkqR2cnQDymwLB+25ZyMzICg/cm/A==,}+ "@t3-oss/[email protected]":+ resolution:+ {+ integrity: sha512-zVOiYO0+CF7EnBScz8s0O5JnJLPTU0lrUi8qhKXfIxIJXvI/jcppSiXXsEJwfB4A6XZawY/Wg/EQGKANi/aPmQ==,+ }+ peerDependencies:+ arktype: ^2.1.0+ typescript: ">=5.0.0"+ valibot: ^1.0.0-beta.7 || ^1.0.0+ zod: ^3.24.0 || ^4.0.0-beta.0+ peerDependenciesMeta:+ typescript:+ optional: true+ valibot:+ optional: true+ zod:+ optional: true++ "@t3-oss/[email protected]":+ resolution:+ {+ integrity: sha512-6ecXR7SH7zJKVcBODIkB7wV9QLMU23uV8D9ec6P+ULHJ5Ea/YXEHo+Z/2hSYip5i9ptD/qZh8VuOXyldspvTTg==,+ }+ peerDependencies:+ typescript: ">=5.0.0"+ valibot: ^1.0.0-beta.7 || ^1.0.0+ zod: ^3.24.0 || ^4.0.0-beta.0+ peerDependenciesMeta:+ typescript:+ optional: true+ valibot:+ optional: true+ zod:+ optional: true+"@tybys/[email protected]":resolution:{@@ -4303,6 +4356,13 @@ packages:}engines: { node: ">= 6.0.0" }+ resolution:+ {+ integrity: sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==,+ }+ engines: { node: ">= 14" }+resolution:{@@ -4408,6 +4468,12 @@ packages:}engines: { node: ">= 0.4" }+ resolution:+ {+ integrity: sha512-IZCEEXaJ8g+Ijd59WtSYwtjnqXiwM8sWQ5EjGamcto7+HVN9eK0C4p0zDlCuAwWhpqr6fIBkxPuYDl4/Mcj/+Q==,+ }+resolution:{@@ -4546,6 +4612,12 @@ packages:integrity: sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==,}+ resolution:+ {+ integrity: sha512-EM7aMFTXbptt/wZdMlBv2t8IViwQL+h6SLHosp8Yf0dqJMTnY6iL32opnAB6kAdL0SZPuvcAzFr31o0c/R3/RA==,+ }+resolution:{@@ -4605,6 +4677,12 @@ packages:engines: { node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7 }hasBin: true+ resolution:+ {+ integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==,+ }+resolution:{@@ -5165,6 +5243,12 @@ packages:integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==,}+ resolution:+ {+ integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==,+ }+resolution:{@@ -5580,6 +5664,12 @@ packages:}engines: { node: ">= 18" }+ resolution:+ {+ integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==,+ }+resolution:{@@ -5803,6 +5893,20 @@ packages:integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==,}+ resolution:+ {+ integrity: sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==,+ }+ engines: { node: ">=14" }++ resolution:+ {+ integrity: sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==,+ }+ engines: { node: ">=14" }+resolution:{@@ -5928,6 +6032,34 @@ packages:}engines: { node: ">= 0.4" }+ resolution:+ {+ integrity: sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==,+ }+ engines: { node: ">=14" }++ resolution:+ {+ integrity: sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==,+ }+ engines: { node: ">=14" }++ resolution:+ {+ integrity: sha512-/fhDZEJZvOV3X5jmD+fKxMqma5q2Q9nZNSF3kn1F18tpxmA86BcTxAGBQdM0N89Z3bEaIs+HVznSmFJEAmMTjA==,+ }+ engines: { node: ">=14.0.0" }++ resolution:+ {+ integrity: sha512-8PDG5VItm6E1TdZWDqtRrUJSlBcNwz0/MwCa6AL81y/RxPGXJRUwKqGZfCoVX1ZBbfr3I4NkDxBmeTyOAZSWqw==,+ }+ engines: { node: ">=14.0.0" }+resolution:{@@ -5947,6 +6079,13 @@ packages:integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==,}+ resolution:+ {+ integrity: sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==,+ }+ engines: { node: ">=14.0.0" }+resolution:{@@ -6047,6 +6186,13 @@ packages:}engines: { node: ">= 6" }+ resolution:+ {+ integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==,+ }+ engines: { node: ">= 14" }+resolution:{@@ -6338,6 +6484,13 @@ packages:integrity: sha512-9Cbovsa52vNQCjdXOzeQq5CnCbAcRk05aU62K20WO372NrTv0NxibLFCK6lQ4/iZEFdEA3p3t2VNOn8AJ53F5g==,}+ resolution:+ {+ integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==,+ }+ engines: { node: ">=8" }+resolution:{@@ -6486,6 +6639,12 @@ packages:engines: { node: ">=6" }hasBin: true+ resolution:+ {+ integrity: sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==,+ }+resolution:{@@ -6544,6 +6703,18 @@ packages:integrity: sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==,}+ resolution:+ {+ integrity: sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==,+ }++ resolution:+ {+ integrity: sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==,+ }+resolution:{@@ -8706,6 +8877,12 @@ packages:integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==,}+ resolution:+ {+ integrity: sha512-XdVKMF4SJ0nP/O7XIPB0JwAEuT9lDIYnNsK8yGVe43y0AWoKeJNdv3ZNWh7ksJ6KqQFjOO6ox/VEitLnaVNufw==,+ }+resolution:{@@ -8999,6 +9176,12 @@ snapshots:"@jridgewell/gen-mapping": 0.3.8"@jridgewell/trace-mapping": 0.3.25+ "@ark/[email protected]":+ dependencies:+ "@ark/util": 0.46.0++ "@ark/[email protected]": {}+"@babel/[email protected]":dependencies:"@babel/helper-validator-identifier": 7.25.9@@ -11864,6 +12047,22 @@ snapshots:"@swc/counter": 0.1.3tslib: 2.8.1+ dependencies:+ arktype: 2.1.20+ optionalDependencies:+ typescript: 5.8.3+ zod: 3.24.4++ dependencies:+ optionalDependencies:+ typescript: 5.8.3+ zod: 3.24.4+ transitivePeerDependencies:+ - arktype+"@tybys/[email protected]":dependencies:tslib: 2.8.1@@ -12258,6 +12457,8 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]: {}+optionalDependencies:ajv: 8.17.1@@ -12312,6 +12513,11 @@ snapshots:+ dependencies:+ "@ark/schema": 0.46.0+ "@ark/util": 0.46.0+dependencies:call-bound: 1.0.4@@ -12413,6 +12619,8 @@ snapshots:dependencies:require-from-string: 2.0.2+ [email protected]: {}+@@ -12463,6 +12671,8 @@ snapshots:node-releases: 2.0.19update-browserslist-db: 1.1.3([email protected])+ [email protected]: {}+@@ -12743,6 +12953,10 @@ snapshots:+ dependencies:+ safe-buffer: 5.2.1+@@ -12925,7 +13139,7 @@ snapshots:eslint: 9.26.0([email protected])eslint-import-resolver-node: 0.3.9- eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))+ eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))eslint-plugin-react: 7.37.4([email protected]([email protected]))eslint-plugin-react-hooks: 5.2.0([email protected]([email protected]))@@ -12955,22 +13169,21 @@ snapshots:stable-hash: 0.0.5tinyglobby: 0.2.12optionalDependencies:- eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))+ eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:eslint: 9.26.0([email protected])eslint-import-resolver-node: 0.3.9transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])):dependencies:"@rtsao/scc": 1.1.0array-includes: 3.1.8@@ -12981,7 +13194,7 @@ snapshots:doctrine: 2.1.0eslint: 9.26.0([email protected])eslint-import-resolver-node: 0.3.9- eslint-module-utils: 2.12.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected]))+ eslint-module-utils: 2.12.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))hasown: 2.0.2is-core-module: 2.16.1is-glob: 4.0.3@@ -12993,7 +13206,7 @@ snapshots:string.prototype.trimend: 1.0.9tsconfig-paths: 3.15.0optionalDependencies:transitivePeerDependencies:- eslint-import-resolver-typescript- eslint-import-resolver-webpack@@ -13189,6 +13402,8 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]: {}+@@ -13329,6 +13544,26 @@ snapshots:+ dependencies:+ extend: 3.0.2+ https-proxy-agent: 7.0.6+ is-stream: 2.0.1+ node-fetch: 2.7.0+ uuid: 9.0.1+ transitivePeerDependencies:+ - encoding+ - supports-color++ dependencies:+ gaxios: 6.7.1+ google-logging-utils: 0.0.2+ json-bigint: 1.0.0+ transitivePeerDependencies:+ - encoding+ - supports-color+@@ -13412,12 +13647,54 @@ snapshots:define-properties: 1.2.1gopd: 1.2.0+ dependencies:+ base64-js: 1.5.1+ ecdsa-sig-formatter: 1.0.11+ gaxios: 6.7.1+ gcp-metadata: 6.1.1+ gtoken: 7.1.0+ jws: 4.0.0+ transitivePeerDependencies:+ - encoding+ - supports-color++ [email protected]: {}++ dependencies:+ extend: 3.0.2+ gaxios: 6.7.1+ google-auth-library: 9.15.1+ qs: 6.14.0+ url-template: 2.0.8+ uuid: 9.0.1+ transitivePeerDependencies:+ - encoding+ - supports-color++ dependencies:+ google-auth-library: 9.15.1+ googleapis-common: 7.2.0+ transitivePeerDependencies:+ - encoding+ - supports-color++ dependencies:+ gaxios: 6.7.1+ jws: 4.0.0+ transitivePeerDependencies:+ - encoding+ - supports-color+@@ -13482,6 +13759,13 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ agent-base: 7.1.3+ debug: 4.4.0+ transitivePeerDependencies:+ - supports-color+@@ -13640,6 +13924,8 @@ snapshots:+ [email protected]: {}+@@ -13721,6 +14007,10 @@ snapshots:+ dependencies:+ bignumber.js: 9.3.0+@@ -13751,6 +14041,17 @@ snapshots:readable-stream: 2.3.8setimmediate: 1.0.5+ dependencies:+ buffer-equal-constant-time: 1.0.1+ ecdsa-sig-formatter: 1.0.11+ safe-buffer: 5.2.1++ dependencies:+ jwa: 2.0.1+ safe-buffer: 5.2.1+dependencies:json-buffer: 3.0.1@@ -15231,6 +15532,8 @@ snapshots:dependencies:punycode: 2.3.1+ [email protected]: {}+dependencies:react: 18.3.1diff --git a/src/actions/subscribe-action.ts b/src/actions/subscribe-action.tsindex a34b49a..1e5d049 100644--- a/src/actions/subscribe-action.ts+++ b/src/actions/subscribe-action.ts@@ -6,6 +6,7 @@ import { generateSubscriptionToken } from "@/utils/subscription-token";import { checkRateLimit, ipLimiter, emailLimiter } from "@/lib/rate-limit";import { headers } from "next/headers";import ConfirmSubscriptionEmail from "@/emails/confirm-subscription";+import { env } from "@/env";const subscribeSchema = z.object({@@ -13,10 +14,6 @@ const subscribeSchema = z}).strict();-if (!process.env.RESEND_AUDIENCE_ID) {- throw new Error("RESEND_AUDIENCE_ID is not set");-}-const CONFIRMATION_URL =process.env.VERCEL_ENV === "production"? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`@@ -50,7 +47,7 @@ export async function subscribeAction(formData: FormData) {// Check if email already existsconst { data: existingContacts } = await resend.contacts.list({- audienceId: process.env.RESEND_AUDIENCE_ID as string,+ audienceId: env.RESEND_AUDIENCE_ID,});if (diff --git a/src/app/api/generate-invoice/constants.tsx b/src/app/api/generate-invoice/render-pdf-on-server.tsxsimilarity index 95%rename from src/app/api/generate-invoice/constants.tsxrename to src/app/api/generate-invoice/render-pdf-on-server.tsxindex 22b3b2c..ab0a299 100644--- a/src/app/api/generate-invoice/constants.tsx+++ b/src/app/api/generate-invoice/render-pdf-on-server.tsx@@ -13,6 +13,7 @@ import {import type { InvoiceData, SupportedLanguages } from "@/app/schema";import { TRANSLATIONS } from "@/app/schema/translations";import { STATIC_ASSETS_URL } from "@/config";+import { env } from "@/env";// eslint-disable-next-line no-restricted-importsimport {Document,@@ -319,7 +320,7 @@ const translateInvoiceNumberLabel = ({return invoiceNumberLabel;};-const INVOICE_NET_PRICE = Number(process.env.INVOICE_NET_PRICE) || 0;+const INVOICE_NET_PRICE = Number(env.INVOICE_NET_PRICE) || 0;export const ENGLISH_INVOICE_REAL_DATA = {language: "en",@@ -338,29 +339,29 @@ export const ENGLISH_INVOICE_REAL_DATA = {invoiceType: "Reverse Charge",invoiceTypeFieldIsVisible: true,seller: {- name: process.env.SELLER_NAME!,- address: process.env.SELLER_ADDRESS!,+ name: env.SELLER_NAME,+ address: env.SELLER_ADDRESS,- vatNo: process.env.SELLER_VAT_NO!,+ vatNo: env.SELLER_VAT_NO,vatNoFieldIsVisible: true,- email: process.env.SELLER_EMAIL!,- accountNumber: process.env.SELLER_ACCOUNT_NUMBER!,+ email: env.SELLER_EMAIL,+ accountNumber: env.SELLER_ACCOUNT_NUMBER,accountNumberFieldIsVisible: true,- swiftBic: process.env.SELLER_SWIFT_BIC!,+ swiftBic: env.SELLER_SWIFT_BIC,swiftBicFieldIsVisible: true,notesFieldIsVisible: true,},buyer: {- name: process.env.BUYER_NAME!,- address: process.env.BUYER_ADDRESS!,+ name: env.BUYER_NAME,+ address: env.BUYER_ADDRESS,- vatNo: process.env.BUYER_VAT_NO!,+ vatNo: env.BUYER_VAT_NO,vatNoFieldIsVisible: true,- email: process.env.BUYER_EMAIL!,+ email: env.BUYER_EMAIL,notesFieldIsVisible: true,},items: [diff --git a/src/app/api/generate-invoice/route.tsx b/src/app/api/generate-invoice/route.tsxindex 2359c39..63f1414 100644--- a/src/app/api/generate-invoice/route.tsx+++ b/src/app/api/generate-invoice/route.tsx@@ -1,26 +1,33 @@+import { INVOICE_DEFAULT_NUMBER_VALUE } from "@/app/constants";+import { invoiceSchema } from "@/app/schema";+import {+ createOrFindInvoiceFolder,+ initializeGoogleDrive,+ uploadFile,+} from "@/lib/google-drive";import { resend } from "@/lib/resend";+import { sendTelegramMessage } from "@/lib/telegram";+// eslint-disable-next-line no-restricted-importsimport { renderToBuffer } from "@react-pdf/renderer";import dayjs from "dayjs";-import { type NextRequest, NextResponse } from "next/server";+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 "./constants";-import { INVOICE_DEFAULT_NUMBER_VALUE } from "@/app/constants";+} from "./render-pdf-on-server";-if (!process.env.AUTH_TOKEN) {- throw new Error("AUTH_TOKEN is not set");-}+import { env } from "@/env";++export const dynamic = "force-dynamic";export async function GET(req: NextRequest) {try {- // Check if the request is authorized- const AUTH_TOKEN = process.env.AUTH_TOKEN;-- if (req.headers.get("Authorization") !== `Bearer ${AUTH_TOKEN}`) {+ if (req.headers.get("Authorization") !== `Bearer ${env.AUTH_TOKEN}`) {return new NextResponse("Unauthorized", { status: 401 });}@@ -105,12 +112,93 @@ export async function GET(req: NextRequest) {);}+ const newInvoiceDataValidated = invoiceSchema.parse(+ ENGLISH_INVOICE_REAL_DATA+ );+ const stringified = JSON.stringify(newInvoiceDataValidated);+ const compressedData = compressToEncodedURIComponent(stringified);++ const invoiceUrl = `https://easyinvoicepdf.com/?data=${compressedData}`;++ const monthAndYear = dayjs().format("MMMM, YYYY");++ // *___________UPLOAD INVOICES TO GOOGLE DRIVE___________*++ // 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,+ });++ const { folderToUploadInvoices, googleDriveFolderPath } = result;++ // 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(+ "Some files failed to upload to Google Drive:",+ failedUploads+ );++ return NextResponse.json(+ { error: "Failed to upload invoices to Google Drive" },+ { status: 500 }+ );+ }++ // 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 email with PDF attachmentconst emailResponse = await resend.emails.send({from: "Vlad from EasyInvoicePDF.com <[email protected]>",- to: "[email protected]",- subject: `📝 Invoice for ${dayjs().format("MMMM, YYYY")}`,- text: `Hello,\n\nPlease find your invoices in the attachments. Please check them carefully and let me know if any adjustments are needed.\n\nDate: ${dayjs().format("MMMM D, YYYY")}\n\nBest regards,\nEasyInvoicePDF.com`,+ 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><br/>+ <a href="${folderToUploadInvoices.webViewLink}">View in Google Drive</a>+ <br/>+ <br/>++ Google Drive folder path: <b>${googleDriveFolderPath}</b>+ <br/>+ <br/>++ Have a nice day!<br/><br/>+ Best regards,<br/>EasyInvoicePDF.com</span>`,attachments: ATTACHMENTS,});@@ -118,8 +206,32 @@ export async function GET(req: NextRequest) {throw new Error(`Failed to send email: ${emailResponse.error.message}`);}+ // Send Telegram notification with PDFs+ await sendTelegramMessage({+ message: `📝 *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})+[View in Google Drive](${folderToUploadInvoices.webViewLink})++Google Drive folder path: *${googleDriveFolderPath}*++Have a nice day!++Best regards,+EasyInvoicePDF.com`,+ files: ATTACHMENTS.map((attachment) => ({+ filename: attachment.filename,+ buffer: Buffer.from(attachment.content),+ })),+ });+return NextResponse.json(- { message: "Email sent successfully", id: emailResponse.data?.id },+ { message: "Invoice sent successfully" },{ status: 200 });} catch (error) {diff --git a/src/app/components/invoice-form/sections/general-information.tsx b/src/app/components/invoice-form/sections/general-information.tsxindex 79ebd1c..4ba8529 100644--- a/src/app/components/invoice-form/sections/general-information.tsx+++ b/src/app/components/invoice-form/sections/general-information.tsx@@ -7,6 +7,7 @@ import {} from "react-hook-form";import {CURRENCY_SYMBOLS,+ CURRENCY_TO_LABEL,LANGUAGE_TO_LABEL,type InvoiceData,} from "@/app/schema";@@ -156,13 +157,15 @@ export const GeneralInformation = memo(function GeneralInformation({{SUPPORTED_CURRENCIES.map((currency) => {const currencySymbol = CURRENCY_SYMBOLS[currency] || null;+ const currencyFullName = CURRENCY_TO_LABEL[currency] || null;+return (<optionkey={currency}value={currency}defaultValue={SUPPORTED_CURRENCIES[0]}>- {currency} {currencySymbol}+ {currency} {currencySymbol} {currencyFullName}</option>);})}diff --git a/src/app/confirm-subscription/page.tsx b/src/app/confirm-subscription/page.tsxindex 4c3f059..b013dcb 100644--- a/src/app/confirm-subscription/page.tsx+++ b/src/app/confirm-subscription/page.tsx@@ -3,6 +3,7 @@ import { resend } from "@/lib/resend";import { redirect } from "next/navigation";import Link from "next/link";import { headers } from "next/headers";+import { env } from "@/env";export const metadata = {robots: {@@ -53,7 +54,7 @@ export default async function ConfirmSubscriptionPage({// Add contact to Resend audienceconst { error } = await resend.contacts.create({email,- audienceId: process.env.RESEND_AUDIENCE_ID as string,+ audienceId: env.RESEND_AUDIENCE_ID,});if (error) {diff --git a/src/app/schema/index.ts b/src/app/schema/index.tsindex 5a0e955..562b14d 100644--- a/src/app/schema/index.ts+++ b/src/app/schema/index.ts@@ -20,6 +20,7 @@ export const SUPPORTED_CURRENCIES = ["CNY", // Chinese Yuan (RMB)"SGD", // Singapore Dollar] as const;+export type SupportedCurrencies = (typeof SUPPORTED_CURRENCIES)[number];export const CURRENCY_SYMBOLS = {@@ -42,9 +43,34 @@ export const CURRENCY_SYMBOLS = {CNY: "¥", // Chinese Yuan (RMB)SGD: "S$", // Singapore Dollar} as const satisfies Record<SupportedCurrencies, string>;+export type CurrencySymbols =(typeof CURRENCY_SYMBOLS)[keyof typeof CURRENCY_SYMBOLS];+export const CURRENCY_TO_LABEL = {+ EUR: "Euro",+ USD: "United States Dollar",+ CAD: "Canadian Dollar",+ AUD: "Australian Dollar",+ GBP: "British Pound Sterling",+ PLN: "Polish Złoty",+ RUB: "Russian Ruble",+ UAH: "Ukrainian Hryvnia",+ BYN: "Belarusian Ruble",+ BRL: "Brazilian Real",+ MXN: "Mexican Peso",+ ARS: "Argentine Peso",+ INR: "Indian Rupee",+ CHF: "Swiss Franc",+ HKD: "Hong Kong Dollar",+ TWD: "New Taiwan Dollar",+ CNY: "Chinese Yuan Renminbi",+ SGD: "Singapore Dollar",+} as const satisfies Record<SupportedCurrencies, string>;++export type CurrencyLabels =+ (typeof CURRENCY_TO_LABEL)[keyof typeof CURRENCY_TO_LABEL];+export const SUPPORTED_LANGUAGES = ["en","pl",diff --git a/src/app/schema/translations.ts b/src/app/schema/translations.tsindex d72c5db..d15c0f8 100644--- a/src/app/schema/translations.ts+++ b/src/app/schema/translations.ts@@ -86,11 +86,18 @@ export const translationSchema = z}).strict();-// Schema for all translations-export const translationsSchema = z.record(- z.enum(SUPPORTED_LANGUAGES),- translationSchema+// Create a map of language to schema+// {+// en: translationSchema,+// pl: translationSchema,+// de: translationSchema,+// ...etc+// }+const languageToSchemaMap = Object.fromEntries(+ SUPPORTED_LANGUAGES.map((lang) => [lang, translationSchema]));+// Schema for all translations+export const translationsSchema = z.object(languageToSchemaMap);// Type for a single language translationexport type TranslationSchema = z.infer<typeof translationSchema>;diff --git a/src/env.ts b/src/env.tsnew file mode 100644index 0000000..f2257e9--- /dev/null+++ b/src/env.ts@@ -0,0 +1,73 @@+import { createEnv } from "@t3-oss/env-nextjs";+import { z } from "zod";++export const env = createEnv({+ server: {+ AUTH_TOKEN: z.string().min(1),++ RESEND_API_KEY: z.string().min(1),+ RESEND_AUDIENCE_ID: z.string().min(1),++ UPSTASH_REDIS_REST_URL: z.string().min(1),+ UPSTASH_REDIS_REST_TOKEN: z.string().min(1),++ TELEGRAM_BOT_TOKEN: z.string().min(1),+ TELEGRAM_CHAT_ID: z.string().min(1),++ SELLER_NAME: z.string().min(1),+ SELLER_ADDRESS: z.string().min(1),+ SELLER_VAT_NO: z.string().min(1),+ SELLER_EMAIL: z.string().email(),+ SELLER_ACCOUNT_NUMBER: z.string().min(1),+ SELLER_SWIFT_BIC: z.string().min(1),++ BUYER_NAME: z.string().min(1),+ BUYER_ADDRESS: z.string().min(1),+ BUYER_VAT_NO: z.string().min(1),+ BUYER_EMAIL: z.string().email(),++ INVOICE_NET_PRICE: z.string().min(1),+ INVOICE_EMAIL_RECIPIENT: z.string().email(),++ GOOGLE_DRIVE_PARENT_FOLDER_ID: z.string().min(1),+ GOOGLE_DRIVE_CLIENT_EMAIL: z.string().email(),+ GOOGLE_DRIVE_PRIVATE_KEY: z.string().min(1),+ },+ client: {+ NEXT_PUBLIC_SENTRY_DSN: z.string().min(1),+ },+ // If you're using Next.js < 13.4.4, you'll need to specify the runtimeEnv manually+ runtimeEnv: {+ NEXT_PUBLIC_SENTRY_DSN: process.env.NEXT_PUBLIC_SENTRY_DSN,++ AUTH_TOKEN: process.env.AUTH_TOKEN,++ RESEND_API_KEY: process.env.RESEND_API_KEY,+ RESEND_AUDIENCE_ID: process.env.RESEND_AUDIENCE_ID,++ UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL,+ UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN,++ TELEGRAM_BOT_TOKEN: process.env.TELEGRAM_BOT_TOKEN,+ TELEGRAM_CHAT_ID: process.env.TELEGRAM_CHAT_ID,++ SELLER_NAME: process.env.SELLER_NAME,+ SELLER_ADDRESS: process.env.SELLER_ADDRESS,+ SELLER_VAT_NO: process.env.SELLER_VAT_NO,+ SELLER_EMAIL: process.env.SELLER_EMAIL,+ SELLER_ACCOUNT_NUMBER: process.env.SELLER_ACCOUNT_NUMBER,+ SELLER_SWIFT_BIC: process.env.SELLER_SWIFT_BIC,++ BUYER_NAME: process.env.BUYER_NAME,+ BUYER_ADDRESS: process.env.BUYER_ADDRESS,+ BUYER_VAT_NO: process.env.BUYER_VAT_NO,+ BUYER_EMAIL: process.env.BUYER_EMAIL,++ INVOICE_NET_PRICE: process.env.INVOICE_NET_PRICE,+ INVOICE_EMAIL_RECIPIENT: process.env.INVOICE_EMAIL_RECIPIENT,++ GOOGLE_DRIVE_PARENT_FOLDER_ID: process.env.GOOGLE_DRIVE_PARENT_FOLDER_ID,+ GOOGLE_DRIVE_CLIENT_EMAIL: process.env.GOOGLE_DRIVE_CLIENT_EMAIL,+ GOOGLE_DRIVE_PRIVATE_KEY: process.env.GOOGLE_DRIVE_PRIVATE_KEY,+ },+});diff --git a/src/lib/google-drive.ts b/src/lib/google-drive.tsnew file mode 100644index 0000000..785d5dd--- /dev/null+++ b/src/lib/google-drive.ts@@ -0,0 +1,223 @@+import { google } from "googleapis";+import { z } from "zod";+import { Readable } from "node:stream";+import { env } from "@/env";++interface GoogleDriveFile {+ id: string;+ name: string;+ mimeType: string;+ webViewLink?: string;+}++interface Success {+ status: "success";+ folderToUploadInvoices: GoogleDriveFile;+ googleDriveFolderPath: string;+}++type CreateOrFindInvoiceFolderResult = Success;++const FolderInputSchema = z.object({+ parentFolderId: z.string().min(1),+ month: z+ .string()+ .regex(/^(0[1-9]|1[0-2])$/, "Month must be between 01 and 12 (MM format)"),+ year: z.string().regex(/^\d{4}$/, "Year must be in YYYY format"),+});++type FolderInput = z.infer<typeof FolderInputSchema>;++let cachedDrive: ReturnType<typeof google.drive> | undefined;++export async function initializeGoogleDrive() {+ if (cachedDrive) {+ return cachedDrive;+ }++ const googlePrivateKey = env.GOOGLE_DRIVE_PRIVATE_KEY.replace(/\\n/g, "\n");++ const auth = new google.auth.GoogleAuth({+ credentials: {+ client_email: env.GOOGLE_DRIVE_CLIENT_EMAIL,+ private_key: googlePrivateKey,+ },+ scopes: ["https://www.googleapis.com/auth/drive"],+ });++ cachedDrive = google.drive({ version: "v3", auth });++ return cachedDrive;+}++async function createFolder(+ drive: ReturnType<typeof google.drive>,+ folderName: string,+ parentFolderId?: string+): Promise<GoogleDriveFile> {+ const fileMetadata = {+ name: folderName,+ mimeType: "application/vnd.google-apps.folder",+ ...(parentFolderId && { parents: [parentFolderId] }),+ };++ const response = await drive.files.create({+ requestBody: fileMetadata,+ fields: "id, name, mimeType, webViewLink",+ });++ if (!response.data.id) {+ throw new Error("Failed to create folder");+ }++ return response.data as GoogleDriveFile;+}++/**+ * Converts a Buffer to a Readable stream for efficient streaming to Google Drive API+ * @param {Buffer} buffer - The input buffer containing file data+ * @returns {Readable} A readable stream created from the buffer using Node's Readable.from()+ */+const bufferToStream = (buffer: Buffer): Readable => Readable.from(buffer);++export async function uploadFile({+ googleDrive,+ fileName,+ fileContent,+ folderId,+}: {+ googleDrive: ReturnType<typeof google.drive>;+ fileName: string;+ fileContent: Buffer;+ folderId: string;+}) {+ const fileMetadata = {+ name: fileName,+ parents: [folderId],+ };++ const media = {+ mimeType: "application/pdf",+ body: bufferToStream(fileContent),+ };++ const response = await googleDrive.files.create({+ requestBody: fileMetadata,+ media,+ fields: "id, name, mimeType, webViewLink",+ });++ if (!response.data.id) {+ throw new Error("Failed to upload file");+ }++ return response.data as GoogleDriveFile;+}++export async function createOrFindInvoiceFolder({+ googleDrive,+ ...input+}: {+ googleDrive: ReturnType<typeof google.drive>;+} & FolderInput): Promise<CreateOrFindInvoiceFolderResult> {+ // Validate input+ const validatedInput = FolderInputSchema.parse(input);++ // First, try to find or create the year folder+ const yearFolderName = validatedInput.year;++ const yearFolderQuery =+ `name = '${yearFolderName}' and mimeType = 'application/vnd.google-apps.folder' and '${validatedInput.parentFolderId}' in parents and trashed = false` as const;++ const yearFolderResponse = await googleDrive.files.list({+ q: yearFolderQuery,+ fields: "files(id, name, mimeType, webViewLink)",+ spaces: "drive",+ });++ let yearFolder: GoogleDriveFile;++ if (yearFolderResponse.data.files?.length) {+ // if the year folder already exists, use it+ yearFolder = yearFolderResponse.data.files[0] as GoogleDriveFile;+ } else {+ // if the year folder does not exist, create it+ yearFolder = await createFolder(+ googleDrive,+ yearFolderName,+ validatedInput.parentFolderId+ );+ }++ // Then try to find or create the month folder inside the year folder+ const monthFolderName = `${validatedInput.month}.${validatedInput.year}`;++ const monthFolderQuery =+ `name = '${monthFolderName}' and mimeType = 'application/vnd.google-apps.folder' and '${yearFolder.id}' in parents and trashed = false` as const;++ const monthFolderResponse = await googleDrive.files.list({+ q: monthFolderQuery,+ fields: "files(id, name, mimeType, webViewLink)",+ spaces: "drive",+ });++ let monthFolder: GoogleDriveFile;++ if (monthFolderResponse.data.files?.length) {+ // if the month folder already exists, use it+ monthFolder = monthFolderResponse.data.files[0] as GoogleDriveFile;++ console.log(+ "\n\n________month folder already exists, using it: ",+ monthFolder,+ { monthFolderName, yearFolderName },+ "\n\n"+ );+ } else {+ // if the month folder does not exist (new month), create it+ monthFolder = await createFolder(+ googleDrive,+ monthFolderName,+ yearFolder.id+ );+ }++ // Finally, try to find or create the invoices folder+ const invoicesFolderQuery =+ `name = 'invoices' and mimeType = 'application/vnd.google-apps.folder' and '${monthFolder.id}' in parents and trashed = false` as const;++ const invoicesFolderResponse = await googleDrive.files.list({+ q: invoicesFolderQuery,+ fields: "files(id, name, mimeType, webViewLink)",+ spaces: "drive",+ });++ let folderToUploadInvoices: GoogleDriveFile;++ if (invoicesFolderResponse.data.files?.length) {+ // if the invoices folder already exists, use it+ folderToUploadInvoices = invoicesFolderResponse.data+ .files[0] as GoogleDriveFile;+ } else {+ // if the invoices folder does not exist, create it+ folderToUploadInvoices = await createFolder(+ googleDrive,+ "invoices",+ monthFolder.id+ );+ }++ const googleDriveFolderPath = `/${yearFolder.name}/${monthFolder.name}/${folderToUploadInvoices.name}`;++ console.log(+ "\n\n________invoice to upload Google Drive folder path: ",+ googleDriveFolderPath,+ "\n\n"+ );++ return {+ status: "success",+ folderToUploadInvoices,+ googleDriveFolderPath,+ };+}diff --git a/src/lib/redis.ts b/src/lib/redis.tsindex fbef6fb..f2df3ff 100644--- a/src/lib/redis.ts+++ b/src/lib/redis.ts@@ -1,14 +1,7 @@+import { env } from "@/env";import { Redis } from "@upstash/redis";-if (!process.env.UPSTASH_REDIS_REST_URL) {- throw new Error("UPSTASH_REDIS_REST_URL is not set");-}--if (!process.env.UPSTASH_REDIS_REST_TOKEN) {- throw new Error("UPSTASH_REDIS_REST_TOKEN is not set");-}-export const redis = new Redis({- url: process.env.UPSTASH_REDIS_REST_URL,- token: process.env.UPSTASH_REDIS_REST_TOKEN,+ url: env.UPSTASH_REDIS_REST_URL,+ token: env.UPSTASH_REDIS_REST_TOKEN,});diff --git a/src/lib/resend.ts b/src/lib/resend.tsindex 49f8b6f..10be544 100644--- a/src/lib/resend.ts+++ b/src/lib/resend.ts@@ -1,7 +1,4 @@+import { env } from "@/env";import { Resend } from "resend";-if (!process.env.RESEND_API_KEY) {- throw new Error("RESEND_API_KEY is not set");-}--export const resend = new Resend(process.env.RESEND_API_KEY);+export const resend = new Resend(env.RESEND_API_KEY);diff --git a/src/lib/telegram.ts b/src/lib/telegram.tsnew file mode 100644index 0000000..905b2b7--- /dev/null+++ b/src/lib/telegram.ts@@ -0,0 +1,66 @@+import { env } from "@/env";++interface SendMessageOptions {+ message: string;+ files?: Array<{+ filename: string;+ buffer: Buffer;+ }>;+}++export async function sendTelegramMessage({+ message,+ files,+}: SendMessageOptions) {+ try {+ // Send text message+ const textResponse = await fetch(+ `https://api.telegram.org/bot${env.TELEGRAM_BOT_TOKEN}/sendMessage`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ chat_id: env.TELEGRAM_CHAT_ID,+ text: message,+ parse_mode: "Markdown",+ }),+ }+ );++ if (!textResponse.ok) {+ throw new Error(+ `Failed to send Telegram message: ${textResponse.statusText}`+ );+ }++ // Send files if any+ if (files?.length) {+ for (const file of files) {+ const formData = new FormData();+ formData.append("chat_id", env.TELEGRAM_CHAT_ID);+ formData.append("document", new Blob([file.buffer]), file.filename);++ const fileResponse = await fetch(+ `https://api.telegram.org/bot${env.TELEGRAM_BOT_TOKEN}/sendDocument`,+ {+ method: "POST",+ body: formData,+ }+ );++ if (!fileResponse.ok) {+ throw new Error(+ `Failed to send file ${file.filename}: ${fileResponse.statusText}`+ );+ }+ }+ }++ return { success: true };+ } catch (error) {+ console.error("Error sending Telegram message:", error);+ throw error;+ }+}