Skip to content

feat(credit_then_invoice): flat fee shrink/expand - #4357

Merged
turip merged 5 commits into
mainfrom
feat/flat-fee-shrink-extend
May 14, 2026
Merged

turip merged 5 commits into
mainfrom
feat/flat-fee-shrink-extend

Conversation

@turip

@turip turip commented May 13, 2026 •

Copy link
Copy Markdown
Member

Adds native shrink and extend handling for flat-fee credit-then-invoice charges.

  • Mutable draft standard lines are updated in place while preserving the active run.
  • Immutable invoice-backed runs keep existing invoice and ledger history, then create replacement gathering lines for changed periods.
  • Detached historical runs can still receive asynchronous payment callbacks while the replacement current run continues to final state independently.
  • No-fiat flat-fee invoices avoid fiat payment booking, and zero-total invoice lines avoid invoice usage accrual.

Summary by CodeRabbit

  • New Features

    • Extend/shrink flat-fee charges and create/manage per-charge realization runs; invoice-accrual and run-start flows for credit-then-invoice.
    • Structured payment event inputs for clearer payment lifecycle handling.
  • Enhancements

    • Immutable runs and explicit no-fiat run handling to control mutability and payment requirements.
    • Run-scoped detailed lines, credit allocations and payments with stronger validation and clearer errors.
  • Tests

    • Added unit/integration tests covering realization run lifecycle, payment totals, and end-to-end credit-then-invoice scenarios.

@turip
turip requested a review from a team as a code owner May 13, 2026 18:39
@coderabbitai

coderabbitai Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

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: 177fb858-ca89-4074-9605-f1f725f687e4

📥 Commits

Reviewing files that changed from the base of the PR and between d76952c and 2ff883e.

📒 Files selected for processing (3)
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/charges/service/invoicable_test.go
  • test/billing/suite.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/billing/charges/service/invoicable_test.go

📝 Walkthrough

Walkthrough

Restructures flat‑fee billing around realization runs: adapters, service flows, and handlers are run‑scoped (use RealizationRunID), runs gain an Immutable flag, InvoiceOnlySettlementMode removed, state machines and realization services refactored, DB migration added, and many tests updated/added.

Changes

Adapter & API surface

Layer / File(s) Summary
Adapter interfaces & inputs
openmeter/billing/charges/flatfee/adapter.go
Top-level Adapter now embeds a new ChargeRunAdapter. ChargeAdapter adds Update/Delete/Get methods. Detailed-line, credit-allocation, payment, and invoiced-usage adapter methods switch to RealizationRunID. CreateCurrentRunInput replaces prior provisioning/assignment inputs and adds service period, amount-after-proration, immutability, optional LineID/InvoiceID, and validation.
Realization run shapes
openmeter/billing/charges/flatfee/realizationrun.go
Added UpdateRealizationRunInput with Normalized()/Validate(). RealizationRunBase now includes Immutable bool.
Invoiced-usage input validation
openmeter/billing/charges/flatfee/adapter.go
CreateInvoicedUsageInput now references RunID and its Validate() aggregates/wraps InvoicedUsage validation errors.

Run‑scoped adapter implementations

Layer / File(s) Summary
Create/attach/detach run
openmeter/billing/charges/flatfee/adapter/realizationrun.go, .../realizationrun_test.go
CreateCurrentRun transactionally creates ChargeFlatFeeRun, sets Charge.CurrentRealizationRunID (errors if already set). UpdateRealizationRun conditionally updates persisted fields. DetachCurrentRun clears charge reference. Tests added.
Detailed lines & credits
openmeter/billing/charges/flatfee/adapter/detailedline.go, .../detailedline_test.go, .../credits.go
UpsertDetailedLines now scoped by RealizationRunID. CreateCreditAllocations validates runID, ensures the run exists, and persists run‑scoped credit allocations. Removed legacy credit-only run totals helper. Tests adjusted to use run IDs.
Payments & invoiced usage
openmeter/billing/charges/flatfee/adapter/payment.go, .../usage.go
CreatePayment and CreateInvoicedUsage accept RunID, validate it, persist run‑scoped payments/usages, and wrap errors with run context.
Mapping & lookup
openmeter/billing/charges/flatfee/adapter/mapper.go, openmeter/billing/charges/flatfee/charge.go
DB→model mapping now copies immutable flag. Added Realizations.GetByLineID() to locate a realization run by invoice line across current/prior runs.

Realizations orchestration and rating

Layer / File(s) Summary
Service wiring & rating
openmeter/billing/charges/flatfee/service/realizations/service.go
Realizations service requires a rating.Service in config; New() wires it. Added internal createCreditAllocations helper that calls adapter with runID.
Start run (credit→invoice)
openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go
StartCreditThenInvoiceRun validates input, creates current run, optionally invokes handler to obtain credit allocations, generates detailed lines using the rating service, upserts detailed lines for the run, updates run totals, and returns the run.
Accrue invoice usage
openmeter/billing/charges/flatfee/service/realizations/invoiceaccrued.go
AccrueInvoiceUsage validates current-run and line/invoice consistency, calls handler when line totals non-zero, persists AccruedUsage via adapter using RunID, and marks the run immutable.
Credits-only / corrections
openmeter/billing/charges/flatfee/service/realizations/creditsonly.go, .../correct.go
Added AllocateCreditsOnly (rounding/validation, handler call, strict allocation-sum equality, adapter creation, run totals update) and CorrectAllCredits (validation, lineage loading, correction orchestration, creating allocations when corrections exist).

Service & state-machine refactor

Layer / File(s) Summary
Credit‑then‑invoice state machine & patch flows
openmeter/billing/charges/flatfee/service/creditheninvoice.go
State wiring extended for realization lifecycle; StartRealization delegates to Realizations service; added ExtendCharge/ShrinkCharge; DeleteCharge detaches run, moves it to prior runs when appropriate; generateInvoicePatches handles mutable vs immutable runs and proration-driven reissuance.
Line engine & linemapper
openmeter/billing/charges/flatfee/service/lineengine.go, .../linemapper.go
OnStandardInvoiceCreated now requires a current run and populates standard lines from run data. Removed CalculateLines. Added mapping helpers to convert/validate detailed lines and totals; run‑centric deletion and unsupported-credit-note handling implemented.
Create flow & gathering line builder
openmeter/billing/charges/flatfee/service/create.go
Charge creation simplified: initial status/advance logic unified; gathering line built via buildFlatFeeGatheringLine which enforces credit_then_invoice, recalculates post‑proration amounts, validates inputs, and constructs the gathering line.

