Skip to content

feat[charges]: flat fee charges happy path - #3896

Merged
turip merged 9 commits into
mainfrom
feat/flat-fee-charges
Mar 4, 2026
Merged

turip merged 9 commits into
mainfrom
feat/flat-fee-charges

Conversation

@turip

@turip turip commented Feb 24, 2026 •

Copy link
Copy Markdown
Member

Overview

This patch adds support for the flat fee charges with credit_then_invoice settlement schemantics.

The credit only path is not yet implemented, as that would require some additional work to be added to the billing periodic jobs.

Ledger interface

This patch makes the following ledger interface available:


type FlatFeeHandler interface {
	// OnFlatFeeAssignedToInvoice is called when a flat fee is being assigned to an invoice
	OnFlatFeeAssignedToInvoice(ctx context.Context, input OnFlatFeeAssignedToInvoiceInput) ([]CreditRealizationCreateInput, error)

	// OnFlatFeeStandardInvoiceUsageAccrued is called when the remaining usage is sent to the customer on a standard invoice.
	OnFlatFeeStandardInvoiceUsageAccrued(ctx context.Context, input OnFlatFeeStandardInvoiceUsageAccruedInput) (LedgerTransactionGroupReference, error)

	// OnFlatFeePaymentAuthorized is called when a flat fee payment is authorized
	OnFlatFeePaymentAuthorized(ctx context.Context, charge FlatFeeCharge) (LedgerTransactionGroupReference, error)

	// OnFlatFeePaymentSettled is called when a flat fee payment is settled
	OnFlatFeePaymentSettled(ctx context.Context, charge FlatFeeCharge) (LedgerTransactionGroupReference, error)

	// OnFlatFeePaymentUncollectible is called when a flat fee payment is uncollectible
	OnFlatFeePaymentUncollectible(ctx context.Context, charge FlatFeeCharge) (LedgerTransactionGroupReference, error)
}

the service_test.go contains an example flow with all the smaller details for simulating the whole flow.

Notes for reviewer

Summary by CodeRabbit

  • New Features

    • Flat-fee charge lifecycle: create, post-create hooks, invoice assignment, payment authorize/settle, accrued usage, and invoicing pending lines.
    • Credit realizations: create, allocate and persist credits tied to charges; settlement records for payments.
  • Enhancements

    • ChargeID propagation across gathering and invoice lines for traceability.
    • Standard-invoice post-creation hooks and registry to apply line-level adjustments (e.g., credits).
  • Bug Fixes

    • Prevent updates to charge-managed lines to avoid inconsistent state.
  • Tests

    • End-to-end charges service tests covering invoicing, credits, and payment flows.

@coderabbitai

coderabbitai Bot commented Feb 24, 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

Propagates ChargeID through gathering and standard invoice lines; introduces ChargeID/Expands types, credit realization and payment-settlement models, flat-fee service and handlers, adapter methods for realizations/payments, invoice post-creation hooks, and end-to-end flows for invoicing, credit allocation, and payment lifecycle.

Changes

Cohort / File(s) Summary
Charge domain & types
openmeter/billing/charges/charge.go, openmeter/billing/charges/credit.go, openmeter/billing/charges/ledger.go, openmeter/billing/charges/errors.go, openmeter/billing/charges/chargeflatfee.go, openmeter/billing/charges/chargeusagebased.go, openmeter/billing/charges/chargecreditpurchase.go
Added ChargeID, Expand/Expands, ChargeAccessor; credit realization types and validation; ledger/timed ledger refs and validation errors; GetChargeID methods; flat-fee state/extensions and handler/service interfaces.
Charge adapter & mappers
openmeter/billing/charges/adapter.go, openmeter/billing/charges/adapter/..., openmeter/billing/charges/adapter/mapper.go, openmeter/billing/charges/adapter/get.go, openmeter/billing/charges/adapter/stdinvoice.go, openmeter/billing/charges/adapter/credit.go, openmeter/billing/charges/adapter/faltfee.go
Updated adapter interfaces/signatures (GetChargeByID/GetChargesByIDs inputs), added UpdateFlatFeeCharge, CreateCreditRealizations, standard-invoice realization methods; mapper functions accept expands and map realizations/payment/accrued usage.
Flat-fee service & handlers
openmeter/billing/charges/service/..., openmeter/billing/charges/service/flatfee/*
New flat-fee service implementation and scaffolding: PostCreate, PostLineAssignedToInvoice, PostInvoiceIssued, PostPaymentAuthorized, PostPaymentSettled; handler interface and test mock; wiring for post-create grouping and invoice interactions.
Invoice model & hooks
openmeter/billing/stdinvoice.go, openmeter/billing/stdinvoicecredits.go, openmeter/billing/stdinvoiceline.go
Added PostCreationCalculationHook and LineMutator types; CreditApplied gained CreditRealizationID and CloneWithAmount; StandardLineBase gained optional ChargeID.
Gathering → Standard line propagation
openmeter/billing/gatheringinvoice.go, openmeter/billing/adapter/gatheringlines.go, openmeter/billing/adapter/stdinvoicelinemapper.go, openmeter/billing/adapter/stdinvoicelines.go
Added ChargeID to GatheringLineBase; propagate/persist ChargeID through adapter create/update paths; replaced AsStandardLine with AsNewStandardLine(invoiceID string) (*StandardLine, error) requiring invoice ID.
Billing service & invoice pipeline
openmeter/billing/service/*.go, openmeter/billing/service/gatheringinvoicependinglines.go, openmeter/billing/service/stdinvoicestate.go, openmeter/billing/service/service.go
Added standard-invoice hook registry and RegisterStandardInvoiceHooks; invoke post-creation calculation hooks during invoice creation and recalc; wrap post-update hooks in a sub-transaction; convert gathering→standard via AsNewStandardLine.
Invoice pending invoicing & charge orchestration
openmeter/billing/charges/service/invoicependinglines.go, openmeter/billing/charges/service/invoice.go, openmeter/billing/charges/service/create.go
New InvoicePendingLines entry; credit allocation per currency/customer; routing of invoice updates to per-charge processors; invoiceChargePostCreate used to create gathering lines from charges.
Schema & persistence
openmeter/ent/schema/charges.go, openmeter/billing/charges/adapter/stdinvoice.go
Added ChargeCreditRealization entity and edges; added authorized/settled transaction group fields on ChargeFlatFee; adapter methods to create/update payment settlements and accrued usage.
HTTP driver & merge guards
openmeter/billing/httpdriver/invoiceline.go
Added guards preventing updates to charge-managed lines (returns validation error when ChargeID present).
Service helpers & tests
openmeter/billing/charges/service/helpers.go, openmeter/billing/charges/service/handlers_test.go, openmeter/billing/charges/service/service_test.go, test/billing/suite.go, openmeter/server/server_test.go, openmeter/billing/derived.gen.go
Helpers to classify charges; flat-fee test handler mock; large end-to-end charges service tests; test infra for custom invoicing and manual approval; NoopBillingService hook stub; equality updates for ChargeID pointer handling.
Other billing logic tweaks
openmeter/billing/service/lineservice/*, openmeter/billing/service/gatheringinvoicependinglines.go, openmeter/billing/errors.go, openmeter/productcatalog/pro_rating.go
Minor changes: apply credits to flat prices, post-creation hook invocation integration, new billing error ErrCannotUpdateChargeManagedLine, and early-return in pro-rating validation.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ChargesService
    participant FlatFeeService
    participant Adapter
    participant BillingService
    participant DB

    Client->>ChargesService: CreateCharges(flatFeeIntents)
    ChargesService->>Adapter: Create charges (DB)
    Adapter->>DB: Insert Charge + ChargeFlatFee
    ChargesService->>ChargesService: invoiceChargePostCreate()
    ChargesService->>FlatFeeService: PostCreate(flatFeeCharge)
    FlatFeeService->>FlatFeeService: build GatheringLine (includes ChargeID)
    FlatFeeService-->>ChargesService: GatheringLineToCreate
    ChargesService->>BillingService: CreatePendingInvoiceLines(gatheringLines)
    BillingService->>DB: Save GatheringLine(s)
    BillingService-->>ChargesService: pending invoices created

    Client->>BillingService: CreateStandardInvoiceFromGatheringLines
    BillingService->>BillingService: activate state machine
    BillingService->>BillingService: invokePostCreationHooks (per line)
    BillingService->>FlatFeeService: PostLineAssignedToInvoice(charge, line)
    FlatFeeService->>FlatFeeService: handler.OnFlatFeeAssignedToInvoice()
    FlatFeeService->>Adapter: CreateCreditRealizations(chargeID, allocations)
    Adapter->>DB: Save ChargeCreditRealization entries
    Adapter-->>FlatFeeService: created realizations
    FlatFeeService-->>BillingService: credit realizations
    BillingService->>BillingService: calculateInvoice() (apply credits)
    BillingService-->>Client: StandardInvoice with credits applied
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~65 minutes

Possibly related PRs

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.03% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat[charges]: flat fee charges happy path' directly corresponds to the main changes in the PR, which implement flat fee charges with full lifecycle support including creation, invoice assignment, and payment handling.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

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

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

❤️ Share

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

@turip
turip force-pushed the feat/flat-fee-charges branch from b6737db to 494df1e Compare February 27, 2026 08:49
@turip turip changed the title Feat/flat fee charges feat[charges]: flat fee charges happy path Feb 27, 2026
@turip
turip marked this pull request as ready for review February 27, 2026 16:27
@turip
turip requested a review from a team as a code owner February 27, 2026 16:27
@turip turip added release-note/misc Miscellaneous changes area/billing labels Feb 27, 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: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
openmeter/billing/httpdriver/invoiceline.go (1)

725-778: 🛠️ Refactor suggestion | 🟠 Major

Prevent partial in-memory mutation before rejecting charge-managed updates

Nice guard addition, but there’s a small state-safety issue: by the time Line 774 is reached, existing has already been mutated. If we reject the update, the function returns an error but leaves a partially modified pointer behind.

Suggested patch
 	if wasChange {
 		if oldBase.ChargeID != nil {
+			// Revert in-memory mutations before rejecting the update.
+			existing.StandardLineBase = oldBase
+			existing.UsageBased = oldUBP
+
 			return nil, false, billing.ValidationError{
 				Err: fmt.Errorf("line[%s]: %w", existing.ID, billing.ErrCannotUpdateChargeManagedLine),
 			}
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/httpdriver/invoiceline.go` around lines 725 - 778, The
function mergeStandardLineFromInvoiceLineReplaceUpdate mutates existing in-place
before checking the charge-managed update guard, which can leave partially
modified state when rejecting; fix by performing all mapping/validation and the
charge-managed check against a copy (e.g. clone existing into a new variable or
construct a new billing.StandardLine) and only assign the mutated values back to
existing after the guard passes. Specifically, use oldBase/oldUBP as before,
apply rateCardParsed and period/name/metadata changes to a local newLine (or
temp fields), perform the existing.SplitLineGroupID && oldBase.ChargeID
validation against the original oldBase (or against the temp before commit), and
only set existing = newLine (or copy fields back) when all validations succeed
so failures leave existing unchanged.
🧹 Nitpick comments (16)
test/billing/suite.go (1)

604-612: Minor naming inconsistency.

The new types (setupCustomInvoicingResponse, setupCustomInvoicingOptions, setupCustomInvoicingOption) are unexported, while similar types in this file (BillingProfileProvisionOptions, BillingProfileProvisionOption) are exported.

Either approach is fine for test code, but consistency would help readability. Consider either exporting these types to match the existing pattern, or leaving them as-is if intentionally limiting their scope to this package.

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

In `@test/billing/suite.go` around lines 604 - 612, The new test helper types are
unexported (setupCustomInvoicingResponse, setupCustomInvoicingOptions,
setupCustomInvoicingOption) but similar helpers in this file are exported (e.g.,
BillingProfileProvisionOptions, BillingProfileProvisionOption); make them
consistent by exporting these three types (rename to
SetupCustomInvoicingResponse, SetupCustomInvoicingOptions,
SetupCustomInvoicingOption) so they follow the existing pattern, or if you
intend package-local scope, add a short comment above the types explaining why
they remain unexported; update any usages of the types/functions accordingly
(e.g., constructors or variables referencing the old names).
tools/migrate/migrations/20260227135631_charges-flat-fee.up.sql (1)

20-21: Small cleanup: the unique index on id is redundant with the primary key.

Line 14 already makes id unique via PRIMARY KEY, so the extra unique index at Line 20-21 is duplicate overhead.

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

In `@tools/migrate/migrations/20260227135631_charges-flat-fee.up.sql` around lines
20 - 21, Remove the redundant unique index creation: delete the CREATE UNIQUE
INDEX "chargecreditrealization_id" ON "charge_credit_realizations" ("id");
statement because the "id" column is already unique via the table's PRIMARY KEY;
update the up migration to omit this index (and if present, update the
corresponding down migration to avoid trying to drop a nonexistent index).
openmeter/billing/service/service.go (1)

184-186: Add a defensive nil-guard in hook registration.

On Line 185, this can panic if a Service instance is created outside New (tests/mocks/manual construction). A tiny guard makes the method safer.

💡 Suggested change
 func (s *Service) RegisterStandardInvoiceHooks(hooks ...billing.StandardInvoiceHook) {
+	if s.standardInvoiceHooks == nil {
+		s.standardInvoiceHooks = models.NewServiceHookRegistry[billing.StandardInvoice]()
+	}
 	s.standardInvoiceHooks.RegisterHooks(hooks...)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/service/service.go` around lines 184 - 186, The
RegisterStandardInvoiceHooks method can panic when called on a nil or
partially-initialized Service; add a defensive nil-guard at the start of
Service.RegisterStandardInvoiceHooks so it returns early if s == nil or
s.standardInvoiceHooks == nil, otherwise call
s.standardInvoiceHooks.RegisterHooks(hooks...); reference the Service type, the
RegisterStandardInvoiceHooks method, and the standardInvoiceHooks.RegisterHooks
invocation when locating the change.
openmeter/billing/charges/service/flatfee/invoice.go (1)

22-24: Skip the DB call when allocations are empty.

On Line 23, we still call CreateCreditRealizations for empty inputs. A quick early return avoids a no-op DB roundtrip on this hot billing path.

💡 Suggested change
  if err != nil {
  	return nil, fmt.Errorf("on flat fee assigned to invoice: %w", err)
  }

+ if len(creditAllocations) == 0 {
+ 	return charges.CreditRealizations{}, nil
+ }
+
  realizations, err := s.adapter.CreateCreditRealizations(ctx, charge.GetChargeID(), creditAllocations)
  if err != nil {
  	return nil, fmt.Errorf("creating credit realizations: %w", err)
  }

As per coding guidelines "Performance should be a priority in critical code paths. Anything related to ... database operations ... 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/flatfee/invoice.go` around lines 22 - 24,
The code currently calls s.adapter.CreateCreditRealizations(ctx,
charge.GetChargeID(), creditAllocations) even when creditAllocations is empty;
update the logic in invoice.go to check if creditAllocations (or its length) is
zero and skip the DB call entirely (return early or continue as appropriate) to
avoid a no-op roundtrip — i.e., before invoking
s.adapter.CreateCreditRealizations, add a guard like if len(creditAllocations)
== 0 { /* skip/return */ } so CreateCreditRealizations is only called for
non-empty allocations.
openmeter/billing/charges/adapter/get.go (1)

