Repository navigation
feat: support usage-based gathering line deletes - #4663
Conversation
📝 WalkthroughWalkthroughThis PR adds a new API-facing shrink-to-realized-period patch for usage-based charges, makes intent mutations error-aware, wires the new behavior into credit-then-invoice and credits-only flows, updates gathering-line delete handling, and refreshes the related docs and tests. ChangesShrink-to-realized-period feature
Sequence Diagram(s)sequenceDiagram
participant LineEngine
participant CreditThenInvoiceStateMachine
participant RealizationRuns
participant IntentLayer
LineEngine->>CreditThenInvoiceStateMachine: ShrinkToRealizedPeriod(patch)
CreditThenInvoiceStateMachine->>RealizationRuns: WithoutVoidedBillingHistory().Latest()
RealizationRuns-->>CreditThenInvoiceStateMachine: latest realization run
CreditThenInvoiceStateMachine->>CreditThenInvoiceStateMachine: ValidateWith(intent)
CreditThenInvoiceStateMachine->>IntentLayer: mutateIntentLayer(ctx, editFn)
IntentLayer-->>CreditThenInvoiceStateMachine: updated ServicePeriod.To
CreditThenInvoiceStateMachine-->>LineEngine: delete gathering line patch
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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 |
394cdb5 to
86c28df
Compare
|
@coderabbitai review |
✅ Action performedReview finished.
|
082dc88 to
a40acdd
Compare
a40acdd to
ee00c8e
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (2)
openmeter/billing/charges/usagebased/service/statemachine.go (1)
147-149: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider wrapping the direct
editFnerror for consistency.When
editFnfails through theMutatepath (lines 134–135, 139–140), the error is wrapped with context like"mutating base intent". In the direct call path here, the error is returned unwrapped, so the sameeditFnfailure produces different error messages depending on whether an override layer already exists.♻️ Optional: wrap error for debuggability
overrideFields := s.Charge.Intent.GetEffectiveIntent().IntentMutableFields if err := editFn(&overrideFields); err != nil { - return err + return fmt.Errorf("editing override intent: %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/statemachine.go` around lines 147 - 149, The direct editFn call in the state machine path returns the raw error, unlike the Mutate path where editFn failures are wrapped with context. Update the editFn handling in the same statemachine.go flow to wrap this error consistently with the existing mutating context used around override/base intent mutations, so callers see the same error shape regardless of whether an override layer already exists.openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go (1)
7062-7159: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider extracting the shared progressive setup into a helper.
The "create progressive usage-based subscription" and "create paid progressive invoice and remaining gathering tail" subtests here are near-identical to the same-named subtests in
TestUsageBasedProgressiveGatheringInvoiceManualDeleteFinalizesCharge(lines 7253–7351). The only differences are the sync target time (2024-03-01vs2024-02-01) and one extraRequire().Lencheck in the third test. That's ~90 lines of duplicated setup.Per the coding guidelines, duplicate setup paths should be parameterized into one helper. A helper returning the six values both tests need (subsView, progressiveInvoice, progressiveLine, chargeID, gatheringInvoice, remainingLine) parameterized by the sync time would eliminate the copy and keep the two tests in sync if the setup evolves.
Based on coding guidelines: "Avoid redundant test helpers and duplicate setup paths; parameterize one helper over near-identical helpers."
♻️ Suggested shared setup helper
+type progressiveUsageBasedSetup struct { + subsView subscription.SubscriptionView + progressiveInvoice billing.StandardInvoice + progressiveLine *billing.StandardLine + chargeID chargesmeta.ChargeID + gatheringInvoice billing.GatheringInvoice + remainingLine billing.GatheringLine +} + +func (s *CreditThenInvoiceTestSuite) setupPaidProgressiveWithGatheringTail(ctx context.Context, syncTo time.Time) progressiveUsageBasedSetup { + s.enableProgressiveBilling() + s.MockStreamingConnector.AddSimpleEvent(*s.APIRequestsTotalFeature.MeterSlug, 0, s.mustParseTime("2023-01-01T00:00:00Z")) + s.MockStreamingConnector.AddSimpleEvent(*s.APIRequestsTotalFeature.MeterSlug, 1, s.mustParseTime("2024-01-01T00:00:00Z")) + s.MockStreamingConnector.AddSimpleEvent(*s.APIRequestsTotalFeature.MeterSlug, 1, s.mustParseTime("2024-01-12T09:30:00Z")) + + subsView := s.createSubscriptionFromPlan(plan.CreatePlanInput{ + // ... same plan config ... + }) + + clock.FreezeTime(clock.Now().Add(time.Minute)) + s.NoError(s.Service.SyncByView(ctx, subsView, syncTo)) + + clock.FreezeTime(s.mustParseTime("2024-01-15T00:00:00Z")) + draftInvoices, err := s.BillingService.InvoicePendingLines(ctx, billing.InvoicePendingLinesInput{ + Customer: s.Customer.GetID(), + AsOf: lo.ToPtr(s.mustParseTime("2024-01-15T00:00:00Z")), + }) + s.NoError(err) + s.Require().Len(draftInvoices, 1) + + progressiveInvoice := draftInvoices[0] + s.Require().Len(progressiveInvoice.Lines.OrEmpty(), 1) + progressiveLine := progressiveInvoice.Lines.OrEmpty()[0] + s.Require().NotNil(progressiveLine.ChargeID) + chargeID := chargesmeta.ChargeID{Namespace: progressiveLine.Namespace, ID: *progressiveLine.ChargeID} + s.Require().NotNil(progressiveInvoice.CollectionAt) + + clock.FreezeTime(progressiveInvoice.CollectionAt.Add(time.Minute)) + progressiveInvoice, err = s.BillingService.AdvanceInvoice(ctx, progressiveInvoice.GetInvoiceID()) + s.NoError(err) + s.Equal(billing.StandardInvoiceStatusDraftWaitingAutoApproval, progressiveInvoice.Status) + + progressiveInvoice, err = s.BillingService.ApproveInvoice(ctx, progressiveInvoice.GetInvoiceID()) + s.NoError(err) + s.Equal(billing.StandardInvoiceStatusPaid, progressiveInvoice.Status) + + gatheringInvoice := s.gatheringInvoice(ctx, s.Namespace, s.Customer.ID) + s.populateChildIDsFromParents(&gatheringInvoice) + s.DebugDumpInvoice("gathering invoice before manual delete", gatheringInvoice) + s.Require().Len(gatheringInvoice.Lines.OrEmpty(), 1) + + remainingLine, found := lo.Find(gatheringInvoice.Lines.OrEmpty(), func(line billing.GatheringLine) bool { + return line.ChargeID != nil && *line.ChargeID == chargeID.ID + }) + s.Require().True(found, "remaining gathering line should exist before manual delete") + s.Equal(progressiveLine.GetServicePeriod().To, remainingLine.ServicePeriod.From) + + return progressiveUsageBasedSetup{ + subsView: subsView, + progressiveInvoice: progressiveInvoice, + progressiveLine: progressiveLine, + chargeID: chargeID, + gatheringInvoice: gatheringInvoice, + remainingLine: remainingLine, + } +}Then each test's setup subtest becomes:
s.Run("create progressive usage-based subscription", func() { - // given: ... - s.enableProgressiveBilling() - s.MockStreamingConnector.AddSimpleEvent(...) - subsView = s.createSubscriptionFromPlan(...) - clock.FreezeTime(clock.Now().Add(time.Minute)) - s.NoError(s.Service.SyncByView(ctx, subsView, s.mustParseTime("2024-03-01T00:00:00Z"))) + // given: progressive billing enabled, usage exists, sync owns credit-then-invoice charge + setup := s.setupPaidProgressiveWithGatheringTail(ctx, s.mustParseTime("2024-03-01T00:00:00Z")) + subsView = setup.subsView + progressiveInvoice = setup.progressiveInvoice + progressiveLine = setup.progressiveLine + chargeID = setup.chargeID + gatheringInvoice = setup.gatheringInvoice + remainingLine = setup.remainingLine })🤖 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/sync_credittheninvoice_test.go` around lines 7062 - 7159, The two progressive setup subtests in this test file duplicate the same invoice creation and payment flow, so factor that shared logic into a single helper instead of keeping near-identical blocks in both places. Create a parameterized helper around the common setup in the progressive test flow, using the existing symbols like s.enableProgressiveBilling, s.createSubscriptionFromPlan, s.BillingService.InvoicePendingLines, s.BillingService.AdvanceInvoice, s.BillingService.ApproveInvoice, and s.gatheringInvoice, and have it return the shared values the tests need. Keep only the differing sync target time and any extra assertion at the call sites so both tests stay aligned as the setup evolves.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.
Nitpick comments:
In `@openmeter/billing/charges/usagebased/service/statemachine.go`:
- Around line 147-149: The direct editFn call in the state machine path returns
the raw error, unlike the Mutate path where editFn failures are wrapped with
context. Update the editFn handling in the same statemachine.go flow to wrap
this error consistently with the existing mutating context used around
override/base intent mutations, so callers see the same error shape regardless
of whether an override layer already exists.
In
`@openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go`:
- Around line 7062-7159: The two progressive setup subtests in this test file
duplicate the same invoice creation and payment flow, so factor that shared
logic into a single helper instead of keeping near-identical blocks in both
places. Create a parameterized helper around the common setup in the progressive
test flow, using the existing symbols like s.enableProgressiveBilling,
s.createSubscriptionFromPlan, s.BillingService.InvoicePendingLines,
s.BillingService.AdvanceInvoice, s.BillingService.ApproveInvoice, and
s.gatheringInvoice, and have it return the shared values the tests need. Keep
only the differing sync target time and any extra assertion at the call sites so
both tests stay aligned as the setup evolves.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: da0be41a-10f3-4dec-9c7b-0a1180fdd5d9
📒 Files selected for processing (17)
.agents/skills/charges/SKILL.mdopenmeter/billing/charges/meta/patch.goopenmeter/billing/charges/meta/patch_target_test.goopenmeter/billing/charges/meta/patchshrinktorealizedperiod.goopenmeter/billing/charges/meta/triggers.goopenmeter/billing/charges/usagebased/adapter/charge.goopenmeter/billing/charges/usagebased/adapter/intentoverride_test.goopenmeter/billing/charges/usagebased/charge.goopenmeter/billing/charges/usagebased/realizationrun.goopenmeter/billing/charges/usagebased/realizationrun_test.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/rating/service_test.goopenmeter/billing/charges/usagebased/service/statemachine.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
Summary
Add a usage-based shrink-to-realized-period patch for manual gathering line deletion.
Rules:
Summary by CodeRabbit
New Features
Bug Fixes
Tests / Docs
RealizationRuns.Latest()semantics.Greptile Summary
This PR adds usage-based gathering-line delete handling. The main changes are:
Confidence Score: 4/5
This is close, but the validation gap should be fixed before merging.
openmeter/billing/charges/usagebased/service/lineengine.go
Important Files Changed
Prompt To Fix All With AI
Reviews (3): Last reviewed commit: "feat(billing): support usage-based gathe..." | Re-trigger Greptile
Context used: