Files
lead-scraper/app/api/leads/export/route.ts
Timo Uttenweiler 54e0d22f9c mein-solar: full feature set
- Schema: companyType, topics, salesScore, salesReason, offerPackage, approved, approvedAt, SearchHistory table
- /api/search-history: GET (by mode) + POST (save query)
- /api/ai-search: stadtwerke/industrie/custom prompts with history dedup
- /api/enrich-leads: website scraping + GPT-4o-mini enrichment (fire-and-forget after each job)
- /api/generate-email: personalized outreach via GPT-4o
- Suche page: 3 mode tabs (Stadtwerke/Industrie/Freie Suche), Alle-Bundesländer queue button, AiSearchModal gets searchMode + history
- Leadspeicher: Bewertung dots column, Paket badge column, Freigeben toggle button, email generator in SidePanel, approved-only export option
- Leads API: approvedOnly + companyType filters, new fields in PATCH

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 21:06:07 +02:00

128 lines
4.6 KiB
TypeScript

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 } },
];
}
const approvedOnly = searchParams.get("approvedOnly") === "true";
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;
if (approvedOnly) where.approved = true;
const leads = await prisma.lead.findMany({
where,
orderBy: { capturedAt: "desc" },
take: 10000,
});
const rows = leads.map(l => ({
"Unternehmen": l.companyName || "",
"Domain": l.domain || "",
"Kontaktname": l.contactName || "",
"Position": l.contactTitle || "",
"E-Mail": l.email || "",
"Telefon": l.phone || "",
"Adresse": l.address || "",
"LinkedIn": l.linkedinUrl || "",
"Branche": l.industry || "",
"Suchbegriff": l.sourceTerm || "",
"Tags": l.tags ? (JSON.parse(l.tags) as string[]).join(", ") : "",
"Unternehmenstyp": l.companyType || "",
"Themen": l.topics ? (JSON.parse(l.topics) as string[]).join(", ") : "",
"Vertriebsrelevanz": l.salesScore?.toString() || "",
"Begründung": l.salesReason || "",
"Angebotspaket": l.offerPackage || "",
"Freigegeben": l.approved ? "Ja" : "Nein",
"Erfasst am": new Date(l.capturedAt).toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", year: "numeric" }),
}));
const filename = `onyva-leads-vault-${new Date().toISOString().split("T")[0]}`;
if (format === "xlsx") {
const ws = XLSX.utils.json_to_sheet(rows);
// Column widths (one per column)
ws["!cols"] = [
{ wch: 30 }, // Unternehmen
{ wch: 28 }, // Domain
{ wch: 24 }, // Kontaktname
{ wch: 24 }, // Position
{ wch: 34 }, // E-Mail
{ wch: 18 }, // Telefon
{ wch: 36 }, // Adresse
{ wch: 36 }, // LinkedIn
{ wch: 22 }, // Branche
{ wch: 30 }, // Suchbegriff
{ wch: 28 }, // Tags
{ wch: 14 }, // Erfasst am
];
// Freeze header row
ws["!freeze"] = { xSplit: 0, ySplit: 1 };
// Autofilter across all columns
const colCount = Object.keys(rows[0] ?? {}).length || 17;
const lastCol = String.fromCharCode(64 + colCount);
ws["!autofilter"] = { ref: `A1:${lastCol}1` };
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[];
return new NextResponse(new Uint8Array(arr).buffer, {
headers: {
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Content-Disposition": `attachment; filename="${filename}.xlsx"`,
},
});
}
// CSV — UTF-8 BOM so Excel opens it correctly
const colKeys = Object.keys(rows[0] ?? {});
const escape = (v: string) =>
v.includes(",") || v.includes('"') || v.includes("\n") || v.includes("\r")
? `"${v.replace(/"/g, '""')}"`
: v;
const csv =
"\uFEFF" +
[
colKeys.map(escape).join(","),
...rows.map(r => colKeys.map(h => escape(String(r[h as keyof typeof r] ?? ""))).join(",")),
].join("\r\n");
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 });
}
}