Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@devkiran
Copy link
Collaborator

@devkiran devkiran commented Jul 9, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Adjusted payouts usage to reflect reductions when a charge fails.

@vercel
Copy link
Contributor

vercel bot commented Jul 9, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
dub 🛑 Canceled (Inspect) Jul 9, 2025 7:19pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 9, 2025

Walkthrough

A new database update operation has been introduced in the Stripe charge failure webhook handler. After marking an invoice as failed and resetting payouts, the code now decrements the payoutsUsage field in the corresponding project record by the invoice amount.

Changes

File(s) Change Summary
apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts Changed workspace retrieval from findUniqueOrThrow to an update operation that decrements payoutsUsage in the project record after a charge failure.

Sequence Diagram(s)

sequenceDiagram
    participant Stripe
    participant WebhookHandler
    participant Database

    Stripe->>WebhookHandler: Stripe charge.failed event
    WebhookHandler->>Database: Mark invoice as failed
    WebhookHandler->>Database: Reset payouts
    WebhookHandler->>Database: Decrement project.payoutsUsage by invoice amount
Loading

Possibly related PRs

Suggested reviewers

  • steven-tey

Poem

A charge has failed, the code takes note,
Payouts reset, and numbers float.
Down goes usage, a careful tweak,
The ledger balanced, strong not weak.
With every update, the system’s sound—
Hopping forward, changes abound! 🐇


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9b8313b and f0249b1.

📒 Files selected for processing (1)
  • apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@devkiran devkiran requested a review from steven-tey July 9, 2025 18:57
Copy link
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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3bb8bd1 and 9b8313b.

📒 Files selected for processing (1)
  • apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: steven-tey
PR: dubinc/dub#0
File: :0-0
Timestamp: 2025-06-25T21:20:59.837Z
Learning: In the Dub codebase, payout limit validation uses a two-stage pattern: server actions perform quick sanity checks (payoutsUsage > payoutsLimit) for immediate user feedback, while the cron job (/cron/payouts) performs authoritative validation (payoutsUsage + payoutAmount > payoutsLimit) with actual calculated amounts before processing. This design provides fast user feedback while ensuring accurate limit enforcement at transaction time.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
🔇 Additional comments (1)
apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts (1)

56-66: Good implementation of payoutsUsage reduction on charge failure.

The logic correctly decrements the payoutsUsage when a charge fails, which aligns with the PR objectives. This ensures accurate usage tracking for payout limits.

Comment on lines 56 to 66
// Reduce the payoutsUsage by the invoice amount since the charge failed
await prisma.project.update({
where: {
id: invoice.workspaceId,
},
data: {
payoutsUsage: {
decrement: invoice.amount,
},
},
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider wrapping database operations in a transaction for atomicity.

The current implementation performs three separate database operations sequentially. If the payoutsUsage decrement fails, the invoice and payouts would already be updated, leading to an inconsistent state.

Consider wrapping these operations in a transaction:

+  await prisma.$transaction(async (tx) => {
+    // Mark the invoice as failed
+    const invoice = await tx.invoice.update({
+      where: {
+        id: invoiceId,
+      },
+      data: {
+        status: "failed",
+        failedReason,
+      },
+    });
+
+    // Mark the payouts as pending again
+    await tx.payout.updateMany({
+      where: {
+        invoiceId,
+      },
+      data: {
+        status: "pending",
+        userId: null,
+        invoiceId: null,
+      },
+    });
+
+    // Reduce the payoutsUsage by the invoice amount since the charge failed
+    await tx.project.update({
+      where: {
+        id: invoice.workspaceId,
+      },
+      data: {
+        payoutsUsage: {
+          decrement: invoice.amount,
+        },
+      },
+    });
+  });

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts between lines 56 and
66, the database update for decrementing payoutsUsage should be wrapped in a
transaction along with the other related database operations to ensure
atomicity. Refactor the code to use a Prisma transaction that includes all the
database updates so that if any operation fails, none of the changes are
committed, preventing inconsistent state.

💡 Verification agent

🧩 Analysis chain

Verify that payoutsUsage cannot go negative and validate usage tracking consistency.

The decrement operation could potentially make payoutsUsage negative if there's a data inconsistency (e.g., if the original payout wasn't properly tracked in usage). This could affect payout limit validation.

Please verify the usage tracking flow and ensure proper safeguards:


🏁 Script executed:

#!/bin/bash
# Description: Search for payoutsUsage increment operations to understand the usage tracking flow
# Expected: Find where payoutsUsage is incremented to ensure consistent tracking

echo "=== Searching for payoutsUsage increment operations ==="
rg -A 5 -B 5 "payoutsUsage.*increment"

echo -e "\n=== Searching for payoutsUsage update operations ==="
rg -A 5 -B 5 "payoutsUsage.*\{"

echo -e "\n=== Searching for payout processing logic ==="
rg -A 10 -B 5 "status.*completed.*payout"

Length of output: 3958


Prevent Negative payoutsUsage in charge-failed webhook

Guard against underflow when decrementing payoutsUsage—ensure it never drops below zero by first reading the current value and clamping the result.

Locations to update:

  • apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts

Suggested change:

--- a/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
@@ /* before decrement */ 
- // Reduce the payoutsUsage by the invoice amount since the charge failed
- await prisma.project.update({
-   where: { id: invoice.workspaceId },
-   data: {
-     payoutsUsage: { decrement: invoice.amount },
-   },
- });
+ // Safely reduce payoutsUsage, clamping at zero to avoid negative values
+ const project = await prisma.project.findUnique({
+   where: { id: invoice.workspaceId },
+   select: { payoutsUsage: true },
+ });
+ if (project) {
+   const newUsage = Math.max(project.payoutsUsage - invoice.amount, 0);
+   await prisma.project.update({
+     where: { id: invoice.workspaceId },
+     data: { payoutsUsage: newUsage },
+   });
+ }

This preserves the two-stage design (immediate sanity vs. authoritative cron check) and prevents negative balances.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Reduce the payoutsUsage by the invoice amount since the charge failed
await prisma.project.update({
where: {
id: invoice.workspaceId,
},
data: {
payoutsUsage: {
decrement: invoice.amount,
},
},
});
// Safely reduce payoutsUsage, clamping at zero to avoid negative values
const project = await prisma.project.findUnique({
where: { id: invoice.workspaceId },
select: { payoutsUsage: true },
});
if (project) {
const newUsage = Math.max(project.payoutsUsage - invoice.amount, 0);
await prisma.project.update({
where: { id: invoice.workspaceId },
data: { payoutsUsage: newUsage },
});
}
🤖 Prompt for AI Agents
In apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts around lines 56 to 66,
the code decrements payoutsUsage by invoice.amount without checking if it will
go below zero. To fix this, first query the current payoutsUsage value for the
project, then calculate the new value by subtracting invoice.amount but clamp it
to a minimum of zero. Finally, update payoutsUsage with this clamped value to
prevent negative balances.

@steven-tey steven-tey merged commit 2f3d24a into main Jul 9, 2025
5 of 7 checks passed
@steven-tey steven-tey deleted the decrement-payout-usage branch July 9, 2025 19:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants