Skip to content

fix(billing): [OM-434] delete empty invoices during issuing - #4849

Merged
turip merged 2 commits into
mainfrom
feat/om-434-delete-empty-invoices
Aug 5, 2026
Merged

turip merged 2 commits into
mainfrom
feat/om-434-delete-empty-invoices

Conversation

@turip

@turip turip commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

Summary

When issuing begins, billing now deletes a standard invoice if it has no non-deleted lines. The deletion is recorded as a system change and synchronized to the configured invoicing app instead of finalizing the invoice.

This is stacked on #4843, where custom-currency overage lines can be deleted after credits fully cover the charge or the resulting fiat amount rounds to zero. Those invoices now complete their lifecycle as deleted rather than remaining as empty drafts.

Behavioral changes

  • An invoice with zero non-deleted lines transitions into the deletion lifecycle when issuing starts.
  • Billing calls the invoicing app's delete operation and skips finalization, charge booking, and payment processing.
  • If app deletion fails, the invoice enters delete.failed and can be retried without replacing the original deletion timestamp.
  • The decision is based on line presence, not invoice totals. A zero-total invoice with an active line still follows the normal issuing lifecycle.
  • Invoice action details report deleted as the approval result when the expanded invoice is empty.

Validation

  • Added generic billing lifecycle coverage for successful empty-invoice deletion, app deletion failure and retry, and zero-total invoices with active lines.
  • Extended fix(billing): [OM-434] delete empty custom-currency overage lines #4843's flat-fee and usage-based lifecycle cases to assert persisted invoice status, system deletion metadata, invoicing app deletion, and absence of finalization.
  • Covered both progressive and non-progressive usage-based lifecycles.
  • Ran the targeted billing and charge-service test suites with PostgreSQL.
  • Ran make lint-go-fast in the repository's Nix development shell.

Jira: OM-434

Summary by CodeRabbit

  • Bug Fixes
    • Empty invoices are now automatically deleted instead of issued.
    • Deletion is synchronized with the invoicing system, while charge booking and payment are skipped.
    • Failed invoice deletions can be retried safely.
    • Invoices with active zero-value lines continue through the normal issuing process.
    • Invoice status, deletion timestamps, and deletion details are preserved consistently.
    • Deleted invoice lines are handled consistently when viewing invoice details.

Greptile Summary

This PR routes standard invoices with no active lines through the existing deletion lifecycle when issuing begins, preserving normal issuing for zero-total invoices that still contain an active line.

  • Dynamically selects deletion or issuing after draft.ready_to_issue.
  • Records system deletion metadata before synchronizing deletion to the invoicing app.
  • Adds successful deletion, failed synchronization, retry, and zero-total lifecycle coverage.
  • Extends the sandbox mock with finalize and delete call counts.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
openmeter/billing/service/stdinvoicestate.go Adds line-presence-based routing from ready-to-issue into the existing deletion lifecycle and prepares system deletion metadata before app synchronization.
openmeter/app/sandbox/mock.go Replaces Boolean finalize/delete tracking with call counters used to verify lifecycle behavior.
test/billing/invoice_test.go Covers empty-invoice deletion, failed app deletion and retry, timestamp preservation, and zero-total invoices with active lines.
openmeter/billing/charges/service/invoicable_test.go Updates flat-fee lifecycle expectations for invoices whose only line is deleted.
openmeter/billing/charges/service/usagebased_test.go Updates usage-based lifecycle expectations and verifies deletion synchronization without finalization.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  Ready["draft.ready_to_issue"] --> Check{"Any non-deleted lines?"}
  Check -->|Yes| SyncIssue["issuing.syncing"]
  SyncIssue --> Finalize["Finalize through invoicing app"]
  Check -->|No| Prepare["Prepare system deletion"]
  Prepare --> SyncDelete["delete.syncing"]
  SyncDelete --> AppDelete["Delete through invoicing app"]
  AppDelete -->|Success| Deleted["deleted"]
  AppDelete -->|Failure| DeleteFailed["delete.failed"]
  DeleteFailed -->|Retry| SyncDelete
Loading

Reviews (3): Last reviewed commit: "chore(billing): address invoice deletion..." | Re-trigger Greptile

Context used:

@turip
turip requested a review from a team as a code owner August 4, 2026 09:17
@turip turip added release-note/feature Release note: Exciting New Features area/billing labels Aug 4, 2026
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Invoices with no non-deleted lines now enter system deletion instead of issuance. The change updates state handling, sandbox call tracking, documentation, and standard and custom-currency lifecycle tests. Active zero-total invoices still follow the issuing path.

Changes

Empty invoice deletion

Layer / File(s) Summary
Empty invoice state transitions
openmeter/billing/service/stdinvoicestate.go, openmeter/billing/README.md
Empty invoices prepare system deletion and synchronize deletion. Invoices with active lines continue to issuance.
Sandbox deletion call tracking
openmeter/app/sandbox/mock.go
The mock tracks finalization and deletion call counts and exposes count accessors.
Invoice lifecycle coverage
test/billing/invoice_test.go, openmeter/billing/charges/service/invoicable_test.go, openmeter/billing/charges/service/usagebased_test.go
Tests cover deletion, retryable deletion failures, metadata, deleted-line expansion, and active zero-total invoice issuance.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Approval
  participant InvoiceState
  participant SandboxApp
  Approval->>InvoiceState: Approve draft invoice
  InvoiceState->>InvoiceState: Check for non-deleted lines
  InvoiceState->>InvoiceState: Prepare system deletion
  InvoiceState->>SandboxApp: Synchronize invoice deletion
Loading

Possibly related PRs

Suggested reviewers: galexihu, tothandras

🚥 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 clearly and concisely describes the main change: deleting empty invoices when issuing begins.
✨ 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/om-434-delete-empty-invoices

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: 2

🧹 Nitpick comments (1)
test/billing/invoice_test.go (1)

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

Use Require().Equal for the zero-total precondition.

Replace s.Zero(...) with s.Require().Equal(float64(0), ...). This keeps the decimal assertion in the required form and stops the lifecycle test when its setup is invalid.

Proposed change
-	s.Zero(invoice.Totals.Total.InexactFloat64())
+	s.Require().Equal(float64(0), invoice.Totals.Total.InexactFloat64())

As per coding guidelines, “When precision permits, compare alpacadecimal.Decimal through InexactFloat64() with require.Equal; inline one-off expected balances.”

🤖 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 `@test/billing/invoice_test.go` at line 1547, Replace the s.Zero() assertion on
invoice.Totals.Total.InexactFloat64() with s.Require().Equal(float64(0),
invoice.Totals.Total.InexactFloat64()) to use the required form for the
precondition check. This ensures the test lifecycle stops when its setup is
invalid and aligns with the coding guideline for comparing decimal values
through InexactFloat64() with require.Equal.

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/README.md`:
- Around line 96-97: In the documentation describing the invoice lifecycle
condition, replace the term "visible line" with "non-deleted line" to accurately
reflect the actual criterion used. A deleted line can be visible when
deleted-line expansion is requested, so the decision criterion is whether a line
is non-deleted, not whether it appears visually. Update the sentence to state
that a non-deleted line with a zero total follows the normal issuing lifecycle,
while maintaining the explanation about deleted lines entering deletion.

In `@openmeter/billing/service/stdinvoicestate.go`:
- Around line 904-906: The TODO comment around line 46 states that invoice
deletion is not implemented, but the diff now shows that deleteInvoice is being
called to prepare a system deletion for empty invoices, making this TODO stale.
Either remove the TODO entirely if invoice deletion is now fully supported, or
update it to only document specific deletion behaviors that remain unsupported,
excluding the empty invoice deletion scenario that is now prepared via the
deleteInvoice call with ChangeSourceSystem.

---

Nitpick comments:
In `@test/billing/invoice_test.go`:
- Line 1547: Replace the s.Zero() assertion on
invoice.Totals.Total.InexactFloat64() with s.Require().Equal(float64(0),
invoice.Totals.Total.InexactFloat64()) to use the required form for the
precondition check. This ensures the test lifecycle stops when its setup is
invalid and aligns with the coding guideline for comparing decimal values
through InexactFloat64() with require.Equal.
🪄 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 Plus

Run ID: 5bdd9006-11a9-4178-9e35-86ade37d1e7b

📥 Commits

Reviewing files that changed from the base of the PR and between 4824648 and 6f93cb4.

📒 Files selected for processing (6)
  • openmeter/app/sandbox/mock.go
  • openmeter/billing/README.md
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/service/usagebased_test.go
  • openmeter/billing/service/stdinvoicestate.go
  • test/billing/invoice_test.go

Comment thread openmeter/billing/README.md Resolved
@turip
turip force-pushed the fix/om-434-delete-empty-custom-currency-overage-lines branch from 4824648 to 2359e94 Compare August 4, 2026 15:58
Base automatically changed from fix/om-434-delete-empty-custom-currency-overage-lines to main August 5, 2026 08:48
@turip
turip force-pushed the feat/om-434-delete-empty-invoices branch from 2e58a58 to ad95170 Compare August 5, 2026 08:51
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@turip
turip merged commit b9d9c31 into main Aug 5, 2026
27 checks passed
@turip
turip deleted the feat/om-434-delete-empty-invoices branch August 5, 2026 09:34
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