Files
aragrp/app/api/consulting/route.ts
T
2026-02-19 22:46:08 +03:30

83 lines
2.4 KiB
TypeScript

import { NextResponse } from 'next/server'
/** API بله سازگار با API تلگرام — مستندات: https://dev.bale.ai */
const BALE_API = 'https://tapi.bale.ai'
export interface ConsultingRequestBody {
fullName: string
organization: string
phone: string
area: string
description?: string
}
function escapeHtml(text: string): string {
return text
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
}
export async function POST(request: Request) {
const token = process.env.BALE_BOT_TOKEN
const chatId = process.env.BALE_CHAT_ID
if (!token || !chatId) {
return NextResponse.json(
{
error:
'بله پیکربندی نشده است. BALE_BOT_TOKEN و BALE_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 = [
'📩 درخواست جدید مشاوره سازمانی',
'────────────────',
`👤 نام و نام خانوادگی: ${escapeHtml(fullName.trim())}`,
`🏢 نام سازمان: ${escapeHtml(organization.trim())}`,
`📱 شماره تماس: ${escapeHtml(phone.trim())}`,
`📋 حوزه مشاوره: ${escapeHtml(area.trim())}`,
]
if (description?.trim()) {
lines.push('', `💬 توضیحات:\n${escapeHtml(description.trim())}`)
}
const text = lines.join('\n')
try {
const res = await fetch(`${BALE_API}/bot${token}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
text,
}),
})
const data = await res.json().catch(() => ({}))
if (!res.ok) {
return NextResponse.json(
{ error: data.description || 'ارسال به بله ناموفق بود' },
{ status: 502 }
)
}
return NextResponse.json({ ok: true })
} catch {
return NextResponse.json({ error: 'خطا در ارتباط با بله' }, { status: 502 })
}
}