Repository navigation
refactor(credit): model invoice purchases with state machine - #4859
Conversation
📝 WalkthroughWalkthroughInvoice 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. ChangesInvoice credit-purchase lifecycle
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
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
🧪 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.
🧹 Nitpick comments (3)
openmeter/billing/charges/creditpurchase/service/invoice_test.go (2)
138-141: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd
given/when/thenintent comments to these two tests.
TestInvoiceCreditPurchasePaymentPassesExactFiatAmountandTestInvoiceCreditPurchaseStateMachineRejectsMismatchedPaymentLineare 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, andthenintent 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 valueConsider
InexactFloat64()for the decimal assertions.
require.True(t, x.Equal(y))prints onlyfalsewhen it fails.49.99is 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.DecimalthroughInexactFloat64()withrequire.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 winExtract the shared invoice-line relationship checks. Both
Validatemethods 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 ascreditpurchaserealizations.ValidateChargeLineRelationship(charge, lineWithHeader) []errorwould 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 inAuthorizeInvoicedPaymentInput.Validatewith the shared helper, and keep theAsInvoiceSettlementcheck 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
📒 Files selected for processing (9)
AGENTS.mdopenmeter/billing/charges/README.mdopenmeter/billing/charges/creditpurchase/service/external_test.goopenmeter/billing/charges/creditpurchase/service/invoice.goopenmeter/billing/charges/creditpurchase/service/invoice_test.goopenmeter/billing/charges/creditpurchase/service/realizations/service.goopenmeter/billing/charges/service/creditpurchase_test.gotest/credits/creditgrant_test.gotest/credits/voidgrant_test.go
Summary
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 lintnix develop --impure .#ci -c make test— 6,785 tests passed, 9 skippedPOSTGRES_HOST=127.0.0.1 go test -tags=dynamic ./test/creditsSummary by CodeRabbit
Greptile Summary
The PR refactors invoice-settled credit purchases onto the stateless charge lifecycle and derives detailed states for legacy active purchases.
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
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 .-> FinalReviews (1): Last reviewed commit: "refactor(credit): model invoice purchase..." | Re-trigger Greptile
Context used: