import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/db"; import { Prisma } from "@prisma/client"; import * as XLSX from "xlsx"; export async function GET(req: NextRequest) { try { const { searchParams } = new URL(req.url); const search = searchParams.get("search") || ""; const statuses = searchParams.getAll("status"); const sourceTabs = searchParams.getAll("sourceTab"); const priorities = searchParams.getAll("priority"); const hasEmail = searchParams.get("hasEmail"); const emailOnly = searchParams.get("emailOnly") === "true"; const format = searchParams.get("format") || "csv"; // "csv" | "xlsx" const where: Prisma.LeadWhereInput = {}; if (search) { where.OR = [ { domain: { contains: search } }, { companyName: { contains: search } }, { contactName: { contains: search } }, { email: { contains: search } }, ]; } if (statuses.length > 0) where.status = { in: statuses }; if (sourceTabs.length > 0) where.sourceTab = { in: sourceTabs }; if (priorities.length > 0) where.priority = { in: priorities }; if (hasEmail === "yes" || emailOnly) where.email = { not: null }; else if (hasEmail === "no") where.email = null; const leads = await prisma.lead.findMany({ where, orderBy: { capturedAt: "desc" }, take: 10000, }); const rows = leads.map(l => ({ "Status": l.status, "Priorität": l.priority, "Unternehmen": l.companyName || "", "Domain": l.domain || "", "Kontaktname": l.contactName || "", "Jobtitel": l.contactTitle || "", "E-Mail": l.email || "", "E-Mail Konfidenz": l.emailConfidence != null ? Math.round(l.emailConfidence * 100) + "%" : "", "LinkedIn": l.linkedinUrl || "", "Telefon": l.phone || "", "Quelle": l.sourceTab, "Suchbegriff": l.sourceTerm || "", "Tags": l.tags ? JSON.parse(l.tags).join(", ") : "", "Land": l.country || "", "Mitarbeiter": l.headcount || "", "Branche": l.industry || "", "Notizen": l.notes || "", "Erfasst am": new Date(l.capturedAt).toLocaleString("de-DE"), "Kontaktiert am": l.contactedAt ? new Date(l.contactedAt).toLocaleString("de-DE") : "", "SERP Rang": l.serpRank?.toString() || "", "SERP URL": l.serpUrl || "", "SERP Titel": l.serpTitle || "", "SERP Snippet": l.serpSnippet || "", "Lead ID": l.id, })); const filename = `leadflow-vault-${new Date().toISOString().split("T")[0]}`; if (format === "xlsx") { const ws = XLSX.utils.json_to_sheet(rows); // Column widths ws["!cols"] = [ { wch: 14 }, { wch: 10 }, { wch: 28 }, { wch: 28 }, { wch: 22 }, { wch: 22 }, { wch: 32 }, { wch: 14 }, { wch: 30 }, { wch: 16 }, { wch: 12 }, { wch: 24 }, { wch: 20 }, { wch: 8 }, { wch: 10 }, { wch: 16 }, { wch: 30 }, { wch: 18 }, { wch: 18 }, { wch: 8 }, { wch: 40 }, { wch: 30 }, { wch: 40 }, { wch: 28 }, ]; const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, "LeadVault"); const arr = XLSX.write(wb, { type: "array", bookType: "xlsx" }) as number[]; const buf = new Uint8Array(arr).buffer; return new NextResponse(buf, { headers: { "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Content-Disposition": `attachment; filename="${filename}.xlsx"`, }, }); } // CSV — UTF-8 BOM so Excel opens it correctly + \r\n line endings const headers = Object.keys(rows[0] ?? { "Status": "", "Priorität": "", "Unternehmen": "", "Domain": "", "Kontaktname": "", "Jobtitel": "", "E-Mail": "", "E-Mail Konfidenz": "", "LinkedIn": "", "Telefon": "", "Quelle": "", "Suchbegriff": "", "Tags": "", "Land": "", "Mitarbeiter": "", "Branche": "", "Notizen": "", "Erfasst am": "", "Kontaktiert am": "", "SERP Rang": "", "SERP URL": "", "SERP Titel": "", "SERP Snippet": "", "Lead ID": "", }); const escape = (v: string) => v.includes(",") || v.includes('"') || v.includes("\n") || v.includes("\r") ? `"${v.replace(/"/g, '""')}"` : v; const csv = "\uFEFF" + // UTF-8 BOM — tells Excel to use UTF-8 [ headers.map(escape).join(","), ...rows.map(r => headers.map(h => escape(String(r[h as keyof typeof r] ?? ""))).join(",")), ].join("\r\n"); // Windows line endings for Excel return new NextResponse(csv, { headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": `attachment; filename="${filename}.csv"`, }, }); } catch (err) { console.error("GET /api/leads/export error:", err); return NextResponse.json({ error: "Export failed" }, { status: 500 }); } }