feat: weekly attendance streak tracking v2#449
Conversation
|
Warning Review limit reached
More reviews will be available in 53 minutes and 20 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughAdds a 4-week attendance streak feature: initializes streak fields at signup, adds a "My Streak" screen and profile menu entry, updates streak state on check-ins via a Firestore trigger, and generates/uploads/sends a certificate when streak ≥ 4. ChangesEvent Streaks: Data Model, Display, and Tracking
Sequence Diagram(s)sequenceDiagram
participant User
participant StreakScreen
participant Firestore as Firestore (Read)
User->>StreakScreen: Navigate to Streak screen
StreakScreen->>Firestore: Subscribe to users/{uid}
Firestore-->>StreakScreen: currentStreak, longestStreak, certificates
StreakScreen-->>User: Render streak stats & progress bar
sequenceDiagram
participant CheckIn as Check-In Document
participant attendanceStreak as attendanceStreak Trigger
participant FirestoreTx as Firestore (Transaction)
participant certificateService as Certificate Award
CheckIn->>attendanceStreak: onDocumentCreated event
attendanceStreak->>FirestoreTx: Read user + streak fields
attendanceStreak->>FirestoreTx: Compare lastAttendanceAt vs 7-day window
attendanceStreak->>FirestoreTx: Update currentStreak & longestStreak
FirestoreTx-->>attendanceStreak: Transaction committed
attendanceStreak->>FirestoreTx: Re-read currentStreak
alt currentStreak >= 4
attendanceStreak->>certificateService: awardDedicatedStudentCertificate(userId)
certificateService->>Firestore: Generate PDF, upload to Storage, record certificate
certificateService->>Resend: Send email with PDF attachment
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@sheeeuWu resolev the 12 issues flagged by sonar and the conflict |
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/src/screens/StreakScreen.js`:
- Around line 23-28: The onSnapshot subscription on userRef currently only
handles the success snapshot path and can leave the component stuck in loading
on Firestore errors; update the onSnapshot call to provide the error callback
(second argument) that handles errors by calling setLoading(false), optionally
setting an error state or logging the error, and avoiding silent failure; ensure
the unsubscribe variable and existing snapshot handler (which calls setUserData)
remain unchanged but add the error handler to clear loading and surface/log the
error so the UI can react.
- Line 189: The certificate list key currently uses
`${cert.type}-${cert.awardedAt}` which can produce duplicates; update the key
prop in the map/render where certificates are rendered in StreakScreen to use a
stable unique identifier such as `cert.id` if available, and fall back to a
deterministic composite (e.g. `${cert.id ||
`${cert.type}-${cert.awardedAt}-${index}`}`) or similar, ensuring you reference
the mapped item (cert) and the map callback index variable so keys are unique
and stable across renders.
In `@cloud-functions/src/attendanceStreak.ts`:
- Around line 11-16: The handler currently reads the userId from the document
payload (const userId = event.data?.data()?.userId) which can be missing;
instead use the trigger path param event.params.userId as the canonical user id
and only fall back to event.data()?.userId for backward compatibility—replace
the lookup with a canonicalUserId (e.g., const userId = event.params.userId ??
event.data?.data()?.userId), update the existence check to use that
canonicalUserId, and ensure all subsequent references (streak update logic in
this function) use that canonical variable.
- Around line 39-50: The current elapsed-milliseconds check using diffMs and
WEEK_MS incorrectly treats any <7 days as same week; replace this with
calendar-week comparisons: compute a week identifier (e.g., year + ISO week
number or a UTC week-start timestamp) for now and lastAttendanceAt (use
lastAttendanceAt.toDate()/now.toDate() or equivalent), then if
lastAttendanceWeek === currentWeek return (already attended this calendar week),
else if lastAttendanceWeek === previousWeek set newStreak = currentStreak + 1,
otherwise reset streak; update the conditional in the block referencing
lastAttendanceAt, diffMs, WEEK_MS, currentStreak, and newStreak accordingly.
In `@cloud-functions/src/dedicatedStudentCertificate.ts`:
- Around line 77-128: Replace the non-atomic alreadyAwarded check + later
FieldValue.arrayUnion with an atomic "claim" step using a Firestore transaction:
in a transaction read the user doc (users collection) and if no existing
claim/entry for type "dedicated_student" create a placeholder certificate record
(or a separate certificateClaims subdoc) with type:"dedicated_student",
status:"pending_delivery" and claimedAt set, and only if the transaction commits
continue to generatePdfBuffer(), file.save(), and send the email; after a
successful send update the user's certificate entry (or claim doc) to
status:"delivered" and set awardedAt and certificateUrl (use a transaction or
conditional update to set those fields), and if email/send fails leave the
status as "pending_delivery" so retries can resume claiming→send→finalize
without duplicate awards; reference functions/fields: alreadyAwarded,
FieldValue.arrayUnion, generatePdfBuffer, file.save, file.getSignedUrl and the
users collection certificate object (type/awardedAt/certificateUrl).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 53a3da58-8764-4a03-afca-c9198a680e1e
📒 Files selected for processing (9)
.gitignoreapp/App.jsapp/src/lib/AuthContext.jsapp/src/screens/ProfileScreen.jsapp/src/screens/StreakScreen.jscloud-functions/src/attendanceStreak.tscloud-functions/src/certificateService.tscloud-functions/src/dedicatedStudentCertificate.tscloud-functions/src/index.ts
|
conlfict and coderabbit suggestion |
cd45eff to
8cc823f
Compare
|
b96f704
into
roshankumar0036singh:main
|
thank you for reviewing and merging PR t_t |



Description
Implements weekly attendance streak tracking for students. Every time a student checks in to an event, their streak is updated. Reaching a 4-week consecutive streak awards them a "Dedicated Student" certificate delivered via email.
Fixes #57
Type of change
How Has This Been Tested?
All 4 streak scenarios were verified locally using the Firebase emulator suite. To reproduce:
Checklist:
Summary by CodeRabbit
New Features
Improvements
Chores