96 lines
2.5 KiB
TypeScript
96 lines
2.5 KiB
TypeScript
'use server'
|
|
|
|
const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN
|
|
const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID
|
|
const TELEGRAM_URL = process.env.TELEGRAM_URL ?? 'https://api.telegram.org'
|
|
|
|
export type ContactFormData = {
|
|
name: string
|
|
phone: string
|
|
email?: string
|
|
subject?: string
|
|
message?: string
|
|
}
|
|
|
|
function buildTelegramMessage(data: ContactFormData): string {
|
|
const lines = [
|
|
'📞 *تماس با ما*',
|
|
'',
|
|
`👤 *نام:* ${data.name}`,
|
|
`📱 *تلفن:* ${data.phone}`,
|
|
]
|
|
if (data.email?.trim()) {
|
|
lines.push(`📧 *ایمیل:* ${data.email.trim()}`)
|
|
}
|
|
if (data.subject?.trim()) {
|
|
lines.push(`📌 *موضوع:* ${data.subject.trim()}`)
|
|
}
|
|
if (data.message?.trim()) {
|
|
lines.push('', '*پیام:*', data.message.trim())
|
|
}
|
|
return lines.join('\n')
|
|
}
|
|
|
|
export async function submitContact(
|
|
data: ContactFormData
|
|
): Promise<{ success: boolean; error?: string }> {
|
|
const name = data.name?.trim()
|
|
const phone = data.phone?.trim().replace(/\s/g, '')
|
|
|
|
if (!name || name.length < 2) {
|
|
return { success: false, error: 'نام و نام خانوادگی را وارد کنید.' }
|
|
}
|
|
if (!phone || phone.length < 10) {
|
|
return { success: false, error: 'شماره تماس معتبر وارد کنید.' }
|
|
}
|
|
|
|
if (!TELEGRAM_BOT_TOKEN || !TELEGRAM_CHAT_ID) {
|
|
console.error('TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID is not set')
|
|
return {
|
|
success: false,
|
|
error: 'پیکربندی ارسال پیام انجام نشده است. لطفاً با پشتیبانی تماس بگیرید.',
|
|
}
|
|
}
|
|
|
|
const text = buildTelegramMessage({
|
|
name,
|
|
phone,
|
|
email: data.email,
|
|
subject: data.subject,
|
|
message: data.message,
|
|
})
|
|
|
|
const url = `${TELEGRAM_URL}/bot${TELEGRAM_BOT_TOKEN}/sendMessage`
|
|
const body = {
|
|
chat_id: TELEGRAM_CHAT_ID,
|
|
text,
|
|
parse_mode: 'Markdown',
|
|
}
|
|
|
|
try {
|
|
const res = await fetch(url, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(body),
|
|
})
|
|
|
|
const result = await res.json()
|
|
|
|
if (!res.ok || !result.ok) {
|
|
console.error('Telegram API error:', result)
|
|
return {
|
|
success: false,
|
|
error: 'ارسال پیام با خطا مواجه شد. لطفاً دوباره تلاش کنید.',
|
|
}
|
|
}
|
|
|
|
return { success: true }
|
|
} catch (e) {
|
|
console.error('Failed to send to Telegram', e)
|
|
return {
|
|
success: false,
|
|
error: 'ارسال پیام با خطا مواجه شد. لطفاً دوباره تلاش کنید.',
|
|
}
|
|
}
|
|
}
|