Skip to content

refactor: Intent mutable/immutable field split - #4571

Merged
turip merged 6 commits into
mainfrom
turip/creditpurchase-no-baselayer
Jun 25, 2026
Merged

turip merged 6 commits into
mainfrom
turip/creditpurchase-no-baselayer

Conversation

@turip

@turip turip commented Jun 25, 2026 •

Copy link
Copy Markdown
Member

Summary

This refactors charge intent types so the domain model distinguishes immutable charge identity from mutable billing intent fields.

The shared charges/meta.Intent now carries stable charge identity and ownership fields such as customer, currency, managed-by, subscription reference, annotations, and unique reference ID. The mutable line-facing fields now live in charges/meta.IntentMutableFields: name, description, metadata, service/full/billing periods, and tax config.

Type Naming

The charge-type intent names now follow this contract:

Type Meaning
flatfee.Intent create/effective flat-fee intent payload
usagebased.Intent create/effective usage-based intent payload
creditpurchase.Intent credit-purchase intent payload with its mutable fields inline
flatfee.OverridableIntent persisted flat-fee intent with BaseLayer plus optional OverrideLayer
usagebased.OverridableIntent persisted usage-based intent with BaseLayer plus optional OverrideLayer
IntentMutableFields charge-type mutable fields that can become the base or override layer

This removes the old IntentOverride naming from flat-fee and usage-based charges. Overrides are represented as the optional OverrideLayer of the same mutable-field shape used by the base layer.

Domain Rules

Create paths receive the effective intent shape (flatfee.Intent, usagebased.Intent, creditpurchase.Intent). Persistence paths store layered intent state where the charge type supports overrides.

Flat-fee and usage-based charges can compute an effective intent from the persisted layered form. Code that rates, maps invoice lines, or creates charge-backed billing artifacts should use the effective intent. Code that persists or mutates charge state should work against the layered OverridableIntent.

Credit purchases do not get an override layer in this PR. Their intent is only split enough to share the same immutable/mutable field boundary as the other charge types.

Patch Targeting

Charge patches now carry an explicit ChangeTarget (base or override). Flat-fee and usage-based charge mutation paths use that target to mutate the correct intent layer, and reject override-targeted changes when no override layer exists.

Subscription sync still builds charge intents from target state, but now constructs immutable intent fields and mutable intent fields separately instead of relying on a shared helper that mixed both concerns.

Summary by CodeRabbit

  • New Features
    • Charges now use a clearer base vs. override structure for intent data across flat-fee, usage-based, and credit-purchase flows, improving consistency for updates and deletions.
  • Bug Fixes
    • Fixed multiple cases where service periods, invoice timing, pricing/discounts, feature keys, and tax configuration could be read from the wrong layer.
    • Improved annotation and tax code propagation when creating, updating, and overriding charges.
  • Tests
    • Updated fixtures and assertions to match the revised charge intent structure and layer-specific field locations.

@coderabbitai

coderabbitai Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f548ee1c-e162-44a7-9f93-9cf7381b8354

📥 Commits

Reviewing files that changed from the base of the PR and between 09d9317 and 230822d.

