Repository navigation
fix(ledger): api balance - #4185
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
📝 WalkthroughWalkthroughRefactors customer balance service wiring and signatures: a new exported Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant APIHandler as API Handler
participant Facade
participant BalanceService as customerbalance.Service
participant Ledger as HistoricalLedger
Client->>APIHandler: GET /customers/:id/credits (no currency filter)
APIHandler->>Facade: GetBalances(customerID, request)
Facade->>BalanceService: GetFBOCurrencies(customerID) / GetBalance(customerID, currency)
BalanceService->>Ledger: Query FBO account + Receivable account transactions
Ledger-->>BalanceService: FBO balances + Receivable balances
BalanceService-->>Facade: Combined ledger.Balance per currency
Facade-->>APIHandler: []CreditBalance (includes zero balances)
APIHandler-->>Client: 200 OK with balances
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 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 docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
openmeter/ledger/customerbalance/transactions.go (1)
132-139:⚠️ Potential issue | 🟠 MajorTrack running balances per currency for unfiltered pages.
When
input.Currencyis nil, a page can include transactions from multiple currencies. Line 133 seeds the running balance fromitems[0].Currency, and line 138 applies that same balance to every item, so before/after balances are wrong for the other currencies.🐛 Proposed fix
- if len(items) > 0 { - runningBalance, err := s.GetBalance(ctx, input.CustomerID, items[0].Currency, lo.ToPtr(result.Items[0].Cursor())) - if err != nil { - return ListCreditTransactionsResult{}, fmt.Errorf("get FBO balance after transaction %s: %w", result.Items[0].ID().ID, err) - } - - applyCreditTransactionBalances(items, runningBalance.Settled()) - } + runningBalances := make(map[currencyx.Code]alpacadecimal.Decimal) + for i := range items { + currency := items[i].Currency + runningBalance, ok := runningBalances[currency] + if !ok { + balance, err := s.GetBalance(ctx, input.CustomerID, currency, lo.ToPtr(result.Items[i].Cursor())) + if err != nil { + return ListCreditTransactionsResult{}, fmt.Errorf("get FBO balance after transaction %s: %w", result.Items[i].ID().ID, err) + } + + runningBalance = balance.Settled() + } + + items[i].Balance.After = runningBalance + items[i].Balance.Before = runningBalance.Sub(items[i].Amount) + runningBalances[currency] = items[i].Balance.Before + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/ledger/customerbalance/transactions.go` around lines 132 - 139, When input.Currency is nil the code seeds a single runningBalance from items[0].Currency and applies it to every item, which gives wrong before/after balances for other currencies; change the logic to collect the distinct currencies present in items and for each currency call s.GetBalance(ctx, input.CustomerID, currency, lo.ToPtr(result.Items[0].Cursor())) to obtain a per-currency runningBalance, then call applyCreditTransactionBalances only on the slice of items for that currency using that currency's runningBalance; update references around items, input.Currency, s.GetBalance, runningBalance and applyCreditTransactionBalances to process items grouped by currency.
🧹 Nitpick comments (3)
openmeter/ledger/customerbalance/service.go (2)
136-148: Combinedsettledfeeding pending — looks right, just worth a comment.Pending projection now uses
bookedBalance.Settled() + advanceBalance.Settled()as its starting point, which matches the PR intent of reflecting receivable-funded balance in what's available to draw against. Since the meaning of "settled" in this function changed (it's now "total usable"), a short doc comment onsettledwould save future readers a trip through the ledger package.📝 Suggested tiny doc tweak
- settled := bookedBalance.Settled().Add(advanceBalance.Settled()) + // settled = booked FBO settled + funded receivable (advance) settled; + // this is the amount available before pending charges are applied. + settled := bookedBalance.Settled().Add(advanceBalance.Settled())🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/ledger/customerbalance/service.go` around lines 136 - 148, The variable settled in service.go now represents the combined usable settled balance (bookedBalance.Settled() + advanceBalance.Settled()) which is then passed into CalculatePendingBalance; add a short doc comment above the settled assignment (or above the surrounding function) clarifying that "settled" here means the total usable/receivable-funded settled balance used as the starting point for pending projection, and mention that it is computed from bookedBalance.Settled() and advanceBalance.Settled(); reference s.getChargePendingBalanceImpacts, balanceCalculator.CalculatePendingBalance, and the settled variable to make the intent clear for future readers.
100-113: ExportedNewreturning unexported*service.
Newis exported but returns*service, which trips therevivelinter'sunexported-returnrule and forces callers to store it without being able to spell the type. Since you've already got theServiceinterface in place for exactly this abstraction, returningServicewould be the idiomatic fit—and the only test consumer (testenv_test.go) only calls interface methods on it anyway.♻️ Suggested refactor
-func New(config Config) (*service, error) { +func New(config Config) (Service, error) { if err := config.Validate(); err != nil { return nil, err } return &service{ ... }, nil }And in
testenv_test.go:- Service *service + Service Service🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/ledger/customerbalance/service.go` around lines 100 - 113, The exported constructor New currently returns an unexported concrete type *service which triggers the linter; change New's signature to return the exported Service interface instead of *service, construct and return the same &service{...} value but with the declared return type Service, and update any callers (e.g., tests that instantiate New, like in testenv_test.go) to accept the Service interface rather than the concrete type so callers compile without referencing the unexported service type.openmeter/ledger/customerbalance/testenv_test.go (1)
163-210: Small DRY opportunity: theResolverDependenciesliteral is built three times.Same
{AccountService: base.Deps.ResolversService, SubAccountService: base.Deps.AccountService}value appears at thecollectorServiceconstruction and inside bothNewFlatFeeHandler/NewUsageBasedHandlercalls. Pulling it into a local var would tighten this setup and make future dep changes a one-liner. Totally optional, but pleasant to read.♻️ Proposed refactor
+ resolverDeps := transactions.ResolverDependencies{ + AccountService: base.Deps.ResolversService, + SubAccountService: base.Deps.AccountService, + } + collectorService := ledgercollector.NewService(ledgercollector.Config{ - Ledger: base.Deps.HistoricalLedger, - Dependencies: transactions.ResolverDependencies{ - AccountService: base.Deps.ResolversService, - SubAccountService: base.Deps.AccountService, - }, + Ledger: base.Deps.HistoricalLedger, + Dependencies: resolverDeps, }) @@ flatFeeService, err := flatfeeservice.New(flatfeeservice.Config{ Adapter: flatFeeAdapter, - Handler: ledgerchargeadapter.NewFlatFeeHandler( - base.Deps.HistoricalLedger, - transactions.ResolverDependencies{ - AccountService: base.Deps.ResolversService, - SubAccountService: base.Deps.AccountService, - }, - collectorService, - ), + Handler: ledgerchargeadapter.NewFlatFeeHandler(base.Deps.HistoricalLedger, resolverDeps, collectorService), @@ usageService, err := usagebasedservice.New(usagebasedservice.Config{ Adapter: usageAdapter, - Handler: ledgerchargeadapter.NewUsageBasedHandler( - base.Deps.HistoricalLedger, - transactions.ResolverDependencies{ - AccountService: base.Deps.ResolversService, - SubAccountService: base.Deps.AccountService, - }, - collectorService, - ), + Handler: ledgerchargeadapter.NewUsageBasedHandler(base.Deps.HistoricalLedger, resolverDeps, collectorService),🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/ledger/customerbalance/testenv_test.go` around lines 163 - 210, The ResolverDependencies literal is duplicated in ledgercollector.NewService (collectorService) and in both ledgerchargeadapter.NewFlatFeeHandler and ledgerchargeadapter.NewUsageBasedHandler calls; extract that struct into a single local variable (e.g., resolverDeps := transactions.ResolverDependencies{AccountService: base.Deps.ResolversService, SubAccountService: base.Deps.AccountService}) and use resolverDeps in the three places (collectorService config and the two New*Handler calls) to remove repetition and make future changes one-line.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/ledger/customerbalance/facade.go`:
- Line 114: The code currently only calls f.service.GetFBOCurrencies for
currency discovery (line with GetFBOCurrencies) while GetBalance considers
receivables and pending charges; update GetBalances (the currency discovery
logic) to aggregate currencies from all relevant sources instead of only
FBO—e.g. call/merge results from GetFBOCurrencies plus the service methods that
return receivable/advance/pending-charge currencies (or a single service method
that returns all non-zero-balance currencies) and dedupe the list before
computing balances with GetBalance for each currency; also add a
unit/integration test that creates a receivable-only or advance-only balance (no
FBO activity) for a customerID and verifies that the currency is discovered and
returned by GetBalances/GetBalance.
In `@openmeter/ledger/customerbalance/testenv_test.go`:
- Around line 263-268: The helper passTimeAfterServicePeriod currently mutates
process-global state via clock.SetTime and clock.ResetTime which breaks safe
parallel tests; refactor it to avoid touching the global clock by accepting an
injected clock instance or setter/cleanup pair (e.g., add a parameter like clk
clock.Interface or setFunc/resetFunc) and use that for SetTime/ResetTime instead
of calling clock.SetTime/clock.ResetTime, updating all callers to pass the
test-local/mock clock, or alternatively document and enforce that tests using
passTimeAfterServicePeriod must not run in parallel (use t.Run without
t.Parallel and keep t.Cleanup(clock.ResetTime) if you choose the documentation
route).
---
Outside diff comments:
In `@openmeter/ledger/customerbalance/transactions.go`:
- Around line 132-139: When input.Currency is nil the code seeds a single
runningBalance from items[0].Currency and applies it to every item, which gives
wrong before/after balances for other currencies; change the logic to collect
the distinct currencies present in items and for each currency call
s.GetBalance(ctx, input.CustomerID, currency,
lo.ToPtr(result.Items[0].Cursor())) to obtain a per-currency runningBalance,
then call applyCreditTransactionBalances only on the slice of items for that
currency using that currency's runningBalance; update references around items,
input.Currency, s.GetBalance, runningBalance and applyCreditTransactionBalances
to process items grouped by currency.
---
Nitpick comments:
In `@openmeter/ledger/customerbalance/service.go`:
- Around line 136-148: The variable settled in service.go now represents the
combined usable settled balance (bookedBalance.Settled() +
advanceBalance.Settled()) which is then passed into CalculatePendingBalance; add
a short doc comment above the settled assignment (or above the surrounding
function) clarifying that "settled" here means the total
usable/receivable-funded settled balance used as the starting point for pending
projection, and mention that it is computed from bookedBalance.Settled() and
advanceBalance.Settled(); reference s.getChargePendingBalanceImpacts,
balanceCalculator.CalculatePendingBalance, and the settled variable to make the
intent clear for future readers.
- Around line 100-113: The exported constructor New currently returns an
unexported concrete type *service which triggers the linter; change New's
signature to return the exported Service interface instead of *service,
construct and return the same &service{...} value but with the declared return
type Service, and update any callers (e.g., tests that instantiate New, like in
testenv_test.go) to accept the Service interface rather than the concrete type
so callers compile without referencing the unexported service type.
In `@openmeter/ledger/customerbalance/testenv_test.go`:
- Around line 163-210: The ResolverDependencies literal is duplicated in
ledgercollector.NewService (collectorService) and in both
ledgerchargeadapter.NewFlatFeeHandler and
ledgerchargeadapter.NewUsageBasedHandler calls; extract that struct into a
single local variable (e.g., resolverDeps :=
transactions.ResolverDependencies{AccountService: base.Deps.ResolversService,
SubAccountService: base.Deps.AccountService}) and use resolverDeps in the three
places (collectorService config and the two New*Handler calls) to remove
repetition and make future changes one-line.
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: f4a9533d-6f4c-4c68-844b-7ad93e9b846a
📒 Files selected for processing (12)
api/v3/handlers/customers/credits/get_balance.goapp/common/customerbalance.goopenmeter/ledger/customerbalance/facade.goopenmeter/ledger/customerbalance/facade_test.goopenmeter/ledger/customerbalance/noop.goopenmeter/ledger/customerbalance/service.goopenmeter/ledger/customerbalance/service_test.goopenmeter/ledger/customerbalance/testenv_test.goopenmeter/ledger/customerbalance/transactions.goopenmeter/ledger/customerbalance/transactions_test.goopenmeter/ledger/primitives.goopenmeter/ledger/testutils/integration.go
💤 Files with no reviewable changes (1)
- api/v3/handlers/customers/credits/get_balance.go
| var err error | ||
|
|
||
| codes, err = f.service.getFBOCurrencies(ctx, input.CustomerID) | ||
| codes, err = f.service.GetFBOCurrencies(ctx, input.CustomerID) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Description: Inspect whether discovered customer-balance currencies come only from FBO routes.
# Expected: the implementation used by Facade.GetBalances should include every source that can make GetBalance non-zero.
rg -nP -C6 'func \([^)]*\)\s*GetFBOCurrencies|GetFBOCurrencies\s*\('
# Description: Check whether tests cover discovered balances where there is receivable/advance activity without an FBO balance.
# Expected: a GetBalances test without explicit currencies that sets up receivable-only or pending-only activity.
rg -nP -C4 'GetBalances|fundOpenReceivable|credit only charge with no starting credits|advance' openmeter/ledger/customerbalanceRepository: openmeterio/openmeter
Length of output: 28697
🏁 Script executed:
# Get full GetFBOCurrencies implementation
cat -n openmeter/ledger/customerbalance/service.go | sed -n '151,180p'Repository: openmeterio/openmeter
Length of output: 1269
🏁 Script executed:
# Check GetFBOCurrencies more thoroughly
rg -A20 'func \(s \*service\) GetFBOCurrencies' openmeter/ledger/customerbalance/service.goRepository: openmeterio/openmeter
Length of output: 902
🏁 Script executed:
# Look for all tests of GetBalances in facade, especially discovery scenarios
rg -B5 -A15 'facade\.GetBalances.*GetBalancesInput\{' openmeter/ledger/customerbalance/Repository: openmeterio/openmeter
Length of output: 5387
🏁 Script executed:
# Check if there's any way to create receivable activity in a currency without FBO
rg -B3 -A3 'fundOpenReceivable|ReceivableAccount' openmeter/ledger/customerbalance/service.goRepository: openmeterio/openmeter
Length of output: 301
Use all balance sources for currency discovery, not just FBO.
GetBalance includes receivable and pending charge impacts, but GetBalances discovery still relies only on GetFBOCurrencies. If a customer has advance activity (e.g., a credit-only charge with no starting credits) or receivable-only balances in a currency without any FBO activity, that currency won't be discovered and the non-zero balance will be omitted from the API response.
Add a test that creates a receivable-only or advance-only balance without FBO backing to ensure currency discovery captures all sources that can make GetBalance non-zero.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@openmeter/ledger/customerbalance/facade.go` at line 114, The code currently
only calls f.service.GetFBOCurrencies for currency discovery (line with
GetFBOCurrencies) while GetBalance considers receivables and pending charges;
update GetBalances (the currency discovery logic) to aggregate currencies from
all relevant sources instead of only FBO—e.g. call/merge results from
GetFBOCurrencies plus the service methods that return
receivable/advance/pending-charge currencies (or a single service method that
returns all non-zero-balance currencies) and dedupe the list before computing
balances with GetBalance for each currency; also add a unit/integration test
that creates a receivable-only or advance-only balance (no FBO activity) for a
customerID and verifies that the currency is discovered and returned by
GetBalances/GetBalance.
| func (e *testEnv) passTimeAfterServicePeriod(t *testing.T, servicePeriod timeutil.ClosedPeriod) { | ||
| t.Helper() | ||
|
|
||
| clock.SetTime(servicePeriod.To.Add(time.Second)) | ||
| t.Cleanup(clock.ResetTime) | ||
| } |
There was a problem hiding this comment.
Heads up on using a global clock in a shared helper.
clock.SetTime / clock.ResetTime mutates process-global state, so any test using this helper should not be run with t.Parallel() against other clock-sensitive tests. The t.Cleanup(clock.ResetTime) is a nice touch — just worth keeping in mind if parallelism ever gets flipped on in this package.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@openmeter/ledger/customerbalance/testenv_test.go` around lines 263 - 268, The
helper passTimeAfterServicePeriod currently mutates process-global state via
clock.SetTime and clock.ResetTime which breaks safe parallel tests; refactor it
to avoid touching the global clock by accepting an injected clock instance or
setter/cleanup pair (e.g., add a parameter like clk clock.Interface or
setFunc/resetFunc) and use that for SetTime/ResetTime instead of calling
clock.SetTime/clock.ResetTime, updating all callers to pass the test-local/mock
clock, or alternatively document and enforce that tests using
passTimeAfterServicePeriod must not run in parallel (use t.Run without
t.Parallel and keep t.Cleanup(clock.ResetTime) if you choose the documentation
route).
Overview
Fixes the displayed balance
customerbalancetest setup was also incorrectNotes for reviewer
Summary by CodeRabbit
Bug Fixes
New Features