Files
workparking/app/api/leads/route.ts
deonisii 97237d85ad
All checks were successful
Auto Deploy / deploy (push) Successful in 16s
Исправил ошибки связанные с интеграцией с CRM
2026-04-19 01:53:02 +03:00

95 lines
2.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { NextResponse } from "next/server";
type LeadRequestBody = {
name?: string;
phone?: string;
email?: string | null;
message?: string | null;
};
function normalizePhone(input: string) {
const digits = input.replace(/\D/g, "");
if (digits.length === 11 && (digits.startsWith("7") || digits.startsWith("8"))) {
return `+7${digits.slice(1)}`;
}
if (digits.length === 10) {
return `+7${digits}`;
}
return null;
}
export async function POST(request: Request) {
const apiUrl = process.env.ESPOCRM_API_URL?.trim();
const apiKey = process.env.ESPOCRM_API_KEY?.trim();
const leadSource = process.env.ESPOCRM_LEAD_SOURCE?.trim() || "Web Site";
if (!apiUrl || !apiKey) {
console.error("EspoCRM env is not configured");
return NextResponse.json(
{ error: "Интеграция CRM временно не настроена" },
{ status: 500 },
);
}
try {
const body = (await request.json()) as LeadRequestBody;
const name = body.name?.trim() || "";
const email = body.email?.trim() || null;
const message = body.message?.trim() || null;
const phoneNumber = body.phone ? normalizePhone(body.phone) : null;
if (name.length < 2 || !phoneNumber) {
return NextResponse.json(
{ error: "Проверьте название объекта и номер телефона" },
{ status: 400 },
);
}
const descriptionParts = [message || "Заявка с сайта"];
if (email) {
descriptionParts.push(`Email: ${email}`);
}
const payload = {
name,
phoneNumber,
emailAddress: email,
description: descriptionParts.join("\n"),
source: leadSource,
};
const response = await fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"X-Api-Key": apiKey,
},
body: JSON.stringify(payload),
cache: "no-store",
});
if (!response.ok) {
const errorText = await response.text();
console.error("EspoCRM lead create failed:", response.status, errorText);
return NextResponse.json(
{ error: "Не удалось отправить заявку в CRM" },
{ status: 502 },
);
}
return NextResponse.json({ success: true }, { status: 201 });
} catch (error) {
console.error("POST /api/leads error:", error);
return NextResponse.json(
{ error: "Не удалось обработать заявку" },
{ status: 500 },
);
}
}