Skip to content

Conversation

@laouji
Copy link
Contributor

@laouji laouji commented Aug 1, 2025

Fixes: PMNT-136

Hard to know when this changed, because there are also mentions of ending_before reversing the order of transactions returned, which was the case when we implemented this API. Now the docs say that the order of transactions are always returned in "reverse chronological order":

https://docs.stripe.com/api/pagination

Regarding the Refund fix:

Two adjustments indicating an initial amount of 116.26 and an adjustment of -35.00

-[ RECORD 1 ]----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
created_at | 2025-01-31 10:18:00
reference  | txn_3QnHIRP1LsJEPLtE1xO4Hmyb
amount     | 11625
status     | SUCCEEDED
raw        | {"amount":11625,"available_on":1738886400,"created":1738318680,"currency":"eur","description":"Payment for Invoice","exchange_rate":0,"fee":403,"fee_details":[{"amount":403,"application":"","currency":"eur","description":"Stripe processing fees","type":"stripe_fee"}],"id":"txn_3QnHIRP1LsJEPLtE1xO4Hmyb","net":11222,"object":"balance_transaction","reporting_category":"charge","source":{"id":"ch_3QnHIRP1LsJEPLtE1H05h57x","object":"charge"},"status":"available","type":"charge"}
-[ RECORD 2 ]----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
created_at | 2025-01-31 10:39:36
reference  | txn_3QnHIRP1LsJEPLtE1wtXyyhQ
amount     | 3500
status     | REFUNDED
raw        | {"amount":-3500,"available_on":1738886400,"created":1738319976,"currency":"eur","description":"REFUND FOR CHARGE (Payment for Invoice)","exchange_rate":0,"fee":0,"fee_details":[],"id":"txn_3QnHIRP1LsJEPLtE1wtXyyhQ","net":-3500,"object":"balance_transaction","reporting_category":"refund","source":{"id":"re_3QnHIRP1LsJEPLtE1NLCwcfF","object":"refund"},"status":"available","type":"refund"}

And the resulting payment:

-[ RECORD 1 ]----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
sort_id                | 123
id                     | eyJDb25uZWN0b3JJRCI6eyJQcm92aWRlciI6InN0cmlwZSIsIlJlZmVyZW5jZSI6IjA4MTVkYWIzLTIxZDAtNDM2Ny04YWExLThmODVkODAxZWM3OSJ9LCJSZWZlcmVuY2UiOiJ0eG5fM1FuSElSUDFMc0pFUEx0RTF4TzRIbXliIiwiVHlwZSI6IlBBWS1JTiJ9
connector_id           | eyJQcm92aWRlciI6InN0cmlwZSIsIlJlZmVyZW5jZSI6IjA4MTVkYWIzLTIxZDAtNDM2Ny04YWExLThmODVkODAxZWM3OSJ9
reference              | txn_3QnHIRP1LsJEPLtE1xO4Hmyb
created_at             | 2025-01-31 10:18:00
type                   | PAY-IN
initial_amount         | 11625
amount                 | 8125
asset                  | EUR/2
scheme                 | CARD_MASTERCARD
source_account_id      |
destination_account_id | eyJDb25uZWN0b3JJRCI6eyJQcm92aWRlciI6InN0cmlwZSIsIlJlZmVyZW5jZSI6IjA4MTVkYWIzLTIxZDAtNDM2Ny04YWExLThmODVkODAxZWM3OSJ9LCJSZWZlcmVuY2UiOiJyb290In0
metadata               | {}

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 1, 2025

Walkthrough

This update introduces helper functions to reverse the order of Stripe API results for accounts, bank accounts, and balance transactions, addressing Stripe's change to reverse chronological ordering. It also adds a logging field to the client, updates client instantiation to accept a logger, introduces a Backend interface with a generated mock, and adds new and updated tests.

Changes

Cohort / File(s) Change Summary
Account, Bank Account, and Transaction Ordering
.../client/accounts.go, .../client/external_accounts.go, .../client/payments.go
Added helper functions to reverse API result slices for accounts, bank accounts, and transactions.
Backend Interface and Mock
.../client/backend.go, .../client/backend_generated.go
Introduced a Backend interface and generated a GoMock mock for backend interaction.
Client Struct and Instantiation
.../client/client.go, .../client/plugin.go
Added a logger field to the client struct and updated instantiation to accept a logger argument.
Payments Logic
.../client/payments.go, .../stripe/payments.go
Changed payment translation logic to use the full charge amount, not net of refunds.
Testing
.../client/client_test.go, .../client/payments_test.go
Added new Ginkgo/Gomega-based tests for client and payments functionality.

Sequence Diagram(s)

sequenceDiagram
    participant Plugin
    participant Logger
    participant Client
    participant Backend
    participant StripeAPI

    Plugin->>Logger: Pass logger to Client.New
    Plugin->>Client: Instantiate client with logger, backend, apiKey
    Client->>Backend: Make API call (e.g., GetPayments)
    Backend->>StripeAPI: Perform HTTP request
    StripeAPI-->>Backend: Return data (reverse chronological order)
    Backend-->>Client: Return data
    Client->>Client: Reverse data order (restore chronological)
    Client->>Logger: Log debug info (e.g., latest ID, batch size)
    Client-->>Plugin: Return processed results
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–20 minutes

Assessment against linked issues

Objective Addressed Explanation
Correct handling of Stripe charge amounts in payment records (PMNT-136)
Refund adjustment should not update initial_amount in the payment (PMNT-136)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Introduction of Backend interface and GoMock-generated mock (backend.go, backend_generated.go) No objective in PMNT-136 requires a new backend abstraction or mocking; this is unrelated to charge/refund handling.
Addition of logger field and logger argument to client struct (client.go, plugin.go) Logger integration is not specified in PMNT-136; unrelated to payment amount calculation.
Addition of Ginkgo/Gomega-based test suite for client (client_test.go) General test scaffolding is not part of the objectives in PMNT-136.

Possibly related PRs

  • formancehq/payments#445: Adds a VerifyWebhook method, idempotency key handling, and test refactoring for Stripe plugins and clients.
  • formancehq/payments#306: Modifies control flow for empty Stripe account results; related to result ordering logic in accounts.go.

Suggested labels

build-images

Poem

A bunny hopped through Stripe's code,
Flipping lists from tail to head,
Now charges, banks, and logs all flow
In order—just as payments said!
With mocks and tests the fields are bright,
This patch brings data back to right.
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 134ab79 and dfa4946.

📒 Files selected for processing (10)
  • internal/connectors/plugins/public/stripe/client/accounts.go (1 hunks)
  • internal/connectors/plugins/public/stripe/client/backend.go (1 hunks)
  • internal/connectors/plugins/public/stripe/client/backend_generated.go (1 hunks)
  • internal/connectors/plugins/public/stripe/client/client.go (3 hunks)
  • internal/connectors/plugins/public/stripe/client/client_test.go (1 hunks)
  • internal/connectors/plugins/public/stripe/client/external_accounts.go (1 hunks)
  • internal/connectors/plugins/public/stripe/client/payments.go (2 hunks)
  • internal/connectors/plugins/public/stripe/client/payments_test.go (1 hunks)
  • internal/connectors/plugins/public/stripe/payments.go (1 hunks)
  • internal/connectors/plugins/public/stripe/plugin.go (1 hunks)
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: fguery
PR: formancehq/payments#427
File: internal/connectors/plugins/public/qonto/transfers.go:123-145
Timestamp: 2025-05-19T15:19:31.674Z
Learning: In the Qonto connector (and possibly other payment connectors), transfers are initially created with PAYMENT_STATUS_PENDING status regardless of the API response status. They are only marked as completed when they are later retrieved via the fetch payments endpoint. This is an intentional design to ensure consistent status transitions.
📚 Learning: the `balance` struct in `internal/connectors/plugins/public/dummypay/client/client.go` is only used ...
Learnt from: laouji
PR: formancehq/payments#193
File: internal/connectors/plugins/public/dummypay/client/client.go:104-131
Timestamp: 2024-12-12T12:45:27.164Z
Learning: The `Balance` struct in `internal/connectors/plugins/public/dummypay/client/client.go` is only used in tests, so changing `AmountInMinors` from `int64` to `*big.Int` is not necessary.

Applied to files:

  • internal/connectors/plugins/public/stripe/plugin.go
  • internal/connectors/plugins/public/stripe/payments.go
  • internal/connectors/plugins/public/stripe/client/client_test.go
  • internal/connectors/plugins/public/stripe/client/external_accounts.go
  • internal/connectors/plugins/public/stripe/client/payments.go
  • internal/connectors/plugins/public/stripe/client/client.go
  • internal/connectors/plugins/public/stripe/client/backend_generated.go
  • internal/connectors/plugins/public/stripe/client/payments_test.go
📚 Learning: the qonto connector plugin has unit tests for fetchnextbalances in internal/connectors/plugins/publi...
Learnt from: fguery
PR: formancehq/payments#427
File: internal/connectors/plugins/public/qonto/balances.go:20-55
Timestamp: 2025-05-15T16:35:29.660Z
Learning: The Qonto connector plugin has unit tests for fetchNextBalances in internal/connectors/plugins/public/qonto/balances_test.go, covering success cases, missing FromPayload, invalid JSON handling, and other error conditions.

