Skip to content

Commit 6783ff7

Browse files
committed
feat: create updateStreakStart function
handles streakDays update when user manually sets their streak start date
1 parent 5e93d9e commit 6783ff7

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/pages/Dashboard.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import React, { useState, useEffect } from 'react';
22
import { Link } from 'react-router-dom';
33
import { useAuth } from '../utils/auth';
4-
import { updateStreak, getUserProfile } from '../utils/firebase';
4+
import { updateStreak, getUserProfile, updateStreakStart } from '../utils/firebase';
55
import { cn } from '@/lib/utils';
66
import {
77
ArrowRight,

src/utils/firebase.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ export const register = async (email: string, password: string, username: string
9393
role: 'member', // Default role
9494
joinedAt: Timestamp.now(),
9595
streakDays: 0,
96+
streakStart: Timestamp.now(),
9697
lastCheckIn: Timestamp.now()
9798
});
9899

@@ -247,6 +248,32 @@ export const updateStreak = async (userId: string) => {
247248
}
248249
};
249250

251+
export const updateStreakStart = async (userId: string, startDate: Date) => {
252+
try {
253+
const userRef = doc(db, 'users', userId);
254+
const userDoc = await getDoc(userRef);
255+
256+
if (userDoc.exists()) {
257+
const userData = userDoc.data();
258+
const lastCheckIn = userData.lastCheckIn?.toDate() || new Date(0);
259+
260+
const diffInMilliseconds = startDate.getTime() - lastCheckIn.getTime();
261+
const diffInDays = Math.floor(diffInMilliseconds / (1000 * 60 * 60 * 24));
262+
263+
await updateDoc(userRef, {
264+
streakDays: diffInDays > 0 ? diffInDays : 0, // Ensure streakDays is not negative
265+
});
266+
267+
return { success: true, diffInDays, message: 'Streak start updated successfully' };
268+
}
269+
270+
return { success: false, message: 'User not found' };
271+
} catch (error) {
272+
console.error('Error setting streak:', error);
273+
return { success: false, message: error.message };
274+
}
275+
};
276+
250277
// Log relapse with multiple triggers (used for analytics)
251278
export const logRelapse = async (userId: string, triggers: string[], notes?: string) => {
252279
try {

0 commit comments

Comments
 (0)