Skip to content

Commit

Permalink
feat: add donor email to organization alerts (#33)
Browse files Browse the repository at this point in the history
- add new function to fetch multiple docs in once.
---------

Co-authored-by: Elara Liu <[email protected]>
  • Loading branch information
marycaserio and ZL-Asica authored Dec 6, 2024
1 parent 805e3f2 commit 561f6fc
Show file tree
Hide file tree
Showing 3 changed files with 101 additions and 3 deletions.
44 changes: 44 additions & 0 deletions src/components/Alerts/OrganizationAlerts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,47 @@ import {
ListItemText,
} from '@mui/material';
import dayjs from 'dayjs';
import { useState, useEffect } from 'react';

import { useEventStore } from '@/stores';

import { getOrDefaultDocuments } from '@/utils/firebase';

const defaultDonorProfile: DonorProfile = {
uid: '',
name: '',
email: '',
profilePic: '',
joinedEvents: [],
createdAt: new Date().toISOString(),
role: 'donor',
providedSupplies: [],
saved: [],
};

const OrganizationAlerts = () => {
const events = useEventStore((store) => store.events);
const [donorEmails, setDonorEmails] = useState<Record<string, string>>({});

useEffect(() => {
const fetchDonorEmails = async () => {
const donorIds = events.map((event) => event.donorId);
const donorProfiles = await getOrDefaultDocuments<DonorProfile>(
donorIds,
defaultDonorProfile
);

const emails: Record<string, string> = {};
for (const profile of donorProfiles) {
emails[profile.uid] = profile.email;
}
setDonorEmails(emails);
};

if (events.length > 0) {
fetchDonorEmails();
}
}, [events]);

return (
<Box sx={{ padding: 3 }}>
Expand Down Expand Up @@ -43,6 +79,14 @@ const OrganizationAlerts = () => {
{event.title.split('from')[1].trim() || 'Loading...'}{' '}
{/* Display donor name */}
</Typography>
<Typography
variant='body2'
sx={{ mb: 1 }}
>
<strong>Donor Email:</strong>{' '}
{donorEmails[event.donorId] || 'Loading...'}{' '}
{/* Display donor name */}
</Typography>
<Typography
variant='body2'
sx={{ mb: 1 }}
Expand Down
58 changes: 56 additions & 2 deletions src/utils/firebase/firebaseUtils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import type { DocumentData, WithFieldValue } from 'firebase/firestore';
import { doc, getDoc, setDoc } from 'firebase/firestore';
import {
collection,
doc,
getDoc,
getDocs,
query,
setDoc,
where,
} from 'firebase/firestore';

import { db } from './firebaseConfig';

Expand Down Expand Up @@ -57,4 +65,50 @@ const updateDocument = async <T>(
}
};

export { getOrCreateDocument, updateDocument };
const getOrDefaultDocuments = async <T extends WithFieldValue<DocumentData>>(
uids: string[],
defaultData: T
): Promise<T[]> => {
const results: T[] = [];
const BATCH_SIZE = 10; // Firestore `in` query limit
const collectionName = defaultData.role;

try {
const existingDocs: Record<string, T> = {};

// Split UIDs into batches to respect Firestore's `in` query limit
const batches = [];
for (let i = 0; i < uids.length; i += BATCH_SIZE) {
batches.push(uids.slice(i, i + BATCH_SIZE));
}

// Fetch existing documents in batches
for (const batch of batches) {
const docsQuery = query(
collection(db, collectionName),
where('__name__', 'in', batch)
);
const querySnapshot = await getDocs(docsQuery);
// eslint-disable-next-line unicorn/no-array-for-each
querySnapshot.forEach((docSnap) => {
if (docSnap.exists()) {
existingDocs[docSnap.id] = docSnap.data() as T;
}
});
}

// Map UIDs to their corresponding documents or default data
for (const uid of uids) {
results.push(existingDocs[uid] || { ...defaultData, id: uid });
}
} catch (error) {
console.error(
`Error in getOrDefaultDocuments for ${collectionName}:`,
error
);
}

return results;
};

export { getOrCreateDocument, updateDocument, getOrDefaultDocuments };
2 changes: 1 addition & 1 deletion src/utils/firebase/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { loginUser, logoutUser } from './auth';
export { auth, db } from './firebaseConfig';
export { updateDocument } from './firebaseUtils';
export { updateDocument, getOrDefaultDocuments } from './firebaseUtils';
export { updateEvent, removeEvent } from './eventsUtils';

0 comments on commit 561f6fc

Please sign in to comment.