Skip to content

feat: implement credits-only flat fee handling - #4009

Merged
GAlexIHU merged 2 commits into
mainfrom
feat/flat-fee-credits-only
Mar 26, 2026
Merged

GAlexIHU merged 2 commits into
mainfrom
feat/flat-fee-credits-only

Conversation

@turip

@turip turip commented Mar 26, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Implement credits-only lifecycle for flat fee charges using a state machine (Created → Active → Final), mirroring
    the usage-based credits-only pattern
  • Flat fee credit-only charges start as Created and transition to Final when clock.Now() >= InvoiceAt, allocating
    the full AmountAfterProration as credits via the new OnCreditsOnlyUsageAccrued handler
  • Extend AdvanceCharges dispatch and autoAdvanceCreatedCharges to handle flat fee credit-only charges alongside
    usage-based ones

Test

  • TestFlatFeeCreditOnlyLifecycle — create before InvoiceAt (stays Created), advance at InvoiceAt (goes to Final
    with credit realizations), final advance is noop
  • TestFlatFeeCreditOnlyCreateImmediatelyFinal — auto-advance on create when clock >= InvoiceAt
  • All existing tests pass (TestFlatFeePartialCreditRealizations, TestUsageBasedCreditOnlyLifecycle,
    TestUsageBasedCreateImmediatelyActive, TestUsageBasedCreateImmediatelyFinal)

Summary by CodeRabbit

Release Notes

  • New Features

    • Added credit-only settlement mode support for flat-fee charges with automated state progression (Created → Active → Final)
    • Integrated flat-fee credit-only charge advancement into the main billing workflow alongside usage-based charges
    • Implemented credit allocation handler for flat-fee credit-only activation events
  • Tests

    • Added test coverage for flat-fee credit-only charge lifecycle, immediate finalization, and state transitions

@coderabbitai

coderabbitai Bot commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This 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

Cohort / File(s) Summary
Flat-Fee Type System
openmeter/billing/charges/flatfee/charge.go, flatfee/handler.go, flatfee/statemachine.go
Added State.AdvanceAfter field with validation, new OnCreditsOnlyUsageAccruedInput handler callback type and interface method to support credit allocation, and Status/Trigger types with validation and transitions for the state machine.
Flat-Fee Service Implementation
openmeter/billing/charges/flatfee/service/service.go, service/create.go, service/triggers.go, service/creditsonly.go
Wired distributed Locker into service config, updated Create to set initial status based on settlement mode, implemented AdvanceCharge endpoint with transaction + lock acquisition, and added comprehensive CreditsOnlyStateMachine managing state transitions, handler callbacks, and credit realizations persistence.
Flat-Fee Persistence
openmeter/billing/charges/flatfee/adapter/charge.go, adapter/mapper.go
Extended adapter to persist AdvanceAfter via SetAdvanceAfter in charge updates, and updated mapper to populate State.AdvanceAfter when loading charges from DB.
Charges Service Orchestration
openmeter/billing/charges/service/advance.go, service/create.go
Reorganized AdvanceCharges to partition charges by type and process flat-fee credit-only charges via new AdvanceCharge endpoint, and updated autoAdvanceCreatedCharges to gather customers from both usage-based and flat-fee credit-only charges.
Test Scaffolding & Handlers
openmeter/billing/charges/service/base_test.go, service/handlers_test.go, openmeter/ledger/chargeadapter/flatfee.go, test/credits/mockledger.go, test/credits/sanity_test.go
Moved locker initialization earlier in test setup and wired it into service configs, extended flat-fee test handler with OnCreditsOnlyUsageAccrued callback support, added ledger adapter handler stub, and implemented mock ledger credit allocation logic.
Integration Tests & Documentation
openmeter/billing/charges/service/invoicable_test.go, .agents/skills/charges/SKILL.md
Added comprehensive lifecycle tests covering credit-only flat-fee creation, advancement at invoice time, and immediate finality scenarios, plus updated guidance documenting supported behaviors, state transitions, and configuration requirements.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • tothandras
  • GAlexIHU
  • chrisgacsal
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: implement credits-only flat fee handling' directly describes the main change: implementing a credits-only lifecycle for flat fee charges, which is the core of this PR.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/flat-fee-credits-only

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 and usage tips.

@turip turip added release-note/feature Release note: Exciting New Features area/billing labels Mar 26, 2026
@turip
turip marked this pull request as ready for review March 26, 2026 09:35
@turip
turip requested a review from a team as a code owner March 26, 2026 09:35
@turip
turip requested a review from GAlexIHU March 26, 2026 09:35

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

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 InvoiceAt path. createGatheringLines still runs before autoAdvanceCreatedCharges in openmeter/billing/charges/service/create.go, so a regression that creates pending lines here would slip through.

🧪 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())
As per coding guidelines, `**/*_test.go`: Make sure the tests are comprehensive and cover the changes.
🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 37d4d5e and 12ef36c.

📒 Files selected for processing (19)
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go
  • openmeter/billing/charges/flatfee/charge.go
  • openmeter/billing/charges/flatfee/handler.go
  • openmeter/billing/charges/flatfee/service.go
  • openmeter/billing/charges/flatfee/service/create.go
  • openmeter/billing/charges/flatfee/service/creditsonly.go
  • openmeter/billing/charges/flatfee/service/service.go
  • openmeter/billing/charges/flatfee/service/triggers.go
  • openmeter/billing/charges/flatfee/statemachine.go
  • openmeter/billing/charges/service/advance.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/handlers_test.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/ledger/chargeadapter/flatfee.go
  • test/credits/mockledger.go
  • test/credits/sanity_test.go

Comment thread test/credits/mockledger.go Resolved

This branch was previously deployed

1 inactive deployment
dev — 12ef36c4 Deployed Mar 26, 2026 by turip via Migration Checks #12871
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants