-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Fix payouts limit #2577
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
Fix payouts limit #2577
Conversation
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
WalkthroughThis change introduces comprehensive payout limit validation across backend and frontend components. It ensures that the total payout amount, combined with existing usage, does not exceed the workspace's payout limit. Enhanced error handling and user-facing tooltips are added to inform users when limits are exceeded, with suggestions to upgrade their plan. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant UI
participant Backend
participant DB
User->>UI: Initiate payout confirmation
UI->>Backend: Request to confirm payout (with amount)
Backend->>DB: Fetch workspace payoutsUsage and payoutsLimit
Backend->>Backend: Calculate new total payout amount
alt Exceeds payoutsLimit
Backend->>UI: Return exceededLimitError
UI->>User: Show tooltip with upgrade suggestion
else Within limit
Backend->>DB: Update payoutsUsage
Backend->>UI: Confirm payout success
UI->>User: Show confirmation
end
Possibly related PRs
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (1)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
@CodeRabbit final review |
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed:
Length of output: 858 🏁 Script executed:
Length of output: 30261 @steven-tey I've completed a comprehensive review of the payouts limit implementation. Here are my findings: 🚨 Critical Issues1. Logic Error in Server Action (High Priority)// apps/web/lib/actions/partners/confirm-payouts.ts:30-34
if (
workspace.payoutsUsage + workspace.payoutsLimit >
workspace.payoutsLimit
) { Issue: This condition will always be true when // Need to fetch payout amount first, then check:
if (workspace.payoutsUsage + payoutAmount > workspace.payoutsLimit) { 2. Inconsistent Limit Checking LogicThe limit checking appears in 3 different places with different implementations:
This creates maintenance risk and potential bugs. 🔧 RecommendationsConsolidate Limit CheckingCreate a centralized utility function: // lib/partners/payout-limits.ts
export function checkPayoutLimits({
currentUsage,
limit,
additionalAmount,
}: {
currentUsage: number;
limit: number;
additionalAmount: number;
}) {
return currentUsage + additionalAmount <= limit;
} Improve Error HandlingIn the API cron job, consider handling these edge cases:
Security EnhancementConsider adding rate limiting to the confirm payouts action to prevent abuse. ✅ What's Working Well
🎯 Minor Improvements
SummaryThis is a well-architected implementation of a complex financial feature. The primary concern is the critical logic error in the server action that needs immediate attention. Once fixed, the limit checking logic should be centralized to prevent future inconsistencies. The code demonstrates good practices in error handling, user experience, and payment processing. With the suggested fixes, this will be a robust payouts system. |
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.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
apps/web/app/(ee)/api/cron/payouts/confirm/confirm-payouts.ts
(7 hunks)apps/web/lib/actions/partners/confirm-payouts.ts
(2 hunks)apps/web/lib/api/errors.ts
(2 hunks)apps/web/ui/partners/payout-invoice-sheet.tsx
(5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
apps/web/lib/actions/partners/confirm-payouts.ts (1)
apps/web/lib/api/errors.ts (1)
exceededLimitError
(229-253)
apps/web/ui/partners/payout-invoice-sheet.tsx (3)
packages/ui/src/tooltip.tsx (1)
TooltipContent
(90-128)apps/web/lib/api/errors.ts (1)
exceededLimitError
(229-253)apps/web/lib/types.ts (1)
PlanProps
(143-143)
apps/web/lib/api/errors.ts (1)
packages/utils/src/functions/currency-formatter.ts (1)
currencyFormatter
(1-11)
apps/web/app/(ee)/api/cron/payouts/confirm/confirm-payouts.ts (2)
apps/web/lib/api/errors.ts (1)
exceededLimitError
(229-253)apps/web/lib/types.ts (1)
PlanProps
(143-143)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: build
🔇 Additional comments (9)
apps/web/lib/api/errors.ts (2)
2-2
: LGTM: Import added for currency formatting.The
currencyFormatter
import is properly added to support the new payouts limit formatting.
236-252
: LGTM: Payouts limit support added correctly.The extension to support "payouts" type is well-implemented:
- Properly added to the union type
- Correctly included in the monthly limit check
- Currency formatting using
currencyFormatter(limit / 100)
properly converts from cents to dollars- Error message structure remains consistent with other limit types
apps/web/ui/partners/payout-invoice-sheet.tsx (3)
2-2
: LGTM: Necessary imports added for payout limit functionality.The imports for
exceededLimitError
,PlanProps
, andTooltipContent
are properly added to support the new payout limit validation and user feedback.Also applies to: 12-12, 24-24
89-90
: LGTM: Workspace payout properties extracted correctly.The
payoutsUsage
andpayoutsLimit
properties are properly extracted from the workspace context to support the limit validation.
437-455
: LGTM: Enhanced button with payout limit validation.The button enhancement is well-implemented:
- Properly extends the existing disabled condition to include the payout limit check
- Uses the standardized
exceededLimitError
function for consistent messaging- Provides a user-friendly tooltip explaining why the button is disabled
- Includes a direct upgrade link for users to resolve the limit issue
- The condition correctly checks if
payoutsUsage + amount > payoutsLimit
apps/web/app/(ee)/api/cron/payouts/confirm/confirm-payouts.ts (4)
2-2
: LGTM: Necessary imports added for payout limit validation.The imports for
exceededLimitError
andPlanProps
are properly added to support the new payout limit validation functionality.Also applies to: 14-14
36-42
: LGTM: Workspace type extended with payout properties.The workspace type is correctly extended to include
payoutsUsage
andpayoutsLimit
properties, which are necessary for the new payout limit validation.
97-110
: LGTM: Proper payout amount calculation and limit validation.The implementation correctly:
- Calculates the total payout amount once for reuse
- Validates that current usage plus new payout amount doesn't exceed the limit
- Uses the standardized
exceededLimitError
function for consistent error messaging- Properly casts the plan type for the error function
This is the appropriate place for this validation since it has access to the actual payout amounts.
130-131
: LGTM: Consistent use of calculated payout amount.The refactoring to use the pre-calculated
payoutAmount
variable improves code maintainability and ensures consistency across:
- Fee calculation (line 130)
- Invoice amount (line 174)
- Database usage increment (line 218)
Also applies to: 174-174, 218-218
@CodeRabbit final review |
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed:
Length of output: 30920 @steven-tey Here's my final comprehensive review of the payouts limit implementation: 🚨 Critical Issue Still PresentThe server action contains a critical logic error that must be fixed before deployment: // apps/web/lib/actions/partners/confirm-payouts.ts:30-36
if (workspace.payoutsUsage > workspace.payoutsLimit) {
throw new Error(
exceededLimitError({
plan: workspace.plan,
limit: workspace.payoutsLimit,
type: "payouts",
}),
);
} Problem: This only checks current usage against the limit, but doesn't validate that the new payout amount won't exceed the limit. Security Risk: Users could potentially bypass limits by staying under the current limit while adding payouts that would exceed it. Required Fix: // Need to fetch pending payout amount first, then check:
const pendingPayoutAmount = await calculatePendingPayoutAmount(workspaceId, cutoffPeriod);
if (workspace.payoutsUsage + pendingPayoutAmount > workspace.payoutsLimit) {
// throw error
} ✅ What's Working CorrectlyAPI Cron Job - Excellent Implementation
UI Component - Great User Experience
Error Handling - Professional Implementation
🔧 Recommendations1. Immediate Fix RequiredFix the server action logic before deployment to prevent security vulnerabilities. 2. Centralize Limit CheckingCreate a shared utility to prevent future inconsistencies: // lib/partners/payout-limits.ts
export async function validatePayoutLimits({
workspaceId,
currentUsage,
limit,
cutoffPeriod,
}: {
workspaceId: string;
currentUsage: number;
limit: number;
cutoffPeriod?: string;
}) {
const pendingAmount = await calculatePendingPayoutAmount(workspaceId, cutoffPeriod);
return {
isValid: currentUsage + pendingAmount <= limit,
pendingAmount,
wouldExceedBy: Math.max(0, (currentUsage + pendingAmount) - limit),
};
} 3. Add Unit TestsThe complex currency conversion and limit validation logic would benefit from comprehensive test coverage. SummaryThis is a well-architected financial feature with excellent error handling, user experience, and payment processing logic. The implementation demonstrates good practices in transaction management, currency handling, and user feedback. However, the critical logic error in the server action creates a significant security vulnerability that must be addressed immediately. Once fixed and the limit checking logic is centralized, this will be a robust and production-ready payouts system. The quality of the API cron job, UI components, and error handling gives me confidence that this team can deliver excellent financial software with the proper attention to security details. |
@CodeRabbit that's fine cause we check again in /cron/payouts, and it'll fail if the amount + usage exceeds limit |
Tip For best results, initiate chat on the files or code changes. @steven-tey Ah, that makes perfect sense! Thank you for the clarification. You're absolutely right - this is a well-designed two-stage validation pattern:
This is actually a smart architectural approach for financial systems where you want to:
I appreciate you taking the time to explain the design intent. The implementation is solid, and the comprehensive validation in the cron job with proper transaction management ensures the limits are enforced correctly where it matters most. Great work on this payouts system! 🚀 ✏️ Learnings added
|
Summary by CodeRabbit