Repository navigation
feat: persist amount discounts on charge run detailed lines - #4869
Conversation
📝 WalkthroughWalkthroughCharge detailed lines now store signed amount-discount snapshots. The change adds charge-specific models, JSONB persistence, validation, flat-fee and usage-based adapter support, nested base mapping, and rating lifecycle coverage. ChangesDetailed-line discount model
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant BillingRating
participant ChargeDetailedLine
participant FlatFeeAdapter
participant UsageBasedAdapter
participant ChargeRunDatabase
BillingRating->>ChargeDetailedLine: Map amount discount snapshots
ChargeDetailedLine->>FlatFeeAdapter: Provide validated flat-fee line
ChargeDetailedLine->>UsageBasedAdapter: Provide validated usage-based line
FlatFeeAdapter->>ChargeRunDatabase: Upsert amount_discounts
UsageBasedAdapter->>ChargeRunDatabase: Upsert amount_discounts
ChargeRunDatabase-->>FlatFeeAdapter: Load persisted discounts
ChargeRunDatabase-->>UsageBasedAdapter: Load persisted discounts
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 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 |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
pkg/framework/entutils/valuescanner_test.go (1)
17-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winInline the single-use test wrapper.
newTestStringArrayOptiononly passes its input intotestStringArrayOption. Inline it at the scanner construction site.Proposed change
-func newTestStringArrayOption(option mo.Option[testStringArray]) testStringArrayOption { - return testStringArrayOption{Option: option} -} - func TestJSONStringArrayOptionValueScanner(t *testing.T) { t.Parallel() - scanner := JSONStringArrayOptionValueScanner(newTestStringArrayOption) + scanner := JSONStringArrayOptionValueScanner(func(option mo.Option[testStringArray]) testStringArrayOption { + return testStringArrayOption{Option: option} + })As per coding guidelines, “Add test helpers only when reused or when their names capture non-obvious domain semantics.”
🤖 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 `@pkg/framework/entutils/valuescanner_test.go` around lines 17 - 24, Remove the single-use newTestStringArrayOption helper and pass a direct constructor function at the JSONStringArrayOptionValueScanner call in TestJSONStringArrayOptionValueScanner, preserving the existing testStringArrayOption wrapping behavior.Source: Coding guidelines
openmeter/billing/charges/flatfee/adapter/detailedline_test.go (1)
179-179: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse required assertions for the changed decimal checks.
Use
s.Require().Equalfor theseInexactFloat64()comparisons. This matches the test guideline and stops dependent assertions after a failed value check.
openmeter/billing/charges/flatfee/adapter/detailedline_test.go#L179-L179: replaces.Equalwiths.Require().Equal.openmeter/billing/charges/flatfee/adapter/detailedline_test.go#L229-L230: replace boths.Equalcalls withs.Require().Equal.openmeter/billing/charges/service/invoicable_test.go#L4171-L4171: replaces.Equalwiths.Require().Equal.openmeter/billing/charges/service/invoicable_test.go#L4177-L4177: replaces.Equalwiths.Require().Equal.As per coding guidelines, “When precision permits, compare
alpacadecimal.DecimalthroughInexactFloat64()withrequire.Equal.”🤖 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/detailedline_test.go` at line 179, Replace the specified s.Equal assertions for InexactFloat64() decimal comparisons with s.Require().Equal: detailedline_test.go lines 179 and 229-230, and invoicable_test.go lines 4171 and 4177. Keep the compared values and test behavior unchanged while making each assertion required.Source: Coding guidelines
openmeter/billing/charges/usagebased/adapter/detailedline_test.go (2)
207-207: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse require-level assertions for decimal comparisons.
Use
s.Require().Equalfor theseInexactFloat64()checks. This makes the assertion behavior consistent with the test guideline.As per coding guidelines, compare
alpacadecimal.DecimalthroughInexactFloat64()withrequire.Equalwhen precision permits.Also applies to: 288-289
🤖 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/detailedline_test.go` at line 207, Replace the decimal comparison assertions around initialKeepDiscounts and the additional checks at the referenced locations with s.Require().Equal while continuing to compare InexactFloat64() values. Keep the existing expected values and assertion order unchanged.Source: Coding guidelines
291-308: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winExercise clearing through
UpsertRunDetailedLines.This direct Ent update proves that reads map SQL
NULLto an absent option. It does not test that an upsert clears existing discounts when the incomingAmountDiscountsvalue is absent. Keep this read check, and add an adapter upsert for the retained line with absent discounts. Then assert that both the persisted field and the reloaded detailed line are absent.🤖 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/detailedline_test.go` around lines 291 - 308, Extend the test around the existing GetByID assertion to call the adapter’s UpsertRunDetailedLines for the retained line with AmountDiscounts absent, rather than relying only on the direct Ent update. Verify the upsert succeeds, then assert both the persisted database field and the reloaded detailed line’s AmountDiscounts are absent; retain the existing read-mapping check.
🤖 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/flatfee/adapter/detailedline_test.go`:
- Around line 257-270: Extend the test after the existing direct
ClearAmountDiscounts update by calling the adapter’s UpsertDetailedLines path
with AmountDiscounts absent for the same detailed line. Then verify the
persisted row has a NULL amount-discounts value and the fetched realization
still reports AmountDiscounts as absent.
---
Nitpick comments:
In `@openmeter/billing/charges/flatfee/adapter/detailedline_test.go`:
- Line 179: Replace the specified s.Equal assertions for InexactFloat64()
decimal comparisons with s.Require().Equal: detailedline_test.go lines 179 and
229-230, and invoicable_test.go lines 4171 and 4177. Keep the compared values
and test behavior unchanged while making each assertion required.
In `@openmeter/billing/charges/usagebased/adapter/detailedline_test.go`:
- Line 207: Replace the decimal comparison assertions around
initialKeepDiscounts and the additional checks at the referenced locations with
s.Require().Equal while continuing to compare InexactFloat64() values. Keep the
existing expected values and assertion order unchanged.
- Around line 291-308: Extend the test around the existing GetByID assertion to
call the adapter’s UpsertRunDetailedLines for the retained line with
AmountDiscounts absent, rather than relying only on the direct Ent update.
Verify the upsert succeeds, then assert both the persisted database field and
the reloaded detailed line’s AmountDiscounts are absent; retain the existing
read-mapping check.
In `@pkg/framework/entutils/valuescanner_test.go`:
- Around line 17-24: Remove the single-use newTestStringArrayOption helper and
pass a direct constructor function at the JSONStringArrayOptionValueScanner call
in TestJSONStringArrayOptionValueScanner, preserving the existing
testStringArrayOption wrapping behavior.
🪄 Autofix
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 Plus
Run ID: 137fb3af-a541-4db7-b77f-b55b80a59d6d
⛔ Files ignored due to path filters (16)
openmeter/ent/db/chargeflatfeerundetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerundetailedline/chargeflatfeerundetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerundetailedline/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerundetailedline_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerundetailedline_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline/chargeusagebasedrundetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline_update.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**openmeter/ent/db/predicate/predicate.gois excluded by!**/ent/db/**openmeter/ent/db/runtime.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (18)
openmeter/billing/charges/README.mdopenmeter/billing/charges/flatfee/adapter/detailedline.goopenmeter/billing/charges/flatfee/adapter/detailedline_test.goopenmeter/billing/charges/flatfee/detailedline.goopenmeter/billing/charges/flatfee/service/linemapper.goopenmeter/billing/charges/models/amountdiscount/model.goopenmeter/billing/charges/models/amountdiscount/model_test.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/charges/usagebased/adapter/detailedline.goopenmeter/billing/charges/usagebased/adapter/detailedline_test.goopenmeter/billing/charges/usagebased/detailedline.goopenmeter/billing/charges/usagebased/service/rating/service_test.goopenmeter/ent/schema/chargesflatfee.goopenmeter/ent/schema/chargesusagebased.gopkg/framework/entutils/valuescanner.gopkg/framework/entutils/valuescanner_test.gotools/migrate/migrations/20260806141309_add_charge_run_detailed_line_amount_discounts.down.sqltools/migrate/migrations/20260806141309_add_charge_run_detailed_line_amount_discounts.up.sql
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
openmeter/billing/charges/models/detailedline/model_test.go (1)
47-53: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winTest the absent collection state too.
AmountDiscounts{}tests captured empty data. It does not test missing data. Add anilclone case that requiresAmountDiscounts(nil).Clone()to remain nil. Otherwise, a regression that changes persistedNULLinto[]will pass this test.🤖 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/models/detailedline/model_test.go` around lines 47 - 53, Extend TestAmountDiscountsClonePreservesEmptyCollection with a nil-source case that calls AmountDiscounts(nil).Clone() and asserts the result is nil, while retaining the existing empty-collection assertions.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/ent/schema/chargesusagebased.go`:
- Around line 446-448: Restore the local non-empty pricer_reference_id field in
ChargeUsageBasedRunDetailedLine.Fields(); chargedetailedline.Mixin does not
define it, and PricerReferenceID must persist independently from
ChildUniqueReferenceID for correction lines. Keep this field in the
charges-layer schema rather than adding it to the shared billing-line mixin.
---
Nitpick comments:
In `@openmeter/billing/charges/models/detailedline/model_test.go`:
- Around line 47-53: Extend TestAmountDiscountsClonePreservesEmptyCollection
with a nil-source case that calls AmountDiscounts(nil).Clone() and asserts the
result is nil, while retaining the existing empty-collection assertions.
🪄 Autofix
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 Plus
Run ID: ba2a11a5-bdb0-4387-ac6b-706f5a4d89fc
⛔ Files ignored due to path filters (17)
openmeter/ent/db/chargeflatfeerundetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerundetailedline/chargeflatfeerundetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerundetailedline/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerundetailedline_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerundetailedline_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeerundetailedline_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline/chargeusagebasedrundetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline_update.gois excluded by!**/ent/db/**openmeter/ent/db/entmixinaccessor.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**openmeter/ent/db/runtime.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**
📒 Files selected for processing (19)
openmeter/billing/charges/README.mdopenmeter/billing/charges/flatfee/adapter/detailedline.goopenmeter/billing/charges/flatfee/adapter/detailedline_test.goopenmeter/billing/charges/flatfee/detailedline.goopenmeter/billing/charges/models/detailedline/mixin.goopenmeter/billing/charges/models/detailedline/model.goopenmeter/billing/charges/models/detailedline/model_test.goopenmeter/billing/charges/models/detailedline/persistence.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/charges/usagebased/adapter/detailedline.goopenmeter/billing/charges/usagebased/adapter/detailedline_test.goopenmeter/billing/charges/usagebased/detailedline.goopenmeter/billing/charges/usagebased/service/linemapper.goopenmeter/billing/charges/usagebased/service/linemapper_test.goopenmeter/billing/charges/usagebased/service/rating/delta/engine_test.goopenmeter/billing/charges/usagebased/service/rating/service_test.goopenmeter/billing/charges/usagebased/service/rating/subtract/subtract_test.goopenmeter/ent/schema/chargesflatfee.goopenmeter/ent/schema/chargesusagebased.go
🚧 Files skipped from review as they are similar to previous changes (7)
- openmeter/billing/charges/service/invoicable_test.go
- openmeter/billing/charges/usagebased/adapter/detailedline.go
- openmeter/billing/charges/flatfee/adapter/detailedline_test.go
- openmeter/billing/charges/flatfee/detailedline.go
- openmeter/billing/charges/README.md
- openmeter/billing/charges/usagebased/adapter/detailedline_test.go
- openmeter/billing/charges/flatfee/adapter/detailedline.go
Overview
Charge run detailed lines persist aggregate discount totals today, but not the individual amount-discount facts needed to explain them.
This maintenance change:
Existing rows load with absent discount data. Newly rated rows store a present collection, including an empty array when discount capture ran but no discounts applied. No API specification changes are included.
Notes for reviewer
The nullable JSON representation is intentional:
NULLmeans discount facts were not captured for the persisted line[]means capture ran and no amount discounts appliedAmount values are signed so correction lines can reverse previously realized discounts.
Validation:
make lint-go-fastmake test-nocache(6,838 tests passed; 9 skipped)Summary by CodeRabbit
New Features
Documentation
Tests
Greptile Summary
The PR persists signed amount-discount snapshots on flat-fee and usage-based charge-run detailed lines while retaining aggregate totals as the historical authority.
Confidence Score: 5/5
The PR appears safe to merge.
No blocking failure remains.
Important Files Changed
Flowchart
%%{init: {'theme': 'neutral'}}%% flowchart LR Rating[Rating detailed lines] --> Mapping[Charge detailed-line mapping] Mapping --> Model[Signed amount-discount snapshots] Model --> Adapter[Flat-fee or usage-based adapter] Adapter --> DB[(Nullable JSONB amount_discounts)] DB --> Adapter Adapter --> Realization[Expanded charge realization] Model --> Totals[Aggregate DiscountsTotal]Reviews (4): Last reviewed commit: "test(charges): cover nil amount discount..." | Re-trigger Greptile