Skip to content

feat(creditpurchase): resolve cost basis before realization - #4918

Merged
turip merged 5 commits into
mainfrom
feat/creditpurchase-initial-costbasis-resolution
Aug 13, 2026
Merged

turip merged 5 commits into
mainfrom
feat/creditpurchase-initial-costbasis-resolution

Conversation

@turip

@turip turip commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

Business context

A credit purchase grants credits now and settles their monetary value through either an invoice or an external payment. When those credits use a custom currency, OpenMeter must pin the exchange rate used for the purchase so the granted credits, the customer-facing settlement amount, and later ledger activity all refer to the same value.

This change completes that cost-basis flow for credit purchases and aligns it with the behavior already used by usage-based and flat-fee charges.

Flow

  1. A fiat credit purchase starts with its fixed fiat cost basis. A custom-currency purchase starts with a manual, pinned, or dynamic cost-basis intent.
  2. Manual and pinned purchases have their cost basis available immediately. Dynamic purchases remain unresolved while they are only being previewed; their provisional invoice amount is therefore zero.
  3. When the purchase becomes active and OpenMeter is about to grant credits, the dynamic cost basis is resolved using the beginning of the purchase service period.
  4. The resolved cost basis is pinned to the purchase before any credits are granted.
  5. Invoice and externally settled purchases then use that same pinned value for the fiat settlement amount, payment lifecycle, and ledger entries.

If resolution fails, the purchase does not grant credits or advance into its active payment lifecycle. This prevents a purchase from being realized with an unknown or inconsistent monetary value.

What this enables

  • consistent cost-basis pinning across credit purchases, usage-based charges, and flat-fee charges
  • dynamic custom-currency credit purchases through both invoice and external settlement flows
  • a single pinned value for credit grants, customer-facing settlement amounts, and ledger activity
  • safe invoice previews before a dynamic rate is known

Ticket: OM-436

Validation

  • make test-nocache
  • make lint-go-fast
  • focused credit-purchase domain, adapter, service, and end-to-end tests after the review fixes

Greptile Summary

This PR adds durable cost-basis resolution for credit purchases before their first monetary realization.

  • Represents purchase cost basis as either a fiat scalar or shared custom-currency intent and state.
  • Resolves dynamic cost basis at invoice or external-settlement lifecycle boundaries.
  • Updates invoice lines, ledger operations, API conversion, and lifecycle tests to consume resolved fiat amounts.

Confidence Score: 5/5

The PR appears safe to merge because no blocking failure remains within the eligible follow-up review scope.

No blocking failure remains.

Important Files Changed

Filename Overview
openmeter/billing/charges/creditpurchase/service/costbasis.go Resolves initial and dynamic custom-currency cost basis and persists the resulting pinned state.
openmeter/billing/charges/creditpurchase/service/lineengine.go Supports provisional gathering lines and populates standard invoice lines after lifecycle resolution.
openmeter/billing/charges/creditpurchase/adapter/costbasis.go Adds namespace- and ownership-scoped persistence for resolved credit-purchase cost basis.
openmeter/billing/charges/creditpurchase/charge.go Defines resolved charge-state validation and fiat settlement amount calculation.
openmeter/ledger/chargeadapter/creditpurchase.go Updates ledger realization to consume the charge's resolved monetary state.
api/v3/handlers/customers/credits/convert.go Maps resolved settlement currency, amount, and per-unit cost basis into credit-grant API responses.

Sequence Diagram

