Skip to content

Support gathering line creation via invoice edits - #4587

Merged
turip merged 2 commits into
mainfrom
feat/flat-fee-line-create-overrides
Jun 27, 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

This PR adds support for creating flat-fee charge-backed gathering invoice lines through API invoice edits.

Billing now treats API-created gathering lines similarly to standard invoice creates: it preallocates and persists the billing line before dispatching to line engines, then lets the flat-fee line engine create the manually managed charge and merge the charge-produced target state back onto the precreated line identity.

Domain behavior

  • Gathering invoice API edits can add a new flat-fee line.
  • The flat-fee line engine creates a manually managed credit-then-invoice charge for that line.
  • Existing subscription-owned charge lines remain system managed.
  • API-created lines can use invoice-context default tax-code resolvers when the edited line does not carry a line-level tax config.
  • Zero-amount flat-fee creates are rejected with a create-specific validation error instead of producing an unusable charge.

Validation

  • go test -tags=dynamic -count=1 ./openmeter/billing/service
  • env POSTGRES_HOST=127.0.0.1 go test -tags=dynamic -count=1 -run TestCreditThenInvoiceScenarios/TestGatheringManualCreateSync ./openmeter/billing/worker/subscriptionsync/service
  • direnv exec . make test-nocache

Summary by CodeRabbit

  • New Features

    • Added support for manually creating flat-fee lines on gathering invoices.
    • Invoice line edits can now automatically resolve and backfill default tax codes when omitted.
  • Bug Fixes

    • Improved invoice line updates for both gathering and standard invoices, including correct diff/validation behavior.
    • Prevented creation of flat-fee invoice lines with a zero amount.
    • Better preserves manually created gathering lines and their manually-managed charges across later syncs and updates.

@coderabbitai

coderabbitai Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4a5421f2-02b9-4f0e-99fe-42705be014fc

📥 Commits

Reviewing files that changed from the base of the PR and between 22698b6 and e2b9ccf.

📒 Files selected for processing (9)
  • openmeter/billing/charges/creditpurchase/service.go
  • openmeter/billing/charges/flatfee/service.go
  • openmeter/billing/charges/flatfee/service/create.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/service/invoiceupdate_test.go
  • openmeter/billing/stdinvoiceedit.go
  • pkg/syncx/once.go
✅ Files skipped from review due to trivial changes (5)
  • openmeter/billing/charges/flatfee/service/create.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/creditpurchase/service.go
  • openmeter/billing/charges/flatfee/service.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/stdinvoiceedit.go
  • pkg/syncx/once.go
  • openmeter/billing/service/invoiceupdate_test.go

📝 Walkthrough

Walkthrough

This PR adds default tax-code resolver support to invoice-edit inputs, centralizes invoice-line diffing and gathering-line preallocation in billing services, and extends flat-fee manual-create handling for API-created gathering lines. It also adds related tests, a shared once helper, and guidance updates.

Changes

Billing invoice edit and manual-create flow

Layer / File(s) Summary
Default tax-code contract
openmeter/billing/stdinvoiceedit.go, openmeter/billing/service/invoiceupdate.go, pkg/syncx/once.go, AGENTS.md
Invoice-edit inputs now carry default tax-code resolvers, validation and grouping preserve them, the service builds default tax-code resolver helpers, and a generic once helper plus style guidance were added for cached lookups.
Invoice diff and preallocation
openmeter/billing/service/invoiceupdate.go, openmeter/billing/service/stdinvoice.go, openmeter/billing/service/gatheringinvoice.go, openmeter/billing/service/invoiceupdate_test.go
Invoice update paths now use the service diff wrapper, validate diffs before applying edits, mark API-created lines as manually managed, and preallocate gathering-line creations through the adapter; the tests swap in a noop resolver and preallocating adapter.
Manual create flat-fee lines
openmeter/billing/charges/flatfee/service/manualedit.go, openmeter/billing/charges/flatfee/service/lineengine.go, openmeter/billing/errors.go, .agents/skills/charges/SKILL.md, openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go, openmeter/billing/charges/*/service.go, openmeter/billing/charges/flatfee/service/create.go
Manual gathering-line creation now validates inputs, resolves missing tax codes, rejects zero-amount creation, creates charges for API-created gathering lines, and is covered by the subscription-sync manual-create test and charge-engine guidance updates.

Sequence Diagram(s)

sequenceDiagram
  participant Service as Service.applyAPIInvoiceLineEdits
  participant Diff as Service.diffMutableInvoiceLines
  participant Adapter as UpdateGatheringInvoice
  participant Router as line engine routing
  participant Result as mutableInvoiceLineDiff
  Service->>Diff: compute diff with default tax-code resolvers
  Diff-->>Service: validated mutableInvoiceLineDiff
  Service->>Adapter: preallocate created gathering lines
  Adapter-->>Service: persisted gathering lines
  Service->>Router: apply edited invoice lines
  Router-->>Result: created, updated, deleted lines
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • openmeterio/openmeter#4552: Introduces the invoice-line edit routing framework that this PR extends with manual-created gathering-line handling.
  • openmeterio/openmeter#4287: Covers the same invoice edit path for default tax-code resolution and tax-config backfill behavior.
  • openmeterio/openmeter#4586: Modifies the same OnMutableInvoiceLinesEditedViaAPI flat-fee line-engine path that this PR extends for created lines.

Suggested labels

kind/feature

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.55% 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 matches the main change: adding support for creating gathering lines through invoice edits.
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.
✨ 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 support for creating flat-fee gathering invoice lines through invoice edits. The main changes are:

  • Preallocates gathering-line identities before charge creation.
  • Builds manual flat-fee charge intents from API-created gathering lines.
  • Adds invoice-context default tax-code resolvers for edited lines.
  • Rejects zero-amount flat-fee creates.
  • Adds tests and guidance for the new manual-create flow.

Confidence Score: 5/5

This looks safe to merge.

  • No blocking issues found in the changed code.

Important Files Changed

Filename Overview
openmeter/billing/service/invoiceupdate.go Adds default tax-code resolver wiring and provisional gathering-line preallocation for API-created lines.
openmeter/billing/charges/flatfee/service/lineengine.go Routes API-created gathering lines through flat-fee charge creation and merges returned target state onto the preallocated line.
openmeter/billing/charges/flatfee/service/manualedit.go Converts manually created gathering lines into validated flat-fee charge intents.
openmeter/billing/stdinvoiceedit.go Adds default tax-code resolvers to mutable invoice update inputs and preserves them when grouping changes by line engine.
pkg/syncx/once.go Adds a context-aware lazy result helper used by invoice edit tax-code resolution.

Reviews (2): Last reviewed commit: "fix(billing): address invoice edit revie..." | Re-trigger Greptile

Comment thread pkg/syncx/once.go Resolved
@turip
turip marked this pull request as ready for review June 27, 2026 10:51
@turip
turip requested a review from a team as a code owner June 27, 2026 10:51
@turip turip added release-note/feature Release note: Exciting New Features area/billing 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

🧹 Nitpick comments (2)
openmeter/billing/charges/flatfee/service/lineengine.go (1)

427-453: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Please key the merge off the returned line ID instead of slice position.

created[idx] assumes e.service.Create(...) preserves input order. If that ever changes, a multi-line edit can merge the wrong target state or fail inside WithTargetState. The billing-preallocated line ID on charge.GatheringLineToCreate gives you a stable join key here.

Suggested direction
 	createdCharges, err := e.service.Create(ctx, flatfee.CreateInput{
 		Namespace: input.Invoice.GetInvoiceID().Namespace,
 		Intents: lo.Map(created, func(line manualCreatedGatheringLine, _ int) flatfee.Intent {
 			return line.intent
 		}),
 	})
 	if err != nil {
 		return nil, fmt.Errorf("creating manually managed flat-fee charges: %w", err)
 	}
 
 	if len(createdCharges) != len(created) {
 		return nil, fmt.Errorf("expected %d manually created flat-fee charges, got %d", len(created), len(createdCharges))
 	}
 
+	createdByLineID := lo.SliceToMap(created, func(item manualCreatedGatheringLine) (string, manualCreatedGatheringLine) {
+		return item.sourceLine.GetID(), item
+	})
+
 	out := make([]billing.GenericInvoiceLine, 0, len(createdCharges))
-	for idx, charge := range createdCharges {
+	for _, charge := range createdCharges {
 		if charge.GatheringLineToCreate == nil {
-			return nil, fmt.Errorf("line[%s]: manually created flat-fee charge[%s] did not create a gathering line", created[idx].sourceLine.GetID(), charge.Charge.ID)
+			return nil, fmt.Errorf("manually created flat-fee charge[%s] did not create a gathering line", charge.Charge.ID)
 		}
 
-		line, err := created[idx].sourceLine.WithTargetState(charge.GatheringLineToCreate.AsGenericLine())
+		source, ok := createdByLineID[charge.GatheringLineToCreate.ID]
+		if !ok {
+			return nil, fmt.Errorf("manually created flat-fee charge[%s] returned unexpected gathering line[%s]", charge.Charge.ID, charge.GatheringLineToCreate.ID)
+		}
+
+		line, err := source.sourceLine.WithTargetState(charge.GatheringLineToCreate.AsGenericLine())
 		if err != nil {
-			return nil, fmt.Errorf("line[%s]: merging manually created flat-fee charge target state: %w", created[idx].sourceLine.GetID(), err)
+			return nil, fmt.Errorf("line[%s]: merging manually created flat-fee charge target state: %w", source.sourceLine.GetID(), err)
 		}
 
 		out = append(out, 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/charges/flatfee/service/lineengine.go` around lines 427 -
453, The merge in lineengine.go currently relies on created[idx], which assumes
e.service.Create preserves order and can pair the wrong source line with a
returned charge. Update the loop around e.service.Create and WithTargetState to
join each returned charge back to the matching manualCreatedGatheringLine using
the stable billing-preallocated line ID from charge.GatheringLineToCreate
instead of slice position. Keep the existing validation/error handling, but
resolve the source line from that ID before calling WithTargetState so
multi-line edits merge the correct target state.
openmeter/billing/service/invoiceupdate_test.go (1)

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

Run diff.Validate() in this helper too.

Right now it only patches in noop resolvers, so the suite skips the same post-injection validation step that Service.diffMutableInvoiceLines(...) runs in production. A regression in that new validation path would still leave these tests green.

Suggested tweak
 func diffMutableInvoiceLinesForTest(before, after billing.GenericInvoiceReader, createLineRouter billing.CreateLineRouter) (mutableInvoiceLineDiff, error) {
 	diff, err := diffMutableInvoiceLines(before, after, createLineRouter)
 	if err != nil {
 		return mutableInvoiceLineDiff{}, err
 	}
 
 	diff.DefaultTaxCodeResolvers = noopDefaultTaxCodeResolvers()
+
+	if err := diff.Validate(); err != nil {
+		return mutableInvoiceLineDiff{}, err
+	}
 
 	return diff, nil
 }

As per path instructions, "**/*_test.go: Make sure the tests are comprehensive and cover the changes."

🤖 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_test.go` around lines 21 - 29, The
test helper diffMutableInvoiceLinesForTest currently only injects
noopDefaultTaxCodeResolvers after calling diffMutableInvoiceLines, but it does
not mirror the production post-processing validation. Update this helper to also
invoke diff.Validate() on the diff before returning, so the tests exercise the
same validation path as Service.diffMutableInvoiceLines and catch regressions in
that logic.

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/stdinvoiceedit.go`:
- Around line 161-173: The DefaultTaxCodeResolvers.Validate method is returning
errors.Join(errs...) directly instead of the repo’s nillable validation wrapper.
Update Validate in stdinvoiceedit.go to keep collecting issues in var errs
[]error, then return
models.NewNillableGenericValidationError(errors.Join(errs...)) so it follows the
established validation pattern used elsewhere in the repo.

In `@pkg/syncx/once.go`:
- Around line 8-13: Update the doc comment for OnceValues to match its actual
caching behavior: it should say the function executes at most once, caches both
returned values from the first call, and does not retry on error in T2. Keep the
description aligned with OnceValues and sync.Once-style semantics, and remove
the current wording that implies the cached result is not updated after an
error.

---

Nitpick comments:
In `@openmeter/billing/charges/flatfee/service/lineengine.go`:
- Around line 427-453: The merge in lineengine.go currently relies on
created[idx], which assumes e.service.Create preserves order and can pair the
wrong source line with a returned charge. Update the loop around
e.service.Create and WithTargetState to join each returned charge back to the
matching manualCreatedGatheringLine using the stable billing-preallocated line
ID from charge.GatheringLineToCreate instead of slice position. Keep the
existing validation/error handling, but resolve the source line from that ID
before calling WithTargetState so multi-line edits merge the correct target
state.

In `@openmeter/billing/service/invoiceupdate_test.go`:
- Around line 21-29: The test helper diffMutableInvoiceLinesForTest currently
only injects noopDefaultTaxCodeResolvers after calling diffMutableInvoiceLines,
but it does not mirror the production post-processing validation. Update this
helper to also invoke diff.Validate() on the diff before returning, so the tests
exercise the same validation path as Service.diffMutableInvoiceLines and catch
regressions in that logic.
🪄 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: d64ce659-7dd5-49d0-acf9-451511dca05e

📥 Commits

Reviewing files that changed from the base of the PR and between 6a6626a and 22698b6.

📒 Files selected for processing (12)
  • .agents/skills/charges/SKILL.md
  • AGENTS.md
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/flatfee/service/manualedit.go
  • openmeter/billing/errors.go
  • openmeter/billing/service/gatheringinvoice.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/service/invoiceupdate_test.go
  • openmeter/billing/service/stdinvoice.go
  • openmeter/billing/stdinvoiceedit.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • pkg/syncx/once.go

Comment thread openmeter/billing/stdinvoiceedit.go Resolved
Comment thread pkg/syncx/once.go Resolved
@turip
turip merged commit 2521ae0 into main Jun 27, 2026
25 checks passed
@turip
turip deleted the feat/flat-fee-line-create-overrides branch June 27, 2026 13:19
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