Skip to content

feat: persist detailed lines - #4202

Merged
turip merged 5 commits into
mainfrom
feat/persist-detailed-lines
Apr 22, 2026
Merged

turip merged 5 commits into
mainfrom
feat/persist-detailed-lines

Conversation

@turip

@turip turip commented Apr 22, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR adds durable charge-side detailed-line persistence for usage-based realization runs and flat-fee realizations, and moves flat-fee line-engine ownership behind flatfee.Service to match the usage-based structure.

The main goal is to preserve the rated/billed detailed-line representation on the charge side, not only on invoice lines. That gives charge lifecycles a stable, queryable view of what was rated for a run or realization,
which is needed for future rerating, previous-run context, and expand-based read models.

Why

Today, charge lifecycles can rate or bill lines transiently, but the detailed-line output is not consistently persisted as part of the charge aggregate. That creates a few problems:

  • previous rated detail is hard to reuse in later lifecycle steps
  • charge reads cannot expose the same detailed breakdown that billing already produced (credits only esp)
  • replacement semantics are fragile because stale lines are not explicitly reconciled
  • flat-fee and usage-based line-engine ownership were inconsistent, which leaked adapter concerns into wiring and tests
  • invoice lines should be mutable, but for progressive billing we will need a stable history

This change addresses those by making detailed lines first-class persisted charge data and by pushing line-engine ownership back into the charge services.

Why This Shape

A few design choices were intentional:

  • Detailed lines live under realizations/runs, not on the root charge. This matches ownership semantics. The detailed lines belong to a specific realization context.
  • Domain detailed lines do not carry ChargeID / RunID. Those IDs are persistence concerns and are already implied by containment in the aggregate.
  • Flat-fee now owns its line engine through the service. This matches usage-based, keeps lifecycle logic inside the charge package, and avoids leaking adapter-specific persistence hooks into external wiring.
  • Rating inputs for totals vs detailed lines are split. They will diverge over time, and forcing one shared input would create unnecessary coupling.

Summary by CodeRabbit

  • New Features

    • Detailed-line support for flat‑fee and usage‑based charges, retrievable via a new expansion flag (requires also expanding realizations).
    • Flat‑fee service now exposes a line‑engine for billing registration and persists detailed lines as part of invoice/rating flows.
  • Bug Fixes

    • Simplified unique‑index behavior for detailed lines to respect soft‑deletes.
  • Tests

    • New integration tests covering upsert, fetch, ordering, replacement and soft‑delete behavior.

@coderabbitai

coderabbitai Bot commented Apr 22, 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: d8349036-f19f-4486-83ef-482f6b4539ce

📥 Commits

Reviewing files that changed from the base of the PR and between 9060c57 and 0d994b0.

📒 Files selected for processing (1)
  • openmeter/billing/charges/usagebased/adapter/detailedline_test.go
✅ Files skipped from review due to trivial changes (1)
  • openmeter/billing/charges/usagebased/adapter/detailedline_test.go

📝 Walkthrough

Walkthrough

Adds persisted “detailed lines” for flat‑fee and usage‑based charges, a shared stddetailedline model for DB↔domain mapping, moves flat‑fee line‑engine wiring into the flat‑fee service (now requiring a rating dependency), implements transactional Fetch/Upsert adapters with soft‑delete semantics, and simplifies detailed‑line partial index predicates.

Changes

