153 lines
4.4 KiB
TypeScript
153 lines
4.4 KiB
TypeScript
// app/api/leads/route.ts
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
import { prisma } from '@/lib/prisma';
|
|
import { calculateNextFollowup, calculateTemperature } from '@/lib/automation';
|
|
|
|
export async function GET(req: NextRequest) {
|
|
try {
|
|
const { searchParams } = new URL(req.url);
|
|
const search = searchParams.get('search') || '';
|
|
const stage = searchParams.get('stage');
|
|
const temperature = searchParams.get('temperature');
|
|
const city = searchParams.get('city');
|
|
|
|
const where: any = {};
|
|
|
|
if (search) {
|
|
where.OR = [
|
|
{ name: { contains: search } },
|
|
{ ownerName: { contains: search } },
|
|
{ ownerPhone: { contains: search } },
|
|
{ city: { contains: search } },
|
|
{ district: { contains: search } },
|
|
];
|
|
}
|
|
|
|
if (stage && stage !== 'all') {
|
|
where.stage = stage;
|
|
}
|
|
|
|
if (temperature && temperature !== 'all') {
|
|
where.temperature = temperature;
|
|
}
|
|
|
|
if (city && city !== 'all') {
|
|
where.city = city;
|
|
}
|
|
|
|
const leads = await prisma.lead.findMany({
|
|
where,
|
|
include: {
|
|
rooms: true,
|
|
activities: {
|
|
orderBy: { createdAt: 'desc' },
|
|
take: 5,
|
|
},
|
|
onboardingTasks: true,
|
|
},
|
|
orderBy: { updatedAt: 'desc' },
|
|
});
|
|
|
|
return NextResponse.json({ success: true, leads });
|
|
} catch (error: any) {
|
|
console.error('Error fetching leads:', error);
|
|
return NextResponse.json({ success: false, error: error.message }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const body = await req.json();
|
|
let {
|
|
name,
|
|
city,
|
|
district,
|
|
address,
|
|
ownerName,
|
|
ownerPhone,
|
|
supportPhone,
|
|
source = 'تماس سرد',
|
|
stage = 'ارتباط اولیه',
|
|
rooms = [],
|
|
assignedToId,
|
|
} = body;
|
|
|
|
ownerName = ownerName || body.managerName || 'مدیر مجموعه';
|
|
ownerPhone = ownerPhone || body.phone || '';
|
|
|
|
if (!name || !ownerPhone) {
|
|
return NextResponse.json({ success: false, error: 'نام مجموعه و شماره تماس مدیر الزامی است.' }, { status: 400 });
|
|
}
|
|
|
|
// نرمالسازی شماره تلفن (09xxxxxxxxx)
|
|
ownerPhone = ownerPhone.trim().replace(/^(\+98|0098)/, '0');
|
|
if (!ownerPhone.startsWith('0')) {
|
|
ownerPhone = '0' + ownerPhone;
|
|
}
|
|
|
|
// بررسی تکراری نبودن شماره
|
|
const existing = await prisma.lead.findUnique({
|
|
where: { ownerPhone },
|
|
});
|
|
if (existing) {
|
|
return NextResponse.json(
|
|
{ success: false, error: `این شماره تماس قبلاً برای مجموعه "${existing.name}" ثبت شده است.` },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const now = new Date();
|
|
const followup = calculateNextFollowup(stage, now);
|
|
const temp = calculateTemperature({ stage, sentiment: 'neutral' });
|
|
|
|
// دریافت اولین کاربر در صورت عدم انتخاب
|
|
if (!assignedToId) {
|
|
const defaultUser = await prisma.user.findFirst();
|
|
if (defaultUser) assignedToId = defaultUser.id;
|
|
}
|
|
|
|
const lead = await prisma.lead.create({
|
|
data: {
|
|
name,
|
|
city: city || 'تهران',
|
|
district: district || '',
|
|
address: address || '',
|
|
ownerName: ownerName || 'مدیر مجموعه',
|
|
ownerPhone,
|
|
supportPhone: supportPhone || '',
|
|
source,
|
|
stage,
|
|
lastContactAt: now,
|
|
lastContactType: 'تلفنی',
|
|
nextAction: followup.nextAction,
|
|
nextFollowupAt: followup.nextFollowupAt,
|
|
nextChannel: followup.nextChannel,
|
|
smsTag: followup.smsTag,
|
|
temperature: temp.label,
|
|
temperatureScore: temp.score,
|
|
assignedToId,
|
|
rooms: {
|
|
create: (Array.isArray(rooms) ? rooms : []).map((r: string) => ({ title: r })),
|
|
},
|
|
},
|
|
include: {
|
|
rooms: true,
|
|
},
|
|
});
|
|
|
|
// ثبت فعالیت اولیه
|
|
await prisma.activity.create({
|
|
data: {
|
|
leadId: lead.id,
|
|
userId: assignedToId,
|
|
type: 'stage_change',
|
|
content: `لید جدید "${lead.name}" با اقدام بعدی "${lead.nextAction}" ثبت شد.`,
|
|
},
|
|
});
|
|
|
|
return NextResponse.json({ success: true, lead });
|
|
} catch (error: any) {
|
|
console.error('Error creating lead:', error);
|
|
return NextResponse.json({ success: false, error: error.message }, { status: 500 });
|
|
}
|
|
}
|