Repository navigation
refactor(flatfee): split invoice realization and run realization - #4792
Conversation
📝 WalkthroughWalkthroughFlat-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. ChangesFlat-fee rating and detailed-line contracts
Credit realization flows
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
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ 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.
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 liftAdd 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 whoseCurrencyis 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 winConsider collecting the validation errors instead of bailing on the first one.
The repo convention for
Validate()is to accumulate failures and returnmodels.NewNillableGenericValidationError(errors.Join(errs...))— the siblingStartCreditThenInvoiceRunInput.Validate()inopenmeter/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 winNice 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
📒 Files selected for processing (18)
openmeter/billing/charges/flatfee/charge_test.goopenmeter/billing/charges/flatfee/detailedline.goopenmeter/billing/charges/flatfee/rating.goopenmeter/billing/charges/flatfee/realizationrun.goopenmeter/billing/charges/flatfee/service/create.goopenmeter/billing/charges/flatfee/service/creditheninvoice.goopenmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/linemapper.goopenmeter/billing/charges/flatfee/service/realizations/creditsonly.goopenmeter/billing/charges/flatfee/service/realizations/credittheninvoice.goopenmeter/billing/charges/flatfee/service/realizations/preview.goopenmeter/billing/charges/flatfee/service/realizations/rating.goopenmeter/billing/charges/service/base_test.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/charges/usagebased/realizationrun.goopenmeter/billing/invoicedetailedline.goopenmeter/billing/models/stddetailedline/model.go
|
CodeRabbit follow-up:
|
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
Greptile Summary
This PR separates flat-fee charge realization from standard invoice-line construction.
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
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]Reviews (2): Last reviewed commit: "fix(flatfee): aggregate credits-only val..." | Re-trigger Greptile
Context used: