83 lines
2.4 KiB
TypeScript
83 lines
2.4 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
|
|
const TELEGRAM_API = 'https://api.telegram.org'
|
|
|
|
export interface ConsultingRequestBody {
|
|
fullName: string
|
|
organization: string
|
|
phone: string
|
|
area: string
|
|
description?: string
|
|
}
|
|
|
|
function escapeForTelegram(text: string): string {
|
|
return text
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
const token = process.env.TELEGRAM_BOT_TOKEN
|
|
const chatId = process.env.TELEGRAM_CHAT_ID
|
|
|
|
if (!token || !chatId) {
|
|
return NextResponse.json(
|
|
{ error: 'تلگرام پیکربندی نشده است. TELEGRAM_BOT_TOKEN و TELEGRAM_CHAT_ID را در .env.local تنظیم کنید.' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
|
|
let body: ConsultingRequestBody
|
|
try {
|
|
body = await request.json()
|
|
} catch {
|
|
return NextResponse.json({ error: 'بدنه درخواست نامعتبر است' }, { status: 400 })
|
|
}
|
|
|
|
const { fullName, organization, phone, area, description } = body
|
|
if (!fullName?.trim() || !organization?.trim() || !phone?.trim() || !area?.trim()) {
|
|
return NextResponse.json({ error: 'فیلدهای الزامی خالی است' }, { status: 400 })
|
|
}
|
|
|
|
const lines = [
|
|
'📩 <b>درخواست جدید مشاوره سازمانی</b>',
|
|
'',
|
|
`<b>نام و نام خانوادگی:</b> ${escapeForTelegram(fullName.trim())}`,
|
|
`<b>نام سازمان:</b> ${escapeForTelegram(organization.trim())}`,
|
|
`<b>شماره تماس:</b> ${escapeForTelegram(phone.trim())}`,
|
|
`<b>حوزه مشاوره:</b> ${escapeForTelegram(area.trim())}`,
|
|
]
|
|
if (description?.trim()) {
|
|
lines.push('', `<b>توضیحات:</b>`, escapeForTelegram(description.trim()))
|
|
}
|
|
|
|
const text = lines.join('\n')
|
|
|
|
try {
|
|
const res = await fetch(`${TELEGRAM_API}/bot${token}/sendMessage`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
chat_id: chatId,
|
|
text,
|
|
parse_mode: 'HTML',
|
|
}),
|
|
})
|
|
|
|
const data = await res.json().catch(() => ({}))
|
|
if (!res.ok) {
|
|
return NextResponse.json(
|
|
{ error: data.description || 'ارسال به تلگرام ناموفق بود' },
|
|
{ status: 502 }
|
|
)
|
|
}
|
|
return NextResponse.json({ ok: true })
|
|
} catch (err) {
|
|
return NextResponse.json(
|
|
{ error: 'خطا در ارتباط با تلگرام' },
|
|
{ status: 502 }
|
|
)
|
|
}
|
|
}
|