Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

fix(storage): de-duplicate payments when updating db #286

Merged
merged 1 commit into from
Jan 24, 2025

Conversation

paul-nicolas
Copy link
Contributor

Sometimes, we can have two refunds for the same payment inside the same batch, and postgres does not support it and return an error 'command cannot affect row a second time'

Copy link
Contributor

coderabbitai bot commented Jan 24, 2025

Walkthrough

The pull request introduces changes to three files: internal/connectors/engine/activities/errors.go, internal/storage/payments.go, and internal/storage/payments_test.go. The modifications include a minor formatting change in the error handling file, significant improvements to the payment adjustment logic in the storage package, and the addition of new test cases for payment refunds in the test file.

Changes

File Change Summary
internal/connectors/engine/activities/errors.go Removed a blank line before the switch statement in temporalPluginErrorCheck function.
internal/storage/payments.go Enhanced payment adjustment handling by adding maps to track seen payment IDs for refunds, initial amount adjustments, and captures.
internal/storage/payments_test.go Added defaultPaymentsRefunded() helper function and TestPaymentsUpsertRefunded() test to validate refund processing.

Possibly related PRs

Suggested reviewers

  • laouji

Poem

🐰 In the code where payments flow,
Adjustments tracked, with a gentle glow.
A blank line gone, the logic shines bright,
In the realm of rabbits, all feels just right!
With tests in place, refunds take flight,
Coding together, we reach new heights! 🌟

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

@paul-nicolas paul-nicolas marked this pull request as ready for review January 24, 2025 14:21
@paul-nicolas paul-nicolas requested a review from a team as a code owner January 24, 2025 14:21
Copy link

codecov bot commented Jan 24, 2025

Codecov Report

Attention: Patch coverage is 77.77778% with 6 lines in your changes missing coverage. Please review.

Project coverage is 73.04%. Comparing base (4b942f6) to head (565f8bf).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
internal/storage/payments.go 77.77% 2 Missing and 4 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #286      +/-   ##
==========================================
- Coverage   73.04%   73.04%   -0.01%     
==========================================
  Files         537      537              
  Lines       27048    27065      +17     
==========================================
+ Hits        19758    19769      +11     
- Misses       6230     6232       +2     
- Partials     1060     1064       +4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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: 1

🧹 Nitpick comments (1)
internal/storage/payments_test.go (1)

44-145: Comprehensive refund test data
This helper function defaultPaymentsRefunded() creates multiple partial refunds for the same payment ID, which is great for testing the new deduplication logic thoroughly. The approach is robust and ensures coverage of multiple refund scenarios.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4b942f6 and 8d382b0.

📒 Files selected for processing (3)
  • internal/connectors/engine/activities/errors.go (0 hunks)
  • internal/storage/payments.go (2 hunks)
  • internal/storage/payments_test.go (2 hunks)
💤 Files with no reviewable changes (1)
  • internal/connectors/engine/activities/errors.go
🔇 Additional comments (6)
internal/storage/payments.go (5)

69-69: Good addition for tracking refunded payments
This map-based approach to record processed refunds is a neat way to avoid double-counting duplicate payment entries in the same batch.


73-73: Consistent naming
“paymentsCapturedSeen” aligns well with the rest of the naming scheme. No concerns here.


82-89: In-place initial amount adjustments
The logic for updating the InitialAmount in place is clear and helps avoid creating multiple rows for the same payment. This should prevent duplicate inserts.


91-98: Summation of partial refunds
Accumulates partial refund amounts under the same payment ID in the slice, ensuring the final database update correctly offsets the total. This effectively solves the PostgreSQL “a second time” update error.


100-107: Capture and refund reversal handling
Reusing the same approach for captures and reversed refunds (which add amounts back) keeps the logic consistent across payment status transitions.

internal/storage/payments_test.go (1)

