add crm auth, email, status update and search
All checks were successful
Auto Deploy / deploy (push) Successful in 1m7s

This commit is contained in:
deonisii
2026-04-17 21:29:14 +03:00
parent 246fb6d52d
commit 4f67bca4be
16 changed files with 502 additions and 35 deletions

View File

@@ -1,16 +1,80 @@
import { prisma } from "@/lib/prisma";
import LeadStatusSelect from "@/components/lead-status-select";
export const dynamic = "force-dynamic";
export default async function AdminLeadsPage() {
type SearchParams = Promise<{
q?: string;
status?: string;
}>;
export default async function AdminLeadsPage({
searchParams,
}: {
searchParams: SearchParams;
}) {
const params = await searchParams;
const q = params.q?.trim() || "";
const status = params.status?.trim() || "";
const leads = await prisma.lead.findMany({
where: {
AND: [
q
? {
OR: [
{ company: { contains: q, mode: "insensitive" } },
{ phone: { contains: q, mode: "insensitive" } },
{ email: { contains: q, mode: "insensitive" } },
{ message: { contains: q, mode: "insensitive" } },
],
}
: {},
status ? { status: status as any } : {},
],
},
orderBy: { createdAt: "desc" },
});
return (
<main className="min-h-screen bg-neutral-950 text-white">
<div className="max-w-6xl mx-auto px-4 sm:px-6 py-10">
<h1 className="text-3xl font-bold mb-8">Заявки</h1>
<div className="max-w-7xl mx-auto px-4 sm:px-6 py-10">
<div className="flex items-center justify-between gap-4 mb-8">
<h1 className="text-3xl font-bold">Заявки</h1>
<form action="/api/admin/logout" method="POST">
<button className="rounded-2xl border border-white/10 px-4 py-2 hover:bg-white/5">
Выйти
</button>
</form>
</div>
<form className="grid md:grid-cols-[1fr_220px_auto] gap-4 mb-6">
<input
type="text"
name="q"
defaultValue={q}
placeholder="Поиск: компания, телефон, email, сообщение"
className="rounded-2xl border border-white/10 bg-neutral-900 px-4 py-3 outline-none"
/>
<select
name="status"
defaultValue={status}
className="rounded-2xl border border-white/10 bg-neutral-900 px-4 py-3 outline-none"
>
<option value="">Все статусы</option>
<option value="NEW">NEW</option>
<option value="IN_PROGRESS">IN_PROGRESS</option>
<option value="CALL_SCHEDULED">CALL_SCHEDULED</option>
<option value="WON">WON</option>
<option value="LOST">LOST</option>
</select>
<button className="rounded-2xl bg-emerald-600 px-5 py-3 font-semibold hover:bg-emerald-500">
Найти
</button>
</form>
<div className="overflow-x-auto rounded-2xl border border-white/10 bg-neutral-900">
<table className="w-full text-sm">
@@ -19,6 +83,7 @@ export default async function AdminLeadsPage() {
<th className="text-left px-4 py-3">Дата</th>
<th className="text-left px-4 py-3">Компания</th>
<th className="text-left px-4 py-3">Телефон</th>
<th className="text-left px-4 py-3">Email</th>
<th className="text-left px-4 py-3">Сообщение</th>
<th className="text-left px-4 py-3">Статус</th>
<th className="text-left px-4 py-3">Источник</th>
@@ -32,17 +97,18 @@ export default async function AdminLeadsPage() {
</td>
<td className="px-4 py-3">{lead.company}</td>
<td className="px-4 py-3">{lead.phone}</td>
<td className="px-4 py-3 text-neutral-300">
{lead.message || "—"}
<td className="px-4 py-3">{lead.email || "—"}</td>
<td className="px-4 py-3 text-neutral-300">{lead.message || "—"}</td>
<td className="px-4 py-3">
<LeadStatusSelect leadId={lead.id} value={lead.status} />
</td>
<td className="px-4 py-3">{lead.status}</td>
<td className="px-4 py-3">{lead.source}</td>
</tr>
))}
{leads.length === 0 && (
<tr>
<td colSpan={6} className="px-4 py-8 text-center text-neutral-400">
<td colSpan={7} className="px-4 py-8 text-center text-neutral-400">
Пока заявок нет
</td>
</tr>

78
app/admin/login/page.tsx Normal file
View File

@@ -0,0 +1,78 @@
"use client";
import { useState } from "react";
export default function AdminLoginPage() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [errorText, setErrorText] = useState("");
const [isLoading, setIsLoading] = useState(false);
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setErrorText("");
setIsLoading(true);
try {
const response = await fetch("/api/admin/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
});
const data = await response.json();
if (!response.ok) {
setErrorText(data.error || "Ошибка входа");
return;
}
window.location.href = "/admin/leads";
} catch {
setErrorText("Ошибка сети");
} finally {
setIsLoading(false);
}
}
return (
<main className="min-h-screen bg-neutral-950 text-white flex items-center justify-center px-4">
<div className="w-full max-w-md rounded-3xl border border-white/10 bg-neutral-900 p-8">
<h1 className="text-3xl font-bold mb-2">Вход в CRM</h1>
<p className="text-neutral-400 mb-6">WorkParking CRM</p>
<form onSubmit={handleSubmit} className="space-y-4">
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full rounded-2xl border border-white/10 bg-black/30 px-4 py-3 outline-none focus:border-emerald-500"
required
/>
<input
type="password"
placeholder="Пароль"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full rounded-2xl border border-white/10 bg-black/30 px-4 py-3 outline-none focus:border-emerald-500"
required
/>
<button
type="submit"
disabled={isLoading}
className="w-full rounded-2xl bg-emerald-600 px-4 py-3 font-semibold hover:bg-emerald-500 disabled:opacity-60"
>
{isLoading ? "Входим..." : "Войти"}
</button>
{errorText && <p className="text-sm text-red-400">{errorText}</p>}
</form>
</div>
</main>
);
}

View File

@@ -0,0 +1,38 @@
import { NextResponse } from "next/server";
import { createSessionToken, getAdminCredentials, getSessionCookieName } from "@/lib/auth";
type LoginPayload = {
email?: string;
password?: string;
};
export async function POST(request: Request) {
try {
const body = (await request.json()) as LoginPayload;
const email = body.email?.trim().toLowerCase() || "";
const password = body.password?.trim() || "";
const admin = getAdminCredentials();
if (email !== admin.email.toLowerCase() || password !== admin.password) {
return NextResponse.json({ error: "Неверный email или пароль" }, { status: 401 });
}
const token = await createSessionToken(email);
const response = NextResponse.json({ success: true });
response.cookies.set({
name: getSessionCookieName(),
value: token,
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 7,
});
return response;
} catch {
return NextResponse.json({ error: "Ошибка авторизации" }, { status: 500 });
}
}

View File

@@ -0,0 +1,18 @@
import { NextResponse } from "next/server";
import { getSessionCookieName } from "@/lib/auth";
export async function POST() {
const response = NextResponse.json({ success: true });
response.cookies.set({
name: getSessionCookieName(),
value: "",
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
maxAge: 0,
});
return response;
}

View File

@@ -0,0 +1,43 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
const allowedStatuses = [
"NEW",
"IN_PROGRESS",
"CALL_SCHEDULED",
"WON",
"LOST",
] as const;
type LeadStatus = (typeof allowedStatuses)[number];
type PatchPayload = {
status?: LeadStatus;
};
export async function PATCH(
request: Request,
context: { params: Promise<{ id: string }> }
) {
try {
const { id } = await context.params;
const body = (await request.json()) as PatchPayload;
if (!body.status || !allowedStatuses.includes(body.status)) {
return NextResponse.json({ error: "Некорректный статус" }, { status: 400 });
}
const lead = await prisma.lead.update({
where: { id },
data: { status: body.status },
});
return NextResponse.json({ success: true, lead });
} catch (error) {
console.error("PATCH /api/leads/[id] error:", error);
return NextResponse.json(
{ error: "Не удалось обновить статус" },
{ status: 500 }
);
}
}

View File

@@ -4,6 +4,7 @@ import { prisma } from "@/lib/prisma";
type LeadPayload = {
company?: string;
phone?: string;
email?: string;
message?: string;
};
@@ -13,11 +14,12 @@ export async function POST(request: Request) {
const company = body.company?.trim();
const phone = body.phone?.trim();
const email = body.email?.trim().toLowerCase();
const message = body.message?.trim() || "";
if (!company || !phone) {
if (!company || !phone || !email) {
return NextResponse.json(
{ error: "Компания и телефон обязательны" },
{ error: "Компания, телефон и email обязательны" },
{ status: 400 }
);
}
@@ -26,6 +28,7 @@ export async function POST(request: Request) {
data: {
company,
phone,
email,
message,
source: "website",
},
@@ -39,20 +42,4 @@ export async function POST(request: Request) {
{ status: 500 }
);
}
}
export async function GET() {
try {
const leads = await prisma.lead.findMany({
orderBy: { createdAt: "desc" },
});
return NextResponse.json(leads);
} catch (error) {
console.error("GET /api/leads error:", error);
return NextResponse.json(
{ error: "Не удалось получить заявки" },
{ status: 500 }
);
}
}

View File

@@ -2,18 +2,49 @@
import { useState } from "react";
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;
}
function isValidEmail(email: string) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
export default function LeadForm() {
const [company, setCompany] = useState("");
const [phone, setPhone] = useState("");
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [resultMessage, setResultMessage] = useState("");
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setIsSubmitting(true);
setResultMessage("");
const normalizedPhone = normalizePhone(phone);
if (!normalizedPhone) {
setResultMessage("Введите корректный российский телефон");
return;
}
if (!isValidEmail(email.trim())) {
setResultMessage("Введите корректный email");
return;
}
setIsSubmitting(true);
try {
const response = await fetch("/api/leads", {
method: "POST",
@@ -22,7 +53,8 @@ export default function LeadForm() {
},
body: JSON.stringify({
company,
phone,
phone: normalizedPhone,
email,
message,
}),
});
@@ -37,10 +69,10 @@ export default function LeadForm() {
setResultMessage("Заявка отправлена. Мы свяжемся с вами.");
setCompany("");
setPhone("");
setEmail("");
setMessage("");
} catch (error) {
console.error(error);
setResultMessage("Ошибка сети. Попробуйте ещё раз.");
} catch {
setResultMessage("Не удалось сохранить заявку");
} finally {
setIsSubmitting(false);
}
@@ -59,15 +91,24 @@ export default function LeadForm() {
<input
type="tel"
placeholder="+7 (___) ___-__-__"
placeholder="+7 (999) 123-45-67"
value={phone}
onChange={(e) => setPhone(e.target.value)}
className="w-full rounded-2xl border border-white/10 bg-black/30 px-5 py-4 outline-none placeholder:text-neutral-500 focus:border-emerald-500"
required
/>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full rounded-2xl border border-white/10 bg-black/30 px-5 py-4 outline-none placeholder:text-neutral-500 focus:border-emerald-500"
required
/>
<textarea
placeholder="Опишите текущий шлагбаум и что хотите добавить: номерной доступ, приложение, история, аналитика"
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-5 py-4 outline-none placeholder:text-neutral-500 focus:border-emerald-500"

View File

@@ -0,0 +1,62 @@
"use client";
import { useState } from "react";
const statuses = [
{ value: "NEW", label: "NEW" },
{ value: "IN_PROGRESS", label: "IN_PROGRESS" },
{ value: "CALL_SCHEDULED", label: "CALL_SCHEDULED" },
{ value: "WON", label: "WON" },
{ value: "LOST", label: "LOST" },
] as const;
export default function LeadStatusSelect({
leadId,
value,
}: {
leadId: string;
value: string;
}) {
const [status, setStatus] = useState(value);
const [isSaving, setIsSaving] = useState(false);
async function updateStatus(nextStatus: string) {
setStatus(nextStatus);
setIsSaving(true);
try {
const response = await fetch(`/api/leads/${leadId}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ status: nextStatus }),
});
if (!response.ok) {
setStatus(value);
alert("Не удалось обновить статус");
}
} catch {
setStatus(value);
alert("Ошибка сети");
} finally {
setIsSaving(false);
}
}
return (
<select
value={status}
disabled={isSaving}
onChange={(e) => updateStatus(e.target.value)}
className="rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-sm outline-none"
>
{statuses.map((item) => (
<option key={item.value} value={item.value}>
{item.label}
</option>
))}
</select>
);
}

View File

@@ -24,6 +24,10 @@ services:
PORT: 3000
HOSTNAME: 0.0.0.0
DATABASE_URL: postgresql://workparking:change_me_strong_password@db:5432/workparking?schema=public
ADMIN_EMAIL: admin@workparking.ru
ADMIN_PASSWORD: "vvEzQxqXzgjS-9oT"
ADMIN_SESSION_SECRET: "d9yyLuMk7xdNqNv2vxEXQzGHSc_ZcAM49NFfUKZJrFysyZ3Yb2"
CRM_HOST: crm.workparking.ru
ports:
- "127.0.0.1:3011:3000"
depends_on:

71
lib/auth.ts Normal file
View File

@@ -0,0 +1,71 @@
const SESSION_COOKIE = "wp_admin_session";
const SESSION_TTL_SECONDS = 60 * 60 * 24 * 7;
function getSecret() {
const secret = process.env.ADMIN_SESSION_SECRET;
if (!secret) {
throw new Error("ADMIN_SESSION_SECRET is not set");
}
return secret;
}
function toHex(buffer: ArrayBuffer) {
return Array.from(new Uint8Array(buffer))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
async function sign(value: string) {
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(getSecret()),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"]
);
const signature = await crypto.subtle.sign(
"HMAC",
key,
new TextEncoder().encode(value)
);
return toHex(signature);
}
export async function createSessionToken(email: string) {
const expiresAt = Math.floor(Date.now() / 1000) + SESSION_TTL_SECONDS;
const payload = `${email}.${expiresAt}`;
const signature = await sign(payload);
return `${payload}.${signature}`;
}
export async function verifySessionToken(token?: string | null) {
if (!token) return false;
const parts = token.split(".");
if (parts.length < 3) return false;
const signature = parts.pop()!;
const expiresAt = Number(parts.pop());
const email = parts.join(".");
if (!email || !expiresAt || Number.isNaN(expiresAt)) return false;
if (expiresAt < Math.floor(Date.now() / 1000)) return false;
const payload = `${email}.${expiresAt}`;
const expectedSignature = await sign(payload);
return signature === expectedSignature;
}
export function getSessionCookieName() {
return SESSION_COOKIE;
}
export function getAdminCredentials() {
return {
email: process.env.ADMIN_EMAIL || "",
password: process.env.ADMIN_PASSWORD || "",
};
}

41
middleware.ts Normal file
View File

@@ -0,0 +1,41 @@
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookieName, verifySessionToken } from "@/lib/auth";
export async function middleware(request: NextRequest) {
const { pathname, search } = request.nextUrl;
const host = request.headers.get("host") || "";
const crmHost = process.env.CRM_HOST || "crm.workparking.ru";
if (!pathname.startsWith("/admin")) {
return NextResponse.next();
}
if (host !== crmHost) {
const redirectUrl = new URL(request.url);
redirectUrl.host = crmHost;
redirectUrl.protocol = "https:";
return NextResponse.redirect(redirectUrl);
}
const cookieName = getSessionCookieName();
const token = request.cookies.get(cookieName)?.value;
const isAuthed = await verifySessionToken(token);
const isLoginPage = pathname === "/admin/login";
if (!isAuthed && !isLoginPage) {
const loginUrl = new URL("/admin/login", request.url);
loginUrl.searchParams.set("next", `${pathname}${search}`);
return NextResponse.redirect(loginUrl);
}
if (isAuthed && isLoginPage) {
return NextResponse.redirect(new URL("/admin/leads", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/admin/:path*"],
};

19
package-lock.json generated
View File

@@ -10,6 +10,7 @@
"dependencies": {
"@prisma/adapter-pg": "^7.7.0",
"@prisma/client": "^7.7.0",
"dotenv": "^17.4.2",
"framer-motion": "^12.38.0",
"lucide-react": "^1.8.0",
"next": "16.2.4",
@@ -3519,6 +3520,18 @@
}
}
},
"node_modules/c12/node_modules/dotenv": {
"version": "16.6.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
"integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/call-bind": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz",
@@ -3903,9 +3916,9 @@
}
},
"node_modules/dotenv": {
"version": "16.6.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
"integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
"version": "17.4.2",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",
"integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"

View File

@@ -11,6 +11,7 @@
"dependencies": {
"@prisma/adapter-pg": "^7.7.0",
"@prisma/client": "^7.7.0",
"dotenv": "^17.4.2",
"framer-motion": "^12.38.0",
"lucide-react": "^1.8.0",
"next": "16.2.4",

View File

@@ -1,3 +1,4 @@
import "dotenv/config";
import { defineConfig, env } from "prisma/config";
export default defineConfig({

View File

@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Lead" ADD COLUMN "email" TEXT;

View File

@@ -18,6 +18,7 @@ model Lead {
id String @id @default(cuid())
company String
phone String
email String?
message String?
source String @default("website")
status LeadStatus @default(NEW)