diff --git a/hooks/firebase/types/profileTypes.ts b/hooks/firebase/types/profileTypes.ts index ef3e430..5af414f 100644 --- a/hooks/firebase/types/profileTypes.ts +++ b/hooks/firebase/types/profileTypes.ts @@ -43,4 +43,6 @@ export interface UserProfile { googleAccounts?: { [email: string]: GoogleAccount }; microsoftAccounts?: { [email: string]: MicrosoftAccount }; appleAccounts?: { [email: string]: AppleAccount }; + weeklyPoints?: number; + allTimePoints?: number; } \ No newline at end of file diff --git a/hooks/firebase/useUpdateTodo.ts b/hooks/firebase/useUpdateTodo.ts index 58ba21e..01356bf 100644 --- a/hooks/firebase/useUpdateTodo.ts +++ b/hooks/firebase/useUpdateTodo.ts @@ -9,6 +9,7 @@ import { getNextYearlyDates } from "@/hooks/firebase/useCreateTodo"; import { useAuthContext } from "@/contexts/AuthContext"; +import {UserProfile} from "@/hooks/firebase/types/profileTypes"; export const useUpdateTodo = () => { const { user: currentUser, profileData } = useAuthContext(); @@ -108,10 +109,49 @@ export const useUpdateTodo = () => { await batch.commit(); } else { - await firestore() - .collection("Todos") - .doc(todoData.id) - .update(todoData); + + let documentSnapshot = await firestore().collection("Todos").doc(todoData.id).get(); + if (documentSnapshot.exists) { + let todoUpdate = documentSnapshot.data() as IToDo; + + const userBatch = firestore().batch(); + if (todoUpdate.done !== todoData.done) { + + todoUpdate.assignees?.map(async (userId) => { + const userRef = firestore().collection("Profiles").doc(userId); + let userSnapshot = await userRef.get(); + let userData = userSnapshot.data() as UserProfile; + + if (!userData) return; + + // Calculate new points + let userWeeklyPoints = userData.weeklyPoints ?? 0; + const weeklyPoints = todoData.done + ? userWeeklyPoints + todoUpdate.points + : userWeeklyPoints - todoUpdate.points; + + let userAllTimePoints = userData.allTimePoints ?? 0; + const allTimePoints = todoData.done + ? userAllTimePoints + todoUpdate.points + : userAllTimePoints - todoUpdate.points; + + // Update the user's points in Firestore + userData = { + ...userData, + weeklyPoints: weeklyPoints >= 0 ? weeklyPoints : 0, + allTimePoints: allTimePoints >= 0 ? allTimePoints : 0 + } + userBatch.update(userRef, userData); + }); + } + + await firestore() + .collection("Todos") + .doc(todoData.id) + .update(todoData); + + await userBatch.commit(); + } } } catch (e) { console.error(e)