Skip to content

refactor(credit): move purchase valuation and lifecycle to line engine - #4861

Merged
turip merged 3 commits into
mainfrom
feat/credit-purchase-line-engine
Aug 6, 2026
Merged

turip merged 3 commits into
mainfrom
feat/credit-purchase-line-engine

Conversation

@turip

@turip turip commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

Summary

  • make the credit-purchase service own and expose its billing line engine, and register that engine in application and test wiring
  • build credit-purchase standard and detailed invoice lines from the purchased credit quantity and resolved cost basis
  • share the clone-based detailed-line valuation helper with flat-fee and usage-based custom-currency overages
  • route invoice-created, payment-authorized, and payment-settled events through the line engine into the credit-purchase state machine
  • remove the standalone rating-backed credit-purchase line engine and the legacy invoice lifecycle hooks
  • remove redundant unit-level invoice and external-settlement lifecycle tests already covered by the PostgreSQL-backed integration suite, while retaining focused line-mapping and realization coverage

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=1
  • nix develop --impure .#ci -c make lint-go-fast
  • git diff --check

Summary by CodeRabbit

  • New Features

    • Credit purchases now manage invoice, payment authorization, and settlement transitions directly through billing line processing.
    • Invoice lines preserve purchased credit quantities, resolved cost bases, and detailed fiat pricing.
    • Added support for safely attaching and recalculating detailed credit-purchase lines.
  • Bug Fixes

    • Improved validation for missing or mismatched invoice and charge information.
    • Standardized custom-currency overage line calculations and consistency checks.
    • Improved rounding accuracy for external payment authorization amounts.
  • Tests

    • Expanded coverage for credit valuation, currency validation, lifecycle transitions, and payment rounding.

Greptile Summary

The PR moves credit-purchase valuation and invoice lifecycle handling into the credit-purchase line engine.

  • Registers the service-owned line engine in application and test wiring.
  • Builds credit-purchase invoice details from purchased quantity and resolved cost basis.
  • Reuses clone-based detailed-line valuation for custom-currency overages.
  • Routes invoice-created, payment-authorized, and payment-settled events through the charge state machine.
  • Removes the legacy rating-backed engine and service lifecycle hooks.

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/lineengine.go Introduces service-owned line valuation and lifecycle routing for credit-purchase invoice lines.
openmeter/billing/charges/models/creditpurchase/detailedline.go Adds clone-based construction of detailed lines while preserving detailed-line identity and fiat totals.
openmeter/billing/charges/flatfee/service/linemapper.go Reuses the shared detailed-line valuation helper for custom-currency flat-fee overages.
openmeter/billing/charges/usagebased/service/linemapper.go Reuses the shared detailed-line valuation helper for custom-currency usage overages.
app/common/charges.go Registers the credit-purchase service's line engine instead of constructing the removed rating-backed engine.
openmeter/billing/charges/creditpurchase/service/invoice.go Removes legacy lifecycle entry points after routing those events through the line engine.

Sequence Diagram

sequenceDiagram
  participant Billing as Billing service
  participant Engine as Credit-purchase line engine
  participant Charges as Credit-purchase service
  participant SM as Charge state machine
  participant Store as Persistence
  Billing->>Engine: Build standard invoice lines
  Engine->>Charges: GetByIDs(charge IDs)
  Charges->>Store: Load purchases and cost basis
  Store-->>Charges: Charges
  Charges-->>Engine: Charges
  Engine-->>Billing: Valued standard and detailed lines
  Billing->>Engine: Invoice/payment lifecycle event
  Engine->>Charges: Handle lifecycle trigger per line
  Charges->>SM: Advance and fire trigger
  SM->>Store: Persist realizations and state
Loading

Reviews (7): Last reviewed commit: "chore(credit): address review feedback" | Re-trigger Greptile

Context used:

@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Credit-purchase billing now uses a service-owned line engine. Detailed-line valuation is centralized through WithDetailedLines. Invoice lifecycle events route through the line engine instead of billing hooks.

Changes

Credit purchase line-engine migration

