Repository navigation
refactor: Intent mutable/immutable field split - #4571
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (2)
📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughCharge 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
Flat-fee layered intent
Usage-based layered intent
Credit-purchase layered intent
API conversion and billing callers
Ledger and subscription-sync consumers
Usage-based schema changes
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
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
Co-authored-by: Cursor <[email protected]>
Greptile SummaryThis PR splits charge intent data into immutable identity fields and mutable billing fields. The main changes are:
Confidence Score: 4/5This is close, but the billing-line layer handling should be fixed before merging.
openmeter/billing/charges/usagebased/service/create.go; openmeter/billing/charges/flatfee/service/create.go Important Files Changed
|
There was a problem hiding this comment.
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 | 🟠 MajorEnsure gathering lines use the effective intent
The gathering line construction here relies strictly on
charge.Intent.BaseLayer. However, if a charge has an activeOverrideLayer(e.g., a manual price adjustment), the rating logic usesGetEffectiveIntent()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 winPropagate the charge currency into override normalization.
override.Normalized("")skips the currency calculator, soAmountBeforeProrationon 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 winShared state transitions are now keyed off the wrong service period.
These helpers drive the flat-fee lifecycle, but they now ignore
OverrideLayerentirely. 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 liftThis extend/shrink path stops honoring the active override layer.
Once
OverrideLayerexists, these branches still validate, mutate, and reconcile offBaseLayer. That means a patch updates the base periods, butCalculateAmountAfterProration()still sees the old effective override, while line generation andAllocateAtuse 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
BaseLayerhere (for example viaOverridableIntent.Mutate(...)for writes andGetEffectiveIntent()for reads). The PR objective explicitly moved flat-fee patches tobase/overridetargets, 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 winBuild the gathering line from the effective intent, not
BaseLayer.Right now this path rewrites
BaseLayer.ServicePeriod/InvoiceAtand then reads the emitted line fields fromlineIntent.BaseLayer. IfOverrideLayeris 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 winSeed 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 winCover the other flat-fee period fields here too.
These flat-fee patch checks now read
BaseLayer.ServicePeriod, but they still don’t pin the pairedBaseLayer.FullServicePeriod/BaseLayer.BillingPeriodbehavior. 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 winAssert the exact restored deletion timestamp.
Nice coverage here. One small gap: after clearing the override, the test only checks
DeletedAtis 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 winCould we assert a couple of the shared moved fields here too?
Right now this only checks the type-specific
BaseLayerfields. The refactor inmapPendingInvoiceLineToChargeIntentalso 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 winNice spot to add one override-layer case.
newChargeonly buildsOverridableIntentwithBaseLayer, so these tests still won’t tell us what happens whenOverrideLayerdiverges 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
📒 Files selected for processing (96)
api/v3/handlers/customers/charges/convert.goapi/v3/handlers/customers/credits/convert_test.goopenmeter/billing/charges/charge.goopenmeter/billing/charges/creditpurchase/adapter/charge.goopenmeter/billing/charges/creditpurchase/adapter/mapper.goopenmeter/billing/charges/creditpurchase/charge.goopenmeter/billing/charges/creditpurchase/service/create.goopenmeter/billing/charges/creditpurchase/service/external_test.goopenmeter/billing/charges/creditpurchase/service/promotional_test.goopenmeter/billing/charges/flatfee/adapter.goopenmeter/billing/charges/flatfee/adapter/charge.goopenmeter/billing/charges/flatfee/adapter/detailedline_test.goopenmeter/billing/charges/flatfee/adapter/intentoverride.goopenmeter/billing/charges/flatfee/adapter/intentoverride_test.goopenmeter/billing/charges/flatfee/adapter/mapper.goopenmeter/billing/charges/flatfee/adapter/realizationrun_test.goopenmeter/billing/charges/flatfee/charge.goopenmeter/billing/charges/flatfee/charge_test.goopenmeter/billing/charges/flatfee/service/create.goopenmeter/billing/charges/flatfee/service/creditheninvoice.goopenmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/realizations/creditsonly.goopenmeter/billing/charges/flatfee/service/realizations/credittheninvoice.goopenmeter/billing/charges/flatfee/service/realizations/invoiceaccrued.goopenmeter/billing/charges/flatfee/service/realizations/service.goopenmeter/billing/charges/flatfee/service/statemachine.goopenmeter/billing/charges/meta/charge.goopenmeter/billing/charges/meta/intent.goopenmeter/billing/charges/meta/patch.goopenmeter/billing/charges/meta/patchextend.goopenmeter/billing/charges/meta/patchextend_test.goopenmeter/billing/charges/meta/patchshrink.goopenmeter/billing/charges/meta/patchshrink_test.goopenmeter/billing/charges/meta/timestamps.goopenmeter/billing/charges/models/chargemeta/mixin.goopenmeter/billing/charges/service/base_test.goopenmeter/billing/charges/service/create.goopenmeter/billing/charges/service/creditpurchase_test.goopenmeter/billing/charges/service/featureid_test.goopenmeter/billing/charges/service/handlers_test.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/charges/service/lineage_test.goopenmeter/billing/charges/service/pendinglines.goopenmeter/billing/charges/service/pendinglines_test.goopenmeter/billing/charges/service/taxcode_test.goopenmeter/billing/charges/service/truncation_test.goopenmeter/billing/charges/testutils/handlers.goopenmeter/billing/charges/usagebased/adapter/charge.goopenmeter/billing/charges/usagebased/adapter/detailedline_test.goopenmeter/billing/charges/usagebased/adapter/intentoverride.goopenmeter/billing/charges/usagebased/adapter/intentoverride_test.goopenmeter/billing/charges/usagebased/adapter/mapper.goopenmeter/billing/charges/usagebased/charge.goopenmeter/billing/charges/usagebased/service.goopenmeter/billing/charges/usagebased/service/create.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditheninvoice_test.goopenmeter/billing/charges/usagebased/service/creditsonly.goopenmeter/billing/charges/usagebased/service/currenttotals.goopenmeter/billing/charges/usagebased/service/get.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/charges/usagebased/service/rating/details.goopenmeter/billing/charges/usagebased/service/rating/quantitysnapshot.goopenmeter/billing/charges/usagebased/service/rating/service_test.goopenmeter/billing/charges/usagebased/service/rating/subtract/subtract_test.goopenmeter/billing/charges/usagebased/service/rating/testutils/testutils.goopenmeter/billing/charges/usagebased/service/rating/totals.goopenmeter/billing/charges/usagebased/service/run/create.goopenmeter/billing/charges/usagebased/service/run/credits.goopenmeter/billing/charges/usagebased/service/run/payment_test.goopenmeter/billing/charges/usagebased/service/statemachine.goopenmeter/billing/creditgrant/service/service.goopenmeter/billing/worker/subscriptionsync/service/base_test.goopenmeter/billing/worker/subscriptionsync/service/creditsonly_test.goopenmeter/billing/worker/subscriptionsync/service/persistedstate/item.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.goopenmeter/ledger/chargeadapter/creditpurchase_test.goopenmeter/ledger/chargeadapter/flatfee.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/usagebased.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/customerbalance/expired_loader_test.goopenmeter/ledger/customerbalance/service.goopenmeter/ledger/customerbalance/service_test.goopenmeter/ledger/customerbalance/testenv_test.goopenmeter/ledger/customerbalance/transactions.goopenmeter/ledger/customerbalance/transactions_test.gotest/app/stripe/invoice_credits_test.gotest/credits/base.gotest/credits/credit_then_invoice_test.gotest/credits/sanity_test.go
💤 Files with no reviewable changes (1)
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go
Summary
This refactors charge intent types so the domain model distinguishes immutable charge identity from mutable billing intent fields.
The shared
charges/meta.Intentnow 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 incharges/meta.IntentMutableFields: name, description, metadata, service/full/billing periods, and tax config.Type Naming
The charge-type intent names now follow this contract:
flatfee.Intentusagebased.Intentcreditpurchase.Intentflatfee.OverridableIntentBaseLayerplus optionalOverrideLayerusagebased.OverridableIntentBaseLayerplus optionalOverrideLayerIntentMutableFieldsThis removes the old
IntentOverridenaming from flat-fee and usage-based charges. Overrides are represented as the optionalOverrideLayerof 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(baseoroverride). 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