Repository navigation
feat: implement credits-only flat fee handling - #4009
Conversation
📝 WalkthroughWalkthroughThis PR extends the charges system to support credit-only flat-fee charges as first-class citizens alongside usage-based charges. It introduces state machine logic, handler callbacks, distributed locking, persistence mechanisms, and end-to-end orchestration updates. Changes
Sequence Diagram(s)sequenceDiagram
participant Caller
participant FlatFeeService
participant Locker
participant Adapter
participant StateMachine
participant Handler
participant DB
Caller->>FlatFeeService: AdvanceCharge(input)
activate FlatFeeService
FlatFeeService->>FlatFeeService: Validate input
FlatFeeService->>Locker: LockForTX(chargeID)
activate Locker
FlatFeeService->>Adapter: GetByIDs(chargeID)
activate Adapter
Adapter->>DB: Query charge
activate DB
DB-->>Adapter: charge data
deactivate DB
Adapter-->>FlatFeeService: charge
deactivate Adapter
FlatFeeService->>FlatFeeService: Validate settlement mode
FlatFeeService->>StateMachine: NewCreditsOnlyStateMachine(config)
activate StateMachine
StateMachine->>StateMachine: Initialize state machine
deactivate StateMachine
FlatFeeService->>StateMachine: AdvanceUntilStateStable()
activate StateMachine
loop While transitions possible
StateMachine->>StateMachine: FireTriggerNext()
alt Entering Active state
StateMachine->>Handler: OnCreditsOnlyUsageAccrued(amount)
activate Handler
Handler-->>StateMachine: credit allocations
deactivate Handler
StateMachine->>Adapter: CreateCreditAllocations()
activate Adapter
Adapter->>DB: Insert realizations
Adapter-->>StateMachine: success
deactivate Adapter
end
StateMachine->>Adapter: UpdateCharge()
activate Adapter
Adapter->>DB: Update charge state
DB-->>Adapter: success
Adapter-->>StateMachine: success
deactivate Adapter
end
StateMachine-->>FlatFeeService: final charge
deactivate StateMachine
Locker-->>FlatFeeService: unlock
deactivate Locker
FlatFeeService-->>Caller: charge
deactivate FlatFeeService
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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: 3
🧹 Nitpick comments (2)
openmeter/billing/charges/flatfee/charge.go (1)
150-154: Consider clarifying the error message.The error message "advance after is required" is a bit misleading since the field itself is optional (nil is valid). The validation correctly rejects a zero time when the pointer is non-nil, so something like "advance after cannot be zero when set" would be clearer.
✏️ Suggested improvement
if s.AdvanceAfter != nil { if s.AdvanceAfter.IsZero() { - errs = append(errs, fmt.Errorf("advance after is required")) + errs = append(errs, fmt.Errorf("advance after cannot be zero when set")) } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/flatfee/charge.go` around lines 150 - 154, The validation message for s.AdvanceAfter is misleading: change the error produced in the block that checks if s.AdvanceAfter != nil && s.AdvanceAfter.IsZero() to a clearer message such as "advance after cannot be zero when set" so it reflects that a nil pointer is allowed but a zero time value is not; update the fmt.Errorf call in the validation routine that references s.AdvanceAfter to use the new message.openmeter/billing/charges/service/invoicable_test.go (1)
929-1006: Also assert the immediate-final create path does not emit invoice lines.This proves the final state and realizations, but it doesn’t guard the “credits-only skips invoicing” contract on the
create at InvoiceAtpath.createGatheringLinesstill runs beforeautoAdvanceCreatedChargesinopenmeter/billing/charges/service/create.go, so a regression that creates pending lines here would slip through.As per coding guidelines, `**/*_test.go`: Make sure the tests are comprehensive and cover the changes.🧪 Suggested assertion
s.Equal(meta.ChargeStatusFinal, returnedCharge.Status) s.Nil(returnedCharge.State.AdvanceAfter) s.Len(returnedCharge.State.CreditRealizations, 1) s.Equal(float64(50), returnedCharge.State.CreditRealizations[0].Amount.InexactFloat64()) + + gatheringInvoices, err := s.BillingService.ListGatheringInvoices(ctx, billing.ListGatheringInvoicesInput{ + Namespaces: []string{ns}, + Customers: []string{cust.ID}, + Currencies: []currencyx.Code{currencyx.Code(currency.USD)}, + Expand: []billing.GatheringInvoiceExpand{billing.GatheringInvoiceExpandLines}, + }) + s.NoError(err) + s.Len(gatheringInvoices.Items, 0) // And the DB state matches. dbCharge := s.mustGetChargeByID(returnedCharge.GetChargeID())🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/service/invoicable_test.go` around lines 929 - 1006, The test TestFlatFeeCreditOnlyCreateImmediatelyFinal verifies final state and credit realizations but doesn't assert that no invoice lines were emitted; add assertions after the existing checks to ensure the create-at-InvoiceAt credit-only path produced zero invoice lines both on the returned in-memory charge (returnedCharge.State.InvoiceLines or the equivalent invoice-lines slice) and on the DB-loaded charge (dbFF.State.InvoiceLines), to guard against regressions where createGatheringLines runs before autoAdvanceCreatedCharges and creates pending lines.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/billing/charges/flatfee/service/creditsonly.go`:
- Around line 137-140: The production flat-fee adapter's
OnCreditsOnlyUsageAccrued is currently a stub that returns an error; replace
that stub in openmeter/ledger/chargeadapter/flatfee.go by implementing the real
logic (the same behavior tests’ mock provides) so
s.Service.handler.OnCreditsOnlyUsageAccrued(...) in creditsonly.go succeeds in
production: locate the OnCreditsOnlyUsageAccrued method on the flatfee adapter
and implement credit allocation creation/updating and return the
creditAllocations and nil error (mirror the mock handler flow from
handlers_test.go for input mapping, validation, and persistence), ensuring error
wrapping remains consistent if any lower-level calls fail.
In `@openmeter/billing/charges/flatfee/statemachine.go`:
- Around line 35-37: The ToMetaChargeStatus method currently returns
meta.ChargeStatusCreated when s.Validate() fails; change it to return the zero
value for meta.ChargeStatus plus the validation error instead. In other words,
in Status.ToMetaChargeStatus when Validate() returns an error, return a
zero-initialized meta.ChargeStatus (e.g., var zero meta.ChargeStatus or
meta.ChargeStatus(0)) and the error so invalid input cannot silently map to a
real lifecycle state.
In `@test/credits/mockledger.go`:
- Around line 90-101: The mock currently always returns one CreateInput even
when no credits are available; update the logic around creditsToAllocate
(computed from input.AmountToAllocate and l.customerCredits) to check for a zero
allocation and return an empty slice (nil error) when creditsToAllocate is 0 (or
<= 0) so no zero-amount creditrealization.CreateInput is produced; adjust the
code paths that construct the CreateInput with
alpacadecimal.NewFromFloat(creditsToAllocate) and the
ledgertransaction.GroupReference to only run when creditsToAllocate > 0.
---
Nitpick comments:
In `@openmeter/billing/charges/flatfee/charge.go`:
- Around line 150-154: The validation message for s.AdvanceAfter is misleading:
change the error produced in the block that checks if s.AdvanceAfter != nil &&
s.AdvanceAfter.IsZero() to a clearer message such as "advance after cannot be
zero when set" so it reflects that a nil pointer is allowed but a zero time
value is not; update the fmt.Errorf call in the validation routine that
references s.AdvanceAfter to use the new message.
In `@openmeter/billing/charges/service/invoicable_test.go`:
- Around line 929-1006: The test TestFlatFeeCreditOnlyCreateImmediatelyFinal
verifies final state and credit realizations but doesn't assert that no invoice
lines were emitted; add assertions after the existing checks to ensure the
create-at-InvoiceAt credit-only path produced zero invoice lines both on the
returned in-memory charge (returnedCharge.State.InvoiceLines or the equivalent
invoice-lines slice) and on the DB-loaded charge (dbFF.State.InvoiceLines), to
guard against regressions where createGatheringLines runs before
autoAdvanceCreatedCharges and creates pending lines.
🪄 Autofix (Beta)
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
Run ID: c3851b68-2ff2-4f67-890a-90e5f2a12f73
📒 Files selected for processing (19)
.agents/skills/charges/SKILL.mdopenmeter/billing/charges/flatfee/adapter/charge.goopenmeter/billing/charges/flatfee/adapter/mapper.goopenmeter/billing/charges/flatfee/charge.goopenmeter/billing/charges/flatfee/handler.goopenmeter/billing/charges/flatfee/service.goopenmeter/billing/charges/flatfee/service/create.goopenmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/flatfee/service/service.goopenmeter/billing/charges/flatfee/service/triggers.goopenmeter/billing/charges/flatfee/statemachine.goopenmeter/billing/charges/service/advance.goopenmeter/billing/charges/service/base_test.goopenmeter/billing/charges/service/create.goopenmeter/billing/charges/service/handlers_test.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/ledger/chargeadapter/flatfee.gotest/credits/mockledger.gotest/credits/sanity_test.go
Summary
the usage-based credits-only pattern
the full AmountAfterProration as credits via the new OnCreditsOnlyUsageAccrued handler
usage-based ones
Test
with credit realizations), final advance is noop
TestUsageBasedCreateImmediatelyActive, TestUsageBasedCreateImmediatelyFinal)
Summary by CodeRabbit
Release Notes
New Features
Tests