Skip to content

feat: refactor charges common meta to use mixins - #3995

Merged
turip merged 8 commits into
mainfrom
refactor/get-rid-of-meta
Mar 25, 2026
Merged

turip merged 8 commits into
mainfrom
refactor/get-rid-of-meta

Conversation

@turip

@turip turip commented Mar 23, 2026 •

Copy link
Copy Markdown
Member

Overview

This patch simplifies create/get flows for charges by using a mixin for common fields and a view for searches. The view related details are added to the code.

Notes for reviewer

Summary by CodeRabbit

  • New Features

    • Paginated charge listing with filters (namespace, customers, status) and unified ID-based retrieval across charge types; adds charge-type-aware listing/search.
  • Chores

    • Added Make target to generate SQL for DB views.
  • Documentation

    • Clarified database migration guidance for ent view schemas and how to handle Atlas/Ent-generated migration metadata.
  • Chores / Breaking changes

    • Public retrieval and metadata APIs updated to ID-based retrieval and charge registration/deletion flows.

@coderabbitai

coderabbitai Bot commented Mar 23, 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: 99fd7c86-86cc-4c28-814c-7d75eebeff1e

📥 Commits

Reviewing files that changed from the base of the PR and between b6548b4 and 78cb732.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (2)
  • openmeter/billing/charges/meta/adapter.go
  • pkg/framework/entutils/idorder_test.go

📝 Walkthrough

Walkthrough

Refactors billing/charges from meta-first CRUD to a registration/search model: adds a chargemeta Ent mixin, replaces many GetByMetas calls with GetByIDs, introduces a ChargesSearchAdapter (GetTypesByIDs, ListCharges), implements search/list adapters and type-based expansion, and moves meta creation/updates into DB builders plus a RegisterCharges flow.

Changes

Cohort / File(s) Summary
Docs & Tooling
AGENTS.md, Makefile
Document ent.View migration caveat and manual view SQL step; add generate-view-sql Make target to run the view SQL generator.
Charges core & search
openmeter/billing/charges/adapter.go, openmeter/billing/charges/charge.go, openmeter/billing/charges/adapter/search.go, openmeter/billing/charges/service.go, openmeter/billing/charges/service/list.go, openmeter/billing/charges/service/get.go
Embed ChargesSearchAdapter into Adapter; add GetTypesByIDs and ListCharges; implement search adapter and ID-order accessor; add service ListCharges and change GetByIDs-based expansion flow.
Meta adapter → registration
openmeter/billing/charges/meta/adapter.go, openmeter/billing/charges/meta/adapter/charges.go
Replace meta CRUD surface with registration API (RegisterCharges, DeleteRegisteredCharge) and new input types (RegisterChargesInput, IDWithUniqueReferenceID).
Meta adapter removals
openmeter/billing/charges/meta/adapter/create.go, .../get.go, .../update.go, .../mapper.go
Remove legacy meta Create/Get/Update implementations and DB→meta mapping functions (deleted modules).
Chargemeta model & helpers
openmeter/billing/charges/meta/charge.go, openmeter/billing/charges/models/chargemeta/mixin.go
Add ChargeIDs helper and a new chargemeta Ent mixin with Create/Update/MapFromDB helpers centralizing metadata mapping and DB fields (incl. unique partial index).
Usage-based charges
openmeter/billing/charges/usagebased/...
Switch GetByMetas→GetByIDs, persist status/meta via DB builders using chargemeta helpers, add MapChargeFromDB, adjust create/update flows, and register created charges with meta adapter.
Flat-fee charges
openmeter/billing/charges/flatfee/...
Switch GetByMetas→GetByIDs, remove meta-dependent create/update flows, derive metadata from DB via mixin, and change create helper signature to namespace+intent.
Credit-purchase charges
openmeter/billing/charges/creditpurchase/...
Switch GetByMetas→GetByIDs, perform direct DB create/update flows, derive metadata from DB mapping, and register created charges post-insert.
Service callsite updates
openmeter/billing/charges/service/advance.go, .../invoice.go, .../invoicependinglines.go
Replace meta-based listing/calls with new ListCharges/GetByIDs flows and update call sites to the new ID/expands shapes.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant ChargeService as ChargeService
    participant ChargesSearch as ChargesSearchAdapter
    participant TypeAdapters as TypeAdapters
    participant DB as DB

    Note over Client,DB: Type-based resolution using search + per-type adapters
    Client->>ChargeService: GetByIDs(IDs)
    ChargeService->>ChargesSearch: GetTypesByIDs(IDs)
    ChargesSearch->>DB: Query charges_search (namespace, IDs)
    DB-->>ChargesSearch: ChargeWithType[]
    ChargesSearch-->>ChargeService: ChargesWithTypes (ordered)
    ChargeService->>TypeAdapters: Group IDs by type and call GetByIDs(per-type)
    TypeAdapters->>DB: Query per-type charge tables
    DB-->>TypeAdapters: Charge entities
    TypeAdapters-->>ChargeService: Typed Charge[] (per-type)
    ChargeService->>ChargeService: Merge & reorder results to original input order
    ChargeService-->>Client: Charge[]
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 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 main refactoring effort—moving charges metadata handling to use mixins instead of the prior adapter-based approach.

✏️ 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 refactor/get-rid-of-meta

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.

Comment thread tools/migrate/migrations/atlas.sum Resolved
@turip
turip force-pushed the refactor/get-rid-of-meta branch from 42a6956 to 628215c Compare March 24, 2026 09:04
@turip
turip force-pushed the refactor/get-rid-of-meta branch from 628215c to 2574aae Compare March 24, 2026 13:59
@turip
turip force-pushed the refactor/get-rid-of-meta branch from 2574aae to b447f0f Compare March 24, 2026 14:04
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch 2 times, most recently from 593832e to 04aaba5 Compare March 24, 2026 14:29
Base automatically changed from feat/usage-based-charges-lifecycle to main March 24, 2026 19:34
@turip
turip force-pushed the refactor/get-rid-of-meta branch from b447f0f to da17bfd Compare March 25, 2026 07:49
@turip
turip force-pushed the refactor/get-rid-of-meta branch from da17bfd to 9aa0c94 Compare March 25, 2026 08:51
@turip
turip marked this pull request as ready for review March 25, 2026 09:12
@turip
turip requested a review from a team as a code owner March 25, 2026 09:12
@turip turip added release-note/feature Release note: Exciting New Features area/billing labels Mar 25, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (9)
AGENTS.md (1)

110-111: Great documentation addition!

This is exactly the kind of helpful guidance that saves future developers (and agents!) from debugging a non-issue. The wording is clear, actionable, and durable. Nice tie-in with the new generate-view-sql Makefile target too.

One tiny suggestion: consider adding a reference to make generate-view-sql here since it's the tool designed to help with this exact caveat.

📝 Optional: Add cross-reference to the new Makefile target
-**Ent view caveat:** in this repo's current Ent/Atlas setup, schemas declared with `ent.View` can generate query code under `openmeter/ent/db/`, but they do not appear in `openmeter/ent/db/migrate/schema.go` or the generated `migrate.Tables` list. If `atlas migrate --env local diff ...` reports no changes for a new view, verify whether the view exists in generated migration metadata before debugging Atlas; view DDL may need an explicit SQL migration until generator support is added.
+**Ent view caveat:** in this repo's current Ent/Atlas setup, schemas declared with `ent.View` can generate query code under `openmeter/ent/db/`, but they do not appear in `openmeter/ent/db/migrate/schema.go` or the generated `migrate.Tables` list. If `atlas migrate --env local diff ...` reports no changes for a new view, verify whether the view exists in generated migration metadata before debugging Atlas; view DDL may need an explicit SQL migration until generator support is added. Use `make generate-view-sql` to generate view SQL when needed.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@AGENTS.md` around lines 110 - 111, Add a brief cross-reference to the new
Makefile target by mentioning "make generate-view-sql" in the Ent view caveat:
update the paragraph that discusses how view DDL may need an explicit SQL
migration to suggest running make generate-view-sql to produce the view SQL as a
quick verification/fix step; reference the existing terms "ent.View" and the
generated migration metadata (migrate.Tables / migrate/schema.go) so readers
know exactly where to check and which command to run.
openmeter/billing/charges/models/chargemeta/mixin.go (1)

189-193: Normalize AdvanceAfter to UTC too.

Everything else in this mixin gets normalized on the way in/out, but AdvanceAfter is passed through as-is. Keeping one shared timestamp special makes scheduler/API behavior timezone-dependent for no real upside.

♻️ Small cleanup
@@
-		SetNillableAdvanceAfter(in.AdvanceAfter).
+		SetNillableAdvanceAfter(convert.TimePtrIn(in.AdvanceAfter, time.UTC)).
@@
-		SetOrClearAdvanceAfter(in.AdvanceAfter).
+		SetOrClearAdvanceAfter(convert.TimePtrIn(in.AdvanceAfter, time.UTC)).
@@
-		AdvanceAfter: entity.GetAdvanceAfter(),
+		AdvanceAfter: convert.TimePtrIn(entity.GetAdvanceAfter(), time.UTC),

Also applies to: 220-221, 292-294

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

In `@openmeter/billing/charges/models/chargemeta/mixin.go` around lines 189 - 193,
Normalize AdvanceAfter to UTC before storing and when reading: when calling
SetNillableAdvanceAfter(pass in.AdvanceAfter) convert the time pointer to UTC
(e.g., if in.AdvanceAfter != nil then use ptrTo(in.AdvanceAfter.UTC()) ) so you
store a UTC timestamp; apply the same normalization at the other occurrences
noted (the calls around SetNillableAdvanceAfter at the other blocks referenced)
and ensure nils are preserved when normalizing.
openmeter/billing/charges/service/invoice.go (1)

156-166: Dedup the charge IDs before the batch fetch.

A single charge can back multiple standard lines, so this can send the same ID through GetByIDs several times. That adds avoidable DB work and repeated expansion for no gain. Deduping the mapped IDs before the call would keep this invoice hook cheaper. 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 `@openmeter/billing/charges/service/invoice.go` around lines 156 - 166, The
mapped list of charge IDs passed to s.GetByIDs is not deduplicated causing
duplicate DB work; before calling s.GetByIDs (the call that builds meta.ChargeID
from billing.StandardLineWithInvoiceHeader via lo.Map over linesWithChargeID)
collapse duplicates (e.g., build a set keyed by Namespace+ID or use a
map[meta.ChargeID]struct{}), then convert the unique keys back to a slice and
pass that deduped slice into GetByIDs with the same meta.Expands; update the
code around the linesWithChargeID mapping to use the deduped slice.
openmeter/billing/charges/service/get.go (1)

68-90: Consider skipping service calls when there are no charges of that type.

If chargesByType[meta.ChargeTypeUsageBased] is nil/empty, the code still calls s.usageBasedService.GetByIDs with an empty IDs slice. Same for flat fees and credit purchases.

This works if the services handle empty input gracefully (returning []Charge{}, nil), but you could save the round-trip entirely:

💡 Optional optimization
var usageBased []usagebased.Charge
if ids := chargesByType[meta.ChargeTypeUsageBased]; len(ids) > 0 {
    usageBased, err = s.usageBasedService.GetByIDs(ctx, usagebased.GetByIDsInput{
        IDs:     ids,
        Expands: expands,
    })
    if err != nil {
        return nil, err
    }
}
// Similar for flatFee and creditPurchase
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/service/get.go` around lines 68 - 90, The service
calls always invoke s.usageBasedService.GetByIDs, s.flatFeeService.GetByIDs and
s.creditPurchaseService.GetByIDs even when the corresponding chargesByType[...]
slices are empty; avoid unnecessary calls by checking the slice length first
(e.g., if ids := chargesByType[meta.ChargeTypeUsageBased]; len(ids) > 0 { call
s.usageBasedService.GetByIDs(...) } else leave usageBased as an empty slice) and
apply the same pattern for meta.ChargeTypeFlatFee and
meta.ChargeTypeCreditPurchase so you only call each service when there are IDs
to request and still return empty slices when none exist.
openmeter/billing/charges/creditpurchase/service.go (1)

60-81: Remove the orphaned GetByMetasInput struct and its Validate() method (lines 60–81).

The interface was refactored to use GetByIDs with GetByIDsInput (defined in the adapter layer), but GetByMetasInput got left behind and isn't referenced anywhere in the codebase. Cleaning it up will keep things tidy and avoid confusion for future readers.

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

In `@openmeter/billing/charges/creditpurchase/service.go` around lines 60 - 81,
Delete the unused GetByMetasInput type and its associated Validate() method
(symbols: GetByMetasInput and GetByMetasInput.Validate) from the file; remove
both the struct definition and the Validate function implementation so only the
current GetByIDs flow (using GetByIDsInput in adapters) remains and no orphaned
types/methods are left behind.
openmeter/billing/charges/meta/adapter/charges.go (1)

51-63: Consider handling the "not found" case explicitly.

UpdateOneID(...).Where(...).Exec(ctx) will return an error if no matching record exists (either the ID doesn't exist or it's already soft-deleted). If a "not found" scenario should be handled gracefully (e.g., idempotent deletes), you might want to catch that specific error. Otherwise, this looks good!

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

In `@openmeter/billing/charges/meta/adapter/charges.go` around lines 51 - 63, The
DeleteRegisteredCharge method should treat a "not found" result from
tx.db.Charge.UpdateOneID(...).Where(...).SetDeletedAt(...).Exec(ctx) explicitly
instead of propagating it; modify the entutils.TransactingRepoWithNoValue
callback in DeleteRegisteredCharge to capture the Exec error, detect the ent/DB
not-found condition (e.g., ent NotFound/record-not-exist sentinel from your DB
driver) and return nil for idempotent deletes (or convert it to a more specific
error per your API), while still returning other errors unchanged; reference
functions/types: DeleteRegisteredCharge, entutils.TransactingRepoWithNoValue,
tx.db.Charge.UpdateOneID, chargedb.DeletedAtIsNil.
openmeter/billing/charges/meta/adapter.go (1)

25-41: Consider validating non-empty Charges slice.

The validation checks for namespace, type, and individual charge IDs, but doesn't prevent an empty Charges slice. If registering zero charges is invalid (likely a caller bug), might be worth adding:

Suggested addition
 func (i RegisterChargesInput) Validate() error {
 	var errs []error
 	if i.Namespace == "" {
 		errs = append(errs, errors.New("namespace is required"))
 	}

 	if i.Type == "" {
 		errs = append(errs, errors.New("type is required"))
 	}

+	if len(i.Charges) == 0 {
+		errs = append(errs, errors.New("at least one charge is required"))
+	}
+
 	for idx, charge := range i.Charges {
 		if charge.ID == "" {
 			errs = append(errs, fmt.Errorf("charge [%d]: ID is required", idx))
 		}
 	}
 	return errors.Join(errs...)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/meta/adapter.go` around lines 25 - 41,
RegisterChargesInput.Validate currently omits a check that the Charges slice is
non-empty; add a validation that ensures len(i.Charges) > 0 (or i.Charges != nil
&& len(i.Charges) > 0) and append an error like errors.New("charges is
required") when it's empty before iterating through charges; keep using
errors.Join at the end and update the error message to match existing style,
referencing the Validate method and the Charges field.
openmeter/billing/charges/service.go (1)

142-152: Consider adding Expands validation for consistency.

GetByIDInput and GetByIDsInput both validate Expands, but ListChargesInput.Validate() doesn't. For consistency and defensive coding, might be worth adding:

Suggested addition
 func (i ListChargesInput) Validate() error {
 	var errs []error

 	for _, status := range i.StatusNotIn {
 		if err := status.Validate(); err != nil {
 			errs = append(errs, fmt.Errorf("status: %w", err))
 		}
 	}

+	if err := i.Expands.Validate(); err != nil {
+		errs = append(errs, fmt.Errorf("expands: %w", err))
+	}
+
 	return errors.Join(errs...)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/service.go` around lines 142 - 152,
ListChargesInput.Validate currently validates StatusNotIn but omits validating
the Expands field; add the same expands validation logic used in GetByIDInput
and GetByIDsInput to ListChargesInput.Validate by iterating over i.Expands (or
calling the shared expands validator) and appending any fmt.Errorf("expands:
%w", err) to errs before returning errors.Join(errs...), ensuring the function
references ListChargesInput.Validate, the Expands field, and retains existing
StatusNotIn validation.
openmeter/billing/charges/flatfee/adapter/charge.go (1)

148-183: Unused ctx parameter.

The ctx parameter is passed to buildCreateFlatFeeCharge but isn't used anywhere in the function body. Either remove it or consider if it's needed for future use.

Suggested fix
-func (a *adapter) buildCreateFlatFeeCharge(ctx context.Context, ns string, intent flatfee.IntentWithInitialStatus) (*db.ChargeFlatFeeCreate, error) {
+func (a *adapter) buildCreateFlatFeeCharge(ns string, intent flatfee.IntentWithInitialStatus) (*db.ChargeFlatFeeCreate, error) {

And update the call site at line 75:

-			return tx.buildCreateFlatFeeCharge(ctx, in.Namespace, intent)
+			return tx.buildCreateFlatFeeCharge(in.Namespace, intent)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/flatfee/adapter/charge.go` around lines 148 - 183,
The ctx parameter on buildCreateFlatFeeCharge is unused; remove ctx from the
function signature (func (a *adapter) buildCreateFlatFeeCharge(ns string, intent
flatfee.IntentWithInitialStatus) (*db.ChargeFlatFeeCreate, error)) and update
all call sites to stop passing a context argument (search for
buildCreateFlatFeeCharge usages and remove the ctx param), or alternatively if
you actually need context for DB/chargemeta calls, thread ctx into the places
that require it (e.g., any future Create calls) instead of leaving an unused
parameter.
🤖 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/charge.go`:
- Around line 136-151: GetID and GetNamespace currently swallow GetChargeID
errors and return empty strings which produces identical ("","") ordering keys
for invalid Charges; change both methods on type Charge (GetID and GetNamespace)
to return (string, error) instead of just string, call GetChargeID(), and if it
returns an error propagate that error up rather than returning "", and update
all callers to handle the error (i.e., use the returned error to fail
reordering/ordering operations instead of treating an empty string as a valid
key).

In `@openmeter/billing/charges/models/chargemeta/mixin.go`:
- Around line 71-84: The subscription fields (subscription_id,
subscription_phase_id, subscription_item_id) currently allow partial rows which
breaks MapFromDB()'s reconstruction of Subscription; add an all-or-none DB
validation in the mixin so partial presence is rejected rather than silently
flattened. Specifically, in the mixin that defines those fields, implement a
check (e.g., in the mixin's hook that runs after load/from-DB or in the entity's
validation before save) that ensures either all three fields are nil/empty or
all three are non-nil/non-empty, and return an error if the row is partially
populated so MapFromDB() and the Subscription reconstruction fail fast. Ensure
the check references the exact field names subscription_id,
subscription_phase_id, subscription_item_id and ties into the existing
MapFromDB()/Subscription logic path so partial writes are detected at read or
write time.

---

Nitpick comments:
In `@AGENTS.md`:
- Around line 110-111: Add a brief cross-reference to the new Makefile target by
mentioning "make generate-view-sql" in the Ent view caveat: update the paragraph
that discusses how view DDL may need an explicit SQL migration to suggest
running make generate-view-sql to produce the view SQL as a quick
verification/fix step; reference the existing terms "ent.View" and the generated
migration metadata (migrate.Tables / migrate/schema.go) so readers know exactly
where to check and which command to run.

In `@openmeter/billing/charges/creditpurchase/service.go`:
- Around line 60-81: Delete the unused GetByMetasInput type and its associated
Validate() method (symbols: GetByMetasInput and GetByMetasInput.Validate) from
the file; remove both the struct definition and the Validate function
implementation so only the current GetByIDs flow (using GetByIDsInput in
adapters) remains and no orphaned types/methods are left behind.

In `@openmeter/billing/charges/flatfee/adapter/charge.go`:
- Around line 148-183: The ctx parameter on buildCreateFlatFeeCharge is unused;
remove ctx from the function signature (func (a *adapter)
buildCreateFlatFeeCharge(ns string, intent flatfee.IntentWithInitialStatus)
(*db.ChargeFlatFeeCreate, error)) and update all call sites to stop passing a
context argument (search for buildCreateFlatFeeCharge usages and remove the ctx
param), or alternatively if you actually need context for DB/chargemeta calls,
thread ctx into the places that require it (e.g., any future Create calls)
instead of leaving an unused parameter.

In `@openmeter/billing/charges/meta/adapter.go`:
- Around line 25-41: RegisterChargesInput.Validate currently omits a check that
the Charges slice is non-empty; add a validation that ensures len(i.Charges) > 0
(or i.Charges != nil && len(i.Charges) > 0) and append an error like
errors.New("charges is required") when it's empty before iterating through
charges; keep using errors.Join at the end and update the error message to match
existing style, referencing the Validate method and the Charges field.

In `@openmeter/billing/charges/meta/adapter/charges.go`:
- Around line 51-63: The DeleteRegisteredCharge method should treat a "not
found" result from
tx.db.Charge.UpdateOneID(...).Where(...).SetDeletedAt(...).Exec(ctx) explicitly
instead of propagating it; modify the entutils.TransactingRepoWithNoValue
callback in DeleteRegisteredCharge to capture the Exec error, detect the ent/DB
not-found condition (e.g., ent NotFound/record-not-exist sentinel from your DB
driver) and return nil for idempotent deletes (or convert it to a more specific
error per your API), while still returning other errors unchanged; reference
functions/types: DeleteRegisteredCharge, entutils.TransactingRepoWithNoValue,
tx.db.Charge.UpdateOneID, chargedb.DeletedAtIsNil.

In `@openmeter/billing/charges/models/chargemeta/mixin.go`:
- Around line 189-193: Normalize AdvanceAfter to UTC before storing and when
reading: when calling SetNillableAdvanceAfter(pass in.AdvanceAfter) convert the
time pointer to UTC (e.g., if in.AdvanceAfter != nil then use
ptrTo(in.AdvanceAfter.UTC()) ) so you store a UTC timestamp; apply the same
normalization at the other occurrences noted (the calls around
SetNillableAdvanceAfter at the other blocks referenced) and ensure nils are
preserved when normalizing.

In `@openmeter/billing/charges/service.go`:
- Around line 142-152: ListChargesInput.Validate currently validates StatusNotIn
but omits validating the Expands field; add the same expands validation logic
used in GetByIDInput and GetByIDsInput to ListChargesInput.Validate by iterating
over i.Expands (or calling the shared expands validator) and appending any
fmt.Errorf("expands: %w", err) to errs before returning errors.Join(errs...),
ensuring the function references ListChargesInput.Validate, the Expands field,
and retains existing StatusNotIn validation.

In `@openmeter/billing/charges/service/get.go`:
- Around line 68-90: The service calls always invoke
s.usageBasedService.GetByIDs, s.flatFeeService.GetByIDs and
s.creditPurchaseService.GetByIDs even when the corresponding chargesByType[...]
slices are empty; avoid unnecessary calls by checking the slice length first
(e.g., if ids := chargesByType[meta.ChargeTypeUsageBased]; len(ids) > 0 { call
s.usageBasedService.GetByIDs(...) } else leave usageBased as an empty slice) and
apply the same pattern for meta.ChargeTypeFlatFee and
meta.ChargeTypeCreditPurchase so you only call each service when there are IDs
to request and still return empty slices when none exist.

In `@openmeter/billing/charges/service/invoice.go`:
- Around line 156-166: The mapped list of charge IDs passed to s.GetByIDs is not
deduplicated causing duplicate DB work; before calling s.GetByIDs (the call that
builds meta.ChargeID from billing.StandardLineWithInvoiceHeader via lo.Map over
linesWithChargeID) collapse duplicates (e.g., build a set keyed by Namespace+ID
or use a map[meta.ChargeID]struct{}), then convert the unique keys back to a
slice and pass that deduped slice into GetByIDs with the same meta.Expands;
update the code around the linesWithChargeID mapping to use the deduped slice.
🪄 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: 105efe7e-b4a2-44ec-b518-bbd24a68ba5c

📥 Commits

Reviewing files that changed from the base of the PR and between ec000f4 and 9aa0c94.

⛔ Files ignored due to path filters (66)
  • go.mod is excluded by !**/*.mod
  • openmeter/ent/db/charge.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge/charge.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase/chargecreditpurchase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee/chargeflatfee.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargessearchv1.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargessearchv1/chargessearchv1.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargessearchv1/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargessearchv1_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/cursor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/customer.go is excluded by !**/ent/db/**
  • openmeter/ent/db/customer/customer.go is excluded by !**/ent/db/**
  • openmeter/ent/db/customer/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/customer_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/customer_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/customer_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ent.go is excluded by !**/ent/db/**
  • openmeter/ent/db/entmixinaccessor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/expose.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/paginate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/predicate/predicate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscription.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscription/subscription.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscription/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscription_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscription_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscription_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionitem.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionitem/subscriptionitem.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionitem/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionitem_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionitem_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionitem_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionphase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionphase/subscriptionphase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionphase/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionphase_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionphase_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionphase_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/tx.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (52)
  • AGENTS.md
  • Makefile
  • openmeter/billing/charges/adapter.go
  • openmeter/billing/charges/adapter/search.go
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/creditpurchase/adapter.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper.go
  • openmeter/billing/charges/creditpurchase/service.go
  • openmeter/billing/charges/creditpurchase/service/get.go
  • openmeter/billing/charges/flatfee/adapter.go
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go
  • openmeter/billing/charges/flatfee/service.go
  • openmeter/billing/charges/flatfee/service/get.go
  • openmeter/billing/charges/meta/adapter.go
  • openmeter/billing/charges/meta/adapter/charges.go
  • openmeter/billing/charges/meta/adapter/create.go
  • openmeter/billing/charges/meta/adapter/get.go
  • openmeter/billing/charges/meta/adapter/mapper.go
  • openmeter/billing/charges/meta/adapter/update.go
  • openmeter/billing/charges/meta/charge.go
  • openmeter/billing/charges/models/chargemeta/mixin.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/service/advance.go
  • openmeter/billing/charges/service/get.go
  • openmeter/billing/charges/service/invoice.go
  • openmeter/billing/charges/service/invoicependinglines.go
  • openmeter/billing/charges/service/list.go
  • openmeter/billing/charges/usagebased/adapter.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/mapper.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/create.go
  • openmeter/billing/charges/usagebased/service/get.go
  • openmeter/billing/charges/usagebased/statemachine.go
  • openmeter/ent/entc.go
  • openmeter/ent/schema/charges.go
  • openmeter/ent/schema/chargescreditpurchase.go
  • openmeter/ent/schema/chargesflatfee.go
  • openmeter/ent/schema/chargesusagebased.go
  • openmeter/ent/schema/customer.go
  • openmeter/ent/schema/subscription.go
  • pkg/framework/entutils/entsetorclear/setorclear.tpl
  • pkg/framework/entutils/idorder.go
  • tools/migrate/README.md
  • tools/migrate/cmd/viewgen/main.go
  • tools/migrate/migrations/20260325084446_charges-refactor-tables.down.sql
  • tools/migrate/migrations/20260325084446_charges-refactor-tables.up.sql
  • tools/migrate/view_parity_test.go
  • tools/migrate/viewgen/viewgen.go
  • tools/migrate/views.sql
💤 Files with no reviewable changes (4)
  • openmeter/billing/charges/meta/adapter/get.go
  • openmeter/billing/charges/meta/adapter/mapper.go
  • openmeter/billing/charges/meta/adapter/update.go
  • openmeter/billing/charges/meta/adapter/create.go

Comment thread openmeter/billing/charges/charge.go Resolved
@turip turip changed the title feat: get rid of meta feat: refactor charges common meta to use mixins Mar 25, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
openmeter/billing/charges/models/chargemeta/mixin.go (1)

157-161: Make Update() enforce the same input contract as Create().

Create() fails fast on in.Intent.Validate(), but Update() trusts every caller to remember that precondition. Since this helper is now the shared metadata write path, keeping the validation here would make it a lot harder to misuse from another adapter later. As per coding guidelines, **/*.go: In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them.

💡 Possible tweak
 func Update[T Updater[T]](updater Updater[T], in UpdateInput) (T, error) {
+	if err := in.Intent.Validate(); err != nil {
+		var empty T
+		return empty, err
+	}
+
 	return updater.
 		SetName(in.Intent.Name).
 		SetOrClearDeletedAt(convert.TimePtrIn(in.DeletedAt, time.UTC)).
 		SetOrClearDescription(in.Intent.Description).

Also applies to: 207-223

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

In `@openmeter/billing/charges/models/chargemeta/mixin.go` around lines 157 - 161,
Create() validates the input intent with in.Intent.Validate() before proceeding;
Update() should enforce the same contract to avoid misuse. Modify the
Update(...) helper to call in.Intent.Validate() at the start, returning an empty
T and the validation error on failure (mirroring Create's behavior), so that
Update, like Create, fails fast; reference the Update function and the
UpdateInput type and use Intent.Validate() the same way Create[T Creator[T]]
does.
🤖 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 50-54: The call to chargemeta.Update is missing
UpdateInput.AdvanceAfter which causes SetOrClearAdvanceAfter to clear existing
advance_after; include AdvanceAfter in the UpdateInput (e.g., AdvanceAfter:
charge.AdvanceAfter) when calling chargemeta.Update(update,
chargemeta.UpdateInput{...}) so the existing advance_after value is preserved
unless intentionally changed.
- Around line 119-124: The query currently strips meta.ChargeID to raw strings
via lo.Map(input.IDs...) and only reapplies namespacing later (e.g., in
InIDOrder), which makes the DB lookup unscoped by namespace; change the
predicate building in tx.db.ChargeFlatFee.Query() to include namespace as part
of the Ent predicate (e.g., combine dbchargeflatfee.NamespaceEQ(namespace) with
dbchargeflatfee.IDIn(...) or build per-namespace ID lists and use an AND/OR
compound predicate) so that the database query itself uses (namespace AND id IN
...) semantics rather than relying on a reorder step; update the analogous logic
used around InIDOrder (lines ~137-140) to follow the same namespaced predicate
pattern.

In `@openmeter/billing/charges/service.go`:
- Around line 132-156: The ListChargesInput.Validate method is missing
validation of the embedded pagination.Page and should also include index
information when reporting StatusNotIn errors; update ListChargesInput.Validate
to call i.Page.Validate() and append any returned error (e.g., "page: %w") to
errs, and change the status loop to include the index in the error message
(e.g., "status[%d]: %w") when status.Validate() fails; keep the existing
Expands.Validate() handling as-is and return errors.Join(errs...).

---

Nitpick comments:
In `@openmeter/billing/charges/models/chargemeta/mixin.go`:
- Around line 157-161: Create() validates the input intent with
in.Intent.Validate() before proceeding; Update() should enforce the same
contract to avoid misuse. Modify the Update(...) helper to call
in.Intent.Validate() at the start, returning an empty T and the validation error
on failure (mirroring Create's behavior), so that Update, like Create, fails
fast; reference the Update function and the UpdateInput type and use
Intent.Validate() the same way Create[T Creator[T]] does.
🪄 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: 6bcd7011-ce4c-499c-a2c9-5a5b2a08613f

📥 Commits

Reviewing files that changed from the base of the PR and between 9aa0c94 and d21fe3d.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (8)
  • openmeter/billing/charges/creditpurchase/service.go
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/models/chargemeta/mixin.go
  • openmeter/billing/charges/service.go
  • pkg/framework/entutils/idorder.go
  • pkg/framework/entutils/idorder_test.go
  • tools/migrate/migrations/20260325084446_charges-refactor-tables.down.sql
  • tools/migrate/migrations/20260325084446_charges-refactor-tables.up.sql

Comment thread openmeter/billing/charges/service.go Resolved
Comment thread tools/migrate/migrations/atlas.sum Resolved
Comment thread tools/migrate/migrations/atlas.sum Resolved
Comment thread tools/migrate/migrations/atlas.sum Resolved
Comment thread tools/migrate/migrations/atlas.sum Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (4)
.agents/skills/db-migration/SKILL.md (1)

62-62: Optional: Consider simplifying the view parity test explanation.

The sentence explaining the view parity test is pretty packed. You might make it more scannable by splitting it up or leading with the key point. Something like:

The view parity test (TestViewDefinitionsMatchGeneratedSchemaSQL in tools/migrate/view_parity_test.go) validates that view definitions in migrations match the generated view SQL. The test isolates VIEW statements from other DDL, so it's safe to mix VIEW and non-VIEW statements in a single migration file.

But honestly, the current version works fine too — just a readability nitpick!

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

In @.agents/skills/db-migration/SKILL.md at line 62, Rewrite the dense sentence
in SKILL.md to split the key points into two clearer sentences: state that the
view parity test (TestViewDefinitionsMatchGeneratedSchemaSQL in
tools/migrate/view_parity_test.go) validates that view definitions in migrations
match the generated view SQL, then add a second sentence explaining that the
test isolates/strips VIEW statements while preserving other DDL so mixing VIEW
and non-VIEW statements in one migration is safe. Use the test name
TestViewDefinitionsMatchGeneratedSchemaSQL and the file path
tools/migrate/view_parity_test.go in the text to keep the reference clear.
openmeter/billing/charges/creditpurchase/adapter.go (1)

27-52: Maybe share this ID lookup input across charge adapters.

This is now basically the same shape and validator as openmeter/billing/charges/flatfee/adapter.go. Pulling the common bits into the parent charges package would make it much harder for the ID-lookup contract to drift between charge types.

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

In `@openmeter/billing/charges/creditpurchase/adapter.go` around lines 27 - 52,
Extract the duplicated GetByIDsInput struct and its Validate method (symbols:
GetByIDsInput, Validate, Expands) from
openmeter/billing/charges/creditpurchase/adapter.go and
openmeter/billing/charges/flatfee/adapter.go into a single shared definition in
the parent charges package (openmeter/billing/charges); update both adapters to
import and use charges.GetByIDsInput (or move the type to the charges package
and reference it as charges.GetByIDsInput) so the ID-lookup contract is
centralized and cannot drift, and ensure imports and any package-qualified
references are adjusted accordingly.
openmeter/billing/charges/usagebased/adapter/charge.go (1)

111-113: Fix the inline note to match the query.

The comment says the namespace filter is skipped, but the next line applies Namespace(input.Namespace). In this lookup path that reads like the opposite of what the code does.

🤖 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 111 -
113, Update the inline comment to reflect that the namespace filter is in fact
applied to the query: replace the misleading "we are skipping the namespace
filter here" note with a short comment stating that the query includes
Namespace(input.Namespace) and then filters by IDs via
dbchargeusagebased.IDIn(input.IDs...), so the lookup is constrained to the
provided namespace and IDs (reference dbchargeusagebased.Namespace and
dbchargeusagebased.IDIn).
openmeter/billing/charges/service/advance.go (1)

23-38: Avoid expanding every charge type in a usage-based-only pass.

This path only uses chargesByType.usageBased, but s.ListCharges(..., Expands: meta.ExpandRealizations) expands every non-final charge for the customer first. Flat-fee and credit-purchase charges get loaded and expanded just to be dropped a few lines later. A lighter flow would be to list IDs/types first, then expand only the usage-based subset, or add a type filter in the search layer.

As per coding guidelines, performance should be a priority in critical code paths and database operations.

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

In `@openmeter/billing/charges/service/advance.go` around lines 23 - 38, The
current call to s.ListCharges expands realizations for all non-final charges
(Expands: meta.ExpandRealizations) even though this path only uses
chargesByType.usageBased; change the flow to first list charges without
expanding realizations (omit meta.ExpandRealizations or use a lightweight
Expands), derive types via chargesByType(inScopeCharges.Items) and if
len(chargesByType.usageBased) > 0 then call s.ListCharges again restricting by
the usage-based IDs (or add a type filter in the search layer) with Expands:
meta.ExpandRealizations to fetch realizations only for usage-based
charges—update the logic around chargesByType, ListCharges and
meta.Expands/meta.ExpandRealizations accordingly.
🤖 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/adapter/search.go`:
- Around line 61-72: ListChargesInput currently forwards a zero-value Page
straight into query.Paginate which causes empty results; before calling Paginate
in the ListCharges handler (where input.Page is used), detect a zero-value Page
(e.g. input.Page is nil/empty/default) and either treat it as an unpaginated
read or inject an explicit default Page (e.g. a sentinel "no pagination"
behavior or a sensible default page) so Paginate performs an unbounded fetch for
internal callers like AdvanceCharges; keep ListChargesInput.Validate() unchanged
(it intentionally doesn't call i.Page.Validate()) and update the call site that
invokes query.Paginate(ctx, input.Page) to use the adjusted page value instead.

In `@openmeter/billing/charges/meta/adapter.go`:
- Around line 25-40: In RegisterChargesInput.Validate(), tighten the Type check
so it verifies i.Type is one of the allowed charge type constants/enum values
(e.g., the known set used elsewhere) instead of only non-empty; update the
validation to compare i.Type against that whitelist (or call a helper like
IsValidChargeType(type string)) and append/return an error like "type is
invalid" when it doesn't match; keep the existing namespace and charges checks
and use the same error collection pattern in the Validate method to report the
invalid type.

---

Nitpick comments:
In @.agents/skills/db-migration/SKILL.md:
- Line 62: Rewrite the dense sentence in SKILL.md to split the key points into
two clearer sentences: state that the view parity test
(TestViewDefinitionsMatchGeneratedSchemaSQL in
tools/migrate/view_parity_test.go) validates that view definitions in migrations
match the generated view SQL, then add a second sentence explaining that the
test isolates/strips VIEW statements while preserving other DDL so mixing VIEW
and non-VIEW statements in one migration is safe. Use the test name
TestViewDefinitionsMatchGeneratedSchemaSQL and the file path
tools/migrate/view_parity_test.go in the text to keep the reference clear.

In `@openmeter/billing/charges/creditpurchase/adapter.go`:
- Around line 27-52: Extract the duplicated GetByIDsInput struct and its
Validate method (symbols: GetByIDsInput, Validate, Expands) from
openmeter/billing/charges/creditpurchase/adapter.go and
openmeter/billing/charges/flatfee/adapter.go into a single shared definition in
the parent charges package (openmeter/billing/charges); update both adapters to
import and use charges.GetByIDsInput (or move the type to the charges package
and reference it as charges.GetByIDsInput) so the ID-lookup contract is
centralized and cannot drift, and ensure imports and any package-qualified
references are adjusted accordingly.

In `@openmeter/billing/charges/service/advance.go`:
- Around line 23-38: The current call to s.ListCharges expands realizations for
all non-final charges (Expands: meta.ExpandRealizations) even though this path
only uses chargesByType.usageBased; change the flow to first list charges
without expanding realizations (omit meta.ExpandRealizations or use a
lightweight Expands), derive types via chargesByType(inScopeCharges.Items) and
if len(chargesByType.usageBased) > 0 then call s.ListCharges again restricting
by the usage-based IDs (or add a type filter in the search layer) with Expands:
meta.ExpandRealizations to fetch realizations only for usage-based
charges—update the logic around chargesByType, ListCharges and
meta.Expands/meta.ExpandRealizations accordingly.

In `@openmeter/billing/charges/usagebased/adapter/charge.go`:
- Around line 111-113: Update the inline comment to reflect that the namespace
filter is in fact applied to the query: replace the misleading "we are skipping
the namespace filter here" note with a short comment stating that the query
includes Namespace(input.Namespace) and then filters by IDs via
dbchargeusagebased.IDIn(input.IDs...), so the lookup is constrained to the
provided namespace and IDs (reference dbchargeusagebased.Namespace and
dbchargeusagebased.IDIn).
🪄 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: f5ea4fa0-e4f7-48ec-9de5-a2985fd2d973

📥 Commits

Reviewing files that changed from the base of the PR and between d21fe3d and b6548b4.

⛔ Files ignored due to path filters (66)
  • go.mod is excluded by !**/*.mod
  • openmeter/ent/db/charge.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge/charge.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase/chargecreditpurchase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee/chargeflatfee.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargessearchv1.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargessearchv1/chargessearchv1.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargessearchv1/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargessearchv1_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/cursor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/customer.go is excluded by !**/ent/db/**
  • openmeter/ent/db/customer/customer.go is excluded by !**/ent/db/**
  • openmeter/ent/db/customer/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/customer_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/customer_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/customer_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ent.go is excluded by !**/ent/db/**
  • openmeter/ent/db/entmixinaccessor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/expose.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/paginate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/predicate/predicate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscription.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscription/subscription.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscription/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscription_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscription_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscription_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionitem.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionitem/subscriptionitem.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionitem/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionitem_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionitem_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionitem_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionphase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionphase/subscriptionphase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionphase/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionphase_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionphase_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/subscriptionphase_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/tx.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (54)
  • .agents/skills/db-migration/SKILL.md
  • AGENTS.md
  • Makefile
  • openmeter/billing/charges/adapter.go
  • openmeter/billing/charges/adapter/search.go
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/creditpurchase/adapter.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper.go
  • openmeter/billing/charges/creditpurchase/service.go
  • openmeter/billing/charges/creditpurchase/service/get.go
  • openmeter/billing/charges/flatfee/adapter.go
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go
  • openmeter/billing/charges/flatfee/service.go
  • openmeter/billing/charges/flatfee/service/get.go
  • openmeter/billing/charges/meta/adapter.go
  • openmeter/billing/charges/meta/adapter/charges.go
  • openmeter/billing/charges/meta/adapter/create.go
  • openmeter/billing/charges/meta/adapter/get.go
  • openmeter/billing/charges/meta/adapter/mapper.go
  • openmeter/billing/charges/meta/adapter/update.go
  • openmeter/billing/charges/meta/charge.go
  • openmeter/billing/charges/models/chargemeta/mixin.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/service/advance.go
  • openmeter/billing/charges/service/get.go
  • openmeter/billing/charges/service/invoice.go
  • openmeter/billing/charges/service/invoicependinglines.go
  • openmeter/billing/charges/service/list.go
  • openmeter/billing/charges/usagebased/adapter.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/mapper.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/create.go
  • openmeter/billing/charges/usagebased/service/get.go
  • openmeter/billing/charges/usagebased/statemachine.go
  • openmeter/ent/entc.go
  • openmeter/ent/schema/charges.go
  • openmeter/ent/schema/chargescreditpurchase.go
  • openmeter/ent/schema/chargesflatfee.go
  • openmeter/ent/schema/chargesusagebased.go
  • openmeter/ent/schema/customer.go
  • openmeter/ent/schema/subscription.go
  • pkg/framework/entutils/entsetorclear/setorclear.tpl
  • pkg/framework/entutils/idorder.go
  • pkg/framework/entutils/idorder_test.go
  • tools/migrate/README.md
  • tools/migrate/cmd/viewgen/main.go
  • tools/migrate/migrations/20260325084446_charges-refactor-tables.down.sql
  • tools/migrate/migrations/20260325084446_charges-refactor-tables.up.sql
  • tools/migrate/view_parity_test.go
  • tools/migrate/viewgen/viewgen.go
  • tools/migrate/views.sql
💤 Files with no reviewable changes (4)
  • openmeter/billing/charges/meta/adapter/create.go
  • openmeter/billing/charges/meta/adapter/update.go
  • openmeter/billing/charges/meta/adapter/get.go
  • openmeter/billing/charges/meta/adapter/mapper.go
✅ Files skipped from review due to trivial changes (2)
  • AGENTS.md
  • Makefile
🚧 Files skipped from review as they are similar to previous changes (13)
  • openmeter/billing/charges/service/invoice.go
  • openmeter/billing/charges/usagebased/adapter.go
  • openmeter/billing/charges/flatfee/service.go
  • openmeter/billing/charges/creditpurchase/service/get.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper.go
  • openmeter/billing/charges/meta/adapter/charges.go
  • openmeter/billing/charges/usagebased/service/get.go
  • openmeter/billing/charges/meta/charge.go
  • openmeter/billing/charges/adapter.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/statemachine.go
  • openmeter/billing/charges/models/chargemeta/mixin.go
  • openmeter/billing/charges/flatfee/service/get.go

@turip
turip merged commit 19d7c40 into main Mar 25, 2026
23 checks passed
@turip
turip deleted the refactor/get-rid-of-meta branch March 25, 2026 15:40

This branch was previously deployed

1 inactive deployment
dev — 78cb7328 Deployed Mar 25, 2026 by turip via Migration Checks #12860
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants