Добавить форму заявок и серверную интеграцию лидов с 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

View File

@@ -34,6 +34,16 @@ components/
## Локальный запуск ## Локальный запуск
Переменные окружения для отправки лидов в EspoCRM:
```env
ESPOCRM_API_URL=https://crm.parkflow.ru/api/v1/Lead
ESPOCRM_API_KEY=your_api_key_here
ESPOCRM_LEAD_SOURCE=Web Site
```
Их можно положить в локальный `.env` или задать на сервере.
Установить зависимости: Установить зависимости:
```bash ```bash
@@ -98,20 +108,18 @@ docker compose down
- Prisma - Prisma
- PostgreSQL - PostgreSQL
- локальная форма заявок с записью в БД
- API-роуты для лидов
- админка - админка
- локальная авторизация - локальная авторизация
То есть репозиторий теперь хранит только сайт. При этом форма заявок снова доступна, но она работает не через локальную базу, а через внешний CRM API.
## Дальнейшие шаги ## Дальнейшие шаги
Когда будете подключать внешнюю CRM, можно сделать один из вариантов: Когда будете подключать внешнюю CRM, можно сделать один из вариантов:
1. встроить форму из `EspoCRM` на страницу контактов 1. использовать текущую серверную отправку лидов в `EspoCRM`
2. вести кнопки и CTA на внешний CRM-URL 2. встроить форму из `EspoCRM` на страницу контактов
3. подключить webhook/API внешней CRM без своей локальной базы 3. вести кнопки и CTA на внешний CRM-URL
## Репозиторий ## Репозиторий

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 },
);
}
}

View File

