fix: Export-Encoding und Excel-Support
- CSV: UTF-8 BOM + \r\n Zeilenenden → Umlaute in Excel korrekt - CSV: deutsche Spaltennamen, Tags als kommagetrennte Liste - Excel (.xlsx): nativer Export via xlsx-Library mit Spaltenbreiten - Export-Dropdown: CSV und Excel jeweils für aktuelle Ansicht und nur mit E-Mail Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
|
import * as XLSX from "xlsx";
|
||||||
|
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
try {
|
try {
|
||||||
@@ -11,6 +12,7 @@ export async function GET(req: NextRequest) {
|
|||||||
const priorities = searchParams.getAll("priority");
|
const priorities = searchParams.getAll("priority");
|
||||||
const hasEmail = searchParams.get("hasEmail");
|
const hasEmail = searchParams.get("hasEmail");
|
||||||
const emailOnly = searchParams.get("emailOnly") === "true";
|
const emailOnly = searchParams.get("emailOnly") === "true";
|
||||||
|
const format = searchParams.get("format") || "csv"; // "csv" | "xlsx"
|
||||||
|
|
||||||
const where: Prisma.LeadWhereInput = {};
|
const where: Prisma.LeadWhereInput = {};
|
||||||
if (search) {
|
if (search) {
|
||||||
@@ -33,57 +35,86 @@ export async function GET(req: NextRequest) {
|
|||||||
take: 10000,
|
take: 10000,
|
||||||
});
|
});
|
||||||
|
|
||||||
const columns = [
|
|
||||||
"status", "priority", "company_name", "domain", "contact_name",
|
|
||||||
"contact_title", "email", "email_confidence", "linkedin_url", "phone",
|
|
||||||
"source_tab", "source_term", "tags", "country", "headcount", "industry",
|
|
||||||
"notes", "captured_at", "contacted_at", "serp_rank", "serp_url",
|
|
||||||
"serp_title", "serp_snippet", "lead_id",
|
|
||||||
];
|
|
||||||
|
|
||||||
const rows = leads.map(l => ({
|
const rows = leads.map(l => ({
|
||||||
status: l.status,
|
"Status": l.status,
|
||||||
priority: l.priority,
|
"Priorität": l.priority,
|
||||||
company_name: l.companyName || "",
|
"Unternehmen": l.companyName || "",
|
||||||
domain: l.domain || "",
|
"Domain": l.domain || "",
|
||||||
contact_name: l.contactName || "",
|
"Kontaktname": l.contactName || "",
|
||||||
contact_title: l.contactTitle || "",
|
"Jobtitel": l.contactTitle || "",
|
||||||
email: l.email || "",
|
"E-Mail": l.email || "",
|
||||||
email_confidence: l.emailConfidence != null ? Math.round(l.emailConfidence * 100) + "%" : "",
|
"E-Mail Konfidenz": l.emailConfidence != null ? Math.round(l.emailConfidence * 100) + "%" : "",
|
||||||
linkedin_url: l.linkedinUrl || "",
|
"LinkedIn": l.linkedinUrl || "",
|
||||||
phone: l.phone || "",
|
"Telefon": l.phone || "",
|
||||||
source_tab: l.sourceTab,
|
"Quelle": l.sourceTab,
|
||||||
source_term: l.sourceTerm || "",
|
"Suchbegriff": l.sourceTerm || "",
|
||||||
tags: l.tags || "",
|
"Tags": l.tags ? JSON.parse(l.tags).join(", ") : "",
|
||||||
country: l.country || "",
|
"Land": l.country || "",
|
||||||
headcount: l.headcount || "",
|
"Mitarbeiter": l.headcount || "",
|
||||||
industry: l.industry || "",
|
"Branche": l.industry || "",
|
||||||
notes: l.notes || "",
|
"Notizen": l.notes || "",
|
||||||
captured_at: l.capturedAt.toISOString(),
|
"Erfasst am": new Date(l.capturedAt).toLocaleString("de-DE"),
|
||||||
contacted_at: l.contactedAt?.toISOString() || "",
|
"Kontaktiert am": l.contactedAt ? new Date(l.contactedAt).toLocaleString("de-DE") : "",
|
||||||
serp_rank: l.serpRank?.toString() || "",
|
"SERP Rang": l.serpRank?.toString() || "",
|
||||||
serp_url: l.serpUrl || "",
|
"SERP URL": l.serpUrl || "",
|
||||||
serp_title: l.serpTitle || "",
|
"SERP Titel": l.serpTitle || "",
|
||||||
serp_snippet: l.serpSnippet || "",
|
"SERP Snippet": l.serpSnippet || "",
|
||||||
lead_id: l.id,
|
"Lead ID": l.id,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const csv = [
|
const filename = `leadflow-vault-${new Date().toISOString().split("T")[0]}`;
|
||||||
columns.join(","),
|
|
||||||
...rows.map(r =>
|
if (format === "xlsx") {
|
||||||
columns.map(c => {
|
const ws = XLSX.utils.json_to_sheet(rows);
|
||||||
const v = String(r[c as keyof typeof r] || "");
|
|
||||||
return v.includes(",") || v.includes('"') || v.includes("\n")
|
// 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.replace(/"/g, '""')}"`
|
||||||
: v;
|
: v;
|
||||||
}).join(",")
|
|
||||||
),
|
const csv =
|
||||||
].join("\n");
|
"\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, {
|
return new NextResponse(csv, {
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "text/csv; charset=utf-8",
|
"Content-Type": "text/csv; charset=utf-8",
|
||||||
"Content-Disposition": `attachment; filename="leadflow-vault-${new Date().toISOString().split("T")[0]}.csv"`,
|
"Content-Disposition": `attachment; filename="${filename}.csv"`,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -520,8 +520,8 @@ export default function LeadVaultPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function exportCSV(emailOnly = false) {
|
function exportFile(format: "csv" | "xlsx", emailOnly = false) {
|
||||||
const params = new URLSearchParams({ search: debouncedSearch, sortBy, sortDir });
|
const params = new URLSearchParams({ search: debouncedSearch, sortBy, sortDir, format });
|
||||||
filterStatus.forEach(s => params.append("status", s));
|
filterStatus.forEach(s => params.append("status", s));
|
||||||
filterSource.forEach(s => params.append("sourceTab", s));
|
filterSource.forEach(s => params.append("sourceTab", s));
|
||||||
if (filterHasEmail) params.set("hasEmail", filterHasEmail);
|
if (filterHasEmail) params.set("hasEmail", filterHasEmail);
|
||||||
@@ -560,9 +560,10 @@ export default function LeadVaultPage() {
|
|||||||
</button>
|
</button>
|
||||||
<div className="absolute right-0 top-9 hidden group-hover:block z-50 bg-[#1a1a28] border border-[#2e2e3e] rounded-lg shadow-xl p-1 min-w-[220px]">
|
<div className="absolute right-0 top-9 hidden group-hover:block z-50 bg-[#1a1a28] border border-[#2e2e3e] rounded-lg shadow-xl p-1 min-w-[220px]">
|
||||||
{[
|
{[
|
||||||
["Aktuelle Ansicht (CSV)", () => exportCSV()],
|
["Aktuelle Ansicht (CSV)", () => exportFile("csv")],
|
||||||
["Alle Leads (CSV)", () => exportCSV()],
|
["Aktuelle Ansicht (Excel)", () => exportFile("xlsx")],
|
||||||
["Nur mit E-Mail (CSV)", () => exportCSV(true)],
|
["Nur mit E-Mail (CSV)", () => exportFile("csv", true)],
|
||||||
|
["Nur mit E-Mail (Excel)", () => exportFile("xlsx", true)],
|
||||||
].map(([label, fn]) => (
|
].map(([label, fn]) => (
|
||||||
<button key={label as string} onClick={fn as () => void}
|
<button key={label as string} onClick={fn as () => void}
|
||||||
className="w-full text-left px-3 py-2 text-sm text-gray-300 hover:bg-[#2e2e3e] rounded">
|
className="w-full text-left px-3 py-2 text-sm text-gray-300 hover:bg-[#2e2e3e] rounded">
|
||||||
|
|||||||
Reference in New Issue
Block a user