Repository navigation
refactor: currencyx package - #4701
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR replaces calculator-based currency handling with builder-created ChangesCurrency abstraction and allocation
Billing and rating flows
Integrations
Estimated code review effort: 5 (Critical) | ~120 minutes 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 |
5c7b244 to
38b5b37
Compare
38b5b37 to
740cb95
Compare
740cb95 to
5a8f1bb
Compare
5a8f1bb to
33bbaf3
Compare
98b149b to
c21b79c
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
pkg/currencyx/allocation.go (1)
242-311: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winNil-currency validation is broken in
allocation.go, and the test that would've caught it was removed. The nil check invalidateWeightedAllocationInputdoesn't return early, so it panics instead of validating cleanly;validateAmountAllocationInputhas no nil check at all. The old "invalid calculator" subtest that used to exercise this path is gone, so nothing currently catches the regression.
pkg/currencyx/allocation.go#L242-L311: make both validators return early with a clean error whencurrency == nil, per the fix already discussed in this file's review history.pkg/currencyx/allocation_test.go#L142-L186: add back a subtest (for bothTestAllocateByWeightValidationandTestAllocateByAmountValidation) that passes a nilcurrencyx.Currencyand asserts a clean validation error instead of a panic.🤖 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 `@pkg/currencyx/allocation.go` around lines 242 - 311, Update pkg/currencyx/allocation.go lines 242-311 so validateWeightedAllocationInput and validateAmountAllocationInput return immediately with a clean “currency is required” validation error when currency is nil, before calling any Currency methods. In pkg/currencyx/allocation_test.go lines 142-186, restore nil-currency subtests for both TestAllocateByWeightValidation and TestAllocateByAmountValidation, asserting validation errors are returned without panicking.openmeter/ledger/validations.go (1)
78-83: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winUse the raw currency code in the error attributes.
Hey! If
Build()returns an error, thecurrencyvariable will likely benilor a zero value. It might be super helpful to log the actual currency code that failed, rather than the empty object, so we have better context when debugging!🛠️ Proposed fix to log the raw currency code
if err != nil { return ErrCurrencyInvalid.WithAttrs(models.Attributes{ - "currency": currency, + "currency": entry.PostingAddress().Route().Route().Currency, "error": err, }) }🤖 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/ledger/validations.go` around lines 78 - 83, Update the ErrCurrencyInvalid attributes in the validation flow around Build() to use the original raw currency-code input rather than the parsed currency variable. Keep the existing error attribute key and preserve the current error-return behavior.openmeter/billing/charges/usagebased/service/run/preview.go (1)
77-79: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winAdd a nil check before calling
Validate()on the interface.Hey there! Just a quick heads-up: since
CurrencyCalculatoris an interface, callingValidate()on it when it hasn't been provided will trigger a panic. We should probably add a quick nil check here, just like the one mentioned forCorrectAllCredits.🐛 Proposed fix
- if err := i.CurrencyCalculator.Validate(); err != nil { - errs = append(errs, fmt.Errorf("currency calculator: %w", err)) - } + if i.CurrencyCalculator == nil { + 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)) + }🤖 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/usagebased/service/run/preview.go` around lines 77 - 79, Update the validation block for CurrencyCalculator to check that the interface is non-nil before calling Validate(), while preserving the existing error wrapping when validation runs. Follow the established nil-check pattern used for CorrectAllCredits.openmeter/billing/charges/usagebased/service/run/correct.go (1)
142-160: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winPrevent panics on missing currency and align validation with guidelines.
The field type for
Currency/CurrencyCalculatorwas updated to thecurrencyx.Currencyinterface, but theValidate()methods were not updated to check fornil. Calling.Validate()on anilinterface will cause a runtime panic. Additionally, as per coding guidelines,Validate() errormethods must collect all validation errors and returnmodels.NewNillableGenericValidationErrorrather than returning early on the first error.(Note: ensure
github.com/openmeterio/openmeter/openmeter/billing/modelsis imported where needed).
openmeter/billing/charges/usagebased/service/run/correct.go#L142-L160: Add anilcheck forCurrencyCalculator, collect all errors, and return a joined nillable validation error.🛠️ Proposed fix
-func (i CorrectAllCreditRealizationsInput) Validate() error { - if err := i.Charge.Validate(); err != nil { - return fmt.Errorf("charge: %w", err) - } - - if err := i.Run.Validate(); err != nil { - return fmt.Errorf("run: %w", err) - } - - if i.AllocateAt.IsZero() { - return fmt.Errorf("allocate at is required") - } - - if err := i.CurrencyCalculator.Validate(); err != nil { - return fmt.Errorf("currency calculator: %w", err) - } - - return nil -} +func (i CorrectAllCreditRealizationsInput) Validate() error { + var errs []error + if err := i.Charge.Validate(); err != nil { + errs = append(errs, fmt.Errorf("charge: %w", err)) + } + + if err := i.Run.Validate(); err != nil { + errs = append(errs, fmt.Errorf("run: %w", err)) + } + + if i.AllocateAt.IsZero() { + errs = append(errs, fmt.Errorf("allocate at is required")) + } + + if i.CurrencyCalculator == nil { + errs = append(errs, fmt.Errorf("currency calculator is required")) + } else if err := i.CurrencyCalculator.Validate(); err != nil { + errs = append(errs, fmt.Errorf("currency calculator: %w", err)) + } + + return models.NewNillableGenericValidationError(errors.Join(errs...)) +}
openmeter/billing/charges/usagebased/service/run/correct.go#L34-L56: Apply the same pattern to check for anilCurrencyCalculator, collect all errors, and return a joined nillable validation error.🛠️ Proposed fix
-func (i ReconcileCreditRealizationsInput) Validate() error { - if err := i.Charge.Validate(); err != nil { - return fmt.Errorf("charge: %w", err) - } - - if err := i.Run.Validate(); err != nil { - return fmt.Errorf("run: %w", err) - } - - if i.AllocateAt.IsZero() { - return fmt.Errorf("allocate at is required") - } - - if i.TargetAmount.IsNegative() { - return fmt.Errorf("target amount must be zero or positive") - } - - if err := i.CurrencyCalculator.Validate(); err != nil { - return fmt.Errorf("currency calculator: %w", err) - } - - return nil -} +func (i ReconcileCreditRealizationsInput) Validate() error { + var errs []error + if err := i.Charge.Validate(); err != nil { + errs = append(errs, fmt.Errorf("charge: %w", err)) + } + + if err := i.Run.Validate(); err != nil { + errs = append(errs, fmt.Errorf("run: %w", err)) + } + + if i.AllocateAt.IsZero() { + errs = append(errs, fmt.Errorf("allocate at is required")) + } + + if i.TargetAmount.IsNegative() { + errs = append(errs, fmt.Errorf("target amount must be zero or positive")) + } + + if i.CurrencyCalculator == nil { + errs = append(errs, fmt.Errorf("currency calculator is required")) + } else if err := i.CurrencyCalculator.Validate(); err != nil { + errs = append(errs, fmt.Errorf("currency calculator: %w", err)) + } + + return models.NewNillableGenericValidationError(errors.Join(errs...)) +}
openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go#L97-L110: Add anilcheck forCurrencyand wrap the returnederrors.Joinwithmodels.NewNillableGenericValidationError.🛠️ Proposed fix
func (i ApplyInput) Validate() error { var errs []error if i.Plan == nil { errs = append(errs, fmt.Errorf("plan is required")) } if err := i.Customer.Validate(); err != nil { errs = append(errs, fmt.Errorf("customer: %w", err)) } - if err := i.Currency.Validate(); err != nil { + if i.Currency == nil { + errs = append(errs, fmt.Errorf("currency is required")) + } else if err := i.Currency.Validate(); err != nil { errs = append(errs, fmt.Errorf("currency: %w", err)) } - return errors.Join(errs...) + return models.NewNillableGenericValidationError(errors.Join(errs...)) }
openmeter/billing/charges/flatfee/service/realizations/creditsonly.go#L24-L38: Check for anilCurrencyCalculator, collect errors into a slice instead of returning early, and return the joined nillable validation error.🛠️ Proposed fix
-func (i AllocateCreditsOnlyInput) Validate() error { - if err := i.Charge.Validate(); err != nil { - return fmt.Errorf("charge: %w", err) - } - - if i.Amount.IsNegative() { - return fmt.Errorf("amount cannot be negative") - } - - if err := i.CurrencyCalculator.Validate(); err != nil { - return fmt.Errorf("currency calculator: %w", err) - } - - return nil -} +func (i AllocateCreditsOnlyInput) Validate() error { + var errs []error + if err := i.Charge.Validate(); err != nil { + errs = append(errs, fmt.Errorf("charge: %w", err)) + } + + if i.Amount.IsNegative() { + errs = append(errs, fmt.Errorf("amount cannot be negative")) + } + + if i.CurrencyCalculator == nil { + errs = append(errs, fmt.Errorf("currency calculator is required")) + } else if err := i.CurrencyCalculator.Validate(); err != nil { + errs = append(errs, fmt.Errorf("currency calculator: %w", err)) + } + + return models.NewNillableGenericValidationError(errors.Join(errs...)) +}🤖 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/usagebased/service/run/correct.go` around lines 142 - 160, Update all listed validation sites to guard interface-typed Currency/CurrencyCalculator fields against nil before calling Validate, collect every validation error instead of returning early, and return errors.Join wrapped with models.NewNillableGenericValidationError; apply this to both CorrectAllCreditRealizationsInput.Validate and the other validation method in correct.go, Currency validation in reconciler.go, and CurrencyCalculator validation in creditsonly.go, adding the models import where required.Source: Coding guidelines
🧹 Nitpick comments (3)
pkg/currencyx/allocation_test.go (1)
142-186: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMissing nil-currency test case (see linked finding in
allocation.go).The old "invalid calculator" subtest is gone and nothing replaced it to cover a nil/invalid
Currency— which would have caught the panic bug invalidateWeightedAllocationInput. See consolidated comment.🤖 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 `@pkg/currencyx/allocation_test.go` around lines 142 - 186, The TestAllocateByWeightValidation table is missing coverage for a nil or invalid Currency that previously exercised the invalid-calculator path. Add a validation case invoking AllocateByWeight with an invalid Currency and assert it returns an error without panicking, using the expected currency-validation message; keep the existing amount, weight, and zero-amount cases unchanged.test/app/stripe/invoice_credits_test.go (1)
188-191: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse string literal
"USD"for consistency.The rest of this test file uses
currencyx.Code("USD")directly (e.g., lines 121, 126, and 146). Using the string literal here maintains consistency and allows you to remove the newly addedgithub.com/invopop/gobl/currencyimport entirely, nicely matching the cleanup you did indetailedline_test.go.♻️ Proposed refactor
Apply the
"USD"literal to this snippet:- cur, err := currencyx.NewCurrencyBuilder(currencyx.CurrencyTypeFiat). - WithCode(currencyx.Code(currency.USD)). - Build() + cur, err := currencyx.NewCurrencyBuilder(currencyx.CurrencyTypeFiat). + WithCode(currencyx.Code("USD")). + Build()Also apply it further down in the final invoice test block (line 257):
- cur, err := currencyx.NewCurrencyBuilder(currencyx.CurrencyTypeFiat). - WithCode(currencyx.Code(currency.USD)). - Build() + cur, err := currencyx.NewCurrencyBuilder(currencyx.CurrencyTypeFiat). + WithCode(currencyx.Code("USD")). + Build()Then you can safely drop the import at the top of the file:
- "github.com/invopop/gobl/currency"🤖 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 `@test/app/stripe/invoice_credits_test.go` around lines 188 - 191, Replace the currency.USD references in the affected test setup and final invoice test block with the string literal "USD" passed to currencyx.Code. After both usages are updated, remove the now-unused github.com/invopop/gobl/currency import from the test file.openmeter/billing/charges/flatfee/service/realizations/preview.go (1)
60-64: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUpdate the stale error message.
This now builds a
currency, but the wrapped error still says"get currency calculator". Please rename it to something like"build currency"so logs accurately describe the failing operation.🤖 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/preview.go` around lines 60 - 64, Update the error wrapping in the currency construction flow of the preview function to describe building the currency rather than getting a currency calculator. Change the stale message in the err branch after currencyx.CurrencyBuilder.Build while preserving the existing wrapped error and return 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.
Inline comments:
In `@openmeter/billing/rating/service/rate/tieredgraduated.go`:
- Around line 133-135: Update the validation around Currency in the tiered
graduated rate calculation to check whether the interface is nil before calling
Details(). Return the existing “currency calculator is required” error for both
nil Currency and an empty currency code, while preserving the current behavior
for valid currencies.
In `@pkg/currencyx/currency.go`:
- Around line 370-392: Update the custom-currency error return in
CurrencyBuilder.Build so it returns a plain nil Currency interface alongside the
validation error, preventing a typed-nil result from escaping. Keep the existing
precision validation and successful newCustomCurrency path unchanged.
---
Outside diff comments:
In `@openmeter/billing/charges/usagebased/service/run/correct.go`:
- Around line 142-160: Update all listed validation sites to guard
interface-typed Currency/CurrencyCalculator fields against nil before calling
Validate, collect every validation error instead of returning early, and return
errors.Join wrapped with models.NewNillableGenericValidationError; apply this to
both CorrectAllCreditRealizationsInput.Validate and the other validation method
in correct.go, Currency validation in reconciler.go, and CurrencyCalculator
validation in creditsonly.go, adding the models import where required.
In `@openmeter/billing/charges/usagebased/service/run/preview.go`:
- Around line 77-79: Update the validation block for CurrencyCalculator to check
that the interface is non-nil before calling Validate(), while preserving the
existing error wrapping when validation runs. Follow the established nil-check
pattern used for CorrectAllCredits.
In `@openmeter/ledger/validations.go`:
- Around line 78-83: Update the ErrCurrencyInvalid attributes in the validation
flow around Build() to use the original raw currency-code input rather than the
parsed currency variable. Keep the existing error attribute key and preserve the
current error-return behavior.
In `@pkg/currencyx/allocation.go`:
- Around line 242-311: Update pkg/currencyx/allocation.go lines 242-311 so
validateWeightedAllocationInput and validateAmountAllocationInput return
immediately with a clean “currency is required” validation error when currency
is nil, before calling any Currency methods. In pkg/currencyx/allocation_test.go
lines 142-186, restore nil-currency subtests for both
TestAllocateByWeightValidation and TestAllocateByAmountValidation, asserting
validation errors are returned without panicking.
---
Nitpick comments:
In `@openmeter/billing/charges/flatfee/service/realizations/preview.go`:
- Around line 60-64: Update the error wrapping in the currency construction flow
of the preview function to describe building the currency rather than getting a
currency calculator. Change the stale message in the err branch after
currencyx.CurrencyBuilder.Build while preserving the existing wrapped error and
return behavior.
In `@pkg/currencyx/allocation_test.go`:
- Around line 142-186: The TestAllocateByWeightValidation table is missing
coverage for a nil or invalid Currency that previously exercised the
invalid-calculator path. Add a validation case invoking AllocateByWeight with an
invalid Currency and assert it returns an error without panicking, using the
expected currency-validation message; keep the existing amount, weight, and
zero-amount cases unchanged.
In `@test/app/stripe/invoice_credits_test.go`:
- Around line 188-191: Replace the currency.USD references in the affected test
setup and final invoice test block with the string literal "USD" passed to
currencyx.Code. After both usages are updated, remove the now-unused
github.com/invopop/gobl/currency import from the test file.
🪄 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: 2e9f844e-a02d-43ff-8719-917fae6008c4
📒 Files selected for processing (67)
api/v3/handlers/customers/credits/convert.goopenmeter/app/stripe/calculator.goopenmeter/billing/charges/creditpurchase/charge.goopenmeter/billing/charges/creditpurchase/service/create.goopenmeter/billing/charges/creditpurchase/service/external_test.goopenmeter/billing/charges/flatfee/charge.goopenmeter/billing/charges/flatfee/handler.goopenmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/linemapper.goopenmeter/billing/charges/flatfee/service/realizations/correct.goopenmeter/billing/charges/flatfee/service/realizations/creditsonly.goopenmeter/billing/charges/flatfee/service/realizations/credittheninvoice.goopenmeter/billing/charges/flatfee/service/realizations/preview.goopenmeter/billing/charges/models/creditrealization/correction.goopenmeter/billing/charges/models/creditrealization/correction_test.goopenmeter/billing/charges/models/creditrealization/realizations.goopenmeter/billing/charges/usagebased/handler.goopenmeter/billing/charges/usagebased/service/creditsonly_test.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/charges/usagebased/service/linemapper.goopenmeter/billing/charges/usagebased/service/run/correct.goopenmeter/billing/charges/usagebased/service/run/create.goopenmeter/billing/charges/usagebased/service/run/credits.goopenmeter/billing/charges/usagebased/service/run/preview.goopenmeter/billing/charges/usagebased/service/statemachine.goopenmeter/billing/charges/usagebased/service/triggers.goopenmeter/billing/invoicedetailedline.goopenmeter/billing/invoicedetailedline_test.goopenmeter/billing/invoicelinediscount.goopenmeter/billing/models/creditsapplied/model.goopenmeter/billing/models/totals/model.goopenmeter/billing/models/totals/model_test.goopenmeter/billing/rating/detailedline.goopenmeter/billing/rating/detailedline_test.goopenmeter/billing/rating/service/detailedline.goopenmeter/billing/rating/service/mutator/credits_test.goopenmeter/billing/rating/service/mutator/discountpercentage.goopenmeter/billing/rating/service/rate/tieredgraduated.goopenmeter/billing/rating/service/rate/tieredgraduated_test.goopenmeter/billing/rating/service/rate/types.goopenmeter/billing/worker/subscriptionsync/service/reconcile.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.goopenmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.goopenmeter/billing/worker/subscriptionsync/service/sync.goopenmeter/billing/worker/subscriptionsync/service/targetstate/targetstate.goopenmeter/billing/worker/subscriptionsync/service/targetstate/targetstateitem.goopenmeter/ledger/chargeadapter/creditpurchase.goopenmeter/ledger/chargeadapter/flatfee.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/usagebased.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/collector/correct_test.goopenmeter/ledger/validations.goopenmeter/ledger/validations_test.gopkg/currencyx/allocation.gopkg/currencyx/allocation_test.gopkg/currencyx/code.gopkg/currencyx/costbasis.gopkg/currencyx/currency.gopkg/currencyx/currency_test.gopkg/currencyx/fiat.gopkg/currencyx/fiat_test.gopkg/currencyx/validation.gotest/app/stripe/invoice_credits_test.go
💤 Files with no reviewable changes (3)
- pkg/currencyx/fiat_test.go
- pkg/currencyx/validation.go
- pkg/currencyx/fiat.go
GAlexIHU
left a comment
There was a problem hiding this comment.
There's a lot of change surface, i'm worried about the nil value handling & constructor return types in general
|
Also, I checked and realized we were always off on rounding (half-away-from-zero instead of bankers). Fortunately as billing/charges/ledger stores on precision after rounding it is actually safe to change. Let's change both FIAT and CUSTOM rounding to Bankers now. |
|
Also, please make sure to either nuke or properly update the currencyx skill & references as it currently misleads agents |
c21b79c to
7d29015
Compare
|
Want your agent to iterate on Greptile's feedback? Try greploops. |
There was a problem hiding this comment.
Actionable comments posted: 2
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/realizations/correct.go (1)
48-50: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winGuard
CurrencyCalculatorbefore callingValidate().
A nil interface here will panic instead of returning a validation error; add the same check inCorrectAllCreditRealizationsInput.Validate()too.🤖 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/correct.go` around lines 48 - 50, Guard CurrencyCalculator before invoking Validate in the current validation method, returning/appending a validation error when it is nil instead of dereferencing it. Apply the same nil-check behavior in CorrectAllCreditRealizationsInput.Validate(), while preserving the existing wrapped validation error for non-nil calculators.Source: Path instructions
🧹 Nitpick comments (2)
openmeter/billing/rating/service/rate/types.go (1)
33-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
errors.Newfor static errors.A tiny nitpick for you: as per path instructions prioritizing readability, we can swap
fmt.Errorfforerrors.Newsince there are no formatting verbs used here. It's just a bit more idiomatic!♻️ Proposed fix
- if i.CurrencyCalculator == nil { - return fmt.Errorf("currency is required") - } + if i.CurrencyCalculator == nil { + return errors.New("currency is required") + }🤖 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/rating/service/rate/types.go` around lines 33 - 35, Replace the static fmt.Errorf call in the CurrencyCalculator validation with errors.New, adding or reusing the errors import as needed while preserving the existing error message and control flow.Source: Path instructions
openmeter/billing/charges/usagebased/handler.go (1)
82-90: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSimplify the nil checks.
Just a tiny cleanup suggestion: as per path instructions to prioritize readability and maintainability, we can merge these two consecutive
ifstatements into a singleif-elseblock for a slightly cleaner flow. Also, since there's no formatting needed,errors.Newis a perfect fit here!♻️ Proposed refactor
- if currency == nil { - errs = append(errs, fmt.Errorf("currency is required")) - } - - if currency != nil { - if err := i.Corrections.ValidateWith(currency); err != nil { - errs = append(errs, fmt.Errorf("corrections: %w", err)) - } - } + if currency == nil { + errs = append(errs, errors.New("currency is required")) + } else if err := i.Corrections.ValidateWith(currency); err != nil { + errs = append(errs, fmt.Errorf("corrections: %w", err)) + }🤖 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/usagebased/handler.go` around lines 82 - 90, Refactor the consecutive currency checks in the validation flow into a single if-else structure: retain the required-currency error for nil values, and run Corrections.ValidateWith only for non-nil currency values. Replace fmt.Errorf("currency is required") with errors.New("currency is required"), adding the necessary import.Source: Path instructions
🤖 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.
Inline comments:
In `@pkg/currencyx/currency.go`:
- Around line 73-79: Remove the stale exact-parameter behavior description from
the comment above formatCurrencyAmount. Keep the accurate documentation about
formatting rules, integer precision, fractional rescaling, and sign placement,
ensuring the comment no longer implies callers can choose exact preservation.
- Around line 156-162: Complete the CurrencyDetails mappings in
FiatCurrency.Details and the corresponding implementation around CurrencyDetails
at pkg/currencyx/currency.go lines 256-262 by copying DecimalMark and
ThousandsSeparator from the respective definition objects (f.def and c.def),
preserving all existing field mappings.
---
Outside diff comments:
In `@openmeter/billing/charges/flatfee/service/realizations/correct.go`:
- Around line 48-50: Guard CurrencyCalculator before invoking Validate in the
current validation method, returning/appending a validation error when it is nil
instead of dereferencing it. Apply the same nil-check behavior in
CorrectAllCreditRealizationsInput.Validate(), while preserving the existing
wrapped validation error for non-nil calculators.
---
Nitpick comments:
In `@openmeter/billing/charges/usagebased/handler.go`:
- Around line 82-90: Refactor the consecutive currency checks in the validation
flow into a single if-else structure: retain the required-currency error for nil
values, and run Corrections.ValidateWith only for non-nil currency values.
Replace fmt.Errorf("currency is required") with errors.New("currency is
required"), adding the necessary import.
In `@openmeter/billing/rating/service/rate/types.go`:
- Around line 33-35: Replace the static fmt.Errorf call in the
CurrencyCalculator validation with errors.New, adding or reusing the errors
import as needed while preserving the existing error message and control flow.
🪄 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: 9aa896a7-7d95-485a-a99f-98474467ee44
📒 Files selected for processing (67)
api/v3/handlers/customers/credits/convert.goopenmeter/app/stripe/calculator.goopenmeter/billing/charges/creditpurchase/charge.goopenmeter/billing/charges/creditpurchase/service/create.goopenmeter/billing/charges/creditpurchase/service/external_test.goopenmeter/billing/charges/flatfee/charge.goopenmeter/billing/charges/flatfee/handler.goopenmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/linemapper.goopenmeter/billing/charges/flatfee/service/realizations/correct.goopenmeter/billing/charges/flatfee/service/realizations/creditsonly.goopenmeter/billing/charges/flatfee/service/realizations/credittheninvoice.goopenmeter/billing/charges/flatfee/service/realizations/preview.goopenmeter/billing/charges/models/creditrealization/correction.goopenmeter/billing/charges/models/creditrealization/correction_test.goopenmeter/billing/charges/models/creditrealization/realizations.goopenmeter/billing/charges/usagebased/handler.goopenmeter/billing/charges/usagebased/service/creditsonly_test.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/charges/usagebased/service/linemapper.goopenmeter/billing/charges/usagebased/service/run/correct.goopenmeter/billing/charges/usagebased/service/run/create.goopenmeter/billing/charges/usagebased/service/run/credits.goopenmeter/billing/charges/usagebased/service/run/preview.goopenmeter/billing/charges/usagebased/service/statemachine.goopenmeter/billing/charges/usagebased/service/triggers.goopenmeter/billing/invoicedetailedline.goopenmeter/billing/invoicedetailedline_test.goopenmeter/billing/invoicelinediscount.goopenmeter/billing/models/creditsapplied/model.goopenmeter/billing/models/totals/model.goopenmeter/billing/models/totals/model_test.goopenmeter/billing/rating/detailedline.goopenmeter/billing/rating/detailedline_test.goopenmeter/billing/rating/service/detailedline.goopenmeter/billing/rating/service/mutator/credits_test.goopenmeter/billing/rating/service/mutator/discountpercentage.goopenmeter/billing/rating/service/rate/tieredgraduated.goopenmeter/billing/rating/service/rate/tieredgraduated_test.goopenmeter/billing/rating/service/rate/types.goopenmeter/billing/worker/subscriptionsync/service/reconcile.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.goopenmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.goopenmeter/billing/worker/subscriptionsync/service/sync.goopenmeter/billing/worker/subscriptionsync/service/targetstate/targetstate.goopenmeter/billing/worker/subscriptionsync/service/targetstate/targetstateitem.goopenmeter/ledger/chargeadapter/creditpurchase.goopenmeter/ledger/chargeadapter/flatfee.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/usagebased.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/collector/correct_test.goopenmeter/ledger/validations.goopenmeter/ledger/validations_test.gopkg/currencyx/allocation.gopkg/currencyx/allocation_test.gopkg/currencyx/code.gopkg/currencyx/costbasis.gopkg/currencyx/currency.gopkg/currencyx/currency_test.gopkg/currencyx/fiat.gopkg/currencyx/fiat_test.gopkg/currencyx/validation.gotest/app/stripe/invoice_credits_test.go
💤 Files with no reviewable changes (3)
- pkg/currencyx/fiat.go
- pkg/currencyx/validation.go
- pkg/currencyx/fiat_test.go
🚧 Files skipped from review as they are similar to previous changes (56)
- openmeter/billing/charges/flatfee/handler.go
- openmeter/billing/charges/usagebased/service/run/preview.go
- openmeter/billing/models/creditsapplied/model.go
- pkg/currencyx/costbasis.go
- openmeter/billing/charges/usagebased/service/run/create.go
- openmeter/billing/rating/service/mutator/discountpercentage.go
- openmeter/billing/charges/usagebased/service/statemachine.go
- openmeter/billing/charges/flatfee/service/realizations/creditsonly.go
- pkg/currencyx/code.go
- openmeter/billing/charges/usagebased/service/run/credits.go
- openmeter/ledger/validations_test.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go
- openmeter/billing/invoicedetailedline.go
- openmeter/billing/charges/flatfee/service/lineengine.go
- openmeter/billing/charges/creditpurchase/service/external_test.go
- openmeter/billing/models/totals/model.go
- openmeter/billing/charges/creditpurchase/service/create.go
- openmeter/billing/invoicelinediscount.go
- openmeter/billing/worker/subscriptionsync/service/reconcile.go
- openmeter/billing/charges/usagebased/service/linemapper.go
- openmeter/billing/worker/subscriptionsync/service/targetstate/targetstateitem.go
- openmeter/billing/charges/models/creditrealization/realizations.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go
- openmeter/billing/charges/flatfee/service/linemapper.go
- openmeter/billing/charges/usagebased/service/run/correct.go
- openmeter/billing/worker/subscriptionsync/service/sync.go
- openmeter/billing/rating/service/detailedline.go
- openmeter/billing/rating/service/rate/tieredgraduated.go
- openmeter/billing/charges/flatfee/service/realizations/preview.go
- openmeter/ledger/chargeadapter/usagebased.go
- openmeter/billing/rating/detailedline.go
- test/app/stripe/invoice_credits_test.go
- api/v3/handlers/customers/credits/convert.go
- openmeter/billing/rating/detailedline_test.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go
- openmeter/billing/charges/models/creditrealization/correction_test.go
- openmeter/ledger/chargeadapter/usagebased_test.go
- openmeter/billing/rating/service/mutator/credits_test.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go
- openmeter/billing/charges/usagebased/service/creditsonly_test.go
- openmeter/ledger/collector/correct_test.go
- openmeter/billing/charges/usagebased/service/triggers.go
- openmeter/billing/models/totals/model_test.go
- pkg/currencyx/allocation.go
- openmeter/billing/charges/creditpurchase/charge.go
- openmeter/ledger/chargeadapter/flatfee.go
- openmeter/billing/worker/subscriptionsync/service/targetstate/targetstate.go
- openmeter/billing/charges/flatfee/charge.go
- openmeter/billing/invoicedetailedline_test.go
- openmeter/billing/charges/flatfee/service/creditsonly.go
- openmeter/billing/charges/usagebased/service/lineengine.go
- openmeter/billing/rating/service/rate/tieredgraduated_test.go
- openmeter/ledger/chargeadapter/creditpurchase.go
- openmeter/billing/charges/models/creditrealization/correction.go
- pkg/currencyx/currency_test.go
- pkg/currencyx/allocation_test.go
75e2a39 to
41d9ff2
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
pkg/currencyx/currency.go (1)
196-209: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueFiat currency stores the shared
currency.Get()pointer directly instead of cloning.
CustomCurrencyalways builds/receives a fresh*currency.Def, butnewFiatCurrencystores the package-level singleton returned bycurrency.Get()straight intof.def(onlyDefinition()clones on read). If anything ever mutatesf.defin place, it'd corrupt the shared definition for everyFiatCurrencybuilt with that code. Nothing currently mutates it, so this is speculative, but cloning at construction (mirroringcloneDef) would remove the risk entirely.🤖 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 `@pkg/currencyx/currency.go` around lines 196 - 209, Update newFiatCurrency to clone the definition returned by currency.Get before storing it in FiatCurrency.def, mirroring the existing cloneDef behavior used for CustomCurrency. Preserve the current validation and error handling, and ensure each FiatCurrency owns an independent definition rather than the shared package-level pointer.
🤖 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.
Inline comments:
In `@openmeter/app/stripe/calculator.go`:
- Around line 43-53: Update StripeCalculator.FormatAmount to delegate the
original alpacadecimal.Decimal directly to currencyx.Currency’s FormatAmount
method. Remove the Float64 conversion, NumDigits conversion, integer special
case, and related num package usage while preserving the method’s string result.
In `@openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go`:
- Around line 85-93: Guard currency interface usage in ApplyInput.Validate (and
PlanInput validation if it invokes Currency methods) by returning a “currency is
required” validation error when nil, otherwise preserve existing validation
errors. In openmeter/billing/models/totals/model.go:152-160, add a nil guard at
the start of Totals.RoundToPrecision that returns the receiver unchanged;
otherwise retain the existing rounding behavior.
In `@pkg/currencyx/currency.go`:
- Around line 176-179: Correct the nil-guard error messages in
FiatCurrency.Validate and CustomCurrency.Validate: FiatCurrency must report
“fiat currency is not initialized,” while CustomCurrency must report “custom
currency is not initialized.”
---
Nitpick comments:
In `@pkg/currencyx/currency.go`:
- Around line 196-209: Update newFiatCurrency to clone the definition returned
by currency.Get before storing it in FiatCurrency.def, mirroring the existing
cloneDef behavior used for CustomCurrency. Preserve the current validation and
error handling, and ensure each FiatCurrency owns an independent definition
rather than the shared package-level pointer.
🪄 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: 1d883512-2d6f-4863-95bd-ad1b66ea83e5
📒 Files selected for processing (69)
.agents/skills/currencyx/SKILL.md.agents/skills/currencyx/agents/openai.yamlapi/v3/handlers/customers/credits/convert.goopenmeter/app/stripe/calculator.goopenmeter/billing/charges/creditpurchase/charge.goopenmeter/billing/charges/creditpurchase/service/create.goopenmeter/billing/charges/creditpurchase/service/external_test.goopenmeter/billing/charges/flatfee/charge.goopenmeter/billing/charges/flatfee/handler.goopenmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/linemapper.goopenmeter/billing/charges/flatfee/service/realizations/correct.goopenmeter/billing/charges/flatfee/service/realizations/creditsonly.goopenmeter/billing/charges/flatfee/service/realizations/credittheninvoice.goopenmeter/billing/charges/flatfee/service/realizations/preview.goopenmeter/billing/charges/models/creditrealization/correction.goopenmeter/billing/charges/models/creditrealization/correction_test.goopenmeter/billing/charges/models/creditrealization/realizations.goopenmeter/billing/charges/usagebased/handler.goopenmeter/billing/charges/usagebased/service/creditsonly_test.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/charges/usagebased/service/linemapper.goopenmeter/billing/charges/usagebased/service/run/correct.goopenmeter/billing/charges/usagebased/service/run/create.goopenmeter/billing/charges/usagebased/service/run/credits.goopenmeter/billing/charges/usagebased/service/run/preview.goopenmeter/billing/charges/usagebased/service/statemachine.goopenmeter/billing/charges/usagebased/service/triggers.goopenmeter/billing/invoicedetailedline.goopenmeter/billing/invoicedetailedline_test.goopenmeter/billing/invoicelinediscount.goopenmeter/billing/models/creditsapplied/model.goopenmeter/billing/models/totals/model.goopenmeter/billing/models/totals/model_test.goopenmeter/billing/rating/detailedline.goopenmeter/billing/rating/detailedline_test.goopenmeter/billing/rating/service/detailedline.goopenmeter/billing/rating/service/mutator/credits_test.goopenmeter/billing/rating/service/mutator/discountpercentage.goopenmeter/billing/rating/service/rate/tieredgraduated.goopenmeter/billing/rating/service/rate/tieredgraduated_test.goopenmeter/billing/rating/service/rate/types.goopenmeter/billing/worker/subscriptionsync/service/reconcile.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.goopenmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.goopenmeter/billing/worker/subscriptionsync/service/sync.goopenmeter/billing/worker/subscriptionsync/service/targetstate/targetstate.goopenmeter/billing/worker/subscriptionsync/service/targetstate/targetstateitem.goopenmeter/ledger/chargeadapter/creditpurchase.goopenmeter/ledger/chargeadapter/flatfee.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/usagebased.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/collector/correct_test.goopenmeter/ledger/validations.goopenmeter/ledger/validations_test.gopkg/currencyx/allocation.gopkg/currencyx/allocation_test.gopkg/currencyx/code.gopkg/currencyx/costbasis.gopkg/currencyx/currency.gopkg/currencyx/currency_test.gopkg/currencyx/fiat.gopkg/currencyx/fiat_test.gopkg/currencyx/validation.gotest/app/stripe/invoice_credits_test.go
💤 Files with no reviewable changes (5)
- .agents/skills/currencyx/SKILL.md
- pkg/currencyx/fiat_test.go
- pkg/currencyx/validation.go
- .agents/skills/currencyx/agents/openai.yaml
- pkg/currencyx/fiat.go
🚧 Files skipped from review as they are similar to previous changes (53)
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go
- openmeter/billing/charges/flatfee/handler.go
- openmeter/billing/models/creditsapplied/model.go
- openmeter/billing/charges/usagebased/service/run/preview.go
- openmeter/billing/rating/service/rate/tieredgraduated.go
- openmeter/billing/worker/subscriptionsync/service/reconcile.go
- openmeter/billing/charges/usagebased/service/run/create.go
- openmeter/billing/invoicelinediscount.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go
- openmeter/billing/worker/subscriptionsync/service/targetstate/targetstate.go
- openmeter/ledger/chargeadapter/usagebased.go
- openmeter/ledger/chargeadapter/usagebased_test.go
- openmeter/billing/charges/flatfee/service/realizations/correct.go
- openmeter/billing/charges/creditpurchase/charge.go
- openmeter/billing/charges/usagebased/service/run/credits.go
- openmeter/billing/models/totals/model_test.go
- openmeter/billing/charges/flatfee/service/linemapper.go
- openmeter/billing/charges/flatfee/service/realizations/creditsonly.go
- openmeter/billing/charges/usagebased/service/run/correct.go
- openmeter/billing/charges/creditpurchase/service/create.go
- openmeter/billing/charges/usagebased/service/linemapper.go
- openmeter/ledger/validations_test.go
- openmeter/billing/charges/models/creditrealization/realizations.go
- openmeter/billing/charges/usagebased/handler.go
- openmeter/billing/charges/creditpurchase/service/external_test.go
- openmeter/ledger/collector/correct_test.go
- openmeter/billing/rating/detailedline.go
- openmeter/billing/worker/subscriptionsync/service/targetstate/targetstateitem.go
- openmeter/billing/charges/usagebased/service/lineengine.go
- openmeter/ledger/chargeadapter/flatfee_test.go
- openmeter/billing/charges/usagebased/service/triggers.go
- openmeter/ledger/chargeadapter/flatfee.go
- api/v3/handlers/customers/credits/convert.go
- openmeter/billing/charges/models/creditrealization/correction_test.go
- openmeter/billing/rating/service/rate/types.go
- openmeter/billing/worker/subscriptionsync/service/sync.go
- openmeter/billing/charges/flatfee/charge.go
- openmeter/billing/invoicedetailedline_test.go
- openmeter/billing/rating/service/detailedline.go
- openmeter/billing/rating/service/mutator/credits_test.go
- openmeter/billing/charges/flatfee/service/realizations/preview.go
- pkg/currencyx/allocation.go
- openmeter/ledger/chargeadapter/creditpurchase.go
- openmeter/billing/charges/flatfee/service/creditsonly.go
- openmeter/billing/rating/detailedline_test.go
- test/app/stripe/invoice_credits_test.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go
- openmeter/billing/charges/flatfee/service/lineengine.go
- pkg/currencyx/allocation_test.go
- openmeter/billing/invoicedetailedline.go
- openmeter/billing/rating/service/rate/tieredgraduated_test.go
- openmeter/billing/charges/models/creditrealization/correction.go
- openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go
41d9ff2 to
a7edcf2
Compare
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/handler.go (1)
109-111: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winAdd a nil guard for the currency parameter.
It looks like we're missing a check for
currencyCalculator == nilbefore we callValidateWithonCorrections. If it's nil, this could cause a panic! We should catch it early, similar to what was done over in the usage-based handler.🛠️ Proposed fix to guard against a nil currency
- if err := i.Corrections.ValidateWith(currencyCalculator); err != nil { - errs = append(errs, fmt.Errorf("corrections: %w", err)) - } + if currencyCalculator == nil { + errs = append(errs, fmt.Errorf("currency is required")) + } else if err := i.Corrections.ValidateWith(currencyCalculator); err != nil { + errs = append(errs, fmt.Errorf("corrections: %w", err)) + }🤖 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/handler.go` around lines 109 - 111, Update the validation flow around Corrections.ValidateWith to check currencyCalculator for nil before invoking it, and append the same validation error pattern used by the usage-based handler. Only call ValidateWith when the calculator is non-nil, preserving the existing corrections error wrapping.
♻️ Duplicate comments (1)
openmeter/app/stripe/calculator.go (1)
43-53: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winStill not delegating to
currencyx.Currency.FormatAmount.This is the same float64 round-trip flagged on a prior commit —
defchanged source but the body still converts throughamount.Float64()and discards the conversion error, instead of usingc.currency.FormatAmount(amount), whichcurrencyx.Currencynow exposes directly (backed byformatCurrencyAmount, which stays in decimal space viaCoefficientInt64()/Exponent()).🐛 Proposed fix
func (c StripeCalculator) FormatAmount(amount alpacadecimal.Decimal) string { - def := c.currency.Definition() - - if amount.IsInteger() { - return def.FormatAmount(num.MakeAmount(amount.IntPart(), 0)) - } - - am, _ := amount.Float64() - - return def.FormatAmount(num.AmountFromFloat64(am, uint32(amount.NumDigits()))) + return c.currency.FormatAmount(amount) }Note: this may make the
github.com/invopop/gobl/numimport unused in this file if it isn't referenced elsewhere.🤖 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/app/stripe/calculator.go` around lines 43 - 53, Update StripeCalculator.FormatAmount to delegate directly to c.currency.FormatAmount(amount) instead of branching on IsInteger or converting through Float64. Remove the now-unused num import if no other references remain, while preserving the method’s string result.
🧹 Nitpick comments (1)
openmeter/billing/charges/usagebased/handler.go (1)
82-90: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSimplify the nil check.
This works perfectly, but we could simplify it just a tiny bit by using an
else ifinstead of two separateifblocks.✨ Proposed refactor
- if currency == nil { - errs = append(errs, fmt.Errorf("currency is required")) - } - - if currency != nil { - if err := i.Corrections.ValidateWith(currency); err != nil { - errs = append(errs, fmt.Errorf("corrections: %w", err)) - } - } + if currency == nil { + errs = append(errs, fmt.Errorf("currency is required")) + } else if err := i.Corrections.ValidateWith(currency); err != nil { + errs = append(errs, fmt.Errorf("corrections: %w", err)) + }🤖 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/usagebased/handler.go` around lines 82 - 90, Update the validation logic around currency and Corrections.ValidateWith so the second condition is an else-if paired with the currency nil check, preserving the existing error messages and validation 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/handler.go`:
- Around line 109-111: Update the validation flow around
Corrections.ValidateWith to check currencyCalculator for nil before invoking it,
and append the same validation error pattern used by the usage-based handler.
Only call ValidateWith when the calculator is non-nil, preserving the existing
corrections error wrapping.
---
Duplicate comments:
In `@openmeter/app/stripe/calculator.go`:
- Around line 43-53: Update StripeCalculator.FormatAmount to delegate directly
to c.currency.FormatAmount(amount) instead of branching on IsInteger or
converting through Float64. Remove the now-unused num import if no other
references remain, while preserving the method’s string result.
---
Nitpick comments:
In `@openmeter/billing/charges/usagebased/handler.go`:
- Around line 82-90: Update the validation logic around currency and
Corrections.ValidateWith so the second condition is an else-if paired with the
currency nil check, preserving the existing error messages and validation
behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 6b27e36a-f77e-4cdd-92d3-c006385b7cd9
📒 Files selected for processing (69)
.agents/skills/currencyx/SKILL.md.agents/skills/currencyx/agents/openai.yamlapi/v3/handlers/customers/credits/convert.goopenmeter/app/stripe/calculator.goopenmeter/billing/charges/creditpurchase/charge.goopenmeter/billing/charges/creditpurchase/service/create.goopenmeter/billing/charges/creditpurchase/service/external_test.goopenmeter/billing/charges/flatfee/charge.goopenmeter/billing/charges/flatfee/handler.goopenmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/linemapper.goopenmeter/billing/charges/flatfee/service/realizations/correct.goopenmeter/billing/charges/flatfee/service/realizations/creditsonly.goopenmeter/billing/charges/flatfee/service/realizations/credittheninvoice.goopenmeter/billing/charges/flatfee/service/realizations/preview.goopenmeter/billing/charges/models/creditrealization/correction.goopenmeter/billing/charges/models/creditrealization/correction_test.goopenmeter/billing/charges/models/creditrealization/realizations.goopenmeter/billing/charges/usagebased/handler.goopenmeter/billing/charges/usagebased/service/creditsonly_test.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/charges/usagebased/service/linemapper.goopenmeter/billing/charges/usagebased/service/run/correct.goopenmeter/billing/charges/usagebased/service/run/create.goopenmeter/billing/charges/usagebased/service/run/credits.goopenmeter/billing/charges/usagebased/service/run/preview.goopenmeter/billing/charges/usagebased/service/statemachine.goopenmeter/billing/charges/usagebased/service/triggers.goopenmeter/billing/invoicedetailedline.goopenmeter/billing/invoicedetailedline_test.goopenmeter/billing/invoicelinediscount.goopenmeter/billing/models/creditsapplied/model.goopenmeter/billing/models/totals/model.goopenmeter/billing/models/totals/model_test.goopenmeter/billing/rating/detailedline.goopenmeter/billing/rating/detailedline_test.goopenmeter/billing/rating/service/detailedline.goopenmeter/billing/rating/service/mutator/credits_test.goopenmeter/billing/rating/service/mutator/discountpercentage.goopenmeter/billing/rating/service/rate/tieredgraduated.goopenmeter/billing/rating/service/rate/tieredgraduated_test.goopenmeter/billing/rating/service/rate/types.goopenmeter/billing/worker/subscriptionsync/service/reconcile.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.goopenmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.goopenmeter/billing/worker/subscriptionsync/service/sync.goopenmeter/billing/worker/subscriptionsync/service/targetstate/targetstate.goopenmeter/billing/worker/subscriptionsync/service/targetstate/targetstateitem.goopenmeter/ledger/chargeadapter/creditpurchase.goopenmeter/ledger/chargeadapter/flatfee.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/usagebased.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/collector/correct_test.goopenmeter/ledger/validations.goopenmeter/ledger/validations_test.gopkg/currencyx/allocation.gopkg/currencyx/allocation_test.gopkg/currencyx/code.gopkg/currencyx/costbasis.gopkg/currencyx/currency.gopkg/currencyx/currency_test.gopkg/currencyx/fiat.gopkg/currencyx/fiat_test.gopkg/currencyx/validation.gotest/app/stripe/invoice_credits_test.go
💤 Files with no reviewable changes (5)
- .agents/skills/currencyx/agents/openai.yaml
- .agents/skills/currencyx/SKILL.md
- pkg/currencyx/fiat_test.go
- pkg/currencyx/fiat.go
- pkg/currencyx/validation.go
🚧 Files skipped from review as they are similar to previous changes (56)
- pkg/currencyx/costbasis.go
- openmeter/billing/models/creditsapplied/model.go
- openmeter/billing/worker/subscriptionsync/service/reconcile.go
- openmeter/billing/charges/flatfee/service/realizations/creditsonly.go
- openmeter/billing/invoicelinediscount.go
- api/v3/handlers/customers/credits/convert.go
- openmeter/billing/rating/detailedline_test.go
- openmeter/billing/charges/flatfee/service/realizations/preview.go
- openmeter/billing/worker/subscriptionsync/service/targetstate/targetstateitem.go
- openmeter/billing/charges/flatfee/service/realizations/correct.go
- openmeter/billing/rating/service/mutator/credits_test.go
- openmeter/billing/worker/subscriptionsync/service/targetstate/targetstate.go
- openmeter/billing/charges/usagebased/service/run/preview.go
- openmeter/billing/charges/models/creditrealization/correction_test.go
- openmeter/billing/rating/service/rate/tieredgraduated.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go
- openmeter/ledger/validations.go
- openmeter/ledger/validations_test.go
- openmeter/billing/charges/flatfee/service/linemapper.go
- openmeter/billing/charges/usagebased/service/run/create.go
- openmeter/billing/charges/creditpurchase/service/create.go
- test/app/stripe/invoice_credits_test.go
- openmeter/billing/charges/usagebased/service/statemachine.go
- openmeter/billing/rating/service/mutator/discountpercentage.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go
- openmeter/ledger/collector/correct_test.go
- openmeter/billing/charges/flatfee/service/lineengine.go
- openmeter/billing/charges/usagebased/service/run/credits.go
- openmeter/billing/rating/detailedline.go
- openmeter/billing/charges/creditpurchase/charge.go
- openmeter/billing/rating/service/rate/types.go
- openmeter/billing/models/totals/model_test.go
- openmeter/billing/rating/service/detailedline.go
- openmeter/billing/worker/subscriptionsync/service/sync.go
- openmeter/billing/charges/usagebased/service/lineengine.go
- openmeter/billing/charges/usagebased/service/linemapper.go
- openmeter/billing/charges/flatfee/charge.go
- openmeter/ledger/chargeadapter/creditpurchase.go
- openmeter/billing/charges/creditpurchase/service/external_test.go
- pkg/currencyx/code.go
- openmeter/billing/charges/flatfee/service/creditsonly.go
- openmeter/ledger/chargeadapter/flatfee_test.go
- openmeter/billing/models/totals/model.go
- openmeter/billing/rating/service/rate/tieredgraduated_test.go
- openmeter/billing/charges/models/creditrealization/correction.go
- openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go
- openmeter/billing/invoicedetailedline_test.go
- openmeter/ledger/chargeadapter/usagebased.go
- pkg/currencyx/allocation.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go
- openmeter/ledger/chargeadapter/flatfee.go
- openmeter/billing/charges/usagebased/service/triggers.go
- pkg/currencyx/currency_test.go
- openmeter/billing/charges/models/creditrealization/realizations.go
- pkg/currencyx/allocation_test.go
- openmeter/billing/charges/usagebased/service/run/correct.go
c1cc4d0 to
84e36c3
Compare
84e36c3 to
2c32eee
Compare
Overview
Refactor
currencyxpackage to make it reusabe forcurrenciesAPI and also more structured at the same time.Fixes #(issue)
Notes for reviewer
Summary by CodeRabbit
Greptile Summary
This PR refactors currency handling across billing, ledger, and Stripe flows. The main changes are:
currencyx.Currencyinterface and builder-based construction path.Confidence Score: 5/5
This looks safe to merge.
Important Files Changed
Comments Outside Diff (6)
openmeter/billing/charges/flatfee/service/realizations/correct.go, line 182-184 (link)CurrencyCalculatoris now a nil-ablecurrencyx.Currencyinterface, but this validation path callsValidate()before checking whether the field is set. WhenCorrectAllCreditsis reached with a zero-value input or a caller that failed to build the currency, it panics in validation instead of returning a normal validation error.ReconcileCreditRealizationsInput.Validate()already guards the same field above; this path needs the same guard before dereferencing the interface.Prompt To Fix With AI
openmeter/billing/charges/flatfee/service/realizations/correct.go, line 180-182 (link)CorrectAllCreditsstill callsValidate()onCurrencyCalculatorwithout checking whether the interface is nil. A zero-value input, or a caller that fails to build the currency before calling this boundary, can still panic during validation instead of returning a normal validation error. Add the same nil guard used by the reconcile input before dereferencing the currency.Prompt To Fix With AI
openmeter/billing/charges/flatfee/service/realizations/correct.go, line 48-50 (link)CurrencyCalculatoris a nil-able interface, so this validation still panics whenReconcileCreditsreceives a zero-value input. The new validation-before-rounding call reachesi.CurrencyCalculator.Validate()before any nil check, so the correction workflow can still crash instead of returning a validation error.Prompt To Fix With AI
openmeter/billing/charges/flatfee/service/realizations/correct.go, line 178-180 (link)CorrectAllCreditsalso callsValidate()on the currency interface before checking whether it is set. A caller that reaches this boundary with a zero-value input still gets a nil-interface panic instead of a normal validation error, so credit correction cleanup can crash before it can fail cleanly.Prompt To Fix With AI
openmeter/billing/charges/flatfee/service/realizations/correct.go, line 48-50 (link)ReconcileCreditsnow validates before rounding, but this validation still callsValidate()on the nil-ablecurrencyx.Currencyinterface before checking it. When this boundary receives a zero-valueReconcileCreditRealizationsInput, it can still panic here instead of returning a validation error, so the correction workflow can crash before it fails cleanly.Prompt To Fix With AI
openmeter/billing/charges/flatfee/service/realizations/correct.go, line 178-180 (link)CorrectAllCreditshas the same nil-interface path.CurrencyCalculatorcan be nil on a zero-value input, but validation callsValidate()before confirming it is set. That can crash credit correction cleanup during validation instead of returning a normal error to the caller.Prompt To Fix With AI
Reviews (14): Last reviewed commit: "revert: rounding change" | Re-trigger Greptile
Context used (3)