Repository navigation
feat: support usage-based invoice line deletes - #4656
Conversation
📝 WalkthroughWalkthroughThis PR refactors invoice updater construction and patch handling, threads the updater through billing service wiring, adds mutable invoice line API validation and delete processing, and narrows invoice delete validation to gathering invoices with updated test coverage. ChangesBilling charges and invoice updater flow
Estimated code review effort: 4 (Complex) | ~75 minutes Sequence Diagram(s)sequenceDiagram
participant API
participant InvoiceService
participant LineEngine
participant StateMachine
participant InvoiceUpdater
API->>InvoiceService: delete invoice / edit mutable lines
InvoiceService->>LineEngine: ValidateMutableInvoiceLineEditViaAPI()
LineEngine-->>InvoiceService: validation result
InvoiceService->>StateMachine: apply charge patch
StateMachine-->>InvoiceService: DrainInvoicePatches()
InvoiceService->>InvoiceUpdater: ApplyPatches(customerID, patches)
InvoiceUpdater-->>InvoiceService: patch result
InvoiceService-->>API: deletion outcome
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 |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
openmeter/billing/charges/usagebased/service/lineengine.go (1)
423-454: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winWrap errors with line/charge context in the new delete path.
Lines 423-454 return bare
err(return err) for several failure points (standard invoice lookup, patch bisection, singular-patch/target checks, realization deletion), while the rest of the function andapplyChargePatchForInvoiceLineEditViaAPIconsistently wrap errors withfmt.Errorf("...: %w", ...)including the line/charge ID. Bare returns here will make production debugging harder since you lose which line/charge triggered the failure.♻️ Suggested fix
standardInvoice, err := invoice.AsInvoice().AsStandardInvoice() if err != nil { - return err + return fmt.Errorf("usage based line[%s]: getting standard invoice: %w", line.GetID(), err) } stdInvoicePatches, rest, err := patches.BisectByStandardInvoiceID(standardInvoice.ID) if err != nil { - return err + return fmt.Errorf("usage based line[%s]: bisecting invoice patches: %w", line.GetID(), err) } if len(stdInvoicePatches) != 1 { return fmt.Errorf("received unexpected number of standard invoice patches for line[%s]: count=%d %v", line.GetID(), len(stdInvoicePatches), stdInvoicePatches) } stdInvoicePatch, err := stdInvoicePatches.RequireSingularStandardInvoiceLineDeletePatch() if err != nil { - return err + return fmt.Errorf("usage based line[%s]: requiring singular delete patch: %w", line.GetID(), err) } if err := stdInvoicePatch.RequireTarget(line); err != nil { - return err + return fmt.Errorf("usage based line[%s]: validating delete patch target: %w", line.GetID(), err) } standardLine, err := line.AsInvoiceLine().AsStandardLine() if err != nil { - return err + return fmt.Errorf("usage based line[%s]: getting standard line: %w", line.GetID(), err) } charge, err = e.deleteMutableStandardLineRealization(ctx, charge, standardInvoice, &standardLine) if err != nil { - return err + return fmt.Errorf("usage based line[%s]: deleting realization: %w", line.GetID(), 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/lineengine.go` around lines 423 - 454, The new delete path in deleteMutableStandardLineRealization should not return bare errors, since that drops the line/charge context needed for debugging. Update each failure point around standardInvoice.AsInvoice().AsStandardInvoice, patches.BisectByStandardInvoiceID, RequireSingularStandardInvoiceLineDeletePatch, RequireTarget, line.AsInvoiceLine().AsStandardLine, and e.deleteMutableStandardLineRealization to wrap the underlying error with fmt.Errorf including the current line.GetID() and charge identifiers, matching the existing style used elsewhere in applyChargePatchForInvoiceLineEditViaAPI.openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go (1)
6780-6869: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a given/when/then comment to the subtest body.
This subtest sets up a fair bit (subscription, sync, two draft invoices) but doesn't have its own given/when/then intent comment, unlike the other top-level tests in this file. A short blurb here would help future readers quickly grok what state this subtest builds.
As per coding guidelines, "For service and lifecycle subtests, start each non-trivial subtest body with concise intent comments in given/when/then form."
🤖 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 6780 - 6869, The “create progressive draft invoice” subtest in sync_credittheninvoice_test.go is non-trivial and currently lacks the required given/when/then intent comment at the start of the body. Add a short three-part comment near the beginning of this subtest to summarize the setup, the sync/action, and the invoice assertions, following the same style used by the other top-level tests in this file. Refer to the subtest registered by s.Run("create progressive draft invoice", ...) so it’s easy to locate.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/invoiceupdater/patch.go`:
- Around line 29-40: PatchLineDelete.RequireTarget currently validates only the
line ID, but it should also restore the InvoiceID consistency check against
line.GetInvoiceID() to match the previous behavior and
PatchLineUpdate.RequireTarget. Update the validation in
PatchLineDelete.RequireTarget so it rejects deletes when p.InvoiceID does not
match the target line’s invoice ID, alongside the existing nil and line ID
checks.
---
Nitpick comments:
In `@openmeter/billing/charges/usagebased/service/lineengine.go`:
- Around line 423-454: The new delete path in
deleteMutableStandardLineRealization should not return bare errors, since that
drops the line/charge context needed for debugging. Update each failure point
around standardInvoice.AsInvoice().AsStandardInvoice,
patches.BisectByStandardInvoiceID,
RequireSingularStandardInvoiceLineDeletePatch, RequireTarget,
line.AsInvoiceLine().AsStandardLine, and e.deleteMutableStandardLineRealization
to wrap the underlying error with fmt.Errorf including the current line.GetID()
and charge identifiers, matching the existing style used elsewhere in
applyChargePatchForInvoiceLineEditViaAPI.
In
`@openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go`:
- Around line 6780-6869: The “create progressive draft invoice” subtest in
sync_credittheninvoice_test.go is non-trivial and currently lacks the required
given/when/then intent comment at the start of the body. Add a short three-part
comment near the beginning of this subtest to summarize the setup, the
sync/action, and the invoice assertions, following the same style used by the
other top-level tests in this file. Refer to the subtest registered by
s.Run("create progressive draft invoice", ...) so it’s easy to locate.
🪄 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: 47ae0007-9785-4d08-b771-5eb514229fb8
📒 Files selected for processing (22)
app/common/charges.goopenmeter/billing/charges/flatfee/service/creditheninvoice.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/invoiceupdater/invoiceupdate.goopenmeter/billing/charges/invoiceupdater/patch.goopenmeter/billing/charges/invoiceupdater/patches.goopenmeter/billing/charges/invoiceupdater/testutils.goopenmeter/billing/charges/meta/patch.goopenmeter/billing/charges/service/base_test.goopenmeter/billing/charges/service/patch.goopenmeter/billing/charges/service/service.goopenmeter/billing/charges/statemachine/machine.goopenmeter/billing/charges/testutils/service.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/charges/usagebased/service/service.goopenmeter/billing/errors.goopenmeter/billing/httpdriver/invoice.goopenmeter/billing/httpdriver/invoice_test.goopenmeter/billing/invoice_validator.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.goopenmeter/ledger/customerbalance/testenv_test.go
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openmeter/billing/charges/flatfee/service/lineengine.go (1)
396-435: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate charge-fetch/settlement-mode logic between the two API validators.
validateManualUpdateLineViaAPI(Lines 397-421) andvalidateManualDeleteLineViaAPI(Lines 438-462) both: pull the charge ID off the line, fetch the flat-fee charge withExpandRealizations, and reject non-CreditThenInvoicesettlement modes with near-identical error messages. Worth extracting a smalle.getFlatFeeChargeForAPIEdit(ctx, namespace, chargeID, lineID) (flatfee.Charge, error)helper to keep this DRY and avoid the two copies drifting apart later.♻️ Suggested helper extraction
+func (e *LineEngine) getFlatFeeChargeForAPIEdit(ctx context.Context, namespace string, chargeID *string, lineID string, op string) (flatfee.Charge, error) { + if chargeID == nil || *chargeID == "" { + return flatfee.Charge{}, fmt.Errorf("flat fee line[%s]: charge id is required", lineID) + } + + charge, err := e.service.GetByID(ctx, flatfee.GetByIDInput{ + ChargeID: meta.ChargeID{Namespace: namespace, ID: *chargeID}, + Expands: meta.Expands{meta.ExpandRealizations}, + }) + if err != nil { + return flatfee.Charge{}, fmt.Errorf("getting flat fee charge for %s line[%s]: %w", op, lineID, err) + } + + if charge.Intent.GetSettlementMode() != productcatalog.CreditThenInvoiceSettlementMode { + return flatfee.Charge{}, fmt.Errorf("flat fee line[%s]: unsupported settlement mode for API %s: %s", lineID, op, charge.Intent.GetSettlementMode()) + } + + return charge, nil +}Also applies to: 437-465
🤖 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/lineengine.go` around lines 396 - 435, Extract the duplicated charge lookup and settlement-mode check from validateManualUpdateLineViaAPI and validateManualDeleteLineViaAPI into a shared helper (for example, a LineEngine method like getFlatFeeChargeForAPIEdit). Have both validators call that helper to fetch the flat-fee charge with ExpandRealizations, validate the charge ID/namespace, and enforce CreditThenInvoiceSettlementMode, while keeping each validator focused on its own line-edit rules and error wrapping.
🤖 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/flatfee/service/lineengine.go`:
- Around line 396-435: Extract the duplicated charge lookup and settlement-mode
check from validateManualUpdateLineViaAPI and validateManualDeleteLineViaAPI
into a shared helper (for example, a LineEngine method like
getFlatFeeChargeForAPIEdit). Have both validators call that helper to fetch the
flat-fee charge with ExpandRealizations, validate the charge ID/namespace, and
enforce CreditThenInvoiceSettlementMode, while keeping each validator focused on
its own line-edit rules and error wrapping.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a5f36c44-5c0f-4ee7-82d5-307a95495df7
📒 Files selected for processing (11)
openmeter/billing/charges/creditpurchase/lineengine/engine.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/invoiceline.goopenmeter/billing/lineengine.goopenmeter/billing/lineengine/engine.goopenmeter/billing/service/invoice.goopenmeter/billing/service/invoiceupdate.goopenmeter/billing/service/lineengine_test.goopenmeter/billing/testutils/lineengine.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
- openmeter/billing/charges/usagebased/service/lineengine.go
- openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
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)
api/v3/handlers/billinginvoices/delete.go (1)
86-92: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winMove
errorEncoder()ahead ofencodeValidationIssue(). Right nowencodeValidationIssue()catchesbilling.ValidationErrorfirst and returns a plain 400, so the later handler never gets to add the structuredvalidationErrorspayload.api/v3/handlers/billinginvoices/delete.go:86-92🤖 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 `@api/v3/handlers/billinginvoices/delete.go` around lines 86 - 92, The delete-invoice handler is registering error encoders in the wrong order, causing billing.ValidationError to be handled by encodeValidationIssue() before errorEncoder() can add the structured validationErrors payload. Update the httptransport.AppendOptions call in deleteInvoice to place errorEncoder() before encodeValidationIssue(), keeping the existing GenericErrorEncoder first.
🤖 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 `@api/v3/handlers/billinginvoices/delete.go`:
- Around line 86-92: The delete-invoice handler is registering error encoders in
the wrong order, causing billing.ValidationError to be handled by
encodeValidationIssue() before errorEncoder() can add the structured
validationErrors payload. Update the httptransport.AppendOptions call in
deleteInvoice to place errorEncoder() before encodeValidationIssue(), keeping
the existing GenericErrorEncoder first.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 1534d4cc-7728-4714-86c6-934d476f6131
📒 Files selected for processing (3)
api/v3/handlers/billinginvoices/delete.goopenmeter/billing/charges/usagebased/service/lineengine.gotest/billing/lineengine_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- openmeter/billing/charges/usagebased/service/lineengine.go
Summary
Summary by CodeRabbit
Greptile Summary
This PR adds support for deleting usage-based invoice lines through the billing API. The main changes are:
Confidence Score: 5/5
This looks safe to merge.
Important Files Changed
Reviews (4): Last reviewed commit: "fix: stabilize usage-based delete CI" | Re-trigger Greptile
Context used (3)