-
Notifications
You must be signed in to change notification settings - Fork 0
Adding a streak feature #24
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
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| name: Sentry Test Analytics | ||
|
|
||
| on: | ||
| push: | ||
| branches: ['**'] # Run on all branches | ||
| pull_request: | ||
| branches: ['**'] # Run on PRs to any branch | ||
|
|
||
| permissions: | ||
| id-token: write | ||
|
|
||
| jobs: | ||
| test: | ||
| runs-on: ubuntu-latest | ||
| defaults: | ||
| run: | ||
| working-directory: app # This ensures all commands run in the /app directory | ||
|
|
||
| steps: | ||
| - name: Checkout code | ||
| uses: actions/checkout@v4 | ||
|
|
||
| - name: Set up Node.js | ||
| uses: actions/setup-node@v4 | ||
| with: | ||
| node-version: 20 | ||
| cache: 'npm' | ||
| cache-dependency-path: app/package-lock.json | ||
|
|
||
| - name: Install dependencies | ||
| run: npm ci | ||
|
|
||
| - name: Run tests with JUnit output | ||
| run: | | ||
| # Install jest-junit if not already available | ||
| npm install --save-dev jest-junit | ||
| # Run tests with JUnit output for Sentry Test Analytics | ||
| npx jest --testResultsProcessor=jest-junit --outputFile=test-results.junit.xml | ||
| env: | ||
| NODE_ENV: test | ||
| continue-on-error: true # Allow flaky tests to not fail the build | ||
|
|
||
| - name: Upload test results to Sentry | ||
| if: ${{ !cancelled() }} | ||
| uses: getsentry/prevent-action |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| import { NextRequest, NextResponse } from 'next/server'; | ||
| import { getServerSession } from 'next-auth/next'; | ||
| import { authOptions } from '@/lib/auth.config'; | ||
| import { PrismaClient } from '@prisma/client'; | ||
|
|
||
| const prisma = new PrismaClient(); | ||
|
|
||
| // GET: Calculate and return streak data | ||
| export async function GET() { | ||
| const session = await getServerSession(authOptions); | ||
|
|
||
| if (!session?.user?.email) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); | ||
| } | ||
|
|
||
| const user = await prisma.user.findUnique({ | ||
| where: { email: session.user.email }, | ||
| }); | ||
|
|
||
| if (!user) { | ||
| return NextResponse.json({ error: 'User not found' }, { status: 404 }); | ||
| } | ||
|
|
||
| try { | ||
| // Get current week's activities | ||
| const now = new Date(); | ||
| const startOfWeek = new Date(now); | ||
| startOfWeek.setDate(now.getDate() - now.getDay()); // Start of current week (Sunday) | ||
| startOfWeek.setHours(0, 0, 0, 0); | ||
|
|
||
| const endOfWeek = new Date(startOfWeek); | ||
| endOfWeek.setDate(startOfWeek.getDate() + 6); // End of current week (Saturday) | ||
| endOfWeek.setHours(23, 59, 59, 999); | ||
|
|
||
| // Get activities for current week | ||
| const weekActivities = await prisma.activity.findMany({ | ||
| where: { | ||
| userId: user.id, | ||
| date: { | ||
| gte: startOfWeek, | ||
| lte: endOfWeek, | ||
| }, | ||
| }, | ||
| orderBy: { | ||
| date: 'asc', | ||
| }, | ||
| }); | ||
|
|
||
| // Calculate unique days with activities this week | ||
| const uniqueDays = new Set(); | ||
| weekActivities.forEach(activity => { | ||
| const activityDate = new Date(activity.date); | ||
| const dateString = activityDate.toISOString().split('T')[0]; // YYYY-MM-DD format | ||
| uniqueDays.add(dateString); | ||
| }); | ||
|
|
||
| const daysWithActivity = uniqueDays.size; | ||
|
|
||
| // Calculate streak data | ||
| const streakData = { | ||
| currentWeek: { | ||
| daysWithActivity, | ||
| totalActivities: weekActivities.length, | ||
| totalDuration: weekActivities.reduce((sum, activity) => sum + activity.duration, 0), | ||
| totalCalories: weekActivities.reduce((sum, activity) => sum + (activity.calories || 0), 0), | ||
| hasStreak: daysWithActivity >= 4, // Streak threshold: 4+ days | ||
| streakMessage: daysWithActivity >= 4 | ||
| ? `🔥 Amazing! You've worked out ${daysWithActivity} days this week!` | ||
| : daysWithActivity >= 2 | ||
| ? `💪 Great progress! You've worked out ${daysWithActivity} days this week. Keep it up!` | ||
| : daysWithActivity >= 1 | ||
| ? `🎯 Good start! You've worked out ${daysWithActivity} day this week.` | ||
| : `🚀 Ready to start your fitness journey? Log your first activity!`, | ||
| activitiesByDay: weekActivities.reduce((acc, activity) => { | ||
| const dateString = new Date(activity.date).toISOString().split('T')[0]; | ||
| if (!acc[dateString]) { | ||
| acc[dateString] = []; | ||
| } | ||
| acc[dateString].push(activity); | ||
| return acc; | ||
| }, {} as Record<string, typeof weekActivities>), | ||
| }, | ||
| // Calculate last week for comparison | ||
| lastWeek: await calculateLastWeekStreak(user.id, startOfWeek), | ||
| }; | ||
|
|
||
| return NextResponse.json({ streak: streakData }); | ||
| } catch (error) { | ||
| console.error('Error calculating streak:', error); | ||
| return NextResponse.json({ error: 'Failed to calculate streak' }, { status: 500 }); | ||
| } | ||
| } | ||
|
|
||
| // Helper function to calculate last week's streak | ||
| async function calculateLastWeekStreak(userId: string, currentWeekStart: Date) { | ||
| const lastWeekStart = new Date(currentWeekStart); | ||
| lastWeekStart.setDate(currentWeekStart.getDate() - 7); | ||
|
|
||
| const lastWeekEnd = new Date(lastWeekStart); | ||
| lastWeekEnd.setDate(lastWeekStart.getDate() + 6); | ||
| lastWeekEnd.setHours(23, 59, 59, 999); | ||
|
|
||
| const lastWeekActivities = await prisma.activity.findMany({ | ||
| where: { | ||
| userId, | ||
| date: { | ||
| gte: lastWeekStart, | ||
| lte: lastWeekEnd, | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| const uniqueDays = new Set(); | ||
| lastWeekActivities.forEach(activity => { | ||
| const activityDate = new Date(activity.date); | ||
| const dateString = activityDate.toISOString().split('T')[0]; | ||
| uniqueDays.add(dateString); | ||
| }); | ||
|
|
||
| return { | ||
| daysWithActivity: uniqueDays.size, | ||
| totalActivities: lastWeekActivities.length, | ||
| totalDuration: lastWeekActivities.reduce((sum, activity) => sum + activity.duration, 0), | ||
| totalCalories: lastWeekActivities.reduce((sum, activity) => sum + (activity.calories || 0), 0), | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Potential bug: The streak API converts activity dates to UTC using
toISOString(), which is inconsistent with other APIs that use local time, potentially causing incorrect streak calculations.Description: The new streak API at
/api/streak/route.tsconverts activity dates to a UTC date string usingactivityDate.toISOString().split('T')[0]. This is inconsistent with the established pattern in other endpoints, such as/api/activities/route.ts, which parse dates into local time. This discrepancy can lead to incorrect streak calculations. For example, an activity logged by a user in a timezone with a significant UTC offset late on a Sunday night could be converted to Monday in UTC, causing it to be excluded from the current week's streak calculation and misaligning the user's activity log.Suggested fix: Adopt the established date parsing logic from other API routes. Instead of converting to UTC with
toISOString(), ensure the date from the database is treated as local time, similar to the logic in/api/activities/route.tsand/api/meals/route.ts, to ensure consistent date handling across the application.severity: 0.75, confidence: 0.95
Did we get this right? 👍 / 👎 to inform future reviews.