Repository navigation
fix(billing): support credit-only period patches - #4597
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 (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds native Extend/Shrink handling for credits-only flat-fee and usage-based charges, wires the triggers into their state machines, removes emulated-replacement fallback paths in the reconciler, and updates tests to assert the new patch and cancellation behavior. ChangesNative Extend/Shrink for credits-only charges
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
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 adds native period patching for credit-only billing charges. The main changes are:
Confidence Score: 5/5This looks safe to merge.
Important Files Changed
Reviews (3): Last reviewed commit: "fix: lint import grouping" | Re-trigger Greptile |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (4)
openmeter/billing/charges/usagebased/service/creditsonly_test.go (1)
31-40: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd the repo’s short
given/when/thenmarkers at the top of these subtests.These are non-trivial lifecycle subtests, so it’d be good to start each body with the expected intent comments.
As per coding guidelines,
For service and lifecycle subtests, start non-trivial subtest bodies with concise given/when/then intent comments.Also applies to: 50-88
🤖 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/creditsonly_test.go` around lines 31 - 40, The credits-only lifecycle subtests in the test function using newCreditsOnlyStateMachineForTest should begin each non-trivial t.Run body with the repo’s concise given/when/then intent markers. Add the short given/when/then comments at the top of the affected subtests before the CanFire assertions so the lifecycle intent is clear and consistent with the coding guidelines.Source: Coding guidelines
pkg/statelessx/actions.go (1)
9-9: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDrop
lo.Maphere and use the same plain loop shape asAllOf.This version adds an extra dependency use, builds a temporary
[]error, and recreatesWithParameters[T]wrappers on every call. A small loop is easier to read and matches the rest of this file.As per coding guidelines,
Prefer standard library slices and maps helpers for common collection operations, and use github.com/samber/lo only when it clearly improves pointer literals or transformations.Suggested refactor
- "github.com/samber/lo" - "github.com/openmeterio/openmeter/pkg/models" ) @@ func AllOfWithParameters[T models.Validator](fn ...func(context.Context, T) error) func(context.Context, ...any) error { + actions := make([]func(context.Context, ...any) error, 0, len(fn)) + for _, f := range fn { + actions = append(actions, WithParameters[T](f)) + } + return func(ctx context.Context, args ...any) error { - return errors.Join( - lo.Map(fn, func(fn func(context.Context, T) error, _ int) error { - return WithParameters[T](fn)(ctx, args...) - })..., - ) + var outErr error + for _, action := range actions { + if err := action(ctx, args...); err != nil { + outErr = errors.Join(outErr, err) + } + } + + return outErr } }Also applies to: 56-62
🤖 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/statelessx/actions.go` at line 9, Remove the unnecessary lo.Map usage from the affected helper in actions.go and rewrite it with the same straightforward loop pattern used by AllOf. Update the function that builds the []error result to append directly inside the loop instead of creating an intermediate slice and recreating WithParameters[T] wrappers on each call, keeping the implementation simple and consistent with the rest of the file.Sources: Coding guidelines, Path instructions
openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go (1)
963-966: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRefresh the test narrative for native patch behavior.
These assertions now expect the same charge to remain active, advance from the cancellation boundary, and have no realizations. The
Thenblock above still describes the old recreated-charge/pre-cancellation-realization flow, so it’s worth updating to match. As per coding guidelines, “preserve existing explanatory comments unless the code change makes them false, stale, or misleading.”🤖 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/worker/subscriptionsync/service/creditsonly_test.go` around lines 963 - 966, The test narrative in the surrounding `Then` block is stale because the assertions for `afterShrinkCharge` now describe native patch behavior: the same charge stays active, advances from the cancellation boundary, and has no realizations. Update the explanatory comments in `creditsonly_test.go` around the `afterShrinkCharge` assertions so they match the current flow and no longer mention a recreated charge or pre-cancellation realizations.Source: Coding guidelines
openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go (1)
177-177: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winKeep the flat-fee fixture typed as flat-fee.
This helper builds a
chargesflatfee.Charge, but acceptingchargesusagebased.Intentmakes the fixture easy to misuse and obscures which fields matter for flat-fee tests. A small flat-fee-specific intent helper would keep this cleaner. As per coding guidelines, “Keep helper functions honest and narrow.”🤖 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/worker/subscriptionsync/service/reconciler/patchcharge_test.go` at line 177, The flat-fee test helper is too loosely typed because newChargePatchTestFlatFeeItemWithIntent accepts chargesusagebased.Intent even though it builds a chargesflatfee.Charge; update this fixture to use a flat-fee-specific intent type or add a dedicated flat-fee intent helper so the signature matches its purpose. Adjust the related test setup in newChargePatchTestFlatFeeItemWithIntent and any callers so the helper stays narrow and only exposes the flat-fee fields needed by these tests.Source: Coding guidelines
🤖 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/charges/usagebased/service/creditsonly_test.go`:
- Around line 24-43: The new credits-only period patch test only covers
finalization statuses, so extend
TestCreditsOnlyPeriodPatchIsConfiguredForFinalRealizationBoundaries to also
exercise usagebased.StatusCreated and usagebased.StatusActive through
newCreditsOnlyStateMachineForTest. Verify CanFire for both meta.TriggerShrink
and meta.TriggerExtend on those states as well, so the configureStates wiring
for the created/active patch paths is covered.
In `@openmeter/billing/charges/usagebased/service/creditsonly.go`:
- Around line 55-56: `creditsOnlyStateMachine` currently routes `TriggerExtend`
and `TriggerShrink` through `persistActivePeriodPatch()`, which force-sets the
charge to `StatusActive` and rewrites `AdvanceAfter` even when the charge is
still `usagebased.StatusCreated`. Update the `ExtendCharge`/`ShrinkCharge`
handling in `creditsonly.go` so the `StatusCreated` path is special-cased before
`persistActivePeriodPatch()` is called, or split it into a separate
created-state branch that only updates the intended patch fields. Keep the
`StatusCreated` lifecycle state and scheduling unchanged until activation, and
only apply the active-period patch logic for non-created statuses.
---
Nitpick comments:
In `@openmeter/billing/charges/usagebased/service/creditsonly_test.go`:
- Around line 31-40: The credits-only lifecycle subtests in the test function
using newCreditsOnlyStateMachineForTest should begin each non-trivial t.Run body
with the repo’s concise given/when/then intent markers. Add the short
given/when/then comments at the top of the affected subtests before the CanFire
assertions so the lifecycle intent is clear and consistent with the coding
guidelines.
In `@openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go`:
- Around line 963-966: The test narrative in the surrounding `Then` block is
stale because the assertions for `afterShrinkCharge` now describe native patch
behavior: the same charge stays active, advances from the cancellation boundary,
and has no realizations. Update the explanatory comments in
`creditsonly_test.go` around the `afterShrinkCharge` assertions so they match
the current flow and no longer mention a recreated charge or pre-cancellation
realizations.
In
`@openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go`:
- Line 177: The flat-fee test helper is too loosely typed because
newChargePatchTestFlatFeeItemWithIntent accepts chargesusagebased.Intent even
though it builds a chargesflatfee.Charge; update this fixture to use a
flat-fee-specific intent type or add a dedicated flat-fee intent helper so the
signature matches its purpose. Adjust the related test setup in
newChargePatchTestFlatFeeItemWithIntent and any callers so the helper stays
narrow and only exposes the flat-fee fields needed by these tests.
In `@pkg/statelessx/actions.go`:
- Line 9: Remove the unnecessary lo.Map usage from the affected helper in
actions.go and rewrite it with the same straightforward loop pattern used by
AllOf. Update the function that builds the []error result to append directly
inside the loop instead of creating an intermediate slice and recreating
WithParameters[T] wrappers on each call, keeping the implementation simple and
consistent with the rest of the 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: c9190610-9f5e-411a-9b5d-956787812a4e
📒 Files selected for processing (10)
openmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/meta/patch.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditsonly.goopenmeter/billing/charges/usagebased/service/creditsonly_test.goopenmeter/billing/worker/subscriptionsync/service/creditsonly_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.gopkg/statelessx/actions.go
Summary
Validation
env POSTGRES_HOST=127.0.0.1 go test -count=1 -tags=dynamic ./pkg/statelessx ./openmeter/billing/charges/meta ./openmeter/billing/charges/flatfee/... ./openmeter/billing/charges/usagebased/... ./openmeter/billing/worker/subscriptionsync/service/...nix develop --impure .#ci -c make lint-go-fastSummary by CodeRabbit