Repository navigation
feat(credit_then_invoice): flat fee shrink/expand - #4357
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughRestructures flat‑fee billing around realization runs: adapters, service flows, and handlers are run‑scoped (use RealizationRunID), runs gain an ChangesAdapter & API surface
Run‑scoped adapter implementations
Realizations orchestration and rating
Service & state-machine refactor
Payment lifecycle and ledger integration
Settlement modes, patch typing, schema, migrations, tests
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
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 winMake this test time-deterministic.
This test hard-codes
March 1, 2026–April 1, 2026but 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 liftConsider 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 winRemove 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 tradeoffCalling
lineEngine.OnCollectionCompleted/OnInvoiceIssueddirectly 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 throughBillingService.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 winHelper name says generic, implementation is hard-coded to 5 credits.
assertFlatFeeCreditThenInvoiceLineAndRunlooks reusable but bakesfloat64(5)into theCreditsAppliedassertions (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 valueHeads-up: manually rewriting
TotalsafterInvoicePendingLines.Overwriting
lines[0].Totals(and each detailed line'sTotals) 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 likenewZeroAmountChargesTotals(amount, charges)or a helper that respectsbillingtotals.Totalsinvariants 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 valueTiny 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 valueMutating handler-returned slice in place — confirm it's OK.
You're writing
LineIDdirectly into the slice the handler returned. If any handler caches or reuses that allocation slice across calls, this would leak theLineIDto subsequent invocations. In practice handlers seem to construct fresh slices, but a quick// defensive copyor 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 valueTiny 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
OnInvoiceUsageNotAccruedstyle 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 tradeoffOptional: extract per-line deletion into a helper.
OnMutableStandardLinesDeletedis doing quite a lot inline — five guards, a credit correction, detailed-line wipe, and a run update. Pulling the body of thefor _, stdLine := range input.Linesblock into a small helper likedeleteRunForStandardLine(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 winPrefer
s.Runfor these suite subtests.These new subtests still use
s.NoError/s.Require/s.Equal, butt.Rundoes not rebinds.T()the waysuite.Rundoes. 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 newt.Run(...)blocks in this file tos.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
⛔ Files ignored due to path filters (12)
openmeter/ent/db/chargeflatfee/chargeflatfee.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerun.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerun/chargeflatfeerun.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerun/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerun_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerun_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**openmeter/ent/db/plan/plan.gois excluded by!**/ent/db/**openmeter/ent/db/subscription/subscription.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (58)
openmeter/billing/charges/flatfee/adapter.goopenmeter/billing/charges/flatfee/adapter/charge.goopenmeter/billing/charges/flatfee/adapter/credits.goopenmeter/billing/charges/flatfee/adapter/detailedline.goopenmeter/billing/charges/flatfee/adapter/detailedline_test.goopenmeter/billing/charges/flatfee/adapter/mapper.goopenmeter/billing/charges/flatfee/adapter/payment.goopenmeter/billing/charges/flatfee/adapter/realizationrun.goopenmeter/billing/charges/flatfee/adapter/realizationrun_test.goopenmeter/billing/charges/flatfee/adapter/usage.goopenmeter/billing/charges/flatfee/charge.goopenmeter/billing/charges/flatfee/charge_test.goopenmeter/billing/charges/flatfee/handler.goopenmeter/billing/charges/flatfee/realizationrun.goopenmeter/billing/charges/flatfee/service/create.goopenmeter/billing/charges/flatfee/service/creditheninvoice.goopenmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/flatfee/service/helpers.goopenmeter/billing/charges/flatfee/service/invoice.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/linemapper.goopenmeter/billing/charges/flatfee/service/payment.goopenmeter/billing/charges/flatfee/service/payment_test.goopenmeter/billing/charges/flatfee/service/realizations/correct.goopenmeter/billing/charges/flatfee/service/realizations/creditsonly.goopenmeter/billing/charges/flatfee/service/realizations/credittheninvoice.goopenmeter/billing/charges/flatfee/service/realizations/invoiceaccrued.goopenmeter/billing/charges/flatfee/service/realizations/service.goopenmeter/billing/charges/flatfee/service/service.goopenmeter/billing/charges/flatfee/service/triggers.goopenmeter/billing/charges/meta/patch.goopenmeter/billing/charges/meta/patchdelete.goopenmeter/billing/charges/meta/patchextend.goopenmeter/billing/charges/meta/patchshrink.goopenmeter/billing/charges/service/advance_test.goopenmeter/billing/charges/service/base_test.goopenmeter/billing/charges/service/featureid_test.goopenmeter/billing/charges/service/handlers_test.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/charges/service/taxcode_test.goopenmeter/billing/charges/testutils/handlers.goopenmeter/billing/charges/usagebased/service/rating/service_test.goopenmeter/billing/charges/usagebased/service/rating/testutils/testutils.goopenmeter/billing/charges/usagebased/service/triggers.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patch.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patch_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/ent/schema/chargesflatfee.goopenmeter/ledger/chargeadapter/flatfee.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/usagebased.goopenmeter/productcatalog/settlementmode.gotest/app/stripe/invoice_credits_test.gotest/credits/base.gotest/credits/credit_then_invoice_test.gotest/credits/rating_test.gotools/migrate/migrations/20260513083018_add_flat_fee_run_immutable.down.sqltools/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
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
openmeter/billing/charges/flatfee/adapter/realizationrun_test.go (1)
123-129: ⚡ Quick winAssert 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 valueDirect invoice totals manipulation for edge case testing.
The test directly mutates
lines[0].Totalsto create a scenario whereAmountis zero butChargesTotal/Totalare 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 valueConsider decomposing this long helper function.
The
assertFlatFeeCreditThenInvoiceLineAndRunhelper 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:
assertStandardLinePropertiesassertDetailedLinePropertiesassertRunPropertiesassertAccruedUsagePropertiesThis 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
📒 Files selected for processing (11)
openmeter/billing/charges/flatfee/adapter/realizationrun.goopenmeter/billing/charges/flatfee/adapter/realizationrun_test.goopenmeter/billing/charges/flatfee/service/create.goopenmeter/billing/charges/flatfee/service/creditheninvoice.goopenmeter/billing/charges/flatfee/service/realizations/creditsonly.goopenmeter/billing/charges/flatfee/service/realizations/credittheninvoice.goopenmeter/billing/charges/service/advance_test.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patch_test.goopenmeter/ledger/chargeadapter/flatfee_test.gotest/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
Adds native shrink and extend handling for flat-fee credit-then-invoice charges.
Summary by CodeRabbit
New Features
Enhancements
Tests