Repository navigation
feat: refactor charge patch source routing - #4607
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (7)
🚧 Files skipped from review as they are similar to previous changes (6)
📝 WalkthroughWalkthroughReplaces explicit ChangesPatch targeting and LineManualEdit refactor
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 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 |
Greptile SummaryThis PR refactors charge patch routing to derive intent layers from the change source. The main changes are:
Confidence Score: 5/5This looks safe to merge.
Important Files Changed
Reviews (2): Last reviewed commit: "fix(billing): address charge patch revie..." | Re-trigger Greptile |
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
openmeter/billing/charges/meta/patchshrink.go (1)
35-56: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winCollect all shrink validation errors instead of failing fast.
Line 35 and Line 114 still return on the first invalid field, so callers only see one validation problem at a time. Please aggregate into
errslikeValidateWithalready does. As per coding guidelines, “For GoValidate() errormethods, collect all validation issues intovar errs []errorand returnmodels.NewNillableGenericValidationError(errors.Join(errs...))instead of failing fast.”Suggested patch
func (i NewPatchShrinkInput) Validate() error { + var errs []error + if err := i.ChangeSource.Require(billing.ChangeSourceSystem); err != nil { - return fmt.Errorf("change source: %w", err) + errs = append(errs, fmt.Errorf("change source: %w", err)) } if i.NewServicePeriodTo.IsZero() { - return models.NewGenericValidationError(fmt.Errorf("new service period to is required")) + errs = append(errs, fmt.Errorf("new service period to is required")) } if i.NewFullServicePeriodTo.IsZero() { - return models.NewGenericValidationError(fmt.Errorf("new full service period to is required")) + errs = append(errs, fmt.Errorf("new full service period to is required")) } if i.NewBillingPeriodTo.IsZero() { - return models.NewGenericValidationError(fmt.Errorf("new billing period to is required")) + errs = append(errs, fmt.Errorf("new billing period to is required")) } if i.NewInvoiceAt.IsZero() { - return models.NewGenericValidationError(fmt.Errorf("new invoice at is required")) + errs = append(errs, fmt.Errorf("new invoice at is required")) } - return nil + return models.NewNillableGenericValidationError(errors.Join(errs...)) } func (p PatchShrink) Validate() error { + var errs []error + if err := p.GetChangeSource().Require(billing.ChangeSourceSystem); err != nil { - return fmt.Errorf("change source: %w", err) + errs = append(errs, fmt.Errorf("change source: %w", err)) } if p.GetNewServicePeriodTo().IsZero() { - return models.NewGenericValidationError(fmt.Errorf("new service period to is required")) + errs = append(errs, fmt.Errorf("new service period to is required")) } if p.GetNewFullServicePeriodTo().IsZero() { - return models.NewGenericValidationError(fmt.Errorf("new full service period to is required")) + errs = append(errs, fmt.Errorf("new full service period to is required")) } if p.GetNewBillingPeriodTo().IsZero() { - return models.NewGenericValidationError(fmt.Errorf("new billing period to is required")) + errs = append(errs, fmt.Errorf("new billing period to is required")) } if p.GetNewInvoiceAt().IsZero() { - return models.NewGenericValidationError(fmt.Errorf("new invoice at is required")) + errs = append(errs, fmt.Errorf("new invoice at is required")) } - return nil + return models.NewNillableGenericValidationError(errors.Join(errs...)) }Also applies to: 114-135
🤖 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/meta/patchshrink.go` around lines 35 - 56, The Validate methods in NewPatchShrinkInput and the related shrink validation path still fail fast on the first bad field. Update NewPatchShrinkInput.Validate and the other Validate block referenced in the diff to collect all field validation errors into errs instead of returning immediately, following the same pattern used by ValidateWith. Finish by returning models.NewNillableGenericValidationError(errors.Join(errs...)) so callers receive every shrink validation issue at once.Source: Coding guidelines
openmeter/billing/charges/meta/patchshrink_test.go (1)
13-157: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winAdd one routing test for
PatchShrink.GetTargetLayer.This refactor moved
PatchShrinkontoChangeSourcetoo, but this suite only exercisesValidateWithand missing-source construction. UnlikePatchExtend, nothing here proves that system-sourced shrink targets base or that API-sourced shrink is rejected, so a routing regression can sneak through. As per path instructions, "**/*_test.go: Make sure the tests are comprehensive and cover the changes."Also applies to: 159-169
🤖 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/meta/patchshrink_test.go` around lines 13 - 157, Add a focused routing test for PatchShrink.GetTargetLayer in the PatchShrink test suite, since the current tests only cover ValidateWith and construction. Verify that a system ChangeSource routes to the base layer and that an API ChangeSource is rejected or handled as expected, using PatchShrink and GetTargetLayer to locate the code path. Keep the existing validation tests intact and add the new case alongside them so routing regressions are covered.Source: Path instructions
🧹 Nitpick comments (2)
openmeter/billing/charges/usagebased/service/statemachine.go (1)
143-146: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winKeep the new override path on the same validation boundary.
The other mutation paths use
OverridableIntent.Mutate, which normalizes and validates edited fields. Here the new override fields are edited and passed directly toCreateChargeOverride, so this branch can diverge from the domain invariants unless the adapter duplicates that work.Suggested tweak
overrideFields := s.Charge.Intent.GetEffectiveIntent().IntentMutableFields editFn(&overrideFields) + overrideFields = overrideFields.Normalized() + if err := overrideFields.Validate(); err != nil { + return fmt.Errorf("validating override intent: %w", err) + } base, err := s.Adapter.CreateChargeOverride(ctx, s.Charge.ChargeBase, overrideFields)🤖 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/statemachine.go` around lines 143 - 146, The new override branch bypasses the same normalization/validation that other mutation paths get through OverridableIntent.Mutate. Update the override flow in the state machine to apply the same boundary before calling CreateChargeOverride, using the existing intent mutation/validation logic around s.Charge.Intent.GetEffectiveIntent() and editFn so the adapter receives already-normalized fields.openmeter/billing/charges/flatfee/service/statemachine.go (1)
113-116: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winMirror the intent normalization/validation before creating a new override.
The base and existing-override paths go through
OverridableIntent.Mutate, which normalizes and validates edited fields. This new missing-override branch applieseditFnand sends the result straight toCreateChargeOverride, so it can hand off unnormalized/invalid fields unless the adapter happens to catch them.Suggested tweak
- overrideFields := s.Charge.Intent.GetEffectiveIntent().IntentMutableFields + effectiveIntent := s.Charge.Intent.GetEffectiveIntent() + overrideFields := effectiveIntent.IntentMutableFields editFn(&overrideFields) + overrideFields = overrideFields.Normalized(effectiveIntent.Currency) + if err := overrideFields.Validate(); err != nil { + return fmt.Errorf("validating override intent: %w", err) + } base, err := s.Adapter.CreateChargeOverride(ctx, s.Charge.ChargeBase, overrideFields)🤖 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/statemachine.go` around lines 113 - 116, The missing-override path in statemachine.go bypasses the same normalization/validation used by OverridableIntent.Mutate before creating a charge override. Update the branch around editFn and CreateChargeOverride so the edited intent fields are passed through the same mutate/normalize/validate flow as the base and existing-override paths, using the relevant charge intent helpers from s.Charge.Intent.GetEffectiveIntent() before calling s.Adapter.CreateChargeOverride.
🤖 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/change_source_test.go`:
- Around line 9-14: Add the missing happy-path assertion in
TestChangeSourceRequire so it also verifies
ChangeSourceAPIRequest.Require(ChangeSourceAPIRequest) succeeds. Keep the
existing failure checks, but include an explicit no-error assertion for the
APIRequest case to cover the new manual-edit flow that relies on
ChangeSourceAPIRequest.Require, using the ChangeSourceAPIRequest and Require
symbols as the reference points.
In `@openmeter/billing/charges/flatfee/service/creditheninvoice.go`:
- Around line 259-293: The current line-type check in creditheninvoice.go treats
every non-gathering line as standard, which can persist a manual-edit intent
before unsupported types are rejected. Update the branch around the charge
update validation to handle only billing.InvoiceLineTypeStandard explicitly in
addition to billing.InvoiceLineTypeGathering, and add a default case that
returns billing.ErrCannotUpdateChargeManagedLine before any intent mutation.
Keep the logic localized near the current lineType and currentRun checks so
unsupported line types fail fast in this handler.
In `@openmeter/billing/charges/meta/patch_target_test.go`:
- Around line 35-38: The test in TestPeriodPatchValidateRejectsAPIChange is not
isolating the change-source guard because PatchExtend.Validate also fails on
missing period timestamps. Seed the required period times on PatchExtend so
validation reaches the API-request check, then assert the returned error message
mentions change source to pin the rejection path and protect the routing
contract.
---
Outside diff comments:
In `@openmeter/billing/charges/meta/patchshrink_test.go`:
- Around line 13-157: Add a focused routing test for PatchShrink.GetTargetLayer
in the PatchShrink test suite, since the current tests only cover ValidateWith
and construction. Verify that a system ChangeSource routes to the base layer and
that an API ChangeSource is rejected or handled as expected, using PatchShrink
and GetTargetLayer to locate the code path. Keep the existing validation tests
intact and add the new case alongside them so routing regressions are covered.
In `@openmeter/billing/charges/meta/patchshrink.go`:
- Around line 35-56: The Validate methods in NewPatchShrinkInput and the related
shrink validation path still fail fast on the first bad field. Update
NewPatchShrinkInput.Validate and the other Validate block referenced in the diff
to collect all field validation errors into errs instead of returning
immediately, following the same pattern used by ValidateWith. Finish by
returning models.NewNillableGenericValidationError(errors.Join(errs...)) so
callers receive every shrink validation issue at once.
---
Nitpick comments:
In `@openmeter/billing/charges/flatfee/service/statemachine.go`:
- Around line 113-116: The missing-override path in statemachine.go bypasses the
same normalization/validation used by OverridableIntent.Mutate before creating a
charge override. Update the branch around editFn and CreateChargeOverride so the
edited intent fields are passed through the same mutate/normalize/validate flow
as the base and existing-override paths, using the relevant charge intent
helpers from s.Charge.Intent.GetEffectiveIntent() before calling
s.Adapter.CreateChargeOverride.
In `@openmeter/billing/charges/usagebased/service/statemachine.go`:
- Around line 143-146: The new override branch bypasses the same
normalization/validation that other mutation paths get through
OverridableIntent.Mutate. Update the override flow in the state machine to apply
the same boundary before calling CreateChargeOverride, using the existing intent
mutation/validation logic around s.Charge.Intent.GetEffectiveIntent() and editFn
so the adapter receives already-normalized fields.
🪄 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: f0e479b3-d66a-4c8d-b589-22385beeeb82
📒 Files selected for processing (34)
.agents/skills/charges/SKILL.mdopenmeter/billing/change_source_test.goopenmeter/billing/charges/flatfee/charge.goopenmeter/billing/charges/flatfee/service/creditheninvoice.goopenmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/manualedit.goopenmeter/billing/charges/flatfee/service/statemachine.goopenmeter/billing/charges/meta/patch.goopenmeter/billing/charges/meta/patch_target_test.goopenmeter/billing/charges/meta/patchdelete.goopenmeter/billing/charges/meta/patchextend.goopenmeter/billing/charges/meta/patchextend_test.goopenmeter/billing/charges/meta/patchlinemanualedit.goopenmeter/billing/charges/meta/patchshrink.goopenmeter/billing/charges/meta/patchshrink_test.goopenmeter/billing/charges/meta/triggers.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/charges/statemachine/machine.goopenmeter/billing/charges/statemachine/machine_test.goopenmeter/billing/charges/usagebased/charge.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditheninvoice_test.goopenmeter/billing/charges/usagebased/service/creditsonly.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/charges/usagebased/service/statemachine.goopenmeter/billing/lineengine.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.gotest/credits/base.gotest/credits/credit_then_invoice_test.gotest/credits/sanity_lifecycle_test.gotest/credits/sanity_test.go
Summary
Summary by CodeRabbit
New Features
Bug Fixes
Tests