Cohort / File(s) Summary
Docs & Guidance
\.agents/skills/charges/SKILL.md
Updated guidance on charge‑owned detailed lines, expansion requirements, and flat‑fee line‑engine location/wiring.
App wiring & tests
app/common/charges.go, openmeter/billing/charges/testutils/service.go, openmeter/billing/charges/service/base_test.go, openmeter/ledger/customerbalance/testenv_test.go
Flat‑fee service now requires rating.Service; registration uses flatFeeService.GetLineEngine() instead of constructing a separate engine. Test wiring updated accordingly.
Flat‑fee model & service
openmeter/billing/charges/flatfee/charge.go, .../flatfee/detailedline.go, .../flatfee/service.go, .../flatfee/service/*
Added optional Realizations.DetailedLines, DetailedLine(s) types, Service.GetLineEngine() API, moved line‑engine into flat‑fee service, and persist detailed lines during invoice lifecycle.
Flat‑fee adapter & DB impl
openmeter/billing/charges/flatfee/adapter.go, .../adapter/charge.go, .../adapter/detailedline.go, .../adapter/mapper.go, .../adapter/detailedline_test.go
Extended adapter with Fetch/UpsertDetailedLines; Ent-backed transactional implementations added (soft‑delete by ChildUniqueReferenceID, bulk upsert OnConflict), mapping via stddetailedline, stable sorting, and tests.
Usage‑based model & service
openmeter/billing/charges/usagebased/detailedline.go, .../realizationrun.go, .../service/*
Added optional RealizationRun.DetailedLines, DetailedLine(s) types, helpers to ensure/load detailed lines for rating, mapping/persistence of run detailed lines, and rater API changes including PriorRuns handling.
Usage‑based adapter & DB impl
openmeter/billing/charges/usagebased/adapter.go, .../adapter/charge.go, .../adapter/detailedline.go, .../adapter/detailedline_test.go
Added per‑run Fetch/Upsert detailed‑line adapter methods with soft‑delete semantics, mapping helpers, sorting, and integration tests.
Rating & totals
openmeter/billing/charges/usagebased/service/rating/*
Introduced GetDetailedLinesForUsageInput and result handling; rating rewrites child unique reference IDs to include service period; service surface refactor to interface/value types.
Shared detailed‑line model
openmeter/billing/models/stddetailedline/*
New stddetailedline package: generic Create/FromDB mapping, comparators, getters, BackfillTaxConfig, and ordering utilities used across adapters and invoice mapping.
Invoice mapping
openmeter/billing/adapter/stdinvoicelinemapper.go, openmeter/billing/adapter/stdinvoicelines.go
Delegated DB→domain and creation mapping to stddetailedline.FromDB / stddetailedline.Create, removing inline field assembly.
Meta expands & validation
openmeter/billing/charges/meta/charge.go, openmeter/billing/charges/*/adapter.go, openmeter/billing/charges/*/service.go
Added meta.ExpandDetailedLines and validateExpands rule: requesting ExpandDetailedLines requires ExpandRealizations.
DB schema & migrations
openmeter/ent/schema/*.go, tools/migrate/migrations/*simplify_mixin_detailed_line_partial_indexes*.sql
Simplified partial unique index predicates to WHERE deleted_at IS NULL for detailed‑line tables and added corresponding up/down migration scripts.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant FlatFeeService as Flat‑Fee Service
  participant FlatFeeAdapter as Flat‑Fee Adapter
  participant DB as Database

  Client->>FlatFeeService: UpsertDetailedLines(chargeID, lines)
  FlatFeeService->>FlatFeeAdapter: UpsertDetailedLines(chargeID, lines)
  FlatFeeAdapter->>DB: Soft‑delete existing lines by (namespace,chargeID,child_ref)
  FlatFeeAdapter->>DB: Bulk create/upsert lines (ON CONFLICT update)
  DB-->>FlatFeeAdapter: OK/Error
  FlatFeeAdapter-->>FlatFeeService: OK/Error
  FlatFeeService-->>Client: OK/Error

  Client->>FlatFeeService: GetByID(..., ExpandDetailedLines)
  FlatFeeService->>FlatFeeAdapter: GetByID(..., ExpandDetailedLines)
  FlatFeeAdapter->>DB: Query charge + realizations
  FlatFeeAdapter->>DB: Query detailed lines (namespace,chargeID)
  DB-->>FlatFeeAdapter: DetailedLines
  FlatFeeAdapter->>FlatFeeService: Charge with DetailedLines
  FlatFeeService-->>Client: Charge with DetailedLines
Loading
sequenceDiagram
  participant StateMachine as Usage StateMachine
  participant UsageService as Usage Service
  participant Adapter as Usage Adapter
  participant DB as Database
  participant Rater as Rating Service

  StateMachine->>Adapter: FetchDetailedLines(charge)    %% ensureDetailedLinesLoadedForRating
  Adapter->>DB: Query run detailed lines by (namespace,chargeID,runID)
  DB-->>Adapter: DetailedLines
  Adapter-->>StateMachine: charge with DetailedLines

  StateMachine->>Rater: GetDetailedLinesForUsage(Charge, PriorRuns,...)
  Rater->>Rater: GenerateDetailedLines(...)
  Rater->>Rater: Append service period to ChildUniqueReferenceIDs
  Rater-->>StateMachine: DetailedLines result

  StateMachine->>Adapter: UpsertRunDetailedLines(chargeID, runID, lines)
  Adapter->>DB: Soft‑delete existing run lines not in incoming child refs
  Adapter->>DB: Bulk create/upsert new run lines
  DB-->>Adapter: OK/Error
  Adapter-->>StateMachine: OK/Error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

release-note/feature

Suggested reviewers

  • tothandras
  • GAlexIHU
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.63% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the primary objective of the changeset: adding persistent storage for charge-side detailed lines across flat-fee and usage-based billing.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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/persist-detailed-lines

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@turip
turip force-pushed the feat/persist-detailed-lines branch from bddc2c1 to 732e69a Compare April 22, 2026 06:08
@turip
turip force-pushed the feat/persist-detailed-lines branch from 732e69a to dd4bd45 Compare April 22, 2026 06:49
@turip turip added release-note/misc Miscellaneous changes area/billing labels Apr 22, 2026
@turip
turip force-pushed the feat/persist-detailed-lines branch from dd4bd45 to d5fe4e0 Compare April 22, 2026 06:53
@turip
turip marked this pull request as ready for review April 22, 2026 06:54
@turip
turip requested a review from a team as a code owner April 22, 2026 06:54

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (16)
openmeter/billing/charges/usagebased/service/get.go (1)

111-175: Minor: error-channel draining is correct but a bit heavyweight.

The errCh buffered at len(charges) + sync.Map + post-loop range is fine and safe, but since you're already using wg, this could be simplified with an errgroup.Group (with a semaphore-like concurrency cap via g.SetLimit(defaultMaxParallelRatingsPerRequest)), which would replace the semaphore, WaitGroup, errCh, and the nil-check filter loop. Totally optional — leaving as-is is also perfectly readable.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/service/get.go` around lines 111 - 175,
Replace the manual semaphore/wg/errCh pattern with an errgroup to simplify
concurrency: create an errgroup via errgroup.WithContext(ctx), call
g.SetLimit(defaultMaxParallelRatingsPerRequest), and for each charge use
g.Go(func() error { ... }) to run the rating work (invoke
s.rater.GetTotalsForUsage) and return any error instead of pushing to errCh;
store results into ratingResults (keep sync.Map or switch to a map guarded by a
mutex) inside the goroutine; after the loop call g.Wait() and return its error
(or nil) — remove sem.Acquire/Release, wg, errCh, the post-loop draining logic,
and the manual error aggregation.
openmeter/billing/charges/usagebased/service_test.go (1)

11-17: Nice little unit test — optional polish with table-driven cases.

Tight and covers the key rules. 👍 Couple of tiny ideas if you feel like it:

  • Add a case for empty meta.Expands{} to lock in the "no expands requested" behavior.
  • Convert to a table-driven test with t.Run(name, ...) subtests so failures point at the specific case that broke.
  • Consider asserting on the error type/message (e.g., require.ErrorIs or a substring match) so a refactor doesn't silently change which error is returned.

All optional — happy with the current file if you want to keep it minimal.

♻️ Example table-driven rewrite
-func TestValidateExpands(t *testing.T) {
-	t.Parallel()
-
-	require.NoError(t, validateExpands(meta.Expands{meta.ExpandRealizations}))
-	require.NoError(t, validateExpands(meta.Expands{meta.ExpandRealizations, meta.ExpandDetailedLines}))
-	require.Error(t, validateExpands(meta.Expands{meta.ExpandDetailedLines}))
-}
+func TestValidateExpands(t *testing.T) {
+	t.Parallel()
+
+	tests := []struct {
+		name    string
+		expands meta.Expands
+		wantErr bool
+	}{
+		{"empty", meta.Expands{}, false},
+		{"realizations only", meta.Expands{meta.ExpandRealizations}, false},
+		{"realizations + detailed lines", meta.Expands{meta.ExpandRealizations, meta.ExpandDetailedLines}, false},
+		{"detailed lines without realizations", meta.Expands{meta.ExpandDetailedLines}, true},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			err := validateExpands(tc.expands)
+			if tc.wantErr {
+				require.Error(t, err)
+			} else {
+				require.NoError(t, err)
+			}
+		})
+	}
+}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/service_test.go` around lines 11 - 17,
Update TestValidateExpands to a table-driven subtest style: create a slice of
cases (name, input meta.Expands, expected error boolean and optionally expected
error value/message), iterate cases and call t.Run(case.name, func(t
*testing.T){ t.Parallel(); if case.expectError { require.ErrorIs(t,
validateExpands(case.input), <expected error>) or require.Error(t,
validateExpands(case.input)) } else { require.NoError(t,
validateExpands(case.input)) } }); include a case for an empty meta.Expands{} to
lock in "no expands requested" behavior and use meta.ExpandRealizations and
meta.ExpandDetailedLines in the inputs; assert specific error type/message with
require.ErrorIs or a substring match where appropriate.
openmeter/billing/charges/usagebased/service/creditsonly.go (1)

216-221: Tiny nit: the local currentRun.DetailedLines mutation is effectively unused here.

Setting currentRun.DetailedLines = mo.Some(runDetailedLines) on line 220 only updates a local value copy — it isn't written back to s.Charge.Realizations (unlike in creditheninvoice.go where s.Charge.Realizations.SetRealizationRun(currentRun) is called afterwards). The subsequent UpdateRealizationRun doesn't carry detailed lines either, and RefetchCharge at the end reloads state from the DB, so nothing downstream reads this field before the refetch.

Either drop the assignment or add a SetRealizationRun(currentRun) for symmetry with creditheninvoice.go. Not a functional bug, just a readability snag that future-you will thank present-you for. 🙂

♻️ Option A — drop the dead assignment
-	runDetailedLines, err := s.Runs.PersistRunDetailedLines(ctx, s.Charge, currentRun, ratingResult)
-	if err != nil {
+	if _, err := s.Runs.PersistRunDetailedLines(ctx, s.Charge, currentRun, ratingResult); err != nil {
 		return err
 	}
-	currentRun.DetailedLines = mo.Some(runDetailedLines)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/service/creditsonly.go` around lines 216
- 221, The local assignment currentRun.DetailedLines = mo.Some(runDetailedLines)
is dead because it isn't propagated to s.Charge.Realizations or read before
RefetchCharge; either remove that assignment entirely, or if you want symmetry
with creditheninvoice.go, call
s.Charge.Realizations.SetRealizationRun(currentRun) after computing
runDetailedLines so the updated DetailedLines is stored in the charge
realizations; update the code around
PersistRunDetailedLines/UpdateRealizationRun accordingly.
openmeter/billing/charges/usagebased/adapter/charge.go (1)

158-165: Potential N+1 in GetByIDs when expanding detailed lines.

Nice conditional expansion — but calling tx.FetchDetailedLines(ctx, charge) once per charge inside slicesx.MapWithErr means a batch GetByIDs with ExpandDetailedLines does N separate DB queries (one per charge). For small batches it's fine, but on hot paths this could add up.

A single batched query that fetches all detailed lines for all charges at once, then stitches them back in memory, would cut this down to one DB round-trip. Worth considering as a future optimization if batch expand calls become frequent.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/adapter/charge.go` around lines 158 -
165, GetByIDs is causing an N+1 when input.Expands.Has(meta.ExpandDetailedLines)
because the current slicesx.MapWithErr loop calls tx.FetchDetailedLines(ctx,
charge) per charge; change this to a single batched fetch: collect all charge
IDs in GetByIDs, call a new tx.FetchDetailedLinesBatch(ctx, ids) (or overload
FetchDetailedLines to accept []ids) to load all detailed lines in one DB
round-trip, then stitch the returned lines back into the corresponding
usagebased.Charge objects before returning; update the call site where
slicesx.MapWithErr and tx.FetchDetailedLines are used so it uses the batched
fetch and in-memory join instead of per-charge DB calls.
openmeter/billing/charges/flatfee/service/helpers.go (1)

22-26: Add a clarifying comment about soft-delete semantics.

The helper is correct, but since UpsertDetailedLines soft-deletes any existing rows not present in the input list (reconciliation pattern), it's worth documenting that an empty DetailedLines would wipe all persisted detailed lines for the charge. A brief comment like // Note: empty DetailedLines soft-deletes all existing detailed lines for this charge helps future readers understand the reconcile behavior without digging into the adapter.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/flatfee/service/helpers.go` around lines 22 - 26,
Add a brief clarifying comment above the persistDetailedLines function to note
the soft-delete/reconciliation semantics: explain that
s.adapter.UpsertDetailedLines will soft-delete any existing detailed lines not
present in the provided list, so passing an empty line.DetailedLines will remove
all persisted detailed lines for that charge; reference persistDetailedLines,
UpsertDetailedLines, and DetailedLines in the comment so future readers
understand the reconcile behavior without inspecting the adapter.
openmeter/billing/charges/usagebased/service/run/create.go (1)

191-198: Tiny cleanup: avoid setting the current run twice.

With the unconditional SetRealizationRun below, the credit-allocation branch no longer needs its own copy. The shared error message can also stay generic since it now covers both credits and detailed lines.

♻️ Proposed cleanup
-		if err := updatedCharge.Realizations.SetRealizationRun(currentRun); err != nil {
-			return CreateRatedRunResult{}, fmt.Errorf("update realization run: %w", err)
-		}
 	}
 
 	if err := updatedCharge.Realizations.SetRealizationRun(currentRun); err != nil {
-		return CreateRatedRunResult{}, fmt.Errorf("update realization run detailed lines: %w", err)
+		return CreateRatedRunResult{}, fmt.Errorf("update realization run: %w", err)
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/service/run/create.go` around lines 191
- 198, The code calls updatedCharge.Realizations.SetRealizationRun(currentRun)
twice (once inside a conditional branch and again unconditionally), so remove
the duplicate inside the credit-allocation branch and keep only the single
unconditional call; consolidate the error handling to return
CreateRatedRunResult{} with a single generic fmt.Errorf("update realization run:
%w", err) from the remaining SetRealizationRun call to cover both credits and
detailed lines, referencing updatedCharge.Realizations.SetRealizationRun and
CreateRatedRunResult.
tools/migrate/migrations/20260422051837_simplify_mixin_detailed_line_partial_indexes.up.sql (1)

1-12: Double-check the lock window for this index rebuild.

The predicate change is consistent, but dropping/recreating three unique indexes can block writes while the indexes rebuild if these detailed-line tables are already large. Worth scheduling carefully or using a concurrent/expand-contract plan if production row counts are high.

As per coding guidelines, Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@tools/migrate/migrations/20260422051837_simplify_mixin_detailed_line_partial_indexes.up.sql`
around lines 1 - 12, Dropping and recreating the three unique indexes
(billingstdinvdetailedline_ns_parent_child_id on
billing_standard_invoice_detailed_lines, chargeffdetailedline_ns_charge_child_id
on charge_flat_fee_detailed_line, and
chargeubdetailedline_ns_charge_run_child_id on
charge_usage_based_run_detailed_line) will rebuild the indexes and can block
writes; change the migration to use a non-blocking expand/contract approach
(create the new UNIQUE INDEX CONCURRENTLY with the new predicate or a temporary
non-unique concurrent index, backfill/verify, then drop the old index and rename
the new one) or run CREATE INDEX CONCURRENTLY for the new index and then DROP
INDEX CONCURRENTLY for the old one, and document scheduling requirements so this
runs in a maintenance window if row counts are large.
openmeter/billing/models/stddetailedline/create.go (1)

32-51: Minor consistency nit: DeletedAt isn't normalized to UTC.

The service-period bounds are explicitly .In(time.UTC), and FromDB in mapping.go normalizes DeletedAt via convert.TimePtrIn(..., time.UTC). Here SetNillableDeletedAt(line.DeletedAt) passes the pointer through as-is, so a caller handing in a non-UTC time will persist it in whatever zone they supplied — asymmetric with the read path and potentially confusing down the line.

♻️ Suggested tweak
 	create := creator.
 		SetName(line.Name).
 		SetNillableDescription(line.Description).
 		SetCurrency(line.Currency).
 		SetServicePeriodStart(line.ServicePeriod.From.In(time.UTC)).
 		SetServicePeriodEnd(line.ServicePeriod.To.In(time.UTC)).
 		SetQuantity(line.Quantity).
 		SetPerUnitAmount(line.PerUnitAmount).
 		SetCategory(line.Category).
 		SetPaymentTerm(line.PaymentTerm).
 		SetNillableIndex(line.Index).
 		SetChildUniqueReferenceID(line.ChildUniqueReferenceID).
-		SetNillableDeletedAt(line.DeletedAt)
+		SetNillableDeletedAt(convert.TimePtrIn(line.DeletedAt, time.UTC))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/models/stddetailedline/create.go` around lines 32 - 51, The
Create function is passing line.DeletedAt through without timezone normalization
(via SetNillableDeletedAt), causing asymmetry with the read-path which uses
convert.TimePtrIn(..., time.UTC) in FromDB; update Create (in create.go) to
normalize DeletedAt to UTC before calling SetNillableDeletedAt (e.g., apply the
same conversion used in mapping.go/FromDB) so persisted DeletedAt values are
consistently in UTC.
openmeter/billing/charges/usagebased/adapter/detailedline_test.go (2)

192-196: Nice replacement/soft-delete coverage — one extra assertion could harden it.

You validate that "keep" was updated (quantity 3, description cleared) and "delete" was soft-deleted, which is great. Consider also asserting that the new "new" line came through with its description set — right now a regression that dropped descriptions on fresh upserts wouldn't be caught.

✨ Suggested extra assertion
 	s.Nil(fetchedCharge.Realizations[0].DetailedLines.OrEmpty()[0].Description)
+	s.Equal(lo.ToPtr("new description"), fetchedCharge.Realizations[0].DetailedLines.OrEmpty()[1].Description)
+	s.Equal(float64(4), fetchedCharge.Realizations[0].DetailedLines.OrEmpty()[1].Quantity.InexactFloat64())
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/adapter/detailedline_test.go` around
lines 192 - 196, Add an assertion to verify the newly upserted detailed line
("new@[2026-01-01T00:00:00Z..2026-02-01T00:00:00Z]") includes its description
(and optionally its expected quantity) so regressions that drop descriptions on
fresh upserts are detected; locate the test block that inspects
fetchedCharge.Realizations[0].DetailedLines.OrEmpty() and add an s.NotNil /
s.Equal check against DetailedLines.OrEmpty()[1].Description (and/or s.Equal on
DetailedLines.OrEmpty()[1].Quantity.InexactFloat64()) to confirm the "new"
line's description is present and correct.

57-64: defer migrator.CloseOrLogError() inside SetupSuite closes before tests run.

Because defer fires when SetupSuite returns (not when the suite tears down), the migrator is closed right after Up() completes. That's actually fine since you only need it for migrations here — just flagging so it doesn't surprise anyone later if the migrator is needed across tests. If you prefer symmetry, an explicit migrator.CloseOrLogError() right after migrator.Up() would read more intentionally than a defer that runs immediately.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/adapter/detailedline_test.go` around
lines 57 - 64, The defer call to migrator.CloseOrLogError() inside SetupSuite
closes the migrator as soon as SetupSuite returns (so it runs immediately after
migrator.Up()), which can be surprising; either replace the defer with an
explicit migrator.CloseOrLogError() immediately after calling migrator.Up()
inside SetupSuite, or move the defer (or a call) into your suite teardown (e.g.,
TearDownSuite) so the migrator remains open for the lifetime of the tests;
update references to migrator, SetupSuite, migrator.Up(), and
migrator.CloseOrLogError() accordingly.
openmeter/billing/charges/usagebased/service/run/detailedline.go (1)

36-71: run parameter is unused in the mapper.

mapRatingResultToRunDetailedLines takes run usagebased.RealizationRun but never reads it — the run linkage is established later in PersistRunDetailedLines via run.ID passed to the adapter. Either drop it from the signature or thread run-scoped data (e.g., a run-specific timestamp) onto the mapped line so the name reflects reality.

♻️ Quick cleanup if the argument truly isn't needed
-func mapRatingResultToRunDetailedLines(
-	charge usagebased.Charge,
-	run usagebased.RealizationRun,
-	ratingResult usagebasedrating.GetRatingForUsageResult,
-) usagebased.DetailedLines {
+func mapRatingResultToRunDetailedLines(
+	charge usagebased.Charge,
+	ratingResult usagebasedrating.GetRatingForUsageResult,
+) usagebased.DetailedLines {
...
-	detailedLines := mapRatingResultToRunDetailedLines(charge, run, ratingResult)
+	detailedLines := mapRatingResultToRunDetailedLines(charge, ratingResult)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/service/run/detailedline.go` around
lines 36 - 71, The mapRatingResultToRunDetailedLines function currently accepts
run usagebased.RealizationRun but never uses it; remove the unused run parameter
from mapRatingResultToRunDetailedLines (and update all callers, e.g., where
PersistRunDetailedLines invokes it) OR if run-scoped data is required, thread
run into the mapping and populate a run-specific field on
usagebased.DetailedLine (for example RunID or RunTimestamp) so the mapped lines
reflect the run (update the function signature mapRatingResultToRunDetailedLines
and the return population of usagebased.DetailedLine accordingly, and adjust
PersistRunDetailedLines and any adapter calls that expect the new field).
openmeter/billing/charges/usagebased/service/run/detailedline_test.go (1)

70-79: Consider asserting ChildUniqueReferenceID, Name, and the numeric fields too.

This test nicely covers the scaffolding fields, but a core mapping responsibility is carrying ChildUniqueReferenceID (and Name/Quantity/PerUnitAmount) from the rating result onto the detailed line. Right now a regression there would slip through silently. Adding a few more require.Equal calls would lock that behavior down.

✨ Suggested additional assertions
 	require.NotNil(t, out[0].TaxConfig)
 	require.NotSame(t, charge.Intent.TaxConfig, out[0].TaxConfig)
+	require.Equal(t, "Usage", out[0].Name)
+	require.Equal(t, "unit-price-usage@[2025-01-01T00:00:00Z..2025-02-01T00:00:00Z]", out[0].ChildUniqueReferenceID)
+	require.True(t, alpacadecimal.NewFromInt(12).Equal(out[0].Quantity))
+	require.True(t, alpacadecimal.NewFromInt(3).Equal(out[0].PerUnitAmount))

Note: the test input sets ChildUniqueReferenceID to "unit-price-usage@[...]" already, so the mapper is expected to pass it through verbatim (service-period suffixing is handled upstream in rating.GetDetailedLinesForUsage).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/service/run/detailedline_test.go` around
lines 70 - 79, Add assertions that verify the mapper carries through the item
identity and numeric values: in the test using mapRatingResultToRunDetailedLines
(detailedline_test.go) add require.Equal checks on
out[0].ChildUniqueReferenceID, out[0].Name and the numeric fields
out[0].Quantity and out[0].PerUnitAmount (and/or TotalAmount if applicable) to
match the input rating result values used in the test; this ensures
mapRatingResultToRunDetailedLines preserves the
ChildUniqueReferenceID/name/quantity/per-unit amount mapping rather than
silently regressing.
openmeter/billing/charges/usagebased/adapter/detailedline.go (1)

65-102: Optional: guard against chargeID / runID namespace mismatch. 🔒

UpsertRunDetailedLines uses runID.Namespace for the soft-delete Where clause and for lineToPersist.Namespace, while chargeID.ID is used for the charge filter. If a caller ever passes a chargeID and runID from different namespaces, the soft-delete/upsert would silently operate on the wrong partition. A cheap if chargeID.Namespace != runID.Namespace { return fmt.Errorf(...) } at the top would make the invariant explicit and future-proof. Not a blocker — current callers likely always pass matching namespaces.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/adapter/detailedline.go` around lines 65
- 102, Add a namespace-consistency guard at the start of UpsertRunDetailedLines
(after chargeID.Validate(), runID.Validate(), lines.Validate()) that checks
chargeID.Namespace vs runID.Namespace and returns a clear error if they differ;
use the existing symbols (chargeID.Namespace, runID.Namespace) and return a
fmt.Errorf or wrapped error indicating the mismatch so the soft-delete and
created line.Namespace cannot cross partitions silently.
openmeter/billing/charges/flatfee/adapter/detailedline_test.go (1)

145-177: Nice coverage — one tiny suggestion. ✨

Consider also asserting that the "keep" line preserves its original DB ID and CreatedAt across the two upserts. That would lock in the SetIgnore(FieldID) / SetIgnore(FieldCreatedAt) behavior in the OnConflict resolver and catch any future regression that accidentally regenerates IDs on conflict. Totally optional — what's here already covers the main replacement + soft-delete semantics well.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/flatfee/adapter/detailedline_test.go` around lines
145 - 177, Add assertions that the "keep" detailed line preserves its DB ID and
CreatedAt across the two UpsertDetailedLines calls: when you create initialLines
capture the ID and CreatedAt for the line whose ChildUniqueReferenceID == "keep"
(from the value returned by UpsertDetailedLines or by fetching it after the
first upsert via adapter.GetByID), then after the replacement
UpsertDetailedLines call fetch the charge (as you already do) and assert that
fetchedCharge.Realizations.DetailedLines.OrEmpty()[0].ID equals the original ID
and that its CreatedAt equals the original CreatedAt; this locks in the
SetIgnore(FieldID)/SetIgnore(FieldCreatedAt) behavior in the UpsertDetailedLines
conflict resolver.
openmeter/billing/charges/flatfee/service/lineengine.go (1)

60-89: Consider batching charge fetches to avoid N+1 on invoice creation.

Each line triggers its own GetByID(...) call with ExpandRealizations—for invoices with many flat-fee lines, this adds up fast on a hot path. Since you're already collecting all ChargeIDs upfront, you could use GetByIDs(...) for a single batch fetch, then loop through lines with a map lookup before calling PostLineAssignedToInvoice per-line.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/flatfee/service/lineengine.go` around lines 60 -
89, The current loop over input.Lines causes an N+1 by calling e.service.GetByID
for each line; change to collect all ChargeIDs from input.Lines first, call a
batched e.service.GetByIDs (requesting meta.ExpandRealizations) to fetch all
charges at once, populate a chargesByID map from the batch result, then iterate
input.Lines to look up charge := chargesByID[*stdLine.ChargeID] and proceed to
call e.service.PostLineAssignedToInvoice and convertCreditRealizations as
before; ensure you still validate missing ChargeID and preserve existing error
wrapping and behavior when PostLineAssignedToInvoice returns an error.
openmeter/billing/charges/flatfee/adapter/detailedline.go (1)

88-95: Small style inconsistency with the usage-based adapter around empty ChildUniqueReferenceID.

Here you use lo.Map unconditionally on all lines, while the sibling usage-based adapter (openmeter/billing/charges/usagebased/adapter/detailedline.go lines 104-110) uses lo.FilterMap to skip empty strings. Since DetailedLines.Validate() already calls line.Validate() on each line—which enforces non-empty ChildUniqueReferenceID—either approach works fine in practice. That said, the usage-based approach is more defensive. For consistency and clarity across the two adapters, consider aligning to the same pattern.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/flatfee/adapter/detailedline.go` around lines 88 -
95, Replace the unconditional lo.Map over lines with a defensive lo.FilterMap
that skips empty ChildUniqueReferenceID values: build childRefsToKeep from
flatfee.DetailedLine items by filtering out "" before mapping to
ChildUniqueReferenceID, so
deleteQuery.Where(dbchargeflatfeedetailedline.ChildUniqueReferenceIDNotIn(childRefsToKeep...))
receives only non-empty refs; this aligns the flatfee adapter (childRefsToKeep,
lines, ChildUniqueReferenceID) with the usage-based adapter's pattern.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@openmeter/billing/charges/flatfee/adapter/charge.go`:
- Around line 198-202: The current expand path maps over each flatfee.Charge and
calls tx.FetchDetailedLines per-charge causing N+1 DB queries; change this to
perform a single batched fetch by collecting all charge IDs from the returned
out slice and calling a new or existing batch helper (e.g.,
tx.FetchDetailedLinesBatch or extend tx.FetchDetailedLines to accept
[]flatfee.Charge or []ID) that issues one query returning detailed lines grouped
by charge ID, then merge the results back into each flatfee.Charge (preserve
order) instead of using slicesx.MapWithErr to call FetchDetailedLines for each
element; update signatures and tests accordingly to ensure one DB round-trip for
the expand path.

In `@openmeter/billing/charges/flatfee/charge.go`:
- Line 232: The DetailedLines field uses a non-pointer mo.Option[DetailedLines],
so omitempty won't omit the field when the Option is absent; change the struct
field type to *mo.Option[DetailedLines] (i.e., DetailedLines
*mo.Option[DetailedLines]) and ensure code sets it to nil when the expansion is
not present, or alternatively replace `omitempty` with `omitzero` if you verify
samber/mo's Option implements IsZero() in your dependency version; apply the
same change to the analogous Option field in usagebased/realizationrun.go.

In `@openmeter/billing/charges/usagebased/adapter/detailedline_test.go`:
- Line 89: Replace the use of context.Background() with the test's cancellable
context by using s.T().Context(); specifically change the ctx variable
initialization (ctx := context.Background()) in the detailed line test to ctx :=
s.T().Context() so the test inherits cancellation/timeouts from the testing
framework (referencing the test suite receiver s and its T().Context() method).

---

Nitpick comments:
In `@openmeter/billing/charges/flatfee/adapter/detailedline_test.go`:
- Around line 145-177: Add assertions that the "keep" detailed line preserves
its DB ID and CreatedAt across the two UpsertDetailedLines calls: when you
create initialLines capture the ID and CreatedAt for the line whose
ChildUniqueReferenceID == "keep" (from the value returned by UpsertDetailedLines
or by fetching it after the first upsert via adapter.GetByID), then after the
replacement UpsertDetailedLines call fetch the charge (as you already do) and
assert that fetchedCharge.Realizations.DetailedLines.OrEmpty()[0].ID equals the
original ID and that its CreatedAt equals the original CreatedAt; this locks in
the SetIgnore(FieldID)/SetIgnore(FieldCreatedAt) behavior in the
UpsertDetailedLines conflict resolver.

In `@openmeter/billing/charges/flatfee/adapter/detailedline.go`:
- Around line 88-95: Replace the unconditional lo.Map over lines with a
defensive lo.FilterMap that skips empty ChildUniqueReferenceID values: build
childRefsToKeep from flatfee.DetailedLine items by filtering out "" before
mapping to ChildUniqueReferenceID, so
deleteQuery.Where(dbchargeflatfeedetailedline.ChildUniqueReferenceIDNotIn(childRefsToKeep...))
receives only non-empty refs; this aligns the flatfee adapter (childRefsToKeep,
lines, ChildUniqueReferenceID) with the usage-based adapter's pattern.

In `@openmeter/billing/charges/flatfee/service/helpers.go`:
- Around line 22-26: Add a brief clarifying comment above the
persistDetailedLines function to note the soft-delete/reconciliation semantics:
explain that s.adapter.UpsertDetailedLines will soft-delete any existing
detailed lines not present in the provided list, so passing an empty
line.DetailedLines will remove all persisted detailed lines for that charge;
reference persistDetailedLines, UpsertDetailedLines, and DetailedLines in the
comment so future readers understand the reconcile behavior without inspecting
the adapter.

In `@openmeter/billing/charges/flatfee/service/lineengine.go`:
- Around line 60-89: The current loop over input.Lines causes an N+1 by calling
e.service.GetByID for each line; change to collect all ChargeIDs from
input.Lines first, call a batched e.service.GetByIDs (requesting
meta.ExpandRealizations) to fetch all charges at once, populate a chargesByID
map from the batch result, then iterate input.Lines to look up charge :=
chargesByID[*stdLine.ChargeID] and proceed to call
e.service.PostLineAssignedToInvoice and convertCreditRealizations as before;
ensure you still validate missing ChargeID and preserve existing error wrapping
and behavior when PostLineAssignedToInvoice returns an error.

In `@openmeter/billing/charges/usagebased/adapter/charge.go`:
- Around line 158-165: GetByIDs is causing an N+1 when
input.Expands.Has(meta.ExpandDetailedLines) because the current
slicesx.MapWithErr loop calls tx.FetchDetailedLines(ctx, charge) per charge;
change this to a single batched fetch: collect all charge IDs in GetByIDs, call
a new tx.FetchDetailedLinesBatch(ctx, ids) (or overload FetchDetailedLines to
accept []ids) to load all detailed lines in one DB round-trip, then stitch the
returned lines back into the corresponding usagebased.Charge objects before
returning; update the call site where slicesx.MapWithErr and
tx.FetchDetailedLines are used so it uses the batched fetch and in-memory join
instead of per-charge DB calls.

In `@openmeter/billing/charges/usagebased/adapter/detailedline_test.go`:
- Around line 192-196: Add an assertion to verify the newly upserted detailed
line ("new@[2026-01-01T00:00:00Z..2026-02-01T00:00:00Z]") includes its
description (and optionally its expected quantity) so regressions that drop
descriptions on fresh upserts are detected; locate the test block that inspects
fetchedCharge.Realizations[0].DetailedLines.OrEmpty() and add an s.NotNil /
s.Equal check against DetailedLines.OrEmpty()[1].Description (and/or s.Equal on
DetailedLines.OrEmpty()[1].Quantity.InexactFloat64()) to confirm the "new"
line's description is present and correct.
- Around line 57-64: The defer call to migrator.CloseOrLogError() inside
SetupSuite closes the migrator as soon as SetupSuite returns (so it runs
immediately after migrator.Up()), which can be surprising; either replace the
defer with an explicit migrator.CloseOrLogError() immediately after calling
migrator.Up() inside SetupSuite, or move the defer (or a call) into your suite
teardown (e.g., TearDownSuite) so the migrator remains open for the lifetime of
the tests; update references to migrator, SetupSuite, migrator.Up(), and
migrator.CloseOrLogError() accordingly.

In `@openmeter/billing/charges/usagebased/adapter/detailedline.go`:
- Around line 65-102: Add a namespace-consistency guard at the start of
UpsertRunDetailedLines (after chargeID.Validate(), runID.Validate(),
lines.Validate()) that checks chargeID.Namespace vs runID.Namespace and returns
a clear error if they differ; use the existing symbols (chargeID.Namespace,
runID.Namespace) and return a fmt.Errorf or wrapped error indicating the
mismatch so the soft-delete and created line.Namespace cannot cross partitions
silently.

In `@openmeter/billing/charges/usagebased/service_test.go`:
- Around line 11-17: Update TestValidateExpands to a table-driven subtest style:
create a slice of cases (name, input meta.Expands, expected error boolean and
optionally expected error value/message), iterate cases and call
t.Run(case.name, func(t *testing.T){ t.Parallel(); if case.expectError {
require.ErrorIs(t, validateExpands(case.input), <expected error>) or
require.Error(t, validateExpands(case.input)) } else { require.NoError(t,
validateExpands(case.input)) } }); include a case for an empty meta.Expands{} to
lock in "no expands requested" behavior and use meta.ExpandRealizations and
meta.ExpandDetailedLines in the inputs; assert specific error type/message with
require.ErrorIs or a substring match where appropriate.

In `@openmeter/billing/charges/usagebased/service/creditsonly.go`:
- Around line 216-221: The local assignment currentRun.DetailedLines =
mo.Some(runDetailedLines) is dead because it isn't propagated to
s.Charge.Realizations or read before RefetchCharge; either remove that
assignment entirely, or if you want symmetry with creditheninvoice.go, call
s.Charge.Realizations.SetRealizationRun(currentRun) after computing
runDetailedLines so the updated DetailedLines is stored in the charge
realizations; update the code around
PersistRunDetailedLines/UpdateRealizationRun accordingly.

In `@openmeter/billing/charges/usagebased/service/get.go`:
- Around line 111-175: Replace the manual semaphore/wg/errCh pattern with an
errgroup to simplify concurrency: create an errgroup via
errgroup.WithContext(ctx), call g.SetLimit(defaultMaxParallelRatingsPerRequest),
and for each charge use g.Go(func() error { ... }) to run the rating work
(invoke s.rater.GetTotalsForUsage) and return any error instead of pushing to
errCh; store results into ratingResults (keep sync.Map or switch to a map
guarded by a mutex) inside the goroutine; after the loop call g.Wait() and
return its error (or nil) — remove sem.Acquire/Release, wg, errCh, the post-loop
draining logic, and the manual error aggregation.

In `@openmeter/billing/charges/usagebased/service/run/create.go`:
- Around line 191-198: The code calls
updatedCharge.Realizations.SetRealizationRun(currentRun) twice (once inside a
conditional branch and again unconditionally), so remove the duplicate inside
the credit-allocation branch and keep only the single unconditional call;
consolidate the error handling to return CreateRatedRunResult{} with a single
generic fmt.Errorf("update realization run: %w", err) from the remaining
SetRealizationRun call to cover both credits and detailed lines, referencing
updatedCharge.Realizations.SetRealizationRun and CreateRatedRunResult.

In `@openmeter/billing/charges/usagebased/service/run/detailedline_test.go`:
- Around line 70-79: Add assertions that verify the mapper carries through the
item identity and numeric values: in the test using
mapRatingResultToRunDetailedLines (detailedline_test.go) add require.Equal
checks on out[0].ChildUniqueReferenceID, out[0].Name and the numeric fields
out[0].Quantity and out[0].PerUnitAmount (and/or TotalAmount if applicable) to
match the input rating result values used in the test; this ensures
mapRatingResultToRunDetailedLines preserves the
ChildUniqueReferenceID/name/quantity/per-unit amount mapping rather than
silently regressing.

In `@openmeter/billing/charges/usagebased/service/run/detailedline.go`:
- Around line 36-71: The mapRatingResultToRunDetailedLines function currently
accepts run usagebased.RealizationRun but never uses it; remove the unused run
parameter from mapRatingResultToRunDetailedLines (and update all callers, e.g.,
where PersistRunDetailedLines invokes it) OR if run-scoped data is required,
thread run into the mapping and populate a run-specific field on
usagebased.DetailedLine (for example RunID or RunTimestamp) so the mapped lines
reflect the run (update the function signature mapRatingResultToRunDetailedLines
and the return population of usagebased.DetailedLine accordingly, and adjust
PersistRunDetailedLines and any adapter calls that expect the new field).

In `@openmeter/billing/models/stddetailedline/create.go`:
- Around line 32-51: The Create function is passing line.DeletedAt through
without timezone normalization (via SetNillableDeletedAt), causing asymmetry
with the read-path which uses convert.TimePtrIn(..., time.UTC) in FromDB; update
Create (in create.go) to normalize DeletedAt to UTC before calling
SetNillableDeletedAt (e.g., apply the same conversion used in mapping.go/FromDB)
so persisted DeletedAt values are consistently in UTC.

In
`@tools/migrate/migrations/20260422051837_simplify_mixin_detailed_line_partial_indexes.up.sql`:
- Around line 1-12: Dropping and recreating the three unique indexes
(billingstdinvdetailedline_ns_parent_child_id on
billing_standard_invoice_detailed_lines, chargeffdetailedline_ns_charge_child_id
on charge_flat_fee_detailed_line, and
chargeubdetailedline_ns_charge_run_child_id on
charge_usage_based_run_detailed_line) will rebuild the indexes and can block
writes; change the migration to use a non-blocking expand/contract approach
(create the new UNIQUE INDEX CONCURRENTLY with the new predicate or a temporary
non-unique concurrent index, backfill/verify, then drop the old index and rename
the new one) or run CREATE INDEX CONCURRENTLY for the new index and then DROP
INDEX CONCURRENTLY for the old one, and document scheduling requirements so this
runs in a maintenance window if row counts are large.
🪄 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: 57dd8601-1486-47b8-814d-e11a7ecaa293

📥 Commits

Reviewing files that changed from the base of the PR and between 9066703 and d5fe4e0.

⛔ Files ignored due to path filters (2)
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (53)
  • .agents/skills/charges/SKILL.md
  • app/common/charges.go
  • openmeter/billing/adapter/stdinvoicelinemapper.go
  • openmeter/billing/adapter/stdinvoicelines.go
  • openmeter/billing/charges/flatfee/adapter.go
  • openmeter/billing/charges/flatfee/adapter/charge.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/charge.go
  • openmeter/billing/charges/flatfee/detailedline.go
  • openmeter/billing/charges/flatfee/service.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/service.go
  • openmeter/billing/charges/meta/charge.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/billing/charges/usagebased/adapter.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/detailedline.go
  • openmeter/billing/charges/usagebased/adapter/detailedline_test.go
  • openmeter/billing/charges/usagebased/detailedline.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/currenttotals.go
  • openmeter/billing/charges/usagebased/service/get.go
  • openmeter/billing/charges/usagebased/service/rating/details.go
  • openmeter/billing/charges/usagebased/service/rating/quantitysnapshot.go
  • openmeter/billing/charges/usagebased/service/rating/service.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/charges/usagebased/service/rating/totals.go
  • openmeter/billing/charges/usagebased/service/rating/uniqueref.go
  • openmeter/billing/charges/usagebased/service/run/create.go
  • openmeter/billing/charges/usagebased/service/run/detailedline.go
  • openmeter/billing/charges/usagebased/service/run/detailedline_test.go
  • openmeter/billing/charges/usagebased/service/run/service.go
  • openmeter/billing/charges/usagebased/service/service.go
  • openmeter/billing/charges/usagebased/service/statemachine.go
  • openmeter/billing/charges/usagebased/service_test.go
  • openmeter/billing/models/stddetailedline/create.go
  • openmeter/billing/models/stddetailedline/mapping.go
  • openmeter/billing/models/stddetailedline/model.go
  • openmeter/ent/schema/billing.go
  • openmeter/ent/schema/chargesflatfee.go
  • openmeter/ent/schema/chargesusagebased.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • tools/migrate/migrations/20260422051837_simplify_mixin_detailed_line_partial_indexes.down.sql
  • tools/migrate/migrations/20260422051837_simplify_mixin_detailed_line_partial_indexes.up.sql

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

🧹 Nitpick comments (1)
openmeter/billing/charges/usagebased/service/rating/details.go (1)

16-57: Nice, clean input/result split — LGTM. 👍

The GetDetailedLinesForUsageInput.Validate() order is sensible (charge → customer → meter → offset → prior runs → detailed-lines expansion), and bundling the snapshot Quantity alongside GenerateDetailedLinesResult in GetRatingForUsageResult gives callers everything they need for persistence without re-deriving it.

Tiny optional nit: the result type is GetRatingForUsageResult while the method is GetDetailedLinesForUsage — renaming to GetDetailedLinesForUsageResult would make the pairing obvious at call sites. Totally up to you.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/service/rating/details.go` around lines
16 - 57, Rename the result struct GetRatingForUsageResult to
GetDetailedLinesForUsageResult so it clearly pairs with the
GetDetailedLinesForUsage method; update the type name wherever referenced (e.g.,
construction, return signatures, imports or tests) to use
GetDetailedLinesForUsageResult and keep the embedded
billingrating.GenerateDetailedLinesResult and Quantity alpacadecimal.Decimal
fields unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@openmeter/billing/charges/usagebased/service/rating/details.go`:
- Around line 16-57: Rename the result struct GetRatingForUsageResult to
GetDetailedLinesForUsageResult so it clearly pairs with the
GetDetailedLinesForUsage method; update the type name wherever referenced (e.g.,
construction, return signatures, imports or tests) to use
GetDetailedLinesForUsageResult and keep the embedded
billingrating.GenerateDetailedLinesResult and Quantity alpacadecimal.Decimal
fields unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b0c1ece4-7a64-47f6-b4a3-b7d996871005

📥 Commits

Reviewing files that changed from the base of the PR and between d5fe4e0 and abb3163.

📒 Files selected for processing (1)
  • openmeter/billing/charges/usagebased/service/rating/details.go

@turip
turip merged commit 605f03f into main Apr 22, 2026
27 checks passed
@turip
turip deleted the feat/persist-detailed-lines branch April 22, 2026 07:59

This branch was previously deployed

1 inactive deployment
dev — 0d994b02 Deployed Apr 22, 2026 by turip via Migration Checks #13723
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants