Skip to content

feat: support flat-fee invoice line creates - #4588

Merged
turip merged 2 commits into
mainfrom
feat/flat-fee-line-create-overrides
Jun 28, 2026
Merged

turip merged 2 commits into
mainfrom
feat/flat-fee-line-create-overrides

Conversation

@turip

@turip turip commented Jun 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds charge-backed flat-fee line creation through mutable invoice edits.

Domain Behavior

Manual invoice-line creates can now route to the flat-fee charge line engine for both gathering and standard invoices. Billing still owns invoice-line identity: created lines are preallocated and persisted before line-engine dispatch, and the flat-fee engine attaches charge state to that existing line instead of creating a second customer-facing line.

For gathering invoices, the created charge returns the target gathering line state and billing merges it onto the edited line. For standard invoices, the flat-fee state machine receives an attach-line trigger in the created state, creates the realization run against the preallocated standard line, and emits an update patch that the line engine validates and merges back.

The flat-fee create path also preserves manual feature keys, uses the invoice edit tax-code fallback when needed, and rejects zero-amount flat-fee creates with the existing "delete instead" validation behavior.

Validation

  • go test -tags=dynamic -count=1 ./openmeter/billing/charges/flatfee/service
  • go test -tags=dynamic -count=1 ./openmeter/billing/worker/subscriptionsync/service -run 'TestCreditThenInvoiceScenarios/TestStandardInvoiceManualCreateSync'
  • go vet -tags=dynamic ./openmeter/billing/charges/flatfee/service ./openmeter/billing/service

Summary by CodeRabbit

  • New Features

    • Added support for attaching manually created flat-fee charges to invoice lines during mutable standard invoice edits.
    • Expanded mutable invoice line editing to handle both gathering and standard line types, with improved metadata capture (created time, currency, and tax config).
  • Bug Fixes

    • Hardened API edit/delete validation, including stricter split-line mutation rules and consistent patch targeting.
    • Prevented invoice edit/callback operations when the invoice is in the gathering state.
    • Tightened progressive-billing constraints and reject zero-amount manual flat-fee line creation.
  • Tests

    • Added/updated coverage for manual flat-fee edit flows and progressive-billing failures.

@turip
turip requested a review from a team as a code owner June 27, 2026 14:33
@coderabbitai

coderabbitai Bot commented Jun 27, 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

Adds attach-invoice-line support for credit-then-invoice flat-fee charges, generalizes manual invoice-line handling and validation, updates invoice edit callbacks, and expands tests for manual attachment and progressive-billing rejections.

Changes

Manual Standard Line Attach for CreditThenInvoice

Layer / File(s) Summary
Invoice line contracts
openmeter/billing/invoiceline.go, openmeter/billing/charges/meta/triggers.go, openmeter/billing/stdinvoiceline.go, openmeter/billing/stdinvoiceline_test.go, openmeter/billing/gatheringinvoice.go
Extends GenericInvoiceLineReader with GetCreatedAt(), GetCurrency(), and GetTaxConfig(), adds TriggerAttachInvoiceLine = "attach_invoice_line", updates StandardLineBase documentation, removes GetInvoiceAt, adds GetSubscriptionReference, verifies StandardLine no longer exposes an GetInvoiceAt accessor, and changes gathering-line tax and currency accessors.
Patch validation and tax diffing
openmeter/billing/charges/invoiceupdater/patch.go, openmeter/billing/service/invoiceupdate.go
Adds RequireTarget and RequireCharge helpers for invoice updater patches and updates invoice line diffing to read tax config directly from the generic accessors.
Manual created-line intent builder
openmeter/billing/charges/flatfee/service/manualedit.go, .agents/skills/charges/SKILL.md
Replaces the gathering-line-only intent builder with intentFromManualCreatedLine, using generic invoice-line readers for created-at, currency, tax, service-period, and feature-key data.
Attach flow and manual edit wiring
openmeter/billing/charges/flatfee/service/creditheninvoice.go, openmeter/billing/charges/flatfee/service/lineengine.go
Wires TriggerAttachInvoiceLine into CreditThenInvoiceStateMachine, adds AttachInvoiceLine, routes manual created-line handling through createManualInvoiceLines, attaches standard lines through the new trigger path, and validates manual delete patches with the new helpers.
Invoice edit validation
openmeter/billing/service/invoice.go, openmeter/billing/service/stdinvoice.go, openmeter/billing/lineengine/engine.go, .agents/skills/billing/SKILL.md
Changes edit callbacks to accept context, rejects gathering-invoice edit callbacks, validates lines directly, removes invoicability checks, and tightens split-line validation for mutable invoice edits.
Manual attach and progressive billing tests
openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go, test/billing/discount_test.go, test/billing/invoice_test.go
Adds the manual standard-line sync test and updates invoice and discount tests to expect progressive-billing rejections.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • tothandras
  • borosr
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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.
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.
Title check ✅ Passed The title clearly matches the main change: adding support for flat-fee invoice line creates.
✨ 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/flat-fee-line-create-overrides

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.

@greptile-apps

greptile-apps Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds charge-backed flat-fee invoice-line creation through mutable invoice edits. The main changes are:

  • Standard and gathering manual flat-fee creates now share the charge-backed create path.
  • Standard creates attach the charge realization to the billing-preallocated line.
  • Patch target checks were centralized for update, delete, and gathering-line patches.
  • Standard-line InvoiceAt is treated as display-only for charge scheduling.
  • Split-line edit validation now rejects only actual unsupported mutations.

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/flatfee/service/manualedit.go Builds flat-fee create intents from generic invoice lines and derives standard-line scheduling from payment-term semantics.
openmeter/billing/charges/flatfee/service/lineengine.go Routes manual flat-fee creates through gathering-line merge or standard-line attach handling.
openmeter/billing/charges/flatfee/service/creditheninvoice.go Adds the attach-invoice-line state transition for standard flat-fee manual creates.
openmeter/billing/stdinvoiceline.go Keeps standard-line InvoiceAt as display data rather than generic scheduling input.
openmeter/billing/lineengine/engine.go Adds split-line override checks that allow unchanged resend values while blocking unsupported mutations.

Reviews (5): Last reviewed commit: "fix(billing): allow split line no-op ove..." | 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: 2

🧹 Nitpick comments (2)
openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go (2)

4269-4299: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the failed zero-amount edit leaves the draft invoice unchanged.

Right now this only proves the error and balances. It would still pass if the preallocated line were left on the invoice before ErrInvoiceLineZeroAmountCreate came back, which is the risky part of this new flow.

Diff suggestion
  s.ErrorIs(err, billing.ErrInvoiceLineZeroAmountCreate)
