Skip to content

feat: charges v2 - #3894

Merged
turip merged 7 commits into
mainfrom
feat/charges-v2
Feb 24, 2026
Merged

turip merged 7 commits into
mainfrom
feat/charges-v2

Conversation

@turip

@turip turip commented Feb 23, 2026 •

Copy link
Copy Markdown
Member

Overview

Adds basic types for charges. This code is mostly dead code, the only reason for this pr, so that actual logic changes are made into sizable PRs.

Given this is closely billing related, I am going to add this under billing as a seperate service. Over time billing should follow this structure of having different sub-services.

Summary by CodeRabbit

  • New Features

    • Added a comprehensive billing charges system with three charge types (flat-fee, usage-based, credit-purchase), intents, states, statuses, settlements, and subscription references.
    • Exposed create and retrieval APIs for charges with input validation and transactional guarantees.
    • Added standardized invoice/settlement models and explicit charge-related error types.
  • Tests

    • Added adapter tests covering create and get flows for each charge type.

@coderabbitai

coderabbitai Bot commented Feb 23, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a full billing charges domain: polymorphic charge models (flat‑fee, usage‑based, credit purchase), validation and errors, service and adapter interfaces plus an ent-backed adapter implementation with transactional Create/Get flows, DB↔domain mappers, and adapter tests.

Changes

Cohort / File(s) Summary
Domain models
openmeter/billing/charges/charge.go, openmeter/billing/charges/chargeflatfee.go, openmeter/billing/charges/chargeusagebased.go, openmeter/billing/charges/chargecreditpurchase.go
Add discriminated Charge and three concrete variants (FlatFee, UsageBased, CreditPurchase) with intents, state, statuses, constructors, type accessors and comprehensive validation.
Supporting types & errors
openmeter/billing/charges/intent.go, openmeter/billing/charges/stdinvoice.go, openmeter/billing/charges/subscription.go, openmeter/billing/charges/errors.go
Add IntentMeta, StandardInvoiceSettlement, SubscriptionReference, error codes and models.ValidationIssue instances plus helper NewChargeNotFoundError.
Service API & wiring
openmeter/billing/charges/service.go, openmeter/billing/charges/service/service.go, openmeter/billing/charges/service/*.go
Declare Service/ChargeService interfaces; implement service constructor, validation, and Get/Create methods that validate inputs and run adapter calls inside transactional wrappers.
Adapter surface & implementation
openmeter/billing/charges/adapter.go, openmeter/billing/charges/adapter/*, openmeter/billing/charges/adapter/adapter.go
Declare Adapter/ChargeAdapter interfaces and provide concrete adapter: config, constructor, transaction helpers (Tx/WithTx), and compile-time interface check.
Adapter behavior: create & get
openmeter/billing/charges/adapter/create.go, openmeter/billing/charges/adapter/get.go
Implement CreateCharges (bulk, transactional creation of charges and related sub-entities with mapping back to domain) and GetChargeByID/GetChargesByIDs (transactional queries with preloads, validation, and mapping).
Mapping & helpers
openmeter/billing/charges/adapter/mapper.go
Map ent DB entities and edges into domain charge variants; provide per-type mappers and helper conversions (timestamps, pro‑rating, managed resource, intents).
Tests
openmeter/billing/charges/adapter/adapter_test.go
Add adapter test suite covering create+retrieve scenarios for flat‑fee, usage‑based, and credit purchase charges with fixture builders and assertions.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Service
    participant Adapter
    participant Database

    rect rgba(100, 200, 255, 0.5)
    Note over Client,Database: CreateCharges flow
    Client->>Service: CreateCharges(ctx, CreateChargeInputs)
    Service->>Service: Validate input
    Service->>Adapter: Tx(ctx) — begin transaction
    Adapter->>Database: Begin transaction
    Database-->>Adapter: tx driver
    Service->>Adapter: CreateCharges(tx ctx, intents)
    Adapter->>Database: Bulk create Charge rows
    Adapter->>Database: Bulk create FlatFee / UsageBased / CreditPurchase edges
    Adapter->>Database: Link sub-entities to parent charges
    Database-->>Adapter: Created entities
    Adapter->>Adapter: Map DB entities → domain charges
    Adapter-->>Service: Return charges
    Service->>Adapter: Commit / finish tx
    Database-->>Service: Transaction committed
    Service-->>Client: Result charges
    end

    rect rgba(100, 255, 200, 0.5)
    Note over Client,Database: GetCharges flow
    Client->>Service: GetChargesByIDs(ctx, namespace, ids)
    Service->>Service: Validate namespace/ids
    Service->>Adapter: Tx(ctx)
    Adapter->>Database: Begin transaction
    Database-->>Adapter: tx driver
    Service->>Adapter: GetChargesByIDs(tx ctx, namespace, ids)
    Adapter->>Database: Query charges with preloaded edges
    Database-->>Adapter: Charge entities + edges
    Adapter->>Adapter: Map each DB entity → domain charge
    Adapter-->>Service: Return charges
    Service->>Adapter: Commit / finish tx
    Database-->>Service: Transaction committed
    Service-->>Client: Result charges
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Suggested labels

release-note/feature

Suggested reviewers

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

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.37% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'feat: charges v2' is vague and doesn't clearly convey what the PR accomplishes. While it relates to the changes, it lacks specificity about the actual contribution. Consider a more descriptive title like 'feat: add charges v2 domain types and adapter' or 'feat: introduce billing charges types and adapter implementation' to better communicate the scope of work.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/charges-v2

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/charges-v2 branch 4 times, most recently from 0ac2cdd to e23c4b4 Compare February 24, 2026 08:24
@turip turip changed the title Feat/charges v2 feat: charges v2 Feb 24, 2026
@turip
turip marked this pull request as ready for review February 24, 2026 09:38
@turip
turip requested a review from a team as a code owner February 24, 2026 09:38
@turip turip added release-note/misc Miscellaneous changes area/billing labels Feb 24, 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: 9

🧹 Nitpick comments (15)
openmeter/billing/charges/adapter/adapter_test.go (2)

44-177: Good happy-path coverage — consider adding edge-case and GetChargeByID tests.

The round-trip create-then-get tests for all three charge types are solid. A few gaps to consider for future coverage:

  • GetChargeByID (from the ChargeService interface) isn't exercised here — only GetChargesByIDs is tested.
  • No negative test cases: e.g., retrieving a non-existent ID, creating invalid charges, passing an empty namespace.
  • No test for creating multiple charges in a single CreateCharges call to verify batch behavior.

Totally fine to defer these if you're planning to add them in a follow-up PR alongside the "real" logic.

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

In `@openmeter/billing/charges/adapter/adapter_test.go` around lines 44 - 177,
Tests only cover happy-path CreateCharges -> GetChargesByIDs round-trips; add
focused tests on ChargeService.GetChargeByID, negative scenarios, and batch
creation: add a new test method(s) on ChargesAdapterTestSuite that calls
s.adapter.GetChargeByID (or the ChargeService implementation) to fetch a single
created charge by ID, assert equality with the created charge, add tests that
request a non-existent ID and assert the expected not-found error/empty result,
add tests that call CreateCharges with multiple valid Charge inputs to verify
batch behavior and with invalid inputs/empty namespace to assert proper
validation/error handling; use existing helpers like newManagedResource,
newIntentMeta, CreateTestCustomer and methods
CreateCharges/GetChargesByIDs/GetChargeByID to locate code under test.

187-204: newIntentMeta helper doesn't set Metadata or Annotations — might want to test those fields round-trip too.

Currently all optional fields (TaxConfig, UniqueReferenceID, Subscription, Metadata, Annotations) are left at zero values. Worth having at least one test that populates these to verify they survive the DB round-trip, especially since the mapper layer needs to handle them.

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

In `@openmeter/billing/charges/adapter/adapter_test.go` around lines 187 - 204,
Update the test helper newIntentMeta in adapter_test.go to populate optional
fields (at minimum Metadata and Annotations) on the charges.IntentMeta it
returns so the DB round-trip is exercised; set Metadata to a non-empty map
(e.g., string keys/values) and Annotations to a non-empty slice (and optionally
fill TaxConfig, UniqueReferenceID, Subscription if relevant) and then add/adjust
assertions in the test that uses newIntentMeta to verify those fields survive
the mapper/DB round-trip. Ensure you reference the charges.IntentMeta fields
(Metadata, Annotations, and any additional optional fields you populate) and
update the related test expectations accordingly.
openmeter/billing/charges/chargecreditpurchase.go (2)

57-65: CreditPurchaseIntent has its own Currency field, but IntentMeta (which it embeds) also has a Currency field.

This shadows the embedded IntentMeta.Currency. The intent's Validate() on Line 74 validates i.Currency which resolves to the outer (CreditPurchaseIntent) field, while i.IntentMeta.Validate() validates the embedded one independently. If they're meant to represent different things (e.g., credit currency vs. billing currency), a more descriptive name for one of them would help avoid confusion. If they should always match, consider removing the duplicate and relying on the embedded field.

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

In `@openmeter/billing/charges/chargecreditpurchase.go` around lines 57 - 65,
CreditPurchaseIntent defines a Currency field that shadows the embedded
IntentMeta.Currency causing inconsistent validation between
CreditPurchaseIntent.Validate (which checks i.Currency) and
i.IntentMeta.Validate (which checks the embedded one); fix by either removing
the duplicate Currency from CreditPurchaseIntent and using the embedded
IntentMeta.Currency everywhere (update JSON tags/consumers to use the embedded
field) or, if they represent different currencies, rename the outer field to a
descriptive name like CreditCurrency (and JSON tag "credit_currency"), update
all references and the Validate() on CreditPurchaseIntent to explicitly validate
both fields and assert they match when required; change references to i.Currency
in CreditPurchaseIntent.Validate to the new name or to i.IntentMeta.Currency as
appropriate.

15-51: Receiver inconsistency: AsCharge() uses pointer receiver while Validate(), Type(), and getters use value receivers.

AsCharge() at Line 42 takes *CreditPurchaseCharge (pointer) while everything else uses CreditPurchaseCharge (value). This is fine functionally since AsCharge stores the pointer in the Charge struct, but worth being aware of — callers with a value-type CreditPurchaseCharge won't see AsCharge in the method set of the interface if it requires pointer receivers.

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

In `@openmeter/billing/charges/chargecreditpurchase.go` around lines 15 - 51, The
receiver for AsCharge is a pointer (*CreditPurchaseCharge) while Validate, Type,
and other methods use value receivers, which breaks method-set consistency;
change AsCharge to use a value receiver (func (c CreditPurchaseCharge)
AsCharge() Charge) and ensure the Charge returned still stores a pointer by
assigning creditPurchase: &c so callers with a value-type CreditPurchaseCharge
can call AsCharge and other methods remain unchanged (references:
CreditPurchaseCharge.Validate, CreditPurchaseCharge.Type,
CreditPurchaseCharge.AsCharge, Charge.creditPurchase).
openmeter/billing/charges/stdinvoice.go (1)

57-65: Validate() only checks Status — consider validating other required fields.

Fields like LineID and ServicePeriod aren't validated here. Totally fine if this is intentional placeholder validation that'll be expanded later, just flagging it in case it was an oversight.

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

In `@openmeter/billing/charges/stdinvoice.go` around lines 57 - 65, The Validate
method on StandardInvoiceSettlement currently only validates Status; extend it
to validate other required fields (e.g., LineID and ServicePeriod) by checking
for zero/empty values and appending wrapped errors to the errs slice (similar to
the Status check) before returning errors.Join(errs...). Locate
StandardInvoiceSettlement.Validate and add checks like "if r.LineID == "" { errs
= append(errs, fmt.Errorf("lineID: required")) }" and validate ServicePeriod
(nil or empty start/end) with descriptive wrapped errors so all missing/invalid
fields are reported.
openmeter/billing/charges/chargeflatfee.go (1)

112-118: Nit: FlatFeeState.Validate() is a no-op with unnecessary ceremony.

The var errs []error and errors.Join(errs...) dance does nothing here. A simple return nil would be cleaner until there's actual validation to add. Totally fine to leave as-is if you prefer the consistency with other Validate() methods though!

Simpler no-op
 func (s FlatFeeState) Validate() error {
-	var errs []error
-
-	return errors.Join(errs...)
+	return nil
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/chargeflatfee.go` around lines 112 - 118,
FlatFeeState.Validate() is currently a no-op that creates an empty slice and
calls errors.Join unnecessarily; simplify by removing the unused errs slice and
replacing the body of FlatFeeState.Validate with a single `return nil` so the
method clearly communicates there's no validation for now (update the
FlatFeeState.Validate method).
openmeter/billing/charges/adapter.go (1)

23-34: Inconsistent naming between type and constant prefix.

The type is ProRatingModeAdapterEnum (Mode before Adapter) but the constants use ProRatingAdapterModeEnum... (Adapter before Mode). This is easy to mix up and could lead to typos down the line. Picking one ordering and sticking with it would help readability.

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

In `@openmeter/billing/charges/adapter.go` around lines 23 - 34, The constant
names are inconsistent with the type name: change the constants from
ProRatingAdapterModeEnumProratePrices and ProRatingAdapterModeEnumNoProrate to
match the type prefix (e.g., ProRatingModeAdapterEnumProratePrices and
ProRatingModeAdapterEnumNoProrate), update the Values() implementation to return
the renamed constants, and search/replace any other usages of the old constant
names to the new ones (ensure the first constant still wraps
productcatalog.ProRatingModeProratePrices and the second remains "no_prorate").
openmeter/billing/charges/adapter/create.go (1)

45-47: Use ID-based lookup for parent charges, like you do for sub-entities.

Lines 45–47 pair createdEntities[idx] with input[idx] using positional indexing. While Ent's CreateBulk.Save() typically preserves insertion order, the rest of your function already handles this more defensively — you use lo.SliceToMap() to create ID-keyed lookups for flat fees, usage-based, and credit purchase entities (lines 93–95, 142–144, 194–196). For consistency and robustness, apply the same pattern to parent charges instead of relying on positional ordering.

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

In `@openmeter/billing/charges/adapter/create.go` around lines 45 - 47, The
current pairing uses positional indexing between createdEntities and input to
build chargeWithOriginal (variables: createdEntities, input,
chargeWithOriginal), which can be brittle; instead build an ID-keyed map from
createdEntities (key by entity.ID) and then iterate the input slice to look up
each original's matching created entity by ID when constructing the pairs so you
mirror the lo.SliceToMap pattern used for flat fees/usage/credits and avoid
relying on insertion order.
openmeter/billing/charges/adapter/mapper.go (2)

322-355: mapCreditPurchaseSettlementToDB uses a sequential try-cast pattern — a bit fragile.

The function tries AsInvoice..., AsExternal..., AsPromotional... in order, relying on each returning a non-nil error to fall through. This works, but if a new settlement type is added, it's easy to forget to add a branch here, and the error at line 354 is quite generic.

Consider adding a brief comment listing the expected variants, or switching on a discriminator field if one exists on CreditPurchaseSettlement, to make this more maintainable.

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

In `@openmeter/billing/charges/adapter/mapper.go` around lines 322 - 355, The
try-cast chain in mapCreditPurchaseSettlementToDB (using
AsInvoiceCreditPurchaseSettlement, AsExternalAuthorizedCreditPurchaseSettlement,
AsPromotionalCreditPurchaseSettlement) is fragile and missing future variants;
update this function to either switch on a concrete discriminator field on
charges.CreditPurchaseSettlement if one exists (e.g., settlement.Type() or a
Kind/Variant method) and handle each known variant explicitly, or if no
discriminator exists, keep the casts but add a clear top-of-function comment
listing the expected variants and replace the generic error with one that
includes the settlement's identifying info and the handled variants (so failures
indicate an unrecognized variant), ensuring you reference
mapCreditPurchaseSettlementToDB and the three As* methods when making the
change.

357-371: Default pro-rating config sets Mode: ProRatingModeProratePrices even when disabled.

In proRatingConfigFromDB, the default branch returns Enabled: false but still sets Mode: ProRatingModeProratePrices. While this likely doesn't affect behavior (since Enabled gates the mode), it's a bit misleading for anyone inspecting the config. Consider leaving Mode as the zero value or using a dedicated "none" mode, if one exists.

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

In `@openmeter/billing/charges/adapter/mapper.go` around lines 357 - 371, The
default branch of proRatingConfigFromDB returns Enabled:false but still sets
Mode to ProRatingModeProratePrices, which is misleading; update the function
(proRatingConfigFromDB) so that when returning Enabled:false it leaves Mode as
the zero value (or uses a dedicated "none" enum like
productcatalog.ProRatingModeNone if available) instead of
ProRatingModeProratePrices so the disabled config doesn't imply an active mode.
openmeter/billing/charges/chageusagebased.go (2)

55-65: TaxConfig field shadows the embedded IntentMeta.TaxConfig.

UsageBasedIntent embeds IntentMeta, which already has a TaxConfig field (see intent.go line 26). Declaring another TaxConfig here shadows it. This means intent.TaxConfig and intent.IntentMeta.TaxConfig are two different fields, which is a maintenance footgun.

If this is intentional (e.g., usage-based charges store TaxConfig at the sub-entity level rather than the base charge), consider removing TaxConfig from IntentMeta or documenting the distinction. Otherwise, it's a subtle source of bugs in serialization and mapping.

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

In `@openmeter/billing/charges/chageusagebased.go` around lines 55 - 65,
UsageBasedIntent declares a TaxConfig field that shadows the embedded
IntentMeta.TaxConfig; remove the duplicate TaxConfig from UsageBasedIntent so
you only use IntentMeta.TaxConfig (and its JSON tag) when
serializing/deserializing, updating any references in code that access
UsageBasedIntent.TaxConfig to instead use the embedded IntentMeta (e.g.,
intent.TaxConfig or intent.IntentMeta.TaxConfig); if the duplicate was
intentional, instead rename the field (e.g., UsageTaxConfig) and update JSON
tags and all usages to make the distinction explicit.

40-45: AsCharge() uses a pointer receiver while all other methods use value receivers.

AsCharge() on line 40 takes *UsageBasedCharge, but Validate(), Type(), and the getters all use value receivers. This inconsistency means you can't call AsCharge() on a non-addressable UsageBasedCharge value. If the pointer receiver is intentional (to avoid a copy and store the original pointer in Charge), that's fine — but worth noting that the Charge struct then holds a pointer to the original, so mutations to the original will be reflected. If that's not desired, consider making it a value receiver for consistency.

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

In `@openmeter/billing/charges/chageusagebased.go` around lines 40 - 45,
AsCharge() uses a pointer receiver while Validate(), Type(), and the getters use
value receivers, causing inconsistency and preventing calls on non-addressable
values; either change AsCharge to a value receiver or make the design
intentional. Update the method signature from func (c *UsageBasedCharge)
AsCharge() Charge to func (c UsageBasedCharge) AsCharge() Charge and ensure
Charge construction stores a copy (e.g., if Charge.usageBased is a pointer,
assign usageBased: &c or change Charge.usageBased to a value type), or
alternatively document/keep the pointer receiver but accept that Charge will
hold the original pointer; adjust the UsageBasedCharge/Charge types accordingly
(referencing AsCharge, Validate, Type, and the Charge.usageBased field) for
consistency.
openmeter/billing/charges/charge.go (3)

82-102: Unreachable return Charge{} at line 101.

The type constraint on T guarantees the switch is exhaustive, so line 101 is dead code. It's harmless, but a panic("unreachable") would make the intent clearer and catch any future mistakes if the constraint is widened without updating the switch.

Proposed tweak
 	case CreditPurchaseCharge:
 		return Charge{
 			t:              ChargeTypeCreditPurchase,
 			creditPurchase: &v,
 		}
 	}
 
-	return Charge{}
+	panic("unreachable: unsupported charge type in NewCharge")
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/charge.go` around lines 82 - 102, The final "return
Charge{}" in NewCharge[T FlatFeeCharge | UsageBasedCharge |
CreditPurchaseCharge] is unreachable due to the exhaustive type constraint;
replace it with an explicit panic to signal impossible control flow. Change the
unreachable return to panic("unreachable") (or add a default branch in the type
switch that panics) so NewCharge clearly fails fast if the constraint is ever
changed without updating the switch, referencing the NewCharge function and the
ChargeType* cases (FlatFeeCharge, UsageBasedCharge, CreditPurchaseCharge).

178-190: Charges.Validate() stringifies nested errors, losing the error chain.

At line 185, err.Error() is stored as a string attribute, which means callers can't use errors.Is or errors.As on the inner error. If structured error inspection is needed downstream, consider wrapping the original error instead. If this is just for human-readable validation output, it's fine as-is.

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

In `@openmeter/billing/charges/charge.go` around lines 178 - 190, Charges.Validate
currently stringifies nested validation errors by calling err.Error() when
creating ErrChargeInvalid via ErrChargeInvalid.WithAttr("error", err.Error());
instead preserve the original error chain so callers can use errors.Is/As by
either passing the error value (ErrChargeInvalid.WithAttr("error", err)) if
WithAttr supports non-string values, or by wrapping the original error into the
returned error (e.g., wrap ErrChargeInvalid with fmt.Errorf("%w: %v",
ErrChargeInvalid.WithAttr("index", i), err) or
errors.Join(ErrChargeInvalid.WithAttr("index", i), err)) so the attribute
"error" no longer loses the error type and callers can inspect the underlying
error; update the code in Charges.Validate accordingly.

137-147: Naming inconsistency: AsCreditPurchase vs AsFlatFeeCharge / AsUsageBasedCharge.

The other extractor methods include "Charge" in their name (AsGenericCharge, AsFlatFeeCharge, AsUsageBasedCharge), but this one doesn't. Since there's only one call site, renaming to AsCreditPurchaseCharge for consistency is a low-impact change worth doing.

Proposed rename
-func (c Charge) AsCreditPurchase() (CreditPurchaseCharge, error) {
+func (c Charge) AsCreditPurchaseCharge() (CreditPurchaseCharge, error) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/charge.go` around lines 137 - 147, The method name
AsCreditPurchase is inconsistent with other extractors; rename the method to
AsCreditPurchaseCharge and update its declaration and all call sites (e.g., any
place calling Charge.AsCreditPurchase) to use AsCreditPurchaseCharge; keep the
implementation and signature (returns CreditPurchaseCharge, error) identical
aside from the name so behavior doesn't change, and run tests/compile to ensure
no remaining references to AsCreditPurchase remain.
🤖 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/mapper.go`:
- Around line 297-320: The PromotionalCreditPurchaseSettlement mapping
drops/overwrites the generic fields (SettlementCurrency, CostBasis, TaxConfig)
causing schema constraint violations and silent data loss; update
mapCreditPurchaseSettlementFromDB to populate
PromotionalCreditPurchaseSettlement with GenericCreditPurchaseSettlement (use
the local variable generic) and update mapCreditPurchaseSettlementToDB to write
those fields back for PromotionalCreditPurchaseSettlement, or alternatively add
explicit validation in both map functions to error if any of those generic
fields are non-empty for promotional settlements (choose one approach and apply
consistently in mapCreditPurchaseSettlementFromDB and
mapCreditPurchaseSettlementToDB).

In `@openmeter/billing/charges/chageusagebased.go`:
- Line 1: Rename the source file from "chageusagebased.go" to
"chargeusagebased.go" to fix the typo; update any references to the filename in
the repo (e.g., CI scripts, build lists, or documentation) and run `go test
./...` to ensure no package import or build constraints break—the package
declaration remains "package charges", so no code edits needed inside the file
unless other files referenced the misspelled filename explicitly.
- Around line 28-31: The State.Validate() error is being wrapped with the wrong
label; update the error wrapping in the block that checks c.State.Validate() so
it uses "state: %w" instead of "status: %w" (the corresponding Status.Validate()
block should remain "status: %w"); locate the c.State.Validate() call and change
the fmt.Errorf wrapping string accordingly so errors clearly indicate whether
state or status validation failed.
- Around line 82-84: The code calls i.Discounts.Validate() without checking for
nil, which can panic because Discounts is a *productcatalog.Discounts pointer;
add a nil guard like the one used for TaxConfig: check if i.Discounts != nil
before calling i.Discounts.Validate(), and if it is nil skip validation (or
handle accordingly) so you only append validation errors when Validate() is
invoked on a non-nil Discounts.

In `@openmeter/billing/charges/chargecreditpurchase.go`:
- Around line 127-128: The error text for the negative cost check is misleading:
in the block that calls s.CostBasis.IsNegative() (where errs is appended via
append(errs, fmt.Errorf(...))), update the error string to reflect that zero is
allowed—use "must not be negative" or "must be non‑negative" instead of "must be
positive" so the message matches the IsNegative() check.
- Around line 156-174: The constant InitiatedPaymentSettlementStatus is declared
but not included in PaymentSettlementStatus.Values(), causing Validate() to
reject "initiated"; update the Values() method to include
string(InitiatedPaymentSettlementStatus) (or, if exclusion was intentional, add
a clarifying comment above InitiatedPaymentSettlementStatus and adjust usage
accordingly) so PaymentSettlementStatus.Validate() and Values() are consistent;
see the InitiatedPaymentSettlementStatus const and the
PaymentSettlementStatus.Values() and Validate() methods to make the change.
- Around line 236-263: The switch cases for
CreditPurchaseSettlementTypeInvoice/External/Promotional append an error when
the inner pointers (s.invoice, s.external, s.promotional) are nil but then
immediately call .Validate() on them, which can panic; update each case so
Validate() is only invoked when the pointer is non-nil (e.g., use an else or
else-if branch or return/continue after appending the nil error) — specifically
change the logic around s.invoice.Validate(), s.external.Validate(), and
s.promotional.Validate() so you check nil and only call Validate on a non-nil
receiver, leaving the default case that appends the invalid type error (s.t)
unchanged.

In `@openmeter/billing/charges/README.md`:
- Around line 1-32: Fix the README.md in the "Realizations" and "Usage Based
charges" sections: replace the incorrect table separator row ("+----+...+") with
the standard Markdown separator ("|---|---|---|"), change "payed" to "paid" in
the ExternalSettlement example, change "it's status" to "its status", change
"The customer have used" to "The customer has used", hyphenate "Usage-based",
and change "tried to fulfilled" to "tried to be fulfilled" (locate these edits
around the "Realizations" table, the ExternalSettlement line, the example
sentence starting "The customer have used...", the "Usage Based charges"
heading, and the invoice creation bullet that mentions "tried to fulfilled").

In `@openmeter/billing/charges/stdinvoice.go`:
- Line 54: The TODO comment on the Totals field contains a typo; update the
comment on the Totals billing.Totals field (symbol: Totals) from "// TODO: is
this neededed?" to "// TODO: is this needed?" (or remove/clarify the TODO if
more appropriate) so the word "neededed" is corrected to "needed".

---

Nitpick comments:
In `@openmeter/billing/charges/adapter.go`:
- Around line 23-34: The constant names are inconsistent with the type name:
change the constants from ProRatingAdapterModeEnumProratePrices and
ProRatingAdapterModeEnumNoProrate to match the type prefix (e.g.,
ProRatingModeAdapterEnumProratePrices and ProRatingModeAdapterEnumNoProrate),
update the Values() implementation to return the renamed constants, and
search/replace any other usages of the old constant names to the new ones
(ensure the first constant still wraps productcatalog.ProRatingModeProratePrices
and the second remains "no_prorate").

In `@openmeter/billing/charges/adapter/adapter_test.go`:
- Around line 44-177: Tests only cover happy-path CreateCharges ->
GetChargesByIDs round-trips; add focused tests on ChargeService.GetChargeByID,
negative scenarios, and batch creation: add a new test method(s) on
ChargesAdapterTestSuite that calls s.adapter.GetChargeByID (or the ChargeService
implementation) to fetch a single created charge by ID, assert equality with the
created charge, add tests that request a non-existent ID and assert the expected
not-found error/empty result, add tests that call CreateCharges with multiple
valid Charge inputs to verify batch behavior and with invalid inputs/empty
namespace to assert proper validation/error handling; use existing helpers like
newManagedResource, newIntentMeta, CreateTestCustomer and methods
CreateCharges/GetChargesByIDs/GetChargeByID to locate code under test.
- Around line 187-204: Update the test helper newIntentMeta in adapter_test.go
to populate optional fields (at minimum Metadata and Annotations) on the
charges.IntentMeta it returns so the DB round-trip is exercised; set Metadata to
a non-empty map (e.g., string keys/values) and Annotations to a non-empty slice
(and optionally fill TaxConfig, UniqueReferenceID, Subscription if relevant) and
then add/adjust assertions in the test that uses newIntentMeta to verify those
fields survive the mapper/DB round-trip. Ensure you reference the
charges.IntentMeta fields (Metadata, Annotations, and any additional optional
fields you populate) and update the related test expectations accordingly.

In `@openmeter/billing/charges/adapter/create.go`:
- Around line 45-47: The current pairing uses positional indexing between
createdEntities and input to build chargeWithOriginal (variables:
createdEntities, input, chargeWithOriginal), which can be brittle; instead build
an ID-keyed map from createdEntities (key by entity.ID) and then iterate the
input slice to look up each original's matching created entity by ID when
constructing the pairs so you mirror the lo.SliceToMap pattern used for flat
fees/usage/credits and avoid relying on insertion order.

In `@openmeter/billing/charges/adapter/mapper.go`:
- Around line 322-355: The try-cast chain in mapCreditPurchaseSettlementToDB
(using AsInvoiceCreditPurchaseSettlement,
AsExternalAuthorizedCreditPurchaseSettlement,
AsPromotionalCreditPurchaseSettlement) is fragile and missing future variants;
update this function to either switch on a concrete discriminator field on
charges.CreditPurchaseSettlement if one exists (e.g., settlement.Type() or a
Kind/Variant method) and handle each known variant explicitly, or if no
discriminator exists, keep the casts but add a clear top-of-function comment
listing the expected variants and replace the generic error with one that
includes the settlement's identifying info and the handled variants (so failures
indicate an unrecognized variant), ensuring you reference
mapCreditPurchaseSettlementToDB and the three As* methods when making the
change.
- Around line 357-371: The default branch of proRatingConfigFromDB returns
Enabled:false but still sets Mode to ProRatingModeProratePrices, which is
misleading; update the function (proRatingConfigFromDB) so that when returning
Enabled:false it leaves Mode as the zero value (or uses a dedicated "none" enum
like productcatalog.ProRatingModeNone if available) instead of
ProRatingModeProratePrices so the disabled config doesn't imply an active mode.

In `@openmeter/billing/charges/chageusagebased.go`:
- Around line 55-65: UsageBasedIntent declares a TaxConfig field that shadows
the embedded IntentMeta.TaxConfig; remove the duplicate TaxConfig from
UsageBasedIntent so you only use IntentMeta.TaxConfig (and its JSON tag) when
serializing/deserializing, updating any references in code that access
UsageBasedIntent.TaxConfig to instead use the embedded IntentMeta (e.g.,
intent.TaxConfig or intent.IntentMeta.TaxConfig); if the duplicate was
intentional, instead rename the field (e.g., UsageTaxConfig) and update JSON
tags and all usages to make the distinction explicit.
- Around line 40-45: AsCharge() uses a pointer receiver while Validate(),
Type(), and the getters use value receivers, causing inconsistency and
preventing calls on non-addressable values; either change AsCharge to a value
receiver or make the design intentional. Update the method signature from func
(c *UsageBasedCharge) AsCharge() Charge to func (c UsageBasedCharge) AsCharge()
Charge and ensure Charge construction stores a copy (e.g., if Charge.usageBased
is a pointer, assign usageBased: &c or change Charge.usageBased to a value
type), or alternatively document/keep the pointer receiver but accept that
Charge will hold the original pointer; adjust the UsageBasedCharge/Charge types
accordingly (referencing AsCharge, Validate, Type, and the Charge.usageBased
field) for consistency.

In `@openmeter/billing/charges/charge.go`:
- Around line 82-102: The final "return Charge{}" in NewCharge[T FlatFeeCharge |
UsageBasedCharge | CreditPurchaseCharge] is unreachable due to the exhaustive
type constraint; replace it with an explicit panic to signal impossible control
flow. Change the unreachable return to panic("unreachable") (or add a default
branch in the type switch that panics) so NewCharge clearly fails fast if the
constraint is ever changed without updating the switch, referencing the
NewCharge function and the ChargeType* cases (FlatFeeCharge, UsageBasedCharge,
CreditPurchaseCharge).
- Around line 178-190: Charges.Validate currently stringifies nested validation
errors by calling err.Error() when creating ErrChargeInvalid via
ErrChargeInvalid.WithAttr("error", err.Error()); instead preserve the original
error chain so callers can use errors.Is/As by either passing the error value
(ErrChargeInvalid.WithAttr("error", err)) if WithAttr supports non-string
values, or by wrapping the original error into the returned error (e.g., wrap
ErrChargeInvalid with fmt.Errorf("%w: %v", ErrChargeInvalid.WithAttr("index",
i), err) or errors.Join(ErrChargeInvalid.WithAttr("index", i), err)) so the
attribute "error" no longer loses the error type and callers can inspect the
underlying error; update the code in Charges.Validate accordingly.
- Around line 137-147: The method name AsCreditPurchase is inconsistent with
other extractors; rename the method to AsCreditPurchaseCharge and update its
declaration and all call sites (e.g., any place calling Charge.AsCreditPurchase)
to use AsCreditPurchaseCharge; keep the implementation and signature (returns
CreditPurchaseCharge, error) identical aside from the name so behavior doesn't
change, and run tests/compile to ensure no remaining references to
AsCreditPurchase remain.

In `@openmeter/billing/charges/chargecreditpurchase.go`:
- Around line 57-65: CreditPurchaseIntent defines a Currency field that shadows
the embedded IntentMeta.Currency causing inconsistent validation between
CreditPurchaseIntent.Validate (which checks i.Currency) and
i.IntentMeta.Validate (which checks the embedded one); fix by either removing
the duplicate Currency from CreditPurchaseIntent and using the embedded
IntentMeta.Currency everywhere (update JSON tags/consumers to use the embedded
field) or, if they represent different currencies, rename the outer field to a
descriptive name like CreditCurrency (and JSON tag "credit_currency"), update
all references and the Validate() on CreditPurchaseIntent to explicitly validate
both fields and assert they match when required; change references to i.Currency
in CreditPurchaseIntent.Validate to the new name or to i.IntentMeta.Currency as
appropriate.
- Around line 15-51: The receiver for AsCharge is a pointer
(*CreditPurchaseCharge) while Validate, Type, and other methods use value
receivers, which breaks method-set consistency; change AsCharge to use a value
receiver (func (c CreditPurchaseCharge) AsCharge() Charge) and ensure the Charge
returned still stores a pointer by assigning creditPurchase: &c so callers with
a value-type CreditPurchaseCharge can call AsCharge and other methods remain
unchanged (references: CreditPurchaseCharge.Validate, CreditPurchaseCharge.Type,
CreditPurchaseCharge.AsCharge, Charge.creditPurchase).

In `@openmeter/billing/charges/chargeflatfee.go`:
- Around line 112-118: FlatFeeState.Validate() is currently a no-op that creates
an empty slice and calls errors.Join unnecessarily; simplify by removing the
unused errs slice and replacing the body of FlatFeeState.Validate with a single
`return nil` so the method clearly communicates there's no validation for now
(update the FlatFeeState.Validate method).

In `@openmeter/billing/charges/stdinvoice.go`:
- Around line 57-65: The Validate method on StandardInvoiceSettlement currently
only validates Status; extend it to validate other required fields (e.g., LineID
and ServicePeriod) by checking for zero/empty values and appending wrapped
errors to the errs slice (similar to the Status check) before returning
errors.Join(errs...). Locate StandardInvoiceSettlement.Validate and add checks
like "if r.LineID == "" { errs = append(errs, fmt.Errorf("lineID: required")) }"
and validate ServicePeriod (nil or empty start/end) with descriptive wrapped
errors so all missing/invalid fields are reported.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 508f0f6 and 6162290.

⛔ Files ignored due to path filters (84)
  • go.sum is excluded by !**/*.sum, !**/*.sum
  • openmeter/ent/db/billinginvoiceline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline/billinginvoiceline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoicesplitlinegroup.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoicesplitlinegroup/billinginvoicesplitlinegroup.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoicesplitlinegroup/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoicesplitlinegroup_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoicesplitlinegroup_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoicesplitlinegroup_update.go is excluded by !**/ent/db/**
  • 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_delete.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_delete.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_delete.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/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_delete.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/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/expose.go is excluded by !**/ent/db/**
  • openmeter/ent/db/hook/hook.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/standardinvoicesettlement.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement/standardinvoicesettlement.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_update.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 (26)
  • openmeter/billing/charges/README.md
  • openmeter/billing/charges/adapter.go
  • openmeter/billing/charges/adapter/adapter.go
  • openmeter/billing/charges/adapter/adapter_test.go
  • openmeter/billing/charges/adapter/create.go
  • openmeter/billing/charges/adapter/get.go
  • openmeter/billing/charges/adapter/mapper.go
  • openmeter/billing/charges/chageusagebased.go
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/chargecreditpurchase.go
  • openmeter/billing/charges/chargeflatfee.go
  • openmeter/billing/charges/errors.go
  • openmeter/billing/charges/intent.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/get.go
  • openmeter/billing/charges/service/service.go
  • openmeter/billing/charges/stdinvoice.go
  • openmeter/billing/charges/subscription.go
  • openmeter/ent/schema/billing.go
  • openmeter/ent/schema/charges.go
  • openmeter/ent/schema/customer.go
  • openmeter/ent/schema/subscription.go
  • pkg/framework/entutils/mixins.go
  • tools/migrate/migrations/20260223144814_charges.down.sql
  • tools/migrate/migrations/20260223144814_charges.up.sql

Comment thread openmeter/billing/charges/README.md Resolved
Comment thread openmeter/billing/charges/stdinvoice.go Resolved
@turip
turip force-pushed the feat/charges-v2 branch 2 times, most recently from 51efaa0 to 8ce07d0 Compare February 24, 2026 11:45

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (7)
openmeter/billing/charges/chageusagebased.go (3)

1-1: ⚠️ Potential issue | 🟡 Minor

Typo in filename: chageusagebased.go.
Consider renaming to chargeusagebased.go for consistency and discoverability.

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

In `@openmeter/billing/charges/chageusagebased.go` at line 1, The filename has a
typo ("chageusagebased.go")—rename the file to "chargeusagebased.go" to match
the intended word and improve discoverability; update any imports or references
(search the repo for "chageusagebased" and replace with "chargeusagebased"),
ensure the package declaration remains "package charges" inside the renamed
file, and run go build / go test to catch any leftover references or compile
errors.

55-84: ⚠️ Potential issue | 🟠 Major

Guard against nil Discounts before Validate().
Line 82 can panic when Discounts is nil.

🛡️ Suggested fix
-	if err := i.Discounts.Validate(); err != nil {
-		errs = append(errs, fmt.Errorf("discounts: %w", err))
-	}
+	if i.Discounts != nil {
+		if err := i.Discounts.Validate(); err != nil {
+			errs = append(errs, fmt.Errorf("discounts: %w", err))
+		}
+	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/chageusagebased.go` around lines 55 - 84, The
Validate method on UsageBasedIntent can panic when Discounts is nil; update
UsageBasedIntent.Validate to guard the nil pointer before calling
Discounts.Validate by checking if i.Discounts != nil and only invoking
i.Discounts.Validate() when non-nil (and append any returned error with the
"discounts: %w" context), otherwise skip validation for discounts or treat nil
as no discounts; locate the check inside the UsageBasedIntent.Validate function
where Discounts is currently validated and add the nil guard around that call.

12-38: ⚠️ Potential issue | 🟡 Minor

Wrap State.Validate errors with “state”, not “status”.
Line 29 currently labels state validation as status, which makes errors misleading.

🔧 Suggested fix
 	if err := c.State.Validate(); err != nil {
-		errs = append(errs, fmt.Errorf("status: %w", err))
+		errs = append(errs, fmt.Errorf("state: %w", err))
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/chageusagebased.go` around lines 12 - 38, In
UsageBasedCharge.Validate change the error wrapping for the State validation:
currently the call to c.State.Validate() is wrapped with fmt.Errorf("status:
%w", err) which is misleading; update that to fmt.Errorf("state: %w", err) so
errors from c.State are labeled "state" (leave the Intent and Status validation
wraps unchanged).
openmeter/billing/charges/README.md (1)

5-31: ⚠️ Potential issue | 🟡 Minor

Polish the table separator and a few grammar bits.
The current separator row and typos make the table render oddly and read awkwardly.

✏️ Suggested doc fixes
 | Type | Description | Example |
-+----+-----------+-------+
+|------|-------------|---------|
 | CreditRecognition | Fulfilled by consuming the customer's credit balance, there's no settlement needed, as the system settles the possible credit transfers | |
-| InvoiceLaterRecognition | Represents an amount charge that will be eventually paid | The customer have used $10 in the service period of [2026-01-01..2026-01-02] that we are going to invoice the customer for once the billing period happens |
-| StandardInvoiceSettlement | Represents a request for the end user that will be eventually payed using a standard invoice | The customer has $20 worth of InvoiceLaterRealization so we send him an invoice with that amount |
-| ExternalSettlement | Represents a settlement that is performed on the external system | e.g. the user's own payment gateway handles the settlement and we are just notified of it's status |
+| InvoiceLaterRecognition | Represents an amount charge that will be eventually paid | The customer has used $10 in the service period of [2026-01-01..2026-01-02] that we are going to invoice the customer for once the billing period happens |
+| StandardInvoiceSettlement | Represents a request for the end user that will be eventually paid using a standard invoice | The customer has $20 worth of InvoiceLaterRealization so we send him an invoice with that amount |
+| ExternalSettlement | Represents a settlement that is performed on the external system | e.g. the user's own payment gateway handles the settlement and we are just notified of its status |

-# Usage Based charges
+# Usage-Based charges
@@
-- (optionally): All StandardInvoiceObligationRealizations are tried to fulfilled using credits
+- (optionally): All StandardInvoiceObligationRealizations are tried to be fulfilled using credits
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/README.md` around lines 5 - 31, Fix the malformed
Markdown table separator and a few grammar issues: replace the current separator
row with a proper Markdown separator like "| --- | --- | --- |" so the rows for
the types (CreditRecognition, InvoiceLaterRecognition,
StandardInvoiceSettlement, ExternalSettlement) render correctly, and correct
wording typos in the descriptions and examples (e.g., "have used" → "has used",
"payed" → "paid", "it's" → "its", and any awkward phrasing in headings like
"Revenue recognition train" / "Creating an invoice" to read clearly).
openmeter/billing/charges/chargecreditpurchase.go (3)

170-175: ⚠️ Potential issue | 🟠 Major

initiated is declared but rejected by Validate.
Values() omits InitiatedPaymentSettlementStatus, so validation fails for a declared constant.

✅ Suggested fix (if initiated is intended to be valid)
 func (s PaymentSettlementStatus) Values() []string {
 	return []string{
+		string(InitiatedPaymentSettlementStatus),
 		string(AuthorizedPaymentSettlementStatus),
 		string(SettledPaymentSettlementStatus),
 	}
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/chargecreditpurchase.go` around lines 170 - 175,
PaymentSettlementStatus.Values() currently returns only
AuthorizedPaymentSettlementStatus and SettledPaymentSettlementStatus while
InitiatedPaymentSettlementStatus is declared and thus rejected by validation;
update the Values() method to include string(InitiatedPaymentSettlementStatus)
so that PaymentSettlementStatus.Values() lists all declared constants (or if
InitiatedPaymentSettlementStatus should be invalid, remove that constant and any
references to it) — look for the PaymentSettlementStatus type and the Values()
method to make the change.

311-342: ⚠️ Potential issue | 🔴 Critical

Avoid nil-pointer Validate calls in settlement validation.
If the inner settlement pointer is nil, Validate() will panic even after appending the error.

🛠 Suggested fix
 	case CreditPurchaseSettlementTypeInvoice:
 		if s.invoice == nil {
 			errs = append(errs, fmt.Errorf("invoice is required"))
-		}
-
-		if err := s.invoice.Validate(); err != nil {
-			errs = append(errs, fmt.Errorf("invoice: %w", err))
+		} else if err := s.invoice.Validate(); err != nil {
+			errs = append(errs, fmt.Errorf("invoice: %w", err))
 		}
 	case CreditPurchaseSettlementTypeExternal:
 		if s.external == nil {
 			errs = append(errs, fmt.Errorf("external is required"))
-		}
-
-		if err := s.external.Validate(); err != nil {
-			errs = append(errs, fmt.Errorf("external: %w", err))
+		} else if err := s.external.Validate(); err != nil {
+			errs = append(errs, fmt.Errorf("external: %w", err))
 		}
 	case CreditPurchaseSettlementTypePromotional:
 		if s.promotional == nil {
 			errs = append(errs, fmt.Errorf("promotional is required"))
-		}
-
-		if err := s.promotional.Validate(); err != nil {
-			errs = append(errs, fmt.Errorf("promotional: %w", err))
+		} else if err := s.promotional.Validate(); err != nil {
+			errs = append(errs, fmt.Errorf("promotional: %w", err))
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/chargecreditpurchase.go` around lines 311 - 342,
The Validate method on CreditPurchaseSettlement may call Validate() on a nil
inner pointer (invoice/external/promotional) after already appending an error;
update CreditPurchaseSettlement.Validate to only call s.invoice.Validate(),
s.external.Validate(), or s.promotional.Validate() when the corresponding
pointer is non-nil — e.g. for each case first check if s.invoice != nil (or
s.external != nil, s.promotional != nil), append the "required" error if nil and
skip calling Validate; if non-nil then call its Validate() and wrap any returned
error (invoice: %w, external: %w, promotional: %w) before appending to errs,
preserving the existing switch and final errors.Join(errs...) behavior.

121-130: ⚠️ Potential issue | 🟡 Minor

Error message doesn’t match the validation condition.
This check allows zero (IsNegative() only rejects negatives), but the message says “positive.” Consider “must not be negative” / “must be non‑negative.”

✏️ Suggested fix
 	if s.CostBasis.IsNegative() {
-		errs = append(errs, fmt.Errorf("cost basis must be positive"))
+		errs = append(errs, fmt.Errorf("cost basis must not be negative"))
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/chargecreditpurchase.go` around lines 121 - 130,
The error message in GenericCreditPurchaseSettlement.Validate is inconsistent:
the CostBasis.IsNegative() check allows zero but the message says "must be
positive"; update the error text to "cost basis must not be negative" or "cost
basis must be non-negative" so it matches the existing IsNegative() condition
(or if you actually require strictly positive, change the condition to reject
zero as well by checking IsZero() or <= 0); adjust the fmt.Errorf call in
Validate accordingly to reference s.CostBasis.IsNegative() / the new condition.
🧹 Nitpick comments (1)
openmeter/billing/charges/adapter/adapter_test.go (1)

44-86: Consider a mixed-type batch CreateCharges test.
You’re already hitting each type individually; a single test that creates multiple charge types in one call would cover the bulk pairing + mapping logic too.

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

In `@openmeter/billing/charges/adapter/adapter_test.go` around lines 44 - 86, Add
a new test that calls the adapter's CreateCharges with a mixed-type slice (e.g.,
the existing FlatFeeCharge plus at least one other charge type created via
charges.NewCharge like a UsageCharge or TieredCharge) so the batch
pairing/mapping logic is exercised; construct each charge with distinct
ManagedResource IDs and valid Intent/State data, call
s.adapter.CreateCharges(ctx, []charges.Charge{...}), assert no error, assert
created length equals input length, convert each created to GenericCharge via
AsGenericCharge and verify their ManagedResource IDs, then fetch them back with
GetChargesByIDs and assert created[i] equals fetched[i] to ensure mapping and
persistence work for mixed-type batches (use the existing
TestCreateAndGetFlatFeeCharge structure and helper methods such as
CreateTestCustomer, newManagedResource, newIntentMeta, CreateCharges, and
GetChargesByIDs).
🤖 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/chargecreditpurchase.go`:
- Around line 68-90: CreditPurchaseIntent.Validate currently skips validating
the settlement details; update the method to call i.Settlement.Validate() and
append any returned error to errs with context (e.g., fmt.Errorf("settlement:
%w", err)); perform this check where other nested validations occur (alongside
IntentMeta, Currency, TaxConfig) and ensure you handle a nil i.Settlement if
that is allowed by its type.

---

Duplicate comments:
In `@openmeter/billing/charges/chageusagebased.go`:
- Line 1: The filename has a typo ("chageusagebased.go")—rename the file to
"chargeusagebased.go" to match the intended word and improve discoverability;
update any imports or references (search the repo for "chageusagebased" and
replace with "chargeusagebased"), ensure the package declaration remains
"package charges" inside the renamed file, and run go build / go test to catch
any leftover references or compile errors.
- Around line 55-84: The Validate method on UsageBasedIntent can panic when
Discounts is nil; update UsageBasedIntent.Validate to guard the nil pointer
before calling Discounts.Validate by checking if i.Discounts != nil and only
invoking i.Discounts.Validate() when non-nil (and append any returned error with
the "discounts: %w" context), otherwise skip validation for discounts or treat
nil as no discounts; locate the check inside the UsageBasedIntent.Validate
function where Discounts is currently validated and add the nil guard around
that call.
- Around line 12-38: In UsageBasedCharge.Validate change the error wrapping for
the State validation: currently the call to c.State.Validate() is wrapped with
fmt.Errorf("status: %w", err) which is misleading; update that to
fmt.Errorf("state: %w", err) so errors from c.State are labeled "state" (leave
the Intent and Status validation wraps unchanged).

In `@openmeter/billing/charges/chargecreditpurchase.go`:
- Around line 170-175: PaymentSettlementStatus.Values() currently returns only
AuthorizedPaymentSettlementStatus and SettledPaymentSettlementStatus while
InitiatedPaymentSettlementStatus is declared and thus rejected by validation;
update the Values() method to include string(InitiatedPaymentSettlementStatus)
so that PaymentSettlementStatus.Values() lists all declared constants (or if
InitiatedPaymentSettlementStatus should be invalid, remove that constant and any
references to it) — look for the PaymentSettlementStatus type and the Values()
method to make the change.
- Around line 311-342: The Validate method on CreditPurchaseSettlement may call
Validate() on a nil inner pointer (invoice/external/promotional) after already
appending an error; update CreditPurchaseSettlement.Validate to only call
s.invoice.Validate(), s.external.Validate(), or s.promotional.Validate() when
the corresponding pointer is non-nil — e.g. for each case first check if
s.invoice != nil (or s.external != nil, s.promotional != nil), append the
"required" error if nil and skip calling Validate; if non-nil then call its
Validate() and wrap any returned error (invoice: %w, external: %w, promotional:
%w) before appending to errs, preserving the existing switch and final
errors.Join(errs...) behavior.
- Around line 121-130: The error message in
GenericCreditPurchaseSettlement.Validate is inconsistent: the
CostBasis.IsNegative() check allows zero but the message says "must be
positive"; update the error text to "cost basis must not be negative" or "cost
basis must be non-negative" so it matches the existing IsNegative() condition
(or if you actually require strictly positive, change the condition to reject
zero as well by checking IsZero() or <= 0); adjust the fmt.Errorf call in
Validate accordingly to reference s.CostBasis.IsNegative() / the new condition.

In `@openmeter/billing/charges/README.md`:
- Around line 5-31: Fix the malformed Markdown table separator and a few grammar
issues: replace the current separator row with a proper Markdown separator like
"| --- | --- | --- |" so the rows for the types (CreditRecognition,
InvoiceLaterRecognition, StandardInvoiceSettlement, ExternalSettlement) render
correctly, and correct wording typos in the descriptions and examples (e.g.,
"have used" → "has used", "payed" → "paid", "it's" → "its", and any awkward
phrasing in headings like "Revenue recognition train" / "Creating an invoice" to
read clearly).

---

Nitpick comments:
In `@openmeter/billing/charges/adapter/adapter_test.go`:
- Around line 44-86: Add a new test that calls the adapter's CreateCharges with
a mixed-type slice (e.g., the existing FlatFeeCharge plus at least one other
charge type created via charges.NewCharge like a UsageCharge or TieredCharge) so
the batch pairing/mapping logic is exercised; construct each charge with
distinct ManagedResource IDs and valid Intent/State data, call
s.adapter.CreateCharges(ctx, []charges.Charge{...}), assert no error, assert
created length equals input length, convert each created to GenericCharge via
AsGenericCharge and verify their ManagedResource IDs, then fetch them back with
GetChargesByIDs and assert created[i] equals fetched[i] to ensure mapping and
persistence work for mixed-type batches (use the existing
TestCreateAndGetFlatFeeCharge structure and helper methods such as
CreateTestCustomer, newManagedResource, newIntentMeta, CreateCharges, and
GetChargesByIDs).

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6162290 and 8ce07d0.

⛔ Files ignored due to path filters (84)
  • go.sum is excluded by !**/*.sum, !**/*.sum
  • openmeter/ent/db/billinginvoiceline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline/billinginvoiceline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoicesplitlinegroup.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoicesplitlinegroup/billinginvoicesplitlinegroup.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoicesplitlinegroup/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoicesplitlinegroup_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoicesplitlinegroup_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoicesplitlinegroup_update.go is excluded by !**/ent/db/**
  • 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_delete.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_delete.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_delete.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/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_delete.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/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/expose.go is excluded by !**/ent/db/**
  • openmeter/ent/db/hook/hook.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/standardinvoicesettlement.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement/standardinvoicesettlement.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_update.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 (25)
  • openmeter/billing/charges/README.md
  • openmeter/billing/charges/adapter.go
  • openmeter/billing/charges/adapter/adapter.go
  • openmeter/billing/charges/adapter/adapter_test.go
  • openmeter/billing/charges/adapter/create.go
  • openmeter/billing/charges/adapter/get.go
  • openmeter/billing/charges/adapter/mapper.go
  • openmeter/billing/charges/chageusagebased.go
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/chargecreditpurchase.go
  • openmeter/billing/charges/chargeflatfee.go
  • openmeter/billing/charges/errors.go
  • openmeter/billing/charges/intent.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/get.go
  • openmeter/billing/charges/service/service.go
  • openmeter/billing/charges/stdinvoice.go
  • openmeter/billing/charges/subscription.go
  • openmeter/ent/schema/billing.go
  • openmeter/ent/schema/charges.go
  • openmeter/ent/schema/customer.go
  • openmeter/ent/schema/subscription.go
  • tools/migrate/migrations/20260224104052_charges.down.sql
  • tools/migrate/migrations/20260224104052_charges.up.sql
🚧 Files skipped from review as they are similar to previous changes (9)
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/adapter.go
  • openmeter/billing/charges/service/get.go
  • openmeter/billing/charges/service/service.go
  • openmeter/billing/charges/adapter/adapter.go
  • openmeter/billing/charges/errors.go
  • openmeter/billing/charges/stdinvoice.go
  • openmeter/billing/charges/chargeflatfee.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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/adapter_test.go`:
- Around line 132-176: The current TestCreateAndGetCreditPurchaseCharge only
covers the invoice settlement happy path; add unit tests that exercise other
settlement variants (e.g. external/promotional settlements created via
charges.NewCreditPurchaseSettlement with the appropriate
InvoiceCreditPurchaseSettlement alternative structs), plus negative tests for
invalid payloads (missing ManagedResource ID, invalid Intent/CreditAmount,
incorrect SettlementCurrency or CostBasis) to assert CreateCharges returns
validation errors and GetChargesByIDs behaves correctly; add new test functions
in the same suite (e.g. TestCreateCreditPurchase_ExternalSettlement,
TestCreateCreditPurchase_PromotionalSettlement,
TestCreateCreditPurchase_InvalidPayload) that construct Charge objects using
charges.CreditPurchaseCharge, call s.adapter.CreateCharges and
s.adapter.GetChargesByIDs, and assert success or expected error cases
accordingly.

In `@openmeter/billing/charges/chargeusagebased.go`:
- Around line 55-98: UsageBasedIntent.Validate() currently omits checking the
SettlementMode field, allowing empty/unknown modes to pass validation; update
the method (UsageBasedIntent.Validate) to validate i.SettlementMode (e.g.,
ensure it is not the zero/empty value or productcatalog.SettlementMode("")
and/or not an Unknown/Invalid sentinel in productcatalog) and append a
descriptive error like "settlement mode is required/invalid" to the errs slice
when it fails so invalid SettlementMode values are rejected.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8ce07d0 and 06e8b02.

⛔ Files ignored due to path filters (14)
  • 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/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_update.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/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (11)
  • openmeter/billing/charges/adapter.go
  • openmeter/billing/charges/adapter/adapter_test.go
  • openmeter/billing/charges/adapter/create.go
  • openmeter/billing/charges/adapter/mapper.go
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/chargecreditpurchase.go
  • openmeter/billing/charges/chargeusagebased.go
  • openmeter/billing/charges/stdinvoice.go
  • openmeter/ent/schema/charges.go
  • tools/migrate/migrations/20260224121149_charges.down.sql
  • tools/migrate/migrations/20260224121149_charges.up.sql
🚧 Files skipped from review as they are similar to previous changes (3)
  • openmeter/billing/charges/adapter/mapper.go
  • openmeter/billing/charges/stdinvoice.go
  • openmeter/billing/charges/adapter/create.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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/chargeusagebased.go`:
- Line 63: The JSON tag for the Discounts field on UsageBasedIntent is
incorrectly set to "rateCardDiscounts"; update the struct tag on the Discounts
field (Discounts *productcatalog.Discounts) to `json:"discounts"` and search for
any serialization/deserialization uses of UsageBasedIntent or the Discounts
field to adjust tests or callers that expect "rateCardDiscounts" to the new
"discounts" key so the API contract remains consistent.
- Around line 73-75: The current validation uses i.InvoiceAt.IsZero() ||
i.InvoiceAt.Before(i.ServicePeriod.From) but the error message says "must be
after", yet Before allows equality; update the check to enforce strict ordering
by replacing the Before test with a non-After check (i.e., treat equal as
invalid) so the condition becomes i.InvoiceAt.IsZero() ||
!i.InvoiceAt.After(i.ServicePeriod.From), keeping the error message as-is and
referencing i.InvoiceAt and i.ServicePeriod.From in chargeusagebased.go.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06e8b02 and a93d659.

📒 Files selected for processing (1)
  • openmeter/billing/charges/chargeusagebased.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (2)
openmeter/billing/charges/chargeusagebased.go (2)

54-54: JSON tag likely mismatched (rateCardDiscounts).
This still looks like a copy/paste artifact; intent JSON probably wants "discounts".

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

In `@openmeter/billing/charges/chargeusagebased.go` at line 54, The struct field
Discounts in chargeusagebased.go currently uses the JSON tag
`rateCardDiscounts`, which is a copy/paste artifact; update the tag to
`"discounts"` so the field serializes/deserializes as intended (modify the
Discounts *productcatalog.Discounts `json:"rateCardDiscounts"` declaration to
use `json:"discounts"`). Ensure the change is made on the Discounts field to
preserve type and behavior.

64-66: Boundary mismatch: Before allows equality but message says “after”.
If equality is allowed, the message should say “on or after”; if not, the check should use !After(...).

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

In `@openmeter/billing/charges/chargeusagebased.go` around lines 64 - 66, The
boundary check for i.InvoiceAt vs i.ServicePeriod.From is inconsistent: either
allow equality and change the error text to "invoice at must be on or after
service period from", or enforce strict "after" by replacing the condition with
!i.InvoiceAt.After(i.ServicePeriod.From); update the code around the
IsZero/Before check (the block using i.InvoiceAt, i.ServicePeriod.From, Before,
IsZero) accordingly so the condition and the fmt.Errorf message match.
🧹 Nitpick comments (1)
openmeter/billing/charges/adapter/create.go (1)

26-28: Optional: return an empty slice instead of nil.
This avoids nil checks for callers when in.Intents is empty.

♻️ Suggested tweak
-	if len(in.Intents) == 0 {
-		return nil, nil
-	}
+	if len(in.Intents) == 0 {
+		return charges.Charges{}, nil
+	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/adapter/create.go` around lines 26 - 28, The
current early-return returns nil for the intents result when in.Intents is
empty; change that to return an empty slice instead of nil so callers don't need
nil checks. Update the branch that checks if len(in.Intents) == 0 to return an
empty slice value for the function's result type (rather than nil) along with
the nil error; ensure you construct the empty slice with the correct element
type matching the function's return signature so other code consuming the result
can iterate safely.
🤖 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 199-205: The type switch in NewChargeIntent is comparing against
FlatFeeCharge but the generic parameter T is constrained to
FlatFeeIntent|UsageBasedIntent|CreditPurchaseIntent, so the FlatFee case never
matches; change the case to use FlatFeeIntent (i.e., case FlatFeeIntent:) and
set ChargeIntent{t: ChargeTypeFlatFee, flatFee: &v.Intent} so the flatFee branch
is populated correctly (verify similar patterns for UsageBasedIntent and
CreditPurchaseIntent match their respective types).
- Around line 147-152: The Values() method for the ChargeStatus enum currently
returns only Active/Settled/Final which causes Validate() to reject newly
created charges because adapter/buildCreateCharge sets status to
ChargeStatusCreated; update ChargeStatus.Values() to include
string(ChargeStatusCreated) so that "created" is an accepted/valid status,
ensuring Validate(), ChargeStatus.Values(), and adapter/buildCreateCharge remain
consistent.

---

Duplicate comments:
In `@openmeter/billing/charges/chargeusagebased.go`:
- Line 54: The struct field Discounts in chargeusagebased.go currently uses the
JSON tag `rateCardDiscounts`, which is a copy/paste artifact; update the tag to
`"discounts"` so the field serializes/deserializes as intended (modify the
Discounts *productcatalog.Discounts `json:"rateCardDiscounts"` declaration to
use `json:"discounts"`). Ensure the change is made on the Discounts field to
preserve type and behavior.
- Around line 64-66: The boundary check for i.InvoiceAt vs i.ServicePeriod.From
is inconsistent: either allow equality and change the error text to "invoice at
must be on or after service period from", or enforce strict "after" by replacing
the condition with !i.InvoiceAt.After(i.ServicePeriod.From); update the code
around the IsZero/Before check (the block using i.InvoiceAt,
i.ServicePeriod.From, Before, IsZero) accordingly so the condition and the
fmt.Errorf message match.

---

Nitpick comments:
In `@openmeter/billing/charges/adapter/create.go`:
- Around line 26-28: The current early-return returns nil for the intents result
when in.Intents is empty; change that to return an empty slice instead of nil so
callers don't need nil checks. Update the branch that checks if len(in.Intents)
== 0 to return an empty slice value for the function's result type (rather than
nil) along with the nil error; ensure you construct the empty slice with the
correct element type matching the function's return signature so other code
consuming the result can iterate safely.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a93d659 and e7456d8.

📒 Files selected for processing (11)
  • openmeter/billing/charges/adapter.go
  • openmeter/billing/charges/adapter/adapter_test.go
  • openmeter/billing/charges/adapter/create.go
  • openmeter/billing/charges/adapter/mapper.go
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/chargecreditpurchase.go
  • openmeter/billing/charges/chargeflatfee.go
  • openmeter/billing/charges/chargeusagebased.go
  • openmeter/billing/charges/intent.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/service/create.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • openmeter/billing/charges/adapter/adapter_test.go
  • openmeter/billing/charges/adapter.go
  • openmeter/billing/charges/adapter/mapper.go

Comment thread openmeter/billing/charges/charge.go Resolved
Comment thread openmeter/billing/charges/charge.go Resolved
GAlexIHU
GAlexIHU previously approved these changes Feb 24, 2026

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

lgtm

Comment thread openmeter/ent/schema/charges.go Resolved
Comment thread openmeter/billing/charges/charge.go Resolved
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