Skip to content

feat: support flat fee gathering/standard line API edits - #4580

Merged
turip merged 5 commits into
mainfrom
feat/flat-fee-invoice-line-edits
Jun 27, 2026
Merged

turip merged 5 commits into
mainfrom
feat/flat-fee-invoice-line-edits

Conversation

@turip

@turip turip commented Jun 26, 2026 •

Copy link
Copy Markdown
Member

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 ManualEdit trigger. 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

  • API edits can update existing flat-fee charge-backed gathering lines and mutable standard invoice lines.
  • API create and delete for flat-fee charge-backed lines still return the existing charge-managed-line validation error.
  • Zero-amount manual edits are rejected with guidance to delete the line instead.
  • Subscription sync patches target the base intent; manual API edits target the override intent.
  • Gathering-line upserts preserve existing invoice-line identity when possible and create only when no pending line exists.

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

  • New Features
    • Enabled manual editing for flat-fee credit-then-invoice invoice lines (gathering and standard), including end-to-end manual-edit trigger handling and reconciliation.
  • Bug Fixes
    • Improved gathering-line reconciliation to use charge-ID upserts, preserving pending/in-flight lines and aligning shrink/extend updates with the correct service period and invoice attribution.
    • Manual edits that set an amount to zero now require deleting the line instead of applying an invalid update.
  • Documentation
    • Updated billing documentation for charge target-state patching, manual edit routing, and reconciliation rules.

@coderabbitai

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

Changes

Billing target-state patch flow

Layer / File(s) Summary
Target-state line contracts
openmeter/billing/invoiceline.go, openmeter/billing/gatheringinvoice.go, openmeter/billing/stdinvoiceline.go, openmeter/billing/charges/invoiceupdater/patch.go, openmeter/billing/charges/meta/*, openmeter/billing/errors.go, .agents/skills/charges/SKILL.md, AGENTS.md, openmeter/billing/charges/usagebased/service/create.go, openmeter/billing/charges/flatfee/service/create.go
GenericInvoiceLine gains WithTargetState, standard and gathering wrappers implement target-state merging, GenericInvoiceLineReader drops GetTaxConfig and GetInvoiceAt, gathering-line patches switch to charge-id upserts carrying full target state, and related guidance plus managed-by handling are updated.
Invoice patch resolution
openmeter/billing/service/invoiceupdate.go, openmeter/billing/charges/invoiceupdater/invoiceupdate.go
Invoice diffing now derives tax and invoice-at overrides from concrete line types, and invoice updater reconciliation merges gathering-line upserts by charge ID into existing or new lines.
Flat-fee manual edit flow
openmeter/billing/charges/flatfee/service/manualedit.go, openmeter/billing/charges/flatfee/service/creditheninvoice.go, openmeter/billing/charges/flatfee/service/lineengine.go, openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
Flat-fee manual edits now route through a manual-edit trigger, persist override intent changes, reconcile edited invoice lines back into the charge state machine, and validate the behavior in subscription sync tests.
Usage-based gathering-line updates
openmeter/billing/charges/usagebased/service/creditheninvoice.go, openmeter/billing/charges/usagebased/service/creditheninvoice_test.go, test/credits/credit_then_invoice_test.go
Usage-based ExtendCharge and handleRunsOnShrink now emit target-state gathering-line upserts or deletes, with tests updated to assert the new patch behavior and in-place line retention.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • openmeterio/openmeter#4300: Both PRs touch openmeter/billing/charges/invoiceupdater patch parsing and application for charge-id-based gathering-line handling.
  • openmeterio/openmeter#4552: Both PRs involve the invoice-line edit flow through the line-engine hook and manual-edit routing.
  • openmeterio/openmeter#4572: Both PRs are tied to flat-fee charge intent override layering and manual-edit persistence behavior.

Suggested labels

release-note/feature, area/billing

Suggested reviewers

  • tothandras
🚥 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 API edit support for flat-fee gathering and standard invoice lines.
✨ 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-invoice-line-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.

@greptile-apps

greptile-apps Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds manual API edits for flat-fee charge-backed invoice lines. The main changes are:

  • Flat-fee credit-then-invoice edits now flow through a manual edit trigger.
  • Charge override intent state now stores edited customer-facing values.
  • Gathering-line charge updates now use full target-state upserts.
  • Existing pending and draft line identity is preserved during reconciliation.

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/lineengine.go Routes flat-fee manual invoice-line edits through the charge state machine and merges the resulting target state onto the existing line identity.
openmeter/billing/charges/flatfee/service/manualedit.go Adds override intent creation and mutable-field extraction for flat-fee manual edits.
openmeter/billing/charges/invoiceupdater/invoiceupdate.go Applies gathering-line updates by charge ID as target-state upserts against pending invoice lines.
openmeter/billing/gatheringinvoice.go Adds target-state merging for gathering lines while keeping persisted identity and invoice membership.
openmeter/billing/stdinvoiceline.go Adds target-state merging for standard lines while preserving persistence fields and detailed-line IDs.
openmeter/billing/service/invoiceupdate.go Diffs tax config and invoice-at through concrete invoice-line accessors after narrowing the generic reader interface.

Reviews (7): Last reviewed commit: "test(billing): assert usage based delete..." | Re-trigger Greptile

@turip
turip force-pushed the feat/flat-fee-invoice-line-edits branch from 71d086a to cc4f1fa Compare June 26, 2026 10:59
@turip
turip marked this pull request as ready for review June 26, 2026 16:54
@turip
turip requested a review from a team as a code owner June 26, 2026 16:54
@turip turip added the release-note/feature Release note: Exciting New Features label Jun 26, 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: 3

🧹 Nitpick comments (2)
openmeter/billing/charges/usagebased/service/creditheninvoice.go (1)

360-375: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Please 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 final Truncate(...). The changed test surface only exercises the shrink upsert path, so a small ExtendCharge case 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 win

Please 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 editedInvoice actually kept the line’s edited period / tax config / management mode. A quick lookup by updatedLine.ID would 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

📥 Commits

Reviewing files that changed from the base of the PR and between f7eb03a and 219153e.

📒 Files selected for processing (19)
  • .agents/skills/charges/SKILL.md
  • AGENTS.md
  • 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/invoiceupdate.go
  • openmeter/billing/charges/invoiceupdater/patch.go
  • openmeter/billing/charges/meta/patch.go
  • openmeter/billing/charges/meta/triggers.go
  • openmeter/billing/charges/usagebased/service/create.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice_test.go
  • openmeter/billing/errors.go
  • openmeter/billing/gatheringinvoice.go
  • openmeter/billing/invoiceline.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/stdinvoiceline.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • test/credits/credit_then_invoice_test.go

Comment thread openmeter/billing/gatheringinvoice.go Resolved
@turip

turip commented Jun 26, 2026

Copy link
Copy Markdown
Member Author

@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 UpdateCharge persists an existing override layer via updateIntentOverride when charge.Intent.GetOverrideLayerMutableFields() is present.

Last chance to provide meaningful, verified comments here, otherwise we will remove CodeRabbit from this repository.

@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor
🧩 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'
done

Length 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'
done

Length of output: 226711



@turip You were right — my earlier “in-memory only” comment was incorrect. Sorry.

I re-checked both the repo review config and the current code path:

  • .coderabbit.yaml explicitly says not to claim a mutation is unpersisted until the full persistence flow is traced, and not to post findings based on prior memory without re-verifying.
  • In openmeter/billing/charges/flatfee/adapter/charge.go, UpdateCharge(...) persists the base row first, then on Line 84–90 it calls tx.updateIntentOverride(ctx, charge.GetChargeID(), overrideLayer) when charge.Intent.GetOverrideLayerMutableFields() is present.
  • In openmeter/billing/charges/flatfee/adapter/intentoverride.go, updateIntentOverride(...) on Line 171–229 performs the actual ChargeFlatFeeOverride DB update, including tax fields, periods, invoice-at, feature key, and discounts.
  • The behavior is covered in openmeter/billing/charges/flatfee/adapter/intentoverride_test.go: updating without an existing override fails, and updating an existing override is persisted and then observable on subsequent fetches.

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
Learnt from: turip
URL: https://github.com/openmeterio/openmeter/pull/4580

Timestamp: 2026-06-26T17:13:29.505Z
Learning: In this repository, `.coderabbit.yaml` contains a path instruction for `openmeter/billing/charges/**/service/*.go` that forbids claiming a mutation is "only in memory" unless the full persistence path has been traced in reachable current code; findings must be re-verified against the current code and domain model rather than prior review memory.

Learnt from: turip
URL: https://github.com/openmeterio/openmeter/pull/4580

Timestamp: 2026-06-26T17:13:29.505Z
Learning: In `openmeter/billing/charges/flatfee/adapter/charge.go`, `(*adapter).UpdateCharge` persists an existing flat-fee override layer by calling `tx.updateIntentOverride(ctx, charge.GetChargeID(), overrideLayer)` when `charge.Intent.GetOverrideLayerMutableFields()` is non-nil, and `openmeter/billing/charges/flatfee/adapter/intentoverride.go` persists that override through an Ent update of `ChargeFlatFeeOverride`.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

✅ Action performed

Full review finished.

@turip
turip force-pushed the feat/flat-fee-invoice-line-edits branch from 219153e to 2b22668 Compare June 26, 2026 17:20

@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: 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 | 🟡 Minor

Assert 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 vet and go test after 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 win

Rename 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

📥 Commits

Reviewing files that changed from the base of the PR and between f7eb03a and 219153e.

📒 Files selected for processing (19)
  • .agents/skills/charges/SKILL.md
  • AGENTS.md
  • 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/invoiceupdate.go
  • openmeter/billing/charges/invoiceupdater/patch.go
  • openmeter/billing/charges/meta/patch.go
  • openmeter/billing/charges/meta/triggers.go
  • openmeter/billing/charges/usagebased/service/create.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice_test.go
  • openmeter/billing/errors.go
  • openmeter/billing/gatheringinvoice.go
  • openmeter/billing/invoiceline.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/stdinvoiceline.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • test/credits/credit_then_invoice_test.go

Comment thread .agents/skills/charges/SKILL.md Resolved
Comment thread openmeter/billing/stdinvoiceline.go Resolved

@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/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

📥 Commits

Reviewing files that changed from the base of the PR and between 2b22668 and f5e5de6.

📒 Files selected for processing (4)
  • openmeter/billing/charges/flatfee/service/create.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/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

@turip turip changed the title Support flat fee gathering line API edits featSupport flat fee gathering line API edits Jun 27, 2026
@turip turip changed the title featSupport flat fee gathering line API edits feat: support flat fee gathering/standard line API edits Jun 27, 2026
@turip
turip merged commit a6eaf64 into main Jun 27, 2026
26 checks passed
@turip
turip deleted the feat/flat-fee-invoice-line-edits branch June 27, 2026 08:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants