Repository navigation
refactor(credit): move purchase valuation and lifecycle to line engine - #4861
Conversation
📝 WalkthroughWalkthroughCredit-purchase billing now uses a service-owned line engine. Detailed-line valuation is centralized through ChangesCredit purchase line-engine migration
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Invoice
participant CreditPurchaseLineEngine
participant CreditPurchaseService
participant Charge
Invoice->>CreditPurchaseLineEngine: Create invoice lines
CreditPurchaseLineEngine->>CreditPurchaseService: Retrieve charges and build lines
CreditPurchaseLineEngine->>CreditPurchaseService: Dispatch invoice lifecycle event
CreditPurchaseService->>Charge: Update credit-purchase state
Charge-->>Invoice: Updated invoice charge state
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 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 |
986a1e0 to
b5b1095
Compare
b5b1095 to
115aa8b
Compare
115aa8b to
7322a4c
Compare
7322a4c to
f800d16
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (8)
openmeter/billing/charges/creditpurchase/service/lineengine_test.go (1)
14-20: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: tighten the test name.
The test asserts the engine type and that the engine no longer implements
billing.LineCalculator. The nameTestLineEngineUsesChargeOwnedValuationpromises a valuation assertion that is not here. Something likeTestLineEngineDoesNotImplementLineCalculatordescribes the guard more directly. The guard itself is a good idea for keeping the removed dependency out.🤖 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/lineengine_test.go` around lines 14 - 20, Rename TestLineEngineUsesChargeOwnedValuation to describe the behavior it actually verifies: the returned line engine does not implement billing.LineCalculator. Keep the existing engine-type and interface assertions unchanged.openmeter/billing/charges/creditpurchase/service/lineengine.go (2)
280-280: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAdd a short comment for the charge write-back.
Line 280 stores the updated charge back into
chargesByID. That only matters when several standard lines point at the same charge, so the next iteration fires its trigger against the post-transition state instead of a stale one. That intent is not visible from the code, and the guidelines ask for comments that capture non-obvious domain intent.📝 Suggested comment
+ // Several lines can reference one charge. Keep the post-transition charge so the + // next line fires its trigger against current lifecycle state, not a stale read. chargesByID[updatedCharge.ID] = updatedCharge🤖 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/lineengine.go` at line 280, Add a concise comment immediately above the chargesByID assignment in the charge-processing loop explaining that writing back the updated charge ensures subsequent standard lines sharing the charge use the post-transition state for trigger evaluation rather than stale data.Source: Coding guidelines
174-184: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winSwap the hand-rolled dedupe for
lo.Uniq.
lois already imported on line 8, and the guidelines prefer standardslices/mapsand thenloover local helpers. The set-plus-slice bookkeeping collapses to one line here, and order is preserved either way.♻️ Proposed simplification
- chargeIDs := make([]string, 0, len(input.Lines)) - seenChargeIDs := make(map[string]struct{}, len(input.Lines)) - - for _, stdLine := range input.Lines { - if _, ok := seenChargeIDs[*stdLine.ChargeID]; ok { - continue - } - - seenChargeIDs[*stdLine.ChargeID] = struct{}{} - chargeIDs = append(chargeIDs, *stdLine.ChargeID) - } + chargeIDs := lo.Uniq(lo.Map(input.Lines, func(stdLine *billing.StandardLine, _ int) string { + return *stdLine.ChargeID + }))🤖 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/lineengine.go` around lines 174 - 184, Replace the seenChargeIDs map and manual deduplication loop in the charge ID collection with lo.Uniq over the input line charge IDs, preserving their original order and the resulting chargeIDs behavior.Source: Coding guidelines
openmeter/billing/charges/service/creditpurchase_test.go (1)
939-940: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: compare these decimals through
InexactFloat64().
s.Equalonalpacadecimal.Decimalcompares the struct, so a value that round-trips through the database with a different internal exponent can fail even when the amount matches. The coding guidelines preferInexactFloat64()with an exact expected value when precision permits, and0.5and100both qualify.♻️ Suggested tweak
- s.Equal(alpacadecimal.NewFromFloat(0.5), detailedLine.PerUnitAmount) - s.Equal(alpacadecimal.NewFromFloat(100), detailedLine.Quantity) + s.Equal(float64(0.5), detailedLine.PerUnitAmount.InexactFloat64()) + s.Equal(float64(100), detailedLine.Quantity.InexactFloat64())🤖 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_test.go` around lines 939 - 940, Update the assertions for detailedLine.PerUnitAmount and detailedLine.Quantity to compare their InexactFloat64() values against the expected 0.5 and 100 values, avoiding struct-level decimal equality while preserving the existing expectations.Source: Coding guidelines
openmeter/billing/charges/models/creditpurchase/detailedline_test.go (1)
99-133: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueNice tests. One optional gap: the new cost-basis rule.
The new
ResolvedCostBasisrule rejects zero and negative values, and the new credit-amount rule rejects negatives. Neither branch has a case here. A short table case next toTestNewDetailedLineRejectsInconsistentFiatAmountwould lock the new boundary in place.🤖 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/models/creditpurchase/detailedline_test.go` around lines 99 - 133, The test coverage around newDetailedLine should add table-driven cases for the new validation boundaries: zero and negative ResolvedCostBasis values, plus a negative CreditAmount. Place the cases alongside TestNewDetailedLineRejectsInconsistentFiatAmount and assert each input is rejected with the appropriate validation error.Source: Path instructions
openmeter/billing/charges/service/invoice.go (1)
13-21: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: state the guard positively.
The switch matches five statuses with an empty body and returns from
default. It works, but a reader has to invert the logic to see which statuses continue. Aslices.Containsguard makes the intent read forward. Purely a readability call, so feel free to keep the switch if you prefer it.♻️ Alternative form
- switch invoice.Status { - case billing.StandardInvoiceStatusDraftCreated, - billing.StandardInvoiceStatusIssued, - billing.StandardInvoiceStatusPaymentProcessingAuthorized, - billing.StandardInvoiceStatusPaymentProcessingBookingAuthorizedAndSettled, - billing.StandardInvoiceStatusPaid: - default: - return nil - } + // Earnings are recognized once the invoice reaches a status that fixes its amounts. + earningsRecognitionStatuses := []billing.StandardInvoiceStatus{ + billing.StandardInvoiceStatusDraftCreated, + billing.StandardInvoiceStatusIssued, + billing.StandardInvoiceStatusPaymentProcessingAuthorized, + billing.StandardInvoiceStatusPaymentProcessingBookingAuthorizedAndSettled, + billing.StandardInvoiceStatusPaid, + } + if !slices.Contains(earningsRecognitionStatuses, invoice.Status) { + return 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/service/invoice.go` around lines 13 - 21, Optionally refactor the invoice status guard to use a positive allowlist check, such as slices.Contains, for the five accepted statuses and return nil when the status is not included. Preserve the existing behavior and status set; retaining the current switch is also acceptable.Source: Path instructions
openmeter/billing/charges/models/creditpurchase/detailedline.go (1)
156-200: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: share the valuation checks between the two input types.
WithDetailedLinesInput.Validaterepeats five checks fromnewDetailedLineInput.Validate(credit currency, credit amount, cost basis, fiat currency, fiat amount plus precision).WithDetailedLinesthen callsnewDetailedLine, which validates again. A small shared value struct (for example acreditValuationembedded in both inputs) would keep the rules in one place, andWithDetailedLinesInputwould only add theLine/currency-consistency check on top.🤖 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/models/creditpurchase/detailedline.go` around lines 156 - 200, Share the repeated valuation validation between newDetailedLineInput.Validate and WithDetailedLinesInput.Validate by extracting the credit/fiat currency, amount, cost-basis, and precision fields and checks into a common creditValuation-style value struct or validator. Update both input types to reuse that validation, leaving WithDetailedLinesInput responsible only for line presence, name, and line/fiat-currency consistency checks.openmeter/billing/charges/creditpurchase/service/realizations_test.go (1)
77-87: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse the repository decimal assertion convention.
Compare the expected and actual values with
require.EqualandInexactFloat64(). This gives useful expected-versus-actual output when the test fails.Proposed change
- require.True(t, input.FiatAmount.Equal(alpacadecimal.RequireFromString(tt.expectedAmount))) + require.Equal(t, alpacadecimal.RequireFromString(tt.expectedAmount).InexactFloat64(), input.FiatAmount.InexactFloat64()) ... - require.True(t, adapter.createdExternalPayment.FiatAmount.Equal(alpacadecimal.RequireFromString(tt.expectedAmount))) + require.Equal(t, alpacadecimal.RequireFromString(tt.expectedAmount).InexactFloat64(), adapter.createdExternalPayment.FiatAmount.InexactFloat64())As per coding guidelines, compare
alpacadecimal.Decimalvalues throughInexactFloat64()withrequire.Equalwhen precision permits.🤖 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_test.go` around lines 77 - 87, Update the decimal assertions in the external payment realization test around AuthorizeExternalPayment to compare expected and actual values using require.Equal with each value converted via InexactFloat64(), replacing the current Equal-based require.True checks while preserving the existing expected amounts.Source: Coding guidelines
🤖 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.
Nitpick comments:
In `@openmeter/billing/charges/creditpurchase/service/lineengine_test.go`:
- Around line 14-20: Rename TestLineEngineUsesChargeOwnedValuation to describe
the behavior it actually verifies: the returned line engine does not implement
billing.LineCalculator. Keep the existing engine-type and interface assertions
unchanged.
In `@openmeter/billing/charges/creditpurchase/service/lineengine.go`:
- Line 280: Add a concise comment immediately above the chargesByID assignment
in the charge-processing loop explaining that writing back the updated charge
ensures subsequent standard lines sharing the charge use the post-transition
state for trigger evaluation rather than stale data.
- Around line 174-184: Replace the seenChargeIDs map and manual deduplication
loop in the charge ID collection with lo.Uniq over the input line charge IDs,
preserving their original order and the resulting chargeIDs behavior.
In `@openmeter/billing/charges/creditpurchase/service/realizations_test.go`:
- Around line 77-87: Update the decimal assertions in the external payment
realization test around AuthorizeExternalPayment to compare expected and actual
values using require.Equal with each value converted via InexactFloat64(),
replacing the current Equal-based require.True checks while preserving the
existing expected amounts.
In `@openmeter/billing/charges/models/creditpurchase/detailedline_test.go`:
- Around line 99-133: The test coverage around newDetailedLine should add
table-driven cases for the new validation boundaries: zero and negative
ResolvedCostBasis values, plus a negative CreditAmount. Place the cases
alongside TestNewDetailedLineRejectsInconsistentFiatAmount and assert each input
is rejected with the appropriate validation error.
In `@openmeter/billing/charges/models/creditpurchase/detailedline.go`:
- Around line 156-200: Share the repeated valuation validation between
newDetailedLineInput.Validate and WithDetailedLinesInput.Validate by extracting
the credit/fiat currency, amount, cost-basis, and precision fields and checks
into a common creditValuation-style value struct or validator. Update both input
types to reuse that validation, leaving WithDetailedLinesInput responsible only
for line presence, name, and line/fiat-currency consistency checks.
In `@openmeter/billing/charges/service/creditpurchase_test.go`:
- Around line 939-940: Update the assertions for detailedLine.PerUnitAmount and
detailedLine.Quantity to compare their InexactFloat64() values against the
expected 0.5 and 100 values, avoiding struct-level decimal equality while
preserving the existing expectations.
In `@openmeter/billing/charges/service/invoice.go`:
- Around line 13-21: Optionally refactor the invoice status guard to use a
positive allowlist check, such as slices.Contains, for the five accepted
statuses and return nil when the status is not included. Preserve the existing
behavior and status set; retaining the current switch is also acceptable.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 3ce2a8f0-1eab-432d-80b3-6b35e828af05
📒 Files selected for processing (20)
app/common/charges.goopenmeter/billing/charges/README.mdopenmeter/billing/charges/creditpurchase/lineengine/engine.goopenmeter/billing/charges/creditpurchase/service.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/realizations_test.goopenmeter/billing/charges/creditpurchase/service/service.goopenmeter/billing/charges/flatfee/service/linemapper.goopenmeter/billing/charges/models/creditpurchase/detailedline.goopenmeter/billing/charges/models/creditpurchase/detailedline_test.goopenmeter/billing/charges/models/creditpurchase/standardline_test.goopenmeter/billing/charges/service/base_test.goopenmeter/billing/charges/service/creditpurchase_test.goopenmeter/billing/charges/service/invoice.goopenmeter/billing/charges/testutils/service.goopenmeter/billing/charges/usagebased/service/linemapper.go
💤 Files with no reviewable changes (2)
- openmeter/billing/charges/creditpurchase/lineengine/engine.go
- openmeter/billing/charges/creditpurchase/service/invoice.go
Summary
Why
This consolidates invoice-settled credit-purchase valuation and lifecycle ownership in the charge-owned line engine. It preserves purchased quantity and resolved cost basis on invoice details and establishes the structure needed to implement cost-basis pinning.
Ticket: OM-436
Validation
POSTGRES_HOST=127.0.0.1 go test -tags=dynamic ./openmeter/billing/charges/... -count=1nix develop --impure .#ci -c make lint-go-fastgit diff --checkSummary by CodeRabbit
New Features
Bug Fixes
Tests
Greptile Summary
The PR moves credit-purchase valuation and invoice lifecycle handling into the credit-purchase line engine.
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
Reviews (7): Last reviewed commit: "chore(credit): address review feedback" | Re-trigger Greptile
Context used: