Skip to content

refactor: split charges - #3943

Merged
turip merged 5 commits into
mainfrom
refactor/split-charges
Mar 16, 2026
Merged

turip merged 5 commits into
mainfrom
refactor/split-charges

Conversation

@turip

@turip turip commented Mar 13, 2026 •

Copy link
Copy Markdown
Member

Overview

This refactor changes the existing charges codebase by:

  • splitting it into multiple components
  • making sure that the database structure is normalized and constraints are in place

New package structure

The charges package is split into multiple subservices:

  • meta: common metadata for all charges (no service layer for now)
  • models: reusable realization models (this enables the database structure changes)
  • flatfee: flat fee handler with dedicated adapter and service
  • creditpurchase: creditpurchase service with dedicated adapter
  • charges (main package): responsible for hooks with billing and external APIs

Database structure

Instead of the generic realization tables this patch makes sure that each subsystem (flat fee/ credit purchase) has its own database tables with proper FK constraints and indexes.

This improves safety by ensuring the data constraints on database level.

Usage based

Usage based is dropped, as that was not implemented.

Notes for reviewer

Charges adapter is empty, but it's kept, as List will require the adapter to be present.

Summary by CodeRabbit

  • New Features

    • Adds dedicated Flat‑Fee and Credit‑Purchase billing services with create/get flows, invoicing, credit allocations, and external payment lifecycle handling.
    • Adds typed settlement and payment models (external & invoiced) and handler interfaces for authorization/settlement.
  • Refactor

    • Major architecture reorg: charges split into focused subpackages with a central meta layer and per‑type workflows.
  • Chores

    • Removes legacy mixed/usage‑based charge APIs and consolidates creation/retrieval around by‑type services.

@coderabbitai

coderabbitai Bot commented Mar 13, 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

Restructures the billing/charges package into meta, flatfee, and creditpurchase modules; removes legacy monolithic adapters, charge types, and payment/stdinvoice models; adds new adapters, mappers, services, models, and validation for flat-fee and credit-purchase flows with transactional support and reworked Get/Create semantics.

Changes

Cohort / File(s) Summary
Removed legacy adapters & tests
openmeter/billing/charges/adapter.go, openmeter/billing/charges/adapter/*, openmeter/billing/charges/adapter/adapter_test.go
Removed the monolithic charges adapter interfaces and many adapter implementation files and tests; Adapter now reduced to entutils.TxCreator at top-level.
Deleted legacy charge types & payment/stdinvoice
openmeter/billing/charges/charge*.go, openmeter/billing/charges/payment.go, openmeter/billing/charges/stdinvoice.go, openmeter/billing/charges/chargeusagebased.go
Removed legacy FlatFee/UsageBased/CreditPurchase types, intents, state models, and stdinvoice/payment types and related validation/error constants.
New meta layer + adapter
openmeter/billing/charges/meta/*, openmeter/billing/charges/meta/adapter/*
Added meta package (ChargeID/Type/Status, Intent, ManagedResource), meta.Adapter interface and implementation (Create, GetByIDs, UpdateStatus) with validation and mappers.
Flat-fee module (new)
openmeter/billing/charges/flatfee/*, openmeter/billing/charges/flatfee/adapter/*, openmeter/billing/charges/flatfee/service/*
Introduced flatfee package: Charge/Intent/State types, adapter (CreateCharges/Update/GetByIDs/CreatePayment/CreateCreditAllocations/CreateInvoicedUsage), mappers, handler interface, prorating enum, and lifecycle service methods.
Credit-purchase module (new)
openmeter/billing/charges/creditpurchase/*, openmeter/billing/charges/creditpurchase/adapter/*, openmeter/billing/charges/creditpurchase/service/*
Added creditpurchase package: Charge/Intent/State, polymorphic Settlement (Invoice/External/Promotional), adapter (Create/Update/GetByIDs, external payment create/update), service orchestration for external payment lifecycle, handler interface, and mappers.
Models & mixins reorganized
openmeter/billing/charges/models/payment/*, .../creditrealization/*, .../invoicedusage/*, .../ledgertransaction/*
Extracted and expanded payment settlement models (Base/External/Invoiced + mixins), credit-realization and invoiced-usage mixins and mapping helpers, ledger transaction GroupReference/TimedGroupReference types.
Charges service refactor
openmeter/billing/charges/service/*
Rewires charges service to use MetaAdapter + flatfee.Service + creditpurchase.Service; changes Create/Get flows (bulk flatfee creation, meta-first GetByIDs then type-specific fetch), removes old orchestrators.
Helpers, tests & small utilities
openmeter/billing/charges/helpers.go, openmeter/billing/charges/service/*_test.go
Added WithIndex generic helper and updated tests/handler stubs to new flatfee/creditpurchase/meta types and interfaces.
Totals API tweak
openmeter/billing/models/totals/mixin.go
Renamed Mutator→Setter and added setters for taxes/charges/discounts/credits used by totals mixin.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Client as Client
    participant ChargesSvc as ChargesService
    participant MetaAdapter as MetaAdapter
    participant CPAdapter as CreditPurchaseAdapter
    participant DB as Database

    Client->>ChargesSvc: Create CreditPurchase (CreateInput)
    ChargesSvc->>MetaAdapter: Create meta (CreateInput) + Tx
    MetaAdapter->>DB: INSERT charge meta row
    DB-->>MetaAdapter: meta record
    MetaAdapter-->>ChargesSvc: meta returned
    ChargesSvc->>CPAdapter: CreateCharge(meta + intent) + Tx
    CPAdapter->>DB: INSERT credit-purchase row (with meta.id)
    DB-->>CPAdapter: credit-purchase record
    CPAdapter-->>ChargesSvc: mapped creditpurchase.Charge
    ChargesSvc-->>Client: created creditpurchase.Charge
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

Suggested reviewers

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

@turip
turip force-pushed the refactor/split-charges branch 4 times, most recently from 0029413 to e174eba Compare March 14, 2026 20:18
@turip
turip marked this pull request as ready for review March 14, 2026 20:26
@turip
turip requested a review from a team as a code owner March 14, 2026 20:26
@turip turip added release-note/misc Miscellaneous changes area/billing labels Mar 14, 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: 19

🧹 Nitpick comments (13)
openmeter/billing/charges/models/payment/errors.go (1)

28-35: Tiny grammar nit on the error message.

The message "cannot settle not authorized payment" reads a bit awkwardly. Consider something like "cannot settle an unauthorized payment" or "cannot settle payment: not authorized" for slightly better readability.

That said, if there's a convention across the codebase to keep messages terse like this, totally fine to leave it as is!

💬 Optional grammar tweak
 var ErrCannotSettleNotAuthorizedPayment = models.NewValidationIssue(
 	ErrCodeCannotSettleNotAuthorizedPayment,
-	"cannot settle not authorized payment",
+	"cannot settle an unauthorized payment",
 	models.WithCriticalSeverity(),
 	commonhttp.WithHTTPStatusCodeAttribute(http.StatusBadRequest),
 )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/models/payment/errors.go` around lines 28 - 35,
Update the validation issue message for ErrCannotSettleNotAuthorizedPayment to
improve grammar/readability: change the human message passed to
models.NewValidationIssue (currently "cannot settle not authorized payment") to
a clearer phrasing such as "cannot settle an unauthorized payment" (or "cannot
settle payment: not authorized") while keeping
ErrCodeCannotSettleNotAuthorizedPayment and the use of
models.NewValidationIssue, models.WithCriticalSeverity(), and
commonhttp.WithHTTPStatusCodeAttribute(http.StatusBadRequest) untouched.
openmeter/billing/charges/meta/service.go (1)

3-5: Keep Service distinct from Adapter.

type Service = Adapter makes the two names identical, so code depending on Service still couples straight to the DB-facing adapter surface. If this package ever needs transactions or hooks, it’ll be much easier to evolve if Service is its own interface (or if callers just use Adapter until a real service exists). As per coding guidelines: openmeter/**/*.go should follow the service/adapter pattern.

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

In `@openmeter/billing/charges/meta/service.go` around lines 3 - 5, Replace the
type alias Service = Adapter with a distinct Service interface/type so callers
are not coupled to the DB-facing Adapter; locate the declaration of Service and
Adapter in service.go and either (a) declare Service as its own interface that
mirrors the Adapter method set (e.g., type Service interface { /* same methods
as Adapter */ }) and keep Adapter as the DB implementation, or (b) introduce a
concrete service struct (e.g., type service struct { adapter Adapter }) that
implements the Service interface by delegating to Adapter; this preserves the
adapter/service separation and makes it possible to add transaction.Run and
hooks later.
openmeter/billing/charges/models/invoicedusage/mixin.go (1)

60-71: Drop the extra SetChargeID constraint here.

Create() never uses it, and this mixin doesn’t define a charge_id field of its own. Keeping it in Creator ties this helper to a specific parent schema for no real benefit and makes reuse harder.

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

In `@openmeter/billing/charges/models/invoicedusage/mixin.go` around lines 60 -
71, The Creator interface in invoicedusage/mixin.go includes an unnecessary
SetChargeID constraint; remove the SetChargeID(chargeID string) T method from
the Creator[T any] interface because the mixin doesn't define a charge_id field
and Create() never uses it, which will decouple this mixin from a specific
parent schema—update the Creator interface declaration (and any local references
to Creator) to exclude SetChargeID so implementations of Creator are no longer
required to provide that method.
openmeter/billing/charges/creditpurchase/service/create.go (1)

24-24: Minor typo in comment.

Small nit: "active" should be "activate".

-		// Let's active the state machine for the credit purchase charge
+		// Let's activate the state machine for the credit purchase charge
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/creditpurchase/service/create.go` at line 24, Fix
the comment typo in create.go: change the comment "// Let's active the state
machine for the credit purchase charge" to use "activate" instead of "active"
(the comment associated with the credit purchase state machine activation logic
in the create.go file).
openmeter/billing/charges/flatfee/service/service.go (1)

1-1: Package naming consideration.

The package is named flatfee but lives in the service/ directory. This is a bit unconventional - typically packages in a service/ folder are named service. If this is intentional to avoid import path collisions (like flatfee/service.service), might be worth adding a brief doc comment explaining the choice for future readers.

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

In `@openmeter/billing/charges/flatfee/service/service.go` at line 1, The package
is declared as "flatfee" inside a directory named "service", which is
unconventional and may confuse readers; either rename the package declaration to
"service" to match the directory or add a brief package doc comment at the top
explaining why the package is intentionally named "flatfee" (e.g., to avoid
import collisions) so future maintainers understand the choice—update the
package line and/or add the doc comment near the package declaration to make the
intent explicit.
openmeter/billing/charges/creditpurchase/adapter/adapter.go (1)

23-37: Consider consistent validation style across adapters.

This Validate() uses early returns while other files in this PR (like flatfee/service/service.go) aggregate errors with errors.Join. Both approaches are valid, but consistency across the new adapter implementations would help maintainability. Not blocking, just a thought for polish.

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

In `@openmeter/billing/charges/creditpurchase/adapter/adapter.go` around lines 23
- 37, The Validate method on Config currently returns on first missing field;
change it to collect all missing-field errors and return a single combined error
(using errors.Join) so it matches the aggregated validation style used elsewhere
(e.g., flatfee/service/service.go); specifically, in Config.Validate gather
errors for Client, Logger, and MetaAdapter into a slice (or err variables) and
return errors.Join(...) if any errors were collected, otherwise nil.
openmeter/billing/charges/flatfee/adapter/mapper.go (1)

72-86: Consider documenting the default Mode value.

When proRatingConfigFromDB returns a disabled config (lines 80-85), it still sets Mode: productcatalog.ProRatingModeProratePrices. This is probably intentional for serialization consistency, but a brief comment would clarify the reasoning.

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

In `@openmeter/billing/charges/flatfee/adapter/mapper.go` around lines 72 - 86,
The default disabled ProRatingConfig returned by proRatingConfigFromDB currently
sets Mode: productcatalog.ProRatingModeProratePrices even when Enabled is false;
add a brief inline comment inside the proRatingConfigFromDB function (near the
default/else return) stating that the Mode is intentionally set for
serialization/compatibility reasons (or to provide a deterministic value) so
callers/serializers won't see an empty/zero value, referencing
productcatalog.ProRatingConfig and productcatalog.ProRatingModeProratePrices to
make the intent explicit.
openmeter/billing/charges/service/get.go (1)

82-116: Sequential fetches could be parallelized if needed.

The flat fee and credit purchase fetches happen sequentially. If performance becomes a concern with large batches, these could be parallelized with an errgroup. Not urgent for now, but worth noting for future optimization.

🤖 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 82 - 116, The two
service calls flatFeeService.GetByIDs and creditPurchaseService.GetByIDs (and
their subsequent loops that write into out using chargesByType and increment
nrFetched) are executed sequentially; to parallelize, run both fetches in
concurrent goroutines using an errgroup (or similar), capture their results into
shared variables (e.g., flatFees and creditPurchases) and any errors into the
group, then wait for group completion before iterating to populate out and
update nrFetched; ensure any access to shared counters or slices is safe (but
you can defer updates to nrFetched and writes to out to the single-threaded
phase after group.Wait()) so the mapping logic that uses chargesByType[...]
[i].Index and charges.NewCharge(...) remains unchanged.
openmeter/billing/charges/meta/adapter.go (1)

86-104: Consider validating empty ChargeIDs slice.

GetByIDsInput.Validate() checks for empty namespace and empty individual IDs, but allows an empty ChargeIDs slice. If calling GetByIDs with no IDs is a valid use case (returns empty result), this is fine. Otherwise, you might want to add a check.

if len(i.ChargeIDs) == 0 {
    errs = append(errs, errors.New("at least one charge ID is required"))
}

Not a blocker—just depends on your API semantics.

🤖 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 86 - 104,
GetByIDsInput.Validate currently checks Namespace and each ChargeIDs element but
allows an empty ChargeIDs slice; update GetByIDsInput.Validate to also check
len(i.ChargeIDs) == 0 and append an error (e.g., "at least one charge ID is
required") to errs so callers can't pass an empty ID list unless that is
intended by API semantics; modify the validation inside the
GetByIDsInput.Validate method (before iterating the slice) to add this check and
return errors.Join(errs...) as before.
openmeter/billing/charges/flatfee/adapter/adapter.go (1)

69-77: Consider wrapping metaAdapter with the transaction for clarity.

The current implementation relies on transaction context propagation—when metaAdapter.Create() and metaAdapter.UpdateStatus() call TransactingRepo internally, they'll detect the driver in context and automatically wrap themselves. While this works, it's not immediately obvious. Since meta.Adapter implements TxCreator and has a WithTx method, explicitly wrapping it here would make the transaction boundary clearer:

func (a *adapter) WithTx(ctx context.Context, tx *entutils.TxDriver) *adapter {
	txDb := entdb.NewTxClientFromRawConfig(ctx, *tx.GetConfig())
	txMetaAdapter := a.metaAdapter.WithTx(ctx, tx)

	return &adapter{
		db:          txDb.Client(),
		logger:      a.logger,
		metaAdapter: txMetaAdapter,
	}
}

This also matches the pattern in other similar adapters and makes it explicit that both the main db and metaAdapter participate in the same transaction.

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

In `@openmeter/billing/charges/flatfee/adapter/adapter.go` around lines 69 - 77,
Wrap the metaAdapter explicitly in the transaction inside adapter.WithTx: after
creating txDb via entdb.NewTxClientFromRawConfig(ctx, *tx.GetConfig()), call the
metaAdapter's WithTx(ctx, tx) (since meta.Adapter implements TxCreator) and
assign that returned txMetaAdapter to the adapter.metaAdapter field so both db
(txDb.Client()) and metaAdapter participate in the same tx; update
adapter.WithTx to return a new adapter with db: txDb.Client(), logger: a.logger,
metaAdapter: txMetaAdapter.
openmeter/billing/charges/flatfee/service/invoice.go (1)

21-28: Validate these handler DTOs before the side-effecting call.

Both inputs already expose Validate(), but the service skips them and goes straight to the handler. Doing the check here keeps the validation contract in one place and stops bad periods or totals from reaching ledger writes.

✂️ Minimal pattern
-	creditAllocations, err := s.handler.OnAssignedToInvoice(ctx, flatfee.OnAssignedToInvoiceInput{
+	onAssignedInput := flatfee.OnAssignedToInvoiceInput{
 		Charge:            charge,
 		ServicePeriod:     line.ServicePeriod,
 		PreTaxTotalAmount: charge.Intent.AmountAfterProration,
-	})
+	}
+	if err := onAssignedInput.Validate(); err != nil {
+		return nil, fmt.Errorf("validating on-assigned-to-invoice input: %w", err)
+	}
+	creditAllocations, err := s.handler.OnAssignedToInvoice(ctx, onAssignedInput)

As per coding guidelines, "Follow service/adapter pattern, constructor patterns, input types, error handling, transactions, hooks, logging, multi-tenancy, and DI wiring conventions documented in the /service skill".

Also applies to: 53-60

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

In `@openmeter/billing/charges/flatfee/service/invoice.go` around lines 21 - 28,
Call Validate() on the DTOs before invoking the side-effecting handler to
prevent invalid data from reaching ledger writes: invoke
flatfee.OnAssignedToInvoiceInput.Validate() on the input you construct just
above the s.handler.OnAssignedToInvoice(ctx,
flatfee.OnAssignedToInvoiceInput{...}) call and return the validation error
(wrapped) if it fails; apply the same pattern to the other handler invocation(s)
in this file (the similar call around lines 53-60) so every DTO is validated in
the service layer before calling s.handler methods.
openmeter/billing/charges/service/invoicependinglines.go (1)

83-93: Make the one-billable-line-per-charge assumption explicit here.

This flow keys work by line ID, but PostLineAssignedToInvoice performs a charge-scoped side effect and the only duplicate guard is the prefetched flatFee.State.CreditRealizations. If billing ever emits two gathering lines with the same ChargeID, the second pass will allocate again in the same run. Tracking processed charge IDs — or failing fast until split-aware allocation exists — would make that invariant much safer.

Also applies to: 96-106, 127-150

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

In `@openmeter/billing/charges/service/invoicependinglines.go` around lines 83 -
93, The code assumes one billable gathering line per ChargeID but currently keys
by LineID (chargesManagedGatheringLines) and later calls
PostLineAssignedToInvoice which does charge-scoped side effects; to make the
invariant explicit, add tracking of processed ChargeIDs when building
chargesManagedGatheringLines (or immediately after) and fail-fast or skip
duplicates: detect duplicate line.ChargeID values, log/return an error (or
return a clear failure) if a ChargeID appears more than once so allocation is
not applied twice; apply the same duplicate-guard logic around the code paths
referenced by PostLineAssignedToInvoice and where
flatFee.State.CreditRealizations is used (the areas around lines 96-106 and
127-150) so duplicates are rejected or skipped consistently.
openmeter/billing/charges/service/service_test.go (1)

150-173: Please add one mixed Create case.

All of the new Create assertions here use a single intent, so the by-type split/merge path never proves that output order stays aligned with the original input when flat fees and credit purchases are interleaved. A tiny [credit purchase, flat fee] case would catch that pretty quickly.

As per coding guidelines **/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests.

Also applies to: 464-472, 595-603, 680-688

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

In `@openmeter/billing/charges/service/service_test.go` around lines 150 - 173,
Tests calling s.Charges.Create only exercise single-intent inputs, so the code
path that splits/merges by type and preserves input order isn't verified; add
one mixed-intent test case that calls s.Charges.Create with Intents containing a
credit purchase intent first and a flat fee intent second (use the existing
helper s.createMockChargeIntent with appropriate parameters for a credit
purchase and the flat fee used elsewhere), assert res length is 2, verify res[0]
is the credit-purchase type and res[1] is meta.ChargeTypeFlatFee, and
convert/assert using the existing helpers (e.g., AsFlatFeeCharge or the
credit-purchase equivalent) to ensure output order matches input; add similar
mixed-case assertions for the other referenced test blocks as well.
🤖 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 59-64: The typed accessor AsFlatFeeCharge currently only checks
the discriminator c.t and then dereferences c.flatFee which can be nil; update
AsFlatFeeCharge (and likewise AsCreditPurchase) to also guard against a nil
payload by checking c.flatFee != nil (or c.creditPurchase != nil) after
verifying c.t and return a descriptive error if nil, otherwise return the
dereferenced value; keep the discriminator check and error messages consistent
with GetChargeID().

In `@openmeter/billing/charges/creditpurchase/adapter/charge.go`:
- Around line 111-135: The code pairs DB rows with input.Charges by slice index
after calling tx.db.ChargeCreditPurchase.Query().All(ctx), but query.All does
not guarantee the same order or presence of all IDs; change this to match rows
to the original input by ID: build a map from input.Charges keyed by charge.ID,
iterate the returned entities and for each entity look up the corresponding
meta.Charge from that map (error if missing), then call
MapCreditPurchaseChargeFromDB(entity.ID-matched input charge, entity,
input.Expands) and append to out; update references around
entutils.TransactingRepo, tx.db.ChargeCreditPurchase.Query()/IDIn,
input.Charges, and MapCreditPurchaseChargeFromDB accordingly.

In `@openmeter/billing/charges/creditpurchase/chargecreditpurchase.go`:
- Around line 26-49: Charge.Validate currently only validates
Intent/Status/State and misses verifying persisted identity fields, allowing
zero-value Namespace/ID to proceed; update Charge.Validate to explicitly check
c.ID and c.Namespace (the fields used by GetChargeID and storage paths) and
append descriptive errors (e.g. "id: value required", "namespace: value
required") to errs before returning errors.Join(errs...), ensuring the domain
validation fails early and consistently when identity is missing.

In `@openmeter/billing/charges/creditpurchase/service/external.go`:
- Around line 22-37: The handler call s.handler.OnCreditPurchaseInitiated is
executed before the charge state is persisted (via s.adapter.UpdateCharge),
which risks duplicate ledger side effects if the DB write fails; change the flow
to persist the transition first (set charge.State.CreditGrantRealization / other
transition fields and call s.adapter.UpdateCharge) and only after successful
persistence invoke s.handler.OnCreditPurchaseInitiated, supplying an idempotency
token or the persisted transition identifier so the handler can deduplicate;
apply the same pattern to the other two flows that call s.handler.On... (the
blocks referenced around the same file) or implement an outbox/transition record
that is written prior to invoking handler callbacks.

In `@openmeter/billing/charges/creditpurchase/service/promotional.go`:
- Around line 13-27: The promotional grant path must be made idempotent by
checking and setting a durable processing/realized marker using a DB-level
compare-and-set before calling s.handler.OnPromotionalCreditPurchase: first read
the charge and if charge.State.CreditGrantRealization is non-nil return early;
otherwise perform a single atomic UpdateCharge (or a dedicated adapter method)
that sets a "processing" marker (or the final TimedGroupReference placeholder)
conditioned on the existing state to prevent races; only after that CAS succeeds
call s.handler.OnPromotionalCreditPurchase (or have the handler be idempotent
keyed by charge.ID) and then persist the final ledgerTransactionGroupReference
via another conditional UpdateCharge if needed; use s.adapter.UpdateCharge (or
add an adapter method) to perform the conditional compare-and-set and reference
the functions s.handler.OnPromotionalCreditPurchase, s.adapter.UpdateCharge, and
the field charge.State.CreditGrantRealization in your changes.

In `@openmeter/billing/charges/creditpurchase/settlment.go`:
- Around line 139-175: The MarshalJSON method on Settlement must validate that
when s.t is SettlementTypeInvoice the s.invoice pointer is non-nil, and when s.t
is SettlementTypeExternal the s.external pointer is non-nil, returning an error
if the required payload is missing (mirroring Validate()); update
Settlement.MarshalJSON to check s.t and the corresponding pointer (s.invoice,
s.external) before building serde and return a descriptive error for missing
payloads so invalid settlements are not serialized.

In `@openmeter/billing/charges/flatfee/adapter.go`:
- Around line 41-45: The validation condition for InitialStatus is inverted: the
code currently checks if i.InitialStatus == "" before calling
i.InitialStatus.Validate(), which skips validation for non-empty values and
validates only when empty; change the logic to call i.InitialStatus.Validate()
when the status is non-empty (i.InitialStatus != "") or alternatively remove the
condition to always validate (depending on intended behavior). Locate the check
around i.InitialStatus and update the condition so that InitialStatus.Validate()
is invoked for non-empty statuses (or unconditionally if you want empty strings
validated as well).

In `@openmeter/billing/charges/flatfee/adapter/charge.go`:
- Around line 123-151: The loop that maps DB entities to meta inputs uses
input.Charges[idx] which is invalid because
tx.db.ChargeFlatFee.Query().Where(...IDIn(...)).All(ctx) returns entities in
unspecified order; instead, build a lookup map from input.Charges keyed by
Charge.ID, then iterate over entities and for each entity use entity.ID to find
the matching meta Charge from that map; call MapChargeFlatFeeFromDB(entity,
matchedMeta, input.Expands), and return an error if a matching meta is missing
to avoid silent mismatches (references: MapChargeFlatFeeFromDB, entities,
input.Charges, IDIn(...).All()).

In `@openmeter/billing/charges/flatfee/charge.go`:
- Around line 30-45: The Charge.Validate method is missing validation for the
embedded managed resource so charges with empty namespace/ID can pass; update
Charge.Validate to call the managed resource's validator (e.g.,
c.Managed.Validate() or the actual embedded type's Validate method) and/or
explicitly check that the managed resource's Namespace and ID are non-empty,
appending any error as fmt.Errorf("managed: %w", err) to the errs slice before
returning errors.Join(errs...); use the exact embedded field name (Managed,
ManagedResource, etc.) in your fix to locate the code.

In `@openmeter/billing/charges/flatfee/service/payment.go`:
- Around line 54-89: The code currently checks payment.StatusAuthorized
in-memory and calls s.handler.OnPaymentSettled before persisting the settled
state, leaving a race; update this to perform a durable compare-and-set in the
adapter layer (or use a DB-level status transition guard) so the transition from
StatusAuthorized to StatusSettled is atomic—e.g., add a new adapter method (or
extend s.adapter.UpdatePayment) that accepts the expected current status and the
new settled fields and returns an error if the current DB status differs, call
that atomic update after s.handler.OnPaymentSettled (or alternately obtain/lock
an idempotency key in the adapter before invoking s.handler.OnPaymentSettled)
and only mark charge.State.Payment/charge.Status final after the durable CAS
succeeds; reference s.handler.OnPaymentSettled, s.adapter.UpdatePayment,
s.adapter.UpdateCharge, paymentSettlement, charge.State.Payment, and
payment.StatusAuthorized when implementing.
- Around line 15-50: The current flow checks charge.State.Payment in-memory then
calls s.handler.OnPaymentAuthorized and persists afterwards, allowing races to
authorize twice; fix by moving the authorization guard into durable state: add
or use an adapter method (e.g., s.adapter.MarkPaymentAuthorizing / a conditional
UpdateCharge CAS) that atomically checks charge.State.Payment is nil and
persists a pending-authorization marker for charge.GetChargeID() before calling
s.handler.OnPaymentAuthorized; if the conditional update fails return
ErrPaymentAlreadyAuthorized; make s.handler.OnPaymentAuthorized idempotent by
accepting the charge ID (or using the persisted marker) so repeated calls are
safe; after handler returns, create the payment (s.adapter.CreatePayment) and
then update the persisted charge to set charge.State.Payment to the final
paymentSettlement via s.adapter.UpdateCharge, all using the charge ID and
honoring transactional/conditional semantics.

In `@openmeter/billing/charges/models/creditrealization/mixin.go`:
- Around line 64-71: The unique index defined in mixinBase.Indexes includes
"deleted_at" in the index columns which prevents Postgres from enforcing
uniqueness for active rows; update the index definition used in
mixinBase.Indexes to remove "deleted_at" from index.Fields(...) and keep the
predicate via entsql.IndexWhere("deleted_at IS NULL") so the unique constraint
applies only to rows matching the WHERE clause (e.g., use
index.Fields("namespace", "charge_id",
"line_id").Annotations(entsql.IndexWhere("deleted_at IS NULL")).Unique()).

In `@openmeter/billing/charges/models/invoicedusage/mixin.go`:
- Around line 80-87: The builder chain on creator in mixin.go includes a
duplicated call to SetNillableLineID(invoicedUsage.LineID); remove the redundant
second SetNillableLineID invocation so the chain reads:
SetAnnotations(...).SetNamespace(...).SetNillableLineID(invoicedUsage.LineID)...SetMutable(...).SetNillableLedgerTransactionGroupID(trnsGroupID),
leaving a single SetNillableLineID call associated with invoicedUsage.LineID to
avoid the confusing duplicate.

In `@openmeter/billing/charges/models/ledgertransaction/ledger.go`:
- Around line 25-30: The current GetIDOrNull method only guards against a nil
receiver but returns a pointer to a zero-value string, so empty IDs leak; update
GroupReference.GetIDOrNull to also return nil when TransactionGroupID is the
empty string (i.e., treat zero-value as unset) and similarly update the other
OrNull helpers (e.g., the GetCreatedAtOrNull-style methods referenced) to return
nil for zero time values; locate and modify the methods on the GroupReference
type (e.g., GetIDOrNull and the OrNull timestamp helper) to check for the
zero-value and return nil instead of a pointer to a zero value.

In `@openmeter/billing/charges/service.go`:
- Around line 75-98: GetByIDsInput.Validate currently only checks for empty
strings, making batch lookups accept malformed IDs; update
GetByIDsInput.Validate to validate each id by coercing to meta.ChargeID (e.g.
meta.ChargeID(id)) and applying the same validation used by GetByIDInput (or the
ChargeID's validation method), returning an error keyed to the index when
validation fails, and keep the existing empty-check and expands validation
behavior; modify the loop in GetByIDsInput.Validate to call that ChargeID
validation for each id and append formatted errors for invalid IDs.

In `@openmeter/billing/charges/service/create.go`:
- Around line 96-100: The loop currently assigns created charges by creation
order into out (out[idx] = createdCharge.Value) which scrambles caller order;
instead read the original intent index stored on each created charge (e.g.
createdCharge.SavedInputIndex or similar field), and place the value into out at
that saved index (out[savedIndex] = createdCharge.Value), preserving
len(input.Intents) for the out slice; update the loop over createdCharges to use
that saved input index rather than the loop index.
- Around line 75-77: The output remapping uses the loop index instead of each
charge's original position causing reordered outputs; in the code handling
createdCharges (the loop that assigns into out), change the loop to iterate
values (for _, createdCharge := range createdCharges) and assign using
createdCharge.Index (out[createdCharge.Index] = createdCharge.Value) so each
created charge is placed at its original input position; ensure you reference
the createdCharges slice and createdCharge.Index field when making the change.

In `@openmeter/billing/charges/service/get.go`:
- Line 79: The slice `out` is being allocated with length len(chargesByType)
(number of keys) which is too small and causes out[targetIndex] OOB errors;
instead compute the total number of charge entries (sum of lengths of each value
slice in the chargesByType map) and allocate `out` with that total as the length
or allocate with that total as capacity and use append. Locate the `out :=
make(charges.Charges, len(chargesByType))` line and replace it by summing over
`chargesByType` (or build with append) so `out` has room for every charge before
writing to `out[targetIndex]`.

In `@openmeter/billing/charges/service/invoice.go`:
- Around line 19-24: The dispatch currently only wires and accepts flat-fee
processors causing credit-purchase charges to hit the unsupported path; update
the handling to include creditpurchase paths: extend handleStandardInvoiceUpdate
to choose processorByType.creditPurchase when the invoice line references a
credit-purchase charge, and update handleChargeEvent to accept
meta.ChargeTypeCreditPurchase (in addition to meta.ChargeTypeFlatFee) and
dispatch to processorByType.creditPurchase accordingly; ensure functions/types
referenced are chargeProcessorFn, processorByType, handleStandardInvoiceUpdate,
handleChargeEvent, and meta.ChargeTypeCreditPurchase so credit-purchase
lifecycle hooks run.

---

Nitpick comments:
In `@openmeter/billing/charges/creditpurchase/adapter/adapter.go`:
- Around line 23-37: The Validate method on Config currently returns on first
missing field; change it to collect all missing-field errors and return a single
combined error (using errors.Join) so it matches the aggregated validation style
used elsewhere (e.g., flatfee/service/service.go); specifically, in
Config.Validate gather errors for Client, Logger, and MetaAdapter into a slice
(or err variables) and return errors.Join(...) if any errors were collected,
otherwise nil.

In `@openmeter/billing/charges/creditpurchase/service/create.go`:
- Line 24: Fix the comment typo in create.go: change the comment "// Let's
active the state machine for the credit purchase charge" to use "activate"
instead of "active" (the comment associated with the credit purchase state
machine activation logic in the create.go file).

In `@openmeter/billing/charges/flatfee/adapter/adapter.go`:
- Around line 69-77: Wrap the metaAdapter explicitly in the transaction inside
adapter.WithTx: after creating txDb via entdb.NewTxClientFromRawConfig(ctx,
*tx.GetConfig()), call the metaAdapter's WithTx(ctx, tx) (since meta.Adapter
implements TxCreator) and assign that returned txMetaAdapter to the
adapter.metaAdapter field so both db (txDb.Client()) and metaAdapter participate
in the same tx; update adapter.WithTx to return a new adapter with db:
txDb.Client(), logger: a.logger, metaAdapter: txMetaAdapter.

In `@openmeter/billing/charges/flatfee/adapter/mapper.go`:
- Around line 72-86: The default disabled ProRatingConfig returned by
proRatingConfigFromDB currently sets Mode:
productcatalog.ProRatingModeProratePrices even when Enabled is false; add a
brief inline comment inside the proRatingConfigFromDB function (near the
default/else return) stating that the Mode is intentionally set for
serialization/compatibility reasons (or to provide a deterministic value) so
callers/serializers won't see an empty/zero value, referencing
productcatalog.ProRatingConfig and productcatalog.ProRatingModeProratePrices to
make the intent explicit.

In `@openmeter/billing/charges/flatfee/service/invoice.go`:
- Around line 21-28: Call Validate() on the DTOs before invoking the
side-effecting handler to prevent invalid data from reaching ledger writes:
invoke flatfee.OnAssignedToInvoiceInput.Validate() on the input you construct
just above the s.handler.OnAssignedToInvoice(ctx,
flatfee.OnAssignedToInvoiceInput{...}) call and return the validation error
(wrapped) if it fails; apply the same pattern to the other handler invocation(s)
in this file (the similar call around lines 53-60) so every DTO is validated in
the service layer before calling s.handler methods.

In `@openmeter/billing/charges/flatfee/service/service.go`:
- Line 1: The package is declared as "flatfee" inside a directory named
"service", which is unconventional and may confuse readers; either rename the
package declaration to "service" to match the directory or add a brief package
doc comment at the top explaining why the package is intentionally named
"flatfee" (e.g., to avoid import collisions) so future maintainers understand
the choice—update the package line and/or add the doc comment near the package
declaration to make the intent explicit.

In `@openmeter/billing/charges/meta/adapter.go`:
- Around line 86-104: GetByIDsInput.Validate currently checks Namespace and each
ChargeIDs element but allows an empty ChargeIDs slice; update
GetByIDsInput.Validate to also check len(i.ChargeIDs) == 0 and append an error
(e.g., "at least one charge ID is required") to errs so callers can't pass an
empty ID list unless that is intended by API semantics; modify the validation
inside the GetByIDsInput.Validate method (before iterating the slice) to add
this check and return errors.Join(errs...) as before.

In `@openmeter/billing/charges/meta/service.go`:
- Around line 3-5: Replace the type alias Service = Adapter with a distinct
Service interface/type so callers are not coupled to the DB-facing Adapter;
locate the declaration of Service and Adapter in service.go and either (a)
declare Service as its own interface that mirrors the Adapter method set (e.g.,
type Service interface { /* same methods as Adapter */ }) and keep Adapter as
the DB implementation, or (b) introduce a concrete service struct (e.g., type
service struct { adapter Adapter }) that implements the Service interface by
delegating to Adapter; this preserves the adapter/service separation and makes
it possible to add transaction.Run and hooks later.

In `@openmeter/billing/charges/models/invoicedusage/mixin.go`:
- Around line 60-71: The Creator interface in invoicedusage/mixin.go includes an
unnecessary SetChargeID constraint; remove the SetChargeID(chargeID string) T
method from the Creator[T any] interface because the mixin doesn't define a
charge_id field and Create() never uses it, which will decouple this mixin from
a specific parent schema—update the Creator interface declaration (and any local
references to Creator) to exclude SetChargeID so implementations of Creator are
no longer required to provide that method.

In `@openmeter/billing/charges/models/payment/errors.go`:
- Around line 28-35: Update the validation issue message for
ErrCannotSettleNotAuthorizedPayment to improve grammar/readability: change the
human message passed to models.NewValidationIssue (currently "cannot settle not
authorized payment") to a clearer phrasing such as "cannot settle an
unauthorized payment" (or "cannot settle payment: not authorized") while keeping
ErrCodeCannotSettleNotAuthorizedPayment and the use of
models.NewValidationIssue, models.WithCriticalSeverity(), and
commonhttp.WithHTTPStatusCodeAttribute(http.StatusBadRequest) untouched.

In `@openmeter/billing/charges/service/get.go`:
- Around line 82-116: The two service calls flatFeeService.GetByIDs and
creditPurchaseService.GetByIDs (and their subsequent loops that write into out
using chargesByType and increment nrFetched) are executed sequentially; to
parallelize, run both fetches in concurrent goroutines using an errgroup (or
similar), capture their results into shared variables (e.g., flatFees and
creditPurchases) and any errors into the group, then wait for group completion
before iterating to populate out and update nrFetched; ensure any access to
shared counters or slices is safe (but you can defer updates to nrFetched and
writes to out to the single-threaded phase after group.Wait()) so the mapping
logic that uses chargesByType[...] [i].Index and charges.NewCharge(...) remains
unchanged.

In `@openmeter/billing/charges/service/invoicependinglines.go`:
- Around line 83-93: The code assumes one billable gathering line per ChargeID
but currently keys by LineID (chargesManagedGatheringLines) and later calls
PostLineAssignedToInvoice which does charge-scoped side effects; to make the
invariant explicit, add tracking of processed ChargeIDs when building
chargesManagedGatheringLines (or immediately after) and fail-fast or skip
duplicates: detect duplicate line.ChargeID values, log/return an error (or
return a clear failure) if a ChargeID appears more than once so allocation is
not applied twice; apply the same duplicate-guard logic around the code paths
referenced by PostLineAssignedToInvoice and where
flatFee.State.CreditRealizations is used (the areas around lines 96-106 and
127-150) so duplicates are rejected or skipped consistently.

In `@openmeter/billing/charges/service/service_test.go`:
- Around line 150-173: Tests calling s.Charges.Create only exercise
single-intent inputs, so the code path that splits/merges by type and preserves
input order isn't verified; add one mixed-intent test case that calls
s.Charges.Create with Intents containing a credit purchase intent first and a
flat fee intent second (use the existing helper s.createMockChargeIntent with
appropriate parameters for a credit purchase and the flat fee used elsewhere),
assert res length is 2, verify res[0] is the credit-purchase type and res[1] is
meta.ChargeTypeFlatFee, and convert/assert using the existing helpers (e.g.,
AsFlatFeeCharge or the credit-purchase equivalent) to ensure output order
matches input; add similar mixed-case assertions for the other referenced test
blocks as well.
🪄 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: 2406fefa-67dc-4ab5-b1d3-dad5fc12fd41

📥 Commits

Reviewing files that changed from the base of the PR and between 0d75c55 and e174eba.

⛔ Files ignored due to path filters (89)
  • 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/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/chargecreditpurchaseexternalpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseexternalpayment/chargecreditpurchaseexternalpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseexternalpayment/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseexternalpayment_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseexternalpayment_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseexternalpayment_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseexternalpayment_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditrealization/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditrealization_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditrealization_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeexternalpaymentsettlement/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeexternalpaymentsettlement_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeexternalpaymentsettlement_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeexternalpaymentsettlement_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeexternalpaymentsettlement_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/chargeflatfeecreditallocations.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeecreditallocations/chargeflatfeecreditallocations.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeecreditallocations/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeecreditallocations_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeecreditallocations_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeecreditallocations_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeecreditallocations_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeinvoicedusage.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeinvoicedusage/chargeflatfeeinvoicedusage.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeinvoicedusage/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeinvoicedusage_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeinvoicedusage_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeinvoicedusage_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeinvoicedusage_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeepayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeepayment/chargeflatfeepayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeepayment/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeepayment_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeepayment_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeepayment_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeepayment_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoiceaccruedusage/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoiceaccruedusage_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoiceaccruedusage_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoiceaccruedusage_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoicepaymentsettlement/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoicepaymentsettlement_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoicepaymentsettlement_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoicepaymentsettlement_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/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/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/tx.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (96)
  • openmeter/billing/charges/adapter.go
  • openmeter/billing/charges/adapter/adapter_test.go
  • openmeter/billing/charges/adapter/charge.go
  • openmeter/billing/charges/adapter/create.go
  • openmeter/billing/charges/adapter/credit.go
  • openmeter/billing/charges/adapter/creditpurchase.go
  • openmeter/billing/charges/adapter/external.go
  • openmeter/billing/charges/adapter/faltfee.go
  • openmeter/billing/charges/adapter/get.go
  • openmeter/billing/charges/adapter/mapper.go
  • openmeter/billing/charges/adapter/stdinvoice.go
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/chargecreditpurchase.go
  • openmeter/billing/charges/chargeflatfee.go
  • openmeter/billing/charges/chargeusagebased.go
  • openmeter/billing/charges/creditpurchase/adapter.go
  • openmeter/billing/charges/creditpurchase/adapter/adapter.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper.go
  • openmeter/billing/charges/creditpurchase/adapter/payment.go
  • openmeter/billing/charges/creditpurchase/chargecreditpurchase.go
  • openmeter/billing/charges/creditpurchase/handler.go
  • openmeter/billing/charges/creditpurchase/service.go
  • openmeter/billing/charges/creditpurchase/service/create.go
  • openmeter/billing/charges/creditpurchase/service/external.go
  • openmeter/billing/charges/creditpurchase/service/get.go
  • openmeter/billing/charges/creditpurchase/service/promotional.go
  • openmeter/billing/charges/creditpurchase/service/service.go
  • openmeter/billing/charges/creditpurchase/settlment.go
  • openmeter/billing/charges/errors.go
  • openmeter/billing/charges/flatfee/adapter.go
  • openmeter/billing/charges/flatfee/adapter/adapter.go
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/flatfee/adapter/credits.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go
  • openmeter/billing/charges/flatfee/adapter/payment.go
  • openmeter/billing/charges/flatfee/adapter/usage.go
  • openmeter/billing/charges/flatfee/charge.go
  • openmeter/billing/charges/flatfee/handler.go
  • openmeter/billing/charges/flatfee/prorating.go
  • openmeter/billing/charges/flatfee/service.go
  • openmeter/billing/charges/flatfee/service/create.go
  • openmeter/billing/charges/flatfee/service/get.go
  • openmeter/billing/charges/flatfee/service/invoice.go
  • openmeter/billing/charges/flatfee/service/payment.go
  • openmeter/billing/charges/flatfee/service/service.go
  • openmeter/billing/charges/helpers.go
  • openmeter/billing/charges/meta/adapter.go
  • openmeter/billing/charges/meta/adapter/adapter.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/meta/errors.go
  • openmeter/billing/charges/meta/intent.go
  • openmeter/billing/charges/meta/resource.go
  • openmeter/billing/charges/meta/service.go
  • openmeter/billing/charges/meta/subscription.go
  • openmeter/billing/charges/models/creditrealization/mixin.go
  • openmeter/billing/charges/models/creditrealization/models.go
  • openmeter/billing/charges/models/invoicedusage/mixin.go
  • openmeter/billing/charges/models/invoicedusage/stdinvoice.go
  • openmeter/billing/charges/models/ledgertransaction/ledger.go
  • openmeter/billing/charges/models/payment/errors.go
  • openmeter/billing/charges/models/payment/external.go
  • openmeter/billing/charges/models/payment/invoiced.go
  • openmeter/billing/charges/models/payment/mixin.go
  • openmeter/billing/charges/models/payment/models.go
  • openmeter/billing/charges/payment.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/creditpurchase.go
  • openmeter/billing/charges/service/creditpurchase/creditpurchase.go
  • openmeter/billing/charges/service/creditpurchase/external.go
  • openmeter/billing/charges/service/creditpurchase/promotional.go
  • openmeter/billing/charges/service/flatfee/flatfee.go
  • openmeter/billing/charges/service/flatfee/payment.go
  • openmeter/billing/charges/service/get.go
  • openmeter/billing/charges/service/handlers_test.go
  • openmeter/billing/charges/service/helpers.go
  • openmeter/billing/charges/service/invoice.go
  • openmeter/billing/charges/service/invoicependinglines.go
  • openmeter/billing/charges/service/service.go
  • openmeter/billing/charges/service/service_test.go
  • openmeter/billing/charges/stdinvoice.go
  • openmeter/billing/models/totals/mixin.go
  • openmeter/ent/schema/billing.go
  • openmeter/ent/schema/charges.go
  • openmeter/ent/schema/chargescreditpurchase.go
  • openmeter/ent/schema/chargesflatfee.go
  • pkg/framework/entutils/entmixinaccessor/mixinaccessor.tpl
  • pkg/framework/entutils/mixinhelper.go
  • pkg/framework/entutils/mixins.go
  • tools/migrate/migrations/20260314200257_charge-normalize-db.down.sql
  • tools/migrate/migrations/20260314200257_charge-normalize-db.up.sql
💤 Files with no reviewable changes (22)
  • openmeter/billing/charges/adapter/charge.go
  • openmeter/billing/charges/service/creditpurchase/creditpurchase.go
  • openmeter/billing/charges/adapter/adapter_test.go
  • openmeter/billing/charges/service/flatfee/flatfee.go
  • openmeter/billing/charges/chargeusagebased.go
  • openmeter/billing/charges/adapter/get.go
  • openmeter/billing/charges/chargeflatfee.go
  • openmeter/billing/charges/service/creditpurchase/external.go
  • openmeter/billing/charges/stdinvoice.go
  • openmeter/billing/charges/adapter/stdinvoice.go
  • openmeter/billing/charges/service/flatfee/payment.go
  • openmeter/billing/charges/errors.go
  • openmeter/billing/charges/adapter/creditpurchase.go
  • openmeter/billing/charges/adapter/external.go
  • openmeter/billing/charges/adapter/credit.go
  • openmeter/billing/charges/adapter/faltfee.go
  • openmeter/billing/charges/service/creditpurchase/promotional.go
  • openmeter/billing/charges/adapter/mapper.go
  • openmeter/billing/charges/payment.go
  • openmeter/billing/charges/adapter/create.go
  • openmeter/billing/charges/chargecreditpurchase.go
  • openmeter/billing/charges/adapter.go

Comment thread openmeter/billing/charges/charge.go Resolved
Comment thread openmeter/billing/charges/service.go 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: 4

♻️ Duplicate comments (2)
openmeter/billing/charges/creditpurchase/adapter/charge.go (1)

123-135: ⚠️ Potential issue | 🟠 Major

Match credit-purchase rows back to metas by ID.

All(ctx) does not preserve the order of input.Charges, and a missing row shifts every later input.Charges[idx] lookup too. That can hydrate one DB row with another charge's meta before the final reorder step.

💡 Suggested fix
-		entitiesMapped := make([]creditpurchase.Charge, 0, len(entities))
-		for idx, entity := range entities {
-			charge, err := MapCreditPurchaseChargeFromDB(input.Charges[idx], entity, input.Expands)
+		chargeMetaByID := make(map[string]meta.Charge, len(input.Charges))
+		for _, chargeMeta := range input.Charges {
+			chargeMetaByID[chargeMeta.ID] = chargeMeta
+		}
+
+		entitiesMapped := make([]creditpurchase.Charge, 0, len(entities))
+		for _, entity := range entities {
+			chargeMeta, ok := chargeMetaByID[entity.ID]
+			if !ok {
+				return nil, fmt.Errorf("missing charge meta for charge %s", entity.ID)
+			}
+
+			charge, err := MapCreditPurchaseChargeFromDB(chargeMeta, entity, input.Expands)
 			if err != nil {
 				return nil, err
 			}
 			entitiesMapped = append(entitiesMapped, charge)
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/creditpurchase/adapter/charge.go` around lines 123
- 135, The code currently assumes query.All(ctx) returns rows in the same order
as input.Charges and uses index-based lookup (input.Charges[idx]) when calling
MapCreditPurchaseChargeFromDB, which is unsafe; instead, build a lookup map from
the returned entities keyed by their ID (from entities slice), then iterate over
input.Charges and for each charge find the matching entity by ID and pass that
entity into MapCreditPurchaseChargeFromDB (and return a clear error if a
matching DB row is missing) so MapCreditPurchaseChargeFromDB is invoked with the
correct row rather than by positional index.
openmeter/billing/charges/flatfee/adapter/charge.go (1)

