feat(invitations): user-facing referral abilities, redemption event, referrer notification#3980
Conversation
…referrer notification Widen invitationAbilities behind a new config.invitations.userFacing flag (default OFF, admin-only preserved): authenticated users can create their own invitation and read invitations they sent (server-scoped via the existing InvitationsService.list() invitedBy scoping). resend stays explicitly admin-gated in the controller since its POST verb maps to the same CASL 'create' action as new-invitation creation. Also: emit an invitation_redeemed analytics event on accept, carry invite/referral attribution on the signup event, notify the referrer by email (existing mailer abstraction) when their referral reward is freshly credited, and index users.referredBy. Closes #3945
… gate) Widening invitationAbilities to authenticated users makes an unbounded POST /api/invitations a DB-bloat / outbound-email-spam abuse surface (caught by the pre-push critical-review gate). Add an invitationsCreate rate-limit profile (base-layer pattern, active under every NODE_ENV, stricter cap in production) on both the canonical route and the /api/auth/invitations alias, which points at the same controller. Also: move mailer.isConfigured() inside notifyReferrer's try/catch so a synchronous throw from the check itself can't escape.
|
Warning Review limit reached
Next review available in: 52 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
WalkthroughThis PR enables config-gated user-facing invitation access, adds creation throttles to canonical and legacy routes, enforces admin-only resend behavior, records invitation attribution analytics, emails referrers after fresh rewards, and indexes ChangesReferral invitation rollout
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Signup
participant InvitationService
participant AuthController
participant AnalyticsService
Signup->>InvitationService: accept invitation
InvitationService->>AnalyticsService: capture invitation_redeemed
Signup->>AuthController: complete account creation
AuthController->>AnalyticsService: capture user_signed_up attribution
sequenceDiagram
participant InvitationService
participant BillingReferralService
participant UserService
participant Mailer
InvitationService->>BillingReferralService: grant referral reward
BillingReferralService->>UserService: load referrer
BillingReferralService->>Mailer: send referral reward email
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ 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 |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #3980 +/- ##
==========================================
+ Coverage 93.12% 93.15% +0.02%
==========================================
Files 170 170
Lines 5615 5639 +24
Branches 1809 1817 +8
==========================================
+ Hits 5229 5253 +24
Misses 311 311
Partials 75 75
Flags with carried forward coverage won't be shown. Click here to find out more. Continue to review full report in Codecov by Harness.
🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 `@config/templates/referral-reward-earned.html`:
- Line 4: Replace the empty title element in the referral reward earned template
with a non-empty title that combines the configured app name and the referral
reward context, preserving the template’s existing variable conventions.
🪄 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: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 6979157b-234b-4ed1-bd99-28857d696c98
📒 Files selected for processing (19)
config/defaults/production.config.jsconfig/defaults/test.config.jsconfig/templates/referral-reward-earned.htmllib/middlewares/tests/rateLimiter.baseLayer.unit.tests.jsmodules/auth/controllers/auth.controller.jsmodules/auth/routes/auth.routes.jsmodules/auth/tests/auth.silent.catch.unit.tests.jsmodules/billing/services/billing.referral.service.jsmodules/billing/tests/billing.referral.service.unit.tests.jsmodules/invitations/README.mdmodules/invitations/config/invitations.development.config.jsmodules/invitations/controllers/invitations.controller.jsmodules/invitations/policies/invitations.policy.jsmodules/invitations/routes/invitations.routes.jsmodules/invitations/services/invitations.service.jsmodules/invitations/tests/invitations.controller.unit.tests.jsmodules/invitations/tests/invitations.policy.unit.tests.jsmodules/invitations/tests/invitations.service.unit.tests.jsmodules/users/models/users.model.mongoose.js
CodeRabbit (HTMLHint): title-require. Mirrors the existing app-name pattern used elsewhere in this template's own copy.
Summary
The invitations module ships a referral reward path, but
invitationAbilitiesonly grantedmanage allto platform admins — regular authenticated users had no ability onInvitation, so a user-facing referrals surface was unreachable. Groundwork (invitedBy-scopedlist(), self-invite guard) shipped earlier.invitationAbilitiesbehind a newconfig.invitations.userFacingflag (stack default OFF, preserving current admin-only behavior for every existing deployment): authenticated users cancreateanInvitationandreadinvitations they sent — the real invitedBy-scoping is enforced inInvitationsService.list()(both grants are collection-level CASL rules; no per-documentInvitationsubject is registered, and the reasoning for that is documented inline).resend(POST /invitations/:id/resend) stays explicitly admin-gated in the controller, independent of the flag: its POST verb maps to the same CASLcreateaction as new-invitation creation, so a naive widen would otherwise let any user resend someone else's pending invite.remove/revokeneeded no change (non-admins are never granteddelete).invitation_redeemedevent on accept, and carryinvited/invitationId/invitedByattribution on theuser_signed_upevent.referral-reward-earnedtemplate) to the referrer when their referral reward is freshly credited — fires exactly once per invitation (piggybacks on the existing atomic ledger dedup guard), so a reconcile-cron back-fill or a replayed event never double-sends.users.referredBy(supports the "who did I refer" query).Stack-generic: no project-specific enums/names/amounts; reward amounts stay config-driven as before; tests use generic mock data.
Test plan
npm run lint— cleannpm run test:coverage -- --testPathPatterns='unit'— 164 suites / 2226 tests passed, coverage threshold holds (integration/E2E skipped locally, no MongoDB available in this environment — CI runs the full suite)invitationAbilitiesfor both flag states + admin-always-wins;resend's admin-only gate (3 rejection cases);accept()'sinvitation_redeemedcapture (incl. best-effort swallow);user_signed_upinvite/referral properties (invited + non-invited paths);notifyReferrer(mailer off, freshly-applied grant, non-applied grant, duplicate replay, missing email, send failure)Closes #3945
Summary by CodeRabbit
New Features
Bug Fixes
Documentation