Files
tripwithbonus/frontend/lib/main/sendLead.ts
2025-05-24 15:12:37 +03:00

55 lines
1.4 KiB
TypeScript

import { Lead } from '@/app/types'
import { getSession } from 'next-auth/react'
export const sendLead = async (data: Lead & { id?: number }) => {
const API_URL = process.env.NEXT_PUBLIC_API_URL
const session = await getSession()
if (!session?.accessToken) {
throw new Error('No access token found')
}
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${session.accessToken}`,
}
try {
const body = JSON.stringify({
name: data.name,
phone_number: data.phone_number,
email: data.email,
moving_price: data.moving_price,
moving_date: data.moving_date,
comment: data.comment,
route: data.id,
})
const response = await fetch(`${API_URL}/account/send_lead/`, {
method: 'POST',
headers,
body,
})
if (!response.ok) {
let errorMessage = `Failed to send lead data: ${response.status} ${response.statusText}`
try {
const errorData = await response.text()
if (errorData) {
errorMessage += ` - ${errorData}`
}
} catch (e) {
console.error('Error parsing error response:', e)
}
throw new Error(errorMessage)
}
const text = await response.text()
return text ? JSON.parse(text) : null
} catch (error) {
console.error('Error sending lead data:', error)
throw error
}
}