feat: LeadVault - zentrale Lead-Datenbank mit CRM-Funktionen

- Prisma-Schema: Lead + LeadEvent Modelle (Migration 20260320)
- lib/services/leadVault.ts: sinkLeadsToVault mit Deduplizierung
- Auto-Sync: alle 4 Pipelines schreiben Leads in LeadVault
- GET /api/leads: Filter, Sortierung, Pagination (Server-side)
- PATCH/DELETE /api/leads/[id]: Status, Priorität, Tags, Notizen
- POST /api/leads/bulk: Bulk-Aktionen für mehrere Leads
- GET /api/leads/stats: Statistiken + 7-Tage-Sparkline
- POST /api/leads/quick-serp: SERP-Capture ohne Enrichment
- GET /api/leads/export: CSV-Export mit allen Feldern
- app/leadvault/page.tsx: vollständige UI mit Stats, Quick SERP,
  Filter-Leiste, sortierbare Tabelle, Bulk-Aktionen, Side Panel
- Sidebar: LeadVault-Eintrag mit Live-Badge (neue Leads)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Timo Uttenweiler
2026-03-20 17:33:12 +01:00
parent 6711633a5d
commit 042fbeb672
16 changed files with 1800 additions and 5 deletions

View File

@@ -0,0 +1,70 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params;
const body = await req.json() as Record<string, unknown>;
const oldLead = await prisma.lead.findUnique({ where: { id } });
if (!oldLead) return NextResponse.json({ error: "Not found" }, { status: 404 });
const allowedFields = [
"status", "priority", "notes", "tags", "country", "headcount",
"industry", "contactedAt", "companyName", "contactName", "contactTitle",
"email", "phone", "linkedinUrl", "domain",
];
const data: Record<string, unknown> = {};
for (const field of allowedFields) {
if (field in body) data[field] = body[field];
}
const updated = await prisma.lead.update({ where: { id }, data });
// Track status change events
if (body.status && body.status !== oldLead.status) {
await prisma.leadEvent.create({
data: {
leadId: id,
event: `Status geändert zu "${body.status}"`,
},
});
// Auto-set contactedAt when marking as contacted
if (body.status === "contacted" && !oldLead.contactedAt) {
await prisma.lead.update({ where: { id }, data: { contactedAt: new Date() } });
}
}
return NextResponse.json(updated);
} catch (err) {
console.error("PATCH /api/leads/[id] error:", err);
return NextResponse.json({ error: "Update failed" }, { status: 500 });
}
}
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params;
await prisma.lead.delete({ where: { id } });
return NextResponse.json({ deleted: true });
} catch (err) {
console.error("DELETE /api/leads/[id] error:", err);
return NextResponse.json({ error: "Delete failed" }, { status: 500 });
}
}
export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params;
const lead = await prisma.lead.findUnique({
where: { id },
include: { events: { orderBy: { at: "asc" } } },
});
if (!lead) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json(lead);
} catch (err) {
return NextResponse.json({ error: "Fetch failed" }, { status: 500 });
}
}

View File

@@ -0,0 +1,64 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
export async function POST(req: NextRequest) {
try {
const body = await req.json() as {
ids: string[];
action: "status" | "priority" | "tag" | "delete";
value: string;
};
const { ids, action, value } = body;
if (!ids?.length) return NextResponse.json({ error: "No IDs provided" }, { status: 400 });
if (action === "delete") {
const { count } = await prisma.lead.deleteMany({ where: { id: { in: ids } } });
return NextResponse.json({ updated: count });
}
if (action === "status") {
const { count } = await prisma.lead.updateMany({
where: { id: { in: ids } },
data: { status: value },
});
// Create events for status change
for (const id of ids) {
await prisma.leadEvent.create({
data: { leadId: id, event: `Status geändert zu "${value}" (Bulk)` },
}).catch(() => {}); // ignore if lead was deleted
}
return NextResponse.json({ updated: count });
}
if (action === "priority") {
const { count } = await prisma.lead.updateMany({
where: { id: { in: ids } },
data: { priority: value },
});
return NextResponse.json({ updated: count });
}
if (action === "tag") {
// Add tag to each lead's tags JSON array
const leads = await prisma.lead.findMany({ where: { id: { in: ids } }, select: { id: true, tags: true } });
let count = 0;
for (const lead of leads) {
const existing: string[] = JSON.parse(lead.tags || "[]");
if (!existing.includes(value)) {
await prisma.lead.update({
where: { id: lead.id },
data: { tags: JSON.stringify([...existing, value]) },
});
count++;
}
}
return NextResponse.json({ updated: count });
}
return NextResponse.json({ error: "Unknown action" }, { status: 400 });
} catch (err) {
console.error("POST /api/leads/bulk error:", err);
return NextResponse.json({ error: "Bulk action failed" }, { status: 500 });
}
}

