-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathcsv.ts
More file actions
134 lines (121 loc) · 4.21 KB
/
Copy pathcsv.ts
File metadata and controls
134 lines (121 loc) · 4.21 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import type { ValidationTask } from '../Zustand/Store';
import type { Transaction } from '../pages/VaultTransactions';
export type AnalyticsRow = {
name: string;
success: number;
failed: number;
capital: number;
milestones: number;
};
const TASK_HEADERS: string[] = ['ID', 'Status', 'Vault Name', 'Owner', 'Amount', 'Deadline', 'Milestone', 'Notes'];
const TX_HEADERS: string[] = ['ID', 'Type', 'Vault', 'Amount (XLM)', 'Fee (XLM)', 'Status', 'Timestamp', 'Hash', 'Block', 'From', 'To', 'Memo'];
const ANALYTICS_HEADERS: string[] = ['Period', 'Success %', 'Failed %', 'Capital (USDC)', 'Milestones'];
/** Safe placeholder for amount/fee cells that are not finite numbers after normalization. */
export const NON_FINITE_NUMERIC_PLACEHOLDER = '';
/**
* Normalizes a numeric CSV cell to a canonical dot-decimal, ungrouped string.
* Non-finite values (NaN, ±Infinity) and unparseable input resolve to
* {@link NON_FINITE_NUMERIC_PLACEHOLDER}. Call this before {@link escapeCell}.
*/
export function normalizeNumericCell(value: number | string): string {
let n: number;
if (typeof value === 'number') {
n = value;
} else if (typeof value === 'string') {
const stripped = value.replace(/,/g, '').trim();
if (stripped.length === 0) return NON_FINITE_NUMERIC_PLACEHOLDER;
n = Number(stripped);
} else {
return NON_FINITE_NUMERIC_PLACEHOLDER;
}
if (!Number.isFinite(n)) {
return NON_FINITE_NUMERIC_PLACEHOLDER;
}
return new Intl.NumberFormat('en-US', {
useGrouping: false,
maximumSignificantDigits: 21,
}).format(n);
}
function escapeCell(value: string): string {
if (value.length > 0 && /^[=+\-@\t\r]/.test(value)) {
value = `'${value}`;
}
if (value.includes('"') || value.includes(',') || value.includes('\n') || value.includes('\r')) {
return `"${value.replace(/"/g, '""')}"`;
}
return value;
}
function taskToRow(task: ValidationTask): string {
const cells = [
task.id,
task.status,
task.vaultName,
task.owner,
task.amount,
task.deadline,
task.milestone,
task.notes ?? '',
];
return cells.map(escapeCell).join(',');
}
function analyticsRowToRow(row: AnalyticsRow): string {
const cells = [
row.name,
String(row.success),
String(row.failed),
String(row.capital),
String(row.milestones),
];
return cells.map(escapeCell).join(',');
}
function txToRow(tx: Transaction): string {
const cells = [
tx.id,
tx.type,
tx.vault,
normalizeNumericCell(tx.amount),
normalizeNumericCell(tx.fee),
tx.status,
tx.timestamp instanceof Date ? tx.timestamp.toISOString() : String(tx.timestamp),
tx.hash,
String(tx.block),
tx.from,
tx.to,
tx.memo,
];
return cells.map(escapeCell).join(',');
}
export function toCsv(tasks: ValidationTask[]): string;
export function toCsv(txs: Transaction[], type: 'transactions'): string;
export function toCsv(rows: AnalyticsRow[], type: 'analytics'): string;
export function toCsv(data: Array<ValidationTask | Transaction | AnalyticsRow>, type?: 'transactions' | 'analytics'): string {
if (type === 'analytics') {
const headerRow = ANALYTICS_HEADERS.join(',');
if (data.length === 0) return headerRow;
const rows = (data as AnalyticsRow[]).map(analyticsRowToRow);
return [headerRow, ...rows].join('\r\n');
} else if (type === 'transactions') {
const headerRow = TX_HEADERS.join(',');
if (data.length === 0) return headerRow;
const rows = (data as Transaction[]).map(txToRow);
return [headerRow, ...rows].join('\r\n');
} else {
const headerRow = TASK_HEADERS.join(',');
if (data.length === 0) return headerRow;
const rows = (data as ValidationTask[]).map(taskToRow);
return [headerRow, ...rows].join('\r\n');
}
}
export function downloadCsv(csv: string, filename: string): void {
if (typeof document === 'undefined' || typeof URL === 'undefined') return;
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', filename);
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}