Integrate Rewards page with backend Discord roles and achievements#475
Conversation
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 6 minutes and 47 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, 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 have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThe Rewards page has been refactored to fetch achievement and Discord role data from the backend via a new Changes
Sequence DiagramsequenceDiagram
participant RC as Rewards Component
participant API as rewardsApi
participant Backend as Backend (/rewards/me)
participant Normalize as normalizeRewardsSnapshot
RC->>RC: Component mounts
RC->>RC: Set isLoading=true
RC->>API: getMyRewards()
API->>Backend: GET /rewards/me
alt Success
Backend-->>API: RewardsSnapshot JSON
API->>Normalize: normalizeRewardsSnapshot(payload)
Normalize-->>API: RewardsSnapshot (typed & validated)
API-->>RC: RewardsSnapshot
RC->>RC: Set snapshot, isLoading=false
RC->>RC: Render achievements & summary
else Error
Backend-->>API: Error response
API-->>RC: Rejection
RC->>RC: Set error, isLoading=false
RC->>RC: Show error alert + sync pending fallback
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@app/src/pages/Rewards.tsx`:
- Around line 99-103: The UI uses two different sources for totals causing
inconsistent progress: keep a single computed total and unlocked count used
everywhere. Replace uses of totalCount and unlockedCount with a unified total =
snapshot?.summary.totalCount ?? rewardRoles.length ?? 0 and unlocked =
snapshot?.summary.unlockedCount ?? rewardRoles.filter(r => r.unlocked).length
(or similar) and then compute progressWidth = total > 0 ? (unlocked / total) *
100 : 0; update all references (rewardRoles, unlockedCount, totalCount,
progressWidth) to use these unified values so the count and progress bar remain
consistent.
- Around line 58-64: The synchronous state resets inside the useEffect (the
calls to setIsLoading(true) and setError(null) at the start of loadRewards)
should be removed because they run synchronously before the first await and
violate the react-hooks/set-state-in-effect rule; edit the useEffect/loadRewards
block to eliminate those two immediate setter calls (or, if you need to reset
state only when the async begins, move them to just before the first await
inside the async function) and keep cancellation handling (cancelled flag) and
the existing try/catch/finally logic in functions loadRewards/useEffect intact.
In `@app/src/services/api/rewardsApi.ts`:
- Around line 20-44: normalizeAchievement is converting malformed credit amounts
into 0 by calling asNumber directly; change the logic for creditAmountUsd so it
returns null unless the raw value is a valid finite number (e.g. check typeof
raw.creditAmountUsd === 'number' or if it's a string, attempt
Number(raw.creditAmountUsd) and verify Number.isFinite(parsed) before calling
asNumber). Update the creditAmountUsd assignment in normalizeAchievement to
perform this validation and only call asNumber when the parsed value is a valid
finite number; otherwise set creditAmountUsd to null.
- Around line 92-100: The getMyRewards method in rewardsApi currently calls
apiClient.get<ApiResponse<unknown>>('/rewards/me') and immediately passes
response.data to normalizeRewardsSnapshot; you must validate the
ApiResponse.success flag before using response.data. Update getMyRewards (and
other API methods that follow this pattern) to check response.data.success (or
have apiClient.get throw when success is false), and if success is false throw
or return a rejected error that includes the backend error message (from
response.data.error) so callers aren’t silently shown empty data; look for the
symbols rewardsApi, getMyRewards, apiClient.get, ApiResponse, and
normalizeRewardsSnapshot to implement this change.
🪄 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
Run ID: 491fa44b-8728-4775-9d5a-f33ec17da697
📒 Files selected for processing (5)
app/src/pages/Rewards.tsxapp/src/pages/__tests__/Rewards.test.tsxapp/src/services/api/__tests__/rewardsApi.test.tsapp/src/services/api/rewardsApi.tsapp/src/types/rewards.ts
…ackend-336 # Conflicts: # app/src/pages/Rewards.tsx
…ogic - Removed redundant loading state management in the Rewards component. - Updated the calculation of unlocked and total rewards to derive values from the achievements array when necessary, enhancing accuracy. - Adjusted the display logic to reflect the new calculation method for better clarity. Enhancements in the rewards API include improved error handling for backend failures, ensuring robust user feedback during data retrieval. Added a utility function to validate numeric values, enhancing data normalization for achievements. Updated tests to cover new error handling scenarios and ensure consistent behavior across the rewards API.
- Adjusted the formatting of the unlocked rewards calculation for better clarity and maintainability. - Ensured consistent code style in the Rewards component, enhancing overall readability. These changes contribute to a cleaner codebase and facilitate future modifications.
Summary
/rewards/merewardsApiclient plus normalized rewards types for Discord linkage, role sync state, achievements, and server-tracked metricstinyhumansai/backend:developProblem
app/src/pages/Rewards.tsxinferred reward progress from local message counts, Redux channel state, and profile fields instead of canonical backend dataSolution
app/src/services/api/rewardsApi.tsandapp/src/types/rewards.tsto normalize the backend rewards payload into stable app-side typesapp/src/pages/Rewards.tsxto fetch the rewards snapshot on load and render Discord membership, role-sync status, achievement progress, and credit amounts from backend data/rewards/mecontract that is already present intinyhumansai/backend, so no backend changes are included in this PRSubmission Checklist
app/) and/orcargo test(core) for logic you add or changeapp/test/e2e, mock backend,tests/json_rpc_e2e.rsas appropriate)//////!(Rust), JSDoc or brief file/module headers (TS) on public APIs and non-obvious modules(Any feature related checklist can go in here)
Impact
/rewards/meendpoint already available ontinyhumansai/backend:developRelated
Summary by CodeRabbit
Release Notes
New Features
Tests