/** * `leads export [--out ]` — dump every lead as CSV to stdout or a file. */ import { defineCommand } from "citty"; import consola from "consola"; import { writeFile } from "node:fs/promises"; const COLUMNS = [ "id", "email", "firstName", "lastName", "phone", "company", "source", "status", "utmSource", "utmMedium", "utmCampaign", "utmTerm", "utmContent", "gclid", "fbclid", "referrer", "landingPage", "score", "createdAt", "lastTouchAt", ] as const; function csvEscape(v: unknown): string { if (v === null || v === undefined) return ""; const s = String(v); if (s.includes(",") || s.includes('"') || s.includes("\n")) { return `"${s.replace(/"/g, '""')}"`; } return s; } export const leadsExportCommand = defineCommand({ meta: { name: "export", description: "Export all leads as CSV." }, args: { out: { type: "string", required: false, description: "Output file path (default stdout)." }, status: { type: "string", required: false, description: "Filter by status." }, }, async run({ args }) { const { getDbClient } = await import("@toolctrl/db/client.server"); const prisma = getDbClient(); const where = args.status ? { status: String(args.status) as never } : {}; const leads = await prisma.lead.findMany({ where, orderBy: { createdAt: "desc" } }); const header = COLUMNS.join(","); const lines = [header]; for (const l of leads) { const row = COLUMNS.map((c) => csvEscape((l as Record)[c])).join(","); lines.push(row); } const csv = `${lines.join("\n")}\n`; if (args.out) { await writeFile(String(args.out), csv, "utf8"); consola.success(`Wrote ${leads.length} leads to ${args.out}.`); } else { process.stdout.write(csv); consola.success(`Exported ${leads.length} leads.`); } }, });