577-592: Validating cumulative refund application
The test confirms that two consecutive refunds in the same batch yield the correct final amount (100 - 10 - 10 = 80). This checks the core objective of preventing duplicate rows and is a valuable addition to the suite.

paymentsRefunded := make([]payment, 0)
paymentsInitatialAmountToAdjustSeen := make(map[models.PaymentID]int)
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

Fix variable name typo
The variable paymentsInitatialAmountToAdjustSeen seems to have a spelling error. Renaming it to something like paymentsInitialAmountToAdjustSeen would improve readability.

- paymentsInitatialAmountToAdjustSeen := make(map[models.PaymentID]int)
+ paymentsInitialAmountToAdjustSeen := make(map[models.PaymentID]int)
📝 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
paymentsInitatialAmountToAdjustSeen := make(map[models.PaymentID]int)
paymentsInitialAmountToAdjustSeen := make(map[models.PaymentID]int)

Copy link
Contributor

@laouji laouji left a comment

Choose a reason for hiding this comment

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

The small typo correction suggested by coderabbit might not be bad to fix...

Sometimes, we can have two refunds for the same payment
inside the same batch, and postgres does not support it
and return an error 'command cannot affect row a second
time'
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: 0

🧹 Nitpick comments (2)
internal/storage/payments_test.go (2)

44-144: Add documentation to explain the test data setup.

The function creates a complex test scenario but lacks documentation explaining the purpose and structure of the test data. Consider adding a comment block explaining:

  • The purpose of having multiple entries with the same payment ID
  • The significance of the timing sequence
  • The expected final state after processing these payments

Add this documentation at the start of the function:

+// defaultPaymentsRefunded creates test data that simulates a payment with multiple refunds.
+// It generates three entries for the same payment:
+// 1. Initial payment of 100 USD
+// 2. First refund of 10 USD
+// 3. Second refund of 10 USD
+// The entries are created with different timestamps to test the handling of multiple refunds
+// in the same batch.
 func defaultPaymentsRefunded() []models.Payment {

Consider using different reference values for refunds.

While valid, using the same reference "test1" for both the original payment and refunds might not represent real-world scenarios accurately. Consider using distinct references for refunds to make the test more realistic.

-						Reference: "test1",
+						Reference: "refund1",
 						CreatedAt: now.Add(-59 * time.Minute).UTC().Time,
 						Status:    models.PAYMENT_STATUS_REFUNDED,
 					},
-					Reference: "test1",
+					Reference: "refund1",

577-591: Enhance test assertions for better coverage and clarity.

While the test correctly verifies the final amount, it could benefit from additional assertions to ensure the complete state is correct.

Consider expanding the test:

 	actual, err := store.PaymentsGet(ctx, pID1)
 	require.NoError(t, err)
-	// two refunds in the same batch, should be 100 - 10 - 10 = 80
-	require.Equal(t, big.NewInt(80), actual.Amount)
+	// Verify complete payment state after refunds
+	require.Equal(t, big.NewInt(80), actual.Amount, "Final amount should be 80 (100 - 10 - 10)")
+	require.Equal(t, big.NewInt(100), actual.InitialAmount, "Initial amount should remain unchanged")
+	require.Equal(t, models.PAYMENT_STATUS_REFUNDED, actual.Status, "Payment status should be REFUNDED")
+	require.Len(t, actual.Adjustments, 3, "Should have 3 adjustments (1 payment + 2 refunds)")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8d382b0 and 565f8bf.

📒 Files selected for processing (3)
  • internal/connectors/engine/activities/errors.go (0 hunks)
  • internal/storage/payments.go (2 hunks)
  • internal/storage/payments_test.go (2 hunks)
💤 Files with no reviewable changes (1)
  • internal/connectors/engine/activities/errors.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/storage/payments.go

@paul-nicolas paul-nicolas merged commit 1bb1c5b into main Jan 24, 2025
9 checks passed
@paul-nicolas paul-nicolas deleted the fix/payments-upsert branch January 24, 2025 15:07
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants