Repository navigation
Support gathering line creation via invoice edits - #4587
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (9)
✅ Files skipped from review due to trivial changes (5)
🚧 Files skipped from review as they are similar to previous changes (4)
📝 WalkthroughWalkthroughThis 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. ChangesBilling invoice edit and manual-create flow
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Greptile SummaryThis PR adds support for creating flat-fee gathering invoice lines through invoice edits. The main changes are:
Confidence Score: 5/5This looks safe to merge.
Important Files Changed
Reviews (2): Last reviewed commit: "fix(billing): address invoice edit revie..." | Re-trigger Greptile |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
openmeter/billing/charges/flatfee/service/lineengine.go (1)
427-453: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winPlease key the merge off the returned line ID instead of slice position.
created[idx]assumese.service.Create(...)preserves input order. If that ever changes, a multi-line edit can merge the wrong target state or fail insideWithTargetState. The billing-preallocated line ID oncharge.GatheringLineToCreategives 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 winRun
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
📒 Files selected for processing (12)
.agents/skills/charges/SKILL.mdAGENTS.mdopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/manualedit.goopenmeter/billing/errors.goopenmeter/billing/service/gatheringinvoice.goopenmeter/billing/service/invoiceupdate.goopenmeter/billing/service/invoiceupdate_test.goopenmeter/billing/service/stdinvoice.goopenmeter/billing/stdinvoiceedit.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.gopkg/syncx/once.go
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
Validation
Summary by CodeRabbit
New Features
Bug Fixes