Skip to content

feat: weekly attendance streak tracking v2#449

Merged
roshankumar0036singh merged 5 commits into
roshankumar0036singh:mainfrom
sheeeuWu:feat/weekly-attendance-streak-v2
May 31, 2026
Merged

feat: weekly attendance streak tracking v2#449
roshankumar0036singh merged 5 commits into
roshankumar0036singh:mainfrom
sheeeuWu:feat/weekly-attendance-streak-v2

Conversation

@sheeeuWu
Copy link
Copy Markdown
Contributor

@sheeeuWu sheeeuWu commented May 30, 2026

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

  • New feature (non-breaking change which adds functionality)

How Has This Been Tested?

All 4 streak scenarios were verified locally using the Firebase emulator suite. To reproduce:

  1. Start emulators: cd cloud-functions && npm run serve
  2. Run test script: npx ts-node src/scripts/testStreak.ts
  • Test 1 — Fresh user first check-in: currentStreak: 1
  • Test 2 — 4 consecutive weekly check-ins: currentStreak: 4, certificate written to user document
  • Test 3 — Same week double check-in: streak unchanged
  • Test 4 — Missed 2+ weeks: currentStreak resets to 1, longestStreak preserved

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • New Features

    • Streak tracking system to monitor attendance.
    • "My Streak" screen showing current streak, longest streak, progress, 4‑week cycle, and certificates.
    • Automatic awarding of achievement certificates when milestones are reached.
  • Improvements

    • Sign-up now initializes default streak fields for new profiles.
    • Certificate generation and delivery workflow improved (PDF generation, storage, and email sending).
  • Chores

    • Updated ignore rules for local scripts.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 30, 2026

Review Change Stack

Warning

Review limit reached

@sheeeuWu, we couldn't start this review because you've reached your PR review rate limit.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 2b7f0d13-26ff-4236-a77e-20e5c2c08c9e

📥 Commits

Reviewing files that changed from the base of the PR and between 08438cf and aa37fa1.

📒 Files selected for processing (3)
  • app/src/screens/MyEventsScreen.js
  • app/src/screens/UserFeed.js
  • cloud-functions/src/server.ts
📝 Walkthrough

Walkthrough

Adds 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.

Changes

Event Streaks: Data Model, Display, and Tracking

Layer / File(s) Summary
Streak Data Model & Profile Navigation
app/src/lib/AuthContext.js, app/src/screens/ProfileScreen.js, .gitignore
New user documents initialize with currentStreak, longestStreak, and lastAttendanceAt; ProfileScreen adds MaterialCommunityIcons and a "Streak" Activity menu item that navigates to the Streak screen; .gitignore excludes cloud-functions/src/scripts/.
Streak Display Screen
app/App.js, app/src/screens/StreakScreen.js
Adds StreakScreen import and authenticated Streak route; MyStreakScreen subscribes to users/{uid}, shows current/longest streaks, certificate count, 4-week milestone progress, weekly completion indicators, certificates list, and themed styles.
Attendance Streak Tracking
cloud-functions/src/attendanceStreak.ts, cloud-functions/src/index.ts
Firestore onDocumentCreated trigger for check-ins computes ISO-week keys, updates currentStreak/longestStreak/lastAttendanceAt in a transaction, re-reads streak and calls awardDedicatedStudentCertificate when streak ≥ 4; exported from cloud functions index.
Certificate Generation & Email Delivery
cloud-functions/src/certificateService.ts, cloud-functions/src/dedicatedStudentCertificate.ts
getResendClient() used per-send; new awardDedicatedStudentCertificate(userId) renders a PDF from a template, uploads to Storage, writes delivered certificate record to user doc, and sends an email via Resend (skipped in emulator).
Env & Middleware Formatting
cloud-functions/.env.example, cloud-functions/src/middleware/appCheck.ts, cloud-functions/src/middleware/ipWhitelist.ts
Whitespace/formatting updates only; no behavioral changes to app check or IP whitelist logic.

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
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

level:intermediate, type:testing, quality:clean

Suggested reviewers

  • roshankumar0036singh

Poem

🐰 I hopped through code to count the weeks,

Four little marks on tiny cheeks,
A certificate tucked in a digital nest —
For steady students who showed their best.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat: weekly attendance streak tracking v2' directly and clearly summarizes the main change—implementing weekly attendance streak tracking functionality.
Linked Issues check ✅ Passed The PR implements all coding requirements from issue #57: weekly attendance streak tracking with currentStreak/longestStreak fields, a 4-week certificate award mechanism, and streak visualization on the profile screen.
Out of Scope Changes check ✅ Passed Minor formatting changes in middleware files (appCheck.ts, ipWhitelist.ts) and .env.example appear incidental; all functional changes directly support the streak feature scope.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@roshankumar0036singh
Copy link
Copy Markdown
Owner

@sheeeuWu resolev the 12 issues flagged by sonar and the conflict

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0b5273a and 2f38b68.

📒 Files selected for processing (9)
  • .gitignore
  • app/App.js
  • app/src/lib/AuthContext.js
  • app/src/screens/ProfileScreen.js
  • app/src/screens/StreakScreen.js
  • cloud-functions/src/attendanceStreak.ts
  • cloud-functions/src/certificateService.ts
  • cloud-functions/src/dedicatedStudentCertificate.ts
  • cloud-functions/src/index.ts

Comment thread app/src/screens/StreakScreen.js Outdated
Comment thread app/src/screens/StreakScreen.js Outdated
Comment thread cloud-functions/src/attendanceStreak.ts Outdated
Comment thread cloud-functions/src/attendanceStreak.ts
Comment thread cloud-functions/src/dedicatedStudentCertificate.ts
@roshankumar0036singh
Copy link
Copy Markdown
Owner

conlfict and coderabbit suggestion

@sheeeuWu sheeeuWu force-pushed the feat/weekly-attendance-streak-v2 branch from cd45eff to 8cc823f Compare May 31, 2026 12:08
@sonarqubecloud
Copy link
Copy Markdown

@roshankumar0036singh roshankumar0036singh merged commit b96f704 into roshankumar0036singh:main May 31, 2026
6 checks passed
@sheeeuWu sheeeuWu deleted the feat/weekly-attendance-streak-v2 branch May 31, 2026 14:42
@sheeeuWu
Copy link
Copy Markdown
Contributor Author

thank you for reviewing and merging PR t_t

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add "Event Streaks" for Consistent Attendance

2 participants