sequenceDiagram
  participant Client
  participant CreditPurchase
  participant CostBasisResolver
  participant InvoiceEngine
  participant Ledger
  Client->>CreditPurchase: Create funded credit purchase
  alt Fiat, manual, or pinned
    CreditPurchase->>CreditPurchase: Materialize resolved state
  else Dynamic custom currency
    CreditPurchase->>CreditPurchase: Persist unresolved intent
  end
  CreditPurchase->>InvoiceEngine: Create provisional gathering line
  InvoiceEngine->>CreditPurchase: Standard invoice created
  CreditPurchase->>CostBasisResolver: Resolve at service-period start
  CostBasisResolver-->>CreditPurchase: Pinned fiat conversion rate
  CreditPurchase->>Ledger: Grant purchased credits
  CreditPurchase-->>InvoiceEngine: Replace line with resolved amount
  InvoiceEngine->>CreditPurchase: Authorization and settlement events
Loading

Reviews (5): Last reviewed commit: "feat(creditpurchase): resolve dynamic co..." | Re-trigger Greptile

Context used:

Summary by CodeRabbit

  • New Features

    • Added dynamic, manual, pinned, and fiat cost-basis support for credit purchases.
    • Dynamic cost bases resolve at service-period start and retain resolved values.
    • Invoice lines support provisional zero-value amounts until resolution.
    • Added fiat settlement amount calculation with currency conversion and rounding.
  • Bug Fixes

    • Improved validation for currencies, cost bases, settlement amounts, and charge references.
    • Restricted cost-basis updates to the owning charge.
    • Promotional credit grants now process independently of payment settlement.

@turip
turip requested a review from a team as a code owner August 11, 2026 13:49
@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d37ed144-4e7c-47d2-a5ee-aa89fd1ee3e0

📥 Commits

Reviewing files that changed from the base of the PR and between f339085 and 7d0ed34.

📒 Files selected for processing (15)
  • api/v3/handlers/customers/credits/convert.go
  • openmeter/billing/charges/README.md
  • openmeter/billing/charges/creditpurchase/adapter.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/costbasis.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper_test.go
  • openmeter/billing/charges/creditpurchase/charge_test.go
  • openmeter/billing/charges/creditpurchase/service/costbasis.go
  • openmeter/billing/charges/creditpurchase/service/create.go
  • openmeter/billing/charges/creditpurchase/service/invoice_test.go
  • openmeter/billing/charges/meta/customcurrency.go
  • openmeter/billing/charges/meta/customcurrency_test.go
  • openmeter/billing/charges/service/creditpurchase_costbasis_test.go
  • openmeter/billing/charges/service/creditpurchase_test.go
  • test/credits/creditpurchase_costbasis_test.go
🚧 Files skipped from review as they are similar to previous changes (8)
  • openmeter/billing/charges/creditpurchase/service/create.go
  • openmeter/billing/charges/creditpurchase/service/costbasis.go
  • openmeter/billing/charges/README.md
  • openmeter/billing/charges/meta/customcurrency.go
  • openmeter/billing/charges/service/creditpurchase_costbasis_test.go
  • openmeter/billing/charges/creditpurchase/charge_test.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper_test.go
  • openmeter/billing/charges/creditpurchase/service/invoice_test.go

📝 Walkthrough

Walkthrough

Credit purchases now resolve and persist cost-basis state across creation, invoice processing, payment settlement, and credit issuance. Dynamic custom-currency purchases can remain unresolved until the service period starts.

Changes

Credit purchase cost-basis lifecycle

