Repository navigation
fix(billing): support invoice delete source handling - #4554
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (10)
📒 Files selected for processing (17)
📝 WalkthroughWalkthroughAdds a ChangesInvoice Deletion Source
Sequence Diagram(s)sequenceDiagram
participant APIClient
participant HTTPDriver
participant BillingService
participant InvoiceStateMachine
participant BillingAdapter
APIClient->>HTTPDriver: DELETE /invoice/{id}
HTTPDriver->>BillingService: DeleteInvoice(DeleteInvoiceInput{Invoice, DeletionSource: APIRequest})
BillingService->>BillingService: ExecuteTriggerWithArgs(DeleteInvoiceTriggerInput{Source: APIRequest})
BillingService->>InvoiceStateMachine: FireAndActivate(TriggerDelete, args...)
InvoiceStateMachine->>InvoiceStateMachine: deleteInvoice — record DeletionSource, skip system dispatch
InvoiceStateMachine->>BillingAdapter: UpdateStandardInvoice (sets deletion_source)
BillingAdapter-->>InvoiceStateMachine: updated invoice
InvoiceStateMachine-->>BillingService: deleted
BillingService-->>HTTPDriver: success
HTTPDriver-->>APIClient: 204 No Content
sequenceDiagram
participant ChargesUpdater
participant BillingService
participant InvoiceStateMachine
participant LineEngine
ChargesUpdater->>BillingService: DeleteInvoice(DeleteInvoiceInput{Invoice, DeletionSource: System})
BillingService->>InvoiceStateMachine: FireAndActivate(TriggerDelete, DeleteInvoiceTriggerInput{Source: System})
InvoiceStateMachine->>InvoiceStateMachine: deleteInvoice — ChangeSourceSystem branch
InvoiceStateMachine->>LineEngine: dispatchSystemStandardLineDeletions(non-deleted lines only)
LineEngine-->>InvoiceStateMachine: ok
InvoiceStateMachine->>BillingService: invoice marked deleted
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 |
e09d4a5 to
1aa2076
Compare
61b8488 to
d5b64d9
Compare
Greptile SummaryThis PR adds an explicit
Confidence Score: 4/5Safe to merge; the delete-lifecycle rerouting is logically sound, migration is backward-compatible, and both the unit and integration tests cover the key branching paths. The core logic — typing the delete source through the trigger, guarding against double-dispatch via DeletedAt, and rerouting DeleteFailed through TriggerDelete — is correct and well-tested. The two findings are a slightly misleading comment about the dispatch-failure retry path and the Ent-generated validator using string literals instead of the billing constants; neither affects runtime behavior. No migration rollback issues, no missing validations. openmeter/billing/service/stdinvoicestate.go (deleteInvoice guard comment) and openmeter/ent/db/billinginvoice/billinginvoice.go (DeletionSourceValidator literals) are the only files worth a second glance, both for documentation/maintainability rather than correctness. Important Files Changed
|
| // Each delete attempt owns its validation result. This keeps a retry from | ||
| // being poisoned by a prior delete-sync failure. | ||
| m.Invoice.ValidationIssues = nil | ||
|
|
||
| // DeletedAt is persisted before delete syncing starts. If syncing later fails | ||
| // and delete is retried, the source-specific line-engine cleanup has already | ||
| // run and must not be dispatched again. | ||
| if m.Invoice.DeletedAt != nil { | ||
| return nil | ||
| } |
There was a problem hiding this comment.
Guard comment overstates coverage for dispatch-failure retries
The comment says "the source-specific line-engine cleanup has already run and must not be dispatched again," but that invariant only holds when DeletedAt != nil. If dispatchSystemStandardLineDeletions returns an error, DeletedAt is never set (the assignment is two lines below the error return), so the guard will not fire on the next retry and the dispatch will run a second time. The behavior on that path is actually correct — retrying a failed dispatch is desirable — but the comment implies the guard covers all retry scenarios when it only covers the sync-failure-after-successful-dispatch path. Consider tightening the comment to reflect that DeletedAt == nil means the first dispatch attempt did not complete, so a re-dispatch on retry is intentional.
Why
Charge-managed invoices need deletion to behave differently depending on who initiated the delete. A public API invoice delete should only delete the invoice, while a system delete produced by subscription or charge reconciliation must also notify line engines so charge-backed realization state and ledger cleanup can follow the same path as standard-line deletion.
This matters for empty charge-backed standard invoices: the invoice should remain inspectable with its historical lines, but charge engines still need a system deletion signal for every currently active standard line.
What Changed
ChangeSourcetoDeleteInvoiceInputand persists it on standard invoices for audit.DeleteFailedas retryable by callingDeleteInvoiceagain, so delete retry remains a delete action rather than a genericRetryInvoiceaction.OnMutableStandardLinesDeletedBySystem(...)only for non-deleted standard lines when the delete source issystem.api_requestand charge/subscription empty-invoice deletes assystem.billing_invoices.deletion_sourcemigration and generated Ent mapping.Validation
direnv exec . make migrate-check-validatedirenv exec . go vet -tags=dynamic ./openmeter/billing/...direnv exec . go test -tags=dynamic ./openmeter/billing/service -run 'Test(DeleteInvoice|DispatchSystemStandardLineDeletions)'direnv exec . go test -tags=dynamic -run '^$' ./test/billingStacked on #4552.
Summary by CodeRabbit
New Features
Bug Fixes
Documentation