62 lines
1.6 KiB
TypeScript
62 lines
1.6 KiB
TypeScript
/**
|
|
* Pure CSV serializer for the admin marketing-leads inbox export
|
|
* (Phase 05 #78, admin-UI CSV download).
|
|
*
|
|
* Column ordering and CSV-escaping rules mirror `packages/cli/src/commands/
|
|
* leads/export.ts` so the admin-UI download and the `toolctrl-cli leads
|
|
* export` operator-side dump are byte-compatible.
|
|
*/
|
|
|
|
export const LEAD_CSV_COLUMNS = [
|
|
"id",
|
|
"email",
|
|
"firstName",
|
|
"lastName",
|
|
"phone",
|
|
"company",
|
|
"source",
|
|
"status",
|
|
"utmSource",
|
|
"utmMedium",
|
|
"utmCampaign",
|
|
"utmTerm",
|
|
"utmContent",
|
|
"gclid",
|
|
"fbclid",
|
|
"referrer",
|
|
"landingPage",
|
|
"score",
|
|
"createdAt",
|
|
"lastTouchAt",
|
|
] as const;
|
|
|
|
export type LeadCsvColumn = (typeof LEAD_CSV_COLUMNS)[number];
|
|
|
|
export type LeadCsvRow = {
|
|
readonly [K in LeadCsvColumn]?: unknown;
|
|
};
|
|
|
|
export function escapeCsvValue(value: unknown): string {
|
|
if (value === null || value === undefined) return "";
|
|
const raw = value instanceof Date ? value.toISOString() : String(value);
|
|
if (/[",\n\r]/.test(raw)) {
|
|
return `"${raw.replace(/"/g, '""')}"`;
|
|
}
|
|
return raw;
|
|
}
|
|
|
|
export function serializeLeadsCsv(rows: ReadonlyArray<LeadCsvRow>): string {
|
|
const lines: string[] = [LEAD_CSV_COLUMNS.join(",")];
|
|
for (const row of rows) {
|
|
lines.push(LEAD_CSV_COLUMNS.map((col) => escapeCsvValue(row[col])).join(","));
|
|
}
|
|
return `${lines.join("\n")}\n`;
|
|
}
|
|
|
|
export function leadsCsvFilename(date: Date = new Date()): string {
|
|
const yyyy = date.getUTCFullYear();
|
|
const mm = String(date.getUTCMonth() + 1).padStart(2, "0");
|
|
const dd = String(date.getUTCDate()).padStart(2, "0");
|
|
return `marketing-leads-${yyyy}${mm}${dd}.csv`;
|
|
}
|