Skip to content

refactor(flatfee): split invoice realization and run realization - #4792

Merged
turip merged 2 commits into
mainfrom
feat/flatfee-split-invoice-run-realization
Jul 27, 2026
Merged

turip merged 2 commits into
mainfrom
feat/flatfee-split-invoice-run-realization

Conversation

@turip

@turip turip commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Summary

This separates realization of a flat-fee charge run from realization of its standard invoice line.

The charge run now retains the charge-side rating and realization outcome, while the standard invoice line is produced from that outcome at the billing boundary. This allows credit-then-invoice runs and invoice lines to use different denominations, which is required when a run is realized in a custom credit currency but invoiced in fiat.

Validation

Not run after rebase, as requested.

Summary by CodeRabbit

  • New Features
    • Introduced flat-fee rating via rateable intents, including proration, effective pricing, and percentage discounts.
    • Added support for building, validating, and persisting detailed billing lines from rating results.
    • Updated credit-only and credit-then-invoice realization flows for consistent credit allocation and reconciliation.
  • Bug Fixes
    • Improved correctness of realization totals, detailed-line totals, and discount/credit handling across flat-fee scenarios.
    • Enforced alignment between charge intent service periods and realization service periods.
  • Documentation
    • Clarified meaning of totals and detailed-line content on realization runs.
  • Tests
    • Expanded coverage for effective-intent rateable intent behavior and discount/correlation handling.

Greptile Summary

This PR separates flat-fee charge realization from standard invoice-line construction.

  • Introduces an effective rateable intent and charge-side rating result.
  • Persists realization detailed lines and reconciles credit allocations against rated totals.
  • Rebuilds standard invoice lines from persisted realization runs at billing boundaries.

Confidence Score: 3/5

The PR is not yet safe to merge because custom-currency credit-then-invoice runs can still be written to fiat invoice lines without cost-basis conversion.

The realization path calculates and persists amounts in the charge currency, while the invoice mapper copies those values into a fiat-denominated standard line and only applies fiat rounding; the configured conversion rate is never applied.

Files Needing Attention: openmeter/billing/charges/flatfee/service/linemapper.go, openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go

Important Files Changed

Filename Overview
openmeter/billing/charges/flatfee/rating.go Introduces the normalized rateable intent used to produce charge-side prices, discounts, periods, and totals.
openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go Moves credit-then-invoice rating and detailed-line persistence into realization runs, while retaining the charge denomination for run calculations.
openmeter/billing/charges/flatfee/service/linemapper.go Reconstructs invoice lines from charge-side runs, but the previously reported custom-to-fiat denomination boundary remains unresolved.
openmeter/billing/charges/flatfee/service/creditsonly.go Rates effective intents before credit allocation and persists reconciled run totals and detailed lines.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  Intent[Effective flat-fee intent] --> Rating[Charge-side rating]
  Rating --> Run[Realization run]
  Run --> Credits[Credit allocation and reconciliation]
  Run --> Mapper[Invoice-line mapper]
  Credits --> Mapper
  Mapper --> Line[Standard invoice line]
Loading

Reviews (2): Last reviewed commit: "fix(flatfee): aggregate credits-only val..." | Re-trigger Greptile

Context used:

@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Flat-fee rating now derives normalized values from effective intents, produces reusable detailed lines and totals, and feeds those results through gathering, credit-only, and credit-then-invoice realization flows. Shared detailed-line credit operations and discount-focused lifecycle tests were added.

Changes

Flat-fee rating and detailed-line contracts

Layer / File(s) Summary
Rateable intent and shared detailed-line operations
openmeter/billing/charges/flatfee/{rating.go,detailedline.go}, openmeter/billing/models/stddetailedline/model.go, openmeter/billing/invoicedetailedline.go, openmeter/billing/charges/{flatfee,usagebased}/realizationrun.go
Effective intents become validated rateable intents; detailed lines gain shared cloning, validation, aggregation, credit reversal, and credit application operations.
Rating integration and standard-line mapping
openmeter/billing/charges/flatfee/service/{create.go,lineengine.go,linemapper.go}, openmeter/billing/charges/flatfee/service/realizations/{rating.go,preview.go}
Gathering previews and standard-line population use rating results, effective pricing and discounts, and charge/run validation.

Credit realization flows

