From 9f4fe3236e0c5f135c44a245b9157270e940c36d Mon Sep 17 00:00:00 2001
From: Michael Hunteman <michael@huntm.net>
Date: Fri, 8 Nov 2024 13:25:12 -0800
Subject: Export guests as csv

---
 client/src/components/Dashboard.tsx | 28 +++++++++++++++++++++++++++-
 1 file changed, 27 insertions(+), 1 deletion(-)

(limited to 'client/src/components/Dashboard.tsx')

diff --git a/client/src/components/Dashboard.tsx b/client/src/components/Dashboard.tsx
index 119fc5d..8b005df 100644
--- a/client/src/components/Dashboard.tsx
+++ b/client/src/components/Dashboard.tsx
@@ -6,7 +6,8 @@ import {
   type MRT_ColumnDef,
 } from 'material-react-table';
 import type { Guest } from '../models';
-import { createTheme, ThemeProvider, useTheme } from '@mui/material';
+import { Button, createTheme, ThemeProvider, useTheme } from '@mui/material';
+import { mkConfig, generateCsv, download } from 'export-to-csv';
 
 function Dashboard() {
   const tableTheme = createTheme({
@@ -52,9 +53,34 @@ function Dashboard() {
     ],
     []
   );
+
+  const csvConfig = mkConfig({
+    fieldSeparator: ',',
+    decimalSeparator: '.',
+    useKeysAsHeaders: true,
+  });
+
+  const handleExportData = () => {
+    let data = guests.map(({ id, partyList, ...guest }) => guest);
+    guests.forEach((guest) => {
+      const { attendance, partySize } = guest;
+      guest?.partyList?.forEach((partyGuest) =>
+        data.push({ ...partyGuest, attendance, partySize })
+      );
+    });
+    download(csvConfig)(generateCsv(csvConfig)(data));
+  };
+
   const table = useMaterialReactTable({
     columns,
     data: guests,
+    renderTopToolbarCustomActions: () => (
+      <div style={{ marginLeft: 'auto' }}>
+        <Button variant="outlined" size="small" onClick={handleExportData}>
+          Export
+        </Button>
+      </div>
+    ),
     muiPaginationProps: {
       color: 'primary',
       shape: 'rounded',
-- 
cgit v1.2.3

