// app/api/tasks/today/route.ts import { NextRequest, NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { isOverdue, OBJECTION_PLAYBOOK } from '@/lib/automation'; export async function GET(req: NextRequest) { try { const now = new Date(); // پایان امروز const endOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999); const leads = await prisma.lead.findMany({ where: { stage: { notIn: ['بایگانی / ناموفق', 'بسته شد / موفق'], }, nextFollowupAt: { lte: endOfToday, }, }, include: { rooms: true, }, orderBy: { nextFollowupAt: 'asc' }, }); // تفکیک بر اساس کانال پیگیری const smsTasks = leads .filter((l) => l.nextChannel === 'پیامک') .map((l) => ({ ...l, isOverdue: isOverdue(l.nextFollowupAt), })); const callTasks = leads .filter((l) => l.nextChannel !== 'پیامک') .map((l) => { // یافتن پاسخ پیشنهادی به اعتراض const matchedObjection = OBJECTION_PLAYBOOK.find((o) => l.objection && l.objection.includes(o.objection)); return { ...l, isOverdue: isOverdue(l.nextFollowupAt), suggestedResponse: matchedObjection ? (matchedObjection.rebuttal || (matchedObjection as any).response) : null, suggestedKeyPoint: matchedObjection ? (matchedObjection.action || (matchedObjection as any).keyPoint) : null, }; }); // استخراج وظایف آنبوردینگ مجموعه‌های فعال const onboardingPendingTasks = await prisma.onboardingTask.findMany({ where: { doneAt: null, lead: { stage: 'بسته شد / موفق', clubMember: false, }, }, include: { lead: { select: { id: true, name: true, ownerName: true, ownerPhone: true, onboardingWeek: true, ekipaStartDate: true, }, }, }, orderBy: { week: 'asc' }, }); const overdueCount = leads.filter((l) => isOverdue(l.nextFollowupAt)).length; return NextResponse.json({ success: true, summary: { totalDueToday: leads.length, overdueCount, smsCount: smsTasks.length, callCount: callTasks.length, onboardingCount: onboardingPendingTasks.length, }, smsTasks, callTasks, onboardingTasks: onboardingPendingTasks, }); } catch (error: any) { console.error('Error fetching today tasks:', error); return NextResponse.json({ success: false, error: error.message }, { status: 500 }); } }