@@ -1,3 +1,5 @@
import LeadForm from "@/components/lead-form";
export default function ContactsPage() { export default function ContactsPage() {
return ( return (
<main className="bg-neutral-950"> <main className="bg-neutral-950">
@@ -88,46 +90,11 @@ export default function ContactsPage() {
<section id="contact-request" className="pb-16 sm:pb-20"> <section id="contact-request" className="pb-16 sm:pb-20">
<div className="max-w-5xl mx-auto px-4 sm:px-6"> <div className="max-w-5xl mx-auto px-4 sm:px-6">
<div className="rounded-[32px] border border-white/10 bg-neutral-900 p-6 sm:p-10"> <div className="rounded-[32px] border border-white/10 bg-neutral-900 p-6 sm:p-10">
<div className="max-w-3xl"> <LeadForm
<h2 className="text-3xl font-bold tracking-[-0.04em] sm:text-4xl"> id="lead-form"
Обсудим ваш объект title="Оставить заявку"
</h2> description="Заполните короткую форму. Заявка будет отправлена напрямую в CRM, а мы свяжемся с вами для уточнения задачи."
<p className="mt-4 text-base leading-relaxed text-neutral-400 sm:text-lg"> />
Мы убрали локальную CRM, базу заявок и админку из сайта. Дальше
сюда можно спокойно подключить внешнюю форму из EspoCRM или
любой другой системы, а пока используйте прямые контакты.
</p>
</div>
<div className="mt-8 grid gap-4 md:grid-cols-2">
<a
href="tel:+79999698149"
className="rounded-3xl border border-emerald-500/30 bg-emerald-500/10 px-5 py-5 transition-colors hover:bg-emerald-500/15"
>
<div className="text-sm uppercase tracking-[0.18em] text-emerald-300">
Телефон
</div>
<div className="mt-3 text-2xl font-semibold">
+7 (999) 969-81-49
</div>
<p className="mt-2 text-neutral-400">
Для обсуждения объекта, внедрения и тарифов
</p>
</a>
<a
href="mailto:sale@parkflow.ru"
className="rounded-3xl border border-white/10 bg-black/25 px-5 py-5 transition-colors hover:border-white/20 hover:bg-white/[0.03]"
>
<div className="text-sm uppercase tracking-[0.18em] text-neutral-400">
Email
</div>
<div className="mt-3 text-2xl font-semibold">sale@parkflow.ru</div>
<p className="mt-2 text-neutral-400">
Можно сразу прислать адрес объекта и краткое описание задачи
</p>
</a>
</div>
</div> </div>
</div> </div>
</section> </section>

View File

@@ -1,6 +1,7 @@
import Link from "next/link"; import Link from "next/link";
import Image from "next/image"; import Image from "next/image";
import BarrierIcon from "@/components/barrier-icon"; import BarrierIcon from "@/components/barrier-icon";
import LeadForm from "@/components/lead-form";
import { import {
ArrowRight, ArrowRight,
Camera, Camera,
@@ -134,7 +135,7 @@ export default function Home() {
<div className="mt-7 flex flex-col gap-3 sm:mt-8 sm:flex-row sm:gap-4"> <div className="mt-7 flex flex-col gap-3 sm:mt-8 sm:flex-row sm:gap-4">
<Link <Link
href="/contacts#contact-request" href="/contacts#lead-form"
className="inline-flex items-center justify-center gap-2 rounded-2xl bg-emerald-600 px-5 py-3.5 text-sm font-semibold text-white transition-colors hover:bg-emerald-500 sm:px-6 sm:py-4 sm:text-base" className="inline-flex items-center justify-center gap-2 rounded-2xl bg-emerald-600 px-5 py-3.5 text-sm font-semibold text-white transition-colors hover:bg-emerald-500 sm:px-6 sm:py-4 sm:text-base"
> >
Получить консультацию Получить консультацию
@@ -410,35 +411,11 @@ export default function Home() {
</div> </div>
<div className="rounded-[28px] border border-white/10 bg-black/25 p-5 shadow-[inset_0_1px_0_rgba(255,255,255,0.05)] sm:p-6"> <div className="rounded-[28px] border border-white/10 bg-black/25 p-5 shadow-[inset_0_1px_0_rgba(255,255,255,0.05)] sm:p-6">
<h3 className="text-3xl font-bold tracking-[-0.05em]"> <LeadForm
Свяжитесь с нами title="Оставить заявку"
</h3> description="Заполните форму, и заявка уйдёт напрямую в CRM. Мы свяжемся с вами, чтобы обсудить объект и подходящий сценарий запуска."
<p className="mt-4 text-base leading-relaxed text-neutral-400 sm:text-lg"> compact
Дальше вы сможете подключить сюда форму из EspoCRM или другой />
внешней CRM. Пока сайт остаётся чистым фронтом без своей базы
заявок и админки.
</p>
<div className="mt-8 grid gap-3">
<a
href="tel:+79999698149"
className="inline-flex items-center justify-center rounded-2xl bg-emerald-600 px-5 py-4 text-base font-semibold text-white transition-colors hover:bg-emerald-500"
>
Позвонить: +7 (999) 969-81-49
</a>
<a
href="mailto:sale@parkflow.ru"
className="inline-flex items-center justify-center rounded-2xl border border-white/15 bg-white/[0.02] px-5 py-4 text-base font-semibold transition-colors hover:border-white/30 hover:bg-white/5"
>
Написать: sale@parkflow.ru
</a>
<Link
href="/contacts#contact-request"
className="inline-flex items-center justify-center rounded-2xl border border-white/15 bg-white/[0.02] px-5 py-4 text-base font-semibold transition-colors hover:border-white/30 hover:bg-white/5"
>
Открыть страницу контактов
</Link>
</div>
</div> </div>
</div> </div>
</div> </div>

314
components/lead-form.tsx Normal file
View File

@@ -0,0 +1,314 @@
"use client";
import { useState } from "react";
type FieldErrors = {
name?: string;
phone?: string;
email?: string;
};
type LeadFormProps = {
id?: string;
title?: string;
description?: string;
compact?: boolean;
};
function getPhoneDigits(input: string) {
return input.replace(/\D/g, "").slice(0, 11);
}
function formatRussianPhoneInput(input: string) {
const digits = getPhoneDigits(input);
if (!digits) {
return "";
}
let normalized = digits;
if (normalized[0] === "8") {
normalized = `7${normalized.slice(1)}`;
}
if (normalized[0] !== "7") {
normalized = `7${normalized.slice(0, 10)}`;
}
normalized = normalized.slice(0, 11);
const country = "+7";
const part1 = normalized.slice(1, 4);
const part2 = normalized.slice(4, 7);
const part3 = normalized.slice(7, 9);
const part4 = normalized.slice(9, 11);
let result = country;
if (part1) {
result += ` (${part1}`;
}
if (part1.length === 3) {
result += ")";
}
if (part2) {
result += ` ${part2}`;
}
if (part3) {
result += `-${part3}`;
}
if (part4) {
result += `-${part4}`;
}
return result;
}
function normalizePhone(input: string) {
const digits = getPhoneDigits(input);
if (digits.length === 11 && (digits.startsWith("7") || digits.startsWith("8"))) {
return `7${digits.slice(1)}`;
}
if (digits.length === 10) {
return `7${digits}`;
}
return null;
}
function isValidEmail(email: string) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
export default function LeadForm({
id,
title,
description,
compact = false,
}: LeadFormProps) {
const [name, setName] = useState("");
const [phone, setPhone] = useState("");
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [resultMessage, setResultMessage] = useState("");
const [submitError, setSubmitError] = useState(false);
const [errors, setErrors] = useState<FieldErrors>({});
function validateFields() {
const nextErrors: FieldErrors = {};
const trimmedName = name.trim();
const trimmedEmail = email.trim();
const normalizedPhone = normalizePhone(phone);
if (trimmedName.length < 2) {
nextErrors.name = "Укажите название объекта или компании";
}
if (!normalizedPhone) {
nextErrors.phone = "Введите российский номер в формате +7";
}
if (trimmedEmail && !isValidEmail(trimmedEmail)) {
nextErrors.email = "Проверьте корректность email";
}
return {
nextErrors,
trimmedName,
trimmedEmail,
normalizedPhone,
};
}
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setResultMessage("");
setSubmitError(false);
const { nextErrors, trimmedName, trimmedEmail, normalizedPhone } =
validateFields();
if (Object.keys(nextErrors).length > 0 || !normalizedPhone) {
setErrors(nextErrors);
return;
}
setErrors({});
setIsSubmitting(true);
try {
const response = await fetch("/api/leads", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: trimmedName,
phone: normalizedPhone,
email: trimmedEmail || null,
message: message.trim() || null,
}),
});
const data = await response.json();
if (!response.ok) {
setSubmitError(true);
setResultMessage(data.error || "Не удалось отправить заявку");
return;
}
setName("");
setPhone("");
setEmail("");
setMessage("");
setResultMessage("Заявка отправлена. Мы свяжемся с вами.");
setSubmitError(false);
} catch {
setSubmitError(true);
setResultMessage("Не удалось отправить заявку");
} finally {
setIsSubmitting(false);
}
}
const fieldClassName =
"w-full rounded-2xl border bg-black/30 px-4 py-3.5 text-white outline-none transition-colors placeholder:text-neutral-500 focus:border-emerald-500 sm:px-5 sm:py-4";
const labelClassName = "mb-2 block text-sm font-medium text-neutral-200";
const helperClassName = "mt-2 text-xs text-neutral-500";
const errorClassName = "mt-2 text-xs text-rose-300";
return (
<div id={id}>
{(title || description) && (
<div className={compact ? "mb-6" : "mb-8"}>
{title && (
<h3 className="text-2xl font-semibold tracking-[-0.03em] sm:text-3xl">
{title}
</h3>
)}
{description && (
<p className="mt-3 max-w-2xl text-sm leading-relaxed text-neutral-400 sm:text-base">
{description}
</p>
)}
</div>
)}
<form onSubmit={handleSubmit} className="grid gap-4 sm:gap-5" noValidate>
<div>
<label htmlFor="lead-name" className={labelClassName}>
Объект или компания
</label>
<input
id="lead-name"
type="text"
placeholder="Например: ЖК Сокол, ТСЖ Север, УК Домсервис"
value={name}
onChange={(e) => {
setName(e.target.value);
if (errors.name) {
setErrors((current) => ({ ...current, name: undefined }));
}
}}
className={`${fieldClassName} ${errors.name ? "border-rose-400/70" : "border-white/10"}`}
autoComplete="organization"
required
/>
{errors.name ? (
<p className={errorClassName}>{errors.name}</p>
) : (
<p className={helperClassName}>Укажите ЖК, ТСЖ, УК или адрес объекта</p>
)}
</div>
<div>
<label htmlFor="lead-phone" className={labelClassName}>
Телефон
</label>
<input
id="lead-phone"
type="tel"
placeholder="+7 (999) 123-45-67"
value={phone}
onChange={(e) => {
setPhone(formatRussianPhoneInput(e.target.value));
if (errors.phone) {
setErrors((current) => ({ ...current, phone: undefined }));
}
}}
className={`${fieldClassName} ${errors.phone ? "border-rose-400/70" : "border-white/10"}`}
inputMode="numeric"
autoComplete="tel"
required
/>
{errors.phone ? (
<p className={errorClassName}>{errors.phone}</p>
) : (
<p className={helperClassName}>Только российские номера</p>
)}
</div>
<div>
<label htmlFor="lead-email" className={labelClassName}>
Email
</label>
<input
id="lead-email"
type="email"
placeholder="name@company.ru"
value={email}
onChange={(e) => {
setEmail(e.target.value);
if (errors.email) {
setErrors((current) => ({ ...current, email: undefined }));
}
}}
className={`${fieldClassName} ${errors.email ? "border-rose-400/70" : "border-white/10"}`}
autoComplete="email"
/>
{errors.email ? (
<p className={errorClassName}>{errors.email}</p>
) : (
<p className={helperClassName}>Необязательно, но удобно для ответа</p>
)}
</div>
<div>
<label htmlFor="lead-message" className={labelClassName}>
Комментарий
</label>
<textarea
id="lead-message"
placeholder="Коротко опишите объект и задачу"
value={message}
onChange={(e) => setMessage(e.target.value)}
className="min-h-32 w-full rounded-2xl border border-white/10 bg-black/30 px-4 py-3.5 text-white outline-none transition-colors placeholder:text-neutral-500 focus:border-emerald-500 sm:px-5 sm:py-4"
/>
</div>
<button
type="submit"
disabled={isSubmitting}
className="inline-flex items-center justify-center rounded-2xl bg-emerald-600 px-6 py-4 text-base font-semibold text-white transition-colors hover:bg-emerald-500 disabled:cursor-not-allowed disabled:opacity-60"
>
{isSubmitting ? "Отправка..." : "Оставить заявку"}
</button>
{resultMessage && (
<p className={`text-sm ${submitError ? "text-rose-300" : "text-emerald-300"}`}>
{resultMessage}
</p>
)}
</form>
</div>
);
}

View File

@@ -1,7 +1,7 @@
"use client"; "use client";
import Link from "next/link"; import Link from "next/link";
import { Menu, X, Send, MessageCircle, Phone } from "lucide-react"; import { Menu, X, Send, MessageCircle, FileText } from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
@@ -74,12 +74,12 @@ export default function MobileMenu({
<div className="flex-1 overflow-y-auto px-4 py-5"> <div className="flex-1 overflow-y-auto px-4 py-5">
<div className="mx-auto w-full max-w-none"> <div className="mx-auto w-full max-w-none">
<Link <Link
href="/contacts#contact-request" href="/contacts#lead-form"
onClick={() => setMobileOpen(false)} onClick={() => setMobileOpen(false)}
className="mb-6 flex w-full items-center justify-center gap-2 rounded-2xl bg-emerald-600 px-4 py-4 text-sm font-semibold text-white transition-colors hover:bg-emerald-500" className="mb-6 flex w-full items-center justify-center gap-2 rounded-2xl bg-emerald-600 px-4 py-4 text-sm font-semibold text-white transition-colors hover:bg-emerald-500"
> >
<Phone className="w-5 h-5" /> <FileText className="w-5 h-5" />
Связаться с нами Оставить заявку
</Link> </Link>
<nav className="flex w-full flex-col rounded-3xl border border-white/10 bg-white/[0.03] px-4 py-1"> <nav className="flex w-full flex-col rounded-3xl border border-white/10 bg-white/[0.03] px-4 py-1">

View File

@@ -8,5 +8,8 @@ services:
NODE_ENV: production NODE_ENV: production
PORT: 3000 PORT: 3000
HOSTNAME: 0.0.0.0 HOSTNAME: 0.0.0.0
ESPOCRM_API_URL: ${ESPOCRM_API_URL}
ESPOCRM_API_KEY: ${ESPOCRM_API_KEY}
ESPOCRM_LEAD_SOURCE: ${ESPOCRM_LEAD_SOURCE:-Web Site}
ports: ports:
- "127.0.0.1:3011:3000" - "127.0.0.1:3011:3000"