Applied to files:

  • internal/connectors/plugins/public/stripe/client/client_test.go
  • internal/connectors/plugins/public/stripe/client/payments.go
  • internal/connectors/plugins/public/stripe/client/backend_generated.go
  • internal/connectors/plugins/public/stripe/client/payments_test.go
📚 Learning: in `test/e2e/api_accounts_test.go`, the `subscribe` function already includes error handling, so it'...
Learnt from: laouji
PR: formancehq/payments#193
File: test/e2e/api_accounts_test.go:97-106
Timestamp: 2024-12-12T11:00:02.458Z
Learning: In `test/e2e/api_accounts_test.go`, the `Subscribe` function already includes error handling, so it's unnecessary to add additional error handling when calling it in tests.

Applied to files:

  • internal/connectors/plugins/public/stripe/client/client_test.go
  • internal/connectors/plugins/public/stripe/client/payments_test.go
📚 Learning: in the v2bankaccountmessagepayload struct, the relatedaccounts field is intentionally mapped to json...
Learnt from: paul-nicolas
PR: formancehq/payments#394
File: internal/events/bank_account.go:33-42
Timestamp: 2025-04-01T11:39:55.104Z
Learning: In the V2BankAccountMessagePayload struct, the RelatedAccounts field is intentionally mapped to JSON field "adjustments" rather than "relatedAccounts" for backward compatibility with v2 API.

Applied to files:

  • internal/connectors/plugins/public/stripe/client/external_accounts.go
  • internal/connectors/plugins/public/stripe/client/accounts.go
📚 Learning: the debug flag in the payments service is primarily used to control the visibility of dummypay in co...
Learnt from: laouji
PR: formancehq/payments#316
File: internal/api/services/accounts_list_test.go:22-22
Timestamp: 2025-02-06T13:29:29.038Z
Learning: The debug flag in the payments service is primarily used to control the visibility of dummypay in configurations, and this behavior is tested in internal/connectors/plugins/registry/plugins_test.go.

Applied to files:

  • internal/connectors/plugins/public/stripe/client/payments_test.go
🧬 Code Graph Analysis (1)
internal/connectors/plugins/public/stripe/plugin.go (1)
internal/connectors/plugins/public/stripe/client/client.go (1)
  • New (47-62)
⏰ 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). (2)
  • GitHub Check: Cursor Bugbot
  • GitHub Check: Tests
🔇 Additional comments (17)
internal/connectors/plugins/public/stripe/payments.go (1)

121-121: LGTM! Fixes payment amount calculation as per PR objectives.

This change correctly addresses the issue identified in PMNT-136 where the original payment adjustment was using the wrong field. By setting the amount directly to balanceTransaction.Source.Charge.Amount instead of subtracting AmountRefunded, the payment record will now accurately reflect the initial charge amount, while refunds will be handled separately as distinct transactions.

internal/connectors/plugins/public/stripe/client/client_test.go (1)

1-13: LGTM! Standard Ginkgo test suite setup.

Clean and proper setup for the Stripe client test suite using Ginkgo and Gomega testing frameworks.

internal/connectors/plugins/public/stripe/plugin.go (1)

36-36: LGTM! Fixes client constructor call to match expected signature.

This change correctly passes the logger parameter to client.New(), enabling logging capabilities in the Stripe client and aligning with the updated constructor signature.

internal/connectors/plugins/public/stripe/client/client.go (3)

7-7: LGTM! Adds necessary logging import.


36-36: LGTM! Adds logger field to client struct.

This enables logging capabilities throughout the Stripe client operations.


47-47: LGTM! Updates constructor to accept and assign logger.

The function signature correctly accepts the logger parameter and properly assigns it to the client struct, enabling consistent logging across client operations.

Also applies to: 54-54

internal/connectors/plugins/public/stripe/client/external_accounts.go (2)

54-55: LGTM! Correctly applies data reversal for Stripe API ordering.

This change addresses Stripe's API behavior of returning data in reverse chronological order, as mentioned in the PR objectives.


63-71: LGTM! Well-implemented helper function for reversing bank accounts.

The reverseBankAccounts function correctly:

  • Creates a copy to avoid mutating the original slice
  • Uses efficient two-pointer reversal algorithm
  • Includes clear documentation explaining the Stripe API behavior
internal/connectors/plugins/public/stripe/client/accounts.go (2)

42-43: LGTM! Clean integration of reversal logic.

The change correctly integrates the new reverseAccounts helper function to handle Stripe's API ordering changes while maintaining the existing logic flow.


53-60: LGTM! Correct reversal implementation.