Layer / File(s) Summary
Service wiring and contracts
openmeter/billing/charges/creditpurchase/service/..., openmeter/billing/charges/creditpurchase/adapter.go, openmeter/billing/charges/models/costbasis/..., app/common/charges.go, test/credits/...
The service receives a currencies dependency. Cost-basis inputs use value-based fields and explicit validation.
Cost-basis resolution and persistence
openmeter/billing/charges/creditpurchase/service/costbasis.go, openmeter/billing/charges/creditpurchase/adapter/..., openmeter/billing/charges/creditpurchase/charge.go
Initial and dynamic resolution produces persisted state. Custom-currency state includes a charge cost-basis identifier and resolved timestamp.
Settlement and invoice flow
openmeter/billing/charges/creditpurchase/service/{create.go,lineengine.go,invoice.go,external.go}, openmeter/ledger/chargeadapter/creditpurchase.go, openmeter/billing/charges/meta/customcurrency.go
Unresolved dynamic cost bases produce provisional zero-value invoice lines. Resolved charges provide settlement currency and fiat amounts for authorization, settlement, and credit issuance.
Promotional grants and validation coverage
openmeter/billing/charges/creditpurchase/service/realizations/..., openmeter/billing/charges/service/creditpurchase_costbasis_test.go, test/credits/creditpurchase_costbasis_test.go, openmeter/billing/charges/README.md
Promotional grants move to the realizations service. Tests cover resolution, persistence, replacement, lifecycle transitions, invoice previews, and currency validation. Documentation describes the updated state model.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CreditPurchaseService
  participant CostBasisResolver
  participant ChargeAdapter
  participant InvoiceOrPaymentFlow
  CreditPurchaseService->>CostBasisResolver: resolve initial or service-period cost basis
  CostBasisResolver-->>CreditPurchaseService: return resolved or unresolved state
  CreditPurchaseService->>ChargeAdapter: create or update charge state
  InvoiceOrPaymentFlow->>ChargeAdapter: authorize, settle, or grant credits
  ChargeAdapter-->>InvoiceOrPaymentFlow: use resolved cost basis and settlement fiat currency
Loading
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: resolving credit-purchase cost basis before realization.
✨ 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 feat/creditpurchase-initial-costbasis-resolution

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.

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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@openmeter/billing/charges/creditpurchase/costbasis_test.go`:
- Around line 155-197: Add a case in the “fiat resolved state matches immutable
intent” test that copies validState, changes ResolvedAt to differ from
createdAt, and calls ChargeBase.validateCostBasis with that state. Assert the
validation error contains “time must match charge creation time”, while
preserving the existing valid, rate-mismatch, source, and missing-state cases.
🪄 Autofix

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 Plus

Run ID: 9ee13000-e9fa-424b-8b44-bd9f6dad588a

📥 Commits

Reviewing files that changed from the base of the PR and between 00b1172 and 87cefa5.

📒 Files selected for processing (23)
  • app/common/charges.go
  • openmeter/billing/charges/README.md
  • openmeter/billing/charges/creditpurchase/adapter.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper_test.go
  • openmeter/billing/charges/creditpurchase/charge.go
  • openmeter/billing/charges/creditpurchase/charge_test.go
  • openmeter/billing/charges/creditpurchase/costbasis.go
  • openmeter/billing/charges/creditpurchase/costbasis_test.go
  • openmeter/billing/charges/creditpurchase/service/costbasis.go
  • openmeter/billing/charges/creditpurchase/service/create.go
  • openmeter/billing/charges/creditpurchase/service/external_test.go
  • openmeter/billing/charges/creditpurchase/service/service.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/creditpurchase_costbasis_test.go
  • openmeter/billing/charges/service/creditpurchase_test.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
  • openmeter/ledger/customerbalance/service_test.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • test/credits/base.go
  • test/credits/creditgrant_test.go

@turip turip added release-note/feature Release note: Exciting New Features area/billing labels Aug 11, 2026
@turip turip changed the title feat(creditpurchase): resolve initial cost basis feat(creditpurchase): resolve cost basis before realization Aug 12, 2026
@turip
turip force-pushed the feat/creditpurchase-initial-costbasis-resolution branch from 237edb1 to f339085 Compare August 12, 2026 12:34

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

🧹 Nitpick comments (7)
openmeter/ledger/chargeadapter/creditpurchase.go (1)

80-91: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

These twelve lines are now identical in both payment handlers. The unresolved-state precondition, the settlement fiat lookup, and the costBasis extraction repeat verbatim in OnCreditPurchasePaymentAuthorized and OnCreditPurchasePaymentSettled. A small named helper would keep the two handlers in step if the precondition ever changes, and the name captures real domain meaning rather than being a pass-through.

♻️ Suggested helper
// resolvedSettlementBasis returns the settlement currency and resolved cost
// basis for a payment-backed credit purchase. It fails the precondition when
// cost-basis resolution has not happened yet, because the ledger cannot
// denominate the payment without it.
func resolvedSettlementBasis(charge chargecreditpurchase.Charge) (currencyx.Code, alpacadecimal.Decimal, error) {
	if charge.State.ResolvedCostBasis == nil {
		return "", alpacadecimal.Zero, models.NewGenericPreConditionFailedError(
			fmt.Errorf("credit purchase charge[%s] cost basis is unresolved", charge.ID),
		)
	}

	fiatCurrency, err := charge.Intent.GetSettlementFiatCurrency()
	if err != nil {
		return "", alpacadecimal.Zero, fmt.Errorf("get settlement fiat currency: %w", err)
	}

	return currencyx.Code(fiatCurrency.GetFiatCode()), charge.State.ResolvedCostBasis.CostBasis, nil
}

Each handler then becomes:

-	if charge.State.ResolvedCostBasis == nil {
-		return ledgertransaction.GroupReference{}, models.NewGenericPreConditionFailedError(
-			fmt.Errorf("credit purchase charge[%s] cost basis is unresolved", charge.ID),
-		)
-	}
-
-	fiatCurrency, err := charge.Intent.GetSettlementFiatCurrency()
-	if err != nil {
-		return ledgertransaction.GroupReference{}, fmt.Errorf("get settlement fiat currency: %w", err)
-	}
-
-	costBasis := charge.State.ResolvedCostBasis.CostBasis
+	settlementCurrency, costBasis, err := resolvedSettlementBasis(charge)
+	if err != nil {
+		return ledgertransaction.GroupReference{}, err
+	}

The later settlementCurrency := currencyx.Code(fiatCurrency.GetFiatCode()) line then drops out of both handlers.

As per coding guidelines: "Do not hide type switching, validation, persistence mapping, or meaningful domain translation inside local closures; use named helpers."

Also applies to: 166-177

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/ledger/chargeadapter/creditpurchase.go` around lines 80 - 91,
Extract the duplicated unresolved-cost-basis validation, settlement fiat lookup,
and cost-basis extraction from OnCreditPurchasePaymentAuthorized and
OnCreditPurchasePaymentSettled into a named resolvedSettlementBasis helper. Have
it return the settlement currency and resolved cost basis, preserving the
existing precondition and wrapped currency lookup errors, then update both
handlers to use it and remove their redundant conversion logic.

