Repository navigation
feat: flat fee delete patch support - #4031
Conversation
|
Caution Review failedPull request was closed or merged during review 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:
📝 WalkthroughWalkthroughAdds a charge-patching flow (ApplyPatches) with patch types and remapping, refactors charge-search APIs to Changes
Sequence Diagram(s)sequenceDiagram
participant Caller as Caller
participant ChargeService as ChargeService
participant Adapter as Adapter
participant Invocable as Invocable(FlatFee)
participant StateMachine as StateMachine
participant Handler as Handler
participant DB as DB
Caller->>ChargeService: ApplyPatches(input)
ChargeService->>Adapter: GetByIDs(namespace, ids)
Adapter-->>ChargeService: ChargeSearchItems
ChargeService->>ChargeService: newInvocableCharges(...) -> map[id]Invocable
ChargeService->>Invocable: TriggerPatch(patch)
Invocable->>StateMachine: FireAndActivate(trigger, params)
StateMachine->>Handler: OnCreditsOnlyUsageAccruedCorrection(corrections)
Handler->>DB: create credit correction records
StateMachine->>Adapter: DeleteCharge(charge)
Adapter->>DB: update charge (DeletedAt, status)
Adapter-->>StateMachine: deletion ack
StateMachine-->>Invocable: return updated charge
Invocable-->>ChargeService: result
ChargeService-->>Caller: ApplyPatches returns
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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 |
f3df2f5 to
9c5e7d8
Compare
065c2e3 to
1e6df27
Compare
1e6df27 to
c67be5b
Compare
c67be5b to
a82a292
Compare
a82a292 to
7509062
Compare
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (10)
openmeter/billing/charges/meta/charge.go (1)
101-102: Minor grammar nit in the comment.The comment reads "is deleted no further actions" — might read better as "is deleted; no further actions are possible on it" with a semicolon or comma for clarity. Super minor!
✏️ Suggested tweak
- // ChargeStatusDeleted is the status of a charge that is deleted no further actions are possible on it. + // ChargeStatusDeleted is the status of a charge that is deleted; no further actions are possible on it. ChargeStatusDeleted ChargeStatus = "deleted"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/meta/charge.go` around lines 101 - 102, Fix the minor grammar in the doc comment for ChargeStatusDeleted: change "is deleted no further actions are possible on it." to use proper punctuation and clarity (e.g., "is deleted; no further actions are possible on it." or "is deleted, and no further actions are possible on it.") so the comment for the ChargeStatusDeleted constant reads clearly.openmeter/billing/charges/flatfee/service/creditsonly.go (1)
162-164: Good to see the TODO for future extraction.The
ErrUnsupportedOperationandFireAndActivatepattern is useful and could benefit other state machines. The TODO acknowledges this — just a reminder to circle back when you have time to DRY this up across the codebase.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/flatfee/service/creditsonly.go` around lines 162 - 164, The TODO notes that ErrUnsupportedOperation and the FireAndActivate pattern belong in a shared helper: extract ErrUnsupportedOperation (currently declared in creditsonly.go) and the FireAndActivate state-transition logic into a reusable package (e.g., state or statemachine) so other state machines can import them; keep the exported symbol names ErrUnsupportedOperation and FireAndActivate (or provide clearly named equivalents) and update creditsonly.go to import and use the new helper functions/types instead of local implementations to DRY the codebase.openmeter/billing/charges/meta/patchextend.go (1)
30-44: Consider accumulating errors inValidate()for consistency.The
Validate()method returns on the first error, whileValidateWith()accumulates all errors viaerrors.Join. If a caller provides multiple zero timestamps, they'll get one error at a time instead of seeing all issues upfront.This isn't blocking, but aligning with
ValidateWith's accumulation pattern could improve the UX:♻️ Optional: Accumulate all validation errors
func (p PatchExtend) Validate() error { + var errs []error + if p.NewServicePeriodTo.IsZero() { - return fmt.Errorf("new service period to is required") + errs = append(errs, fmt.Errorf("new service period to is required")) } if p.NewFullServicePeriodTo.IsZero() { - return fmt.Errorf("new full service period to is required") + errs = append(errs, fmt.Errorf("new full service period to is required")) } if p.NewBillingPeriodTo.IsZero() { - return fmt.Errorf("new billing period to is required") + errs = append(errs, fmt.Errorf("new billing period to is required")) } - return nil + return errors.Join(errs...) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/meta/patchextend.go` around lines 30 - 44, PatchExtend.Validate currently returns on the first missing timestamp; change it to collect all validation failures into a slice or error list and return a single joined error (use errors.Join) so callers see every missing field at once. Specifically inspect PatchExtend.Validate and check the fields NewServicePeriodTo, NewFullServicePeriodTo and NewBillingPeriodTo, appending an error for each IsZero() case, then return errors.Join(...) (or nil if none) to mirror the accumulation behavior of ValidateWith.openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go (1)
332-344: Consider inverting the nil check for clarity.The current structure checks emptiness, then nil, then applies. The else branch only handles the error case. A simpler structure:
♻️ Optional: Simplify guard structure
if !input.Plan.ChargePatches.IsEmpty() { - if s.chargesService != nil { - // Let's finalize the input's global fields - chargePatches := input.Plan.ChargePatches - chargePatches.CustomerID = input.Customer - - if err := s.chargesService.ApplyPatches(ctx, chargePatches); err != nil { - return fmt.Errorf("updating charges: %w", err) - } - } else { + if s.chargesService == nil { return fmt.Errorf("charges service is required when there are charge patches") } + + // Let's finalize the input's global fields + chargePatches := input.Plan.ChargePatches + chargePatches.CustomerID = input.Customer + + if err := s.chargesService.ApplyPatches(ctx, chargePatches); err != nil { + return fmt.Errorf("updating charges: %w", err) + } }This puts the error case first (early return pattern) and keeps the happy path less indented.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go` around lines 332 - 344, Invert the guard by surfacing the error case first: if s.chargesService == nil && !input.Plan.ChargePatches.IsEmpty() return fmt.Errorf("charges service is required when there are charge patches"), then handle the happy path: if !input.Plan.ChargePatches.IsEmpty() { chargePatches := input.Plan.ChargePatches; chargePatches.CustomerID = input.Customer; if err := s.chargesService.ApplyPatches(ctx, chargePatches); err != nil { return fmt.Errorf("updating charges: %w", err) } }, referencing input.Plan.ChargePatches, s.chargesService and ApplyPatches in reconciler.go.openmeter/billing/charges/service/helpers.go (1)
65-83: Variable shadowing withsi.On line 67, you're shadowing the parameter
siwith the loop variable. This works but can be confusing to readers. Consider using a different name for the loop variable.♻️ Rename loop variable to avoid shadowing
-func (s *service) newInvocableCharges(si charges.ChargeSearchItems) (map[string]InvocableCharge, error) { - result := make(map[string]InvocableCharge, len(si)) - for _, si := range si { - if _, exists := result[si.ID.ID]; exists { - return nil, fmt.Errorf("duplicated charge ID: %s", si.ID.ID) +func (s *service) newInvocableCharges(searchItems charges.ChargeSearchItems) (map[string]InvocableCharge, error) { + result := make(map[string]InvocableCharge, len(searchItems)) + for _, item := range searchItems { + if _, exists := result[item.ID.ID]; exists { + return nil, fmt.Errorf("duplicated charge ID: %s", item.ID.ID) } - switch si.Type { + switch item.Type { case meta.ChargeTypeFlatFee: - result[si.ID.ID] = &flatFeeInvocableCharge{ - chargeID: si.ID, + result[item.ID.ID] = &flatFeeInvocableCharge{ + chargeID: item.ID, flatFeeService: s.flatFeeService, } default: - return nil, fmt.Errorf("unsupported charge type: %s", si.Type) + return nil, fmt.Errorf("unsupported charge type: %s", item.Type) } } return result, nil }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/service/helpers.go` around lines 65 - 83, The function newInvocableCharges shadows its parameter si by using the same name for the loop variable, which is confusing; rename the loop variable (e.g., items -> item or chargeItem) throughout the loop body so references like si.ID, si.Type become item.ID, item.Type (or chosen name) and update checks and map assignments accordingly in newInvocableCharges and any referenced symbols (flatFeeInvocableCharge construction, duplicated ID check, unsupported type error) to avoid shadowing.openmeter/billing/charges/meta/patchshrink.go (1)
30-44: Consider aggregating validation errors for consistency.
Validate()returns on the first error, whileValidateWith()aggregates all errors usingerrors.Join. This inconsistency means callers get different error reporting behavior depending on which method they call. If you want uniform behavior, consider aggregating here too.That said, this is totally fine if the intention is to keep standalone
Validate()simple and fast-fail.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/meta/patchshrink.go` around lines 30 - 44, PatchShrink.Validate currently returns on the first missing field but ValidateWith aggregates all errors via errors.Join; update PatchShrink.Validate to collect all validation failures into a slice of errors (e.g., for NewServicePeriodTo, NewFullServicePeriodTo, NewBillingPeriodTo) and return errors.Join(errs...) so callers get a consistent aggregated error shape like ValidateWith; keep using the same error messages to preserve behavior.openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go (1)
54-57: Avoid callingValidate()twice.You're calling
intent.Validate()twice here - once to check and once in the error message. This is a minor inefficiency and could mask different errors if the validation is non-deterministic (unlikely, but still).♻️ Store the validation result
func (c *chargePatchCollection) addCreate(intent charges.ChargeIntent) error { - if intent.Validate() != nil { - return fmt.Errorf("invalid intent: %w", intent.Validate()) - } + if err := intent.Validate(); err != nil { + return fmt.Errorf("invalid intent: %w", err) + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go` around lines 54 - 57, The addCreate method on chargePatchCollection calls intent.Validate() twice; capture the validation error once into a variable (e.g., err := intent.Validate()) and if err != nil return fmt.Errorf("invalid intent: %w", err) so both the check and the wrapped error use the same result; update the function addCreate and any similar spots using charges.ChargeIntent.Validate to reuse the stored validation error instead of invoking Validate() twice.openmeter/billing/charges/service/patchtmp.go (1)
126-155: Duplicated logic across charge types - acceptable for temporary code.The
tmpApplyPatchToCreateIntentfunction has nearly identical handling forFlatFeeandUsageBasedcases. Normally I'd suggest extracting the common logic, but since this is explicitly temporary code (to be replaced when proper shrink/extend is implemented), the duplication is fine to keep things simple.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/service/patchtmp.go` around lines 126 - 155, The code in tmpApplyPatchToCreateIntent duplicates the same update logic for FlatFee and UsageBased charges; since this is temporary code, no refactor is required—leave the switch handling in tmpApplyPatchToCreateIntent (cases for meta.ChargeTypeFlatFee and meta.ChargeTypeUsageBased, and the default error) as-is until a proper shrink/extend remap is implemented.openmeter/billing/charges/service/patch.go (1)
45-49: Fast-path empty patch sets.
applyPatchesalways does aGetByIDsround-trip, even whenpatchesByChargeIDis empty. A tiny guard makes that case explicit, keeps this DB path cheaper, and avoids leaning on the empty-IDIn(...)behavior.As per coding guidelines, "Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks."♻️ Suggested tweak
func (s *service) applyPatches(ctx context.Context, customerID customer.CustomerID, patchesByChargeID map[string]charges.Patch) error { + if len(patchesByChargeID) == 0 { + return nil + } + chargesItems, err := s.adapter.GetByIDs(ctx, charges.GetByIDsInput{ Namespace: customerID.Namespace, IDs: lo.Keys(patchesByChargeID), })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/service/patch.go` around lines 45 - 49, In applyPatches, avoid the unnecessary DB round-trip when there are no patches: check if the patchesByChargeID map is empty at the top of the function (before calling s.adapter.GetByIDs) and return nil immediately; this uses the existing applyPatches signature and prevents calling GetByIDs with an empty ID list, reducing cost on the critical DB path.openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go (1)
235-367: Worth adding one expand-path regression too.These cases lock down delete and shrink nicely, but the PR also routes expand through the same patch pipeline. One scenario that lengthens an active flat-fee period would help cover the other half of the feature while the temporary remapping is still in play.
As per coding guidelines, "
**/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests."Also applies to: 369-521
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go` around lines 235 - 367, Add a sibling expand-path regression to the CreditsOnlySubscriptionHandlerTestSuite that mirrors the cancellation case but exercises expansion: after provisioning two flat-fee charges via Service.SynchronizeSubscription (same flow used in TestCreditsOnlyFlatFeeCancellationAtPeriodBoundary and helper createSubscriptionFromPlanAt), simulate an extension of the active flat-fee period (advance clock to a time where the subscription is lengthened or update the plan/timing to extend the first phase), call SubscriptionService to apply the change and re-run Service.SynchronizeSubscription, then assert using expectCreditsOnlyFlatFeeCharges that the second-period charge is either shifted/extended (new service/billing periods and invoiceAt) or an additional charge is created with correct ChildUniqueReferenceIDs and that original child IDs map correctly; use the same helpers (expectCreditsOnlyFlatFeeCharges, createSubscriptionFromPlanAt, SubscriptionService.Cancel/Update, SynchronizeSubscription) so the test covers the expand code path.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/billing/charges/flatfee/service/triggers.go`:
- Around line 50-56: The TriggerPatch implementation currently returns nil for
the *Charge result after calling stateMachine.FireAndActivate, causing an
interface mismatch; update TriggerPatch (the method invoking
stateMachine.FireAndActivate) to return the updated *Charge instead of nil by
retrieving the charge after the state transition (e.g., reload from the charge
repository or obtain the updated charge from the state machine) so its signature
matches the interface and mirrors AdvanceCharge behavior; alternatively, if
callers truly don't need the charge, change the interface signature to return
only error, but prefer returning the reloaded *Charge to preserve contract and
consistency with AdvanceCharge.
In `@openmeter/billing/charges/patch.go`:
- Around line 56-75: ConcatenateApplyPatchesInputs currently dereferences
inputs[0] and will panic if called with no arguments; add a guard at the start
of ConcatenateApplyPatchesInputs to handle an empty inputs slice (either return
an empty ApplyPatchesInput and nil error or return an explicit error) before
accessing inputs[0]; ensure the created result (ApplyPatchesInput) still
initializes Creates and PatchesByChargeID with zero capacity when inputs is
empty and keep the rest of the logic unchanged so subsequent uses of CustomerID,
Creates and PatchesByChargeID are safe.
In `@openmeter/billing/charges/service/patch.go`:
- Around line 60-61: The error message in the namespace check for charge.ID vs
customerID is showing actual and expected backwards; in the function containing
the check (where charge.ID.Namespace and customerID.Namespace are compared)
update the fmt.Errorf call so it prints the actual namespace
(charge.ID.Namespace) then the expected namespace (customerID.Namespace) for the
message referencing charge.ID.ID, e.g. change the argument order to reflect
"actual, expected" rather than the current reversed order.
In `@openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go`:
- Around line 160-167: The logChargesPatches function logs creates using the
loop variable chargeID which is actually the slice index, causing a misleading
"charge_id" field; update the creates loop in logChargesPatches to either log
the index with a descriptive key (e.g., "create_index") or extract the real
charge identifier from the patch (e.g., patch.ID or patch.Intent.ID) and use
that as "charge_id" so the log reflects the true entity; adjust the log field
name accordingly in the log.Info call for patches.Creates.
---
Nitpick comments:
In `@openmeter/billing/charges/flatfee/service/creditsonly.go`:
- Around line 162-164: The TODO notes that ErrUnsupportedOperation and the
FireAndActivate pattern belong in a shared helper: extract
ErrUnsupportedOperation (currently declared in creditsonly.go) and the
FireAndActivate state-transition logic into a reusable package (e.g., state or
statemachine) so other state machines can import them; keep the exported symbol
names ErrUnsupportedOperation and FireAndActivate (or provide clearly named
equivalents) and update creditsonly.go to import and use the new helper
functions/types instead of local implementations to DRY the codebase.
In `@openmeter/billing/charges/meta/charge.go`:
- Around line 101-102: Fix the minor grammar in the doc comment for
ChargeStatusDeleted: change "is deleted no further actions are possible on it."
to use proper punctuation and clarity (e.g., "is deleted; no further actions are
possible on it." or "is deleted, and no further actions are possible on it.") so
the comment for the ChargeStatusDeleted constant reads clearly.
In `@openmeter/billing/charges/meta/patchextend.go`:
- Around line 30-44: PatchExtend.Validate currently returns on the first missing
timestamp; change it to collect all validation failures into a slice or error
list and return a single joined error (use errors.Join) so callers see every
missing field at once. Specifically inspect PatchExtend.Validate and check the
fields NewServicePeriodTo, NewFullServicePeriodTo and NewBillingPeriodTo,
appending an error for each IsZero() case, then return errors.Join(...) (or nil
if none) to mirror the accumulation behavior of ValidateWith.
In `@openmeter/billing/charges/meta/patchshrink.go`:
- Around line 30-44: PatchShrink.Validate currently returns on the first missing
field but ValidateWith aggregates all errors via errors.Join; update
PatchShrink.Validate to collect all validation failures into a slice of errors
(e.g., for NewServicePeriodTo, NewFullServicePeriodTo, NewBillingPeriodTo) and
return errors.Join(errs...) so callers get a consistent aggregated error shape
like ValidateWith; keep using the same error messages to preserve behavior.
In `@openmeter/billing/charges/service/helpers.go`:
- Around line 65-83: The function newInvocableCharges shadows its parameter si
by using the same name for the loop variable, which is confusing; rename the
loop variable (e.g., items -> item or chargeItem) throughout the loop body so
references like si.ID, si.Type become item.ID, item.Type (or chosen name) and
update checks and map assignments accordingly in newInvocableCharges and any
referenced symbols (flatFeeInvocableCharge construction, duplicated ID check,
unsupported type error) to avoid shadowing.
In `@openmeter/billing/charges/service/patch.go`:
- Around line 45-49: In applyPatches, avoid the unnecessary DB round-trip when
there are no patches: check if the patchesByChargeID map is empty at the top of
the function (before calling s.adapter.GetByIDs) and return nil immediately;
this uses the existing applyPatches signature and prevents calling GetByIDs with
an empty ID list, reducing cost on the critical DB path.
In `@openmeter/billing/charges/service/patchtmp.go`:
- Around line 126-155: The code in tmpApplyPatchToCreateIntent duplicates the
same update logic for FlatFee and UsageBased charges; since this is temporary
code, no refactor is required—leave the switch handling in
tmpApplyPatchToCreateIntent (cases for meta.ChargeTypeFlatFee and
meta.ChargeTypeUsageBased, and the default error) as-is until a proper
shrink/extend remap is implemented.
In `@openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go`:
- Around line 235-367: Add a sibling expand-path regression to the
CreditsOnlySubscriptionHandlerTestSuite that mirrors the cancellation case but
exercises expansion: after provisioning two flat-fee charges via
Service.SynchronizeSubscription (same flow used in
TestCreditsOnlyFlatFeeCancellationAtPeriodBoundary and helper
createSubscriptionFromPlanAt), simulate an extension of the active flat-fee
period (advance clock to a time where the subscription is lengthened or update
the plan/timing to extend the first phase), call SubscriptionService to apply
the change and re-run Service.SynchronizeSubscription, then assert using
expectCreditsOnlyFlatFeeCharges that the second-period charge is either
shifted/extended (new service/billing periods and invoiceAt) or an additional
charge is created with correct ChildUniqueReferenceIDs and that original child
IDs map correctly; use the same helpers (expectCreditsOnlyFlatFeeCharges,
createSubscriptionFromPlanAt, SubscriptionService.Cancel/Update,
SynchronizeSubscription) so the test covers the expand code path.
In `@openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go`:
- Around line 54-57: The addCreate method on chargePatchCollection calls
intent.Validate() twice; capture the validation error once into a variable
(e.g., err := intent.Validate()) and if err != nil return fmt.Errorf("invalid
intent: %w", err) so both the check and the wrapped error use the same result;
update the function addCreate and any similar spots using
charges.ChargeIntent.Validate to reuse the stored validation error instead of
invoking Validate() twice.
In `@openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go`:
- Around line 332-344: Invert the guard by surfacing the error case first: if
s.chargesService == nil && !input.Plan.ChargePatches.IsEmpty() return
fmt.Errorf("charges service is required when there are charge patches"), then
handle the happy path: if !input.Plan.ChargePatches.IsEmpty() { chargePatches :=
input.Plan.ChargePatches; chargePatches.CustomerID = input.Customer; if err :=
s.chargesService.ApplyPatches(ctx, chargePatches); err != nil { return
fmt.Errorf("updating charges: %w", err) } }, referencing
input.Plan.ChargePatches, s.chargesService and ApplyPatches in reconciler.go.
🪄 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: c922f763-5a1b-458d-804c-f93e5ea465e5
⛔ Files ignored due to path filters (5)
openmeter/ent/db/chargecreditpurchase/chargecreditpurchase.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfee/chargeflatfee.gois excluded by!**/ent/db/**openmeter/ent/db/chargessearchv1/chargessearchv1.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**
📒 Files selected for processing (42)
AGENTS.mdopenmeter/billing/charges/adapter.goopenmeter/billing/charges/adapter/search.goopenmeter/billing/charges/charge.goopenmeter/billing/charges/flatfee/adapter.goopenmeter/billing/charges/flatfee/adapter/charge.goopenmeter/billing/charges/flatfee/handler.goopenmeter/billing/charges/flatfee/service.goopenmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/flatfee/service/get.goopenmeter/billing/charges/flatfee/service/triggers.goopenmeter/billing/charges/flatfee/statemachine.goopenmeter/billing/charges/meta/charge.goopenmeter/billing/charges/meta/patch.goopenmeter/billing/charges/meta/patchdelete.goopenmeter/billing/charges/meta/patchextend.goopenmeter/billing/charges/meta/patchshrink.goopenmeter/billing/charges/meta/triggers.goopenmeter/billing/charges/models/creditrealization/realizations.goopenmeter/billing/charges/patch.goopenmeter/billing/charges/service.goopenmeter/billing/charges/service/get.goopenmeter/billing/charges/service/handlers_test.goopenmeter/billing/charges/service/helpers.goopenmeter/billing/charges/service/patch.goopenmeter/billing/charges/service/patchtmp.goopenmeter/billing/charges/testutils/handlers.goopenmeter/billing/charges/usagebased/adapter/charge.goopenmeter/billing/charges/usagebased/service/creditsonly.goopenmeter/billing/charges/usagebased/service/statemachine.goopenmeter/billing/worker/subscriptionsync/service/creditsonly_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/disabled.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/patch.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patch.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.goopenmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.goopenmeter/ledger/chargeadapter/flatfee.gopkg/statelessx/actions.go
💤 Files with no reviewable changes (5)
- openmeter/billing/charges/flatfee/statemachine.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/disabled.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/patch.go
There was a problem hiding this comment.
🧹 Nitpick comments (3)
openmeter/billing/charges/patch.go (1)
62-66: CustomerID consistency is not enforced across inputs.The function uses
inputs[0].CustomerIDfor the result but doesn't check that all subsequent inputs have the same CustomerID. If callers pass inputs with different customers, the result will silently use the first one's ID while merging patches from all inputs.🛡️ Proposed fix to validate CustomerID consistency
result := ApplyPatchesInput{ CustomerID: inputs[0].CustomerID, Creates: make(ChargeIntents, 0, lo.SumBy(inputs, func(input ApplyPatchesInput) int { return len(input.Creates) })), PatchesByChargeID: make(map[string]Patch, lo.SumBy(inputs, func(input ApplyPatchesInput) int { return len(input.PatchesByChargeID) })), } for _, input := range inputs { + if input.CustomerID != result.CustomerID { + return ApplyPatchesInput{}, fmt.Errorf("customer ID mismatch: expected %s, got %s", result.CustomerID, input.CustomerID) + } result.Creates = append(result.Creates, input.Creates...)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/patch.go` around lines 62 - 66, The code sets result.CustomerID from inputs[0].CustomerID but doesn't validate that all entries in inputs share the same CustomerID; add a validation step before building result that iterates over inputs and checks each input.CustomerID equals inputs[0].CustomerID, and if any differ return an error (or propagate an appropriate failure) instead of silently merging; update the caller-facing function that constructs ApplyPatchesInput to surface this error so inconsistent CustomerID values cannot be merged.openmeter/billing/charges/service/patch.go (1)
45-52: Consider early return when no patches to apply.When
patchesByChargeIDis empty, this still callsGetByIDswith an empty slice. While likely harmless, returning early would skip the unnecessary database call.♻️ Optional: Add early return
func (s *service) applyPatches(ctx context.Context, customerID customer.CustomerID, patchesByChargeID map[string]charges.Patch) error { + if len(patchesByChargeID) == 0 { + return nil + } + chargesItems, err := s.adapter.GetByIDs(ctx, charges.GetByIDsInput{ Namespace: customerID.Namespace, IDs: lo.Keys(patchesByChargeID), })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/service/patch.go` around lines 45 - 52, In applyPatches, avoid calling s.adapter.GetByIDs when there are no patches by adding an early return: check if len(patchesByChargeID) == 0 and return nil immediately; this should be placed at the start of the applyPatches function (before calling s.adapter.GetByIDs) and references the existing patchesByChargeID map and GetByIDs call so the change is localized and skips the unnecessary database round-trip.openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go (1)
54-57: Double validation call - store the error from the first call.
intent.Validate()is called twice here: once for the nil check and again to wrap the error. This is inefficient and could behave inconsistently if validation has side effects (unlikely, but still).♻️ Proposed fix
func (c *chargePatchCollection) addCreate(intent charges.ChargeIntent) error { - if intent.Validate() != nil { - return fmt.Errorf("invalid intent: %w", intent.Validate()) + if err := intent.Validate(); err != nil { + return fmt.Errorf("invalid intent: %w", err) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go` around lines 54 - 57, In addCreate on chargePatchCollection, avoid calling intent.Validate() twice: call it once, store the returned error in a local variable (e.g., err := intent.Validate()), return nil if err is nil, otherwise return fmt.Errorf("invalid intent: %w", err); this ensures only a single validation invocation on charges.ChargeIntent and uses that captured error for the wrapped log.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@openmeter/billing/charges/patch.go`:
- Around line 62-66: The code sets result.CustomerID from inputs[0].CustomerID
but doesn't validate that all entries in inputs share the same CustomerID; add a
validation step before building result that iterates over inputs and checks each
input.CustomerID equals inputs[0].CustomerID, and if any differ return an error
(or propagate an appropriate failure) instead of silently merging; update the
caller-facing function that constructs ApplyPatchesInput to surface this error
so inconsistent CustomerID values cannot be merged.
In `@openmeter/billing/charges/service/patch.go`:
- Around line 45-52: In applyPatches, avoid calling s.adapter.GetByIDs when
there are no patches by adding an early return: check if len(patchesByChargeID)
== 0 and return nil immediately; this should be placed at the start of the
applyPatches function (before calling s.adapter.GetByIDs) and references the
existing patchesByChargeID map and GetByIDs call so the change is localized and
skips the unnecessary database round-trip.
In `@openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go`:
- Around line 54-57: In addCreate on chargePatchCollection, avoid calling
intent.Validate() twice: call it once, store the returned error in a local
variable (e.g., err := intent.Validate()), return nil if err is nil, otherwise
return fmt.Errorf("invalid intent: %w", err); this ensures only a single
validation invocation on charges.ChargeIntent and uses that captured error for
the wrapped log.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 0e916e23-9ed4-493e-bfac-42acb4b2cae8
📒 Files selected for processing (4)
openmeter/billing/charges/flatfee/service/triggers.goopenmeter/billing/charges/patch.goopenmeter/billing/charges/service/patch.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go
✅ Files skipped from review due to trivial changes (1)
- openmeter/billing/charges/flatfee/service/triggers.go
9b501bd to
1e49d0f
Compare
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 (1)
openmeter/billing/charges/adapter.go (1)
58-76:⚠️ Potential issue | 🟡 MinorRemove
GetTypesByIDsInput— it's unused dead code.This struct and its
Validatemethod aren't referenced anywhere in the codebase. Since the interface now usesGetByIDsInputfromservice.go, this type can be safely deleted.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/adapter.go` around lines 58 - 76, Remove the unused dead type GetTypesByIDsInput and its Validate method: delete the entire GetTypesByIDsInput struct declaration and the func (i GetTypesByIDsInput) Validate() error from adapter.go since the codebase now uses GetByIDsInput from service.go and there are no references to GetTypesByIDsInput or its Validate method.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/billing/charges/flatfee/adapter/charge.go`:
- Around line 88-93: Remove AdvanceAfter from the UpdateInput passed to
chargemeta.Update for flat-fee charges: in the call site where you build the
UpdateInput (the call to chargemeta.Update and the struct literal for
chargemeta.UpdateInput), stop assigning AdvanceAfter: charge.State.AdvanceAfter
so UpdateInput does not contain AdvanceAfter for flat-fee adapter/charge paths;
leave all other fields (ManagedResource, Intent, Status) as-is.
- Around line 81-86: The delete flow mutates the in-memory charge
(charge.DeletedAt and charge.Status) but never persists DeletedAt, so deleted
flat-fee charges still match queries using DeletedAtIsNil; inside the
TransactingRepoWithNoValue callback that builds
tx.db.ChargeFlatFee.UpdateOneID(charge.ID).Where(dbchargeflatfee.NamespaceEQ(charge.Namespace)),
include the DeletedAt and Status updates on the ent mutation (i.e., set
deleted_at to clock.Now() and status to meta.ChargeStatusDeleted on the
UpdateOneID mutation) so both fields are persisted; reference the UpdateOneID
mutation on tx.db.ChargeFlatFee, the charge struct's DeletedAt/Status, and the
dbchargeflatfee.NamespaceEQ filter when applying the changes.
In `@openmeter/billing/charges/flatfee/service/creditsonly.go`:
- Around line 239-243: The delete currently returns the result of
s.refetchCharge(ctx) which can surface transient read errors after
s.Adapter.DeleteCharge(ctx, s.Charge) already succeeded; change the flow so
DeleteCharge is the committed success boundary: after a successful
s.Adapter.DeleteCharge call return nil (or the success value) immediately, and
make the refetch best-effort (e.g., call s.refetchCharge(ctx) asynchronously or
call it synchronously but swallow/log any error instead of returning it). Update
code around s.Adapter.DeleteCharge and s.refetchCharge to ensure the adapter
delete error is still returned, but refetch errors are logged and not
propagated.
---
Outside diff comments:
In `@openmeter/billing/charges/adapter.go`:
- Around line 58-76: Remove the unused dead type GetTypesByIDsInput and its
Validate method: delete the entire GetTypesByIDsInput struct declaration and the
func (i GetTypesByIDsInput) Validate() error from adapter.go since the codebase
now uses GetByIDsInput from service.go and there are no references to
GetTypesByIDsInput or its Validate method.
🪄 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: 6651bae6-527b-49b2-af83-33d3114e2db9
⛔ Files ignored due to path filters (5)
openmeter/ent/db/chargecreditpurchase/chargecreditpurchase.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfee/chargeflatfee.gois excluded by!**/ent/db/**openmeter/ent/db/chargessearchv1/chargessearchv1.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**
📒 Files selected for processing (42)
AGENTS.mdopenmeter/billing/charges/adapter.goopenmeter/billing/charges/adapter/search.goopenmeter/billing/charges/charge.goopenmeter/billing/charges/flatfee/adapter.goopenmeter/billing/charges/flatfee/adapter/charge.goopenmeter/billing/charges/flatfee/handler.goopenmeter/billing/charges/flatfee/service.goopenmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/flatfee/service/get.goopenmeter/billing/charges/flatfee/service/triggers.goopenmeter/billing/charges/flatfee/statemachine.goopenmeter/billing/charges/meta/charge.goopenmeter/billing/charges/meta/patch.goopenmeter/billing/charges/meta/patchdelete.goopenmeter/billing/charges/meta/patchextend.goopenmeter/billing/charges/meta/patchshrink.goopenmeter/billing/charges/meta/triggers.goopenmeter/billing/charges/models/creditrealization/realizations.goopenmeter/billing/charges/patch.goopenmeter/billing/charges/service.goopenmeter/billing/charges/service/get.goopenmeter/billing/charges/service/handlers_test.goopenmeter/billing/charges/service/helpers.goopenmeter/billing/charges/service/patch.goopenmeter/billing/charges/service/patchtmp.goopenmeter/billing/charges/testutils/handlers.goopenmeter/billing/charges/usagebased/adapter/charge.goopenmeter/billing/charges/usagebased/service/creditsonly.goopenmeter/billing/charges/usagebased/service/statemachine.goopenmeter/billing/worker/subscriptionsync/service/creditsonly_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/disabled.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/patch.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patch.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.goopenmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.goopenmeter/ledger/chargeadapter/flatfee.gopkg/statelessx/actions.go
💤 Files with no reviewable changes (5)
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/disabled.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/patch.go
- openmeter/billing/charges/flatfee/statemachine.go
✅ Files skipped from review due to trivial changes (7)
- openmeter/billing/charges/usagebased/service/statemachine.go
- openmeter/billing/charges/meta/patch.go
- openmeter/billing/charges/meta/triggers.go
- openmeter/billing/charges/testutils/handlers.go
- openmeter/billing/charges/usagebased/service/creditsonly.go
- AGENTS.md
- openmeter/billing/charges/patch.go
🚧 Files skipped from review as they are similar to previous changes (12)
- openmeter/billing/charges/flatfee/service/get.go
- openmeter/billing/charges/models/creditrealization/realizations.go
- openmeter/billing/charges/flatfee/service.go
- openmeter/billing/charges/service/handlers_test.go
- openmeter/ledger/chargeadapter/flatfee.go
- pkg/statelessx/actions.go
- openmeter/billing/charges/flatfee/handler.go
- openmeter/billing/charges/service/helpers.go
- openmeter/billing/charges/flatfee/service/triggers.go
- openmeter/billing/charges/service/patch.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go
- openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go
Overview
Add support for flat fee delete/shrink/expand (prorate). For now the shrink/expand is structured as a create/delete which is fine for the time being.
Notes for reviewer
Summary by CodeRabbit
New Features
Improvements
Documentation