Skip to content

feat: support usage-based invoice line deletes - #4656

Merged
turip merged 4 commits into
mainfrom
feat/delete-usagebased-support
Jul 7, 2026
Merged

turip merged 4 commits into
mainfrom
feat/delete-usagebased-support

Conversation

@turip

@turip turip commented Jul 7, 2026 •

Copy link
Copy Markdown
Member

Summary

  1. Delete support for usage-based standard invoice lines.
  2. Prevalidation support for mutable invoice-line API edits.

Summary by CodeRabbit

  • New Features
    • Usage-based charge processing now applies invoice updates as part of the end-to-end charge flow.
    • Added pre-validation for API-driven mutable invoice line edits, enabling safer handling of deletions.
  • Bug Fixes
    • Strengthened validation and correctness around mutable invoice line deletion, including progressive standard/gathering-line scenarios.
    • Improved invoice delete validation behavior to better distinguish standard vs. gathering invoices.
  • Tests
    • Expanded/refactored invoice deletion, line editing, and credit-then-invoice sync coverage, including progressive deletion and draft-invoice cases.

Greptile Summary

This PR adds support for deleting usage-based invoice lines through the billing API. The main changes are:

  • Usage-based standard invoice line delete handling.
  • Pre-validation for mutable invoice line edits.
  • Invoice updater wiring for usage-based charge cleanup.
  • Patch helpers for invoice line update and delete flows.
  • Tests for invoice deletion and credit-then-invoice sync paths.

Confidence Score: 5/5

This looks safe to merge.

  • No blocking issues found in the changed code.

Important Files Changed

Filename Overview
openmeter/billing/charges/usagebased/service/lineengine.go Adds usage-based API standard-line delete validation, charge patch handling, realization cleanup, and gathering-line patch application.
openmeter/billing/service/invoice.go Adds pre-trigger validation for API standard invoice deletion before invoice state is mutated.
openmeter/billing/service/invoiceupdate.go Adds shared validation and grouping for API invoice line edits and standard-line delete dispatch.
openmeter/billing/charges/invoiceupdater/patches.go Adds patch collection helpers for invoice bisection and singular patch validation.
openmeter/billing/invoice_validator.go Allows API standard invoice deletion while keeping the gathering-invoice guard for unsupported usage-based gathering-line deletes.

Reviews (4): Last reviewed commit: "fix: stabilize usage-based delete CI" | Re-trigger Greptile

Context used (3)

  • Context used - CLAUDE.md (source)
  • Context used - AGENTS.md (source)
  • Context used - api/spec/AGENTS.md (source)

@turip
turip requested a review from a team as a code owner July 7, 2026 11:25
@turip turip added release-note/feature Release note: Exciting New Features area/billing labels Jul 7, 2026
@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This 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.

Changes

Billing charges and invoice updater flow

Layer / File(s) Summary
Updater API and patch helpers
openmeter/billing/charges/invoiceupdater/*, openmeter/billing/charges/flatfee/service/creditheninvoice.go, openmeter/billing/charges/usagebased/service/creditheninvoice.go
Introduces Updater as an interface, adds Config validation, switches patch handling to Patches, and adds singular/partitioning helpers plus test utilities.
Updater wiring across charges services
app/common/charges.go, openmeter/billing/charges/service/*, openmeter/billing/charges/usagebased/service/*, openmeter/billing/charges/statemachine/machine.go, openmeter/billing/charges/meta/patch.go, openmeter/billing/charges/testutils/service.go, openmeter/ledger/customerbalance/testenv_test.go
Builds and injects the updater through service constructors, config validation, state machine patch storage, and shared test environments.
Mutable line edit and delete handling
openmeter/billing/charges/flatfee/service/*, openmeter/billing/charges/usagebased/service/lineengine.go, openmeter/billing/charges/creditpurchase/lineengine/engine.go, openmeter/billing/lineengine.go, openmeter/billing/lineengine/engine.go, openmeter/billing/invoiceline.go, test/billing/lineengine_test.go, openmeter/billing/service/lineengine_test.go
Refactors flat-fee patch targeting, adds API validation hooks, and implements usage-based mutable invoice-line delete handling with realization cleanup.
Invoice delete validation and tests
openmeter/billing/httpdriver/*, openmeter/billing/invoice_validator.go, openmeter/billing/errors.go, openmeter/billing/service/*, openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
Moves delete validation into the gathering-invoice path and updates the related validation, service orchestration, and sync coverage.

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
Loading

Possibly related PRs

Suggested labels: release-note/feature, area/billing

Suggested reviewers: tothandras, GAlexIHU

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the main change: adding support for usage-based invoice line deletes.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/delete-usagebased-support

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
openmeter/billing/charges/usagebased/service/lineengine.go (1)

423-454: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Wrap 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 and applyChargePatchForInvoiceLineEditViaAPI consistently wrap errors with fmt.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 win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between 50d7ae9 and 4c69d87.

📒 Files selected for processing (22)
  • app/common/charges.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/invoiceupdater/invoiceupdate.go
  • openmeter/billing/charges/invoiceupdater/patch.go
  • openmeter/billing/charges/invoiceupdater/patches.go
  • openmeter/billing/charges/invoiceupdater/testutils.go
  • openmeter/billing/charges/meta/patch.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/patch.go
  • openmeter/billing/charges/service/service.go
  • openmeter/billing/charges/statemachine/machine.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/service/service.go
  • openmeter/billing/errors.go
  • openmeter/billing/httpdriver/invoice.go
  • openmeter/billing/httpdriver/invoice_test.go
  • openmeter/billing/invoice_validator.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • openmeter/ledger/customerbalance/testenv_test.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
openmeter/billing/charges/flatfee/service/lineengine.go (1)

396-435: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate charge-fetch/settlement-mode logic between the two API validators.

validateManualUpdateLineViaAPI (Lines 397-421) and validateManualDeleteLineViaAPI (Lines 438-462) both: pull the charge ID off the line, fetch the flat-fee charge with ExpandRealizations, and reject non-CreditThenInvoice settlement modes with near-identical error messages. Worth extracting a small e.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

📥 Commits

Reviewing files that changed from the base of the PR and between ca2bf03 and 223647f.

📒 Files selected for processing (11)
  • openmeter/billing/charges/creditpurchase/lineengine/engine.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/invoiceline.go
  • openmeter/billing/lineengine.go
  • openmeter/billing/lineengine/engine.go
  • openmeter/billing/service/invoice.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/service/lineengine_test.go
  • openmeter/billing/testutils/lineengine.go
  • openmeter/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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Move errorEncoder() ahead of encodeValidationIssue(). Right now encodeValidationIssue() catches billing.ValidationError first and returns a plain 400, so the later handler never gets to add the structured validationErrors payload. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 223647f and 5880f69.

📒 Files selected for processing (3)
  • api/v3/handlers/billinginvoices/delete.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • test/billing/lineengine_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/billing/charges/usagebased/service/lineengine.go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants