Skip to content

refactor(credit): model invoice purchases with state machine - #4859

Merged
turip merged 1 commit into
mainfrom
feat/invoice-credit-purchase-state-machine
Aug 6, 2026
Merged

turip merged 1 commit into
mainfrom
feat/invoice-credit-purchase-state-machine

Conversation

@turip

@turip turip commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

Summary

  • model invoice-settled credit purchases with the same stateless lifecycle pattern used by charge state machines
  • separate credit granting, invoice payment authorization, settlement, and finalization into explicit detailed states
  • move payment and grant mechanics into the realization service with validated operation inputs
  • map legacy generic active charges from their persisted realization facts at state-machine construction time
  • update domain documentation and lifecycle coverage, including PostgreSQL-backed credit grant scenarios

Why

This is a refactor that establishes the lifecycle boundary needed before implementing cost-basis pinning.

Ticket: OM-436

Impact

Invoice-settled credit purchases now expose detailed payment lifecycle statuses instead of the generic active status. Existing active charges are mapped at runtime without replaying ledger effects; a follow-up SQL migration is documented in code.

Validation

  • nix develop --impure .#ci -c make lint
  • nix develop --impure .#ci -c make test — 6,785 tests passed, 9 skipped
  • POSTGRES_HOST=127.0.0.1 go test -tags=dynamic ./test/credits

Summary by CodeRabbit

  • New Features
    • Invoice-funded credit purchases now follow distinct payment stages: pending, authorized, and settled.
    • Credits are granted when an invoice is created, before payment authorization.
    • External direct-paid purchases can record authorization and settlement sequentially.
  • Bug Fixes
    • Improved validation for invoice, payment, and charge relationships.
    • Prevented mismatched payment lines and incomplete credit grants from advancing.
  • Documentation
    • Updated billing guidance to reflect invoice creation, authorization, and settlement workflows.

Greptile Summary

The PR refactors invoice-settled credit purchases onto the stateless charge lifecycle and derives detailed states for legacy active purchases.

  • Separates credit granting, payment authorization, settlement, and finalization into explicit transitions.
  • Moves invoice payment realization logic behind validated realization-service operations.
  • Adds lifecycle, legacy-state mapping, exact-amount, and PostgreSQL-backed credit-grant coverage.

Confidence Score: 5/5

The PR appears safe to merge, with no concrete blocking or independently actionable non-blocking issues identified.

The new lifecycle preserves transactional persistence on billing hook paths, maps legacy states from durable realization facts, and validates charge, invoice, line, and payment relationships before performing effects.

Important Files Changed

Filename Overview
openmeter/billing/charges/creditpurchase/service/invoice.go Introduces the invoice credit-purchase state machine, legacy-state mapping, validated lifecycle dispatch, and billing-hook adapters; no actionable defect was established.
openmeter/billing/charges/creditpurchase/service/realizations/service.go Generalizes credit granting across payment-backed settlements and adds validated invoice authorization and settlement realization operations.
openmeter/billing/charges/creditpurchase/service/invoice_test.go Covers grant, authorization, settlement, fiat amount preservation, legacy mappings, and invalid realization relationships.
openmeter/billing/charges/README.md Documents the new invoice-backed credit-purchase lifecycle and durable realization facts.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  Created[Created] -->|Invoice created| Grant[Active: initial credit grant]
  Grant -->|Grant credits / next| Pending[Active: payment pending]
  Pending -->|Payment authorized| Authorized[Active: payment authorized]
  Authorized -->|Payment paid| Settled[Active: payment settled]
  Settled -->|Finalize / next| Final[Final]
  Legacy[Legacy active] -. Grant only .-> Pending
  Legacy -. Authorized payment .-> Authorized
  Legacy -. Settled payment .-> Final
Loading

Reviews (1): Last reviewed commit: "refactor(credit): model invoice purchase..." | Re-trigger Greptile

Context used:

@turip
turip requested a review from a team as a code owner August 6, 2026 06:53
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Invoice credit purchases now use a dedicated state machine. The flow grants credits before payment pending, records authorization and settlement separately, reconciles legacy statuses, validates invoice relationships, and updates related tests and documentation.

Changes

Invoice credit-purchase lifecycle

Layer / File(s) Summary
Realization payment operations
AGENTS.md, openmeter/billing/charges/creditpurchase/service/realizations/service.go
Validation guidance now covers multi-parameter operations. The realization service adds invoice payment authorization and settlement operations.
Invoice state-machine orchestration
openmeter/billing/charges/creditpurchase/service/invoice.go, openmeter/billing/charges/README.md
Invoice lifecycle handling now validates triggers, reconciles legacy statuses, and dispatches credit, authorization, and settlement transitions through a state machine.
Lifecycle behavior validation
openmeter/billing/charges/creditpurchase/service/invoice_test.go, openmeter/billing/charges/creditpurchase/service/external_test.go, openmeter/billing/charges/service/creditpurchase_test.go, test/credits/*
Tests cover lifecycle statuses, legacy reconciliation, payment relationships, exact amounts, adapter calls, and invoice-funded grants.

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

Sequence Diagram(s)

sequenceDiagram
  participant InvoiceLifecycleHook
  participant InvoiceCreditPurchaseStateMachine
  participant RealizationsService
  participant InvoicePaymentAdapter
  participant Charge
  InvoiceLifecycleHook->>InvoiceCreditPurchaseStateMachine: Handle lifecycle trigger
  InvoiceCreditPurchaseStateMachine->>RealizationsService: Grant credits or authorize payment
  RealizationsService->>InvoicePaymentAdapter: Create or update invoiced payment
  RealizationsService->>Charge: Store realization state
  InvoiceCreditPurchaseStateMachine->>RealizationsService: Settle authorized payment
  RealizationsService->>InvoicePaymentAdapter: Persist settled payment
  InvoiceCreditPurchaseStateMachine->>Charge: Advance payment status
Loading

Possibly related PRs

Suggested labels: area/billing, kind/refactor, release-note/misc

Suggested reviewers: tothandras, galexihu, mark-vass-konghq

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: modeling invoice credit purchases with a state machine.
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.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/invoice-credit-purchase-state-machine

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.

🧹 Nitpick comments (3)
openmeter/billing/charges/creditpurchase/service/invoice_test.go (2)

138-141: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add given/when/then intent comments to these two tests.

TestInvoiceCreditPurchasePaymentPassesExactFiatAmount and TestInvoiceCreditPurchaseStateMachineRejectsMismatchedPaymentLine are lifecycle tests, but they skip the intent comments that the other tests in this file carry. A short header keeps the file consistent.

As per coding guidelines: "Begin non-trivial service or lifecycle subtests with concise given, when, and then intent comments."

♻️ Suggested headers
 func TestInvoiceCreditPurchasePaymentPassesExactFiatAmount(t *testing.T) {
+	// given:
+	// - a granted invoice-settled credit purchase whose line total is not a whole number
+	// when:
+	// - the service authorizes and then settles the invoice payment
+	// then:
+	// - the persisted payment carries the exact line total without rounding
 	charge := newGrantedInvoiceStateMachineTestCharge(t, creditpurchase.StatusActivePaymentPending)
 func TestInvoiceCreditPurchaseStateMachineRejectsMismatchedPaymentLine(t *testing.T) {
+	// given:
+	// - an authorized invoice credit purchase whose payment points at a different line
+	// when:
+	// - billing reports settlement for the mismatched line
+	// then:
+	// - validation rejects the trigger and nothing is persisted
 	charge := newGrantedInvoiceStateMachineTestCharge(t, creditpurchase.StatusActivePaymentAuthorized)

Also applies to: 276-280

🤖 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/invoice_test.go` around
lines 138 - 141, Add concise given/when/then intent comments to
TestInvoiceCreditPurchasePaymentPassesExactFiatAmount and
TestInvoiceCreditPurchaseStateMachineRejectsMismatchedPaymentLine, matching the
header style used by the other lifecycle tests in the file.

Source: Coding guidelines


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

Consider InexactFloat64() for the decimal assertions.

require.True(t, x.Equal(y)) prints only false when it fails. 49.99 is exactly representable, so the guideline's preferred form gives a readable diff. This applies to the other .Equal(fiatAmount) assertions in this file too.

As per coding guidelines: "When precision permits, compare alpacadecimal.Decimal through InexactFloat64() with require.Equal."

♻️ Example
-	require.True(t, authorizedCharge.Realizations.InvoiceSettlement.FiatAmount.Equal(fiatAmount))
+	require.Equal(t, fiatAmount.InexactFloat64(), authorizedCharge.Realizations.InvoiceSettlement.FiatAmount.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/creditpurchase/service/invoice_test.go` at line
114, Update all decimal assertions comparing values to fiatAmount in invoice
tests, including the assertion on
authorizedCharge.Realizations.InvoiceSettlement.FiatAmount, to compare their
InexactFloat64() results with require.Equal. Apply the same pattern to every
other .Equal(fiatAmount) assertion in the file.

Source: Coding guidelines

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

189-206: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the shared invoice-line relationship checks. Both Validate methods encode the same four rules: the invoice namespace matches the charge, the line charge ID matches the charge, the line namespace matches the charge, and the line invoice ID matches the invoice. Two copies of one rule set will drift as the lifecycle grows, and a rule added in one place will silently not apply in the other. A single exported helper such as creditpurchaserealizations.ValidateChargeLineRelationship(charge, lineWithHeader) []error would let both callers append its result.

  • openmeter/billing/charges/creditpurchase/service/invoice.go#L189-L206: replace the inlined namespace, charge ID, and invoice ID checks with a call to the shared helper, and keep the payment-relationship checks at Lines 208-216 here since they are specific to this boundary.
  • openmeter/billing/charges/creditpurchase/service/realizations/service.go#L112-L143: replace the same inlined checks in AuthorizeInvoicedPaymentInput.Validate with the shared helper, and keep the AsInvoiceSettlement check that is specific to this input.

Not a blocker for this PR. The duplication is small today, and it is easier to pull apart now than after a third caller appears.

As per coding guidelines: "Do not extract trivial or single-use helpers unless the name captures non-obvious domain intent" — this helper is reused and its name captures the charge-to-line relationship contract.

🤖 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/invoice.go` around lines 189
- 206, Extract the four shared invoice-line relationship validations into an
exported creditpurchaserealizations.ValidateChargeLineRelationship helper
returning []error. In
openmeter/billing/charges/creditpurchase/service/invoice.go lines 189-206,
replace the duplicated checks with the helper result while retaining the
payment-specific checks at lines 208-216. In
openmeter/billing/charges/creditpurchase/service/realizations/service.go lines
112-143, use the same helper in AuthorizeInvoicedPaymentInput.Validate and
retain its AsInvoiceSettlement-specific validation.

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/invoice_test.go`:
- Around line 138-141: Add concise given/when/then intent comments to
TestInvoiceCreditPurchasePaymentPassesExactFiatAmount and
TestInvoiceCreditPurchaseStateMachineRejectsMismatchedPaymentLine, matching the
header style used by the other lifecycle tests in the file.
- Line 114: Update all decimal assertions comparing values to fiatAmount in
invoice tests, including the assertion on
authorizedCharge.Realizations.InvoiceSettlement.FiatAmount, to compare their
InexactFloat64() results with require.Equal. Apply the same pattern to every
other .Equal(fiatAmount) assertion in the file.

In `@openmeter/billing/charges/creditpurchase/service/invoice.go`:
- Around line 189-206: Extract the four shared invoice-line relationship
validations into an exported
creditpurchaserealizations.ValidateChargeLineRelationship helper returning
[]error. In openmeter/billing/charges/creditpurchase/service/invoice.go lines
189-206, replace the duplicated checks with the helper result while retaining
the payment-specific checks at lines 208-216. In
openmeter/billing/charges/creditpurchase/service/realizations/service.go lines
112-143, use the same helper in AuthorizeInvoicedPaymentInput.Validate and
retain its AsInvoiceSettlement-specific validation.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: e076619f-175a-455b-94f6-faf92308697a

📥 Commits

Reviewing files that changed from the base of the PR and between 0f8b7cc and 8b83c37.

📒 Files selected for processing (9)
  • AGENTS.md
  • openmeter/billing/charges/README.md
  • 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/realizations/service.go
  • openmeter/billing/charges/service/creditpurchase_test.go
  • test/credits/creditgrant_test.go
  • test/credits/voidgrant_test.go

@turip
turip merged commit e516e97 into main Aug 6, 2026
28 of 31 checks passed
@turip
turip deleted the feat/invoice-credit-purchase-state-machine branch August 6, 2026 08:18
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