+	rejectedInvoice, err := s.BillingService.GetStandardInvoiceById(ctx, billing.GetStandardInvoiceByIdInput{
+		Invoice: draftInvoice.GetInvoiceID(),
+		Expand:  billing.StandardInvoiceExpandAll,
+	})
+	s.NoError(err)
+	s.Require().Len(rejectedInvoice.Lines.OrEmpty(), 1)
+	_, rejectedFound := lo.Find(rejectedInvoice.Lines.OrEmpty(), func(line *billing.StandardLine) bool {
+		return line != nil && line.Name == "Zero manual standard setup fee"
+	})
+	s.False(rejectedFound, "rejected zero-amount line should not persist")
  s.assertCreditThenInvoiceBalances(expectedCreditThenInvoiceBalances{

As per path instructions, **/*_test.go: “Make sure the tests are comprehensive and cover the changes.” Based on PR objectives, billing now “preallocates and persists invoice lines before dispatching to the line engine.”

🤖 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 4269 - 4299, The zero-amount update test in the
UpdateStandardInvoice flow only checks the error and balances, so it misses the
regression where the draft invoice may still keep the preallocated line after
ErrInvoiceLineZeroAmountCreate. Extend this test around
BillingService.UpdateStandardInvoice to assert the draft invoice state is
unchanged after the failed EditFn, using the existing draftInvoice and invoice
line helpers to verify the added line was not persisted on the invoice.

Source: Path instructions


4325-4400: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Please pin the “no second customer-facing line” contract with a count assertion.

Finding one attached line by name and ID is good, but this would still pass if the attach flow also left a duplicate preallocated line behind. A Len(..., 2) on both the edited and refetched invoice would catch that regression directly.

Diff suggestion
  s.Require().NoError(err)
  s.DebugDumpInvoice("edited draft invoice", editedInvoice)
+	s.Require().Len(editedInvoice.Lines.OrEmpty(), 2, "manual attach should reuse the preallocated line instead of creating a duplicate")
  s.assertCreditThenInvoiceBalances(expectedCreditThenInvoiceBalances{
@@
  s.NoError(err)
+	s.Require().Len(refetchedInvoice.Lines.OrEmpty(), 2, "manual attach should persist exactly one new customer-facing line")
  refetchedCreatedLine, found := lo.Find(refetchedInvoice.Lines.OrEmpty(), func(line *billing.StandardLine) bool {

As per path instructions, **/*_test.go: “Make sure the tests are comprehensive and cover the changes.” Based on PR objectives, the flat-fee engine should “attach charge state to the existing line rather than creating a second customer-facing line.”

🤖 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 4325 - 4400, The test currently verifies the attached manual line
by name and ID, but it does not assert that only one customer-facing line
exists. In this sync_credittheninvoice_test.go scenario around editedInvoice and
refetchedInvoice, add a line-count assertion on the invoice lines to ensure the
attach flow does not leave a duplicate preallocated line behind. Keep the
existing lo.Find checks for createdLine/refetchedCreatedLine, but pin the
contract with a Len assertion on both the edited and refetched invoice line
collections so the flat-fee attach behavior is covered end to end.

Source: Path instructions

🤖 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/flatfee/service/manualedit.go`:
- Line 172: The manual flat fee creation path is converting tax config in the
line builder before the fallback logic can run, so nil tax config causes a
failure. Update the manual edit flow in the line handling code around the
`GetTaxConfig()` / `ToProductCatalog()` conversion so it first checks whether
the tax config is present and only converts when non-nil, otherwise lets the
existing default tax-code fallback in this service apply. Use the
`manualedit.go` line construction logic and the `TaxConfig` assignment as the
place to guard this.

In `@openmeter/billing/charges/invoiceupdater/patch.go`:
- Around line 80-115: The target validation in PatchLineUpdate.RequireTarget and
PatchLineDelete.RequireTarget only compares plain line ID and InvoiceID, so a
namespace mismatch can slip through. Update both helpers to validate the full
namespaced line identifier carried by the patch and the
billing.GenericInvoiceLineReader, using the LineID value instead of just ID
where available. Keep the existing invoice check, but ensure the target line
comparison fails whenever the namespace portion differs.

---

Nitpick comments:
In
`@openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go`:
- Around line 4269-4299: The zero-amount update test in the
UpdateStandardInvoice flow only checks the error and balances, so it misses the
regression where the draft invoice may still keep the preallocated line after
ErrInvoiceLineZeroAmountCreate. Extend this test around
BillingService.UpdateStandardInvoice to assert the draft invoice state is
unchanged after the failed EditFn, using the existing draftInvoice and invoice
line helpers to verify the added line was not persisted on the invoice.
- Around line 4325-4400: The test currently verifies the attached manual line by
name and ID, but it does not assert that only one customer-facing line exists.
In this sync_credittheninvoice_test.go scenario around editedInvoice and
refetchedInvoice, add a line-count assertion on the invoice lines to ensure the
attach flow does not leave a duplicate preallocated line behind. Keep the
existing lo.Find checks for createdLine/refetchedCreatedLine, but pin the
contract with a Len assertion on both the edited and refetched invoice line
collections so the flat-fee attach behavior is covered end to end.
🪄 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: 2c0ba298-47e0-47fc-96f0-e45486360742

📥 Commits

Reviewing files that changed from the base of the PR and between 2521ae0 and 42254d0.

📒 Files selected for processing (9)
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/flatfee/service/manualedit.go
  • openmeter/billing/charges/invoiceupdater/patch.go
  • openmeter/billing/charges/meta/triggers.go
  • openmeter/billing/gatheringinvoice.go
  • openmeter/billing/invoiceline.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go

@turip
turip force-pushed the feat/flat-fee-line-create-overrides branch from 42254d0 to efd641f Compare June 27, 2026 17:32
@turip turip added area/billing release-note/feature Release note: Exciting New Features labels Jun 27, 2026

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
test/billing/discount_test.go (1)

178-195: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Please assert the invoice stays unchanged after the rejected edit.

Right now this only checks the returned error. A bug that mutates the progressively billed line before surfacing billing.ErrInvoiceLineProgressiveBillingUsageDiscountUpdateForbidden would still pass. Re-fetching the invoice and asserting the usage discount is unchanged would close that gap. As per path instructions, "Suggest missing tests only when the PR introduces behavior without meaningful coverage, or when the current tests would pass despite a concrete regression in the changed code."

🤖 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/discount_test.go` around lines 178 - 195, Add an assertion in
the “Editing a progressively billed invoice line usage discount is rejected”
test that re-fetches the invoice after UpdateStandardInvoice returns the
forbidden error and verifies the line’s usage discount was not mutated. Use the
existing BillingService.UpdateStandardInvoice flow and the invoice line access
via invoice.Lines.OrEmpty()[0] to confirm the pre-edit state remains unchanged
after ErrInvoiceLineProgressiveBillingUsageDiscountUpdateForbidden.

Source: Path instructions

test/billing/invoice_test.go (1)

1798-1817: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Nice contract check, but we should also prove the failed edit is side-effect free.

Both cases stop at the error assertion now. If UpdateStandardInvoice accidentally mutates the line or marks it deleted before returning billing.ErrInvoiceProgressiveBillingNotSupported, these tests would still pass. I'd add a re-fetch plus unchanged line/totals assertions after each failure. As per path instructions, "Suggest missing tests only when the PR introduces behavior without meaningful coverage, or when the current tests would pass despite a concrete regression in the changed code."

Also applies to: 1850-1867

🤖 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` around lines 1798 - 1817, Add post-failure
coverage to prove UpdateStandardInvoice is side-effect free when it rejects
progressive billing edits: after the error assertions in the "updating a
progressively billed line item is rejected" and the other affected failing-case
test, re-fetch the invoice and assert the targeted line from
invoice.Lines.GetByID (and any related totals/state) remains unchanged and not
deleted. Use the existing BillingService.UpdateStandardInvoice,
invoice.GetInvoiceID, and line lookup helpers to verify the rejected edit did
not mutate invoice state before returning
billing.ErrInvoiceProgressiveBillingNotSupported.

Source: Path instructions

🤖 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/service/invoice.go`:
- Around line 640-643: The gathering-invoice rejection in
executeTriggerOnInvoice is currently returned as a raw fmt.Errorf, which causes
UpdateStandardInvoice to surface it as an internal error instead of a
validation-style response. Move this check onto the validation path used in
service/invoice.go, and return the same kind of validation error that
DeleteInvoice uses for gathering invoices, keeping the behavior consistent for
StandardInvoiceStatusGathering.
- Around line 666-676: The joined validation errors from the StandardLine loop
are returned as plain errors instead of the normal billing validation type.
Update the invoice update path in invoice.go so the errors produced by
line.Validate() in the sm.Invoice.Lines validation branch are wrapped as
billing.ValidationError, matching the earlier sm.Invoice.Validate() handling and
the edit-failure expectations in the invoice update flow.

---

Outside diff comments:
In `@test/billing/discount_test.go`:
- Around line 178-195: Add an assertion in the “Editing a progressively billed
invoice line usage discount is rejected” test that re-fetches the invoice after
UpdateStandardInvoice returns the forbidden error and verifies the line’s usage
discount was not mutated. Use the existing BillingService.UpdateStandardInvoice
flow and the invoice line access via invoice.Lines.OrEmpty()[0] to confirm the
pre-edit state remains unchanged after
ErrInvoiceLineProgressiveBillingUsageDiscountUpdateForbidden.

In `@test/billing/invoice_test.go`:
- Around line 1798-1817: Add post-failure coverage to prove
UpdateStandardInvoice is side-effect free when it rejects progressive billing
edits: after the error assertions in the "updating a progressively billed line
item is rejected" and the other affected failing-case test, re-fetch the invoice
and assert the targeted line from invoice.Lines.GetByID (and any related
totals/state) remains unchanged and not deleted. Use the existing
BillingService.UpdateStandardInvoice, invoice.GetInvoiceID, and line lookup
helpers to verify the rejected edit did not mutate invoice state before
returning billing.ErrInvoiceProgressiveBillingNotSupported.
🪄 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: 704b93aa-1963-49ce-be82-7a5f6cbd43f9

📥 Commits

Reviewing files that changed from the base of the PR and between 42254d0 and efd641f.

📒 Files selected for processing (16)
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/flatfee/service/manualedit.go
  • openmeter/billing/charges/invoiceupdater/patch.go
  • openmeter/billing/charges/meta/triggers.go
  • openmeter/billing/gatheringinvoice.go
  • openmeter/billing/invoiceline.go
  • openmeter/billing/lineengine/engine.go
  • openmeter/billing/service/invoice.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/service/stdinvoice.go
  • openmeter/billing/stdinvoiceline.go
  • openmeter/billing/stdinvoiceline_test.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • test/billing/discount_test.go
  • test/billing/invoice_test.go
✅ Files skipped from review due to trivial changes (1)
  • openmeter/billing/stdinvoiceline_test.go
🚧 Files skipped from review as they are similar to previous changes (9)
  • openmeter/billing/charges/meta/triggers.go
  • openmeter/billing/charges/invoiceupdater/patch.go
  • openmeter/billing/gatheringinvoice.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/charges/flatfee/service/manualedit.go
  • openmeter/billing/invoiceline.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go

Comment thread openmeter/billing/service/invoice.go Resolved
Comment thread openmeter/billing/service/invoice.go Resolved
@turip
turip force-pushed the feat/flat-fee-line-create-overrides branch from efd641f to 5e5ce42 Compare June 27, 2026 17:43

@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

🤖 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/lineengine/engine.go`:
- Around line 180-183: The guard in engine.go’s line validation is too broad
because it rejects any presence of Price or FeatureKey in ChangesToApply, even
when the values are unchanged. Update the check around the validation error in
the helper that processes override.ChangesToApply so it only fails when Price or
FeatureKey actually differ from override.ExistingLine, or move the validation to
after applying the override and compare against the resulting line. Keep the
existing billing.ValidationError path and
ErrInvoiceProgressiveBillingNotSupported behavior, but scope it to real changes
only.
🪄 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: 817aec26-50cd-41f2-aa98-3bb2e7488fd3

📥 Commits

Reviewing files that changed from the base of the PR and between efd641f and 5e5ce42.

📒 Files selected for processing (16)
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/flatfee/service/manualedit.go
  • openmeter/billing/charges/invoiceupdater/patch.go
  • openmeter/billing/charges/meta/triggers.go
  • openmeter/billing/gatheringinvoice.go
  • openmeter/billing/invoiceline.go
  • openmeter/billing/lineengine/engine.go
  • openmeter/billing/service/invoice.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/service/stdinvoice.go
  • openmeter/billing/stdinvoiceline.go
  • openmeter/billing/stdinvoiceline_test.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • test/billing/discount_test.go
  • test/billing/invoice_test.go
🚧 Files skipped from review as they are similar to previous changes (15)
  • openmeter/billing/stdinvoiceline_test.go
  • openmeter/billing/service/stdinvoice.go
  • openmeter/billing/charges/meta/triggers.go
  • openmeter/billing/invoiceline.go
  • test/billing/discount_test.go
  • openmeter/billing/stdinvoiceline.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/gatheringinvoice.go
  • openmeter/billing/charges/invoiceupdater/patch.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • test/billing/invoice_test.go
  • openmeter/billing/service/invoice.go
  • openmeter/billing/charges/flatfee/service/manualedit.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • openmeter/billing/charges/flatfee/service/lineengine.go

Comment thread openmeter/billing/lineengine/engine.go Resolved
@turip
turip force-pushed the feat/flat-fee-line-create-overrides branch from 5e5ce42 to 885fabd Compare June 27, 2026 17:54

@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)
test/billing/invoice_test.go (1)

1798-1817: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Also assert the rejected edit leaves the stored line unchanged.

Right now this would still pass if UpdateStandardInvoice returns the right error but partially persists the price change. A quick reload assertion would cover that side effect, and the small given/when/then comments satisfy the service-subtest style rule too.

Suggested test tightening
 		s.Run("updating a progressively billed line item is rejected", func() {
+			// Given a progressively billed line from the mid-period invoice.
+			originalPrice := flatPerUnit.UsageBased.Price
+
+			// When an API edit tries to update the line price.
 			_, err := s.BillingService.UpdateStandardInvoice(ctx, billing.UpdateStandardInvoiceInput{
 				Invoice:      invoice.GetInvoiceID(),
 				ChangeSource: billing.ChangeSourceAPIRequest,
@@
 
+			// Then the edit is rejected and the stored line remains unchanged.
 			require.Error(s.T(), err)
 			require.ErrorAs(s.T(), err, &billing.ValidationError{})
 			require.ErrorIs(s.T(), err, billing.ErrInvoiceProgressiveBillingNotSupported)
+
+			reloadedInvoice, reloadErr := s.BillingService.GetStandardInvoiceById(ctx, billing.GetStandardInvoiceByIdInput{
+				Invoice: invoice.GetInvoiceID(),
+				Expand: billing.StandardInvoiceExpands{
+					billing.StandardInvoiceExpandLines,
+				},
+			})
+			require.NoError(s.T(), reloadErr)
+
+			reloadedLine := reloadedInvoice.Lines.GetByID(flatPerUnit.ID)
+			require.NotNil(s.T(), reloadedLine)
+			require.Equal(s.T(), originalPrice, reloadedLine.UsageBased.Price, "rejected update should not persist line price")
 		})

As per path instructions, “Make sure the tests are comprehensive and cover the changes.” As per coding guidelines, “For service and lifecycle subtests, start non-trivial subtest bodies with concise given/when/then intent comments.”

🤖 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` around lines 1798 - 1817, The
progressive-billing rejection test in the UpdateStandardInvoice path should also
verify no partial mutation is persisted. In the subtest around
BillingService.UpdateStandardInvoice, keep the existing error assertions and
then reload the invoice/line state to confirm the flatPerUnit line still has its
original UsageBased.Price. Add concise given/when/then comments at the start of
the non-trivial subtest body to match the service-subtest style rule.

Sources: Coding guidelines, Path instructions

🤖 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 `@test/billing/invoice_test.go`:
- Around line 1798-1817: The progressive-billing rejection test in the
UpdateStandardInvoice path should also verify no partial mutation is persisted.
In the subtest around BillingService.UpdateStandardInvoice, keep the existing
error assertions and then reload the invoice/line state to confirm the
flatPerUnit line still has its original UsageBased.Price. Add concise
given/when/then comments at the start of the non-trivial subtest body to match
the service-subtest style rule.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 106d6210-ae85-4fde-8e21-1e7273d24903

📥 Commits

Reviewing files that changed from the base of the PR and between 5e5ce42 and 885fabd.

📒 Files selected for processing (16)
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/flatfee/service/manualedit.go
  • openmeter/billing/charges/invoiceupdater/patch.go
  • openmeter/billing/charges/meta/triggers.go
  • openmeter/billing/gatheringinvoice.go
  • openmeter/billing/invoiceline.go
  • openmeter/billing/lineengine/engine.go
  • openmeter/billing/service/invoice.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/service/stdinvoice.go
  • openmeter/billing/stdinvoiceline.go
  • openmeter/billing/stdinvoiceline_test.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • test/billing/discount_test.go
  • test/billing/invoice_test.go
🚧 Files skipped from review as they are similar to previous changes (14)
  • openmeter/billing/charges/meta/triggers.go
  • openmeter/billing/stdinvoiceline_test.go
  • openmeter/billing/gatheringinvoice.go
  • test/billing/discount_test.go
  • openmeter/billing/charges/invoiceupdater/patch.go
  • openmeter/billing/service/stdinvoice.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/lineengine/engine.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/invoiceline.go
  • openmeter/billing/service/invoice.go
  • openmeter/billing/charges/flatfee/service/manualedit.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go

@turip turip changed the title Support flat-fee invoice line creates feat: support flat-fee invoice line creates Jun 28, 2026
@turip
turip merged commit db3581c into main Jun 28, 2026
26 checks passed
@turip
turip deleted the feat/flat-fee-line-create-overrides branch June 28, 2026 11:44
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