Layer / File(s) Summary
Credit-then-invoice flow
openmeter/billing/charges/flatfee/service/{creditheninvoice.go,lineengine.go}, openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go
Run inputs use line and invoice IDs, while realization starts and reconciliation rebuild runs and detailed lines from rated intents.
Credit-only flow and lifecycle coverage
openmeter/billing/charges/flatfee/service/{creditsonly.go,realizations/creditsonly.go}, openmeter/billing/charges/service/*_test.go
Credit-only allocation consumes rated totals, persists detailed lines, updates runs for zero allocations, and verifies discounted persisted details.

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

Sequence Diagram(s)

sequenceDiagram
  participant FlatFeeCharge
  participant FlatFeeService
  participant RatingService
  participant CreditRealizations
  participant RealizationRun
  FlatFeeService->>FlatFeeCharge: GetRateableIntent()
  FlatFeeService->>RatingService: Rate(rateable intent)
  RatingService-->>FlatFeeService: DetailedLines and Totals
  FlatFeeService->>CreditRealizations: Reconcile credits from rated totals
  CreditRealizations-->>FlatFeeService: Credit realizations
  FlatFeeService->>RealizationRun: Persist totals and detailed lines
Loading

Possibly related PRs

Suggested labels: kind/refactor

Suggested reviewers: tothandras

🚥 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
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 matches the main change: flat-fee invoice realization was split from run realization.
✨ 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/flatfee-split-invoice-run-realization

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.

@turip
turip marked this pull request as ready for review July 27, 2026 08:59
@turip
turip requested a review from a team as a code owner July 27, 2026 08:59

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
openmeter/billing/charges/flatfee/service/create.go (1)

189-216: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Add custom-currency to invoice-currency conversion when materializing flat-fee lines. rateableIntent.GetPrice() carries a custom-currency amount, but here it is placed into lines whose Currency is the fiat invoice currency. Reuse the existing conversion helper plus the charge’s resolved cost basis at these mapping points so fiat totals and invoice patch amounts reflect the converted value rather than relabeled custom-currency values.

🤖 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/flatfee/service/create.go` around lines 189 - 216,
Convert the custom-currency price to the invoice currency before assigning it to
the materialized flat-fee line. Update the mapping in create.go around
gatheringLine and the corresponding mapping in linemapper.go, reusing the
existing currency-conversion helper and the charge’s resolved cost basis so both
line prices and invoice patch amounts contain converted values while retaining
the invoice Currency.
🧹 Nitpick comments (2)
openmeter/billing/charges/flatfee/service/realizations/creditsonly.go (1)

29-42: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider collecting the validation errors instead of bailing on the first one.

The repo convention for Validate() is to accumulate failures and return models.NewNillableGenericValidationError(errors.Join(errs...)) — the sibling StartCreditThenInvoiceRunInput.Validate() in openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go (Lines 24-40) already does exactly that, so this one is the odd one out.

♻️ Proposed refactor
 func (i AllocateCreditsOnlyInput) Validate() error {
+	var errs []error
+
 	if err := i.Charge.Validate(); err != nil {
-		return fmt.Errorf("charge: %w", err)
+		errs = append(errs, fmt.Errorf("charge: %w", err))
 	}
 
 	if err := i.Totals.Validate(); err != nil {
-		return fmt.Errorf("totals: %w", err)
+		errs = append(errs, fmt.Errorf("totals: %w", err))
 	}
 
 	if i.CurrencyCalculator == nil {
-		return fmt.Errorf("currency calculator is required")
+		errs = append(errs, errors.New("currency calculator is required"))
+	} else if err := i.CurrencyCalculator.Validate(); err != nil {
+		errs = append(errs, fmt.Errorf("currency calculator: %w", err))
 	}
 
-	if err := i.CurrencyCalculator.Validate(); err != nil {
-		return fmt.Errorf("currency calculator: %w", err)
-	}
-
-	return nil
+	return models.NewNillableGenericValidationError(errors.Join(errs...))
 }

As per coding guidelines: "For Validate() error methods, collect all validation failures and return models.NewNillableGenericValidationError(errors.Join(errs...)), preserving field context with wrapped errors."

🤖 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/flatfee/service/realizations/creditsonly.go` around
lines 29 - 42, Update the enclosing Validate method to collect all failures from
Totals.Validate, the required CurrencyCalculator check, and
CurrencyCalculator.Validate instead of returning immediately. Preserve each
field’s context in wrapped errors, then return
models.NewNillableGenericValidationError(errors.Join(errs...)) following
StartCreditThenInvoiceRunInput.Validate; return nil when no validation errors
occur.

Source: Coding guidelines

openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go (1)

121-153: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Nice symmetry here — maybe extract the shared credit-application tail?

Both blocks do the exact same five steps (guard allocated > target, map to credits applied, WithCreditsApplied, UpsertDetailedLines, recompute totals + NoFiatTransactionRequired). A small helper taking (ctx, runID, currency, chargeID, target, realizations, ratedLines) and returning (detailedLines, totals) would keep the two paths from drifting apart later.

Totally fine to leave as-is if you prefer the explicitness.

Also applies to: 238-278

🤖 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/flatfee/service/realizations/credittheninvoice.go`
around lines 121 - 153, Extract the duplicated credit-application tail from both
realization paths into a shared helper, such as the logic surrounding
StartCreditThenInvoiceRunResult and its corresponding block near the later flow.
Have it accept the context, run ID, currency, charge ID, allocation target,
credit realizations, and rated lines; perform the allocation guard, credit
mapping, detailed-line update, persistence, and totals calculation; and return
detailed lines plus totals. Replace both inline implementations with the helper
while preserving their existing error context and NoFiatTransactionRequired
behavior.
🤖 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.

Outside diff comments:
In `@openmeter/billing/charges/flatfee/service/create.go`:
- Around line 189-216: Convert the custom-currency price to the invoice currency
before assigning it to the materialized flat-fee line. Update the mapping in
create.go around gatheringLine and the corresponding mapping in linemapper.go,
reusing the existing currency-conversion helper and the charge’s resolved cost
basis so both line prices and invoice patch amounts contain converted values
while retaining the invoice Currency.

---

Nitpick comments:
In `@openmeter/billing/charges/flatfee/service/realizations/creditsonly.go`:
- Around line 29-42: Update the enclosing Validate method to collect all
failures from Totals.Validate, the required CurrencyCalculator check, and
CurrencyCalculator.Validate instead of returning immediately. Preserve each
field’s context in wrapped errors, then return
models.NewNillableGenericValidationError(errors.Join(errs...)) following
StartCreditThenInvoiceRunInput.Validate; return nil when no validation errors
occur.

In `@openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go`:
- Around line 121-153: Extract the duplicated credit-application tail from both
realization paths into a shared helper, such as the logic surrounding
StartCreditThenInvoiceRunResult and its corresponding block near the later flow.
Have it accept the context, run ID, currency, charge ID, allocation target,
credit realizations, and rated lines; perform the allocation guard, credit
mapping, detailed-line update, persistence, and totals calculation; and return
detailed lines plus totals. Replace both inline implementations with the helper
while preserving their existing error context and NoFiatTransactionRequired
behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c5b144d4-810a-4c02-8c7a-8820d6e369f6

📥 Commits

Reviewing files that changed from the base of the PR and between 33876cd and 8c86a5e.

📒 Files selected for processing (18)
  • openmeter/billing/charges/flatfee/charge_test.go
  • openmeter/billing/charges/flatfee/detailedline.go
  • openmeter/billing/charges/flatfee/rating.go
  • openmeter/billing/charges/flatfee/realizationrun.go
  • openmeter/billing/charges/flatfee/service/create.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/creditsonly.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/flatfee/service/linemapper.go
  • openmeter/billing/charges/flatfee/service/realizations/creditsonly.go
  • openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go
  • openmeter/billing/charges/flatfee/service/realizations/preview.go
  • openmeter/billing/charges/flatfee/service/realizations/rating.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/invoicedetailedline.go
  • openmeter/billing/models/stddetailedline/model.go

@turip turip added release-note/misc Miscellaneous changes area/billing labels Jul 27, 2026
@turip

turip commented Jul 27, 2026

Copy link
Copy Markdown
Member Author

CodeRabbit follow-up:

  • AllocateCreditsOnlyInput.Validate: fixed in 05a53d5ed by aggregating validation failures and handling a nil currency calculator safely.
  • Custom-currency conversion: addressed together with the Greptile finding.
  • CTI credit-application helper extraction: will not implement; the explicit lifecycle paths are preferred here and the suggestion was non-blocking.
  • Docstring coverage warning: will not implement; we will not add mechanical docstrings solely to satisfy the bot metric.

@turip
turip merged commit c582e04 into main Jul 27, 2026
25 of 27 checks passed
@turip
turip deleted the feat/flatfee-split-invoice-run-realization branch July 27, 2026 09:52
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