Skip to content

refactor: route invoice line edits through line engines - #4552

Merged
turip merged 10 commits into
mainfrom
feat/invoice-line-engine-api-edits
Jun 23, 2026
Merged

turip merged 10 commits into
mainfrom
feat/invoice-line-engine-api-edits

Conversation

@turip

@turip turip commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

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:

  • API requests, where a user is intentionally overriding invoice lines.
  • System updates, where billing, subscription sync, or charges are reconciling their own state.

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

  • Adds generic invoice line diffing for standard and gathering invoice edits.
  • Adds API edit line-engine callback inputs/results and enforces result count matching.
  • Moves manual line canonicalization into line engines.
  • Keeps ChangeSource on public update inputs to distinguish API vs system update behavior.
  • Adds DefaultCreateLineRouter in the billing package and charge-aware create routing in the charges module.
  • Updates HTTP line replacement so charge-managed override decisions are no longer made in the handler.
  • Preserves system-originated delete handling for charge-backed standard lines.

Summary by CodeRabbit

  • New Features
    • Added API-driven mutable invoice line edits (create/update/delete) with engine-specific handling and consistent created/updated/deleted results.
    • Introduced a configurable “create line” router for charges, including credits-based routing with feature-gate control and flat-vs-usage engine selection.
    • Added change-source tracking so API requests vs system updates follow different edit/dispatch behavior.
  • Bug Fixes
    • Improved invoice edit diffing/persistence behavior for gathering and standard invoices.
    • Added precise equality support for discounts to improve change detection.
  • Documentation
    • Added “Lineengine Charges Integration Plan” and expanded mutable-edit guidance.
  • Tests
    • Expanded coverage for routing selection, validation/error paths, and invoice edit flows.

@coderabbitai

coderabbitai Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR wires a ChangeSource discriminator (system vs api_request) into all invoice update paths, introduces a CreateLineRouter abstraction for routing new invoice lines to the right charge engine, adds OnMutableInvoiceLinesEditedViaAPI across all line engines, and implements a full invoice line diff-and-apply pipeline in the billing service. All existing callers are updated to supply the new ChangeSource field.

Changes

Invoice Line Engine Routing & ChangeSource Dispatch

Layer / File(s) Summary
Core contracts: ChangeSource, LineEngine interface, GenericInvoice/Line interfaces
openmeter/billing/lineengine.go, openmeter/billing/service.go, openmeter/billing/invoice.go, openmeter/billing/invoiceline.go, openmeter/billing/discount.go, openmeter/billing/derived.gen.go, pkg/equal/equal.go
Adds ChangeSource type/constants with validation, renames OnMutableStandardLinesDeleted to OnMutableStandardLinesDeletedBySystem, adds OnMutableInvoiceLinesEditedViaAPI and CreateLineRouter/DefaultCreateLineRouter to the LineEngine contract, expands GenericInvoice and GenericInvoiceLineReader interfaces, and adds Discounts.Equal and ComparablePtrEqual helpers.
Invoice/line data model: ChangeSource fields, accessors, and stdinvoiceedit types
openmeter/billing/stdinvoice.go, openmeter/billing/gatheringinvoice.go, openmeter/billing/stdinvoiceline.go, openmeter/billing/stdinvoiceedit.go, openmeter/billing/stdinvoiceline_test.go
Adds ChangeSource to UpdateStandardInvoiceInput/UpdateGatheringInvoiceInput with validation; adds GetType/CloneAsGenericInvoice/UnsetLines to both invoice types; adds accessor/mutator methods on line base types; introduces ExistingLineOverride, InvoiceLineOverride(s), OnMutableInvoiceUpdateInput/Result, and their Apply logic with immutability test.
CreateLineRouter: charges-linerouter implementation and tests
openmeter/billing/charges/linerouter/linerouter.go, openmeter/billing/charges/linerouter/linerouter_test.go, openmeter/billing/charges/testutils/linerouter.go, openmeter/billing/charges/testutils/service.go
Implements Router.GetLineEngineForCreateLine with credits/feature-gate checks and price-type-based engine selection. Includes a full table-driven test suite and test utility routers for the charges test suites.
Service engine registry: RegisterCreateLineRouter
openmeter/billing/service/lineengine.go, openmeter/billing/service/lineengine_test.go
Adds createLineRouter field, RegisterCreateLineRouter/GetCreateLineRouter to engineRegistry; exposes Service.RegisterCreateLineRouter; removes Service.OnMutableStandardLinesDeleted. Updates tests for the new dispatch path and registration constraints.
LineEngine implementations: OnMutableInvoiceLinesEditedViaAPI and rename
openmeter/billing/charges/creditpurchase/lineengine/engine.go, openmeter/billing/charges/flatfee/service/lineengine.go, openmeter/billing/charges/usagebased/service/lineengine.go, openmeter/billing/lineengine/engine.go, openmeter/billing/testutils/lineengine.go
Implements OnMutableInvoiceLinesEditedViaAPI (rejects non-empty edits with ErrCannotUpdateChargeManagedLine) and renames OnMutableStandardLinesDeleted to OnMutableStandardLinesDeletedBySystem across all engines. The base lineengine also snapshots manual standard line quantity overrides for API-created/updated lines.
Invoice line diff and applyAPIInvoiceLineEdits pipeline
openmeter/billing/service/invoiceupdate.go, openmeter/billing/service/invoiceupdate_test.go, openmeter/billing/service/invoice.go, openmeter/billing/charges/invoiceupdater/invoiceupdate.go
New invoiceupdate.go adds diffMutableInvoiceLines, diffInvoiceLine, applyAPIInvoiceLineEdits (clone, preallocate IDs, dispatch per engine, validate, merge), and dispatchSystemStandardLineDeletions. Removes old collectNewlyDeletedStandardLines and its invocation from executeTriggerOnInvoice. Comprehensive test coverage for diffing, applying, and preallocation.
UpdateStandardInvoice/UpdateGatheringInvoice: ChangeSource-based dispatch
openmeter/billing/service/stdinvoice.go, openmeter/billing/service/gatheringinvoice.go, openmeter/billing/httpdriver/invoice.go, openmeter/billing/worker/subscriptionsync/service/reconciler/invoiceupdater/invoiceupdate.go
Wires the diff-and-apply pipeline into both update paths, branching on ChangeSource. HTTP driver passes ChangeSourceAPIRequest; charges and subscription sync reconcilers pass ChangeSourceSystem.
HTTP driver merge simplification
openmeter/billing/httpdriver/invoiceline.go
Removes change-detection/ManagedBy enforcement from mergeStandardLineFromInvoiceLineReplaceUpdate and mergeGatheringLineFromInvoiceLineReplaceUpdate, and drops SnapshotLineQuantity from the merge loop (now handled by the line engine pipeline).
App wiring: newChargesRegistry with CreateLineRouter
app/common/billing.go, app/common/charges.go, openmeter/server/server_test.go
Passes creditsConfig and featureGate into newChargesRegistry, creates and registers a createLineRouter in the charges registry setup, and adds RegisterCreateLineRouter to NoopBillingService.
Charges service test suite wiring
openmeter/billing/charges/service/base_test.go
Wires a createLineRouter with credits enabled into the charges base test suite SetupSuite.
Integration and sync test ChangeSource propagation
openmeter/billing/worker/subscriptionsync/service/sync_test.go, openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go, openmeter/billing/worker/subscriptionsync/service/reconciler/patch_test.go, test/billing/invoice_test.go, test/billing/collection_test.go, test/billing/discount_test.go, test/billing/tax_test.go, test/billing/lineengine_test.go, test/app/stripe/invoice_test.go
Adds ChangeSource: billing.ChangeSourceAPIRequest or ChangeSourceSystem to all Update*Invoice call sites; removes manual ManagedBy assignments from edit callbacks where the system now handles it.
README and skills docs
openmeter/billing/README.md, .agents/skills/billing/SKILL.md, .agents/skills/charges/SKILL.md
Adds a "Lineengine Charges Integration Plan" section describing the create/attach/realize flow, transaction scope, and callback identity invariants. Updates charges and billing skill docs with wiring requirements and callback contracts.

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
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • openmeterio/openmeter#4317: Introduced the OnMutableStandardLinesDeleted hook that this PR renames to OnMutableStandardLinesDeletedBySystem and reshapes into the new ChangeSource-based dispatch flow.
  • openmeterio/openmeter#4100: Extended newChargesRegistry in app/common/charges.go to register flat-fee/credit-purchase line engines — this PR extends the same registry setup to also register the CreateLineRouter.
  • openmeterio/openmeter#4544: Both PRs modify UpdateGatheringInvoice and UpdateStandardInvoice service paths, with this PR's ChangeSource dispatch building directly on top of those update paths.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.46% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main refactoring: routing invoice line edits through line engines instead of handling them in the HTTP/service layer.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/invoice-line-engine-api-edits

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.

