// app/api/dashboard/stats/route.ts import { NextRequest, NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { PIPELINE_STAGES, isOverdue } from '@/lib/automation'; export async function GET(req: NextRequest) { try { const leads = await prisma.lead.findMany({ include: { rooms: true, }, }); const totalLeads = leads.length; const warmLeads = leads.filter((l) => l.temperature === 'گرم').length; const neutralLeads = leads.filter((l) => l.temperature === 'خنثی').length; const coldLeads = leads.filter((l) => l.temperature === 'سرد').length; const closedWonLeads = leads.filter((l) => l.stage === 'بسته شد / موفق'); const closedLostLeads = leads.filter((l) => l.stage === 'بایگانی / ناموفق'); const conversionRate = totalLeads > 0 ? Math.round((closedWonLeads.length / totalLeads) * 100) : 0; const now = new Date(); const endOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999); const dueTodayLeads = leads.filter( (l) => l.nextFollowupAt && l.nextFollowupAt <= endOfToday && !['بایگانی / ناموفق', 'بسته شد / موفق'].includes(l.stage) ); const overdueLeads = leads.filter( (l) => l.nextFollowupAt && isOverdue(l.nextFollowupAt) && !['بایگانی / ناموفق', 'بسته شد / موفق'].includes(l.stage) ); // توزیع مراحل پایپ‌لاین (قیف فروش) const funnel = PIPELINE_STAGES.map((s: any) => { const stageName = typeof s === 'string' ? s : s.stage; const count = leads.filter((l) => l.stage === stageName).length; const percentage = totalLeads > 0 ? Math.round((count / totalLeads) * 100) : 0; return { stage: stageName, count, percentage }; }); // اعتراضات پرتکرار const objectionCounts: { [key: string]: number } = {}; leads.forEach((l) => { if (l.objection && l.objection !== 'بدون اعتراض') { objectionCounts[l.objection] = (objectionCounts[l.objection] || 0) + 1; } }); const topObjections = Object.entries(objectionCounts) .map(([name, count]) => ({ name, count })) .sort((a, b) => b.count - a.count); // محاسبه فروش ماه اخیر و فروش کل مجموعه‌های موفق const totalSalesLastMonth = closedWonLeads.reduce((acc, l) => acc + (l.salesLastMonth || 0), 0); const totalSalesAll = closedWonLeads.reduce((acc, l) => acc + (l.salesTotal || 0), 0); // فعالیت‌های اخیر const recentActivities = await prisma.activity.findMany({ take: 8, orderBy: { createdAt: 'desc' }, include: { lead: { select: { id: true, name: true } }, }, }); return NextResponse.json({ success: true, stats: { totalLeads, warmLeads, neutralLeads, coldLeads, closedWonCount: closedWonLeads.length, closedLostCount: closedLostLeads.length, conversionRate, dueTodayCount: dueTodayLeads.length, overdueCount: overdueLeads.length, totalSalesLastMonth, totalSalesAll, }, funnel, topObjections, recentActivities, }); } catch (error: any) { console.error('Error fetching dashboard stats:', error); return NextResponse.json({ success: false, error: error.message }, { status: 500 }); } }