The reverseAccounts function is implemented correctly with:

  • Proper copy creation to avoid input mutation
  • Standard two-pointer reversal algorithm
  • Clear documentation of the Stripe API behavior change
internal/connectors/plugins/public/stripe/client/payments.go (3)

68-69: LGTM! Consistent reversal implementation.

The integration of reverseTransactions follows the same clean pattern as the accounts implementation, correctly handling Stripe's API ordering change.


75-75: LGTM! Useful debug logging addition.

The debug log provides valuable information for troubleshooting timeline progression and batch processing, including account ID, latest ID, and batch size.


91-98: LGTM! Correct reversal implementation.

The reverseTransactions function correctly implements the same reversal pattern as reverseAccounts, with proper copying and two-pointer reversal algorithm.

internal/connectors/plugins/public/stripe/client/backend.go (1)

10-17: LGTM! Well-designed backend abstraction.

The Backend interface provides a clean abstraction for Stripe API calls with:

  • Comprehensive method coverage (Call, CallStreaming, CallRaw, CallMultipart, SetMaxNetworkRetries)
  • Proper use of Stripe SDK types for type safety
  • Correctly configured mock generation directive
  • Clear separation of concerns for better testability
internal/connectors/plugins/public/stripe/client/payments_test.go (2)

37-49: LGTM! Proper error handling test.

The test correctly verifies that backend errors are properly propagated through the GetPayments method.


51-93: LGTM! Comprehensive success scenario test.

The test effectively verifies:

  • Chronological ordering of results (validates reversal logic)
  • Timeline latest ID update to the newest entry
  • Pagination status handling
  • Proper mock data setup that simulates Stripe's reverse chronological response

The test design correctly provides reversed data in the mock to verify that the reversal function produces chronological output.

internal/connectors/plugins/public/stripe/client/backend_generated.go (1)

1-111: LGTM! Properly generated mock implementation.

This is a correctly generated GoMock implementation that provides complete mock functionality for the Backend interface. The generated code includes all necessary methods and follows proper GoMock patterns.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch PMNT-136

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.
  • 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate unit tests to generate unit tests for 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.

@codecov
Copy link

codecov bot commented Aug 1, 2025

Codecov Report

❌ Patch coverage is 12.50000% with 28 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.70%. Comparing base (2688aea) to head (ac749de).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...onnectors/plugins/public/stripe/client/payments.go 0.00% 10 Missing ⚠️
...onnectors/plugins/public/stripe/client/accounts.go 0.00% 9 Missing ⚠️
.../plugins/public/stripe/client/external_accounts.go 0.00% 9 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #505      +/-   ##
==========================================
- Coverage   68.75%   68.70%   -0.06%     
==========================================
  Files         715      715              
  Lines       36816    36846      +30     
==========================================
+ Hits        25313    25315       +2     
- Misses      10182    10209      +27     
- Partials     1321     1322       +1     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@laouji laouji marked this pull request as ready for review August 4, 2025 07:49
@laouji laouji requested a review from a team as a code owner August 4, 2025 07:49
Copy link
Contributor

@fguery fguery left a comment

Choose a reason for hiding this comment

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

Question -- how did we detect this change?
Can we / should we have some contract testing?

@fguery
Copy link
Contributor

fguery commented Aug 4, 2025

COntract testing as in more like "monitoring testing" -- run a set of queries, make sure the response don't change.

@laouji
Copy link
Contributor Author

laouji commented Aug 4, 2025

Question -- how did we detect this change?

I was testing something unrelated and realized that it was wonky 🙁

COntract testing as in more like "monitoring testing" -- run a set of queries, make sure the response don't change.

I guess we'd have to set up some tests that run against the actual PSP using hardcoded tokens? We could maybe do that in a private repo to avoid leaking tokens. If you have some specific ideas might be worth exploring.

@fguery
Copy link
Contributor

fguery commented Aug 4, 2025

Question -- how did we detect this change?

I was testing something unrelated and realized that it was wonky 🙁

COntract testing as in more like "monitoring testing" -- run a set of queries, make sure the response don't change.

I guess we'd have to set up some tests that run against the actual PSP using hardcoded tokens? We could maybe do that in a private repo to avoid leaking tokens. If you have some specific ideas might be worth exploring.

Yeah that's what I mean.
I don't have a specific idea (beside what you're saying -- create a repo, and run queries using the sandbox token (ideally prod but I think we're fine with sandbox too))

@laouji laouji added this pull request to the merge queue Aug 4, 2025
Merged via the queue into main with commit 1a0e74b Aug 4, 2025
7 checks passed
@laouji laouji deleted the PMNT-136 branch August 4, 2025 09:58
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