- Implemented backend logic for saving weekly and all time points for todos

This commit is contained in:
Dejan
2024-12-22 18:31:22 +01:00
parent 4866dd1b3f
commit 2c6474007c
2 changed files with 46 additions and 4 deletions

View File

@ -43,4 +43,6 @@ export interface UserProfile {
googleAccounts?: { [email: string]: GoogleAccount };
microsoftAccounts?: { [email: string]: MicrosoftAccount };
appleAccounts?: { [email: string]: AppleAccount };
weeklyPoints?: number;
allTimePoints?: number;
}

View File

@ -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 {
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)