⛔ Files ignored due to path filters (2)
  • openmeter/ent/db/chargeusagebased_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_update.go is excluded by !**/ent/db/**
📒 Files selected for processing (2)
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/ent/schema/chargesusagebased.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/billing/charges/usagebased/adapter/charge.go

📝 Walkthrough

Walkthrough

Charge intent data is split into immutable base fields and mutable nested fields across shared billing models, flat-fee and usage-based charge paths, credit-purchase handling, API conversion, and downstream consumers.

Shared intent contracts

Layer / File(s) Summary
Shared intent contracts
openmeter/billing/charges/meta/*, openmeter/billing/charges/models/chargemeta/mixin.go, openmeter/billing/charges/charge.go, openmeter/billing/charges/service/create.go
Shared intent types, patch validation, charge metadata mapping, and generic charge helpers now separate immutable base fields from mutable fields.

Flat-fee layered intent

Layer / File(s) Summary
Flat-fee layered intent
openmeter/billing/charges/flatfee/*
Flat-fee charge models, override persistence, service flows, and tests now read and write BaseLayer fields through OverridableIntent.

Usage-based layered intent

Layer / File(s) Summary
Usage-based layered intent
openmeter/billing/charges/usagebased/*
Usage-based charge models, override persistence, service flows, rating, and tests now read and write BaseLayer fields through OverridableIntent.

Credit-purchase layered intent

Layer / File(s) Summary
Credit-purchase layered intent
openmeter/billing/charges/creditpurchase/*, openmeter/billing/creditgrant/service/service.go
Credit-purchase charge intents now split base identity fields from mutable fields across adapters, creation, and tests.

API conversion and billing callers

Layer / File(s) Summary
API conversion and billing callers
api/v3/handlers/customers/charges/convert.go, api/v3/handlers/customers/credits/convert_test.go, test/app/stripe/invoice_credits_test.go, openmeter/billing/charges/service/pendinglines.go, openmeter/billing/charges/service/*_test.go, openmeter/billing/charges/testutils/handlers.go, test/credits/*
Customer charge conversion, pending-line mapping, shared billing service callers, and Stripe credit fixtures now map the split intent layout in both directions.

Ledger and subscription-sync consumers

Layer / File(s) Summary
Ledger and subscription-sync consumers
openmeter/ledger/*, openmeter/billing/worker/subscriptionsync/service/*, openmeter/billing/worker/subscriptionsync/service/reconciler/*
Ledger, customer balance, and subscription-sync consumers now source timing, tax, feature, and balance data from BaseLayer and update layered intent fixtures.

Usage-based schema changes

Layer / File(s) Summary
Usage-based schema changes
openmeter/ent/schema/chargesusagebased.go
Usage-based schema fields no longer mark feature key and price immutable.

Sequence Diagram(s)

sequenceDiagram
  participant APIHandlers
  participant ChargeAdapters
  participant ChargeModels
  participant BillingServices
  participant LedgerConsumers

  APIHandlers->>ChargeAdapters: map request fields into BaseLayer and IntentMutableFields
  ChargeAdapters->>ChargeModels: build OverridableIntent and validate layered intent
  BillingServices->>ChargeModels: read BaseLayer for periods, price, tax, and feature data
  BillingServices->>LedgerConsumers: pass layered charge data into balance and booking flows
  LedgerConsumers->>ChargeModels: read BaseLayer for tax, feature, and timing values
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main refactor: splitting intent data into mutable and immutable fields.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch turip/creditpurchase-no-baselayer

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.

@turip turip changed the title Refactor charge intent mutable fields refactor: Intent mutable/immutable field split Jun 25, 2026
@turip
turip marked this pull request as ready for review June 25, 2026 13:58
@turip
turip requested a review from a team as a code owner June 25, 2026 13:58
@greptile-apps

greptile-apps Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR splits charge intent data into immutable identity fields and mutable billing fields. The main changes are:

  • Shared charge intent metadata moved into stable identity fields.
  • Flat-fee and usage-based charges now store base and override mutable layers.
  • Credit-purchase intents now share the same mutable-field boundary.
  • Charge patches now target either the base layer or override layer.

Confidence Score: 4/5

This is close, but the billing-line layer handling should be fixed before merging.

  • Overridden usage-based charges can create gathering lines from stale base values.
  • Overridden flat-fee charges can create or update billing lines from stale base values.
  • Credit-purchase split and override persistence changes did not show another blocking issue in the reviewed code.

openmeter/billing/charges/usagebased/service/create.go; openmeter/billing/charges/flatfee/service/create.go

Important Files Changed

Filename Overview
openmeter/billing/charges/usagebased/service/create.go Usage-based gathering line creation now uses the layered intent shape, but still reads billing-line fields from the base layer.
openmeter/billing/charges/flatfee/service/create.go Flat-fee gathering line creation now uses layered intents, but still reads billing-line fields from the base layer.
openmeter/billing/charges/creditpurchase/charge.go Credit-purchase intent validation and normalization were updated for the immutable and mutable field split.
openmeter/billing/charges/flatfee/adapter/intentoverride.go Flat-fee override persistence was moved to the new mutable-field layer shape.
openmeter/billing/charges/usagebased/adapter/intentoverride.go Usage-based override persistence was moved to the new mutable-field layer shape.

Comments Outside Diff (1)

  1. openmeter/billing/charges/usagebased/service/create.go, line 90 (link)

    P1 Line Uses Base Layer

    When a usage-based charge has an OverrideLayer, this builder still reads every line-facing mutable field from BaseLayer: name, metadata, price, feature key, discounts, billing period, and tax config. The create path and extend/shrink paths call this helper to create or update gathering lines, so an overridden charge can rate with the effective intent while the invoice artifact is created from the stale base intent. Build the line from the effective intent, while keeping the explicit servicePeriod and invoiceAt arguments for split-period calls.

    Context Used: AGENTS.md (source)

    Fix in Claude Code

Fix All in Claude Code

Reviews (3): Last reviewed commit: "fix(charges): persist usage-based intent..." | Re-trigger Greptile

@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

Caution

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

⚠️ Outside diff range comments (7)
openmeter/billing/charges/usagebased/service/create.go (1)

85-147: 🎯 Functional Correctness | 🟠 Major

Ensure gathering lines use the effective intent

The gathering line construction here relies strictly on charge.Intent.BaseLayer. However, if a charge has an active OverrideLayer (e.g., a manual price adjustment), the rating logic uses GetEffectiveIntent() which applies that override.

If you extend or shrink a charge with an active override, the rating calculation will use the new overridden values, but the resulting invoice line will be built from the stale base values. This leads to mismatched amounts.

Please switch the gathering line construction to use charge.Intent.GetEffectiveIntent() to ensure the invoice line accurately reflects the final effective intent used for rating.

Relevant snippet
func gatheringLineFromUsageBasedChargeForPeriod(charge usagebased.Charge, servicePeriod timeutil.ClosedPeriod, invoiceAt time.Time) (usagebased.ChargeWithGatheringLine, error) {
	intent := charge.Intent
	
	// Change intent to use the effective resolved state
	effectiveIntent := intent.GetEffectiveIntent()
	
	// Then use effectiveIntent.BaseLayer or fields directly from effectiveIntent
	// ...
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/service/create.go` around lines 85 -
147, The gathering line builder in gatheringLineFromUsageBasedChargeForPeriod is
using charge.Intent.BaseLayer directly, so it can miss active OverrideLayer
values and produce invoice lines that differ from rating. Update this flow to
resolve the intent via charge.Intent.GetEffectiveIntent() and then build the
billing.GatheringLine from that effective intent, including base fields,
metadata, annotations, discounts, tax config, and subscription data so the
invoice line matches the rated charge.
openmeter/billing/charges/flatfee/adapter/intentoverride.go (1)

123-140: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Propagate the charge currency into override normalization.

override.Normalized("") skips the currency calculator, so AmountBeforeProration on create/update overrides no longer gets rounded to the charge’s real currency precision. That lets override rows persist money values that the base-layer path would normalize first.

Suggested fix
-func (a *adapter) createIntentOverride(ctx context.Context, chargeID meta.ChargeID, override *flatfee.IntentMutableFields) (*flatfee.IntentMutableFields, error) {
+func (a *adapter) createIntentOverride(ctx context.Context, chargeID meta.ChargeID, currency currencyx.Code, override *flatfee.IntentMutableFields) (*flatfee.IntentMutableFields, error) {
 	if err := chargeID.Validate(); err != nil {
 		return nil, fmt.Errorf("charge id: %w", err)
 	}

-	normalized := override.Normalized("")
+	normalized := override.Normalized(currency)
-		intentOverride, err := tx.createIntentOverride(ctx, charge.GetChargeID(), charge.Intent.OverrideLayer)
+		intentOverride, err := tx.createIntentOverride(ctx, charge.GetChargeID(), charge.Intent.Currency, charge.Intent.OverrideLayer)
-func (a *adapter) updateIntentOverride(ctx context.Context, chargeID meta.ChargeID, override *flatfee.IntentMutableFields) (*entdb.ChargeFlatFeeOverride, error) {
+func (a *adapter) updateIntentOverride(ctx context.Context, chargeID meta.ChargeID, currency currencyx.Code, override *flatfee.IntentMutableFields) (*entdb.ChargeFlatFeeOverride, error) {
 	if err := chargeID.Validate(); err != nil {
 		return nil, fmt.Errorf("charge id: %w", err)
 	}

-	normalized := override.Normalized("")
+	normalized := override.Normalized(currency)
-			intentOverride, err := tx.updateIntentOverride(ctx, charge.GetChargeID(), charge.Intent.OverrideLayer)
+			intentOverride, err := tx.updateIntentOverride(ctx, charge.GetChargeID(), charge.Intent.Currency, charge.Intent.OverrideLayer)

Also applies to: 168-184

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/flatfee/adapter/intentoverride.go` around lines 123
- 140, The override normalization in createIntentOverride (and the matching
update path) is using an empty currency, which skips currency-aware rounding and
can persist unnormalized AmountBeforeProration values. Update the normalization
call on flatfee.IntentMutableFields to pass the charge’s actual currency from
chargeID/charge data instead of "", and make the same change in the
corresponding update flow so both createIntentOverride and its sibling path
normalize with the real precision.
openmeter/billing/charges/flatfee/service/statemachine.go (1)

96-119: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Shared state transitions are now keyed off the wrong service period.

These helpers drive the flat-fee lifecycle, but they now ignore OverrideLayer entirely. For an overridden charge, the machine can advance into or out of states using the base service window instead of the effective one.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/flatfee/service/statemachine.go` around lines 96 -
119, The flat-fee state helpers in stateMachine are using
Charge.Intent.BaseLayer.ServicePeriod instead of the effective service period,
so overridden charges follow the wrong window. Update IsInsideServicePeriod,
AdvanceAfterServicePeriodFrom, and AdvanceAfterServicePeriodTo to read from the
effective layer/service period (including OverrideLayer when present), and keep
the related predicates like IsInsideServicePeriodAndZeroAmount and
IsInsideServicePeriodAndNonZeroAmount aligned through IsInsideServicePeriod().
openmeter/billing/charges/flatfee/service/creditheninvoice.go (1)

183-196: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

This extend/shrink path stops honoring the active override layer.

Once OverrideLayer exists, these branches still validate, mutate, and reconcile off BaseLayer. That means a patch updates the base periods, but CalculateAmountAfterProration() still sees the old effective override, while line generation and AllocateAt use the patched base values. You end up with charge state and invoice artifacts describing different intents.

Please drive this through the targeted/effective layer instead of hard-coding BaseLayer here (for example via OverridableIntent.Mutate(...) for writes and GetEffectiveIntent() for reads). The PR objective explicitly moved flat-fee patches to base/override targets, so this path needs that same targeting. As per path instructions, “readability and maintainability” should stay a priority in Go code.

Also applies to: 212-225, 358-362, 442-446

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/flatfee/service/creditheninvoice.go` around lines
183 - 196, The extend/shrink flow in CreditThenInvoiceStateMachine still
hard-codes BaseLayer, so it ignores OverrideLayer and can produce mismatched
charge vs invoice state. Update the validation/mutation/read paths in
ShrinkCharge, applyPeriodPatch, and the related reconciliation logic to operate
on the targeted/effective intent instead of BaseLayer, using
OverridableIntent.Mutate(...) for writes and GetEffectiveIntent() for reads
where appropriate. Make sure the same targeting is used consistently across the
extend/shrink branches so CalculateAmountAfterProration, line generation, and
AllocateAt all see the same effective periods.

Source: Path instructions

openmeter/billing/charges/flatfee/service/create.go (1)

136-205: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Build the gathering line from the effective intent, not BaseLayer.

Right now this path rewrites BaseLayer.ServicePeriod / InvoiceAt and then reads the emitted line fields from lineIntent.BaseLayer. If OverrideLayer is present, proration and the resulting line can still use stale override values, while name/payment-term/tax/discount fields ignore the override entirely. That breaks the layered-intent contract this refactor is introducing.

Suggested fix
 	flatFee := input.Charge
-	lineIntent := flatFee.Intent
-	lineIntent.BaseLayer.ServicePeriod = input.ServicePeriod
-	lineIntent.BaseLayer.InvoiceAt = input.InvoiceAt
-	lineIntent = lineIntent.Normalized()
-	lineIntentFields := lineIntent.BaseLayer
-
-	if err := lineIntent.Validate(); err != nil {
+	lineIntent := flatFee.Intent.GetEffectiveIntent()
+	lineIntent.ServicePeriod = input.ServicePeriod
+	lineIntent.InvoiceAt = input.InvoiceAt
+	lineIntent = lineIntent.Normalized()
+
+	if err := lineIntent.Validate(); err != nil {
 		return billing.GatheringLine{}, fmt.Errorf("validating line intent: %w", err)
 	}
 
 	amountAfterProration, err := lineIntent.CalculateAmountAfterProration()
 	if err != nil {
@@
-	clonedAnnotations, err := flatFee.Intent.Annotations.Clone()
+	clonedAnnotations, err := lineIntent.Annotations.Clone()
 	if err != nil {
 		return billing.GatheringLine{}, fmt.Errorf("cloning annotations: %w", err)
 	}
@@
-				Name:        lineIntentFields.Name,
-				Description: lineIntentFields.Description,
+				Name:        lineIntent.Name,
+				Description: lineIntent.Description,
 			}),
 
-			Metadata:    lineIntentFields.Metadata.Clone(),
+			Metadata:    lineIntent.Metadata.Clone(),
 			Annotations: clonedAnnotations,
 			ManagedBy:   lineIntent.ManagedBy,
@@
 						Amount:      amountAfterProration,
-						PaymentTerm: lineIntentFields.PaymentTerm,
+						PaymentTerm: lineIntent.PaymentTerm,
 					},
 				),
 			),
-			FeatureKey: lineIntentFields.FeatureKey,
+			FeatureKey: lineIntent.FeatureKey,
 
 			Currency:      lineIntent.Currency,
-			ServicePeriod: lineIntentFields.ServicePeriod,
-			InvoiceAt:     lineIntentFields.InvoiceAt,
+			ServicePeriod: lineIntent.ServicePeriod,
+			InvoiceAt:     lineIntent.InvoiceAt,
 
-			TaxConfig: lo.ToPtr(lineIntentFields.TaxConfig.ToTaxConfig()),
+			TaxConfig: lo.ToPtr(lineIntent.TaxConfig.ToTaxConfig()),
@@
-	if lineIntentFields.PercentageDiscounts != nil {
+	if lineIntent.PercentageDiscounts != nil {
 		gatheringLine.RateCardDiscounts = billing.Discounts{
 			Percentage: &billing.PercentageDiscount{
-				PercentageDiscount: *lineIntentFields.PercentageDiscounts,
+				PercentageDiscount: *lineIntent.PercentageDiscounts,
 			},
 		}
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/flatfee/service/create.go` around lines 136 - 205,
The gathering line is being built from lineIntent.BaseLayer instead of the fully
resolved intent, so OverrideLayer values can be ignored or stale when proration
and line fields are assembled. Update create.go to use the effective/normalized
intent returned from lineIntent.Normalized() for all downstream field reads
(including service period, invoice time, name, payment term, tax config,
discounts, and metadata) and keep the proration calculation and
SubscriptionReference aligned with that same resolved intent.
openmeter/billing/charges/flatfee/service/realizations/service.go (1)

73-79: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Seed lineage from the effective feature key.

Line 78 always uses BaseLayer.FeatureKey, so an override-targeted feature change will still create lineage under the old feature. That breaks downstream feature-scoped lineage and credit lookups. Please use the effective mutable fields here instead of hard-coding the base layer.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/flatfee/service/realizations/service.go` around
lines 73 - 79, The lineage seeding in the flat fee realizations flow is using
the base layer feature key instead of the effective mutable feature value.
Update the CreateInitialLineages call in service.go to derive Features from the
effective charge fields used for overrides, not
charge.Intent.BaseLayer.FeatureKey, so lineage and credit lookup are created
under the correct feature. Use the existing realization setup in the same method
as the reference point and keep the empty-feature handling behavior intact.
test/credits/credit_then_invoice_test.go (1)

2841-2867: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Cover the other flat-fee period fields here too.

These flat-fee patch checks now read BaseLayer.ServicePeriod, but they still don’t pin the paired BaseLayer.FullServicePeriod / BaseLayer.BillingPeriod behavior. That leaves a partial update of the moved mutable fields invisible to these tests, especially in the shrink/extend paths where those windows can intentionally differ. As per path instructions, **/*_test.go: "Make sure the tests are comprehensive and cover the changes."

Also applies to: 3347-3402

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/credits/credit_then_invoice_test.go` around lines 2841 - 2867, The
flat-fee patch assertions in the relevant test cases only verify
Intent.BaseLayer.ServicePeriod, so update the checks around
charge.Intent.BaseLayer in these flat-fee shrink/extend scenarios to also assert
the paired FullServicePeriod and BillingPeriod fields. Use the existing helpers
and objects in the test (such as RequireFlatFeeChargeStatus,
mustSingleActiveGatheringLineForCharge, and the charge.Intent.BaseLayer fields)
to pin the expected values for both the shrunk and extended paths so partial
updates to the mutable period fields are caught.

Source: Path instructions

🧹 Nitpick comments (3)
openmeter/billing/charges/usagebased/adapter/intentoverride_test.go (1)

111-207: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the exact restored deletion timestamp.

Nice coverage here. One small gap: after clearing the override, the test only checks DeletedAt is non-nil, so a wrong restored timestamp would still pass. Since the setup uses a known base-layer deletion time, asserting equality would lock down the new base/override propagation contract.

Suggested test tightening
-	charge.Intent.BaseLayer.IntentDeletedAt = lo.ToPtr(time.Date(2026, 1, 5, 0, 0, 0, 0, time.UTC))
+	baseDeletedAt := time.Date(2026, 1, 5, 0, 0, 0, 0, time.UTC)
+	charge.Intent.BaseLayer.IntentDeletedAt = lo.ToPtr(baseDeletedAt)
...
-	s.NotNil(updated.Intent.BaseLayer.IntentDeletedAt)
+	s.Require().NotNil(updated.Intent.BaseLayer.IntentDeletedAt)
+	s.Equal(baseDeletedAt, *updated.Intent.BaseLayer.IntentDeletedAt)
...
-	s.NotNil(fetchedBeforeOverrideCreate.DeletedAt)
+	s.Require().NotNil(fetchedBeforeOverrideCreate.DeletedAt)
+	s.Equal(baseDeletedAt, *fetchedBeforeOverrideCreate.DeletedAt)
...
-	s.NotNil(cleared.DeletedAt)
+	s.Require().NotNil(cleared.DeletedAt)
+	s.Equal(baseDeletedAt, *cleared.DeletedAt)
...
-	s.NotNil(fetchedAfterClear.DeletedAt)
+	s.Require().NotNil(fetchedAfterClear.DeletedAt)
+	s.Equal(baseDeletedAt, *fetchedAfterClear.DeletedAt)

As per path instructions, “Make sure the tests are comprehensive and cover the changes.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/adapter/intentoverride_test.go` around
lines 111 - 207, The test in intentoverride_test should verify the restored
deletion timestamp exactly, not just that DeletedAt is set. After
DeleteChargeOverride and the final GetByID call, assert that the returned
DeletedAt matches the known base-layer timestamp used earlier in the test, using
the same charge lifecycle methods (CreateChargeOverride, UpdateCharge,
DeleteChargeOverride, GetByID) to locate the spot.