View File

@@ -0,0 +1,93 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { Prisma } from "@prisma/client";
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 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 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 => ({
status: l.status,
priority: l.priority,
company_name: l.companyName || "",
domain: l.domain || "",
contact_name: l.contactName || "",
contact_title: l.contactTitle || "",
email: l.email || "",
email_confidence: l.emailConfidence != null ? Math.round(l.emailConfidence * 100) + "%" : "",
linkedin_url: l.linkedinUrl || "",
phone: l.phone || "",
source_tab: l.sourceTab,
source_term: l.sourceTerm || "",
tags: l.tags || "",
country: l.country || "",
headcount: l.headcount || "",
industry: l.industry || "",
notes: l.notes || "",
captured_at: l.capturedAt.toISOString(),
contacted_at: l.contactedAt?.toISOString() || "",
serp_rank: l.serpRank?.toString() || "",
serp_url: l.serpUrl || "",
serp_title: l.serpTitle || "",
serp_snippet: l.serpSnippet || "",
lead_id: l.id,
}));
const csv = [
columns.join(","),
...rows.map(r =>
columns.map(c => {
const v = String(r[c as keyof typeof r] || "");
return v.includes(",") || v.includes('"') || v.includes("\n")
? `"${v.replace(/"/g, '""')}"`
: v;
}).join(",")
),
].join("\n");
return new NextResponse(csv, {
headers: {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": `attachment; filename="leadflow-vault-${new Date().toISOString().split("T")[0]}.csv"`,
},
});
} catch (err) {
console.error("GET /api/leads/export error:", err);
return NextResponse.json({ error: "Export failed" }, { status: 500 });
}
}

View File

@@ -0,0 +1,71 @@
import { NextRequest, NextResponse } from "next/server";
import { getApiKey } from "@/lib/utils/apiKey";
import { runGoogleSerpScraper, pollRunStatus, fetchDatasetItems } from "@/lib/services/apify";
import { isSocialOrDirectory } from "@/lib/utils/domains";
import { sinkLeadsToVault } from "@/lib/services/leadVault";
function sleep(ms: number) { return new Promise(r => setTimeout(r, ms)); }
export async function POST(req: NextRequest) {
try {
const body = await req.json() as {
query: string;
count: number;
country: string;
language: string;
filterSocial: boolean;
};
const { query, count, country, language, filterSocial } = body;
if (!query?.trim()) return NextResponse.json({ error: "Kein Suchbegriff" }, { status: 400 });
const apifyToken = await getApiKey("apify");
if (!apifyToken) return NextResponse.json({ error: "Apify API-Key fehlt" }, { status: 400 });
const maxPages = Math.ceil(count / 10);
const runId = await runGoogleSerpScraper(query, maxPages, country, language, apifyToken);
let runStatus = "";
let datasetId = "";
while (runStatus !== "SUCCEEDED" && runStatus !== "FAILED" && runStatus !== "ABORTED") {
await sleep(3000);
const result = await pollRunStatus(runId, apifyToken);
runStatus = result.status;
datasetId = result.defaultDatasetId;
}
if (runStatus !== "SUCCEEDED") throw new Error(`Apify run ${runStatus}`);
let serpResults = await fetchDatasetItems(datasetId, apifyToken);
if (filterSocial) {
serpResults = serpResults.filter(r => !isSocialOrDirectory(r.domain));
}
// Deduplicate by domain
const seen = new Set<string>();
const unique = serpResults.filter(r => {
if (!r.domain || seen.has(r.domain)) return false;
seen.add(r.domain);
return true;
}).slice(0, count);
const stats = await sinkLeadsToVault(
unique.map((r, i) => ({
domain: r.domain,
companyName: r.title || null,
serpTitle: r.title || null,
serpSnippet: r.description || null,
serpRank: r.position ?? i + 1,
serpUrl: r.url || null,
})),
"quick-serp",
query,
);
return NextResponse.json(stats);
} catch (err) {
console.error("POST /api/leads/quick-serp error:", err);
return NextResponse.json({ error: err instanceof Error ? err.message : "Fehler" }, { status: 500 });
}
}

