Skip to content

Commit 754a978

Browse files
committed
feat: create updateStreakStart function
handles streakDays update when user manually sets their streak start date
1 parent 2afed6f commit 754a978

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
@@ -154,6 +154,7 @@ export const register = async (email: string, password: string, username: string
154154
role: 'member', // Default role
155155
joinedAt: Timestamp.now(),
156156
streakDays: 0,
157+
streakStart: Timestamp.now(),
157158
lastCheckIn: Timestamp.now()
158159
});
159160

@@ -308,6 +309,32 @@ export const updateStreak = async (userId: string) => {
308309
}
309310
};
310311

312+
export const updateStreakStart = async (userId: string, startDate: Date) => {
313+
try {
314+
const userRef = doc(db, 'users', userId);
315+
const userDoc = await getDoc(userRef);
316+
317+
if (userDoc.exists()) {
318+
const userData = userDoc.data();
319+
const lastCheckIn = userData.lastCheckIn?.toDate() || new Date(0);
320+
321+
const diffInMilliseconds = startDate.getTime() - lastCheckIn.getTime();
322+
const diffInDays = Math.floor(diffInMilliseconds / (1000 * 60 * 60 * 24));
323+
324+
await updateDoc(userRef, {
325+
streakDays: diffInDays > 0 ? diffInDays : 0, // Ensure streakDays is not negative
326+
});
327+
328+
return { success: true, diffInDays, message: 'Streak start updated successfully' };
329+
}
330+
331+
return { success: false, message: 'User not found' };
332+
} catch (error) {
333+
console.error('Error setting streak:', error);
334+
return { success: false, message: error.message };
335+
}
336+
};
337+
311338
// Log relapse with multiple triggers (used for analytics)
312339
export const logRelapse = async (userId: string, triggers: string[], notes?: string) => {
313340
try {

0 commit comments

Comments
 (0)