Source: Coding guidelines

openmeter/billing/charges/creditpurchase/adapter/mapper_test.go (1)

34-46: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Small tightening idea. The other subtests pin ResolvedAt to an exact timestamp, but this one only asserts it is non-zero. Since the fiat path reconstructs resolution time from the charge row, asserting the exact value would document which row field it comes from and would catch a future switch to, say, UpdatedAt or clock.Now().

♻️ Suggested assertion
-		require.False(t, mapped.ResolvedCostBasis.ResolvedAt.IsZero())
+		require.Equal(t, createdAt, mapped.ResolvedCostBasis.ResolvedAt)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/creditpurchase/adapter/mapper_test.go` around lines
34 - 46, Update the “dedicated fiat materializes resolved state” subtest around
fromDBCostBasis to assert ResolvedCostBasis.ResolvedAt equals the charge row’s
CreatedAt value, replacing the non-zero check. Preserve the existing assertions
and use the existing createdAt fixture to document the source timestamp.
openmeter/billing/charges/creditpurchase/charge_test.go (1)

112-153: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Solid table test — one branch is still uncovered. GetFiatSettlementAmount gained a new guard that returns "cost basis is unresolved" when State.ResolvedCostBasis is nil. That guard sits on a monetary path, and nothing here exercises it. A tiny subtest would lock it in.

💚 Suggested extra subtest
t.Run("unresolved cost basis has no settlement amount", func(t *testing.T) {
	charge := Charge{ChargeBase: ChargeBase{Intent: testCases["fiat purchase"]}}

	_, err := charge.GetFiatSettlementAmount()
	require.ErrorContains(t, err, "cost basis is unresolved")
})

As per path instructions: "Make sure the tests are comprehensive and cover the changes."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/creditpurchase/charge_test.go` around lines 112 -
153, Add a subtest to TestChargeGetFiatSettlementAmount that constructs a charge
from the existing “fiat purchase” case without State.ResolvedCostBasis, calls
GetFiatSettlementAmount, and asserts the error contains “cost basis is
unresolved”.