Source: Path instructions

openmeter/billing/charges/service/pendinglines_test.go (1)

117-133: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Could we assert a couple of the shared moved fields here too?

Right now this only checks the type-specific BaseLayer fields. The refactor in mapPendingInvoiceLineToChargeIntent also rebuilds shared intent data like service periods, tax config, metadata, and annotations, so a bad wiring there would still pass this test. As per path instructions, **/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/service/pendinglines_test.go` around lines 117 -
133, The pending lines test only verifies type-specific BaseLayer data, so
extend the assertions in pendinglines_test.go around the existing
usageBasedCharge and flatFeeCharge checks to also cover shared intent fields
rebuilt by mapPendingInvoiceLineToChargeIntent, such as service periods, tax
config, metadata, and annotations. Use the existing charge lookups and intent
objects in the test to assert a few representative moved fields for both charges
so a bad shared-field mapping cannot slip through.

Source: Path instructions

openmeter/ledger/chargeadapter/usagebased_test.go (1)

615-633: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Nice spot to add one override-layer case.

newCharge only builds OverridableIntent with BaseLayer, so these tests still won’t tell us what happens when OverrideLayer diverges on tax / feature / service-period fields. One focused accrual case there would make the new layering contract much harder to regress. As per path instructions, **/*_test.go: "Make sure the tests are comprehensive and cover the changes."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/ledger/chargeadapter/usagebased_test.go` around lines 615 - 633,
Add one focused accrual test for the OverrideLayer path in
newCharge/OverridableIntent, since the current case only exercises BaseLayer.
Extend the test setup to populate OverrideLayer with divergent tax, feature key,
and service-period values, then assert the accrual behavior reflects those
overrides instead of the base fields. Use the existing
chargeusagebased.OverridableIntent and newCharge test helpers to keep the case
close to the current coverage.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@openmeter/billing/charges/creditpurchase/charge.go`:
- Around line 193-195: The CreditPurchase validation path currently returns
early for unsupported EffectiveAt, which bypasses any previously collected
errors and skips the standard aggregated validation contract. Update the
Validate method in the credit purchase charge logic to keep EffectiveAt in the
same error collection flow as the other checks, append the unsupported-field
error to the existing errs slice, and return it through
models.NewNillableGenericValidationError(errors.Join(errs...)) instead of
returning errors.New directly.

In `@openmeter/billing/charges/flatfee/adapter/charge.go`:
- Around line 66-71: The flat-fee adapter is still passing `AdvanceAfter` into
`chargemeta.UpdateInput`, which allows normal updates to change or clear
scheduling state. In `charge.go`, update the `chargemeta.Update(...)` call in
the flat-fee update path so `AdvanceAfter` is no longer populated for this
adapter, keeping only the supported fields like `ManagedResource`,
`IntentMutableFields`, `Annotations`, and `Status`.

In `@openmeter/billing/charges/flatfee/service/creditsonly.go`:
- Around line 72-76: The credits-only state machine is still using
Charge.Intent.BaseLayer fields instead of the effective intent, so
override-backed charges are scheduled and booked against the wrong billing data.
Update the CreditsOnlyStateMachine paths that read InvoiceAt, ServicePeriod, and
PaymentTerm to use the effective intent/accessor for the charge rather than
BaseLayer, including the scheduling check in AdvanceAfterInvoiceAt and the
run/correction-credits logic referenced in the other affected branches. Keep the
behavior consistent with any overrides so all date/period/term decisions come
from the resolved intent.

In `@openmeter/billing/charges/flatfee/service/realizations/creditsonly.go`:
- Around line 56-60: AllocateCreditsOnly is using Intent.BaseLayer values when
building OnAllocateCreditsInput, which ignores override-specific billing fields.
Update the input construction in creditsonly.go to source ServicePeriod and
PaymentTerm from the effective charge/intent values used by the override path,
not always from intentFields.BaseLayer, so UsageBookedAt and the booked period
are derived from the correct override-backed dates.

In `@openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go`:
- Around line 114-118: The `BookedAt` calculation in `credittheninvoice.go` is
still using `charge.Intent.BaseLayer.PaymentTerm` instead of the effective
runtime payment term. Update the `handlerInput` setup to resolve the mutable
`OverridableIntent` value first (override when present, base otherwise) and pass
that effective term into `flatfee.UsageBookedAt`. Also apply the same
effective-term lookup to the other `UsageBookedAt(...)` call sites introduced in
this refactor so they all use the charge’s actual billing intent.

In `@openmeter/billing/charges/usagebased/adapter/charge.go`:
- Around line 36-45: Persist the base-layer FeatureKey and Price in the
ChargeUsageBased update path, since base-targeted edits are currently lost on
readback. Update the charge update flow in ChargeUsageBased UpdateOneID to write
Intent.BaseLayer.FeatureKey and Intent.BaseLayer.Price alongside the other
base-layer fields, and make sure the read paths in MapChargeBaseFromDB and the
create flow continue to round-trip those values from the same source
consistently.

---

Outside diff comments:
In `@openmeter/billing/charges/flatfee/adapter/intentoverride.go`:
- Around line 123-140: The override normalization in createIntentOverride (and
the matching update path) is using an empty currency, which skips currency-aware
rounding and can persist unnormalized AmountBeforeProration values. Update the
normalization call on flatfee.IntentMutableFields to pass the charge’s actual
currency from chargeID/charge data instead of "", and make the same change in
the corresponding update flow so both createIntentOverride and its sibling path
normalize with the real precision.

In `@openmeter/billing/charges/flatfee/service/create.go`:
- Around line 136-205: The gathering line is being built from
lineIntent.BaseLayer instead of the fully resolved intent, so OverrideLayer
values can be ignored or stale when proration and line fields are assembled.
Update create.go to use the effective/normalized intent returned from
lineIntent.Normalized() for all downstream field reads (including service
period, invoice time, name, payment term, tax config, discounts, and metadata)
and keep the proration calculation and SubscriptionReference aligned with that
same resolved intent.

In `@openmeter/billing/charges/flatfee/service/creditheninvoice.go`:
- Around line 183-196: The extend/shrink flow in CreditThenInvoiceStateMachine
still hard-codes BaseLayer, so it ignores OverrideLayer and can produce
mismatched charge vs invoice state. Update the validation/mutation/read paths in
ShrinkCharge, applyPeriodPatch, and the related reconciliation logic to operate
on the targeted/effective intent instead of BaseLayer, using
OverridableIntent.Mutate(...) for writes and GetEffectiveIntent() for reads
where appropriate. Make sure the same targeting is used consistently across the
extend/shrink branches so CalculateAmountAfterProration, line generation, and
AllocateAt all see the same effective periods.

In `@openmeter/billing/charges/flatfee/service/realizations/service.go`:
- Around line 73-79: The lineage seeding in the flat fee realizations flow is
using the base layer feature key instead of the effective mutable feature value.
Update the CreateInitialLineages call in service.go to derive Features from the
effective charge fields used for overrides, not
charge.Intent.BaseLayer.FeatureKey, so lineage and credit lookup are created
under the correct feature. Use the existing realization setup in the same method
as the reference point and keep the empty-feature handling behavior intact.

In `@openmeter/billing/charges/flatfee/service/statemachine.go`:
- Around line 96-119: The flat-fee state helpers in stateMachine are using
Charge.Intent.BaseLayer.ServicePeriod instead of the effective service period,
so overridden charges follow the wrong window. Update IsInsideServicePeriod,
AdvanceAfterServicePeriodFrom, and AdvanceAfterServicePeriodTo to read from the
effective layer/service period (including OverrideLayer when present), and keep
the related predicates like IsInsideServicePeriodAndZeroAmount and
IsInsideServicePeriodAndNonZeroAmount aligned through IsInsideServicePeriod().

In `@openmeter/billing/charges/usagebased/service/create.go`:
- Around line 85-147: The gathering line builder in
gatheringLineFromUsageBasedChargeForPeriod is using charge.Intent.BaseLayer
directly, so it can miss active OverrideLayer values and produce invoice lines
that differ from rating. Update this flow to resolve the intent via
charge.Intent.GetEffectiveIntent() and then build the billing.GatheringLine from
that effective intent, including base fields, metadata, annotations, discounts,
tax config, and subscription data so the invoice line matches the rated charge.

In `@test/credits/credit_then_invoice_test.go`:
- Around line 2841-2867: The flat-fee patch assertions in the relevant test
cases only verify Intent.BaseLayer.ServicePeriod, so update the checks around
charge.Intent.BaseLayer in these flat-fee shrink/extend scenarios to also assert
the paired FullServicePeriod and BillingPeriod fields. Use the existing helpers
and objects in the test (such as RequireFlatFeeChargeStatus,
mustSingleActiveGatheringLineForCharge, and the charge.Intent.BaseLayer fields)
to pin the expected values for both the shrunk and extended paths so partial
updates to the mutable period fields are caught.

---

Nitpick comments:
In `@openmeter/billing/charges/service/pendinglines_test.go`:
- Around line 117-133: The pending lines test only verifies type-specific
BaseLayer data, so extend the assertions in pendinglines_test.go around the
existing usageBasedCharge and flatFeeCharge checks to also cover shared intent
fields rebuilt by mapPendingInvoiceLineToChargeIntent, such as service periods,
tax config, metadata, and annotations. Use the existing charge lookups and
intent objects in the test to assert a few representative moved fields for both
charges so a bad shared-field mapping cannot slip through.

In `@openmeter/billing/charges/usagebased/adapter/intentoverride_test.go`:
- Around line 111-207: The test in intentoverride_test should verify the
restored deletion timestamp exactly, not just that DeletedAt is set. After
DeleteChargeOverride and the final GetByID call, assert that the returned
DeletedAt matches the known base-layer timestamp used earlier in the test, using
the same charge lifecycle methods (CreateChargeOverride, UpdateCharge,
DeleteChargeOverride, GetByID) to locate the spot.

In `@openmeter/ledger/chargeadapter/usagebased_test.go`:
- Around line 615-633: Add one focused accrual test for the OverrideLayer path
in newCharge/OverridableIntent, since the current case only exercises BaseLayer.
Extend the test setup to populate OverrideLayer with divergent tax, feature key,
and service-period values, then assert the accrual behavior reflects those
overrides instead of the base fields. Use the existing
chargeusagebased.OverridableIntent and newCharge test helpers to keep the case
close to the current coverage.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b6196a1a-0a17-4fad-84df-6126781be73c

📥 Commits

Reviewing files that changed from the base of the PR and between cdbf530 and 1aca466.

📒 Files selected for processing (96)
  • api/v3/handlers/customers/charges/convert.go
  • api/v3/handlers/customers/credits/convert_test.go
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper.go
  • openmeter/billing/charges/creditpurchase/charge.go
  • openmeter/billing/charges/creditpurchase/service/create.go
  • openmeter/billing/charges/creditpurchase/service/external_test.go
  • openmeter/billing/charges/creditpurchase/service/promotional_test.go
  • openmeter/billing/charges/flatfee/adapter.go
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/flatfee/adapter/detailedline_test.go
  • openmeter/billing/charges/flatfee/adapter/intentoverride.go
  • openmeter/billing/charges/flatfee/adapter/intentoverride_test.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go
  • openmeter/billing/charges/flatfee/adapter/realizationrun_test.go
  • openmeter/billing/charges/flatfee/charge.go
  • openmeter/billing/charges/flatfee/charge_test.go
  • openmeter/billing/charges/flatfee/service/create.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/creditsonly.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/flatfee/service/realizations/creditsonly.go
  • openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go
  • openmeter/billing/charges/flatfee/service/realizations/invoiceaccrued.go
  • openmeter/billing/charges/flatfee/service/realizations/service.go
  • openmeter/billing/charges/flatfee/service/statemachine.go
  • openmeter/billing/charges/meta/charge.go
  • openmeter/billing/charges/meta/intent.go
  • openmeter/billing/charges/meta/patch.go
  • openmeter/billing/charges/meta/patchextend.go
  • openmeter/billing/charges/meta/patchextend_test.go
  • openmeter/billing/charges/meta/patchshrink.go
  • openmeter/billing/charges/meta/patchshrink_test.go
  • openmeter/billing/charges/meta/timestamps.go
  • openmeter/billing/charges/models/chargemeta/mixin.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/creditpurchase_test.go
  • openmeter/billing/charges/service/featureid_test.go
  • openmeter/billing/charges/service/handlers_test.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/service/lineage_test.go
  • openmeter/billing/charges/service/pendinglines.go
  • openmeter/billing/charges/service/pendinglines_test.go
  • openmeter/billing/charges/service/taxcode_test.go
  • openmeter/billing/charges/service/truncation_test.go
  • openmeter/billing/charges/testutils/handlers.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/detailedline_test.go
  • openmeter/billing/charges/usagebased/adapter/intentoverride.go
  • openmeter/billing/charges/usagebased/adapter/intentoverride_test.go
  • openmeter/billing/charges/usagebased/adapter/mapper.go
  • openmeter/billing/charges/usagebased/charge.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/create.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice_test.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/currenttotals.go
  • openmeter/billing/charges/usagebased/service/get.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/service/rating/details.go
  • openmeter/billing/charges/usagebased/service/rating/quantitysnapshot.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/charges/usagebased/service/rating/subtract/subtract_test.go
  • openmeter/billing/charges/usagebased/service/rating/testutils/testutils.go
  • openmeter/billing/charges/usagebased/service/rating/totals.go
  • openmeter/billing/charges/usagebased/service/run/create.go
  • openmeter/billing/charges/usagebased/service/run/credits.go
  • openmeter/billing/charges/usagebased/service/run/payment_test.go
  • openmeter/billing/charges/usagebased/service/statemachine.go
  • openmeter/billing/creditgrant/service/service.go
  • openmeter/billing/worker/subscriptionsync/service/base_test.go
  • openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go
  • openmeter/billing/worker/subscriptionsync/service/persistedstate/item.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
  • openmeter/ledger/chargeadapter/flatfee.go
  • openmeter/ledger/chargeadapter/flatfee_test.go
  • openmeter/ledger/chargeadapter/usagebased.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
  • openmeter/ledger/customerbalance/expired_loader_test.go
  • openmeter/ledger/customerbalance/service.go
  • openmeter/ledger/customerbalance/service_test.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • openmeter/ledger/customerbalance/transactions.go
  • openmeter/ledger/customerbalance/transactions_test.go
  • test/app/stripe/invoice_credits_test.go
  • test/credits/base.go
  • test/credits/credit_then_invoice_test.go
  • test/credits/sanity_test.go
💤 Files with no reviewable changes (1)
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go

@turip turip added release-note/misc Miscellaneous changes area/billing labels Jun 25, 2026
@turip
turip merged commit 18e5c91 into main Jun 25, 2026
26 of 29 checks passed
@turip
turip deleted the turip/creditpurchase-no-baselayer branch June 25, 2026 15:18
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