Repository navigation
feat(creditpurchase): resolve cost basis before realization - #4918
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (15)
🚧 Files skipped from review as they are similar to previous changes (8)
📝 WalkthroughWalkthroughCredit 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. ChangesCredit purchase cost-basis lifecycle
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
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✨ 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: 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
📒 Files selected for processing (23)
app/common/charges.goopenmeter/billing/charges/README.mdopenmeter/billing/charges/creditpurchase/adapter.goopenmeter/billing/charges/creditpurchase/adapter/charge.goopenmeter/billing/charges/creditpurchase/adapter/mapper.goopenmeter/billing/charges/creditpurchase/adapter/mapper_test.goopenmeter/billing/charges/creditpurchase/charge.goopenmeter/billing/charges/creditpurchase/charge_test.goopenmeter/billing/charges/creditpurchase/costbasis.goopenmeter/billing/charges/creditpurchase/costbasis_test.goopenmeter/billing/charges/creditpurchase/service/costbasis.goopenmeter/billing/charges/creditpurchase/service/create.goopenmeter/billing/charges/creditpurchase/service/external_test.goopenmeter/billing/charges/creditpurchase/service/service.goopenmeter/billing/charges/service/base_test.goopenmeter/billing/charges/service/creditpurchase_costbasis_test.goopenmeter/billing/charges/service/creditpurchase_test.goopenmeter/billing/charges/testutils/service.goopenmeter/ledger/chargeadapter/creditpurchase_test.goopenmeter/ledger/customerbalance/service_test.goopenmeter/ledger/customerbalance/testenv_test.gotest/credits/base.gotest/credits/creditgrant_test.go
237edb1 to
f339085
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (7)
openmeter/ledger/chargeadapter/creditpurchase.go (1)
80-91: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThese twelve lines are now identical in both payment handlers. The unresolved-state precondition, the settlement fiat lookup, and the
costBasisextraction repeat verbatim inOnCreditPurchasePaymentAuthorizedandOnCreditPurchasePaymentSettled. 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 valueSmall tightening idea. The other subtests pin
ResolvedAtto 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,UpdatedAtorclock.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 winSolid table test — one branch is still uncovered.
GetFiatSettlementAmountgained a new guard that returns"cost basis is unresolved"whenState.ResolvedCostBasisis 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 winConsider rejecting non-positive cost basis, not only zero.
IsZero()lets a negativeresolvedCostBasisthrough. The result is then a negative fiat amount, which contradicts theamount.IsNegative()guard right above it. The internal caller here validatesResolvedCostBasisfirst, butCharge.GetFiatSettlementAmountinopenmeter/billing/charges/creditpurchase/charge.gopassesc.State.ResolvedCostBasis.CostBasisstraight through. A positivity check keeps this exported helper safe for every caller.Also worth a thought:
fiatCurrencyis 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.goline 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 winPrefer
InexactFloat64()for the new cost-basis decimal assertions. Both new test files assertalpacadecimal.Decimalvalues 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: compareResolvedCostBasis.CostBasisand the persisted round-trip throughInexactFloat64(); do the same for the&replacementstruct comparisons on lines 312 and 333.test/credits/creditpurchase_costbasis_test.go#L174-L187: compareline.Totals.Amount,line.Totals.Total,DetailedLines[0].Quantity,DetailedLines[0].PerUnitAmount, andResolvedCostBasis.CostBasisthroughInexactFloat64(); apply the same change to the balance andFiatAmountassertions in the remaining subtests.As per coding guidelines: "When precision permits, compare
alpacadecimal.DecimalthroughInexactFloat64()withrequire.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 winCompare the decimals through
InexactFloat64().
s.Equalonalpacadecimal.Decimalcompares 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 usesInexactFloat64()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 aDecimal. As per coding guidelines: "When precision permits, comparealpacadecimal.DecimalthroughInexactFloat64()withrequire.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 winConsider extracting the shared credit-grant tail.
GrantPromotionalCreditsandGrantCredits(lines 97-139) share the same tail: create the credit grant, assigncharge.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 theledgertransaction.GroupReferencewould 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
📒 Files selected for processing (41)
openmeter/billing/charges/README.mdopenmeter/billing/charges/creditpurchase/adapter.goopenmeter/billing/charges/creditpurchase/adapter/charge.goopenmeter/billing/charges/creditpurchase/adapter/costbasis.goopenmeter/billing/charges/creditpurchase/adapter/mapper.goopenmeter/billing/charges/creditpurchase/adapter/mapper_test.goopenmeter/billing/charges/creditpurchase/charge.goopenmeter/billing/charges/creditpurchase/charge_test.goopenmeter/billing/charges/creditpurchase/costbasis.goopenmeter/billing/charges/creditpurchase/costbasis_test.goopenmeter/billing/charges/creditpurchase/service/costbasis.goopenmeter/billing/charges/creditpurchase/service/create.goopenmeter/billing/charges/creditpurchase/service/external.goopenmeter/billing/charges/creditpurchase/service/external_test.goopenmeter/billing/charges/creditpurchase/service/invoice.goopenmeter/billing/charges/creditpurchase/service/invoice_test.goopenmeter/billing/charges/creditpurchase/service/lineengine.goopenmeter/billing/charges/creditpurchase/service/lineengine_test.goopenmeter/billing/charges/creditpurchase/service/promotional.goopenmeter/billing/charges/creditpurchase/service/promotional_test.goopenmeter/billing/charges/creditpurchase/service/realizations/service.goopenmeter/billing/charges/creditpurchase/service/realizations_test.goopenmeter/billing/charges/creditpurchase/service/service.goopenmeter/billing/charges/creditpurchase/service/statemachine.goopenmeter/billing/charges/meta/customcurrency.goopenmeter/billing/charges/meta/customcurrency_test.goopenmeter/billing/charges/models/costbasis/intent.goopenmeter/billing/charges/models/costbasis/model.goopenmeter/billing/charges/models/creditpurchase/detailedline.goopenmeter/billing/charges/service/creditpurchase_costbasis_test.goopenmeter/billing/charges/service/creditpurchase_test.goopenmeter/billing/charges/service/taxcode_test.goopenmeter/billing/creditgrant/service/service.goopenmeter/ledger/chargeadapter/creditpurchase.goopenmeter/ledger/chargeadapter/creditpurchase_customcurrency_test.goopenmeter/ledger/chargeadapter/creditpurchase_test.goopenmeter/ledger/customerbalance/service_test.goopenmeter/ledger/customerbalance/testenv_test.gotest/app/stripe/invoice_credits_test.gotest/credits/base.gotest/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
|
Addressed the latest review findings in 7d0ed34:
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. |
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
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
Ticket: OM-436
Validation
make test-nocachemake lint-go-fastGreptile Summary
This PR adds durable cost-basis resolution for credit purchases before their first monetary realization.
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
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 eventsReviews (5): Last reviewed commit: "feat(creditpurchase): resolve dynamic co..." | Re-trigger Greptile
Context used:
Summary by CodeRabbit
New Features
Bug Fixes