139-150: ⚠️ Potential issue | 🟠 Major

Match flat-fee rows back to metas by ID.

IDIn(...).All(ctx) gives you an unordered set, so input.Charges[idx] is not a stable match here. If one row is missing, every later mapping is off as well.

💡 Suggested fix
-		entitiesMapped := make([]flatfee.Charge, 0, len(entities))
-		for idx, entity := range entities {
-			charge, err := MapChargeFlatFeeFromDB(entity, input.Charges[idx], input.Expands)
+		chargeMetaByID := make(map[string]meta.Charge, len(input.Charges))
+		for _, chargeMeta := range input.Charges {
+			chargeMetaByID[chargeMeta.ID] = chargeMeta
+		}
+
+		entitiesMapped := make([]flatfee.Charge, 0, len(entities))
+		for _, entity := range entities {
+			chargeMeta, ok := chargeMetaByID[entity.ID]
+			if !ok {
+				return nil, fmt.Errorf("missing charge meta for charge %s", entity.ID)
+			}
+
+			charge, err := MapChargeFlatFeeFromDB(entity, chargeMeta, input.Expands)
 			if err != nil {
 				return nil, err
 			}
 			entitiesMapped = append(entitiesMapped, charge)
 		}
🤖 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 139 - 150,
The code incorrectly assumes query.All(ctx) returns rows in the same order as
input.Charges and uses input.Charges[idx] to map, which breaks when order
differs or rows are missing; fix by building a lookup map from input.Charges
keyed by their ID, iterate the returned entities (from query.All / variable
entities), find the matching input charge via its ID for each entity, then call
MapChargeFlatFeeFromDB(entity, matchedInput, input.Expands), append to
entitiesMapped, and return an explicit error if an entity ID has no
corresponding input charge to avoid silent mismatches.
🧹 Nitpick comments (6)
openmeter/billing/charges/models/creditrealization/mixin.go (1)

60-69: Trim the Creator interface to only required setters.

Create(...) uses SetNillableLineID but never calls SetLineID, so this interface is stricter than needed. Dropping the unused method keeps the contract easier to satisfy and maintain.

✂️ Proposed cleanup
 type Creator[T any] interface {
 	SetNamespace(namespace string) T
 	SetAnnotations(annotations models.Annotations) T
-	SetLineID(lineID string) T
 	SetNillableLineID(lineID *string) T
 	SetAmount(amount alpacadecimal.Decimal) T
 	SetServicePeriodFrom(servicePeriodFrom time.Time) T
 	SetServicePeriodTo(servicePeriodTo time.Time) T
 	SetLedgerTransactionGroupID(ledgerTransactionGroupID string) T
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/models/creditrealization/mixin.go` around lines 60
- 69, The Creator[T any] interface declares SetLineID but Create(...) only uses
SetNillableLineID, so remove the unused SetLineID method from the Creator
interface to relax the contract; update the interface definition (Creator) to
drop SetLineID, scan for any other usages of SetLineID and adjust/remove them if
present, and keep SetNillableLineID, SetAmount, SetNamespace, SetAnnotations,
SetServicePeriodFrom, SetServicePeriodTo, and SetLedgerTransactionGroupID as the
required setters used by Create.
openmeter/billing/charges/flatfee/service/create.go (1)

32-37: Minor: unused idx parameter in lo.Map callback.

The mapping function receives idx but doesn't use it. This is fine functionally—just a nitpick.

-		Intents: lo.Map(input.Intents, func(intent flatfee.Intent, idx int) flatfee.IntentWithInitialStatus {
+		Intents: lo.Map(input.Intents, func(intent flatfee.Intent, _ int) flatfee.IntentWithInitialStatus {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/flatfee/service/create.go` around lines 32 - 37,
The lo.Map callback for mapping input.Intents to flatfee.IntentWithInitialStatus
currently declares an unused idx parameter; update the callback signature in the
call to lo.Map so the index parameter is removed or replaced with an underscore
(e.g., change func(intent flatfee.Intent, idx int) to func(intent
flatfee.Intent)) to eliminate the unused variable warning in the mapping of
intents to flatfee.IntentWithInitialStatus.
openmeter/billing/charges/flatfee/charge.go (1)

89-91: Consider using the type's method directly for clarity.

This works, but instantiating an empty PaymentTermType("") just to call .Values() is a bit unusual. If PaymentTermType has a package-level function or constant slice, that might be clearer.

That said, this is functional and follows patterns elsewhere in the codebase, so totally fine to keep as-is.

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

In `@openmeter/billing/charges/flatfee/charge.go` around lines 89 - 91, Replace
the odd PaymentTermType("") instantiation when calling .Values(): instead use a
clear package-level accessor (e.g. a constant slice or function) and update the
contains check to use it. For example, replace
slices.Contains(productcatalog.PaymentTermType("").Values(),
string(i.PaymentTerm)) with
slices.Contains(productcatalog.PaymentTermTypeValues, string(i.PaymentTerm)) or
slices.Contains(productcatalog.PaymentTermTypeValues(), string(i.PaymentTerm));
locate the check around the PaymentTermType.Values() call and update the symbol
accordingly (PaymentTermType, Values(), i.PaymentTerm, slices.Contains).
openmeter/billing/charges/service/create.go (2)

106-119: Looks like leftover post-create scaffolding.

invoiceChargePostCreateInput and its Validate() method are not referenced anywhere else in this file anymore. Dropping them would make the new inline create flow a bit easier to scan.

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

In `@openmeter/billing/charges/service/create.go` around lines 106 - 119, Remove
the now-unused post-create scaffolding by deleting the
invoiceChargePostCreateInput type and its Validate method since neither
invoiceChargePostCreateInput nor invoiceChargePostCreateInput.Validate() are
referenced elsewhere; ensure any remaining code uses the new inline create flow
and run tests/compile to confirm no remaining references.

136-159: Group gathering lines in one pass.

lo.Uniq(...)+FilterMap(...) walks gatheringLinesToCreate once per (currency, customer) pair, so this turns quadratic as batches grow. A small map-based grouping keeps this path linear and a bit easier to read.

♻️ Possible refactor
-	uniqueCurrencyAndCustomerIDs := lo.Uniq(
-		lo.Map(gatheringLinesToCreate, func(item gatheringLineWithCustomerID, _ int) currencyAndCustomerID {
-			return currencyAndCustomerID{
-				currency:   item.gatheringLine.Currency,
-				customerID: item.customerID,
-			}
-		}),
-	)
-
-	for _, custAndCurrency := range uniqueCurrencyAndCustomerIDs {
-		gatheringLinesForCurrencyAndCustomer := lo.FilterMap(gatheringLinesToCreate, func(item gatheringLineWithCustomerID, _ int) (billing.GatheringLine, bool) {
-			return item.gatheringLine, item.customerID == custAndCurrency.customerID && item.gatheringLine.Currency == custAndCurrency.currency
-		})
-
-		if len(gatheringLinesForCurrencyAndCustomer) == 0 {
-			continue
-		}
+	grouped := make(map[currencyAndCustomerID][]billing.GatheringLine, len(gatheringLinesToCreate))
+	for _, item := range gatheringLinesToCreate {
+		key := currencyAndCustomerID{
+			currency:   item.gatheringLine.Currency,
+			customerID: item.customerID,
+		}
+		grouped[key] = append(grouped[key], item.gatheringLine)
+	}
+
+	for custAndCurrency, gatheringLinesForCurrencyAndCustomer := range grouped {
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/create.go` around lines 136 - 159, The
current code uses lo.Uniq + lo.FilterMap which scans gatheringLinesToCreate once
per currencyAndCustomerID (quadratic); instead, in one pass build a map keyed by
currencyAndCustomerID (or a string composite key) and append each
item.gatheringLine to map[key], then iterate that map and call
s.billingService.CreatePendingInvoiceLines for each key; update references to
gatheringLinesToCreate, currencyAndCustomerID, gatheringLineWithCustomerID,
lo.Uniq, and lo.FilterMap accordingly so the grouping is done in O(n) before
invoking CreatePendingInvoiceLines.
openmeter/billing/charges/charge.go (1)

212-229: Add index context when ByType() returns conversion errors.

Right now the early returns lose which input element failed. Wrapping with idx will make debugging and API error mapping much easier.

💡 Suggested tweak
 	for idx, ch := range i {
 		switch ch.Type() {
 		case meta.ChargeTypeFlatFee:
 			flatFee, err := ch.AsFlatFeeIntent()
 			if err != nil {
-				return ChargeIntentsByType{}, err
+				return ChargeIntentsByType{}, fmt.Errorf("charge intent [%d]: %w", idx, err)
 			}

 			out.FlatFee = append(out.FlatFee, WithIndex[flatfee.Intent]{Index: idx, Value: flatFee})
 		case meta.ChargeTypeCreditPurchase:
 			creditPurchase, err := ch.AsCreditPurchaseIntent()
 			if err != nil {
-				return ChargeIntentsByType{}, err
+				return ChargeIntentsByType{}, fmt.Errorf("charge intent [%d]: %w", idx, err)
 			}

 			out.CreditPurchase = append(out.CreditPurchase, WithIndex[creditpurchase.Intent]{Index: idx, Value: creditPurchase})
 		default:
-			return ChargeIntentsByType{}, fmt.Errorf("unsupported charge type: %s", ch.Type())
+			return ChargeIntentsByType{}, fmt.Errorf("charge intent [%d]: unsupported charge type: %s", idx, ch.Type())
 		}
 	}
🤖 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 212 - 229, The conversion
loop in the ByType-like function returns raw errors which lose which input index
failed; update the error returns from ch.AsFlatFeeIntent and
ch.AsCreditPurchaseIntent (and the default unsupported branch) to wrap the
original error with the index context (e.g., include idx) so callers can map
failures back to the input element — modify the returns in the loop that
currently call ch.AsFlatFeeIntent, ch.AsCreditPurchaseIntent and the default
case to use wrapped errors like fmt.Errorf("index %d: %w", idx, err) (and for
the default fmt.Errorf include idx and ch.Type()) while leaving the
WithIndex[...]{Index: idx, Value: ...} behavior unchanged.
🤖 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/creditpurchase/settlment.go`:
- Line 1: Rename the file from settlment.go to settlement.go to fix the typo;
update any imports or build references that mention the old filename (search for
"settlment.go" in the repo) and ensure the package declaration (package
creditpurchase) and any symbols defined in the file (functions, types) keep
their names unchanged so callers do not need edits; run `go build`/tests to
verify no remaining references to the misspelled filename.

In `@openmeter/billing/charges/flatfee/service/payment.go`:
- Around line 53-92: PostPaymentSettled currently calls s.adapter.UpdatePayment
and then s.adapter.UpdateCharge separately, which can leave a settled payment
while the charge remains non-final on failure; modify the adapter to perform
both updates in a single transactional operation (e.g., add and call a method
like UpdatePaymentAndCharge(ctx, payment payment.Payment, charge flatfee.Charge)
or CommitPaymentSettlement(ctx, paymentSettlement, charge)) and replace the two
separate calls in PostPaymentSettled with that single atomic call so
paymentSettlement and charge.Status are persisted together; keep the pre-checks
around payment.State.Payment and paymentSettlement.Status as-is.
- Around line 42-50: The current flow calls s.adapter.CreatePayment(...) then
s.adapter.UpdateCharge(...), which can error on retry but is protected by the
ChargeFlatFeePayment UNIQUE(namespace, charge_id) constraint; to improve quality
make CreatePayment idempotent by first querying for an existing payment by
(namespace, charge_id) and returning that existing payment if found instead of
failing on constraint violation, otherwise create and return the new payment;
update the CreatePayment implementation (and any helpers it uses) to perform
this upsert-like behavior so callers (e.g., paymentSettlement usage in
payment.go) don’t need to handle constraint errors specially.

In `@openmeter/billing/charges/service/get.go`:
- Around line 56-61: The code currently assigns Index using the order of
chargeMetas when building chargesWithIndex, which loses the original caller
order from input.ChargeIDs and can drop/resize the response; change the logic to
iterate over input.ChargeIDs (preserving caller index) and for each ID look up
the corresponding meta in chargeMetas (by ID) and create
charges.WithIndex[meta.Charge] with Index equal to the input position so out is
sized to len(input.ChargeIDs); additionally, detect and return an error if any
input IDs have no matching meta so we don't silently drop requests. Apply the
same fix pattern to the other similar spots referenced (around the code that
builds with Index at the other locations).

---

Duplicate comments:
In `@openmeter/billing/charges/creditpurchase/adapter/charge.go`:
- Around line 123-135: The code currently assumes query.All(ctx) returns rows in
the same order as input.Charges and uses index-based lookup (input.Charges[idx])
when calling MapCreditPurchaseChargeFromDB, which is unsafe; instead, build a
lookup map from the returned entities keyed by their ID (from entities slice),
then iterate over input.Charges and for each charge find the matching entity by
ID and pass that entity into MapCreditPurchaseChargeFromDB (and return a clear
error if a matching DB row is missing) so MapCreditPurchaseChargeFromDB is
invoked with the correct row rather than by positional index.

In `@openmeter/billing/charges/flatfee/adapter/charge.go`:
- Around line 139-150: The code incorrectly assumes query.All(ctx) returns rows
in the same order as input.Charges and uses input.Charges[idx] to map, which
breaks when order differs or rows are missing; fix by building a lookup map from
input.Charges keyed by their ID, iterate the returned entities (from query.All /
variable entities), find the matching input charge via its ID for each entity,
then call MapChargeFlatFeeFromDB(entity, matchedInput, input.Expands), append to
entitiesMapped, and return an explicit error if an entity ID has no
corresponding input charge to avoid silent mismatches.

---

Nitpick comments:
In `@openmeter/billing/charges/charge.go`:
- Around line 212-229: The conversion loop in the ByType-like function returns
raw errors which lose which input index failed; update the error returns from
ch.AsFlatFeeIntent and ch.AsCreditPurchaseIntent (and the default unsupported
branch) to wrap the original error with the index context (e.g., include idx) so
callers can map failures back to the input element — modify the returns in the
loop that currently call ch.AsFlatFeeIntent, ch.AsCreditPurchaseIntent and the
default case to use wrapped errors like fmt.Errorf("index %d: %w", idx, err)
(and for the default fmt.Errorf include idx and ch.Type()) while leaving the
WithIndex[...]{Index: idx, Value: ...} behavior unchanged.

In `@openmeter/billing/charges/flatfee/charge.go`:
- Around line 89-91: Replace the odd PaymentTermType("") instantiation when
calling .Values(): instead use a clear package-level accessor (e.g. a constant
slice or function) and update the contains check to use it. For example, replace
slices.Contains(productcatalog.PaymentTermType("").Values(),
string(i.PaymentTerm)) with
slices.Contains(productcatalog.PaymentTermTypeValues, string(i.PaymentTerm)) or
slices.Contains(productcatalog.PaymentTermTypeValues(), string(i.PaymentTerm));
locate the check around the PaymentTermType.Values() call and update the symbol
accordingly (PaymentTermType, Values(), i.PaymentTerm, slices.Contains).

In `@openmeter/billing/charges/flatfee/service/create.go`:
- Around line 32-37: The lo.Map callback for mapping input.Intents to
flatfee.IntentWithInitialStatus currently declares an unused idx parameter;
update the callback signature in the call to lo.Map so the index parameter is
removed or replaced with an underscore (e.g., change func(intent flatfee.Intent,
idx int) to func(intent flatfee.Intent)) to eliminate the unused variable
warning in the mapping of intents to flatfee.IntentWithInitialStatus.

In `@openmeter/billing/charges/models/creditrealization/mixin.go`:
- Around line 60-69: The Creator[T any] interface declares SetLineID but
Create(...) only uses SetNillableLineID, so remove the unused SetLineID method
from the Creator interface to relax the contract; update the interface
definition (Creator) to drop SetLineID, scan for any other usages of SetLineID
and adjust/remove them if present, and keep SetNillableLineID, SetAmount,
SetNamespace, SetAnnotations, SetServicePeriodFrom, SetServicePeriodTo, and
SetLedgerTransactionGroupID as the required setters used by Create.

In `@openmeter/billing/charges/service/create.go`:
- Around line 106-119: Remove the now-unused post-create scaffolding by deleting
the invoiceChargePostCreateInput type and its Validate method since neither
invoiceChargePostCreateInput nor invoiceChargePostCreateInput.Validate() are
referenced elsewhere; ensure any remaining code uses the new inline create flow
and run tests/compile to confirm no remaining references.
- Around line 136-159: The current code uses lo.Uniq + lo.FilterMap which scans
gatheringLinesToCreate once per currencyAndCustomerID (quadratic); instead, in
one pass build a map keyed by currencyAndCustomerID (or a string composite key)
and append each item.gatheringLine to map[key], then iterate that map and call
s.billingService.CreatePendingInvoiceLines for each key; update references to
gatheringLinesToCreate, currencyAndCustomerID, gatheringLineWithCustomerID,
lo.Uniq, and lo.FilterMap accordingly so the grouping is done in O(n) before
invoking CreatePendingInvoiceLines.
🪄 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: c84afc56-b823-4a5d-a85c-0791f7a65673

📥 Commits

Reviewing files that changed from the base of the PR and between e174eba and c17b2cb.

⛔ Files ignored due to path filters (2)
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (25)
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/creditpurchase/chargecreditpurchase.go
  • openmeter/billing/charges/creditpurchase/errors.go
  • openmeter/billing/charges/creditpurchase/service/create.go
  • openmeter/billing/charges/creditpurchase/service/promotional.go
  • openmeter/billing/charges/creditpurchase/settlment.go
  • openmeter/billing/charges/flatfee/adapter.go
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/flatfee/charge.go
  • openmeter/billing/charges/flatfee/service/create.go
  • openmeter/billing/charges/flatfee/service/get.go
  • openmeter/billing/charges/flatfee/service/invoice.go
  • openmeter/billing/charges/flatfee/service/payment.go
  • openmeter/billing/charges/flatfee/service/service.go
  • openmeter/billing/charges/models/creditrealization/mixin.go
  • openmeter/billing/charges/models/invoicedusage/mixin.go
  • openmeter/billing/charges/models/ledgertransaction/ledger.go
  • openmeter/billing/charges/models/payment/errors.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/get.go
  • openmeter/billing/charges/service/invoice.go
  • openmeter/billing/charges/service/invoicependinglines.go
  • tools/migrate/migrations/20260314200257_charge-normalize-db.down.sql
  • tools/migrate/migrations/20260314200257_charge-normalize-db.up.sql
🚧 Files skipped from review as they are similar to previous changes (5)
  • openmeter/billing/charges/flatfee/service/get.go
  • openmeter/billing/charges/creditpurchase/service/create.go
  • openmeter/billing/charges/models/invoicedusage/mixin.go
  • openmeter/billing/charges/flatfee/service/service.go
  • openmeter/billing/charges/models/payment/errors.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.

🧹 Nitpick comments (2)
openmeter/billing/charges/flatfee/service/payment.go (1)

56-97: Transaction handling and state machine transitions are clean.

Good implementation - the double-check pattern (nil payment check + status check) protects against invalid transitions. The transaction wrapping ensures UpdatePayment and UpdateCharge are atomic, which addresses the earlier concern about partial updates.

One small thing: the lineWithHeader parameter isn't used in this function (unlike PostPaymentAuthorized where it's used for the amount). If it's there for API consistency or future use, that's fine - just wanted to flag it in case it was unintentional.

,

♻️ Optional: Remove unused parameter if not needed for interface consistency
-func (s *service) PostPaymentSettled(ctx context.Context, charge flatfee.Charge, lineWithHeader billing.StandardLineWithInvoiceHeader) error {
+func (s *service) PostPaymentSettled(ctx context.Context, charge flatfee.Charge) error {

Only if the interface allows it - if both methods need the same signature for callback registration, keeping it is totally reasonable.

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

In `@openmeter/billing/charges/flatfee/service/payment.go` around lines 56 - 97,
The parameter lineWithHeader in PostPaymentSettled is unused; either remove it
from the PostPaymentSettled signature (and any callers) to avoid dead params, or
if signature must match PostPaymentAuthorized, mark it as intentionally unused
(e.g., assign to the blank identifier or rename to _lineWithHeader) so
linters/maintainers know it's deliberate; edit the function PostPaymentSettled
and related interface/call sites accordingly.
openmeter/billing/charges/creditpurchase/settlement.go (1)

64-76: Consider simplifying InvoiceSettlement.Validate() if no extra rules exist.

Right now this just wraps the embedded validation with an extra "generic settlement:" prefix. If there aren't any invoice-specific validation rules planned, you could simplify:

func (s InvoiceSettlement) Validate() error {
    return s.GenericSettlement.Validate()
}

That said, keeping the current structure makes sense if you're planning to add invoice-specific validation later—it's a reasonable placeholder.

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

In `@openmeter/billing/charges/creditpurchase/settlement.go` around lines 64 - 76,
The InvoiceSettlement.Validate method only delegates to
GenericSettlement.Validate while wrapping the error with "generic settlement:";
simplify by returning s.GenericSettlement.Validate() directly in
InvoiceSettlement.Validate if no invoice-specific rules are needed, or keep the
current wrapper only if you intend to add additional invoice-specific validation
later; update the method InvoiceSettlement.Validate accordingly to either return
the embedded validation result or add invoice-specific checks before/after
calling GenericSettlement.Validate.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@openmeter/billing/charges/creditpurchase/settlement.go`:
- Around line 64-76: The InvoiceSettlement.Validate method only delegates to
GenericSettlement.Validate while wrapping the error with "generic settlement:";
simplify by returning s.GenericSettlement.Validate() directly in
InvoiceSettlement.Validate if no invoice-specific rules are needed, or keep the
current wrapper only if you intend to add additional invoice-specific validation
later; update the method InvoiceSettlement.Validate accordingly to either return
the embedded validation result or add invoice-specific checks before/after
calling GenericSettlement.Validate.

In `@openmeter/billing/charges/flatfee/service/payment.go`:
- Around line 56-97: The parameter lineWithHeader in PostPaymentSettled is
unused; either remove it from the PostPaymentSettled signature (and any callers)
to avoid dead params, or if signature must match PostPaymentAuthorized, mark it
as intentionally unused (e.g., assign to the blank identifier or rename to
_lineWithHeader) so linters/maintainers know it's deliberate; edit the function
PostPaymentSettled and related interface/call sites accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5e7abee9-1735-4e9a-99a3-ff1bf174ab3f

📥 Commits

Reviewing files that changed from the base of the PR and between c17b2cb and 4ea403a.

📒 Files selected for processing (4)
  • openmeter/billing/charges/creditpurchase/service/external.go
  • openmeter/billing/charges/creditpurchase/settlement.go
  • openmeter/billing/charges/flatfee/service/invoice.go
  • openmeter/billing/charges/flatfee/service/payment.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • openmeter/billing/charges/flatfee/service/invoice.go
  • openmeter/billing/charges/creditpurchase/service/external.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: 1

🧹 Nitpick comments (1)
openmeter/billing/charges/service/create.go (1)

52-72: Optional perf/readability cleanup: merge the two flat-fee loops into one pass.

Right now flatFees is iterated twice (once for createdCharges, once for gathering lines). In this DB-adjacent path, a single pass keeps it tighter and avoids extra allocations/traversal.

♻️ Suggested refactor
-		createdCharges = append(
-			createdCharges,
-			lo.Map(flatFees, func(fee flatfee.ChargeWithGatheringLine, idx int) charges.WithIndex[charges.Charge] {
-				return charges.WithIndex[charges.Charge]{
-					Index: intentsByType.FlatFee[idx].Index,
-					Value: charges.NewCharge(fee.Charge),
-				}
-			})...,
-		)
-
-		for _, fee := range flatFees {
-			if fee.GatheringLineToCreate != nil {
-				gatheringLinesToCreate = append(gatheringLinesToCreate, gatheringLineWithCustomerID{
-					gatheringLine: *fee.GatheringLineToCreate,
-					customerID: customer.CustomerID{
-						Namespace: input.Namespace,
-						ID:        fee.Charge.Intent.CustomerID,
-					},
-				})
-			}
-		}
+		for idx, fee := range flatFees {
+			createdCharges = append(createdCharges, charges.WithIndex[charges.Charge]{
+				Index: intentsByType.FlatFee[idx].Index,
+				Value: charges.NewCharge(fee.Charge),
+			})
+
+			if fee.GatheringLineToCreate != nil {
+				gatheringLinesToCreate = append(gatheringLinesToCreate, gatheringLineWithCustomerID{
+					gatheringLine: *fee.GatheringLineToCreate,
+					customerID: customer.CustomerID{
+						Namespace: input.Namespace,
+						ID:        fee.Charge.Intent.CustomerID,
+					},
+				})
+			}
+		}

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

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

In `@openmeter/billing/charges/service/create.go` around lines 52 - 72, Merge the
two iterations over flatFees into one pass: inside a single loop over flatFees
(using the index to pull intentsByType.FlatFee[idx].Index), append the
charges.WithIndex entry (Value: charges.NewCharge(fee.Charge)) to createdCharges
and, if fee.GatheringLineToCreate != nil, also append the
gatheringLineWithCustomerID (setting gatheringLine: *fee.GatheringLineToCreate
and customerID: customer.CustomerID{Namespace: input.Namespace, ID:
fee.Charge.Intent.CustomerID}) to gatheringLinesToCreate; keep existing types
and constructors (charges.WithIndex, charges.NewCharge,
gatheringLineWithCustomerID) and preserve the index mapping from
intentsByType.FlatFee.
🤖 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/service/payment.go`:
- Around line 64-66: The guard currently treats any non-payment.StatusAuthorized
as payment.ErrPaymentAlreadySettled which mislabels failed/uncollectible states;
change the check in the settlement logic that examines paymentSettlement.Status
to explicitly switch on known statuses (e.g., payment.StatusAuthorized,
payment.StatusSettled, payment.StatusFailed/uncollectible) and return the
appropriate error for each case instead of always returning
ErrPaymentAlreadySettled; for example, keep the authorized path, return
ErrPaymentAlreadySettled only for already-settled statuses, return a distinct
error (e.g., ErrPaymentFailed or ErrPaymentUncollectible) for
failure/uncollectible statuses, and default to a generic invalid-state error
while preserving charge.ErrorAttributes() in the returned error.

---

Nitpick comments:
In `@openmeter/billing/charges/service/create.go`:
- Around line 52-72: Merge the two iterations over flatFees into one pass:
inside a single loop over flatFees (using the index to pull
intentsByType.FlatFee[idx].Index), append the charges.WithIndex entry (Value:
charges.NewCharge(fee.Charge)) to createdCharges and, if
fee.GatheringLineToCreate != nil, also append the gatheringLineWithCustomerID
(setting gatheringLine: *fee.GatheringLineToCreate and customerID:
customer.CustomerID{Namespace: input.Namespace, ID:
fee.Charge.Intent.CustomerID}) to gatheringLinesToCreate; keep existing types
and constructors (charges.WithIndex, charges.NewCharge,
gatheringLineWithCustomerID) and preserve the index mapping from
intentsByType.FlatFee.
🪄 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: 65967498-c12a-4e79-ac0b-c3ca4e74f34e

📥 Commits

Reviewing files that changed from the base of the PR and between 4ea403a and 37221b2.

📒 Files selected for processing (3)
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/flatfee/service/payment.go
  • openmeter/billing/charges/service/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.

♻️ Duplicate comments (1)
openmeter/billing/charges/flatfee/service/payment.go (1)

69-71: ⚠️ Potential issue | 🟡 Minor

Differentiate non-authorized payment states in the guard.

Right now every non-StatusAuthorized state is returned as ErrPaymentAlreadySettled. That can mislabel invalid states (for example failed/uncollectible) and make operational debugging harder.

Suggested patch
-		if paymentSettlement.Status != payment.StatusAuthorized {
-			return payment.ErrPaymentAlreadySettled.WithAttrs(charge.ErrorAttributes())
-		}
+		switch paymentSettlement.Status {
+		case payment.StatusAuthorized:
+			// continue
+		case payment.StatusSettled:
+			return payment.ErrPaymentAlreadySettled.WithAttrs(charge.ErrorAttributes())
+		default:
+			return payment.ErrCannotSettleNotAuthorizedPayment.WithAttrs(charge.ErrorAttributes())
+		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/flatfee/service/payment.go` around lines 69 - 71,
The guard currently treats every non-payment.StatusAuthorized state as
payment.ErrPaymentAlreadySettled; change this to switch on
paymentSettlement.Status and return more specific errors (e.g., return
payment.ErrPaymentAlreadySettled.WithAttrs(charge.ErrorAttributes()) for
StatusSettled, payment.ErrPaymentFailed.WithAttrs(...) for StatusFailed,
payment.ErrPaymentUncollectible.WithAttrs(...) for StatusUncollectible, and a
generic payment.ErrPaymentInvalidState.WithAttrs(...) for any unknown statuses)
so each non-authorized state is differentiated and preserves
charge.ErrorAttributes(); update the check around paymentSettlement.Status
accordingly.
🧹 Nitpick comments (2)
openmeter/billing/charges/flatfee/service/payment.go (2)

24-40: Validate handler group references before persisting them.

Both lifecycle paths directly persist TransactionGroupID from handler results, but don’t validate the ledgertransaction.GroupReference. If a handler returns an empty ID, you can store an invalid settlement/auth reference.

Suggested patch
 		ledgerTransactionGroupReference, err := s.handler.OnPaymentAuthorized(ctx, charge)
 		if err != nil {
 			return err
 		}
+		if err := ledgerTransactionGroupReference.Validate(); err != nil {
+			return fmt.Errorf("invalid authorization transaction group reference: %w", err)
+		}
@@
 		ledgerTransactionGroupReference, err := s.handler.OnPaymentSettled(ctx, charge)
 		if err != nil {
 			return err
 		}
+		if err := ledgerTransactionGroupReference.Validate(); err != nil {
+			return fmt.Errorf("invalid settlement transaction group reference: %w", err)
+		}

Also applies to: 73-83

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

In `@openmeter/billing/charges/flatfee/service/payment.go` around lines 24 - 40,
Validate the ledger transaction group reference returned by handler before
persisting: after calling s.handler.OnPaymentAuthorized (and the analogous
handler call used later when creating the settlement reference), check that
ledgerTransactionGroupReference.TransactionGroupID (the
ledgertransaction.GroupReference) is non-empty/valid and return an error if not;
only populate payment.InvoicedCreate.Base.Authorized (and the Settlement/Settled
timed group reference in the later block) when the GroupReference is valid to
avoid storing empty IDs.

65-67: Use a structured/domain error for line-ID mismatch.

The plain fmt.Errorf here is a bit inconsistent with the rest of the method, which returns domain errors enriched with charge attributes. Using a domain-style error keeps logging/observability and multi-tenant diagnostics consistent.

As per coding guidelines: "Follow service/adapter pattern, constructor patterns, input types, error handling, transactions, hooks, logging, multi-tenancy, and DI wiring conventions documented in the /service skill."

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

In `@openmeter/billing/charges/flatfee/service/payment.go` around lines 65 - 67,
Replace the plain fmt.Errorf used when comparing paymentSettlement.LineID and
lineWithHeader.Line.ID with the package's domain-style charge error so the error
is enriched with charge attributes and multi-tenant context; locate the
comparison (paymentSettlement.LineID != lineWithHeader.Line.ID) and call the
existing domain/charge error constructor used elsewhere in this package (the
same function used for other enriched errors) and populate it with the
mismatched values (paymentSettlement.LineID and lineWithHeader.Line.ID) plus the
relevant charge attributes (e.g., charge ID / tenant info) so observability and
consistency match the rest of the method.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@openmeter/billing/charges/flatfee/service/payment.go`:
- Around line 69-71: The guard currently treats every
non-payment.StatusAuthorized state as payment.ErrPaymentAlreadySettled; change
this to switch on paymentSettlement.Status and return more specific errors
(e.g., return
payment.ErrPaymentAlreadySettled.WithAttrs(charge.ErrorAttributes()) for
StatusSettled, payment.ErrPaymentFailed.WithAttrs(...) for StatusFailed,
payment.ErrPaymentUncollectible.WithAttrs(...) for StatusUncollectible, and a
generic payment.ErrPaymentInvalidState.WithAttrs(...) for any unknown statuses)
so each non-authorized state is differentiated and preserves
charge.ErrorAttributes(); update the check around paymentSettlement.Status
accordingly.

---

Nitpick comments:
In `@openmeter/billing/charges/flatfee/service/payment.go`:
- Around line 24-40: Validate the ledger transaction group reference returned by
handler before persisting: after calling s.handler.OnPaymentAuthorized (and the
analogous handler call used later when creating the settlement reference), check
that ledgerTransactionGroupReference.TransactionGroupID (the
ledgertransaction.GroupReference) is non-empty/valid and return an error if not;
only populate payment.InvoicedCreate.Base.Authorized (and the Settlement/Settled
timed group reference in the later block) when the GroupReference is valid to
avoid storing empty IDs.
- Around line 65-67: Replace the plain fmt.Errorf used when comparing
paymentSettlement.LineID and lineWithHeader.Line.ID with the package's
domain-style charge error so the error is enriched with charge attributes and
multi-tenant context; locate the comparison (paymentSettlement.LineID !=
lineWithHeader.Line.ID) and call the existing domain/charge error constructor
used elsewhere in this package (the same function used for other enriched
errors) and populate it with the mismatched values (paymentSettlement.LineID and
lineWithHeader.Line.ID) plus the relevant charge attributes (e.g., charge ID /
tenant info) so observability and consistency match the rest of the method.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 48b09044-7a93-4138-80b2-ba1074302f6d

📥 Commits

Reviewing files that changed from the base of the PR and between 37221b2 and 84fe4bc.

📒 Files selected for processing (1)
  • openmeter/billing/charges/flatfee/service/payment.go

@turip
turip force-pushed the refactor/split-charges branch from 84fe4bc to 44a8699 Compare March 16, 2026 07:33
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.

3 participants