Skip to content

fix(ledger): api balance - #4185

Merged
GAlexIHU merged 2 commits into
mainfrom
fix/ledger-api-balance
Apr 20, 2026
Merged

GAlexIHU merged 2 commits into
mainfrom
fix/ledger-api-balance

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Fixes the displayed balance

  • both the values
  • and what currencies are returned

customerbalance test setup was also incorrect

Notes for reviewer

Summary by CodeRabbit

  • Bug Fixes

    • Customer credit balances now include zero-valued balances when no currency filter is specified.
    • Balance calculations improved by combining additional receivable components for more accurate settled/pending amounts.
  • New Features

    • Deterministic transaction cursor ordering for more consistent pagination and stable transaction pages.

@GAlexIHU
GAlexIHU requested a review from a team as a code owner April 20, 2026 14:52
@GAlexIHU GAlexIHU added the release-note/misc Miscellaneous changes label Apr 20, 2026
@coderabbitai

coderabbitai Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5ec41239-9d68-4140-90cf-02b981d3cede

📥 Commits

Reviewing files that changed from the base of the PR and between 2b6d01a and 2f1ef17.

📒 Files selected for processing (1)
  • cmd/server/wire_gen.go
✅ Files skipped from review due to trivial changes (1)
  • cmd/server/wire_gen.go

📝 Walkthrough

Walkthrough

Refactors customer balance service wiring and signatures: a new exported Service interface replaces the old FacadeService contract, concrete implementation is now unexported, GetBalance accepts currencyx.Code (not ledger.RouteFilter), receivable account balances are included in calculations, and the credits get_balance handler no longer skips zero balances when no currency filter is provided.

Changes

Cohort / File(s) Summary
Balance Handler
api/v3/handlers/customers/credits/get_balance.go
Removed conditional that skipped balances with zero settled+pending when request.Currencies.Codes is empty; all balancesByCurrency entries are now converted and appended.
Service Factory / Wiring
app/common/customerbalance.go, cmd/server/wire_gen.go
Factory signatures and local wiring updated to use the new customerbalance.Service interface and renamed local variables.
Facade Layer
openmeter/ledger/customerbalance/facade.go, openmeter/ledger/customerbalance/noop.go
Dropped local FacadeService interface; Facade and noop implementation now depend on the new Service interface and pass currency codes directly instead of ledger.RouteFilter.
Core Service Implementation
openmeter/ledger/customerbalance/service.go, openmeter/ledger/customerbalance/transactions.go
Introduced exported Service interface, renamed concrete type to unexported service; changed GetBalance signature to accept currencyx.Code, removed validate, and included receivable account balance in settled/pending computations; adjusted calls accordingly.
Cursor/Primitives
openmeter/ledger/primitives.go
Added TransactionCursor.Compare(other TransactionCursor) int for deterministic ordering (BookedAt → CreatedAt → ID).
Tests & Testenv
openmeter/ledger/customerbalance/*_test.go, openmeter/ledger/customerbalance/testenv_test.go, openmeter/ledger/testutils/integration.go
Test updates to new signatures and behavior: fund receivables in setups, use ledger collector-backed handlers, generate ULID customer IDs with explicit DB creation, adjust assertions and cursors, and strengthen test helpers/validations.
Minor refactors
openmeter/ledger/customerbalance/facade_test.go, openmeter/ledger/customerbalance/transactions_test.go
Small test-only changes (imports, variable initialization, minor assertions) to align with the refactor.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

area/billing

Suggested reviewers

  • turip
  • tothandras
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main objective: fixing balance display in the ledger API, addressing balance values and currency handling as described in the PR.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/ledger-api-balance

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

Comment @coderabbitai help to get the list of available commands and usage tips.

turip
turip previously approved these changes Apr 20, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 | 🟠 Major

Track running balances per currency for unfiltered pages.

When input.Currency is nil, a page can include transactions from multiple currencies. Line 133 seeds the running balance from items[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: Combined settled feeding 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 on settled would 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: Exported New returning unexported *service.

New is exported but returns *service, which trips the revive linter's unexported-return rule and forces callers to store it without being able to spell the type. Since you've already got the Service interface in place for exactly this abstraction, returning Service would 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: the ResolverDependencies literal is built three times.

Same {AccountService: base.Deps.ResolversService, SubAccountService: base.Deps.AccountService} value appears at the collectorService construction and inside both NewFlatFeeHandler / NewUsageBasedHandler calls. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4516800 and 2b6d01a.

📒 Files selected for processing (12)
  • api/v3/handlers/customers/credits/get_balance.go
  • app/common/customerbalance.go
  • openmeter/ledger/customerbalance/facade.go
  • openmeter/ledger/customerbalance/facade_test.go
  • openmeter/ledger/customerbalance/noop.go
  • openmeter/ledger/customerbalance/service.go
  • openmeter/ledger/customerbalance/service_test.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • openmeter/ledger/customerbalance/transactions.go
  • openmeter/ledger/customerbalance/transactions_test.go
  • openmeter/ledger/primitives.go
  • openmeter/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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 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/customerbalance

Repository: 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.go

Repository: 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.go

Repository: 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.

Comment on lines +263 to +268
func (e *testEnv) passTimeAfterServicePeriod(t *testing.T, servicePeriod timeutil.ClosedPeriod) {
t.Helper()

clock.SetTime(servicePeriod.To.Add(time.Second))
t.Cleanup(clock.ResetTime)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

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

@GAlexIHU
GAlexIHU merged commit 21c9564 into main Apr 20, 2026
36 of 39 checks passed
@GAlexIHU
GAlexIHU deleted the fix/ledger-api-balance branch April 20, 2026 15:40
@coderabbitai coderabbitai Bot mentioned this pull request May 18, 2026

This branch was previously deployed

1 inactive deployment
dev — 2f1ef17e Deployed Apr 20, 2026 by GAlexIHU via Migration Checks #13640
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants