-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport.ts
More file actions
54 lines (49 loc) · 2.01 KB
/
export.ts
File metadata and controls
54 lines (49 loc) · 2.01 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
import { FilteredPurchases, PurchaseWithLineItems } from "@/types/purchase";
import Papa from "papaparse";
import { DISASTER_TYPE_LABELS } from "@/types/disaster";
import { getAllPurchasesForExport } from "@/api/purchase";
const handleCSVCreation = (purchases: PurchaseWithLineItems[]) => {
const data = purchases.flatMap((p) => {
if (p.lineItems.length === 0) {
return [
{
Merchant: p.vendor || "Unknown Vendor",
"Purchase Amount": (p.totalAmountCents / 100).toFixed(2),
"Purchase Date": new Date(p.dateCreated).toLocaleDateString(),
"Line Item": "No line items",
"Line Item Amount": "N/A",
Category: "Undefined",
"Disaster Related": "Non-Disaster",
},
];
}
return p.lineItems.map((li) => ({
Merchant: p.vendor || "Unknown Vendor",
"Purchase Amount": (p.totalAmountCents / 100).toFixed(2),
"Purchase Date": new Date(p.dateCreated).toLocaleDateString(),
"Line Item": li.description || "Unknown Item",
"Line Item Amount": (li.amountCents / 100).toFixed(2),
Category: li.category || "Undefined",
"Disaster Related": DISASTER_TYPE_LABELS.get(li.type || "pending") ?? "Undefined",
}));
});
const csv = Papa.unparse(data);
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `business-transactions.csv`;
link.click();
URL.revokeObjectURL(link.href);
};
export const handleExportClick = async (
setIsExporting: (bool: boolean) => void,
filters: FilteredPurchases,
total?: number
) => {
if (total) {
setIsExporting(true);
const allPurchases = await getAllPurchasesForExport(filters, total);
handleCSVCreation(allPurchases);
setIsExporting(false);
}
};