Source: Path instructions

openmeter/billing/charges/meta/customcurrency.go (1)

28-37: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Consider rejecting non-positive cost basis, not only zero.

IsZero() lets a negative resolvedCostBasis through. The result is then a negative fiat amount, which contradicts the amount.IsNegative() guard right above it. The internal caller here validates ResolvedCostBasis first, but Charge.GetFiatSettlementAmount in openmeter/billing/charges/creditpurchase/charge.go passes c.State.ResolvedCostBasis.CostBasis straight through. A positivity check keeps this exported helper safe for every caller.

Also worth a thought: fiatCurrency is a pointer and is used without a nil check. Both current callers error-check before calling, so this is only about future callers.

♻️ Suggested tightening
 func CalculateFiatAmount(amount, resolvedCostBasis alpacadecimal.Decimal, fiatCurrency *currencyx.FiatCurrency) (alpacadecimal.Decimal, error) {
+	if fiatCurrency == nil {
+		return alpacadecimal.Zero, errors.New("fiat currency is required")
+	}
+
 	if amount.IsNegative() {
-		return alpacadecimal.Zero, fmt.Errorf("amount cannot be negative")
+		return alpacadecimal.Zero, errors.New("amount cannot be negative")
 	}
 
-	if resolvedCostBasis.IsZero() {
-		return alpacadecimal.Zero, fmt.Errorf("resolved cost basis cannot be zero")
+	if !resolvedCostBasis.IsPositive() {
+		return alpacadecimal.Zero, errors.New("resolved cost basis must be positive")
 	}

Note: the message change would need the test at openmeter/billing/charges/meta/customcurrency_test.go line 130 updated too.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/meta/customcurrency.go` around lines 28 - 37,
Update CalculateFiatAmount to reject any non-positive resolvedCostBasis,
including negative values, and adjust the validation error message accordingly.
Preserve the existing amount validation and fiat rounding behavior, and update
the affected custom-currency test expectation to match the new message.
openmeter/billing/charges/service/creditpurchase_costbasis_test.go (2)

105-124: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prefer InexactFloat64() for the new cost-basis decimal assertions. Both new test files assert alpacadecimal.Decimal values by struct equality. That compares the internal representation, so a numerically equal value with a different exponent after a Postgres numeric round-trip would fail. All the values involved (0.25, 0.5, 25, 100) permit float comparison.

  • openmeter/billing/charges/service/creditpurchase_costbasis_test.go#L105-L124: compare ResolvedCostBasis.CostBasis and the persisted round-trip through InexactFloat64(); do the same for the &replacement struct comparisons on lines 312 and 333.
  • test/credits/creditpurchase_costbasis_test.go#L174-L187: compare line.Totals.Amount, line.Totals.Total, DetailedLines[0].Quantity, DetailedLines[0].PerUnitAmount, and ResolvedCostBasis.CostBasis through InexactFloat64(); apply the same change to the balance and FiatAmount assertions in the remaining subtests.

As per coding guidelines: "When precision permits, compare alpacadecimal.Decimal through InexactFloat64() with require.Equal; inline one-off expected balances."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/service/creditpurchase_costbasis_test.go` around
lines 105 - 124, Update decimal assertions in
openmeter/billing/charges/service/creditpurchase_costbasis_test.go:105-124 and
the replacement comparisons around lines 312 and 333, plus
test/credits/creditpurchase_costbasis_test.go:174-187 and its remaining
balance/FiatAmount subtests, to compare alpacadecimal.Decimal values via
InexactFloat64() with require.Equal rather than struct equality; inline one-off
expected balances where applicable.

Source: Coding guidelines


105-107: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Compare the decimals through InexactFloat64().

s.Equal on alpacadecimal.Decimal compares the internal representation, not the numeric value. Lines 105 and 123 compare rates that round-tripped through the Postgres numeric column, so an equal value with a different exponent would fail the assertion. The rest of the credit-purchase suite already uses InexactFloat64() for this reason, and the precision here (0.25, 0.5) permits it.

💚 Suggested tweak
-			s.Equal(test.expectedRate, created.Charge.State.ResolvedCostBasis.CostBasis)
+			s.Equal(test.expectedRate.InexactFloat64(), created.Charge.State.ResolvedCostBasis.CostBasis.InexactFloat64())
 			s.Equal(test.expectedCurrencyCostBasis, created.Charge.State.ResolvedCostBasis.CostBasisID)
-			s.Equal(created.Charge.State.ResolvedCostBasis.CostBasis, persisted[0].State.ResolvedCostBasis.CostBasis)
+			s.Equal(
+				created.Charge.State.ResolvedCostBasis.CostBasis.InexactFloat64(),
+				persisted[0].State.ResolvedCostBasis.CostBasis.InexactFloat64(),
+			)

The same applies to the s.Equal(&replacement, ...) struct comparisons on lines 312 and 333, which embed a Decimal. As per coding guidelines: "When precision permits, compare alpacadecimal.Decimal through InexactFloat64() with require.Equal".

Also applies to: 123-124

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/service/creditpurchase_costbasis_test.go` around
lines 105 - 107, Update the credit-purchase assertions around the expected rate
comparisons and replacement struct comparisons to compare alpacadecimal.Decimal
values via InexactFloat64() with require.Equal, rather than using s.Equal on
decimal representations. Preserve the existing expected values and other field
assertions, including currency cost basis and timestamps.

Source: Coding guidelines

openmeter/billing/charges/creditpurchase/service/realizations/service.go (1)

61-95: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider extracting the shared credit-grant tail.

GrantPromotionalCredits and GrantCredits (lines 97-139) share the same tail: create the credit grant, assign charge.Realizations.CreditGrantRealization, then conditionally backfill advance lineage. Only the duplicate-check message and the handler call differ. A small named helper that takes the charge and the ledgertransaction.GroupReference would keep both paths in sync when the lineage or grant contract changes later.

Totally fine to defer if you prefer to keep the two lifecycles textually independent.

♻️ Sketch of the shared helper
// persistCreditGrant records the grant fact and backfills the advance lineage
// that funds it. Both promotional and payment-backed grants share this tail.
func (s *Service) persistCreditGrant(
	ctx context.Context,
	charge creditpurchase.Charge,
	reference ledgertransaction.GroupReference,
) (creditpurchase.Charge, error) {
	grantRealization, err := s.adapter.CreateCreditGrant(ctx, charge.GetChargeID(), creditpurchase.CreateCreditGrantInput{
		TransactionGroupID: reference.TransactionGroupID,
		GrantedAt:          clock.Now(),
	})
	if err != nil {
		return creditpurchase.Charge{}, err
	}

	charge.Realizations.CreditGrantRealization = &grantRealization

	if reference.TransactionGroupID == "" {
		return charge, nil
	}

	if err := s.lineage.BackfillAdvanceLineageSegments(ctx, lineage.BackfillAdvanceLineageSegmentsInput{
		Namespace:                 charge.Namespace,
		CustomerID:                charge.Intent.CustomerID,
		Currency:                  charge.Intent.Currency,
		Amount:                    charge.Intent.CreditAmount,
		BackingTransactionGroupID: reference.TransactionGroupID,
		FeatureFilters:            charge.Intent.FeatureFilters.Normalize(),
	}); err != nil {
		return creditpurchase.Charge{}, err
	}

	return charge, nil
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/creditpurchase/service/realizations/service.go`
around lines 61 - 95, Extract the shared credit-grant persistence and
lineage-backfill tail from GrantPromotionalCredits and GrantCredits into a named
helper such as persistCreditGrant accepting the charge and
ledgertransaction.GroupReference. Update both methods to retain only their
distinct duplicate checks and handler calls, then delegate grant creation,
realization assignment, and conditional lineage backfill to the helper.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@openmeter/billing/charges/creditpurchase/service/invoice_test.go`:
- Line 45: Update the decimal assertion in the invoice test to compare
price.Amount.InexactFloat64() with the expected zero value using require.Equal.
Keep the expected balance inline and preserve the existing assertion context.

---

Nitpick comments:
In `@openmeter/billing/charges/creditpurchase/adapter/mapper_test.go`:
- Around line 34-46: Update the “dedicated fiat materializes resolved state”
subtest around fromDBCostBasis to assert ResolvedCostBasis.ResolvedAt equals the
charge row’s CreatedAt value, replacing the non-zero check. Preserve the
existing assertions and use the existing createdAt fixture to document the
source timestamp.

In `@openmeter/billing/charges/creditpurchase/charge_test.go`:
- Around line 112-153: Add a subtest to TestChargeGetFiatSettlementAmount that
constructs a charge from the existing “fiat purchase” case without
State.ResolvedCostBasis, calls GetFiatSettlementAmount, and asserts the error
contains “cost basis is unresolved”.

In `@openmeter/billing/charges/creditpurchase/service/realizations/service.go`:
- Around line 61-95: Extract the shared credit-grant persistence and
lineage-backfill tail from GrantPromotionalCredits and GrantCredits into a named
helper such as persistCreditGrant accepting the charge and
ledgertransaction.GroupReference. Update both methods to retain only their
distinct duplicate checks and handler calls, then delegate grant creation,
realization assignment, and conditional lineage backfill to the helper.

In `@openmeter/billing/charges/meta/customcurrency.go`:
- Around line 28-37: Update CalculateFiatAmount to reject any non-positive
resolvedCostBasis, including negative values, and adjust the validation error
message accordingly. Preserve the existing amount validation and fiat rounding
behavior, and update the affected custom-currency test expectation to match the
new message.

In `@openmeter/billing/charges/service/creditpurchase_costbasis_test.go`:
- Around line 105-124: Update decimal assertions in
openmeter/billing/charges/service/creditpurchase_costbasis_test.go:105-124 and
the replacement comparisons around lines 312 and 333, plus
test/credits/creditpurchase_costbasis_test.go:174-187 and its remaining
balance/FiatAmount subtests, to compare alpacadecimal.Decimal values via
InexactFloat64() with require.Equal rather than struct equality; inline one-off
expected balances where applicable.
- Around line 105-107: Update the credit-purchase assertions around the expected
rate comparisons and replacement struct comparisons to compare
alpacadecimal.Decimal values via InexactFloat64() with require.Equal, rather
than using s.Equal on decimal representations. Preserve the existing expected
values and other field assertions, including currency cost basis and timestamps.

In `@openmeter/ledger/chargeadapter/creditpurchase.go`:
- Around line 80-91: Extract the duplicated unresolved-cost-basis validation,
settlement fiat lookup, and cost-basis extraction from
OnCreditPurchasePaymentAuthorized and OnCreditPurchasePaymentSettled into a
named resolvedSettlementBasis helper. Have it return the settlement currency and
resolved cost basis, preserving the existing precondition and wrapped currency
lookup errors, then update both handlers to use it and remove their redundant
conversion logic.
🪄 Autofix

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 Plus

Run ID: 2c229532-483c-4f0d-a0ae-abe9c5964ad6

📥 Commits

Reviewing files that changed from the base of the PR and between e99a392 and f339085.

📒 Files selected for processing (41)
  • openmeter/billing/charges/README.md
  • openmeter/billing/charges/creditpurchase/adapter.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/costbasis.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper_test.go
  • openmeter/billing/charges/creditpurchase/charge.go
  • openmeter/billing/charges/creditpurchase/charge_test.go
  • openmeter/billing/charges/creditpurchase/costbasis.go
  • openmeter/billing/charges/creditpurchase/costbasis_test.go
  • openmeter/billing/charges/creditpurchase/service/costbasis.go
  • openmeter/billing/charges/creditpurchase/service/create.go
  • openmeter/billing/charges/creditpurchase/service/external.go
  • openmeter/billing/charges/creditpurchase/service/external_test.go
  • openmeter/billing/charges/creditpurchase/service/invoice.go
  • openmeter/billing/charges/creditpurchase/service/invoice_test.go
  • openmeter/billing/charges/creditpurchase/service/lineengine.go
  • openmeter/billing/charges/creditpurchase/service/lineengine_test.go
  • openmeter/billing/charges/creditpurchase/service/promotional.go
  • openmeter/billing/charges/creditpurchase/service/promotional_test.go
  • openmeter/billing/charges/creditpurchase/service/realizations/service.go
  • openmeter/billing/charges/creditpurchase/service/realizations_test.go
  • openmeter/billing/charges/creditpurchase/service/service.go
  • openmeter/billing/charges/creditpurchase/service/statemachine.go
  • openmeter/billing/charges/meta/customcurrency.go
  • openmeter/billing/charges/meta/customcurrency_test.go
  • openmeter/billing/charges/models/costbasis/intent.go
  • openmeter/billing/charges/models/costbasis/model.go
  • openmeter/billing/charges/models/creditpurchase/detailedline.go
  • openmeter/billing/charges/service/creditpurchase_costbasis_test.go
  • openmeter/billing/charges/service/creditpurchase_test.go
  • openmeter/billing/charges/service/taxcode_test.go
  • openmeter/billing/creditgrant/service/service.go
  • openmeter/ledger/chargeadapter/creditpurchase.go
  • openmeter/ledger/chargeadapter/creditpurchase_customcurrency_test.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
  • openmeter/ledger/customerbalance/service_test.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • test/app/stripe/invoice_credits_test.go
  • test/credits/base.go
  • test/credits/creditpurchase_costbasis_test.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • openmeter/ledger/customerbalance/service_test.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper.go
  • openmeter/billing/charges/creditpurchase/service/external_test.go
  • openmeter/billing/charges/creditpurchase/service/service.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go

@turip

turip commented Aug 12, 2026

Copy link
Copy Markdown
Member Author

Addressed the latest review findings in 7d0ed34:

  • Fiat cost-basis reconstruction now asserts the exact persisted fallback timestamp.
  • Fiat amount calculation rejects a missing settlement currency and any non-positive resolved cost basis.
  • Decimal assertions use the repository InexactFloat64 convention where precision permits.
  • The unresolved lifecycle behavior remains covered at the owning line-engine and realization boundaries, so no duplicate direct-helper test was added.

Two extraction suggestions were intentionally left unchanged: the payment authorization/settlement checks remain inline because extracting them obscures the two ledger flows, and the promotional/payment grant tails remain separate lifecycle paths. The earlier ResolvedAt == CreatedAt invariant suggestion is outdated; those timestamps are not required to be equal.

@turip
turip merged commit 84dd0f2 into main Aug 13, 2026
27 checks passed
@turip
turip deleted the feat/creditpurchase-initial-costbasis-resolution branch August 13, 2026 06:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants