Repository navigation
Expand file tree
/
Copy pathreportDownloads.ts
More file actions
66 lines (56 loc) · 2.24 KB
/
Copy pathreportDownloads.ts
File metadata and controls
66 lines (56 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import type { DatasetName, PeriodScope, ReportId, RunPeriodRole } from "../domain/types";
import {
buildTagHealthRows,
buildTagHealthRowsFromLiveRecords,
TAG_HEALTH_CSV_HEADERS,
} from "../reports/tagReport";
import { downloadTextFile, recordsToCsv } from "./downloads";
interface ReportCsvDownload {
fileName: string;
contents: string;
mimeType: string;
}
export interface ReportCsvDownloadOutput {
reportId: ReportId;
datasetName: DatasetName;
records: Record<string, unknown>[];
loadedAt: string;
source: "live-api" | "upload";
periodRole?: RunPeriodRole;
currentScope?: PeriodScope;
comparisonScope?: PeriodScope;
}
export function buildReportCsvDownload(output: ReportCsvDownloadOutput): ReportCsvDownload {
const periodRole = output.periodRole ?? "current";
const isTagHealthOutput = output.reportId === "tag-report" && output.datasetName === "tags";
const rows = isTagHealthOutput ? buildTagHealthRowsForOutput(output) : output.records;
return {
fileName: `${buildReportFileStem(output.reportId, output.datasetName, periodRole, output.loadedAt)}.csv`,
contents:
isTagHealthOutput && rows.length === 0
? TAG_HEALTH_CSV_HEADERS.join(",")
: recordsToCsv(rows.map((row) => ({ ...row }))),
mimeType: "text/csv;charset=utf-8",
};
}
export function downloadReportCsv(output: ReportCsvDownloadOutput) {
const download = buildReportCsvDownload(output);
downloadTextFile(download.fileName, download.contents, download.mimeType);
}
function buildTagHealthRowsForOutput(output: ReportCsvDownloadOutput) {
return output.source === "live-api" && output.records.some((record) => typeof record.datasetName === "string")
? buildTagHealthRowsFromLiveRecords(output.records)
: buildTagHealthRows(output.records);
}
function buildReportFileStem(
reportId: ReportId,
datasetName: DatasetName,
periodRole: RunPeriodRole,
loadedAt: string,
): string {
const datasetPart = reportId === "tag-report" && datasetName === "tags" ? "tag-health" : datasetName;
return [reportId, datasetPart, periodRole, loadedAt.slice(0, 10)].map(sanitizeFileNamePart).join("-");
}
function sanitizeFileNamePart(value: string): string {
return value.trim().replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-|-$/g, "") || "report";
}