47-47: Consider making WithCreditRealizations() conditional.

On Line 47, eager-loading this edge for every call can inflate DB work and memory when callers only need base charge data. A separate “with realizations” path/option would keep hot reads leaner.

As per coding guidelines "Performance should be a priority in critical code paths. Anything related to ... database operations ... 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/adapter/get.go` at line 47, The query builder in
get.go currently always calls WithCreditRealizations(), which forces
eager-loading for every fetch; change the signature of the public fetch function
(e.g., GetCharges/Get in openmeter/billing/charges/adapter/get.go) to accept an
explicit flag or options (e.g., includeRealizations bool or a options
struct/variadic functional option) and only invoke WithCreditRealizations() when
that flag/option is true; update internal callers to pass false for hot reads
and true where realizations are required, or add a separate
GetChargesWithRealizations wrapper that calls the original fetch with the flag
set.
openmeter/billing/charges/adapter/credit.go (1)

14-16: Add cheap input guards before opening the transaction.

Line 14 can validate chargeID and short-circuit empty batches, which avoids needless DB work and gives cleaner failures.

Suggested refactor
 func (a *adapter) CreateCreditRealizations(ctx context.Context, chargeID charges.ChargeID, realizations []charges.CreditRealizationCreateInput) (charges.CreditRealizations, error) {
+	if err := chargeID.Validate(); err != nil {
+		return nil, err
+	}
+	if len(realizations) == 0 {
+		return charges.CreditRealizations{}, nil
+	}
+
 	return entutils.TransactingRepo(ctx, a, func(ctx context.Context, tx *adapter) (charges.CreditRealizations, error) {

As per coding guidelines: “Performance should be a priority in critical code paths… database operations… 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/adapter/credit.go` around lines 14 - 16, In
CreateCreditRealizations, add cheap input guards before calling
entutils.TransactingRepo: validate the chargeID (e.g., check for
zero/empty/invalid value used by charges.ChargeID) and return an immediate error
if invalid, and short-circuit when realizations is empty by returning an empty
charges.CreditRealizations with nil error; do these checks at the top of the
CreateCreditRealizations function so the transaction is not opened for invalid
or no-op requests.
openmeter/billing/charges/credit.go (1)

29-31: Consider whether zero amounts should be allowed.

The validation checks IsNegative() but the error message says "must be positive". If a zero-amount credit realization is invalid, you may want !i.Amount.IsPositive() instead. If zero is intentional (e.g., placeholder realizations), then the error message could be updated to "must not be negative" for clarity.

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

In `@openmeter/billing/charges/credit.go` around lines 29 - 31, The validation in
credit.go currently uses i.Amount.IsNegative() but the error message says "must
be positive"; decide policy and update accordingly: if zero amounts are invalid,
change the check to !i.Amount.IsPositive() (so zero also triggers the error) and
keep the message "amount must be positive"; if zero amounts are allowed, keep
the IsNegative() check but change the error text to "amount must not be
negative" to accurately reflect the rule; apply the change in the validation
block where i.Amount is inspected.
openmeter/billing/charges/service/invoicependinglines.go (2)

72-75: gatheringLinesWithoutCharges is populated but unused.

The result struct includes gatheringLinesWithoutCharges but it's never accessed after allocateCreditAmountsToBillableLines returns. If this is for future use, consider adding a comment. Otherwise, you could simplify by not tracking these lines.

🤖 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 72 -
75, The struct gatheringLinesWithCreditAllocationsResult defines a field
gatheringLinesWithoutCharges that is populated by
allocateCreditAmountsToBillableLines but never used; either remove this unused
field from gatheringLinesWithCreditAllocationsResult and stop populating it in
allocateCreditAmountsToBillableLines, or keep it and add a clarifying comment on
its intended future use and ensure callers consume it (e.g., return and document
it). Update the type definition and the allocateCreditAmountsToBillableLines
function (and any callers) accordingly to avoid unused data.

18-18: TODO: Address namespace lockdown handling.

This is flagged for follow-up. Should this be tracked in an issue to ensure it doesn't get forgotten?

Do you want me to open a new issue to track the namespace lockdown handling?

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

In `@openmeter/billing/charges/service/invoicependinglines.go` at line 18, Create
a tracked issue for "namespace lockdown handling" and update the TODO in
invoicependinglines.go to reference that issue ID; then plan and implement the
API change by adding a namespaceLockdown parameter (or a typed NamespaceLockdown
struct) to the service constructor and core methods (e.g.,
NewInvoicePendingLinesService and any method like
GetInvoicePendingLines/GetPendingLines) and wire that parameter through the
service logic to filter/validate namespaces. Ensure the TODO now points to the
new issue and add a short unit test stub verifying behavior when namespace
lockdowns are provided.
openmeter/billing/charges/service/service_test.go (1)

138-138: TODO: Add validation for periods and price.

Worth tracking to ensure complete test coverage. Consider adding these validations in a follow-up.

Would you like me to help draft the additional validation assertions?

🤖 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` at line 138, The test
currently has a TODO to validate periods and price; update the failing test in
service_test.go to add explicit assertions for the created charge's period(s)
and pricing fields: assert the charge.Period.Start and charge.Period.End (or
each element in charge.Periods slice) match the expected start/end times and
durations, assert price.Amount equals the expected numeric value and
price.Currency (and scale/precision if applicable), and add checks for
non-negative/positive invariants (e.g., price.Amount > 0, period.End after
period.Start). Use the same assertion style used elsewhere in this file
(t.Errorf / require / assert) and reference the local variables used in the test
(periods, price, charge) so the new assertions integrate with the existing
setup.
openmeter/billing/charges/service/flatfee/payment.go (2)

26-41: Same note on unused lineWithHeader here.

Same observation as above—lineWithHeader isn't used. The flow itself (handler call → state update → persist) looks solid.

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

In `@openmeter/billing/charges/service/flatfee/payment.go` around lines 26 - 41,
PostPaymentSettled currently accepts an unused parameter lineWithHeader; either
remove that parameter from the PostPaymentSettled signature (and update its
interface and all callers) or mark it intentionally unused (rename to
_lineWithHeader) if it must remain for API compatibility. Locate the method
service.PostPaymentSettled and related interface implementations and callers,
and then either delete the lineWithHeader parameter everywhere or rename it to
_lineWithHeader to satisfy linters while leaving the existing flow that calls
flatFeeHandler.OnFlatFeePaymentSettled and persists via
adapter.UpdateFlatFeeCharge unchanged.

10-24: The lineWithHeader parameter is required by the interface contract.

The parameter is indeed unused in both PostPaymentAuthorized and PostPaymentSettled methods, but it's mandated by the interface definition in chargeflatfee.go. Since it can't be removed without breaking the interface, consider adding a comment explaining why it's there—whether it's reserved for future use or part of a broader handler pattern. This would help future readers understand the design intent.

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

In `@openmeter/billing/charges/service/flatfee/payment.go` around lines 10 - 24,
The parameter lineWithHeader is unused but required by the interface; update the
PostPaymentAuthorized and PostPaymentSettled methods on type service to document
this by adding a brief comment above each method (or at the start of the method
body) stating that lineWithHeader is kept for interface compatibility/reserved
for future use (referencing the interface in chargeflatfee.go), and to satisfy
linters add a deliberate no-op usage like assigning to the blank identifier
(e.g., _ = lineWithHeader) so the variable is acknowledged while the existing
logic using flatFeeHandler.OnFlatFeePaymentAuthorized and
adapter.UpdateFlatFeeCharge remains unchanged.
openmeter/ent/schema/charges.go (1)

342-350: TODO: Fix StandardInvoiceSettlement Annotations.

There's a commented-out Annotations() method with a TODO. If this is blocking or needed for this feature, consider tracking it. Otherwise, it's fine to leave as-is for now.

Would you like me to open an issue to track this TODO for the StandardInvoiceSettlement annotations?

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

In `@openmeter/ent/schema/charges.go` around lines 342 - 350, The TODO notes a
commented-out Annotations method for StandardInvoiceSettlement that should
register the custom table name; restore or implement func
(StandardInvoiceSettlement) Annotations() []schema.Annotation returning
[]schema.Annotation{entsql.Annotation{Table:
"charge_standard_invoice_settlements"}} so the Ent schema maps to the intended
DB table (ensure imports for entsql and schema remain), or if this mapping is
unnecessary, remove the dead code and create a tracked issue; locate the
commented block around StandardInvoiceSettlement and either re-enable the method
as described or delete it and add an issue reference.
openmeter/billing/charges/service/create.go (1)

56-70: Consider validating or documenting the unused usageBased field.

invoiceChargePostCreateInput.Validate() only checks namespace, but the struct also has flatFees and usageBased fields. If usageBased is a placeholder for future work, a comment would help. Otherwise, consider removing it until needed.

🤖 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 56 - 70, The
Validate method for invoiceChargePostCreateInput only checks namespace while
leaving flatFees and usageBased unvalidated or undocumented; either validate the
fields (e.g., ensure flatFees and usageBased contain valid entries/lengths and
return errors from invoiceChargePostCreateInput.Validate) or explicitly
document/annotate the unused usageBased field as a future placeholder (add a
comment on the invoiceChargePostCreateInput struct) or remove it until needed;
update the Validate() implementation and/or the struct comment to reflect the
chosen approach so the unused field is handled or clearly intentional.
openmeter/billing/charges/service/invoice.go (2)

141-158: Redundant return err on Line 151.

At Line 151, err will always be nil since the error case was already handled and returned at Line 147-149. You can simplify this.

✨ Simplify return
 func withBillingTransactionForInvoiceManipulation[T any](ctx context.Context, s *service, customerID customer.CustomerID, fn func(ctx context.Context) (T, error)) (T, error) {
 	var out T

 	err := s.billingService.WithLock(ctx, customerID, func(ctx context.Context) error {
 		var err error
 		out, err = fn(ctx)
-		if err != nil {
-			return err
-		}
-
-		return err
+		return err
 	})
 	if err != nil {
 		return lo.Empty[T](), err
 	}

 	return out, nil
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/service/invoice.go` around lines 141 - 158, The
closure passed to s.billingService.WithLock inside
withBillingTransactionForInvoiceManipulation contains a redundant "return err"
after handling the error from fn; since err is already checked and returned when
non-nil, change that final "return err" in the closure to "return nil" (or
simply return without using err) so the closure returns nil on success. Update
the closure inside withBillingTransactionForInvoiceManipulation to return nil
when fn succeeds.

46-65: Consider adding handlers for usageBased and creditPurchase to avoid runtime surprises.

The switch only handles ChargeTypeFlatFee and returns an error for everything else. Since processorByType has fields for usageBased and creditPurchase, callers might expect those to work too. The current error message is generic — you might want to clarify that these types are "not yet implemented" vs "unsupported" to help with debugging.

💡 Optional: More descriptive error message
 		default:
-			return fmt.Errorf("unsupported charge type: %s", lineWithCharge.Charge.Type())
+			return fmt.Errorf("charge type %s not yet implemented for payment post-processing", lineWithCharge.Charge.Type())
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/service/invoice.go` around lines 46 - 65, The loop
over linesWithCharges only handles ChargeTypeFlatFee and returns a generic
"unsupported" error for all other types; update the switch in the invoice
processing (where lineWithCharge.Charge.Type() is checked) to add explicit cases
for the other known types (e.g., ChargeTypeUsageBased and
ChargeTypeCreditPurchase) that call the corresponding processorByType.usageBased
and processorByType.creditPurchase handlers (and return an explicit "not
implemented" or "handler missing" error if those function pointers are nil), and
change the default branch to return a clearer error stating the charge type is
not implemented rather than generically unsupported. Ensure you reference
ChargeTypeFlatFee, ChargeTypeUsageBased, ChargeTypeCreditPurchase,
processorByType.usageBased, and processorByType.creditPurchase when locating and
implementing the changes.
🤖 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/adapter/stdinvoicelines.go`:
- Line 91: The upsert conflict update chain omits the nillable charge_id field
causing stale values on conflict; in the create call where
SetNillableChargeID(line.ChargeID) is used, add the corresponding updater to the
conflict chain (e.g., include .UpdateChargeID(line.ChargeID) or .ClearChargeID()
if you intend to null it) alongside the other updaters referenced in the upsert
block and the TODO about "all nillable fields must be listed explicitly" to
ensure charge_id is correctly handled on conflict.

In `@openmeter/billing/charges/adapter/faltfee.go`:
- Line 70: Normalize the InvoiceAt timestamp to UTC before persisting by
replacing the raw value with its UTC equivalent: change the call using
SetInvoiceAt(intent.InvoiceAt) to SetInvoiceAt(intent.InvoiceAt.UTC()) so it
matches adjacent period fields that are normalized; update any related variables
or builder chain in the same function/method where SetInvoiceAt is called to
ensure consistent UTC storage.

In `@openmeter/billing/charges/adapter/mapper.go`:
- Around line 59-61: The mapper directly accesses
entity.Edges.CreditRealizations without checking if that edge was loaded, unlike
other edges (FlatFee, UsageBased, CreditPurchase); update the mapping to
defensively validate the edge load like the others: check
entity.Edges.CreditRealizations != nil (or use the same helper/validation
pattern used for FlatFee/UsageBased/CreditPurchase) before calling
mapCreditRealizationFromDB for each item, and ensure callers are required to use
WithCreditRealizations() when they need this data so the mapper can distinguish
"edge not loaded" from "zero realizations."

In `@openmeter/billing/service/gatheringinvoicependinglines.go`:
- Around line 770-773: The error string is misleading: when
sm.calculateInvoice(ctx) fails we log "activating invoice state machine" instead
of indicating invoice calculation; update the fmt.Errorf call in the block that
calls sm.calculateInvoice to return a message that references invoice
calculation (e.g., "calculating invoice" or "recalculating invoice") and include
the wrapped err so the failure comes from calculateInvoice; locate the call to
sm.calculateInvoice in the same function and replace the error text to
accurately reflect the operation.

In `@openmeter/billing/service/stdinvoicestate.go`:
- Around line 526-539: The PostUpdate hooks are being invoked with a direct
pointer to m.Invoice inside transaction.RunWithNoValue
(m.Service.standardInvoiceHooks.PostUpdate), so if a hook mutates the struct and
then returns an error those in-memory changes remain even though DB work rolled
back; fix by calling the hooks with a defensive copy/clone of the invoice
(create a deep copy of m.Invoice before calling PostUpdate), run the hooks
against that clone inside the sub-transaction, and only merge/apply the clone
back to m.Invoice after the hooks succeed (or implement/use an Invoice.Clone
method and copy fields back on success) so no partial in-memory mutations leak
on hook error.

In `@tools/migrate/migrations/20260227135631_charges-flat-fee.up.sql`:
- Around line 12-16: Add non-unique indexes on the FK columns to improve
join/delete/update performance: create an index on charge_id and another on
std_realization_id for the charge_credit_realizations table (use explicit names
like idx_charge_credit_realizations_charge_id and
idx_charge_credit_realizations_std_realization_id) and likewise add indexes for
the other FK columns mentioned around lines 22-23; apply these as separate
CREATE INDEX statements in the migration (or inline INDEX clauses) so the new FK
constraints (CONSTRAINT "charge_credit_realizations_charges_credit_realizations"
and CONSTRAINT
"charge_credit_realizations_standard_invoice_settlements_credit_") are supported
by indexes.

---

Outside diff comments:
In `@openmeter/billing/httpdriver/invoiceline.go`:
- Around line 725-778: The function
mergeStandardLineFromInvoiceLineReplaceUpdate mutates existing in-place before
checking the charge-managed update guard, which can leave partially modified
state when rejecting; fix by performing all mapping/validation and the
charge-managed check against a copy (e.g. clone existing into a new variable or
construct a new billing.StandardLine) and only assign the mutated values back to
existing after the guard passes. Specifically, use oldBase/oldUBP as before,
apply rateCardParsed and period/name/metadata changes to a local newLine (or
temp fields), perform the existing.SplitLineGroupID && oldBase.ChargeID
validation against the original oldBase (or against the temp before commit), and
only set existing = newLine (or copy fields back) when all validations succeed
so failures leave existing unchanged.

---

Nitpick comments:
In `@openmeter/billing/charges/adapter/credit.go`:
- Around line 14-16: In CreateCreditRealizations, add cheap input guards before
calling entutils.TransactingRepo: validate the chargeID (e.g., check for
zero/empty/invalid value used by charges.ChargeID) and return an immediate error
if invalid, and short-circuit when realizations is empty by returning an empty
charges.CreditRealizations with nil error; do these checks at the top of the
CreateCreditRealizations function so the transaction is not opened for invalid
or no-op requests.

In `@openmeter/billing/charges/adapter/get.go`:
- Line 47: The query builder in get.go currently always calls
WithCreditRealizations(), which forces eager-loading for every fetch; change the
signature of the public fetch function (e.g., GetCharges/Get in
openmeter/billing/charges/adapter/get.go) to accept an explicit flag or options
(e.g., includeRealizations bool or a options struct/variadic functional option)
and only invoke WithCreditRealizations() when that flag/option is true; update
internal callers to pass false for hot reads and true where realizations are
required, or add a separate GetChargesWithRealizations wrapper that calls the
original fetch with the flag set.

In `@openmeter/billing/charges/credit.go`:
- Around line 29-31: The validation in credit.go currently uses
i.Amount.IsNegative() but the error message says "must be positive"; decide
policy and update accordingly: if zero amounts are invalid, change the check to
!i.Amount.IsPositive() (so zero also triggers the error) and keep the message
"amount must be positive"; if zero amounts are allowed, keep the IsNegative()
check but change the error text to "amount must not be negative" to accurately
reflect the rule; apply the change in the validation block where i.Amount is
inspected.

In `@openmeter/billing/charges/service/create.go`:
- Around line 56-70: The Validate method for invoiceChargePostCreateInput only
checks namespace while leaving flatFees and usageBased unvalidated or
undocumented; either validate the fields (e.g., ensure flatFees and usageBased
contain valid entries/lengths and return errors from
invoiceChargePostCreateInput.Validate) or explicitly document/annotate the
unused usageBased field as a future placeholder (add a comment on the
invoiceChargePostCreateInput struct) or remove it until needed; update the
Validate() implementation and/or the struct comment to reflect the chosen
approach so the unused field is handled or clearly intentional.

In `@openmeter/billing/charges/service/flatfee/invoice.go`:
- Around line 22-24: The code currently calls
s.adapter.CreateCreditRealizations(ctx, charge.GetChargeID(), creditAllocations)
even when creditAllocations is empty; update the logic in invoice.go to check if
creditAllocations (or its length) is zero and skip the DB call entirely (return
early or continue as appropriate) to avoid a no-op roundtrip — i.e., before
invoking s.adapter.CreateCreditRealizations, add a guard like if
len(creditAllocations) == 0 { /* skip/return */ } so CreateCreditRealizations is
only called for non-empty allocations.

In `@openmeter/billing/charges/service/flatfee/payment.go`:
- Around line 26-41: PostPaymentSettled currently accepts an unused parameter
lineWithHeader; either remove that parameter from the PostPaymentSettled
signature (and update its interface and all callers) or mark it intentionally
unused (rename to _lineWithHeader) if it must remain for API compatibility.
Locate the method service.PostPaymentSettled and related interface
implementations and callers, and then either delete the lineWithHeader parameter
everywhere or rename it to _lineWithHeader to satisfy linters while leaving the
existing flow that calls flatFeeHandler.OnFlatFeePaymentSettled and persists via
adapter.UpdateFlatFeeCharge unchanged.
- Around line 10-24: The parameter lineWithHeader is unused but required by the
interface; update the PostPaymentAuthorized and PostPaymentSettled methods on
type service to document this by adding a brief comment above each method (or at
the start of the method body) stating that lineWithHeader is kept for interface
compatibility/reserved for future use (referencing the interface in
chargeflatfee.go), and to satisfy linters add a deliberate no-op usage like
assigning to the blank identifier (e.g., _ = lineWithHeader) so the variable is
acknowledged while the existing logic using
flatFeeHandler.OnFlatFeePaymentAuthorized and adapter.UpdateFlatFeeCharge
remains unchanged.

In `@openmeter/billing/charges/service/invoice.go`:
- Around line 141-158: The closure passed to s.billingService.WithLock inside
withBillingTransactionForInvoiceManipulation contains a redundant "return err"
after handling the error from fn; since err is already checked and returned when
non-nil, change that final "return err" in the closure to "return nil" (or
simply return without using err) so the closure returns nil on success. Update
the closure inside withBillingTransactionForInvoiceManipulation to return nil
when fn succeeds.
- Around line 46-65: The loop over linesWithCharges only handles
ChargeTypeFlatFee and returns a generic "unsupported" error for all other types;
update the switch in the invoice processing (where lineWithCharge.Charge.Type()
is checked) to add explicit cases for the other known types (e.g.,
ChargeTypeUsageBased and ChargeTypeCreditPurchase) that call the corresponding
processorByType.usageBased and processorByType.creditPurchase handlers (and
return an explicit "not implemented" or "handler missing" error if those
function pointers are nil), and change the default branch to return a clearer
error stating the charge type is not implemented rather than generically
unsupported. Ensure you reference ChargeTypeFlatFee, ChargeTypeUsageBased,
ChargeTypeCreditPurchase, processorByType.usageBased, and
processorByType.creditPurchase when locating and implementing the changes.

In `@openmeter/billing/charges/service/invoicependinglines.go`:
- Around line 72-75: The struct gatheringLinesWithCreditAllocationsResult
defines a field gatheringLinesWithoutCharges that is populated by
allocateCreditAmountsToBillableLines but never used; either remove this unused
field from gatheringLinesWithCreditAllocationsResult and stop populating it in
allocateCreditAmountsToBillableLines, or keep it and add a clarifying comment on
its intended future use and ensure callers consume it (e.g., return and document
it). Update the type definition and the allocateCreditAmountsToBillableLines
function (and any callers) accordingly to avoid unused data.
- Line 18: Create a tracked issue for "namespace lockdown handling" and update
the TODO in invoicependinglines.go to reference that issue ID; then plan and
implement the API change by adding a namespaceLockdown parameter (or a typed
NamespaceLockdown struct) to the service constructor and core methods (e.g.,
NewInvoicePendingLinesService and any method like
GetInvoicePendingLines/GetPendingLines) and wire that parameter through the
service logic to filter/validate namespaces. Ensure the TODO now points to the
new issue and add a short unit test stub verifying behavior when namespace
lockdowns are provided.

In `@openmeter/billing/charges/service/service_test.go`:
- Line 138: The test currently has a TODO to validate periods and price; update
the failing test in service_test.go to add explicit assertions for the created
charge's period(s) and pricing fields: assert the charge.Period.Start and
charge.Period.End (or each element in charge.Periods slice) match the expected
start/end times and durations, assert price.Amount equals the expected numeric
value and price.Currency (and scale/precision if applicable), and add checks for
non-negative/positive invariants (e.g., price.Amount > 0, period.End after
period.Start). Use the same assertion style used elsewhere in this file
(t.Errorf / require / assert) and reference the local variables used in the test
(periods, price, charge) so the new assertions integrate with the existing
setup.

In `@openmeter/billing/service/service.go`:
- Around line 184-186: The RegisterStandardInvoiceHooks method can panic when
called on a nil or partially-initialized Service; add a defensive nil-guard at
the start of Service.RegisterStandardInvoiceHooks so it returns early if s ==
nil or s.standardInvoiceHooks == nil, otherwise call
s.standardInvoiceHooks.RegisterHooks(hooks...); reference the Service type, the
RegisterStandardInvoiceHooks method, and the standardInvoiceHooks.RegisterHooks
invocation when locating the change.

In `@openmeter/ent/schema/charges.go`:
- Around line 342-350: The TODO notes a commented-out Annotations method for
StandardInvoiceSettlement that should register the custom table name; restore or
implement func (StandardInvoiceSettlement) Annotations() []schema.Annotation
returning []schema.Annotation{entsql.Annotation{Table:
"charge_standard_invoice_settlements"}} so the Ent schema maps to the intended
DB table (ensure imports for entsql and schema remain), or if this mapping is
unnecessary, remove the dead code and create a tracked issue; locate the
commented block around StandardInvoiceSettlement and either re-enable the method
as described or delete it and add an issue reference.

In `@test/billing/suite.go`:
- Around line 604-612: The new test helper types are unexported
(setupCustomInvoicingResponse, setupCustomInvoicingOptions,
setupCustomInvoicingOption) but similar helpers in this file are exported (e.g.,
BillingProfileProvisionOptions, BillingProfileProvisionOption); make them
consistent by exporting these three types (rename to
SetupCustomInvoicingResponse, SetupCustomInvoicingOptions,
SetupCustomInvoicingOption) so they follow the existing pattern, or if you
intend package-local scope, add a short comment above the types explaining why
they remain unexported; update any usages of the types/functions accordingly
(e.g., constructors or variables referencing the old names).

In `@tools/migrate/migrations/20260227135631_charges-flat-fee.up.sql`:
- Around line 20-21: Remove the redundant unique index creation: delete the
CREATE UNIQUE INDEX "chargecreditrealization_id" ON "charge_credit_realizations"
("id"); statement because the "id" column is already unique via the table's
PRIMARY KEY; update the up migration to omit this index (and if present, update
the corresponding down migration to avoid trying to drop a nonexistent index).

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1c7c3b1 and 08f53c2.

⛔ Files ignored due to path filters (36)
  • 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/chargecreditrealization.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditrealization/chargecreditrealization.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/chargecreditrealization_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditrealization_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_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/expose.go is excluded by !**/ent/db/**
  • openmeter/ent/db/hook/hook.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/paginate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/predicate/predicate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement/standardinvoicesettlement.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/tx.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (50)
  • openmeter/billing/adapter/gatheringlines.go
  • openmeter/billing/adapter/stdinvoicelinemapper.go
  • openmeter/billing/adapter/stdinvoicelines.go
  • openmeter/billing/charges/adapter.go
  • openmeter/billing/charges/adapter/credit.go
  • openmeter/billing/charges/adapter/faltfee.go
  • openmeter/billing/charges/adapter/get.go
  • openmeter/billing/charges/adapter/mapper.go
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/chargecreditpurchase.go
  • openmeter/billing/charges/chargeflatfee.go
  • openmeter/billing/charges/chargeusagebased.go
  • openmeter/billing/charges/credit.go
  • openmeter/billing/charges/errors.go
  • openmeter/billing/charges/ledger.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/flatfee/create.go
  • openmeter/billing/charges/service/flatfee/flatfee.go
  • openmeter/billing/charges/service/flatfee/invoice.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/derived.gen.go
  • openmeter/billing/errors.go
  • openmeter/billing/gatheringinvoice.go
  • openmeter/billing/httpdriver/invoiceline.go
  • openmeter/billing/service.go
  • openmeter/billing/service/gatheringinvoicependinglines.go
  • openmeter/billing/service/invoice.go
  • openmeter/billing/service/lineservice/credits.go
  • openmeter/billing/service/lineservice/usagebasedline.go
  • openmeter/billing/service/service.go
  • openmeter/billing/service/stdinvoicestate.go
  • openmeter/billing/stdinvoice.go
  • openmeter/billing/stdinvoicecredits.go
  • openmeter/billing/stdinvoiceline.go
  • openmeter/ent/schema/charges.go
  • openmeter/productcatalog/pro_rating.go
  • openmeter/server/server_test.go
  • test/billing/suite.go
  • tools/migrate/migrations/20260227135631_charges-flat-fee.down.sql
  • tools/migrate/migrations/20260227135631_charges-flat-fee.up.sql
  • tools/migrate/migrations/20260227160950_charges-trns-group-id.down.sql
  • tools/migrate/migrations/20260227160950_charges-trns-group-id.up.sql

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

825-835: Optional: split error messages for hook-generation vs mutator-application failures.

Small observability win — it’ll be easier to pinpoint where hook processing failed.

💡 Suggested tweak
 		ops, err := hook(invoice, lo.FromPtr(line))
 		if err != nil {
-			return fmt.Errorf("invoking post creation hook: %w", err)
+			return fmt.Errorf("building post creation line mutators: %w", err)
 		}
@@
 		for _, op := range ops {
 			if err := op(line); err != nil {
-				return fmt.Errorf("invoking post creation hook: %w", err)
+				return fmt.Errorf("applying post creation line mutator: %w", err)
 			}
 		}

As per coding guidelines, in Go code readability and maintainability should be prioritized.

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

In `@openmeter/billing/service/gatheringinvoicependinglines.go` around lines 825 -
835, The current error message "invoking post creation hook: %w" is used both
when generating the ops slice and when applying each op, which obscures whether
generation or application failed; update the two error returns to distinct
messages — e.g., when creating ops return an error like "generating
post-creation hooks: %w" and inside the loop when op(line) fails return
"applying post-creation hook: %w" — reference the ops variable and the op(line)
call to locate the sites to change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@openmeter/billing/charges/adapter/faltfee.go`:
- Around line 83-91: MapFlatFeeChargeFromDB is failing because it calls
CreditRealizationsOrErr() but entity.Edges.CreditRealizations isn't populated;
before calling MapFlatFeeChargeFromDB(entity) in UpdateFlatFeeCharge, populate
the entity's CreditRealizations edge (e.g. set entity.Edges.CreditRealizations =
[]*ent.CreditRealization{} or load the actual realizations) so
CreditRealizationsOrErr() doesn't error, then call MapFlatFeeChargeFromDB and
afterward patch mapped.State.CreditRealizations =
charge.State.CreditRealizations as intended.

---

Nitpick comments:
In `@openmeter/billing/service/gatheringinvoicependinglines.go`:
- Around line 825-835: The current error message "invoking post creation hook:
%w" is used both when generating the ops slice and when applying each op, which
obscures whether generation or application failed; update the two error returns
to distinct messages — e.g., when creating ops return an error like "generating
post-creation hooks: %w" and inside the loop when op(line) fails return
"applying post-creation hook: %w" — reference the ops variable and the op(line)
call to locate the sites to change.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 08f53c2 and c40b4a1.

📒 Files selected for processing (4)
  • openmeter/billing/adapter/stdinvoicelines.go
  • openmeter/billing/charges/adapter/faltfee.go
  • openmeter/billing/charges/adapter/mapper.go
  • openmeter/billing/service/gatheringinvoicependinglines.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (3)
openmeter/billing/charges/chargeflatfee.go (1)

124-128: Consider including the index in CreditRealization validation errors.

When iterating over CreditRealizations, if one fails validation, it's hard to tell which one. Adding the index would help debugging.

Suggested improvement
-	for _, realization := range s.CreditRealizations {
+	for i, realization := range s.CreditRealizations {
 		if err := realization.Validate(); err != nil {
-			errs = append(errs, fmt.Errorf("credit realization: %w", err))
+			errs = append(errs, fmt.Errorf("credit realization[%d]: %w", i, err))
 		}
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/chargeflatfee.go` around lines 124 - 128, The loop
over s.CreditRealizations in chargeflatfee.go currently appends validation
errors without context; change the loop to use an index (for i, realization :=
range s.CreditRealizations) and include that index in the error message when
validation fails (e.g., format like "credit realization[%d]: %w" with i and err)
so it's clear which CreditRealization failed in Validate().
openmeter/billing/charges/stdinvoice.go (1)

87-89: Consider clarifying the error message.

IsNegative() allows zero, so "amount must be positive" might confuse someone expecting strictly positive. "amount must be non-negative" or "amount cannot be negative" would be more precise.

Suggested wording
 	if r.Amount.IsNegative() {
-		errs = append(errs, fmt.Errorf("amount must be positive"))
+		errs = append(errs, fmt.Errorf("amount cannot be negative"))
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/stdinvoice.go` around lines 87 - 89, The error
message for the amount check is misleading because IsNegative() permits zero;
update the error text where r.Amount.IsNegative() is handled (the branch that
appends to errs) to use a clearer phrase like "amount cannot be negative" or
"amount must be non-negative" instead of "amount must be positive" so it
accurately reflects the validation performed.
openmeter/billing/charges/service/flatfee/payment.go (1)

42-57: lineWithHeader parameter is unused.

In PostPaymentSettled, the lineWithHeader parameter isn't used anywhere in the function body. If it's intentionally reserved for future use, consider adding a _ = lineWithHeader or a TODO comment to clarify.

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

In `@openmeter/billing/charges/service/flatfee/payment.go` around lines 42 - 57,
The parameter lineWithHeader in function PostPaymentSettled is unused; either
remove the parameter from the PostPaymentSettled signature and update all
callers to stop passing it, or explicitly mark it as intentionally unused by
referencing it (e.g., "_ = lineWithHeader") or adding a clear TODO comment;
update the function declaration in service.PostPaymentSettled and any callers
accordingly so the compiler no longer flags the unused parameter.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@openmeter/billing/charges/service/flatfee/payment.go`:
- Around line 12-15: In PostPaymentAuthorized, avoid dereferencing
charge.State.Payment when it may be nil: first read paymentState :=
charge.State.Payment (or check charge.State.Payment != nil) and then check if
paymentState.Authorized != nil before returning the "payment already authorized"
error; update the guard at the top of the function (in
service.PostPaymentAuthorized) to use this nil-safe check so the later logic
that handles a nil paymentState remains correct.

In `@openmeter/billing/charges/stdinvoice.go`:
- Around line 71-77: The code contains a duplicated nil check for r.Settled
(nested if r.Settled != nil) inside the validation block; remove the inner
redundant nil check so the block reads a single if r.Settled != nil { if err :=
r.Settled.Validate(); err != nil { errs = append(errs, fmt.Errorf("settled: %w",
err)) } } — update the validation logic that calls r.Settled.Validate() to live
directly inside one nil guard and keep the existing error append behavior.

---

Nitpick comments:
In `@openmeter/billing/charges/chargeflatfee.go`:
- Around line 124-128: The loop over s.CreditRealizations in chargeflatfee.go
currently appends validation errors without context; change the loop to use an
index (for i, realization := range s.CreditRealizations) and include that index
in the error message when validation fails (e.g., format like "credit
realization[%d]: %w" with i and err) so it's clear which CreditRealization
failed in Validate().

In `@openmeter/billing/charges/service/flatfee/payment.go`:
- Around line 42-57: The parameter lineWithHeader in function PostPaymentSettled
is unused; either remove the parameter from the PostPaymentSettled signature and
update all callers to stop passing it, or explicitly mark it as intentionally
unused by referencing it (e.g., "_ = lineWithHeader") or adding a clear TODO
comment; update the function declaration in service.PostPaymentSettled and any
callers accordingly so the compiler no longer flags the unused parameter.

In `@openmeter/billing/charges/stdinvoice.go`:
- Around line 87-89: The error message for the amount check is misleading
because IsNegative() permits zero; update the error text where
r.Amount.IsNegative() is handled (the branch that appends to errs) to use a
clearer phrase like "amount cannot be negative" or "amount must be non-negative"
instead of "amount must be positive" so it accurately reflects the validation
performed.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c40b4a1 and 4c9c9dd.

⛔ Files ignored due to path filters (54)
  • 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/chargecreditrealization.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditrealization/chargecreditrealization.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_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditrealization_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/chargestandardinvoiceaccruedusage.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoiceaccruedusage/chargestandardinvoiceaccruedusage.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_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoiceaccruedusage_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoicepaymentsettlement.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoicepaymentsettlement/chargestandardinvoicepaymentsettlement.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_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoicepaymentsettlement_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/expose.go is excluded by !**/ent/db/**
  • openmeter/ent/db/hook/hook.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/paginate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/predicate/predicate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/standardinvoicesettlement_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/tx.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (10)
  • openmeter/billing/charges/adapter/faltfee.go
  • openmeter/billing/charges/chargeflatfee.go
  • openmeter/billing/charges/chargeusagebased.go
  • openmeter/billing/charges/ledger.go
  • openmeter/billing/charges/service/flatfee/payment.go
  • openmeter/billing/charges/stdinvoice.go
  • openmeter/ent/schema/billing.go
  • openmeter/ent/schema/charges.go
  • tools/migrate/migrations/20260302103256_billing-charges-flat-fee.down.sql
  • tools/migrate/migrations/20260302103256_billing-charges-flat-fee.up.sql

Comment thread openmeter/billing/charges/stdinvoice.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: 6

🧹 Nitpick comments (7)
openmeter/billing/charges/errors.go (1)

45-50: Consider using HTTP 400 instead of 500 for ErrUnsupported.

This error represents an "unsupported" operation - essentially a client requesting something not yet implemented. Using HTTP 500 (Internal Server Error) implies a server-side failure, but this is really a client-addressable issue (they requested an unsupported charge type).

A 400 Bad Request or 501 Not Implemented would better communicate the nature of this error. 400 aligns with the other validation issues in this file.

💡 Suggested change
 var ErrUnsupported = models.NewValidationIssue(
 	ErrCodeUnsupported,
 	"unsupported",
 	models.WithCriticalSeverity(),
-	commonhttp.WithHTTPStatusCodeAttribute(http.StatusInternalServerError),
+	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/errors.go` around lines 45 - 50, Change the HTTP
status for the ErrUnsupported validation issue from 500 to 400: update the call
that constructs ErrUnsupported (models.NewValidationIssue with
ErrCodeUnsupported and commonhttp.WithHTTPStatusCodeAttribute) to use
http.StatusBadRequest instead of http.StatusInternalServerError so the error
reflects a client-side unsupported request consistent with other validation
issues.
openmeter/billing/charges/service/invoicependinglines.go (2)

72-75: gatheringLinesWithoutCharges is computed but never used.

The gatheringLinesWithCreditAllocationsResult struct includes gatheringLinesWithoutCharges, which is populated (line 94-96) but the caller InvoicePendingLines only accesses chargesManagedLines. If this is for future use, a brief comment would help; otherwise, consider removing the dead code.

🤖 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 72 -
75, The struct gatheringLinesWithCreditAllocationsResult contains
gatheringLinesWithoutCharges which is populated in the helper (the block around
where it's set) but never read by the caller InvoicePendingLines; remove
gatheringLinesWithoutCharges from the struct and stop populating it (or add a
concise comment explaining it's intentionally retained for future use) and
adjust any code that constructs the gatheringLinesWithCreditAllocationsResult
(the helper that returns this struct) so it only sets and returns
chargesManagedLines, ensuring no unused field remains.

77-80: Redundant nil check on billableLines.

The caller (InvoicePendingLines) already checks for nil at lines 27-30 before calling this function. While defensive coding is good, this check could be removed if the function is internal-only, or kept with a comment explaining the contract.

🤖 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 77 -
80, The nil check in allocateCreditAmountsToBillableLines is redundant because
the caller InvoicePendingLines already validates billableLines; remove the early
if billableLines == nil { return nil, fmt.Errorf("billable lines are nil") }
block from allocateCreditAmountsToBillableLines (or alternatively replace it
with a brief comment asserting the non-nil contract) so the function relies on
the caller's validation and avoids duplicate checks; reference the
allocateCreditAmountsToBillableLines function and InvoicePendingLines caller
when making the change.
openmeter/billing/charges/service/handlers_test.go (1)

67-69: Reset() preserves struct identity but loses t reference.

When Reset() is called, it reinitializes the entire struct to zero values. If you do eventually use the t field, this reset pattern would lose that reference too. Just a heads up for when you address the unused field.

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

In `@openmeter/billing/charges/service/handlers_test.go` around lines 67 - 69, The
Reset method on flatFeeTestHandler currently zeroes the whole struct losing the
t reference; update Reset() to preserve the t field by only clearing/resetting
other fields instead of assigning *h = flatFeeTestHandler{} — e.g., keep a local
copy of h.t and reassign it after zeroing or explicitly set each non-t field to
its zero value so that the t pointer/reference on flatFeeTestHandler remains
intact.
openmeter/billing/charges/service/flatfee/invoice.go (1)

32-36: Lifecycle violation check looks good, but consider a typed error.

The defensive check for existing AccruedUsage is solid. However, the error returned is a plain fmt.Errorf string. If callers need to distinguish this lifecycle violation from other errors, consider returning a typed/sentinel error similar to ErrCreditRealizationsAlreadyAllocated in errors.go.

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

In `@openmeter/billing/charges/service/flatfee/invoice.go` around lines 32 - 36,
Replace the plain fmt.Errorf in PostInvoiceIssued with a typed/sentinel error so
callers can detect this lifecycle violation; define a package-level error
variable (e.g., ErrAccruedInvoiceUsageExists) similar to
ErrCreditRealizationsAlreadyAllocated in errors.go and return it (optionally
wrapped with context using fmt.Errorf("accrued invoice usage already exists for
charge %s: %w", charge.GetChargeID(), ErrAccruedInvoiceUsageExists)) from
PostInvoiceIssued to replace the current fmt.Errorf.
openmeter/billing/charges/service/invoice.go (1)

110-114: Deduplicate charge IDs before querying.

In this invoice-event DB path, duplicate ChargeIDs from lines can inflate the IN (...) list and do extra mapping work. Small optimization, but useful in higher-volume invoices.

⚡ Small perf tweak
-		ChargeIDs: lo.Map(linesWithChargeID, func(l billing.StandardLineWithInvoiceHeader, _ int) string {
+		ChargeIDs: lo.Uniq(lo.Map(linesWithChargeID, func(l billing.StandardLineWithInvoiceHeader, _ int) string {
 			return *l.Line.ChargeID
-		}),
+		})),
As per coding guidelines `**/*.go`: “Performance should be a priority in critical code paths...database operations...should be vetted for potential performance bottlenecks.”
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/service/invoice.go` around lines 110 - 114, The
current call to s.GetChargesByIDs builds the ChargeIDs list by mapping
linesWithChargeID and can include duplicates; deduplicate the IDs before passing
them to GetChargesByIDs (e.g., collect into a map/set or use a uniq helper) so
the slice passed to GetChargesByIDs contains only unique
*billing.StandardLineWithInvoiceHeader.Line.ChargeID values; update the block
around lo.Map(...) and the GetChargesByIDs invocation to use the deduped slice
to avoid inflating the IN(...) query and extra mapping work.
openmeter/billing/charges/adapter/adapter_test.go (1)

78-82: Add at least one assertion that validates ExpandRealizations behavior.

These updates verify the new input shape, but they don’t yet verify that expanded realization state is correctly populated (or intentionally empty) when ExpandRealizations is requested. A focused assertion/scenario here would make regressions much easier to catch.

As per coding guidelines **/*_test.go: “Make sure the tests are comprehensive and cover the changes.”

Also applies to: 127-131, 176-180

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

In `@openmeter/billing/charges/adapter/adapter_test.go` around lines 78 - 82, Add
assertions to verify ExpandRealizations behavior for GetChargesByIDs: after
calling s.adapter.GetChargesByIDs with charges.GetChargesByIDsInput and
charges.Expands{charges.ExpandRealizations}, assert on the returned fetched (and
its element matching ffCreated.ManagedResource.ID) that the Realizations field
(or equivalent property) is populated and has the expected length/content; also
add a complementary test call without charges.ExpandRealizations to assert that
Realizations is nil/empty. Update the existing calls around GetChargesByIDs,
charges.GetChargesByIDsInput, charges.Expands, and the fetched result checks to
include these explicit assertions so expansion behavior is validated.
🤖 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 402-420: GetChargesByIDsInput.Validate currently allows an empty
ChargeIDs slice because the loop is skipped; update Validate (function
GetChargesByIDsInput.Validate) to explicitly reject an empty list by checking
len(i.ChargeIDs) == 0 and appending an error like "charge IDs: must contain at
least one id" to errs before iterating, ensuring the method returns an error via
errors.Join when no IDs are provided.

In `@openmeter/billing/charges/credit.go`:
- Around line 29-31: The validation currently uses i.Amount.IsNegative() but the
error message says "must be positive", which is inconsistent because zero is
allowed; update the error message to reflect the allowed range (e.g., change the
appended error to fmt.Errorf("amount must be non-negative") so it matches the
IsNegative() check on i.Amount) — alternatively, if zero should be disallowed,
replace the IsNegative() check with a strict-positive test (e.g., ensure
i.Amount.IsZero() or use an IsPositive() helper) for the validation in the same
block referencing i.Amount.

In `@openmeter/billing/charges/service/handlers_test.go`:
- Around line 13-25: The flatFeeTestHandler struct currently declares an unused
t *testing.T field but newFlatFeeTestHandler() does not initialize it; either
remove the t *testing.T field from flatFeeTestHandler if it’s not needed, or
change newFlatFeeTestHandler() to accept (t *testing.T) and set the field
(return &flatFeeTestHandler{t: t}) so tests can use it in methods like
onFlatFeeAssignedToInvoice, onFlatFeeStandardInvoiceUsageAccrued,
onFlatFeePaymentAuthorized, onFlatFeePaymentSettled, and
onFlatFeePaymentUncollectible.

In `@openmeter/billing/charges/service/invoice.go`:
- Around line 53-70: The switch over lineWithCharge.Charge.Type() should not
return an error when a known charge type (e.g., charges.ChargeTypeFlatFee,
usage-based, credit-purchase) has no configured processor; instead, for each
known type (start with handling charges.ChargeTypeFlatFee via AsFlatFeeCharge
and processorByType.flatFee) call the processor if present and otherwise skip
that line silently or log and continue; only return an error in the default
branch for truly unknown/unsupported charge types. Update the switch in the
function handling StandardLineWithInvoiceHeader so that: for ChargeTypeFlatFee
you keep AsFlatFeeCharge and call processorByType.flatFee if non-nil, for other
known enum types (e.g., ChargeTypeUsage, ChargeTypeCreditPurchase) either invoke
their processor if present or skip, and let the default case return fmt.Errorf
for unknown types.

In `@openmeter/billing/charges/service/service_test.go`:
- Around line 358-360: The test currently calls s.Fail("invalid payment term:
%s", price.PaymentTerm) which does not perform format interpolation; replace
this call with s.T().Fatalf("invalid payment term: %s", price.PaymentTerm) (or
alternatively s.FailNow(fmt.Sprintf(...)) if you prefer), targeting the s.Fail
occurrence in the test (the switch default handling for price.PaymentTerm) so
the formatted message is emitted and the test stops immediately.

In `@openmeter/billing/charges/stdinvoice.go`:
- Around line 82-84: The validation currently checks r.Amount.IsNegative() and
appends fmt.Errorf("amount must be positive"), which is misleading because zero
is allowed; update the error message appended where r.Amount.IsNegative() is
evaluated (the validation block using r.Amount.IsNegative() and errs =
append(...)) to a phrasing that reflects non-negativity such as "amount cannot
be negative" or "amount must be non-negative" so the message matches the actual
check.

---

Nitpick comments:
In `@openmeter/billing/charges/adapter/adapter_test.go`:
- Around line 78-82: Add assertions to verify ExpandRealizations behavior for
GetChargesByIDs: after calling s.adapter.GetChargesByIDs with
charges.GetChargesByIDsInput and charges.Expands{charges.ExpandRealizations},
assert on the returned fetched (and its element matching
ffCreated.ManagedResource.ID) that the Realizations field (or equivalent
property) is populated and has the expected length/content; also add a
complementary test call without charges.ExpandRealizations to assert that
Realizations is nil/empty. Update the existing calls around GetChargesByIDs,
charges.GetChargesByIDsInput, charges.Expands, and the fetched result checks to
include these explicit assertions so expansion behavior is validated.

In `@openmeter/billing/charges/errors.go`:
- Around line 45-50: Change the HTTP status for the ErrUnsupported validation
issue from 500 to 400: update the call that constructs ErrUnsupported
(models.NewValidationIssue with ErrCodeUnsupported and
commonhttp.WithHTTPStatusCodeAttribute) to use http.StatusBadRequest instead of
http.StatusInternalServerError so the error reflects a client-side unsupported
request consistent with other validation issues.

In `@openmeter/billing/charges/service/flatfee/invoice.go`:
- Around line 32-36: Replace the plain fmt.Errorf in PostInvoiceIssued with a
typed/sentinel error so callers can detect this lifecycle violation; define a
package-level error variable (e.g., ErrAccruedInvoiceUsageExists) similar to
ErrCreditRealizationsAlreadyAllocated in errors.go and return it (optionally
wrapped with context using fmt.Errorf("accrued invoice usage already exists for
charge %s: %w", charge.GetChargeID(), ErrAccruedInvoiceUsageExists)) from
PostInvoiceIssued to replace the current fmt.Errorf.

In `@openmeter/billing/charges/service/handlers_test.go`:
- Around line 67-69: The Reset method on flatFeeTestHandler currently zeroes the
whole struct losing the t reference; update Reset() to preserve the t field by
only clearing/resetting other fields instead of assigning *h =
flatFeeTestHandler{} — e.g., keep a local copy of h.t and reassign it after
zeroing or explicitly set each non-t field to its zero value so that the t
pointer/reference on flatFeeTestHandler remains intact.

In `@openmeter/billing/charges/service/invoice.go`:
- Around line 110-114: The current call to s.GetChargesByIDs builds the
ChargeIDs list by mapping linesWithChargeID and can include duplicates;
deduplicate the IDs before passing them to GetChargesByIDs (e.g., collect into a
map/set or use a uniq helper) so the slice passed to GetChargesByIDs contains
only unique *billing.StandardLineWithInvoiceHeader.Line.ChargeID values; update
the block around lo.Map(...) and the GetChargesByIDs invocation to use the
deduped slice to avoid inflating the IN(...) query and extra mapping work.

In `@openmeter/billing/charges/service/invoicependinglines.go`:
- Around line 72-75: The struct gatheringLinesWithCreditAllocationsResult
contains gatheringLinesWithoutCharges which is populated in the helper (the
block around where it's set) but never read by the caller InvoicePendingLines;
remove gatheringLinesWithoutCharges from the struct and stop populating it (or
add a concise comment explaining it's intentionally retained for future use) and
adjust any code that constructs the gatheringLinesWithCreditAllocationsResult
(the helper that returns this struct) so it only sets and returns
chargesManagedLines, ensuring no unused field remains.
- Around line 77-80: The nil check in allocateCreditAmountsToBillableLines is
redundant because the caller InvoicePendingLines already validates
billableLines; remove the early if billableLines == nil { return nil,
fmt.Errorf("billable lines are nil") } block from
allocateCreditAmountsToBillableLines (or alternatively replace it with a brief
comment asserting the non-nil contract) so the function relies on the caller's
validation and avoids duplicate checks; reference the
allocateCreditAmountsToBillableLines function and InvoicePendingLines caller
when making the change.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c9c9dd and 1a32bf4.

⛔ Files ignored due to path filters (29)
  • 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/chargecreditrealization.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditrealization/chargecreditrealization.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_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditrealization_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/chargestandardinvoiceaccruedusage.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargestandardinvoiceaccruedusage/chargestandardinvoiceaccruedusage.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_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (26)
  • openmeter/billing/charges/adapter.go
  • openmeter/billing/charges/adapter/adapter_test.go
  • openmeter/billing/charges/adapter/create.go
  • openmeter/billing/charges/adapter/credit.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/chargeflatfee.go
  • openmeter/billing/charges/credit.go
  • openmeter/billing/charges/errors.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/service/flatfee/invoice.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/invoice.go
  • openmeter/billing/charges/service/invoicependinglines.go
  • openmeter/billing/charges/service/service_test.go
  • openmeter/billing/charges/stdinvoice.go
  • openmeter/ent/schema/charges.go
  • tools/migrate/migrations/20260303092401_billing-charges-flat-fee.down.sql
  • tools/migrate/migrations/20260303092401_billing-charges-flat-fee.up.sql
  • tools/migrate/migrations/20260303093315_billing-charges-flat-fee.down.sql
  • tools/migrate/migrations/20260303093315_billing-charges-flat-fee.up.sql
🚧 Files skipped from review as they are similar to previous changes (2)
  • openmeter/billing/charges/service/flatfee/payment.go
  • openmeter/billing/charges/adapter/credit.go

Comment thread openmeter/billing/charges/charge.go Resolved
Comment thread openmeter/billing/charges/credit.go Resolved
Comment thread openmeter/billing/charges/stdinvoice.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: 3

♻️ Duplicate comments (1)
openmeter/billing/charges/stdinvoice.go (1)

80-82: ⚠️ Potential issue | 🟡 Minor

Fix the amount validation message at Line 81.

This check only rejects negative values, so "amount must be positive" is misleading. A non-negative message would match behavior.

Suggested fix
 	if r.Amount.IsNegative() {
-		errs = append(errs, fmt.Errorf("amount must be positive"))
+		errs = append(errs, fmt.Errorf("amount cannot be negative"))
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/stdinvoice.go` around lines 80 - 82, The validation
currently checks r.Amount.IsNegative() but logs "amount must be positive", which
is misleading; update the error message in the append call (the fmt.Errorf
passed to errs in the block that checks r.Amount.IsNegative()) to state that the
amount must be non-negative (or "must not be negative") so the message matches
the actual check.
🧹 Nitpick comments (2)
openmeter/billing/charges/adapter/mapper.go (1)

314-319: Reuse the existing ledger-reference mapper to avoid drift.

This block duplicates logic already implemented in mapLedgerTransactionGroupReferenceFromDB. Reusing the helper keeps mapping behavior consistent and easier to maintain.

♻️ Suggested refactor
 func mapStandardInvoiceAccruedUsageFromDB(entity *entdb.ChargeStandardInvoiceAccruedUsage) charges.StandardInvoiceAccruedUsage {
-	var ledgerTransaction *charges.LedgerTransactionGroupReference
-	if entity.LedgerTransactionGroupID != nil {
-		ledgerTransaction = &charges.LedgerTransactionGroupReference{
-			TransactionGroupID: *entity.LedgerTransactionGroupID,
-		}
-	}
+	ledgerTransaction := mapLedgerTransactionGroupReferenceFromDB(entity.LedgerTransactionGroupID)

As per coding guidelines, for **/*.go readability and maintainability should be prioritized.

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

In `@openmeter/billing/charges/adapter/mapper.go` around lines 314 - 319, The code
duplicates logic for building a LedgerTransactionGroupReference; replace the
manual construction of ledgerTransaction using the helper
mapLedgerTransactionGroupReferenceFromDB so mapping stays consistent: call
mapLedgerTransactionGroupReferenceFromDB(entity.LedgerTransactionGroupID) (or
the appropriate signature) and assign its result to ledgerTransaction instead of
manually creating charges.LedgerTransactionGroupReference, ensuring the null/nil
handling matches the helper's behavior.
openmeter/billing/charges/chargeflatfee.go (1)

145-151: Consider keeping lifecycle interfaces symmetric for the uncollectible path.

Nice addition overall. One small API-shape nit: FlatFeeHandler exposes OnFlatFeePaymentUncollectible, but FlatFeeService does not expose a corresponding post-payment method. Adding it (or deferring both) would keep the lifecycle contract clearer for callers.

Also applies to: 219-220

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

In `@openmeter/billing/charges/chargeflatfee.go` around lines 145 - 151,
FlatFeeService currently lacks a post-payment-uncollectible lifecycle method to
match FlatFeeHandler's OnFlatFeePaymentUncollectible; add a method e.g.
PostPaymentUncollectible(ctx context.Context, charge FlatFeeCharge,
lineWithHeader billing.StandardLineWithInvoiceHeader) error to the
FlatFeeService interface (and implement/update callers) so the service contract
mirrors FlatFeeHandler's uncollectible path and keeps lifecycle symmetry (also
apply the same addition where the interface is referenced around the other
occurrence noted).
🤖 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/service/flatfee/invoice.go`:
- Around line 33-54: PostInvoiceIssued currently dereferences
lineWithHeader.Line without a nil check which can panic; add a guard at the
start of PostInvoiceIssued to return a clear error if lineWithHeader.Line == nil
before any use (e.g. before calling ToClosedPeriod or accessing ID/Totals), then
proceed to call s.flatFeeHandler.OnFlatFeeStandardInvoiceUsageAccrued and build
accruedUsage as before—this ensures PostInvoiceIssued, the
StandardInvoiceAccruedUsage construction, and uses of
lineWithHeader.Line.ID/Totals are safe.
- Around line 34-57: The CreateStandardInvoiceAccruedUsage call can race and
return a unique-constraint error; modify
s.adapter.CreateStandardInvoiceAccruedUsage (or its underlying DB builder) to be
idempotent by using an upsert/OnConflict strategy or by catching the
unique-constraint error and treating it as success when the existing row matches
the intended accruedUsage; update the adapter implementation referenced by
CreateStandardInvoiceAccruedUsage to either use the builder's OnConflict clause
(upsert) or translate constraint violations into a no-op/success result so
concurrent requests or retries don’t fail after charge.State.AccruedUsage and
flatFeeHandler.OnFlatFeeStandardInvoiceUsageAccrued run.

In `@openmeter/billing/charges/stdinvoice.go`:
- Around line 29-32: The Validate method on
StandardInvoicePaymentSettlementStatus currently returns an outdated error
message; update the error string in
StandardInvoicePaymentSettlementStatus.Validate() to reference the
payment-settlement term (e.g., "invalid payment-settlement status: %s" or
similar) instead of "invalid standard invoice settlement status" so
logs/validation reflect the renamed type; ensure the fmt.Errorf call still
formats the invalid value (o) as before.

---

Duplicate comments:
In `@openmeter/billing/charges/stdinvoice.go`:
- Around line 80-82: The validation currently checks r.Amount.IsNegative() but
logs "amount must be positive", which is misleading; update the error message in
the append call (the fmt.Errorf passed to errs in the block that checks
r.Amount.IsNegative()) to state that the amount must be non-negative (or "must
not be negative") so the message matches the actual check.

---

Nitpick comments:
In `@openmeter/billing/charges/adapter/mapper.go`:
- Around line 314-319: The code duplicates logic for building a
LedgerTransactionGroupReference; replace the manual construction of
ledgerTransaction using the helper mapLedgerTransactionGroupReferenceFromDB so
mapping stays consistent: call
mapLedgerTransactionGroupReferenceFromDB(entity.LedgerTransactionGroupID) (or
the appropriate signature) and assign its result to ledgerTransaction instead of
manually creating charges.LedgerTransactionGroupReference, ensuring the null/nil
handling matches the helper's behavior.

In `@openmeter/billing/charges/chargeflatfee.go`:
- Around line 145-151: FlatFeeService currently lacks a
post-payment-uncollectible lifecycle method to match FlatFeeHandler's
OnFlatFeePaymentUncollectible; add a method e.g. PostPaymentUncollectible(ctx
context.Context, charge FlatFeeCharge, lineWithHeader
billing.StandardLineWithInvoiceHeader) error to the FlatFeeService interface
(and implement/update callers) so the service contract mirrors FlatFeeHandler's
uncollectible path and keeps lifecycle symmetry (also apply the same addition
where the interface is referenced around the other occurrence noted).

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1a32bf4 and 2365b21.

📒 Files selected for processing (4)
  • openmeter/billing/charges/adapter/mapper.go
  • openmeter/billing/charges/chargeflatfee.go
  • openmeter/billing/charges/service/flatfee/invoice.go
  • openmeter/billing/charges/stdinvoice.go

Comment thread openmeter/billing/charges/stdinvoice.go Resolved
@turip
turip force-pushed the feat/flat-fee-charges branch 3 times, most recently from ec4ce78 to 78ff013 Compare March 3, 2026 13:35
@turip
turip enabled auto-merge (squash) March 3, 2026 16:44
@turip
turip force-pushed the feat/flat-fee-charges branch from 41b1b02 to 4cb527b Compare March 4, 2026 08:00
@turip
turip merged commit e54db69 into main Mar 4, 2026
23 checks passed
@turip
turip deleted the feat/flat-fee-charges branch March 4, 2026 10:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants