// app/api/leads/[id]/advance/route.ts import { NextRequest, NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { advanceStage, DEFAULT_ONBOARDING_TASKS } from '@/lib/automation'; export async function POST(req: NextRequest, { params }: { params: { id: string } }) { try { const { id } = params; const body = await req.json().catch(() => ({})); const { note, userId } = body; const lead = await prisma.lead.findUnique({ where: { id }, include: { onboardingTasks: true }, }); if (!lead) { return NextResponse.json({ success: false, error: 'لید یافت نشد.' }, { status: 404 }); } const { nextStage, followup, temperature, nextLoopIndex } = advanceStage({ stage: lead.stage, loopIndex: lead.loopIndex, objectionStatus: lead.objectionStatus, tempOverridden: lead.tempOverridden, }); const now = new Date(); const updateData: any = { stage: nextStage, lastContactAt: now, lastContactType: lead.nextChannel === 'پیامک' ? 'پیامک' : 'تلفنی', nextAction: followup.nextAction, nextFollowupAt: followup.nextFollowupAt, nextChannel: followup.nextChannel, smsTag: followup.smsTag, loopIndex: nextLoopIndex, updatedAt: now, }; if (!lead.tempOverridden) { updateData.temperature = temperature.label; updateData.temperatureScore = temperature.score; } // اگر مرحله به "بسته شد / موفق" تغییر یافت و تاریخ شروع ثبت نشده if (nextStage === 'بسته شد / موفق' && !lead.ekipaStartDate) { updateData.ekipaStartDate = now; updateData.onboardingWeek = 1; // ساخت وظایف آنبوردینگ در صورت نبود if (lead.onboardingTasks.length === 0) { for (const t of DEFAULT_ONBOARDING_TASKS) { await prisma.onboardingTask.create({ data: { leadId: lead.id, week: t.week, title: t.title, }, }); } } } // ثبت در تاریخچه تغییرات await prisma.auditLog.create({ data: { leadId: id, userId: userId || lead.assignedToId, field: 'stage', oldValue: lead.stage, newValue: nextStage, }, }); // ثبت فعالیت await prisma.activity.create({ data: { leadId: id, userId: userId || lead.assignedToId, type: 'stage_change', content: `مرحله تغییر یافت: از "${lead.stage}" به "${nextStage}". اقدام بعدی: "${followup.nextAction}"${note ? ` | یادداشت: ${note}` : ''}`, }, }); 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, message: `مرحله به "${nextStage}" با موفقیت تغییر کرد.` }); } catch (error: any) { console.error('Error advancing stage:', error); return NextResponse.json({ success: false, error: error.message }, { status: 500 }); } }