Skip to content

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

feat: add monthly recurring invoice workflow and enhance SEO landing definitions (#226)

Vlad Sazonau0db6efadb70f
diff --git a/.github/workflows/monthly-recurring-invoice.yml b/.github/workflows/monthly-recurring-invoice.yml
new file mode 100644
index 0000000..3d237ea
--- /dev/null
+++ b/.github/workflows/monthly-recurring-invoice.yml
@@ -0,0 +1,182 @@
+name: πŸ“… Monthly Recurring Invoice
+
+concurrency:
+ group: recurring-invoice
+ cancel-in-progress: false
+
+on:
+ schedule:
+ # Run every day from the 10th to the 12th.
+ # We need this range because:
+ # - if the 10th is a weekday -> run on 10th
+ # - if the 10th is Saturday -> run on Monday 12th
+ # - if the 10th is Sunday -> run on Monday 11th
+ - cron: "0 15 10-12 * *"
+ timezone: Europe/Warsaw
+
+jobs:
+ recurring-invoice:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10 # we set a timeout to 5 minutes to avoid the workflow running indefinitely
+ env:
+ TZ: Europe/Warsaw # we use Europe/Warsaw timezone for consistent date handling across local machines and CI
+
+ steps:
+ - name: Determine whether workflow should run today
+ id: date-check
+ run: |
+ output=$(node <<'EOF'
+ // Use local time (Europe/Warsaw) for date calculations.
+ // This ensures consistency with the job's TZ env and Telegram timestamps.
+ const formatter = new Intl.DateTimeFormat('en-US', {
+ timeZone: 'Europe/Warsaw',
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ weekday: 'long'
+ })
+ // Get current date/time in Warsaw timezone
+ const now = new Date()
+ // Parse the formatted date into individual components
+ const parts = formatter.formatToParts(now)
+ // Helper to extract specific date component by type
+ const getPart = (type) => parts.find(p => p.type === type)?.value
+
+ // Extract year, month (convert to 0-based), day, and weekday index
+ const year = parseInt(getPart('year'))
+ const month = parseInt(getPart('month')) - 1 // zero-based for Date constructor
+
+ const today = parseInt(getPart('day'))
+
+ // Map weekday name to numeric index (0 = Sunday, 6 = Saturday)
+ const todayWeekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'].indexOf(getPart('weekday'))
+
+ // Create a Date object for the 10th day of the current month.
+ // Using Intl to get the 10th in Warsaw timezone.
+ const tenthFormatter = new Intl.DateTimeFormat('en-US', {
+ timeZone: 'Europe/Warsaw',
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ weekday: 'long'
+ })
+ const tenthDate = new Date(year, month, 10)
+
+ // Format the 10th day in Warsaw timezone to extract its weekday
+ const tenthParts = tenthFormatter.formatToParts(tenthDate)
+
+ // Helper function to get specific part from formatted date (e.g., 'weekday', 'day')
+ const tenthGetPart = (type) => tenthParts.find(p => p.type === type)?.value
+
+ // Convert weekday name (e.g., 'Saturday') to numeric index (0-6, where 0=Sunday, 6=Saturday)
+ const weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'].indexOf(tenthGetPart('weekday'))
+
+ // Default execution date is the 10th.
+ let targetDay = 10
+
+ // If the 10th falls on Saturday, move execution to Monday the 12th.
+ if (weekday === 6) {
+ targetDay = 12
+ }
+
+ // If the 10th falls on Sunday, move execution to Monday the 11th.
+ if (weekday === 0) {
+ targetDay = 11
+ }
+
+ // Final decision: run only if today matches computed target day.
+ const shouldRun = today === targetDay
+
+ // Expose values to later GitHub Action steps.
+ process.stdout.write(
+ `should_run=${shouldRun}\n` +
+ `weekday=${weekday}\n` +
+ `target_day=${targetDay}\n` +
+ `today=${today}\n` +
+ `today_weekday=${todayWeekday}\n`
+ )
+ EOF
+ )
+ echo "$output" >> $GITHUB_OUTPUT
+
+ - name: Send date-check notification to Telegram
+ run: |
+ WEEKDAY=${{ steps.date-check.outputs.weekday }}
+ TARGET_DAY=${{ steps.date-check.outputs.target_day }}
+ SHOULD_RUN=${{ steps.date-check.outputs.should_run }}
+ WORKFLOW_URL="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
+ NOW="$(date '+%d.%m.%Y %H:%M:%S %Z')"
+ BILLING_PERIOD="$(date '+%B %Y')"
+
+ WEEKDAY_NAMES=("Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday")
+ WEEKDAY_NAME="${WEEKDAY_NAMES[$WEEKDAY]}"
+
+ # Build weekend explanation if 10th fell on Saturday or Sunday
+ WEEKEND_LINE=""
+ if [ "$WEEKDAY" == "0" ] || [ "$WEEKDAY" == "6" ]; then
+ WEEKEND_LINE="10th was a weekend ($WEEKDAY_NAME), so execution moved to Monday ($TARGET_DAY).%0A%0A"
+ fi
+
+ if [ "$SHOULD_RUN" == "true" ]; then
+ STATUS="βœ… Status: Proceeding with invoice generation"
+ else
+ STATUS="⏭️ Status: Skipped (awaiting correct date)"
+ fi
+
+ MESSAGE="πŸ“… Monthly Invoice Workflow%0A%0A"
+ MESSAGE+="πŸ•’ $NOW%0A%0A"
+ MESSAGE+="<b>Billing period:</b> $BILLING_PERIOD%0A%0A"
+ MESSAGE+="$WEEKEND_LINE"
+ MESSAGE+="$STATUS%0A%0A"
+ MESSAGE+="πŸ”— <a href=\"$WORKFLOW_URL\">View Workflow</a>"
+
+ curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_GITHUB_ACTIONS_BOT_TOKEN }}/sendMessage" \
+ -d chat_id="${{ secrets.TELEGRAM_GITHUB_ACTIONS_CHAT_ID }}" \
+ -d text="$MESSAGE" \
+ -d parse_mode="HTML" > /dev/null
+
+ - name: Generate monthly recurring invoice
+ # Execute only if date-check step decided
+ # that today is the correct execution day.
+ if: steps.date-check.outputs.should_run == 'true'
+ run: |
+ curl --fail-with-body \
+ --silent \
+ --show-error \
+ -X GET \
+ --max-time 60 \
+ -H "Authorization: Bearer ${{ secrets.INVOICE_AUTH_TOKEN }}" \
+ https://easyinvoicepdf.com/api/generate-invoice
+
+ - name: Send success notification to Telegram
+ if: steps.date-check.outputs.should_run == 'true' && success()
+ run: |
+ WORKFLOW_URL="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
+ NOW="$(date '+%d.%m.%Y %H:%M:%S %Z')"
+
+ MESSAGE="πŸ“… Monthly Invoice Workflow%0A%0A"
+ MESSAGE+="πŸ•’ $NOW%0A%0A"
+ MESSAGE+="βœ… Status: Invoice generated successfully%0A%0A"
+ MESSAGE+="πŸ”— <a href=\"$WORKFLOW_URL\">View Workflow</a>"
+
+ curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_GITHUB_ACTIONS_BOT_TOKEN }}/sendMessage" \
+ -d chat_id="${{ secrets.TELEGRAM_GITHUB_ACTIONS_CHAT_ID }}" \
+ -d text="$MESSAGE" \
+ -d parse_mode="HTML" > /dev/null
+
+ - name: Send failure notification to Telegram
+ if: failure()
+ run: |
+ WORKFLOW_URL="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
+ NOW="$(date '+%d.%m.%Y %H:%M:%S %Z')"
+
+ MESSAGE="πŸ“… Monthly Invoice Workflow%0A%0A"
+ MESSAGE+="πŸ•’ $NOW%0A%0A"
+ MESSAGE+="🚨 Status: Invoice generation failed%0A"
+ MESSAGE+="Please check the workflow for details%0A%0A"
+ MESSAGE+="πŸ”— <a href=\"$WORKFLOW_URL\">View Workflow</a>"
+
+ curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_GITHUB_ACTIONS_BOT_TOKEN }}/sendMessage" \
+ -d chat_id="${{ secrets.TELEGRAM_GITHUB_ACTIONS_CHAT_ID }}" \
+ -d text="$MESSAGE" \
+ -d parse_mode="HTML" > /dev/null
diff --git a/.gitignore b/.gitignore
index 8f0807f..f016b35 100644
--- a/.gitignore
+++ b/.gitignore
@@ -53,4 +53,6 @@ node_modules/
# i18n
messages/en.d.json.ts
-.pnpm-store/
\ No newline at end of file
+.pnpm-store/
+
+.github/workflows/.secrets
\ No newline at end of file
diff --git a/knip.ts b/knip.ts
index f026c7f..1b62e98 100644
--- a/knip.ts
+++ b/knip.ts
@@ -30,6 +30,7 @@ const config: KnipConfig = {
// ignore tags
// https://knip.dev/reference/configuration#tags
tags: ["-@lintignore"],
+ ignoreBinaries: ["act"],
};
export default config;
diff --git a/package.json b/package.json
index ae6f443..77eb565 100644
--- a/package.json
+++ b/package.json
@@ -33,7 +33,8 @@
"cloudflared:tunnel": "pnpm dlx cloudflared tunnel run easy-invoice-pdf-local-dev",
"corepack:enable": "corepack enable",
"corepack:prepare": "corepack prepare pnpm@latest",
- "update-github-actions": "pnpm dlx actions-up --min-age=7"
+ "update-github-actions": "pnpm dlx actions-up --min-age=7",
+ "test-gh-action-locally:monthly-recurring-invoice": "act schedule -j recurring-invoice --secret-file .github/workflows/.secrets"
},
"dependencies": {
"@hookform/resolvers": "3.9.0",
diff --git a/src/app/(seo-landings)/components/seo-landing-shell.tsx b/src/app/(seo-landings)/components/seo-landing-shell.tsx
index b408687..85572e3 100644
--- a/src/app/(seo-landings)/components/seo-landing-shell.tsx
+++ b/src/app/(seo-landings)/components/seo-landing-shell.tsx
@@ -90,7 +90,11 @@ export function SeoLandingShell({ definition }: SeoLandingShellProps) {
<img
src={definition.hero.heroImage}
alt={definition.hero.h1}
- className="h-auto w-full rounded-lg shadow-sm"
+ className="h-auto w-full rounded-lg bg-slate-100/80 shadow-sm"
+ loading="eager"
+ fetchPriority="high"
+ width={1920}
+ height={1536}
/>
</a>
</div>
@@ -106,29 +110,34 @@ export function SeoLandingShell({ definition }: SeoLandingShellProps) {
</div>
<div className="container mx-auto max-w-4xl flex-1 px-4 pt-6 md:px-6 md:pt-10">
- {definition.sections.map((section, id) => (
- <div key={section.title}>
- <div className="my-2">
- <SeoSectionBlock section={section} id={id} />
- </div>
- {definition.comparisonTable &&
- section.title === "When to use this instead" ? (
- <div className="py-6 md:py-8">
- <h2 className="w-fit bg-rose-500 text-2xl font-semibold tracking-tight text-white dark:bg-cyan-600 dark:text-white md:text-3xl">
- Feature comparison
- </h2>
- {definition.comparisonTable.intro ? (
- <p className="mt-4 max-w-3xl text-lg leading-relaxed text-slate-600">
- {definition.comparisonTable.intro}
- </p>
- ) : null}
- <div className="mt-6">
- <SeoComparisonTable table={definition.comparisonTable} />
- </div>
+ {definition.sections.map((section, id) => {
+ const canShowComparisonTable =
+ section?.showComparisonTable ?? false;
+ const comparisonTable = definition?.comparisonTable;
+
+ return (
+ <div key={section.title}>
+ <div className="my-2">
+ <SeoSectionBlock section={section} id={id} />
</div>
- ) : null}
- </div>
- ))}
+ {canShowComparisonTable && comparisonTable ? (
+ <div className="py-6 md:py-8">
+ <h2 className="w-fit bg-rose-500 text-2xl font-semibold tracking-tight text-white dark:bg-cyan-600 dark:text-white md:text-3xl">
+ πŸ‘‰ Feature comparison
+ </h2>
+ {comparisonTable?.intro ? (
+ <p className="mt-4 max-w-3xl text-lg leading-relaxed text-slate-600">
+ {comparisonTable.intro}
+ </p>
+ ) : null}
+ <div className="mt-6">
+ <SeoComparisonTable table={comparisonTable} />
+ </div>
+ </div>
+ ) : null}
+ </div>
+ );
+ })}
<section
id="faq"
@@ -288,6 +297,10 @@ function SeoSectionBlock({ section, id }: { section: SeoSection; id: number }) {
}
function SeoComparisonTable({ table }: { table: ComparisonTable }) {
+ if (!table) {
+ return null;
+ }
+
const [colA, colB, colC] = table.columnLabels;
return (
diff --git a/src/app/(seo-landings)/components/sticky-seo-cta.tsx b/src/app/(seo-landings)/components/sticky-seo-cta.tsx
index 1d6ecc1..bc7bd09 100644
--- a/src/app/(seo-landings)/components/sticky-seo-cta.tsx
+++ b/src/app/(seo-landings)/components/sticky-seo-cta.tsx
@@ -26,7 +26,7 @@ export function StickySeoCta({
className,
)}
>
- <div className="pointer-events-auto w-full max-w-lg rounded-xl border bg-slate-900 p-3 shadow-lg ring-2 ring-slate-700 sm:flex sm:items-center sm:justify-between sm:gap-3 sm:p-4">
+ <div className="pointer-events-auto w-full max-w-lg rounded-xl border bg-slate-900 p-3 shadow sm:flex sm:items-center sm:justify-between sm:gap-3 sm:p-4">
<p className="text-center text-sm font-medium text-slate-100 sm:text-left">
Generate invoice in 10 seconds - no signup required
</p>
diff --git a/src/app/(seo-landings)/seo-landing-definitions.ts b/src/app/(seo-landings)/seo-landing-definitions.ts
index 7769dc7..f86c1c6 100644
--- a/src/app/(seo-landings)/seo-landing-definitions.ts
+++ b/src/app/(seo-landings)/seo-landing-definitions.ts
@@ -18,6 +18,8 @@ export interface SeoSection {
title: string;
/** Short lead before body content */
lead?: string;
+ /** Show comparison table */
+ showComparisonTable?: boolean;
paragraphs?: string[];
bullets?: string[];
}
@@ -67,9 +69,9 @@ export const SEO_LANDING_DEFINITIONS = {
"Generate professional PDFs in seconds. No account, no signup, no tracking. Start creating now.",
bullets: [
"Create invoices in 60 seconds",
- "No login. No email. No tracking.",
"Download PDF instantly",
"Free and open-source forever",
+ "No login. No email. No tracking.",
],
ctaLabel: "Create Invoice Now",
ctaHref: DEFAULT_INVOICE_TEMPLATE_HREF,
@@ -77,7 +79,7 @@ export const SEO_LANDING_DEFINITIONS = {
},
sections: [
{
- title: "Why no-login matters",
+ title: "πŸ‘‰ Why no-login matters",
lead: "Most tools force you to create an account before you can even download an invoice. That slows you down and adds unnecessary friction.",
paragraphs: ["This tool skips all of that:"],
bullets: [
@@ -88,7 +90,7 @@ export const SEO_LANDING_DEFINITIONS = {
],
},
{
- title: "Who is this for",
+ title: "πŸ‘‰ Who is this for",
bullets: [
"Freelancers who need a quick invoice",
"Developers generating invoices on the fly",
@@ -97,7 +99,7 @@ export const SEO_LANDING_DEFINITIONS = {
],
},
{
- title: "Features",
+ title: "πŸ‘‰ Features",
bullets: [
"Generate professional PDFs in seconds",
"Templates designed to impress clients",
@@ -106,7 +108,7 @@ export const SEO_LANDING_DEFINITIONS = {
],
},
{
- title: "Compare to other tools",
+ title: "πŸ‘‰ Compare to other tools",
lead: "Unlike tools like QuickBooks or Zoho:",
bullets: [
"No onboarding",
@@ -173,7 +175,7 @@ export const SEO_LANDING_DEFINITIONS = {
},
sections: [
{
- title: "Why open-source matters",
+ title: "πŸ‘‰ Why open-source matters",
lead: "Most invoicing tools lock you into their ecosystem.",
paragraphs: ["This one does not:"],
bullets: [
@@ -184,7 +186,7 @@ export const SEO_LANDING_DEFINITIONS = {
],
},
{
- title: "What you can do",
+ title: "πŸ‘‰ What you can do",
bullets: [
"Generate invoices instantly",
"Customize templates and fields before export",
@@ -193,7 +195,7 @@ export const SEO_LANDING_DEFINITIONS = {
],
},
{
- title: "Built for developers",
+ title: "πŸ‘‰ Built for developers",
lead: "Unlike traditional tools like Stripe or QuickBooks, this is designed with developers in mind:",
bullets: [
"Simple architecture you can read quickly",
@@ -203,7 +205,7 @@ export const SEO_LANDING_DEFINITIONS = {
],
},
{
- title: "Self-hosting option",
+ title: "πŸ‘‰ Self-hosting option",
lead: "Want full control?",
paragraphs: ["You can run your own version:"],
bullets: [
@@ -213,7 +215,7 @@ export const SEO_LANDING_DEFINITIONS = {
],
},
{
- title: "Use cases",
+ title: "πŸ‘‰ Use cases",
bullets: [
"Indie hackers",
"SaaS builders",
@@ -274,7 +276,7 @@ export const SEO_LANDING_DEFINITIONS = {
},
sections: [
{
- title: "Why not use Stripe?",
+ title: "πŸ‘‰ Why not use Stripe?",
lead: "Stripe is powerful - but often overkill if you just need a simple invoice.",
paragraphs: ["Common issues:"],
bullets: [
@@ -284,14 +286,15 @@ export const SEO_LANDING_DEFINITIONS = {
],
},
{
- title: "A simpler approach",
+ title: "πŸ‘‰ A simpler approach",
paragraphs: [
"This tool focuses on one thing: generating clean, professional invoices fast.",
"No account setup, no product configuration, and no integrations required.",
],
},
{
- title: "When to use this instead",
+ showComparisonTable: true,
+ title: "πŸ‘‰ When to use this instead",
lead: "Use this tool if:",
bullets: [
"You do not need online payments",
@@ -300,7 +303,7 @@ export const SEO_LANDING_DEFINITIONS = {
],
},
{
- title: "Who this is for",
+ title: "πŸ‘‰ Who this is for",
bullets: ["Freelancers", "Consultants", "Developers", "Side projects"],
},
],
@@ -364,12 +367,11 @@ export const SEO_LANDING_DEFINITIONS = {
],
ctaLabel: "Generate Invoice PDF",
ctaHref: DEFAULT_INVOICE_TEMPLATE_HREF,
- heroImage: `${STATIC_ASSETS_URL}/seo-content/
-def-tmp-v2.png`,
+ heroImage: `${STATIC_ASSETS_URL}/seo-content/def-tmp-v2.png`,
},
sections: [
{
- title: "Why use a PDF invoice template",
+ title: "πŸ‘‰ Why use a PDF invoice template",
lead: "No formatting issues, no surprises.",
bullets: [
"Universally accepted by clients and accounting teams",
@@ -378,7 +380,7 @@ def-tmp-v2.png`,
],
},
{
- title: "What is included",
+ title: "πŸ‘‰ What is included",
bullets: [
"Pre-designed invoice layout ready to fill in",
"Automatic totals calculation as you edit line items",
@@ -387,11 +389,11 @@ def-tmp-v2.png`,
],
},
{
- title: "Who it is for",
+ title: "πŸ‘‰ Who it is for",
bullets: ["Freelancers", "Contractors", "Agencies", "Small businesses"],
},
{
- title: "Skip manual templates",
+ title: "πŸ‘‰ Skip manual templates",
lead: "Instead of editing Word or Excel templates:",
bullets: [
"No formatting headaches",
@@ -400,7 +402,7 @@ def-tmp-v2.png`,
],
},
{
- title: "Better than traditional tools",
+ title: "πŸ‘‰ Better than traditional tools",
lead: "Compared to tools like QuickBooks or Wave:",
bullets: [
"Generate PDFs faster for one-off invoices",
diff --git a/src/app/api/generate-invoice/route.tsx b/src/app/api/generate-invoice/route.tsx
index a7f6e2a..c52d635 100644
--- a/src/app/api/generate-invoice/route.tsx
+++ b/src/app/api/generate-invoice/route.tsx
@@ -229,7 +229,9 @@ The generated invoices are included in the attachments. Please check them carefu
[View invoice online](${invoiceUrl})
[View in Google Drive](${folderToUploadInvoices.webViewLink}) path: *${googleDriveFolderPath}*
-*Don't forget to* [send email to company](${companyEmailLink})
+*☝️ Important - Don't forget to:*
+- [Send email to company](${companyEmailLink})
+- [Submit to KSEF](https://ap.ksef.mf.gov.pl/web/)
Have a nice day!
@@ -263,7 +265,9 @@ EasyInvoicePDF.com`,
<br/>
<br/>
- <b>Important:</b> <a href="${companyEmailLink}"><b>Send these invoices via email to the company</b></a> for processing and payment
+ <b>☝️ Important - Don't forget to:</b><br/>
+ - <a href="${companyEmailLink}"><b>Send these invoices via email to the company</b></a> for processing and payment<br/>
+ - <a href="https://ap.ksef.mf.gov.pl/web/"><b>Submit to KSEF</b></a>
<br/>
<br/>
diff --git a/src/app/api/telegram-webhook/route.ts b/src/app/api/telegram-webhook/route.ts
new file mode 100644
index 0000000..82a368d
--- /dev/null
+++ b/src/app/api/telegram-webhook/route.ts
@@ -0,0 +1,145 @@
+import { env } from "@/env";
+import { sendTelegramMessage } from "@/lib/telegram";
+import { NextResponse, type NextRequest } from "next/server";
+
+export const dynamic = "force-dynamic";
+
+interface TelegramUpdate {
+ update_id: number;
+ message?: {
+ message_id: number;
+ from: {
+ id: number;
+ is_bot: boolean;
+ first_name: string;
+ };
+ chat: {
+ id: number;
+ type: string;
+ };
+ date: number;
+ text?: string;
+ entities?: Array<{
+ offset: number;
+ length: number;
+ type: string;
+ }>;
+ };
+}
+
+/**
+ * Handles incoming Telegram webhook updates.
+ * Processes /generate commands from authorized users to trigger invoice generation.
+ * @param req - Next.js request object containing Telegram update payload
+ * @returns JSON response indicating webhook was processed
+ */
+export async function POST(req: NextRequest) {
+ try {
+ const body = await req.text();
+
+ // Parse and validate incoming Telegram update
+ const update = JSON.parse(body) as TelegramUpdate;
+
+ // Guard: ignore updates without message text
+ if (!update.message?.text) {
+ return new NextResponse(JSON.stringify({ ok: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+
+ const isGenerateInvoiceCommand = update.message.text === "/generate";
+
+ if (!isGenerateInvoiceCommand) {
+ return new NextResponse(JSON.stringify({ ok: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+
+ const senderChatId = update.message.from.id;
+ const allowedChatId = parseInt(env.TELEGRAM_CHAT_ID, 10);
+
+ if (senderChatId !== allowedChatId) {
+ console.error(
+ `[telegram-webhook] Unauthorized user ${senderChatId} tried to invoke /generate`,
+ );
+ await sendTelegramMessage({
+ message: "❌ You are not authorized to use this command.",
+ });
+ return new NextResponse(JSON.stringify({ ok: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+
+ 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",
+ });
+
+ 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}\nError: ${errorText}`,
+ });
+
+ return new NextResponse(JSON.stringify({ ok: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+
+ await sendTelegramMessage({
+ message: `βœ… Invoices generated and sent successfully!`,
+ });
+
+ return new NextResponse(JSON.stringify({ ok: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ } catch (error) {
+ console.error("[telegram-webhook] Error in webhook:", error);
+
+ try {
+ await sendTelegramMessage({
+ message: `🚨 Webhook error: ${error instanceof Error ? error.message : "Unknown error"}`,
+ });
+ } catch (telegramError) {
+ console.error(
+ "[telegram-webhook] Failed to send error message:",
+ telegramError,
+ );
+ }
+
+ return new NextResponse(JSON.stringify({ ok: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+}