Layer / File(s) Summary
Credit valuation and detailed-line API
openmeter/billing/charges/models/creditpurchase/..., openmeter/billing/charges/flatfee/..., openmeter/billing/charges/usagebased/...
Detailed-line inputs now use direct credit valuation values. WithDetailedLines creates detailed lines, recalculates totals, and validates fiat amounts. Flat-fee and usage-based mappers use this API.
Service-owned credit purchase line engine
openmeter/billing/charges/creditpurchase/service.go, openmeter/billing/charges/creditpurchase/service/lineengine.go, openmeter/billing/charges/creditpurchase/service/service.go
The service exposes a billing line engine that validates invoice lines, retrieves charges, builds invoice lines, and dispatches lifecycle events.
Invoice lifecycle ownership migration
openmeter/billing/charges/service/invoice.go, openmeter/billing/charges/creditpurchase/service/invoice.go, openmeter/billing/charges/creditpurchase/service/*_test.go, openmeter/billing/charges/README.md
Invoice processing removes direct charge dispatch. Credit-purchase invoice hooks are removed. Tests cover line-engine routing and fiat amount rounding.
Application and test registration
app/common/charges.go, openmeter/billing/charges/service/base_test.go, openmeter/billing/charges/testutils/service.go
Application and test setup register the line engine obtained from the credit-purchase service.

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
Loading

Possibly related PRs

Suggested reviewers: tothandras

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 summarizes the main change: moving credit-purchase valuation and lifecycle handling into a line engine.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/credit-purchase-line-engine

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.

Base automatically changed from feat/invoice-credit-purchase-state-machine to main August 6, 2026 08:18
@turip
turip force-pushed the feat/credit-purchase-line-engine branch from 986a1e0 to b5b1095 Compare August 6, 2026 08:58
@turip turip added release-note/misc Miscellaneous changes area/billing labels Aug 6, 2026
@turip
turip force-pushed the feat/credit-purchase-line-engine branch from b5b1095 to 115aa8b Compare August 6, 2026 10:36
@turip
turip changed the base branch from main to feat/migrate-external-credit-purchase-status August 6, 2026 10:36
@turip
turip force-pushed the feat/credit-purchase-line-engine branch from 115aa8b to 7322a4c Compare August 6, 2026 10:50
Base automatically changed from feat/migrate-external-credit-purchase-status to main August 6, 2026 10:56
@turip
turip force-pushed the feat/credit-purchase-line-engine branch from 7322a4c to f800d16 Compare August 6, 2026 11:00
@turip
turip marked this pull request as ready for review August 6, 2026 11:02
@turip
turip requested a review from a team as a code owner August 6, 2026 11:02

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

🧹 Nitpick comments (8)
openmeter/billing/charges/creditpurchase/service/lineengine_test.go (1)

14-20: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Optional: tighten the test name.

The test asserts the engine type and that the engine no longer implements billing.LineCalculator. The name TestLineEngineUsesChargeOwnedValuation promises a valuation assertion that is not here. Something like TestLineEngineDoesNotImplementLineCalculator describes 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 value

Add 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 win

Swap the hand-rolled dedupe for lo.Uniq.

lo is already imported on line 8, and the guidelines prefer standard slices/maps and then lo over 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 value

Optional: compare these decimals through InexactFloat64().

s.Equal on alpacadecimal.Decimal compares 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 prefer InexactFloat64() with an exact expected value when precision permits, and 0.5 and 100 both 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 value

Nice tests. One optional gap: the new cost-basis rule.

The new ResolvedCostBasis rule rejects zero and negative values, and the new credit-amount rule rejects negatives. Neither branch has a case here. A short table case next to TestNewDetailedLineRejectsInconsistentFiatAmount would 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 value

Optional: 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. A slices.Contains guard 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 value

Optional: share the valuation checks between the two input types.

WithDetailedLinesInput.Validate repeats five checks from newDetailedLineInput.Validate (credit currency, credit amount, cost basis, fiat currency, fiat amount plus precision). WithDetailedLines then calls newDetailedLine, which validates again. A small shared value struct (for example a creditValuation embedded in both inputs) would keep the rules in one place, and WithDetailedLinesInput would only add the Line/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 win

Use the repository decimal assertion convention.

Compare the expected and actual values with require.Equal and InexactFloat64(). 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.Decimal values through InexactFloat64() with require.Equal when 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

📥 Commits

Reviewing files that changed from the base of the PR and between c74d5a4 and f800d16.

📒 Files selected for processing (20)
  • app/common/charges.go
  • openmeter/billing/charges/README.md
  • openmeter/billing/charges/creditpurchase/lineengine/engine.go
  • openmeter/billing/charges/creditpurchase/service.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/realizations_test.go
  • openmeter/billing/charges/creditpurchase/service/service.go
  • openmeter/billing/charges/flatfee/service/linemapper.go
  • openmeter/billing/charges/models/creditpurchase/detailedline.go
  • openmeter/billing/charges/models/creditpurchase/detailedline_test.go
  • openmeter/billing/charges/models/creditpurchase/standardline_test.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/creditpurchase_test.go
  • openmeter/billing/charges/service/invoice.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/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

@turip turip changed the title refactor(credit): move purchase rating into line engine refactor(credit): move purchase valuation and lifecycle to line engine Aug 6, 2026
@turip
turip merged commit 0c17e84 into main Aug 6, 2026
27 checks passed
@turip
turip deleted the feat/credit-purchase-line-engine branch August 6, 2026 11:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants