ehsan-dashboards/dashboards/crm/app/api/leads/[id]/route.ts

169 lines
4.9 KiB
TypeScript

// app/api/leads/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { calculateTemperature } from '@/lib/automation';
export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
try {
const { id } = params;
const lead = await prisma.lead.findUnique({
where: { id },
include: {
rooms: true,
activities: {
orderBy: { createdAt: 'desc' },
},
onboardingTasks: {
orderBy: { week: 'asc' },
},
auditLogs: {
orderBy: { createdAt: 'desc' },
take: 20,
},
},
});
if (!lead) {
return NextResponse.json({ success: false, error: 'لید یافت نشد.' }, { status: 404 });
}
return NextResponse.json({ success: true, lead });
} catch (error: any) {
return NextResponse.json({ success: false, error: error.message }, { status: 500 });
}
}
export async function PATCH(req: NextRequest, { params }: { params: { id: string } }) {
try {
const { id } = params;
const body = await req.json();
const existing = await prisma.lead.findUnique({
where: { id },
include: { rooms: true },
});
if (!existing) {
return NextResponse.json({ success: false, error: 'لید یافت نشد.' }, { status: 404 });
}
// بررسی فیلدهای قابل آپدیت
const updateData: any = {};
const allowedFields = [
'name',
'city',
'district',
'address',
'ownerName',
'ownerPhone',
'supportPhone',
'source',
'stage',
'lastContactType',
'nextAction',
'nextChannel',
'temperature',
'temperatureScore',
'tempOverridden',
'loopIndex',
'salesChannels',
'deadSlots',
'painPoint',
'aspiration',
'ekipaHook',
'ownerFaq',
'objection',
'objectionStatus',
'smsTag',
'ekipaProviderId',
'salesLastMonth',
'salesTotal',
'calendarStatus',
'clubMember',
'smsLoopStatus',
'assignedToId',
];
for (const field of allowedFields) {
if (body[field] !== undefined) {
updateData[field] = body[field];
}
}
if (body.lastContactAt) {
updateData.lastContactAt = new Date(body.lastContactAt);
}
if (body.nextFollowupAt) {
updateData.nextFollowupAt = new Date(body.nextFollowupAt);
}
if (body.ekipaStartDate) {
updateData.ekipaStartDate = new Date(body.ekipaStartDate);
}
// اگر objection_status تغییر کرده و override دمایی وجود ندارد، نمره دما مجدد محاسبه شود
if (body.objectionStatus && !existing.tempOverridden && !body.tempOverridden) {
const reTemp = calculateTemperature({
stage: body.stage || existing.stage,
lastContactAt: existing.lastContactAt,
objectionStatus: body.objectionStatus,
sentiment: body.sentiment,
});
updateData.temperature = reTemp.label;
updateData.temperatureScore = reTemp.score;
}
// ثبت لاگ تغییرات مهم (Audit Log)
if (body.stage && body.stage !== existing.stage) {
await prisma.auditLog.create({
data: {
leadId: id,
field: 'stage',
oldValue: existing.stage,
newValue: body.stage,
},
});
}
// به‌روزرسانی اتاق‌ها در صورت ارسال
if (Array.isArray(body.rooms)) {
// پاکسازی و ایجاد مجدد اتاق‌ها
await prisma.room.deleteMany({ where: { leadId: id } });
await prisma.room.createMany({
data: body.rooms.map((r: string | { title: string }) => ({
leadId: id,
title: typeof r === 'string' ? r : r.title,
})),
});
}
const updated = await prisma.lead.update({
where: { id },
data: updateData,
include: {
rooms: true,
activities: { take: 5, orderBy: { createdAt: 'desc' } },
onboardingTasks: true,
},
});
return NextResponse.json({ success: true, lead: updated });
} catch (error: any) {
console.error('Error updating lead:', error);
return NextResponse.json({ success: false, error: error.message }, { status: 500 });
}
}
export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
try {
const { id } = params;
await prisma.activity.deleteMany({ where: { leadId: id } });
await prisma.onboardingTask.deleteMany({ where: { leadId: id } });
await prisma.room.deleteMany({ where: { leadId: id } });
await prisma.auditLog.deleteMany({ where: { leadId: id } });
await prisma.lead.delete({ where: { id } });
return NextResponse.json({ success: true });
} catch (error: any) {
return NextResponse.json({ success: false, error: error.message }, { status: 500 });
}
}