Добавить форму заявок и серверную интеграцию лидов с EspoCRM
All checks were successful
Auto Deploy / deploy (push) Successful in 17s

This commit is contained in:
deonisii
2026-04-19 01:44:53 +03:00
parent e90b5a21e3
commit 97b996edc8
7 changed files with 443 additions and 80 deletions

94
app/api/leads/route.ts Normal file
View File

@@ -0,0 +1,94 @@
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;
const apiKey = process.env.ESPOCRM_API_KEY;
const leadSource = process.env.ESPOCRM_LEAD_SOURCE || "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 },
);
}
}