87
app/api/leads/route.ts Normal file
View File

@@ -0,0 +1,87 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { Prisma } from "@prisma/client";
export async function GET(req: NextRequest) {
try {
const { searchParams } = new URL(req.url);
const page = Math.max(1, Number(searchParams.get("page") || 1));
const perPage = Math.min(100, Math.max(10, Number(searchParams.get("perPage") || 50)));
const search = searchParams.get("search") || "";
const sortBy = searchParams.get("sortBy") || "capturedAt";
const sortDir = (searchParams.get("sortDir") || "desc") as "asc" | "desc";
const hasEmail = searchParams.get("hasEmail"); // "yes" | "no" | null
const capturedFrom = searchParams.get("capturedFrom");
const capturedTo = searchParams.get("capturedTo");
const statuses = searchParams.getAll("status");
const sourceTabs = searchParams.getAll("sourceTab");
const priorities = searchParams.getAll("priority");
const tags = searchParams.getAll("tags");
const searchTerm = searchParams.get("searchTerm") || "";
const where: Prisma.LeadWhereInput = {};
if (search) {
where.OR = [
{ domain: { contains: search } },
{ companyName: { contains: search } },
{ contactName: { contains: search } },
{ email: { contains: search } },
{ notes: { 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") where.email = { not: null };
else if (hasEmail === "no") where.email = null;
if (capturedFrom || capturedTo) {
where.capturedAt = {};
if (capturedFrom) where.capturedAt.gte = new Date(capturedFrom);
if (capturedTo) where.capturedAt.lte = new Date(capturedTo);
}
if (searchTerm) {
where.sourceTerm = { contains: searchTerm };
}
if (tags.length > 0) {
// SQLite JSON contains — search for each tag in the JSON string
where.AND = tags.map(tag => ({
tags: { contains: tag },
}));
}
const validSortFields: Record<string, boolean> = {
capturedAt: true, status: true, priority: true, companyName: true,
domain: true, email: true, contactName: true,
};
const orderByField = validSortFields[sortBy] ? sortBy : "capturedAt";
const [total, leads] = await Promise.all([
prisma.lead.count({ where }),
prisma.lead.findMany({
where,
orderBy: { [orderByField]: sortDir },
skip: (page - 1) * perPage,
take: perPage,
}),
]);
return NextResponse.json({
leads,
total,
page,
pages: Math.ceil(total / perPage),
perPage,
});
} catch (err) {
console.error("GET /api/leads error:", err);
return NextResponse.json({ error: "Failed to fetch leads" }, { status: 500 });
}
}

View File

@@ -0,0 +1,42 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
export async function GET() {
try {
const [total, newLeads, contacted, withEmail] = await Promise.all([
prisma.lead.count(),
prisma.lead.count({ where: { status: "new" } }),
prisma.lead.count({ where: { status: { in: ["contacted", "in_progress"] } } }),
prisma.lead.count({ where: { email: { not: null } } }),
]);
// Daily counts for last 7 days
const sevenDaysAgo = new Date();
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 6);
sevenDaysAgo.setHours(0, 0, 0, 0);
const recentLeads = await prisma.lead.findMany({
where: { capturedAt: { gte: sevenDaysAgo } },
select: { capturedAt: true },
});
// Build daily counts map
const dailyMap: Record<string, number> = {};
for (let i = 0; i < 7; i++) {
const d = new Date(sevenDaysAgo);
d.setDate(d.getDate() + i);
dailyMap[d.toISOString().split("T")[0]] = 0;
}
for (const lead of recentLeads) {
const key = lead.capturedAt.toISOString().split("T")[0];
if (key in dailyMap) dailyMap[key]++;
}
const dailyCounts = Object.entries(dailyMap).map(([date, count]) => ({ date, count }));
return NextResponse.json({ total, new: newLeads, contacted, withEmail, dailyCounts });
} catch (err) {
console.error("GET /api/leads/stats error:", err);
return NextResponse.json({ error: "Failed" }, { status: 500 });
}
}