Repository navigation
refactor: route invoice line edits through line engines - #4552
Conversation
|
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:
📝 WalkthroughWalkthroughThis PR wires a ChangesInvoice Line Engine Routing & ChangeSource Dispatch
Sequence Diagram(s)sequenceDiagram
participant HTTPDriver
participant BillingService
participant diffMutableInvoiceLines
participant engineRegistry
participant LineEngine
participant Adapter
HTTPDriver->>BillingService: UpdateStandardInvoice(input, ChangeSource=APIRequest)
BillingService->>BillingService: clone invoice, run EditFn
BillingService->>diffMutableInvoiceLines: before + after invoice lines
diffMutableInvoiceLines-->>BillingService: mutableInvoiceLineDiff (created/updated/deleted)
BillingService->>Adapter: UpsertInvoiceLines (preallocate line IDs)
Adapter-->>BillingService: preallocated lines
BillingService->>engineRegistry: GetCreateLineRouter → assign engine per created line
BillingService->>LineEngine: OnMutableInvoiceLinesEditedViaAPI (grouped by engine)
LineEngine-->>BillingService: OnMutableInvoiceUpdateResult
BillingService->>BillingService: merge results, mark ManuallyManagedLine
BillingService-->>HTTPDriver: updated invoice
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
🚥 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 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 |
Greptile SummaryThis PR routes mutable invoice line creates, updates, and deletes through the billing line-engine ownership model instead of letting the HTTP or service layer hard-code charge-management decisions. API edits and system updates now follow separate paths: API edits are diffed, grouped by line engine, and canonicalized via
Confidence Score: 4/5Safe to merge for the core billing path; the only notable behavioral delta is that charge-managed lines now explicitly reject API deletions, which the PR authors describe as intentional. The refactor is large but well-structured: a clean diff/apply split, thorough test coverage across unit and integration layers, and all production call-sites updated to supply the required ChangeSource. The previous shallow-copy mutation issue (ExistingLineOverride.Apply touching the original line's UsageBased allocation) is resolved by the Clone-first approach. The deliberate breaking change — API deletions of charge-managed lines now return ErrCannotUpdateChargeManagedLine where they previously succeeded silently — is the main risk area for any callers that currently depend on omitting charge-managed lines from the replacement list. The per-engine input struct drops the ChangeSource context after the service layer carefully threads it through, limiting future engine extensibility. openmeter/billing/service/invoiceupdate.go and openmeter/billing/stdinvoiceedit.go are the core of the change and the most important to validate end-to-end. Important Files Changed
|
There was a problem hiding this comment.
Actionable comments posted: 9
🧹 Nitpick comments (3)
openmeter/billing/service/invoiceupdate.go (1)
243-250: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick winUse the repo’s nillable validation wrapper.
Both new
Validate()methods collect errors, but returnerrors.Join(...)directly. Please wrap the joined error withmodels.NewNillableGenericValidationError(...)to keep validation behavior consistent.♻️ Suggested tweak
- return errors.Join(errs...) + return models.NewNillableGenericValidationError(errors.Join(errs...))As per coding guidelines, “For Go
Validate() errormethods, prefer collecting all validation issues intovar errs []errorand returningmodels.NewNillableGenericValidationError(errors.Join(errs...))instead of returning on the first invalid field”.Also applies to: 372-390
🤖 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/service/invoiceupdate.go` around lines 243 - 250, The Validate() method in applyAPIInvoiceLineEditsInput is returning errors.Join() directly instead of wrapping it with the repository's standard validation error wrapper. Modify the return statement to wrap the joined error with models.NewNillableGenericValidationError() to maintain consistency with the codebase's validation patterns. Apply the same fix to the other Validate() method mentioned in the comment (around lines 372-390).Source: Coding guidelines
openmeter/billing/stdinvoice.go (1)
840-853: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick winAlign
Validate()with the repo’s aggregated validation pattern.This method still returns plain errors directly; repo guidance asks
Validate() errormethods to aggregate and returnmodels.NewNillableGenericValidationError(errors.Join(errs...))for consistency.
As per coding guidelines: "For GoValidate() errormethods, prefer collecting all validation issues intovar errs []errorand returningmodels.NewNillableGenericValidationError(errors.Join(errs...))instead of returning on the first invalid field".🤖 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/stdinvoice.go` around lines 840 - 853, The UpdateStandardInvoiceInput.Validate() method currently returns errors immediately on the first validation failure instead of aggregating all issues together. Refactor this method to collect all validation errors into a var errs []error slice, appending each validation failure from Invoice.Validate(), the EditFn nil check, and ChangeSource.Validate() instead of returning early, then return models.NewNillableGenericValidationError(errors.Join(errs...)) at the end to provide all validation issues to the caller at once.Source: Coding guidelines
openmeter/billing/stdinvoiceedit.go (1)
32-83: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick winUnify
Validate()return behavior with the repo pattern.These new
Validate()methods mostly aggregate errors, but they still return rawerrors.Join(...)(and one method is fail-fast). Switching tomodels.NewNillableGenericValidationError(errors.Join(errs...))keeps behavior consistent with the project’s validation contract.
As per coding guidelines: "For GoValidate() errormethods, prefer collecting all validation issues intovar errs []errorand returningmodels.NewNillableGenericValidationError(errors.Join(errs...))instead of returning on the first invalid field".Also applies to: 102-122, 126-142, 165-197, 376-394
🤖 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/stdinvoiceedit.go` around lines 32 - 83, The ExistingLineOverride.Validate() method and other similar validation methods in the file return errors using raw errors.Join() instead of wrapping them with the project's standard validation pattern. Replace the return statement in the ExistingLineOverride.Validate() method that currently returns errors.Join(errs...) with return models.NewNillableGenericValidationError(errors.Join(errs...)) to maintain consistency with the project's validation contract. Apply the same fix to the other validation methods mentioned in the file at lines 102-122, 126-142, 165-197, and 376-394 to ensure all Validate() methods follow the unified error handling pattern.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/linerouter/linerouter_test.go`:
- Around line 18-91: The test table is missing coverage for critical error
cases: add a test case where the line parameter is nil to verify proper
nil-handling in the router, and add a test case where
New(Config{FeatureGate:nil}) is called to verify that initialization fails
appropriately when required configuration is missing. Both cases should set
expectedErr to the appropriate error message and verify the router API enforces
these guardrails as documented in the coding guidelines.
In `@openmeter/billing/charges/linerouter/linerouter.go`:
- Around line 19-25: In the Config.Validate() method, add a nil check for
c.FeatureGate before unconditionally calling its Validate() method to prevent
potential panics. Modify the method to aggregate validation errors in a slice
and return them using
models.NewNillableGenericValidationError(errors.Join(errs...)) pattern as per
coding guidelines. Collect any validation error from c.FeatureGate.Validate()
(if c.FeatureGate is not nil) into the errors slice before returning the
properly formatted validation error.
In `@openmeter/billing/httpdriver/invoiceline.go`:
- Around line 808-816: The guard condition in the split line group validation is
too restrictive because it only triggers when both the existing and new usage
discounts are non-nil, allowing API edits to add or remove usage discounts.
Remove the requirement that both rateCardParsed.Discounts.Usage and
existing.RateCardDiscounts.Usage must be non-nil from the outer if condition,
and instead only check if they are not equal using equal.PtrEqual directly. This
will ensure that any change to the usage discount (adding, removing, or
modifying) on a progressively billed line is blocked. Apply the same fix to the
corresponding merge path around line 885-893.
In `@openmeter/billing/lineengine/engine.go`:
- Around line 102-105: The error handling in the
snapshotManualStandardLineOverrideIfNeeded function call uses line.GetID() after
the function has already returned an error, but since the function returns nil
on failure, this could cause a panic. Capture the line ID before calling
snapshotManualStandardLineOverrideIfNeeded, then check if the error occurred
before attempting to use any properties of the returned line value. Update the
line variable only after confirming the function succeeded. Apply this fix to
both occurrences of snapshotManualStandardLineOverrideIfNeeded calls mentioned
in the review.
In `@openmeter/billing/service/invoiceupdate.go`:
- Around line 130-132: When override is nil and appending to diff.Unchanged in
the invoiceupdate logic, the code only preserves PersistedState but silently
drops mutable non-engine fields like annotations. This causes annotation-only
edits to be lost when applyAPIInvoiceLineEdits rebuilds results from Unchanged
and engine outputs. Modify the logic to explicitly carry through
non-engine-owned fields like annotations in the override parameter or preserve
the edited line item for allowed annotation changes, ensuring that non-engine
field edits are not dropped during the rebuild process. Apply this fix to both
occurrences of this pattern (around line 130-132 and the similar code block at
171-181).
- Around line 338-344: Add a nil check for each line in the loop over
engineResult.UpdatedLines before calling SetManagedBy on it. Check if the line
is not nil before calling the SetManagedBy method to prevent a panic on nil
pointers, allowing the validateLineEngineResult function to properly catch and
return validation errors for nil lines instead.
- Around line 441-471: The validateLineEngineResult function currently only
validates line counts and the managedBy property, but does not verify that the
returned line IDs match the expected line IDs. Add validation logic after the
existing checks to compare the expectedIDs and actualIDs lists and report an
error if they don't match exactly. This ensures the engine returns the correct
lines with the correct identifiers rather than silently replacing expected lines
with unrelated ones. The comparison should be added regardless of whether the
line counts match.
In `@openmeter/billing/stdinvoiceedit.go`:
- Around line 325-331: The code directly dereferences line.UsageBased when
applying Price and FeatureKey overrides without first checking if
line.UsageBased is nil, which will cause a panic if it is nil. Before the blocks
that assign line.UsageBased.Price and line.UsageBased.FeatureKey, add a guard
clause to check if line.UsageBased is not nil, and return an appropriate
validation error if it is nil to ensure proper error handling instead of a
panic.
- Around line 172-194: The validation logic in the lo.Map callbacks for both
i.Created and i.Deleted slices calls line.Validate() without first checking if
the line entry is nil, which will cause a panic if a nil entry exists in either
slice. Add a nil check before calling line.Validate() in both the lo.Map
callback for i.Created and the lo.Map callback for i.Deleted to ensure that nil
entries return a proper error message instead of panicking.
---
Nitpick comments:
In `@openmeter/billing/service/invoiceupdate.go`:
- Around line 243-250: The Validate() method in applyAPIInvoiceLineEditsInput is
returning errors.Join() directly instead of wrapping it with the repository's
standard validation error wrapper. Modify the return statement to wrap the
joined error with models.NewNillableGenericValidationError() to maintain
consistency with the codebase's validation patterns. Apply the same fix to the
other Validate() method mentioned in the comment (around lines 372-390).
In `@openmeter/billing/stdinvoice.go`:
- Around line 840-853: The UpdateStandardInvoiceInput.Validate() method
currently returns errors immediately on the first validation failure instead of
aggregating all issues together. Refactor this method to collect all validation
errors into a var errs []error slice, appending each validation failure from
Invoice.Validate(), the EditFn nil check, and ChangeSource.Validate() instead of
returning early, then return
models.NewNillableGenericValidationError(errors.Join(errs...)) at the end to
provide all validation issues to the caller at once.
In `@openmeter/billing/stdinvoiceedit.go`:
- Around line 32-83: The ExistingLineOverride.Validate() method and other
similar validation methods in the file return errors using raw errors.Join()
instead of wrapping them with the project's standard validation pattern. Replace
the return statement in the ExistingLineOverride.Validate() method that
currently returns errors.Join(errs...) with return
models.NewNillableGenericValidationError(errors.Join(errs...)) to maintain
consistency with the project's validation contract. Apply the same fix to the
other validation methods mentioned in the file at lines 102-122, 126-142,
165-197, and 376-394 to ensure all Validate() methods follow the unified error
handling pattern.
🪄 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: ec98e932-fd48-47e2-9571-f4847a849625
📒 Files selected for processing (46)
app/common/billing.goapp/common/charges.goopenmeter/billing/README.mdopenmeter/billing/charges/creditpurchase/lineengine/engine.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/invoiceupdater/invoiceupdate.goopenmeter/billing/charges/linerouter/linerouter.goopenmeter/billing/charges/linerouter/linerouter_test.goopenmeter/billing/charges/service/base_test.goopenmeter/billing/charges/testutils/linerouter.goopenmeter/billing/charges/testutils/service.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/derived.gen.goopenmeter/billing/discount.goopenmeter/billing/gatheringinvoice.goopenmeter/billing/httpdriver/invoice.goopenmeter/billing/httpdriver/invoiceline.goopenmeter/billing/invoice.goopenmeter/billing/invoiceline.goopenmeter/billing/lineengine.goopenmeter/billing/lineengine/engine.goopenmeter/billing/service.goopenmeter/billing/service/gatheringinvoice.goopenmeter/billing/service/invoice.goopenmeter/billing/service/invoice_test.goopenmeter/billing/service/invoiceupdate.goopenmeter/billing/service/invoiceupdate_test.goopenmeter/billing/service/lineengine.goopenmeter/billing/service/lineengine_test.goopenmeter/billing/service/stdinvoice.goopenmeter/billing/stdinvoice.goopenmeter/billing/stdinvoiceedit.goopenmeter/billing/stdinvoiceline.goopenmeter/billing/testutils/lineengine.goopenmeter/billing/worker/subscriptionsync/service/reconciler/invoiceupdater/invoiceupdate.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patch_test.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.goopenmeter/billing/worker/subscriptionsync/service/sync_test.goopenmeter/server/server_test.gopkg/equal/equal.gotest/app/stripe/invoice_test.gotest/billing/collection_test.gotest/billing/discount_test.gotest/billing/invoice_test.gotest/billing/lineengine_test.gotest/billing/tax_test.go
💤 Files with no reviewable changes (2)
- openmeter/billing/service/invoice_test.go
- openmeter/billing/service/invoice.go
| } | ||
|
|
||
| createdLines := make([]billing.GenericInvoiceLine, 0, len(input.Created)) | ||
| for _, line := range input.Created { |
There was a problem hiding this comment.
Just a question here, wouldn't be simpler/more bullet-proof to use lo.MapErr instead of manually managing the capacity of the slice?
e09d4a5 to
1aa2076
Compare
Summary
This PR routes mutable invoice line edits through the billing line-engine ownership model instead of letting the HTTP/service layer directly decide whether a line is manually managed or charge-managed.
The important domain change is that invoice line creates and updates now go through the owning line engine for API edits. The legacy billing engine can canonicalize manually edited invoice lines, while charge-backed engines can reject unsupported manual changes until charge-backed manual creation is implemented.
Business domain context
Mutable invoices can be edited from two different sources:
Those paths now stay separate. API edits are diffed once, routed by line engine, and the engines return the canonical created/updated lines to persist. System updates do not emit API edit callbacks; standard-line deletes still dispatch the deleted-by-system callback because charge realization cleanup depends on that notification.
The PR also introduces create-line routing so newly created invoice lines can be assigned to the correct engine before they are persisted. Charges get a production router and test router, while billing's default router falls back to the legacy invoice engine.
For future charge-backed manual creates, the flow is documented in
openmeter/billing/README.md: billing preallocates the standard invoice line ID, then the charge engine can create a manually managed charge and attach realization state to that existing line.Implementation notes
ChangeSourceon public update inputs to distinguish API vs system update behavior.DefaultCreateLineRouterin the billing package and charge-aware create routing in the charges module.Summary by CodeRabbit