@turip turip added release-note/misc Miscellaneous changes area/billing labels Jun 22, 2026
@turip turip changed the title feat: route invoice line edits through line engines refactor: route invoice line edits through line engines Jun 22, 2026
@turip
turip marked this pull request as ready for review June 22, 2026 13:43
@turip
turip requested a review from a team as a code owner June 22, 2026 13:43
@greptile-apps

greptile-apps Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This 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 OnMutableInvoiceLinesEditedViaAPI; system updates only fire the legacy OnMutableStandardLinesDeletedBySystem callback for charge-managed line cleanup.

  • New diffing and edit flow (service/invoiceupdate.go, stdinvoiceedit.go): diffMutableInvoiceLines produces a typed {Created, Updated, Deleted, Unchanged} diff; applyAPIInvoiceLineEdits pre-allocates stable IDs for new standard lines, stamps ManuallyManagedLine ownership, routes per-engine, validates result cardinality, and re-stamps engine outputs before persistence.
  • ChangeSource enforcement: UpdateStandardInvoiceInput and UpdateGatheringInvoiceInput now require a ChangeSource field (validated at entry); all existing call-sites in the diff have been updated.
  • Charge create-line router (charges/linerouter): routes new lines to flat-fee or usage-based charge engines when credits are enabled; falls back to DefaultCreateLineRouter (invoice engine) otherwise.

Confidence Score: 4/5

Safe 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

Filename Overview
openmeter/billing/service/invoiceupdate.go New file: implements generic invoice line diffing, API edit application, line pre-allocation for standard invoices, and result validation. Core of the refactor; logic is sound.
openmeter/billing/stdinvoiceedit.go New file: ExistingLineOverride.Apply() clones the input line before applying changes, addressing the previous shallow-copy P1. Gathering and standard line branches are now consistent.
openmeter/billing/lineengine/engine.go Invoice line engine now implements OnMutableInvoiceLinesEditedViaAPI, handling quantity snapshotting for standard non-gathering invoices. Logic is correct.
openmeter/billing/charges/linerouter/linerouter.go New charge-aware create-line router: routes new lines to flat-fee or usage-based charge engines when credits are enabled, falls back to invoice engine otherwise.
openmeter/billing/httpdriver/invoiceline.go Simplified: removes charge-managed line guards and snapshot calls from HTTP layer; responsibility moved into engines and billing service.
openmeter/billing/service/stdinvoice.go UpdateStandardInvoice now diffs lines before/after EditFn and routes changes to engines per ChangeSource; system deletes still dispatch the legacy callback.
openmeter/billing/service/gatheringinvoice.go UpdateGatheringInvoice now clones the invoice before EditFn, diffs lines, and dispatches API edits through engines. System changes bypass the engine callback.
openmeter/billing/lineengine.go Adds ChangeSource enum, OnMutableInvoiceLinesEditedViaAPI to LineEngine interface, CreateLineRouter interface, and DefaultCreateLineRouter.
openmeter/billing/discount.go Adds Discounts.Equal() method using PtrEqual helpers, replacing the generated deriveEqual_ function for Discounts in derived.gen.go.
openmeter/billing/derived.gen.go Removes generated deriveEqual_ for Discounts (now Discounts.Equal()), renumbers helpers to remove gaps. Straightforward codegen update.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant HTTP as HTTP Handler
    participant Svc as BillingService
    participant Diff as diffMutableInvoiceLines
    participant Apply as applyAPIInvoiceLineEdits
    participant Router as CreateLineRouter
    participant Engine as LineEngine

    HTTP->>Svc: UpdateStandardInvoice(ChangeSourceAPIRequest)
    Svc->>Svc: Clone invoice (originalInvoice)
    Svc->>Svc: "EditFn(&invoice)"
    Svc->>Diff: diffMutableInvoiceLines(original, edited, router)
    Diff->>Router: GetLineEngineForCreateLine(newLine)
    Router-->>Diff: LineEngineType
    Diff-->>Svc: "mutableInvoiceLineDiff{Created, Updated, Deleted, Unchanged}"
    Svc->>Apply: applyAPIInvoiceLineEdits(invoice, lineDiff)
    Apply->>Apply: preallocateCreatedStandardLines (standard only)
    Apply->>Apply: stamp Created lines ManuallyManaged
    Apply->>Apply: GroupByLineEngine()
    loop per engine
        Apply->>Engine: OnMutableInvoiceLinesEditedViaAPI(input)
        Engine->>Engine: snapshotManualStandardLineOverrideIfNeeded
        Engine-->>Apply: "OnMutableInvoiceUpdateResult{CreatedLines, UpdatedLines}"
        Apply->>Apply: validateLineEngineResult (count + ID check)
        Apply->>Apply: stamp Updated lines ManuallyManaged
    end
    Apply->>Apply: stamp Deleted lines ManuallyManaged
    Apply->>Apply: SetLines(resultingLines)
    Apply-->>Svc: GenericInvoice
    Svc->>Svc: save invoice to DB

    Note over Svc,Engine: ChangeSourceSystem path skips Apply, but still dispatches system delete callback
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant HTTP as HTTP Handler
    participant Svc as BillingService
    participant Diff as diffMutableInvoiceLines
    participant Apply as applyAPIInvoiceLineEdits
    participant Router as CreateLineRouter
    participant Engine as LineEngine

    HTTP->>Svc: UpdateStandardInvoice(ChangeSourceAPIRequest)
    Svc->>Svc: Clone invoice (originalInvoice)
    Svc->>Svc: "EditFn(&invoice)"
    Svc->>Diff: diffMutableInvoiceLines(original, edited, router)
    Diff->>Router: GetLineEngineForCreateLine(newLine)
    Router-->>Diff: LineEngineType
    Diff-->>Svc: "mutableInvoiceLineDiff{Created, Updated, Deleted, Unchanged}"
    Svc->>Apply: applyAPIInvoiceLineEdits(invoice, lineDiff)
    Apply->>Apply: preallocateCreatedStandardLines (standard only)
    Apply->>Apply: stamp Created lines ManuallyManaged
    Apply->>Apply: GroupByLineEngine()
    loop per engine
        Apply->>Engine: OnMutableInvoiceLinesEditedViaAPI(input)
        Engine->>Engine: snapshotManualStandardLineOverrideIfNeeded
        Engine-->>Apply: "OnMutableInvoiceUpdateResult{CreatedLines, UpdatedLines}"
        Apply->>Apply: validateLineEngineResult (count + ID check)
        Apply->>Apply: stamp Updated lines ManuallyManaged
    end
    Apply->>Apply: stamp Deleted lines ManuallyManaged
    Apply->>Apply: SetLines(resultingLines)
    Apply-->>Svc: GenericInvoice
    Svc->>Svc: save invoice to DB

    Note over Svc,Engine: ChangeSourceSystem path skips Apply, but still dispatches system delete callback
Loading

Reviews (5): Last reviewed commit: "fix: review comments" | Re-trigger Greptile

@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: 9

🧹 Nitpick comments (3)
openmeter/billing/service/invoiceupdate.go (1)

243-250: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Use the repo’s nillable validation wrapper.

Both new Validate() methods collect errors, but return errors.Join(...) directly. Please wrap the joined error with models.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() error methods, prefer collecting all validation issues into var errs []error and returning models.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 win

Align Validate() with the repo’s aggregated validation pattern.

This method still returns plain errors directly; repo guidance asks Validate() error methods to aggregate and return models.NewNillableGenericValidationError(errors.Join(errs...)) for consistency.
As per coding guidelines: "For Go Validate() error methods, prefer collecting all validation issues into var errs []error and returning models.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 win

Unify Validate() return behavior with the repo pattern.

These new Validate() methods mostly aggregate errors, but they still return raw errors.Join(...) (and one method is fail-fast). Switching to models.NewNillableGenericValidationError(errors.Join(errs...)) keeps behavior consistent with the project’s validation contract.
As per coding guidelines: "For Go Validate() error methods, prefer collecting all validation issues into var errs []error and returning models.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

📥 Commits

Reviewing files that changed from the base of the PR and between 277f8d3 and b57888e.

📒 Files selected for processing (46)
  • app/common/billing.go
  • app/common/charges.go
  • openmeter/billing/README.md
  • openmeter/billing/charges/creditpurchase/lineengine/engine.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/invoiceupdater/invoiceupdate.go
  • openmeter/billing/charges/linerouter/linerouter.go
  • openmeter/billing/charges/linerouter/linerouter_test.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/testutils/linerouter.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/derived.gen.go
  • openmeter/billing/discount.go
  • openmeter/billing/gatheringinvoice.go
  • openmeter/billing/httpdriver/invoice.go
  • openmeter/billing/httpdriver/invoiceline.go
  • openmeter/billing/invoice.go
  • openmeter/billing/invoiceline.go
  • openmeter/billing/lineengine.go
  • openmeter/billing/lineengine/engine.go
  • openmeter/billing/service.go
  • openmeter/billing/service/gatheringinvoice.go
  • openmeter/billing/service/invoice.go
  • openmeter/billing/service/invoice_test.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/service/invoiceupdate_test.go
  • openmeter/billing/service/lineengine.go
  • openmeter/billing/service/lineengine_test.go
  • openmeter/billing/service/stdinvoice.go
  • openmeter/billing/stdinvoice.go
  • openmeter/billing/stdinvoiceedit.go
  • openmeter/billing/stdinvoiceline.go
  • openmeter/billing/testutils/lineengine.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/invoiceupdater/invoiceupdate.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patch_test.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • openmeter/billing/worker/subscriptionsync/service/sync_test.go
  • openmeter/server/server_test.go
  • pkg/equal/equal.go
  • test/app/stripe/invoice_test.go
  • test/billing/collection_test.go
  • test/billing/discount_test.go
  • test/billing/invoice_test.go
  • test/billing/lineengine_test.go
  • test/billing/tax_test.go
💤 Files with no reviewable changes (2)
  • openmeter/billing/service/invoice_test.go
  • openmeter/billing/service/invoice.go

Comment thread openmeter/billing/lineengine/engine.go Resolved
Comment thread openmeter/billing/stdinvoiceedit.go Resolved
Comment thread openmeter/billing/stdinvoiceedit.go Resolved
Comment thread openmeter/billing/lineengine/engine.go Outdated
}

createdLines := make([]billing.GenericInvoiceLine, 0, len(input.Created))
for _, line := range input.Created {

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.

Just a question here, wouldn't be simpler/more bullet-proof to use lo.MapErr instead of manually managing the capacity of the slice?

GAlexIHU
GAlexIHU previously approved these changes Jun 23, 2026

@GAlexIHU GAlexIHU 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.

lgtm

@turip
turip force-pushed the feat/invoice-line-engine-api-edits branch from e09d4a5 to 1aa2076 Compare June 23, 2026 10:24
@turip
turip enabled auto-merge (squash) June 23, 2026 10:25
@turip
turip requested review from GAlexIHU and borosr June 23, 2026 10:25
@turip
turip merged commit fb6e001 into main Jun 23, 2026
23 of 25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants