Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add donor email to organization alerts #33

Merged
merged 6 commits into from
Dec 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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';
Loading