Payment lifecycle and ledger integration

Layer / File(s) Summary
Handler types & signatures
openmeter/billing/charges/flatfee/handler.go
Introduced PaymentEventInput (Charge, Amount) with Validate(). OnPaymentAuthorized/OnPaymentSettled now accept these input types.
Service payment handling
openmeter/billing/charges/flatfee/service/payment.go, .../payment_test.go
Payment handlers fetch run by line ID (via Realizations.GetByLineID), validate run/line/invoice consistency, compute payment amount via getPaymentTotal, create run‑scoped payment via adapter, and call handler with explicit amount. Added unit tests for getPaymentTotal and helpers validatePaymentRunForLine/getPaymentTotal.
Ledger adapter updates
openmeter/ledger/chargeadapter/flatfee.go, .../flatfee_test.go
Ledger handlers now accept OnPayment*Input, validate and short‑circuit on zero amounts, and book using clock.Now() with input.Amount. Tests updated for deterministic timestamps and new helpers.

Settlement modes, patch typing, schema, migrations, tests

Layer / File(s) Summary
Settlement mode removal
openmeter/productcatalog/settlementmode.go, various handlers/tests
Removed InvoiceOnlySettlementMode. Handlers and prechecks updated to accept only credit‑based settlement modes. Test fixtures default settlement mode changed to CreditThenInvoiceSettlementMode.
Patch typing
openmeter/billing/charges/meta/patch.go, .../patch*.go
Added PatchType (extend, shrink, delete) and Op() PatchType on Patch interface; implemented on existing patch types.
DB schema & migrations
openmeter/ent/schema/chargesflatfee.go, tools/migrate/migrations/*_add_flat_fee_run_immutable.*.sql
Added immutable boolean column to charge_flat_fee_runs, backfilled false and set NOT NULL; down migration removes it.
Tests & fixtures
test/*, openmeter/billing/charges/*_test.go, openmeter/billing/charges/testutils/*
Extensive test updates/additions across invoicable flows, credit‑then‑invoice scenarios, payment callbacks, adapter/unit tests, and migration-aware assertions. Added helpers (newPaymentEventInput, transactionBookedAtTimes, assertFlatFeeCreditThenInvoiceLineAndRun). Test helpers now default to CreditThenInvoiceSettlementMode.

Sequence Diagram(s)

sequenceDiagram
    participant SM as StateMachine<br/>(CreditThenInvoice)
    participant SVC as Realizations<br/>Service
    participant ADP as Adapter
    participant DB as Database
    participant HND as Handler<br/>(Ledger)

    SM->>SVC: StartCreditThenInvoiceRun(charge, line, invoice)
    activate SVC
    SVC->>ADP: CreateCurrentRun(input)
    activate ADP
    ADP->>DB: INSERT ChargeFlatFeeRun
    ADP->>DB: UPDATE Charge.CurrentRealizationRunID
    ADP-->>SVC: RealizationRunBase
    deactivate ADP

    SVC->>HND: OnAssignedToInvoice(charge, line, invoice)
    activate HND
    HND-->>SVC: CreditAllocations
    deactivate HND

    SVC->>ADP: CreateCreditAllocations(runID, allocations)
    activate ADP
    ADP->>DB: INSERT ChargeFlatFeeRunCreditAllocations
    ADP-->>SVC: Realizations
    deactivate ADP

    SVC->>ADP: UpsertDetailedLines(runID, lines)
    activate ADP
    ADP->>DB: UPSERT ChargeFlatFeeRunDetailedLines
    ADP-->>SVC: (ok)
    deactivate ADP

    SVC->>ADP: UpdateRealizationRun(input)
    activate ADP
    ADP->>DB: UPDATE ChargeFlatFeeRun totals/flags
    ADP-->>SVC: RealizationRunBase
    deactivate ADP

    SVC-->>SM: RealizationRun with credits, details, totals
    deactivate SVC
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

release-note/feature, area/billing

Suggested reviewers

  • tothandras
  • GAlexIHU
✨ 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-shrink-extend

@turip turip changed the title Flat fee credit-then-invoice shrink/extend feat(credit_then_invoice): flat fee shrink/expand May 13, 2026
@turip turip added the kind/feature New feature or request label May 13, 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: 7

Caution

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

⚠️ Outside diff range comments (2)
openmeter/billing/charges/service/advance_test.go (1)

133-162: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Make this test time-deterministic.

This test hard-codes March 1, 2026–April 1, 2026 but never sets the test clock, so behavior depends on when CI runs (for example, on May 13, 2026, that window is already past). That can flip state-transition outcomes and make this test flaky.

🕒 Suggested fix
 	servicePeriod := timeutil.ClosedPeriod{
 		From: datetime.MustParseTimeInLocation(s.T(), "2026-03-01T00:00:00Z", time.UTC).AsTime(),
 		To:   datetime.MustParseTimeInLocation(s.T(), "2026-04-01T00:00:00Z", time.UTC).AsTime(),
 	}
+
+	// Ensure deterministic transition timing.
+	clock.SetTime(servicePeriod.From.Add(-time.Second))
 
 	_, err := s.Charges.Create(ctx, charges.CreateInput{
 		Namespace: ns,
 		Intents: charges.ChargeIntents{
 			s.createMockChargeIntent(createMockChargeIntentInput{
@@
 		},
 	})
 	s.NoError(err)
+
+	clock.SetTime(servicePeriod.From)
 
 	advancedCharges, err := s.Charges.AdvanceCharges(ctx, charges.AdvanceChargesInput{
 		Customer: cust.GetID(),
 	})
🤖 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/service/advance_test.go` around lines 133 - 162,
The test uses a fixed servicePeriod (datetime.MustParseTimeInLocation for
2026-03-01 to 2026-04-01) but never fixes the test clock, making AdvanceCharges
behavior time-dependent; before creating the charge and calling
s.Charges.AdvanceCharges, set the test clock to a deterministic instant inside
that window (e.g. 2026-03-15T00:00:00Z) using the test suite's clock helper
(e.g. s.SetClock / s.Clock = testclock.New / ctx = testclock.WithContext) or by
injecting a fixed clock into the context passed to s.Charges.Create and
s.Charges.AdvanceCharges so the AdvanceCharges call runs with a known current
time. Ensure the clock is restored/controlled for the rest of the test.
openmeter/billing/charges/flatfee/adapter/realizationrun.go (1)

22-62: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Consider adding ForUpdate() for additional defensive protection against concurrent updates.

The read → check → create → update pattern here doesn't have explicit row-level locking, but concurrent invocations for the same charge are already serialized upstream via the charge locker (acquired in withLockedCharge()). That said, adding .ForUpdate() on the initial query (line 23) would make the lock-free guarantee more explicit at the database level and defensively prevent any future refactoring that bypasses the service-layer lock. It's not a correctness issue now, but small detail worth considering for robustness.

🤖 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/adapter/realizationrun.go` around lines 22
- 62, The initial charge lookup in the transaction (inside the
entutils.TransactingRepo closure) should acquire a row lock to defend against
concurrent updates: update the query built in the adapter closure that calls
tx.db.ChargeFlatFee.Query().Where(...).Only(ctx) to include a ForUpdate() call
(i.e., tx.db.ChargeFlatFee.Query().Where(...).ForUpdate()...Only(ctx)) so the
read→check→create→update sequence in realizationrun creation (functions/methods
involving ChargeFlatFee.Query, ChargeFlatFeeRun.Create and UpdateOneID) holds a
DB-level row lock.
🧹 Nitpick comments (9)
openmeter/billing/worker/subscriptionsync/service/reconciler/patch_test.go (1)

43-70: ⚡ Quick win

Remove or repurpose the duplicated test case.

These two cases are effectively the same (CreditThenInvoiceSettlementMode, enableCredits: true, enableCreditThenInvoice: false), and they also share the same name. Keeping both is redundant and can hide a missing branch you might have intended to cover.

♻️ Quick cleanup option
-		{
-			name:               "credit then invoice disabled stays on invoice lines",
-			settlementMode:     productcatalog.CreditThenInvoiceSettlementMode,
-			enableCredits:      true,
-			rateCard:           flatRateCard,
-			expectedCollection: &lineInvoicePatchCollection{},
-		},
🤖 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/reconciler/patch_test.go`
around lines 43 - 70, Two identical test entries in patch_test.go both named
"credit then invoice disabled stays on invoice lines" use
productcatalog.CreditThenInvoiceSettlementMode with enableCredits: true and
enableCreditThenInvoice: false; remove one of these duplicate cases or modify it
to exercise the missing branch (e.g., change enableCreditThenInvoice to true or
swap to a different settlementMode/rateCard) so each test in the table is
unique; update any related expectedCollection (lineInvoicePatchCollection,
flatFeeChargeCollection, usageBasedChargeCollection) to match the altered
scenario and keep the remaining tests' names distinct.
openmeter/billing/charges/service/invoicable_test.go (3)

699-711: ⚖️ Poor tradeoff

Calling lineEngine.OnCollectionCompleted / OnInvoiceIssued directly bypasses the public service flow.

This is the same pattern used in TestFlatFeeCreditThenInvoiceFullyCreditedDoesNotAccrueInvoiceUsage (just below in the file), so it's not novel, but per the guideline "prefer driving behavior through charges.Service.Create, AdvanceCharges, and ApplyPatches" — going through BillingService.ApproveInvoice (as your other new test does) keeps the test in lockstep with the actual orchestration the user-facing API uses, including any future hooks the engine gains. Optional.

As per coding guidelines: "For usage-based billing lifecycle tests, prefer driving behavior through charges.Service.Create, AdvanceCharges, and ApplyPatches rather than calling lower-level charge adapters directly."

🤖 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/service/invoicable_test.go` around lines 699 - 711,
The test is calling the charge adapter methods lineEngine.OnCollectionCompleted
and lineEngine.OnInvoiceIssued directly, which bypasses the public
orchestration; change the test to drive the same behavior through the public
service flow by invoking charges.Service.Create (or creating the charge via the
public API), then use charges.Service.AdvanceCharges and ApplyPatches (or call
BillingService.ApproveInvoice as your other test does) to progress the invoice
lifecycle so the adapter is exercised indirectly; ensure you remove the direct
calls to lineEngine.OnCollectionCompleted and lineEngine.OnInvoiceIssued and
instead assert results after the service-level calls.

2561-2620: ⚡ Quick win

Helper name says generic, implementation is hard-coded to 5 credits.

assertFlatFeeCreditThenInvoiceLineAndRun looks reusable but bakes float64(5) into the CreditsApplied assertions (lines 2570, 2577, 2588, 2606). That's fine for the two tests added now, but the name suggests it'll be reached for in future tests with different credit amounts. Either:

  • rename to assertFlatFeeCreditThenInvoiceLineAndRunWith5Credits, or
  • thread the expected credit amount through assertFlatFeeCreditThenInvoiceLineAndRunInput.
 type assertFlatFeeCreditThenInvoiceLineAndRunInput struct {
 	Invoice                       billing.StandardInvoice
 	FlatFeeChargeID               meta.ChargeID
 	ServicePeriod                 timeutil.ClosedPeriod
 	ExpectedTotals                billingtest.ExpectedTotals
+	ExpectedCreditsApplied        float64
 	ExpectAccruedUsage            bool
 	InvoiceUsageAccruedCallbackID string
 }
🤖 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/service/invoicable_test.go` around lines 2561 -
2620, The helper assertFlatFeeCreditThenInvoiceLineAndRun is hard-coded to
expect 5 credits; either rename it to indicate the fixed 5-credit behavior or
make it generic by adding an expected-credit field to the input and using that
everywhere—update the assertFlatFeeCreditThenInvoiceLineAndRunInput struct to
include ExpectedCreditAmount (type float64 or money.Decimal type used
elsewhere), replace all float64(5) assertions in
assertFlatFeeCreditThenInvoiceLineAndRun with comparisons to
input.ExpectedCreditAmount, and update every caller of
assertFlatFeeCreditThenInvoiceLineAndRun to pass the correct expected credit
amount (or if you choose rename, rename the function and update callers
accordingly).

689-697: 💤 Low value

Heads-up: manually rewriting Totals after InvoicePendingLines.

Overwriting lines[0].Totals (and each detailed line's Totals) in the test body to synthesize the "zero amount, non-zero charges" scenario works, but it bypasses whatever calc/validation flow the engine normally applies. If the totals model ever grows new fields (taxes, fees), this hand-rolled struct will silently miss them. A factory like newZeroAmountChargesTotals(amount, charges) or a helper that respects billingtotals.Totals invariants would make the intent clearer and survive future fields.

🤖 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/service/invoicable_test.go` around lines 689 - 697,
Replace the hand-constructed assignment of billingtotals.Totals with a single
factory/helper that builds totals respecting the model invariants (e.g.
newZeroAmountChargesTotals(amount, charges)); call this helper to set
lines[0].Totals and propagate it to each lines[0].DetailedLines[idx].Totals,
then reassign invoice.Lines via billing.NewStandardInvoiceLines(lines) as
before—this centralizes totals creation (instead of inline struct literal),
ensures future fields (taxes/fees) are populated, and keeps the test intent
clear; modify the test to import/define newZeroAmountChargesTotals and use
alpacadecimal.NewFromInt for the numeric args when creating the totals.
openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go (2)

19-49: 💤 Low value

Tiny suggestion: errors could carry the actual values.

The validation messages like "line charge id must match charge" and "line invoice id must match invoice" are clear, but including the offending IDs would make debugging much faster when this fires in the wild. Something like:

-		errs = append(errs, fmt.Errorf("line charge id must match charge"))
+		errs = append(errs, fmt.Errorf("line charge id %v does not match charge %s", i.Line.ChargeID, i.Charge.ID))

Optional nit.

🤖 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/realizations/credittheninvoice.go`
around lines 19 - 49, The Validate method on StartCreditThenInvoiceRunInput
should include the actual offending ID values in the two mismatch errors to aid
debugging: update the checks in StartCreditThenInvoiceRunInput.Validate that
currently append "line charge id must match charge" and "line invoice id must
match invoice" to instead format the message with the concrete values (e.g.,
include *i.Line.ChargeID and i.Charge.ID for the charge check, and
i.Line.InvoiceID and i.Invoice.ID for the invoice check) using fmt.Errorf to
produce something like "line charge id mismatch: got %v, want %v" and "line
invoice id mismatch: got %v, want %v" before returning via
models.NewNillableGenericValidationError.

112-114: 💤 Low value

Mutating handler-returned slice in place — confirm it's OK.

You're writing LineID directly into the slice the handler returned. If any handler caches or reuses that allocation slice across calls, this would leak the LineID to subsequent invocations. In practice handlers seem to construct fresh slices, but a quick // defensive copy or doc note on the handler contract would future-proof this.

🤖 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/realizations/credittheninvoice.go`
around lines 112 - 114, You are mutating the handler-returned slice
creditAllocations in place by setting creditAllocations[idx].LineID =
lo.ToPtr(in.Line.ID), which can leak state if the handler reuses the slice;
instead make a defensive copy before modifying or update the handler contract.
Fix by allocating a new slice (copying elements from creditAllocations) and set
LineID on the new slice, then use/return that copy; alternatively add a comment
on the handler that it must return a fresh slice and ensure functions like the
caller of creditAllocations follow that contract. Reference creditAllocations
and in.Line.ID in your changes.
openmeter/billing/charges/flatfee/service/realizations/invoiceaccrued.go (1)

80-108: 💤 Low value

Tiny callout: handler runs only on non-zero totals, but run is still marked immutable.

The behavior reads correctly against the PR objective ("Invoice lines with a zero total do not accrue invoice usage"), and the run is still flipped to immutable below regardless. Just noting that there's no explicit OnInvoiceUsageNotAccrued style hook — if downstream consumers ever need to observe "zero-total invoice issued", they currently get nothing. Not a blocker, just future-proofing food for thought.

🤖 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/realizations/invoiceaccrued.go`
around lines 80 - 108, The code only calls s.handler.OnInvoiceUsageAccrued when
line.Totals is non-zero so runs that become immutable on zero-total lines have
no observable "not accrued" event; add a complementary path: introduce and call
a new handler method (e.g., s.handler.OnInvoiceUsageNotAccrued) when
line.Totals.Total.IsZero() that receives flatfee.OnInvoiceUsageNotAccruedInput
(Charge, ServicePeriod, Totals), then create a corresponding
invoicedusage.AccruedUsage (with Totals and nil LedgerTransaction) via
s.adapter.CreateInvoicedUsage (reusing the same CreateInvoicedUsage call site
pattern) and assign it to result.AccruedUsage and result.Run.AccruedUsage so
downstream consumers can observe zero-total accruals.
openmeter/billing/charges/flatfee/service/lineengine.go (1)

137-207: ⚖️ Poor tradeoff

Optional: extract per-line deletion into a helper.

OnMutableStandardLinesDeleted is doing quite a lot inline — five guards, a credit correction, detailed-line wipe, and a run update. Pulling the body of the for _, stdLine := range input.Lines block into a small helper like deleteRunForStandardLine(ctx, charge, stdLine, invoiceID) would make the orchestration easier to scan and keep each concern small. Totally optional.

🤖 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 137 -
207, The loop body in OnMutableStandardLinesDeleted is large and should be
extracted into a helper to improve readability; create a helper like
deleteRunForStandardLine(ctx context.Context, charge flatfee.Charge, stdLine
billing.StandardLine, invoiceID string) error (or include *LineEngine if you
need e.service) and move all logic inside the for loop — charge lookup guard,
charge.Realizations.GetByLineID, the
DeletedAt/InvoiceID/AccruedUsage/Payment/CurrentRun checks,
Currency.Calculator(), e.service.realizations.CorrectAllCredits call,
e.service.adapter.UpsertDetailedLines, and
e.service.adapter.UpdateRealizationRun — into that helper preserving the same
error messages/wrapping and return values, then replace the loop body in
OnMutableStandardLinesDeleted with a call to this helper for each stdLine and
return any error it produces.
test/credits/credit_then_invoice_test.go (1)

1663-1663: ⚡ Quick win

Prefer s.Run for these suite subtests.

These new subtests still use s.NoError/s.Require/s.Equal, but t.Run does not rebind s.T() the way suite.Run does. That usually means failures and helper output get attached to the parent test instead of the subtest, and suite subtest plumbing gets a bit weird. I’d switch the new t.Run(...) blocks in this file to s.Run(...).

🤖 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` at line 1663, Replace the subtests
that call t.Run(...) with s.Run(...) so the testify suite test runner rebinds
s.T() and attaches failures/helpers to the subtest correctly; search for
occurrences of t.Run in this file (e.g., the subtest titled "given a fully
credited immutable flat fee invoice") and change them to s.Run while keeping
existing assertions like s.NoError/s.Require/s.Equal intact.
🤖 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/create.go`:
- Around line 127-129: The stored gathering line is using raw input timestamps
instead of the normalized values, causing mismatch between proration and
persisted data; update the persist logic (the code that writes the
gathering/line record after preparing lineIntent) to assign ServicePeriod and
InvoiceAt from lineIntent (which has been normalized via lineIntent =
lineIntent.Normalized()) rather than from input, ensuring the persisted fields
derive from the normalized timestamps in lineIntent before saving.
- Around line 120-133: The current buildFlatFeeGatheringLine function validates
only the original input but then mutates flatFee.Intent (lineIntent) and
recalculates values without re-checking cross-field rules; after performing
lineIntent = lineIntent.Normalized() (and before calling
lineIntent.CalculateAmountAfterProration()), call the intent-level validation
(e.g., lineIntent.Validate()) and return an error if it fails so the mutated
intent is validated before proration/amount calculation.

In `@openmeter/billing/charges/flatfee/service/creditheninvoice.go`:
- Around line 345-348: The early return in the immutable-invoice proration
branch incorrectly skips the replacement-line flow when only amounts match;
change the condition so we only return when both amounts and the service/invoice
period are unchanged. Concretely, replace the simple equality check on
input.NewAmountAfterProration and input.OldAmountAfterProration with a compound
check that also compares the relevant period fields on input (e.g., start/end or
NewPeriod vs OldPeriod) and only return when amounts are equal AND periods are
equal; otherwise let the replacement/gathering logic run so shrink/extend of
immutable periods still produces replacement lines.
- Around line 242-245: StartRealization currently passes a copy of the line into
s.Realizations.StartCreditThenInvoiceRun (you pass *input.Line) so any mutations
to CreditsApplied are lost; either pass the original pointer through or copy
mutated fields back after the call. Fix by changing the
StartCreditThenInvoiceRun call to pass input.Line (pointer) instead of
*input.Line, or if StartCreditThenInvoiceRun signature requires a value, after
the call copy relevant mutated fields (e.g., CreditsApplied and any other
updated fields) from the returned realization/line back onto input.Line before
returning from StartRealization.

In `@openmeter/billing/charges/flatfee/service/realizations/creditsonly.go`:
- Around line 44-105: AllocateCreditsOnly performs two persistence operations
(s.createCreditAllocations and s.adapter.UpdateRealizationRun) without a
transaction, risking inconsistent state if the second write fails; wrap that
multi-write section in a transaction.Run(ctx, s.adapter, func(ctx
context.Context, txAdapter AdapterType) error { ... }) similar to
StartCreditThenInvoiceRun and AccrueInvoiceUsage: move the calls to
s.createCreditAllocations and s.adapter.UpdateRealizationRun into the
transactional closure, use the transactional adapter/ctx inside the closure,
return any error to abort and roll back, and keep the rounding/validation logic
outside the transaction while returning the created realizations/totals from the
closure to set result.Realizations after transaction success.
- Around line 45-53: Move the call to in.CurrencyCalculator.RoundToPrecision so
validation runs on the original value: call in.Validate() before doing in.Amount
= in.CurrencyCalculator.RoundToPrecision(in.Amount), then keep the subsequent
IsZero() short-circuit after rounding; in other words, validate raw input via
in.Validate() (to catch negatives) and only then round the amount with
in.CurrencyCalculator.RoundToPrecision, preserving the IsZero() check that
follows.

In `@openmeter/ledger/chargeadapter/flatfee_test.go`:
- Around line 1060-1081: The test helper transactionBookedAtTimes currently
returns an empty slice silently when the query yields no rows, letting
downstream timing assertions pass vacuously; after the Query().All(...) call
(and require.NoError), add an explicit assertion that transactions is non-empty
(e.g. require.NotEmpty(t, transactions) or require.Greater(t, len(transactions),
0)) before iterating and collecting tx.BookedAt so the timing checks are
guaranteed to run against at least one transaction.

---

Outside diff comments:
In `@openmeter/billing/charges/flatfee/adapter/realizationrun.go`:
- Around line 22-62: The initial charge lookup in the transaction (inside the
entutils.TransactingRepo closure) should acquire a row lock to defend against
concurrent updates: update the query built in the adapter closure that calls
tx.db.ChargeFlatFee.Query().Where(...).Only(ctx) to include a ForUpdate() call
(i.e., tx.db.ChargeFlatFee.Query().Where(...).ForUpdate()...Only(ctx)) so the
read→check→create→update sequence in realizationrun creation (functions/methods
involving ChargeFlatFee.Query, ChargeFlatFeeRun.Create and UpdateOneID) holds a
DB-level row lock.

In `@openmeter/billing/charges/service/advance_test.go`:
- Around line 133-162: The test uses a fixed servicePeriod
(datetime.MustParseTimeInLocation for 2026-03-01 to 2026-04-01) but never fixes
the test clock, making AdvanceCharges behavior time-dependent; before creating
the charge and calling s.Charges.AdvanceCharges, set the test clock to a
deterministic instant inside that window (e.g. 2026-03-15T00:00:00Z) using the
test suite's clock helper (e.g. s.SetClock / s.Clock = testclock.New / ctx =
testclock.WithContext) or by injecting a fixed clock into the context passed to
s.Charges.Create and s.Charges.AdvanceCharges so the AdvanceCharges call runs
with a known current time. Ensure the clock is restored/controlled for the rest
of the test.

---

Nitpick comments:
In `@openmeter/billing/charges/flatfee/service/lineengine.go`:
- Around line 137-207: The loop body in OnMutableStandardLinesDeleted is large
and should be extracted into a helper to improve readability; create a helper
like deleteRunForStandardLine(ctx context.Context, charge flatfee.Charge,
stdLine billing.StandardLine, invoiceID string) error (or include *LineEngine if
you need e.service) and move all logic inside the for loop — charge lookup
guard, charge.Realizations.GetByLineID, the
DeletedAt/InvoiceID/AccruedUsage/Payment/CurrentRun checks,
Currency.Calculator(), e.service.realizations.CorrectAllCredits call,
e.service.adapter.UpsertDetailedLines, and
e.service.adapter.UpdateRealizationRun — into that helper preserving the same
error messages/wrapping and return values, then replace the loop body in
OnMutableStandardLinesDeleted with a call to this helper for each stdLine and
return any error it produces.

In `@openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go`:
- Around line 19-49: The Validate method on StartCreditThenInvoiceRunInput
should include the actual offending ID values in the two mismatch errors to aid
debugging: update the checks in StartCreditThenInvoiceRunInput.Validate that
currently append "line charge id must match charge" and "line invoice id must
match invoice" to instead format the message with the concrete values (e.g.,
include *i.Line.ChargeID and i.Charge.ID for the charge check, and
i.Line.InvoiceID and i.Invoice.ID for the invoice check) using fmt.Errorf to
produce something like "line charge id mismatch: got %v, want %v" and "line
invoice id mismatch: got %v, want %v" before returning via
models.NewNillableGenericValidationError.
- Around line 112-114: You are mutating the handler-returned slice
creditAllocations in place by setting creditAllocations[idx].LineID =
lo.ToPtr(in.Line.ID), which can leak state if the handler reuses the slice;
instead make a defensive copy before modifying or update the handler contract.
Fix by allocating a new slice (copying elements from creditAllocations) and set
LineID on the new slice, then use/return that copy; alternatively add a comment
on the handler that it must return a fresh slice and ensure functions like the
caller of creditAllocations follow that contract. Reference creditAllocations
and in.Line.ID in your changes.

In `@openmeter/billing/charges/flatfee/service/realizations/invoiceaccrued.go`:
- Around line 80-108: The code only calls s.handler.OnInvoiceUsageAccrued when
line.Totals is non-zero so runs that become immutable on zero-total lines have
no observable "not accrued" event; add a complementary path: introduce and call
a new handler method (e.g., s.handler.OnInvoiceUsageNotAccrued) when
line.Totals.Total.IsZero() that receives flatfee.OnInvoiceUsageNotAccruedInput
(Charge, ServicePeriod, Totals), then create a corresponding
invoicedusage.AccruedUsage (with Totals and nil LedgerTransaction) via
s.adapter.CreateInvoicedUsage (reusing the same CreateInvoicedUsage call site
pattern) and assign it to result.AccruedUsage and result.Run.AccruedUsage so
downstream consumers can observe zero-total accruals.

In `@openmeter/billing/charges/service/invoicable_test.go`:
- Around line 699-711: The test is calling the charge adapter methods
lineEngine.OnCollectionCompleted and lineEngine.OnInvoiceIssued directly, which
bypasses the public orchestration; change the test to drive the same behavior
through the public service flow by invoking charges.Service.Create (or creating
the charge via the public API), then use charges.Service.AdvanceCharges and
ApplyPatches (or call BillingService.ApproveInvoice as your other test does) to
progress the invoice lifecycle so the adapter is exercised indirectly; ensure
you remove the direct calls to lineEngine.OnCollectionCompleted and
lineEngine.OnInvoiceIssued and instead assert results after the service-level
calls.
- Around line 2561-2620: The helper assertFlatFeeCreditThenInvoiceLineAndRun is
hard-coded to expect 5 credits; either rename it to indicate the fixed 5-credit
behavior or make it generic by adding an expected-credit field to the input and
using that everywhere—update the assertFlatFeeCreditThenInvoiceLineAndRunInput
struct to include ExpectedCreditAmount (type float64 or money.Decimal type used
elsewhere), replace all float64(5) assertions in
assertFlatFeeCreditThenInvoiceLineAndRun with comparisons to
input.ExpectedCreditAmount, and update every caller of
assertFlatFeeCreditThenInvoiceLineAndRun to pass the correct expected credit
amount (or if you choose rename, rename the function and update callers
accordingly).
- Around line 689-697: Replace the hand-constructed assignment of
billingtotals.Totals with a single factory/helper that builds totals respecting
the model invariants (e.g. newZeroAmountChargesTotals(amount, charges)); call
this helper to set lines[0].Totals and propagate it to each
lines[0].DetailedLines[idx].Totals, then reassign invoice.Lines via
billing.NewStandardInvoiceLines(lines) as before—this centralizes totals
creation (instead of inline struct literal), ensures future fields (taxes/fees)
are populated, and keeps the test intent clear; modify the test to import/define
newZeroAmountChargesTotals and use alpacadecimal.NewFromInt for the numeric args
when creating the totals.

In `@openmeter/billing/worker/subscriptionsync/service/reconciler/patch_test.go`:
- Around line 43-70: Two identical test entries in patch_test.go both named
"credit then invoice disabled stays on invoice lines" use
productcatalog.CreditThenInvoiceSettlementMode with enableCredits: true and
enableCreditThenInvoice: false; remove one of these duplicate cases or modify it
to exercise the missing branch (e.g., change enableCreditThenInvoice to true or
swap to a different settlementMode/rateCard) so each test in the table is
unique; update any related expectedCollection (lineInvoicePatchCollection,
flatFeeChargeCollection, usageBasedChargeCollection) to match the altered
scenario and keep the remaining tests' names distinct.

In `@test/credits/credit_then_invoice_test.go`:
- Line 1663: Replace the subtests that call t.Run(...) with s.Run(...) so the
testify suite test runner rebinds s.T() and attaches failures/helpers to the
subtest correctly; search for occurrences of t.Run in this file (e.g., the
subtest titled "given a fully credited immutable flat fee invoice") and change
them to s.Run while keeping existing assertions like s.NoError/s.Require/s.Equal
intact.
🪄 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: 628b1159-0069-4fef-b7cb-bfe594254e11

📥 Commits

Reviewing files that changed from the base of the PR and between cdb2d8c and 4543a99.

⛔ Files ignored due to path filters (12)
  • openmeter/ent/db/chargeflatfee/chargeflatfee.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerun.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerun/chargeflatfeerun.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerun/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerun_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerun_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/plan/plan.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscription/subscription.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (58)
  • openmeter/billing/charges/flatfee/adapter.go
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/flatfee/adapter/credits.go
  • openmeter/billing/charges/flatfee/adapter/detailedline.go
  • openmeter/billing/charges/flatfee/adapter/detailedline_test.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go
  • openmeter/billing/charges/flatfee/adapter/payment.go
  • openmeter/billing/charges/flatfee/adapter/realizationrun.go
  • openmeter/billing/charges/flatfee/adapter/realizationrun_test.go
  • openmeter/billing/charges/flatfee/adapter/usage.go
  • openmeter/billing/charges/flatfee/charge.go
  • openmeter/billing/charges/flatfee/charge_test.go
  • openmeter/billing/charges/flatfee/handler.go
  • openmeter/billing/charges/flatfee/realizationrun.go
  • openmeter/billing/charges/flatfee/service/create.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/creditsonly.go
  • openmeter/billing/charges/flatfee/service/helpers.go
  • openmeter/billing/charges/flatfee/service/invoice.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/flatfee/service/linemapper.go
  • openmeter/billing/charges/flatfee/service/payment.go
  • openmeter/billing/charges/flatfee/service/payment_test.go
  • openmeter/billing/charges/flatfee/service/realizations/correct.go
  • openmeter/billing/charges/flatfee/service/realizations/creditsonly.go
  • openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go
  • openmeter/billing/charges/flatfee/service/realizations/invoiceaccrued.go
  • openmeter/billing/charges/flatfee/service/realizations/service.go
  • openmeter/billing/charges/flatfee/service/service.go
  • openmeter/billing/charges/flatfee/service/triggers.go
  • openmeter/billing/charges/meta/patch.go
  • openmeter/billing/charges/meta/patchdelete.go
  • openmeter/billing/charges/meta/patchextend.go
  • openmeter/billing/charges/meta/patchshrink.go
  • openmeter/billing/charges/service/advance_test.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/featureid_test.go
  • openmeter/billing/charges/service/handlers_test.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/service/taxcode_test.go
  • openmeter/billing/charges/testutils/handlers.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/charges/usagebased/service/rating/testutils/testutils.go
  • openmeter/billing/charges/usagebased/service/triggers.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patch.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patch_test.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go
  • openmeter/ent/schema/chargesflatfee.go
  • openmeter/ledger/chargeadapter/flatfee.go
  • openmeter/ledger/chargeadapter/flatfee_test.go
  • openmeter/ledger/chargeadapter/usagebased.go
  • openmeter/productcatalog/settlementmode.go
  • test/app/stripe/invoice_credits_test.go
  • test/credits/base.go
  • test/credits/credit_then_invoice_test.go
  • test/credits/rating_test.go
  • tools/migrate/migrations/20260513083018_add_flat_fee_run_immutable.down.sql
  • tools/migrate/migrations/20260513083018_add_flat_fee_run_immutable.up.sql
💤 Files with no reviewable changes (7)
  • openmeter/billing/charges/flatfee/service/triggers.go
  • openmeter/billing/charges/flatfee/service/helpers.go
  • openmeter/productcatalog/settlementmode.go
  • openmeter/billing/charges/flatfee/service/invoice.go
  • openmeter/billing/charges/usagebased/service/triggers.go
  • openmeter/ledger/chargeadapter/usagebased.go
  • openmeter/billing/charges/flatfee/adapter/charge.go

@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 (3)
openmeter/billing/charges/flatfee/adapter/realizationrun_test.go (1)

123-129: ⚡ Quick win

Assert no side effects after the duplicate-run error.

Nice guard check on Line 128. Please also assert persistence state stayed unchanged (e.g., still exactly one current run for that charge/service period) after the failed second call, so we catch any partial-write regressions too.

As per coding guidelines "**/*_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/flatfee/adapter/realizationrun_test.go` around
lines 123 - 129, The test currently verifies the duplicate CreateCurrentRun call
errors but doesn't assert that persistence didn't change; after the failing
s.adapter.CreateCurrentRun(...) call, query the store for current runs for the
same createdCharges[0].ChargeBase and servicePeriod (use the adapter's read API,
e.g. s.adapter.GetCurrentRun or s.adapter.ListCurrentRunsByChargeAndPeriod /
equivalent method) and assert exactly one current run exists and it matches the
original run (ID/fields) to ensure no partial write occurred.
openmeter/billing/charges/service/invoicable_test.go (2)

692-698: 💤 Low value

Direct invoice totals manipulation for edge case testing.

The test directly mutates lines[0].Totals to create a scenario where Amount is zero but ChargesTotal/Total are non-zero. While this works for testing the specific edge case, it's a bit artificial and could become fragile if the invoice structure changes. Consider whether there's a more natural way to construct this scenario through the billing APIs, or at minimum add a comment explaining why direct mutation is necessary here.

🤖 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/service/invoicable_test.go` around lines 692 - 698,
The test currently mutates lines[0].Totals directly (setting
billingtotals.Totals with ChargesTotal/Total non-zero and pushing that value
into each DetailedLines[idx].Totals) to simulate an edge case; instead either
construct the invoice via the existing billing APIs so Totals are populated
naturally or, if that is impractical, add a brief comment above this block
explaining why direct mutation is necessary and what invariant it is simulating
(e.g., "forcing Total/ChargesTotal != 0 while Amount == 0 to exercise billing
edge-case X"), referencing lines[0].Totals, billingtotals.Totals, and
DetailedLines so future maintainers understand the intent.

2554-2623: 💤 Low value

Consider decomposing this long helper function.

The assertFlatFeeCreditThenInvoiceLineAndRun helper is comprehensive (70 lines) but quite long. While it's testing a cohesive set of properties, consider breaking it down into smaller focused helpers like:

  • assertStandardLineProperties
  • assertDetailedLineProperties
  • assertRunProperties
  • assertAccruedUsageProperties

This would make debugging easier when a specific assertion fails and improve maintainability.

🤖 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/service/invoicable_test.go` around lines 2554 -
2623, The helper assertFlatFeeCreditThenInvoiceLineAndRun is too long; split its
assertions into smaller focused helpers to improve readability and
debuggability: extract the standard-line checks into
assertStandardLineProperties(stdLine, expected... ), detailed-line checks into
assertDetailedLineProperties(detailedLine, expected... ), run-related checks
into assertRunProperties(currentRun, expected... ) (using
mustGetFlatFeeChargeByIDWithDetailedLines and currentRun), and accrued-usage
checks into assertAccruedUsageProperties(currentRun.AccruedUsage, expected... );
replace the inline blocks in assertFlatFeeCreditThenInvoiceLineAndRun with calls
to these new helper functions and move any repeated assertions (Totals,
CreditsApplied comparisons, ID equality checks) into the helpers so the original
function becomes a thin orchestration that returns stdLine.GetLineID().
🤖 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/service/invoicable_test.go`:
- Around line 683-689: The onInvoiceUsageAccrued callback is using the parent
test's fatal assertion s.RequireTotals which will abort the whole test on
failure; change it to use non-fatal assertions that use the callback's testing.T
so failures are isolated. In the invoiceUsageAccruedCallback.Handler invocation
(and specifically replace the call to s.RequireTotals), call the totals
assertion helper that accepts the local t (e.g., billingtest.RequireTotals(t,
billingtest.ExpectedTotals{...}, input.Totals) or the equivalent helper that
takes a *testing.T) so the assertion uses the callback's t instead of s.
- Around line 448-452: The callback handler registered on
s.FlatFeeTestHandler.onInvoiceUsageAccrued uses s.RequireTotals(expectedTotals,
input.Totals) which uses the suite context instead of the callback's t and can
abort the parent test; replace that call with a non-fatal assertion that accepts
the callback's t (e.g. assert.Equal(t, expectedTotals, input.Totals) or
implement an AssertTotals(t, expectedTotals, input.Totals) helper) inside the
invoiceUsageAccruedCallback.Handler(t, func(t *testing.T, input
flatfee.OnInvoiceUsageAccruedInput) { ... }) block; make the same change for the
analogous occurrences in the other callback (lines ~684-688) so all callback
assertions use the callback's t parameter.

---

Nitpick comments:
In `@openmeter/billing/charges/flatfee/adapter/realizationrun_test.go`:
- Around line 123-129: The test currently verifies the duplicate
CreateCurrentRun call errors but doesn't assert that persistence didn't change;
after the failing s.adapter.CreateCurrentRun(...) call, query the store for
current runs for the same createdCharges[0].ChargeBase and servicePeriod (use
the adapter's read API, e.g. s.adapter.GetCurrentRun or
s.adapter.ListCurrentRunsByChargeAndPeriod / equivalent method) and assert
exactly one current run exists and it matches the original run (ID/fields) to
ensure no partial write occurred.

In `@openmeter/billing/charges/service/invoicable_test.go`:
- Around line 692-698: The test currently mutates lines[0].Totals directly
(setting billingtotals.Totals with ChargesTotal/Total non-zero and pushing that
value into each DetailedLines[idx].Totals) to simulate an edge case; instead
either construct the invoice via the existing billing APIs so Totals are
populated naturally or, if that is impractical, add a brief comment above this
block explaining why direct mutation is necessary and what invariant it is
simulating (e.g., "forcing Total/ChargesTotal != 0 while Amount == 0 to exercise
billing edge-case X"), referencing lines[0].Totals, billingtotals.Totals, and
DetailedLines so future maintainers understand the intent.
- Around line 2554-2623: The helper assertFlatFeeCreditThenInvoiceLineAndRun is
too long; split its assertions into smaller focused helpers to improve
readability and debuggability: extract the standard-line checks into
assertStandardLineProperties(stdLine, expected... ), detailed-line checks into
assertDetailedLineProperties(detailedLine, expected... ), run-related checks
into assertRunProperties(currentRun, expected... ) (using
mustGetFlatFeeChargeByIDWithDetailedLines and currentRun), and accrued-usage
checks into assertAccruedUsageProperties(currentRun.AccruedUsage, expected... );
replace the inline blocks in assertFlatFeeCreditThenInvoiceLineAndRun with calls
to these new helper functions and move any repeated assertions (Totals,
CreditsApplied comparisons, ID equality checks) into the helpers so the original
function becomes a thin orchestration that returns stdLine.GetLineID().
🪄 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: 433605c5-e1f3-4d0c-a85d-dcdcedb386d8

📥 Commits

Reviewing files that changed from the base of the PR and between 28d69d0 and d76952c.

📒 Files selected for processing (11)
  • openmeter/billing/charges/flatfee/adapter/realizationrun.go
  • openmeter/billing/charges/flatfee/adapter/realizationrun_test.go
  • openmeter/billing/charges/flatfee/service/create.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/realizations/creditsonly.go
  • openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go
  • openmeter/billing/charges/service/advance_test.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patch_test.go
  • openmeter/ledger/chargeadapter/flatfee_test.go
  • test/credits/credit_then_invoice_test.go
💤 Files with no reviewable changes (1)
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patch_test.go
🚧 Files skipped from review as they are similar to previous changes (7)
  • openmeter/billing/charges/service/advance_test.go
  • openmeter/billing/charges/flatfee/service/realizations/creditsonly.go
  • openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go
  • openmeter/billing/charges/flatfee/service/create.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/adapter/realizationrun.go
  • test/credits/credit_then_invoice_test.go

@turip turip added release-note/feature Release note: Exciting New Features area/billing labels May 13, 2026
@turip
turip requested a review from tothandras May 13, 2026 19:45

This branch was previously deployed

1 inactive deployment
dev — 2ff883ed Deployed May 13, 2026 by turip via Migration Checks #14376
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing kind/feature New feature or request release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants