Repository navigation
feat: support flat fee gathering/standard line API edits - #4580
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR adds manual-edit handling for flat-fee charges, changes gathering-line patches to target-state upserts by charge ID, updates invoice diffing and patch resolution, and adjusts usage-based gathering-line creation, extension, shrink, and tests to match. ChangesBilling target-state patch flow
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 manual API edits for flat-fee charge-backed invoice lines. The main changes are:
Confidence Score: 5/5This looks safe to merge.
Important Files Changed
Reviews (7): Last reviewed commit: "test(billing): assert usage based delete..." | Re-trigger Greptile |
71d086a to
cc4f1fa
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
openmeter/billing/charges/usagebased/service/creditheninvoice.go (1)
360-375: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPlease pin the new extend-path period logic with a focused test.
This helper now decides how far an existing pending gathering line gets advanced on extend, including the
IsVoidedBillingHistory()skip and the finalTruncate(...). The changed test surface only exercises the shrink upsert path, so a smallExtendChargecase with mixed realized/voided runs would make this branch a lot safer to change later.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/charges/usagebased/service/creditheninvoice.go` around lines 360 - 375, The new extend-path logic in remainingGatheringLinePeriod is not covered by a focused test, especially the IsVoidedBillingHistory() skip and the final Truncate(streaming.MinimumWindowSizeDuration) behavior. Add a targeted ExtendCharge test in the existing creditheninvoice service tests that exercises a charge with mixed realized and voided runs, verifies the pending gathering line advances to the expected period, and confirms the voided run is ignored.Source: Path instructions
openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go (1)
3728-3788: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPlease assert the edited standard invoice line itself, not just the charge side effects.
Right now this test proves the charge override and realization got updated, but it never checks that
editedInvoiceactually kept the line’s edited period / tax config / management mode. A quick lookup byupdatedLine.IDwould pin the invoice API behavior this PR is changing.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/worker/subscriptionsync/service/sync_credittheninvoice_test.go` around lines 3728 - 3788, The test currently verifies charge-side effects after UpdateStandardInvoice but does not assert that editedInvoice preserved the edited invoice line fields. Add assertions that look up the line in editedInvoice by updatedLine.ID and confirm its Period, TaxConfig, and ManagedBy match the values set in the EditFn. Use the existing editedInvoice, updatedLine, and UpdateStandardInvoice flow to locate the invoice line and validate the invoice API behavior directly.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 @.agents/skills/charges/SKILL.md:
- Around line 198-199: The manual-edit guidance in the flat-fee line engine is
too absolute about emitting exactly one invoice patch, which does not match the
immutable-run path. Update the `ManualEdit` and related guidance to distinguish
the contracts: pending or mutable lines use a single upsert/update patch, while
immutable current runs delete the old standard line and create a replacement
gathering line. Make the wording in the `SKILL.md` guidance align with the
`ManualEdit` state-machine behavior and avoid implying a single invoice patch
for every case.
In `@openmeter/billing/charges/flatfee/service/manualedit.go`:
- Around line 20-26: The manual override branch in setManualOverrideIntent only
mutates s.Charge.Intent in memory, so later edits are not persisted when an
override row already exists. Update this path to write the changed override
fields back through the override-specific adapter/repository path, using the
existing override layer handling in CreditThenInvoiceStateMachine and the intent
mutation on flatfee.IntentMutableFields, so the override row is saved as well as
the in-memory state.
In `@openmeter/billing/gatheringinvoice.go`:
- Around line 689-696: The merge path in gatheringinvoice.go is copying
persisted identity fields from the target line into merged, but
GatheredInvoiceLine’s SplitLineHierarchy is omitted, so existing split hierarchy
metadata can be lost during updates. Update the merge logic in the same block
that assigns Namespace, ID, CreatedAt, and the other identity fields to also
carry over SplitLineHierarchy from the receiver so split gathering lines keep
their hierarchy when target state is merged.
---
Nitpick comments:
In `@openmeter/billing/charges/usagebased/service/creditheninvoice.go`:
- Around line 360-375: The new extend-path logic in remainingGatheringLinePeriod
is not covered by a focused test, especially the IsVoidedBillingHistory() skip
and the final Truncate(streaming.MinimumWindowSizeDuration) behavior. Add a
targeted ExtendCharge test in the existing creditheninvoice service tests that
exercises a charge with mixed realized and voided runs, verifies the pending
gathering line advances to the expected period, and confirms the voided run is
ignored.
In
`@openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go`:
- Around line 3728-3788: The test currently verifies charge-side effects after
UpdateStandardInvoice but does not assert that editedInvoice preserved the
edited invoice line fields. Add assertions that look up the line in
editedInvoice by updatedLine.ID and confirm its Period, TaxConfig, and ManagedBy
match the values set in the EditFn. Use the existing editedInvoice, updatedLine,
and UpdateStandardInvoice flow to locate the invoice line and validate the
invoice API behavior directly.
🪄 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: d2d00f8c-1b53-41f8-a2d4-4a8873ba9d79
📒 Files selected for processing (19)
.agents/skills/charges/SKILL.mdAGENTS.mdopenmeter/billing/charges/flatfee/service/creditheninvoice.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/manualedit.goopenmeter/billing/charges/invoiceupdater/invoiceupdate.goopenmeter/billing/charges/invoiceupdater/patch.goopenmeter/billing/charges/meta/patch.goopenmeter/billing/charges/meta/triggers.goopenmeter/billing/charges/usagebased/service/create.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditheninvoice_test.goopenmeter/billing/errors.goopenmeter/billing/gatheringinvoice.goopenmeter/billing/invoiceline.goopenmeter/billing/service/invoiceupdate.goopenmeter/billing/stdinvoiceline.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.gotest/credits/credit_then_invoice_test.go
|
@coderabbitai please read the repository review configuration and try again. In particular, re-check the existing override update path before flagging “in-memory only” behavior: flatfee adapter Last chance to provide meaningful, verified comments here, otherwise we will remove CodeRabbit from this repository. |
🧩 Analysis chain🏁 Script executed: #!/bin/bash
set -euo pipefail
echo "== Candidate review config / instruction files =="
fd -HI '(^|/)(\.coderabbit\.ya?ml|coderabbit\.ya?ml|AGENTS\.md|\.github/.*coderabbit.*|.*review.*instructions.*)$' .
echo
echo "== AGENTS.md outline / relevant sections =="
if [ -f AGENTS.md ]; then
nl -ba AGENTS.md | sed -n '1,260p'
fi
echo
echo "== Search for flatfee UpdateCharge and override persistence symbols =="
rg -n -C3 --type=go '\bfunc\s*\(.*\)\s*UpdateCharge\s*\(|\bupdateIntentOverride\s*\(|\bGetOverrideLayerMutableFields\s*\(' openmeter
echo
echo "== Locate flatfee adapter/service files =="
fd -p 'flatfee' openmeter/billing/charges
echo
echo "== AST outline for likely adapter file(s) =="
for f in $(fd -p 'adapter.go' openmeter/billing/charges/flatfee || true); do
echo "-- $f --"
ast-grep outline "$f" --view expanded || true
done
echo
echo "== Read flatfee adapter around UpdateCharge / updateIntentOverride =="
for f in $(rg -l --type=go '\bfunc\s*\(.*\)\s*UpdateCharge\s*\(' openmeter/billing/charges/flatfee); do
echo "-- FILE: $f --"
nl -ba "$f" | sed -n '1,260p'
done
for f in $(rg -l --type=go '\bupdateIntentOverride\s*\(' openmeter/billing/charges/flatfee); do
echo "-- FILE: $f --"
nl -ba "$f" | sed -n '1,260p'
done
echo
echo "== Read intent override accessors / interface =="
for f in $(rg -l --type=go '\bGetOverrideLayerMutableFields\s*\(' openmeter/billing); do
echo "-- FILE: $f --"
nl -ba "$f" | sed -n '1,220p'
doneLength of output: 1989 🏁 Script executed: #!/bin/bash
set -euo pipefail
echo "== .coderabbit.yaml =="
if [ -f .coderabbit.yaml ]; then
sed -n '1,260p' .coderabbit.yaml
fi
echo
echo "== AGENTS.md =="
if [ -f AGENTS.md ]; then
awk '{printf("%6d %s\n", NR, $0)}' AGENTS.md | sed -n '1,260p'
fi
echo
echo "== api/spec/AGENTS.md =="
if [ -f api/spec/AGENTS.md ]; then
awk '{printf("%6d %s\n", NR, $0)}' api/spec/AGENTS.md | sed -n '1,220p'
fi
echo
echo "== Search for UpdateCharge / updateIntentOverride / GetOverrideLayerMutableFields =="
rg -n -C4 --type=go '\bfunc\s*\(.*\)\s*UpdateCharge\s*\(|\bupdateIntentOverride\s*\(|\bGetOverrideLayerMutableFields\s*\(' openmeter/billing
echo
echo "== Flatfee files containing UpdateCharge =="
for f in $(rg -l --type=go '\bfunc\s*\(.*\)\s*UpdateCharge\s*\(' openmeter/billing/charges/flatfee); do
echo "-- FILE: $f --"
awk '{printf("%6d %s\n", NR, $0)}' "$f" | sed -n '1,260p'
done
echo
echo "== Files containing updateIntentOverride =="
for f in $(rg -l --type=go '\bupdateIntentOverride\s*\(' openmeter/billing/charges/flatfee openmeter/billing); do
echo "-- FILE: $f --"
awk '{printf("%6d %s\n", NR, $0)}' "$f" | sed -n '1,260p'
done
echo
echo "== Files containing GetOverrideLayerMutableFields =="
for f in $(rg -l --type=go '\bGetOverrideLayerMutableFields\s*\(' openmeter/billing); do
echo "-- FILE: $f --"
awk '{printf("%6d %s\n", NR, $0)}' "$f" | sed -n '1,240p'
doneLength of output: 226711
I re-checked both the repo review config and the current code path:
So that prior concern should be withdrawn. I’ll re-review this PR from the current code and repo instructions, and I’ll keep future comments limited to verified paths. (╥﹏╥)🐇 ✏️ Learnings added
✅ Action performedFull review finished. |
219153e to
2b22668
Compare
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
test/credits/credit_then_invoice_test.go (1)
2861-2875: 🎯 Functional Correctness | 🟡 MinorAssert that the extension path preserves the gathering line ID.
Nice touch updating the comment to say "updated in place." Just add a direct ID comparison to seal the deal:
s.Equal(firstGatheringLine, activeLine.ID)This ensures the test actually verifies the line identity wasn't swapped out, matching the intent of the updated comment. Quick
go vetandgo testafter dropping that in!🤖 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/credits/credit_then_invoice_test.go` around lines 2861 - 2875, The extension test for the charge/invoice flow is missing an explicit identity check for the active gathering line, so it only verifies fields but not that the same line was preserved. In the s.Run("when the charge is extended before collection") case in credit_then_invoice_test.go, add a direct assertion comparing the original gathering line identifier (firstGatheringLine) to activeLine.ID after calling mustSingleActiveGatheringLineForCharge, so the test confirms the line was updated in place rather than replaced.
🧹 Nitpick comments (1)
test/credits/credit_then_invoice_test.go (1)
2737-2851: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRename the test to match the new in-place behavior.
The body now asserts the pending gathering line keeps the same ID, but the test name still says it “Replaces” the line.
Suggested patch
-func (s *CreditThenInvoiceTestSuite) TestFlatFeeCreditThenInvoiceShrinkExtendPatchReplacesPendingGatheringLineWithProratedAmount() { +func (s *CreditThenInvoiceTestSuite) TestFlatFeeCreditThenInvoiceShrinkExtendPatchUpdatesPendingGatheringLineInPlaceWithProratedAmount() {As per path instructions, “In general when reviewing the Golang code make readability and maintainability a priority.”
🤖 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/credits/credit_then_invoice_test.go` around lines 2737 - 2851, The test name is inconsistent with the updated assertions in TestFlatFeeCreditThenInvoiceShrinkExtendPatchReplacesPendingGatheringLineWithProratedAmount, which now verify the pending gathering line is updated in place and keeps the same ID. Rename this test function to reflect the in-place behavior, and keep the body as-is since it already checks firstGatheringLine matches the active line after the patch.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 @.agents/skills/charges/SKILL.md:
- Around line 198-199: Scope the “returns the merged line” statement in the
flat-fee API invoice-line edit guidance to update/upsert cases only. The current
wording in the ManualEdit flow is too broad because the zero-proration
pending-gathering path still emits a delete-by-charge patch, and the line engine
surfaces the existing validation error rather than a merged line. Update the
wording near the ManualEdit/state-machine guidance to distinguish merge behavior
for upserts from delete-by-charge handling, while keeping the references to the
flat-fee line engine and invoice patch behavior accurate.
In `@openmeter/billing/charges/flatfee/service/creditheninvoice.go`:
- Around line 254-266: The manual edit flow in creditheninvoice.go currently
accepts any CurrentRun in the charge realization state, but immutable runs must
be rejected before applying the override intent. Update the validation around
s.Charge.Realizations.CurrentRun to short-circuit when the run is immutable,
alongside the existing line and invoice attachment checks, so the edit path only
proceeds for mutable standard-line runs and avoids later reconciliation
mismatches.
In `@openmeter/billing/charges/usagebased/service/creditheninvoice_test.go`:
- Around line 183-187: The test in TestShrinkChargeMovesToAwaitingInvoice is
missing coverage for the start of the upsert target window, so it could pass
even if TargetState.ServicePeriod still begins at the old date. Update the
assertions on the AsUpsertGatheringLineByChargeIDPatch result to also verify
TargetState.ServicePeriod.From equals currentRunEnd (the surviving run
boundary), alongside the existing ChargeID, ServicePeriod.To, and InvoiceAt
checks.
In `@openmeter/billing/charges/usagebased/service/creditheninvoice.go`:
- Around line 360-374: The new remaining-window helper in
remainingGatheringLinePeriod only normalizes the realization end timestamps,
which can leave the derived period with inconsistent bounds. Update
remainingGatheringLinePeriod to normalize both the effective service period
bounds from charge.Intent.GetEffectiveServicePeriod and the realization
boundaries before comparing and truncating, matching the normalization approach
used by handleRunsOnShrink. Keep the fix localized to
remainingGatheringLinePeriod and use the existing meta.NormalizeTimestamp and
timeutil.ClosedPeriod flow so the upsert target gets consistent timestamps.
In `@openmeter/billing/stdinvoiceline.go`:
- Around line 282-290: The merge logic in the standard invoice line update path
is dropping the standard line’s split hierarchy, which can detach existing split
lines on update. In the merge code that sets fields on merged (including the
DetailedLinesWithIDReuse call), also preserve SplitLineHierarchy from the source
invoice line i so rebuilt targets keep the existing split structure. Use the
standard line merge/update logic around merged and DetailedLinesWithIDReuse to
make the fix.
---
Outside diff comments:
In `@test/credits/credit_then_invoice_test.go`:
- Around line 2861-2875: The extension test for the charge/invoice flow is
missing an explicit identity check for the active gathering line, so it only
verifies fields but not that the same line was preserved. In the s.Run("when the
charge is extended before collection") case in credit_then_invoice_test.go, add
a direct assertion comparing the original gathering line identifier
(firstGatheringLine) to activeLine.ID after calling
mustSingleActiveGatheringLineForCharge, so the test confirms the line was
updated in place rather than replaced.
---
Nitpick comments:
In `@test/credits/credit_then_invoice_test.go`:
- Around line 2737-2851: The test name is inconsistent with the updated
assertions in
TestFlatFeeCreditThenInvoiceShrinkExtendPatchReplacesPendingGatheringLineWithProratedAmount,
which now verify the pending gathering line is updated in place and keeps the
same ID. Rename this test function to reflect the in-place behavior, and keep
the body as-is since it already checks firstGatheringLine matches the active
line after the patch.
🪄 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: 2255c809-699f-4ab8-94a1-79433d1e5cf3
📒 Files selected for processing (19)
.agents/skills/charges/SKILL.mdAGENTS.mdopenmeter/billing/charges/flatfee/service/creditheninvoice.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/manualedit.goopenmeter/billing/charges/invoiceupdater/invoiceupdate.goopenmeter/billing/charges/invoiceupdater/patch.goopenmeter/billing/charges/meta/patch.goopenmeter/billing/charges/meta/triggers.goopenmeter/billing/charges/usagebased/service/create.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditheninvoice_test.goopenmeter/billing/errors.goopenmeter/billing/gatheringinvoice.goopenmeter/billing/invoiceline.goopenmeter/billing/service/invoiceupdate.goopenmeter/billing/stdinvoiceline.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.gotest/credits/credit_then_invoice_test.go
There was a problem hiding this comment.
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/charges/usagebased/service/creditheninvoice_test.go`:
- Around line 215-217: The current assertion only verifies the patch op from
InvoicePatches() in creditheninvoice_test.go, so a wrong ChargeID would still
pass. Update the test to decode the single patch returned by
machine.InvoicePatches() and assert that its target ChargeID matches the
expected charge for ExtendCharge, alongside the existing
PatchOpDeleteGatheringLineByChargeID check.
🪄 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: dff749cf-6ba6-4312-9fe2-9c86cf9d1b80
📒 Files selected for processing (4)
openmeter/billing/charges/flatfee/service/create.goopenmeter/billing/charges/flatfee/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditheninvoice_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- openmeter/billing/charges/flatfee/service/creditheninvoice.go
What changed
This PR teaches charge-backed flat-fee invoice lines how to accept manual API edits without giving ownership of the subscription-backed charge intent to the invoice layer.
Flat-fee credit-then-invoice charges now handle API edits through a
ManualEdittrigger. The state machine persists the edited customer-facing values into the charge override layer, keeps the subscription-owned base intent intact, and reconciles the charge realization or pending gathering line from the effective intent.The invoice updater now treats gathering-line updates by charge ID as target-state upserts. Instead of delete/create churn, charge reconciliation emits the full desired gathering line and billing merges that target state onto the existing invoice-line identity when one exists. This keeps pending gathering lines stable while still letting charge state remain the source of truth for price, tax, period, invoice date, and discounts.
Standard invoice edits are supported for mutable flat-fee realization runs as well. The realization is reconciled in place, existing line identity and detailed-line persistence state are preserved, and the edited draft invoice line is returned to billing for persistence.
Why it matters
Users can edit flat-fee charge-backed invoice lines from billing APIs while subscription sync continues to own the base subscription intent. Later subscription sync runs can change the base layer, for example after cancellation, without overwriting the manually overridden customer-facing invoice line.
This also closes the gap where pending gathering-line patching only carried period deltas. The patch contract now carries the full target line state, which is important for tax config, price changes, invoice-at changes, and future charge-owned line fields.
Rules encoded here
Coverage
The subscription-sync scenarios cover gathering-line manual edits, standard-invoice manual edits with partial promotional credit allocation, tax-code changes, resync preservation of overrides, and cancellation changing only the base intent while the override remains customer-facing.
Summary by CodeRabbit