Repository navigation
refactor: reusable pricer - #3969
Conversation
|
Caution Review failedPull request was closed or merged during review 📝 WalkthroughWalkthroughIntroduces a new billing rating subsystem to replace the lineservice package. Creates Changes
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes This is a substantial architectural refactor touching core billing logic. The review requires understanding the entire billing/invoicing flow, verifying all lineservice removal doesn't break existing paths, validating the new rating service architecture, checking pricer implementations across multiple types, ensuring mutator ordering/composition is correct, and confirming all call sites have been properly updated. The high heterogeneity of changes (new types, deleted files, signature changes, refactored logic) combined with criticality of billing code drives the elevated effort estimate. Possibly related PRs
Suggested reviewers
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
fca6a2a to
574ce2b
Compare
574ce2b to
9149437
Compare
9149437 to
0a10443
Compare
There was a problem hiding this comment.
Actionable comments posted: 9
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
openmeter/billing/invoicelinediscount.go (1)
330-361:⚠️ Potential issue | 🟠 MajorKeep a compatibility path for
amountdiscounts.Removing
AmountfromStandardLineDiscountschanges the serialized shape. Older invoices that still carryamountdiscounts will decode with that field dropped, andClone/ReuseIDsFromthen persist the stripped version on the next save or recalculation. Please keep a deprecated compat field here, or land an explicit migration before this ships.💡 One safe way to keep older payloads round-tripping
type StandardLineDiscounts struct { + // Deprecated: keep until persisted invoices/API payloads are migrated off amount-based discounts. + Amount AmountLineDiscountsManaged `json:"amount,omitempty"` Usage UsageLineDiscountsManaged `json:"usage,omitempty"` } func (i StandardLineDiscounts) Clone() StandardLineDiscounts { out := StandardLineDiscounts{} + + if len(i.Amount) > 0 { + out.Amount = i.Amount.Clone() + } if len(i.Usage) > 0 { - out.Usage = lo.Map(i.Usage, func(item UsageLineDiscountManaged, _ int) UsageLineDiscountManaged { - return item.Clone() - }) + out.Usage = i.Usage.Clone() } return out } func (i StandardLineDiscounts) Validate() error { var errs []error + + for _, amount := range i.Amount { + if err := amount.Validate(); err != nil { + errs = append(errs, fmt.Errorf("amount[%s]: %w", amount.ID, err)) + } + } for _, usage := range i.Usage { if err := usage.Validate(); err != nil { errs = append(errs, fmt.Errorf("usage[%s]: %w", usage.ID, err)) } } return models.NewNillableGenericValidationError(errors.Join(errs...)) } func (i StandardLineDiscounts) ReuseIDsFrom(existingItems StandardLineDiscounts) StandardLineDiscounts { return StandardLineDiscounts{ + Amount: ReuseIDsFrom(i.Amount, existingItems.Amount), Usage: ReuseIDsFrom(i.Usage, existingItems.Usage), } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/invoicelinediscount.go` around lines 330 - 361, StandardLineDiscounts dropped the deprecated "amount" variant, which will cause older invoices to lose that field when decoded and re-saved; restore a backward-compatible field (e.g., add a DeprecatedAmount or Amount slice with the original managed type and json:"amount,omitempty") to StandardLineDiscounts and update Clone, ReuseIDsFrom and Validate to preserve and handle that field (Clone should deep-clone the amount entries, ReuseIDsFrom should call ReuseIDsFrom for the amount slice similar to Usage, and Validate should include any amount validation/errors or explicitly ignore but preserve them) so older payloads round-trip without being stripped.openmeter/billing/service/gatheringinvoicependinglines.go (1)
632-649:⚠️ Potential issue | 🔴 CriticalPersist the delete on
preSplitAtLine, not online.
preSplitAtLineis the value that gets written back withReplaceByID, but the empty-period branch updatesline.DeletedAtinstead. Because of that copy, the replaced line stays undeleted, so an empty pre-split segment can remain on the gathering invoice and still get billed.🛠️ Minimal fix
// If the line became empty, due to the split, let's remove it from the gathering invoice if preSplitAtLineEmpty { - line.DeletedAt = lo.ToPtr(clock.Now()) + preSplitAtLine.DeletedAt = lo.ToPtr(clock.Now()) } else { if err := preSplitAtLine.Validate(); err != nil { return res, fmt.Errorf("validating pre split line: %w", err) } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/service/gatheringinvoicependinglines.go` around lines 632 - 649, The code is setting DeletedAt on the original variable line instead of the value being written back (preSplitAtLine), so the ReplaceByID call on gatheringInvoice.Lines still writes an undeleted segment; update the empty-period branch to set preSplitAtLine.DeletedAt = lo.ToPtr(clock.Now()) (and keep the subsequent validation/ReplaceByID logic against preSplitAtLine) so the persisted record correctly reflects the deletion when calling gatheringInvoice.Lines.ReplaceByID(preSplitAtLine).openmeter/billing/pricer/service/mutator/credits.go (2)
37-42:⚠️ Potential issue | 🟠 MajorPlease close this TODO with a typed validation error.
Over-allocated credits are an invoice-invalid data condition, but this currently comes back as a raw sentinel. Wrapping it as
billing.ValidationErrorkeeps it on the existing validation-issue path instead of looking like an internal failure.🛡️ Suggested error wrapping
- return pricerResult, billing.ErrInvoiceLineCreditsNotConsumedFully + return pricerResult, billing.ValidationError{ + Err: billing.ErrInvoiceLineCreditsNotConsumedFully, + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/pricer/service/mutator/credits.go` around lines 37 - 42, Replace the raw sentinel return inside the creditValueRemaining.IsPositive() branch with a typed validation error using the billing.ValidationError type so this surface is treated as a validation issue rather than an internal failure; locate the branch that currently returns billing.ErrInvoiceLineCreditsNotConsumedFully (after creditValueRemaining.IsPositive()) and return a billing.ValidationError that wraps that sentinel (include a short context / field like "credits" or "invoice_line" in the validation error message or field property) and return that wrapped error along with pricerResult. Ensure you use the existing billing.ValidationError constructor or struct pattern used elsewhere in the codebase when constructing the wrapped error.
24-28:⚠️ Potential issue | 🟡 MinorSkip zero-value lines before cloning a credit.
A detailed line with a
0total still enters this branch and getsCloneWithAmount(0), so a fully discounted or zero-usage child can end up with a bogusCreditsAppliedrecord.💡 Small guard to avoid zero-amount credit rows
- totalAmount := pricerResult[idx].TotalAmount(i.CurrencyCalculator) + totalAmount := pricerResult[idx].TotalAmount(i.CurrencyCalculator) + if !totalAmount.IsPositive() { + continue + } if totalAmount.LessThanOrEqual(creditValueRemaining) {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/pricer/service/mutator/credits.go` around lines 24 - 28, The code currently appends a cloned credit even when totalAmount is zero; update the branch handling totalAmount to skip zero-value lines by checking totalAmount.IsZero() (or equivalent zero check) before subtracting creditValueRemaining and appending to pricerResult[idx].CreditsApplied via CloneWithAmount; i.e., ensure you only call creditValueRemaining = creditValueRemaining.Sub(totalAmount) and pricerResult[idx].CreditsApplied = append(...) when totalAmount is greater than zero.
🧹 Nitpick comments (10)
openmeter/billing/adapter/stdinvoicelinediff.go (1)
14-14: Unused type alias after refactorThe
amountLineDiscountManagedWithLinetype alias is indeed orphaned—it's defined at line 14 but never used anywhere in the file or codebase. The refactoring correctly shiftedAmountDiscountshandling from theStandardLinelevel down toDetailedLine, but forgot to clean up this type alias.Safe to remove as suggested:
🧹 Suggested cleanup
type ( usageLineDiscountManagedWithLine = entitydiff.EqualerNestedEntity[billing.UsageLineDiscountManaged, *billing.StandardLine] - amountLineDiscountManagedWithLine = entitydiff.EqualerNestedEntity[billing.AmountLineDiscountManaged, *billing.StandardLine] detailedLineWithParent = entitydiff.NestedEntity[*billing.DetailedLine, *billing.StandardLine]🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/adapter/stdinvoicelinediff.go` at line 14, Remove the orphaned type alias amountLineDiscountManagedWithLine (defined as entitydiff.EqualerNestedEntity[billing.AmountLineDiscountManaged, *billing.StandardLine]) since the refactor moved AmountDiscounts handling to DetailedLine and this alias is no longer referenced; locate the declaration of amountLineDiscountManagedWithLine in stdinvoicelinediff.go and delete that single line to clean up the unused symbol.openmeter/billing/pricer/line.go (1)
27-43: I'd keepbilling.*out of this new public accessor.
StandardLineAccessornow forces callers to depend onbilling.CreditsApplied,billing.Discounts, andbilling.StandardLineDiscounts, so the extracted package is still coupled right at its boundary. That makes the later package split a breaking API cleanup instead of an internal refactor. I’d either move these shapes intopricer, or keep this interface internal until the billing split lands.As per coding guidelines, "In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/pricer/line.go` around lines 27 - 43, StandardLineAccessor exposes billing.CreditsApplied, billing.Discounts and billing.StandardLineDiscounts which leaks the billing package across this public accessor; remove the direct dependency by either (a) moving those shapes into this package (pricer) and updating the methods GetCreditsApplied, GetRateCardDiscounts and GetStandardLineDiscounts to return the new local types, or (b) make StandardLineAccessor non-public/internal until the billing split is completed so callers do not depend on billing.*; update all implementations and callers of StandardLineAccessor, GetCreditsApplied, GetRateCardDiscounts and GetStandardLineDiscounts to use the new local types or the internal accessor accordingly.openmeter/billing/pricer/service/mutator/commitments.go (1)
82-90: CarrytotalBilledforward from the mutated line.
AddDiscountForOveragecan changepricerResult[idx], but the running total is still advanced with the pre-mutationlinecopy. Using the updated line keeps the state aligned with what was actually billed and makes the loop easier to follow.♻️ Suggested cleanup
- for idx, line := range pricerResult { + for idx := range pricerResult { // Total spends after adding the line's amount pricerResult[idx] = pricerResult[idx].AddDiscountForOverage(pricer.AddDiscountInput{ BilledAmountBeforeLine: totalBilled, MaxSpend: maxSpend, Currency: i.CurrencyCalculator, }) - totalBilled = totalBilled.Add(line.TotalAmount(i.CurrencyCalculator)) + totalBilled = totalBilled.Add(pricerResult[idx].TotalAmount(i.CurrencyCalculator)) }As per coding guidelines,
**/*.go: "In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/pricer/service/mutator/commitments.go` around lines 82 - 90, The loop advances totalBilled using the pre-mutation variable line, causing the running total to diverge from the mutated pricerResult entry; after calling pricerResult[idx] = pricerResult[idx].AddDiscountForOverage(pricer.AddDiscountInput{...}) update totalBilled using the mutated entry (e.g., pricerResult[idx].TotalAmount(i.CurrencyCalculator)) instead of line.TotalAmount(...) so the running total reflects the actual billed line and keeps state consistent for subsequent iterations.openmeter/billing/httpdriver/invoiceline.go (1)
413-425: Please add/confirm a focused regression test for usage-only discount mapping.Since this now intentionally emits only
Usagediscounts, a tight test aroundmapDiscountsToAPI(empty vs non-empty usage) would make this behavioral change safer.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/httpdriver/invoiceline.go` around lines 413 - 425, Add a focused regression test for mapDiscountsToAPI that verifies the new usage-only behavior: create two cases using billing.StandardLineDiscounts — one with empty Usage and one with a non-empty Usage slice — and assert that mapDiscountsToAPI returns (nil, nil) for the empty case and a non-nil *api.InvoiceLineDiscounts with the expected Usage contents for the non-empty case; also include a test that simulates mapInvoiceLineUsageDiscountsToAPI returning an error and assert the error is propagated (i.e., mapDiscountsToAPI returns a wrapped error). Use the function names mapDiscountsToAPI and mapInvoiceLineUsageDiscountsToAPI and validate the returned api.InvoiceLineDiscounts.openmeter/billing/pricer/service/service.go (1)
5-9: Add an explicit compile-time interface conformance check.Nice catch on the pattern—adding the conformance guard helps prevent interface drift as
pricer.Serviceevolves. It's a small but useful maintainability win.Suggested addition
type service struct{} + +var _ pricer.Service = (*service)(nil) func New() pricer.Service { return &service{} }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/pricer/service/service.go` around lines 5 - 9, Add a compile-time interface conformance check to ensure the concrete type implements pricer.Service: declare a var or _ = (pricer.Service)(&service{}) (or use "var _ pricer.Service = (*service)(nil)"). Place this near the type/service/New definitions so future changes to pricer.Service fail to compile if service no longer satisfies the interface.openmeter/billing/pricer/service/price/package_test.go (1)
298-306: Add one fractional package case here.These assertions only cover whole-number quantities. Since package pricing is decimal-based elsewhere, a case like
10.01 / 10 => 2would protect the ceil/rounding behavior now that this helper is public.🧪 Suggested test addition
require.Equal(t, float64(0), p.GetNumberOfPackages(alpacadecimal.NewFromFloat(0), alpacadecimal.NewFromFloat(10)).InexactFloat64()) require.Equal(t, float64(1), p.GetNumberOfPackages(alpacadecimal.NewFromFloat(1), alpacadecimal.NewFromFloat(10)).InexactFloat64()) require.Equal(t, float64(1), p.GetNumberOfPackages(alpacadecimal.NewFromFloat(9), alpacadecimal.NewFromFloat(10)).InexactFloat64()) require.Equal(t, float64(1), p.GetNumberOfPackages(alpacadecimal.NewFromFloat(10), alpacadecimal.NewFromFloat(10)).InexactFloat64()) + require.Equal(t, float64(2), p.GetNumberOfPackages(alpacadecimal.NewFromFloat(10.01), alpacadecimal.NewFromFloat(10)).InexactFloat64()) require.Equal(t, float64(2), p.GetNumberOfPackages(alpacadecimal.NewFromFloat(11), alpacadecimal.NewFromFloat(10)).InexactFloat64())As per coding guidelines,
**/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/pricer/service/price/package_test.go` around lines 298 - 306, Add a test in TestGetNumberOfPackages to cover fractional quantities: the current cases only test integers, so call p.GetNumberOfPackages with a quantity slightly above a package size (e.g., alpacadecimal.NewFromFloat(10.01) with packageSize alpacadecimal.NewFromFloat(10)) and assert the result is 2 to verify the ceiling behavior of price.Package.GetNumberOfPackages; keep the new assertion consistent with the existing require.Equal pattern and use InexactFloat64() like the other assertions.test/billing/invoice_test.go (1)
2264-2272: Worth adding aCreditsAppliedassertion in this suite too.This file now covers the new child IDs plus max/min spend behavior, but it still doesn’t exercise the credit mutator end-to-end. One invoice case with applied credits on a split line would make the extraction a lot safer.
As per coding guidelines,
**/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/billing/invoice_test.go` around lines 2264 - 2272, The test is missing an assertion for applied credits on the split/child usage line; update the lineExpectations for pricer.UnitPriceUsageChildUniqueReferenceID inside the requireDetailedLines call to include a CreditsApplied field (in the feeLineExpect struct) with the expected numeric value that matches the invoice scenario (the amount of credits applied to that split line). Ensure the expected CreditsApplied value corresponds to how credits are allocated in the invoice under test so the extraction validates the credit mutator end-to-end.openmeter/billing/pricer/service/price/flat_test.go (1)
70-81: Please add the first split-line case for in-advance flat fees.This covers the no-op mid-period branch, but there’s still no split-line case for the branch that should actually charge in advance.
SinglePerPeriodLineModewon’t catch regressions tied toIsFirstInPeriod()/ split-hierarchy handling, so a tiny first-segment case would make this a lot tighter. As per coding guidelines**/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/pricer/service/price/flat_test.go` around lines 70 - 81, Add a new unit subtest that mirrors the existing "flat price, in advance, mid period" case but uses the first-split line mode to exercise the in-advance first-segment branch: call testutil.RunCalculationTestCase with a CalculationTestCase whose Price is productcatalog.NewPriceFrom(productcatalog.FlatPrice{Amount: alpacadecimal.NewFromFloat(100), PaymentTerm: productcatalog.InAdvancePaymentTerm}), set LineMode to testutil.FirstSplitLineMode (the split-first segment mode used to trigger IsFirstInPeriod()), provide a minimal FeatureUsageResponse (e.g., LinePeriodQty: alpacadecimal.NewFromFloat(1)), and assert the expected pricer.DetailedLines that represent the charged in-advance flat fee for the first split segment.openmeter/billing/pricer/service/mutator/credits_test.go (1)
100-167: Worth covering credits on the tier-3 usage line too.The current cases only assert credits on the flat-fee tiers and the minimum-spend child. There’s still no case where leftover credits roll into
usage price for tier 3, so a carry-forward bug in the generic mutator pipeline would still slip through. A small case likeqty=15with credits just above150would pin that down nicely. As per coding guidelines**/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/pricer/service/mutator/credits_test.go` around lines 100 - 167, The test should assert that leftover credits are applied to the tier-3 usage line: change the test case "credits mutator, tier 1 + 2 paid fully in credits" (the call to testutil.RunCalculationTestCase / testutil.CalculationTestCase) to provide CreditsApplied with an Amount just above 150 (e.g. 155) so 100+50 flat fees are consumed and 5 carries to tier-3, and update the expected pricer.DetailedLines entry for "graduated-tiered-3-price-usage" to include a CreditsApplied entry with Amount 5 and the same Description (testCredit1Description) and set Totals.CreditsTotal to 5 and Totals.Total to 0 for that line; leave the other lines' expectations unchanged.openmeter/billing/pricer/service/price/tieredgraduated.go (1)
249-251: Tiny typo: "cummulative" → "cumulative".✏️ Fix
- // Now that we have the ranges, let's iterate over the ranges and calculate the cummulative total amount + // Now that we have the ranges, let's iterate over the ranges and calculate the cumulative total amount🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/pricer/service/price/tieredgraduated.go` around lines 249 - 251, Update the comment above the variable total in the tiered/graduated pricing loop: replace the misspelled word "cummulative" with the correct spelling "cumulative" so the comment reads that it calculates the cumulative total amount and calls the callback for each in-scope range (the comment directly preceding the declaration of total := alpacadecimal.Zero).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/billing/pricer/service/billableperiod.go`:
- Around line 17-25: Check the line price before calling the pricer: move the
nil-check for in.Line.GetPrice() (currently assigning to linePrice and returning
"price is nil") to run before invoking getPricerFor(in.Line). This ensures you
validate the price first (use the existing linePrice variable and error) so
getPricerFor cannot accidentally access a nil price internally; update the code
around getPricerFor and linePrice to reflect the new order.
In `@openmeter/billing/pricer/service/detailledline.go`:
- Around line 85-95: The code treats linePricer.GenerateDetailedLines as
returning a pointer (checks out == nil and uses *out), but the interface/type is
pricer.DetailedLines (non-pointer); make the types consistent by using the
non-pointer return: stop treating out as a pointer — remove the nil check and
the dereference, pass out directly to getTotalsFromDetailedLines, and ensure all
references (linePricer.GenerateDetailedLines, getTotalsFromDetailedLines, and
any variables declared as pricer.DetailedLines) use the non-pointer type;
alternatively, if you prefer pointer semantics, change the
pricer.GenerateDetailedLines signature and the pricer.DetailedLines definition
to return *pricer.DetailedLines everywhere so the current checks remain valid.
- Around line 18-21: validateStandardLine currently calls in.GetPrice() without
checking that the pricer.StandardLineAccessor parameter is non-nil which can
cause a panic; add a nil guard at the start of validateStandardLine (check that
the in parameter is not nil) and return a descriptive validation error (e.g.,
"standard line is nil") so GenerateDetailedLines receives a normal error instead
of panicking; ensure subsequent code still calls in.GetPrice() only after the
nil check.
In `@openmeter/billing/pricer/service/mutator/discountusage.go`:
- Around line 25-38: The code calls l.GetUsage() before checking for a usage
discount, causing flat/non-metered lines (where Usage is nil) to error out;
change the order so you call m.getUsageDiscount(l) first and return early if it
is nil (using m.removeUsageDiscounts(l)), and only call l.GetUsage() after you
know usageDiscount != nil; keep the same error handling semantics (return errors
from getUsageDiscount or GetUsage as before) and update the logic in the
function that currently references l.GetUsage(), m.getUsageDiscount, and
m.removeUsageDiscounts.
In `@openmeter/billing/pricer/service/price/base.go`:
- Around line 52-67: NonProgressiveBillingPricer.ResolveBillablePeriod currently
compares in.AsOf directly against in.Line.GetServicePeriod().To, relying on
callers to pre-truncate timestamps; change the method to normalize/truncate
in.AsOf the same way the progressive resolver does before doing the comparison
so the logic is consistent (i.e., truncate/round down in.AsOf to the billing
window used elsewhere), then use the truncated timestamp in the if check and
subsequent return; update references inside ResolveBillablePeriod (in.AsOf,
in.Line.GetServicePeriod()) only — keep the existing ValidationError check for
GetSplitLineGroupID().
In `@openmeter/billing/pricer/service/price/tieredgraduated_test.go`:
- Around line 238-269: The test name string "tiered graduated, last line, no
usage, minimum price set" is duplicated; rename this t.Run invocation to a
unique name (e.g., include "with preline qty 2" or similar) so it differs from
the other case at line 196; update only the first argument to t.Run enclosing
the test (the test name literal in the t.Run call where
testutil.RunCalculationTestCase is used and referencing
testTiers/Commitments/PreLinePeriodQty) to a distinct descriptive name to make
test output unambiguous.
In `@openmeter/billing/pricer/service/price/tieredvolume.go`:
- Around line 86-92: The FindTierForQuantity function compares quantity against
price.WithSortedTiers().Tiers but returns a pointer to price.Tiers[i], which can
be a different (unsorted) tier; change the implementation to first store the
sorted result (e.g., sorted := price.WithSortedTiers()), iterate over
sorted.Tiers, and when a match is found return a pointer to sorted.Tiers[i] (and
the matching index from that sorted slice) so the returned Tier and Index
correspond to the thresholds actually used for comparison.
In `@openmeter/billing/pricer/service/testutil/ubptest.go`:
- Around line 38-47: The helper only asserts DetailedLines; update
CalculationTestCase to include expected Totals, FinalUsage, and
FinalStandardLineDiscounts (and keep ExpectErrorIs) and modify
RunCalculationTestCase to assert the full pricer.GenerateDetailedLinesResult
returned by GenerateDetailedLinesResult (compare res.Totals, res.FinalUsage,
res.FinalStandardLineDiscounts and res.DetailedLines) so tests fail on
mismatches; use existing types (e.g., pricer.Totals, FeatureUsageResponse,
billing.Discount types) and include clear equality checks or require.Equal
assertions consistent with other tests, and ensure previous behavior for
ExpectErrorIs is preserved.
In `@openmeter/billing/service/invoicecalc/details.go`:
- Around line 24-35: Add a fail-fast check for a missing pricer dependency so we
don't call deps.Pricer.GenerateDetailedLines on nil; either validate deps.Pricer
at the start of the enclosing function that iterates invoice.Lines (before the
loop) or implement/extend CalculatorDependencies.Validate to return a clear
error when Pricer is nil, and have the caller propagate that error; reference
the deps.Pricer.GenerateDetailedLines call and mergeGeneratedDetailedLines to
locate where the nil-method panic would occur and return a descriptive error
like "missing Pricer dependency" instead of proceeding.
---
Outside diff comments:
In `@openmeter/billing/invoicelinediscount.go`:
- Around line 330-361: StandardLineDiscounts dropped the deprecated "amount"
variant, which will cause older invoices to lose that field when decoded and
re-saved; restore a backward-compatible field (e.g., add a DeprecatedAmount or
Amount slice with the original managed type and json:"amount,omitempty") to
StandardLineDiscounts and update Clone, ReuseIDsFrom and Validate to preserve
and handle that field (Clone should deep-clone the amount entries, ReuseIDsFrom
should call ReuseIDsFrom for the amount slice similar to Usage, and Validate
should include any amount validation/errors or explicitly ignore but preserve
them) so older payloads round-trip without being stripped.
In `@openmeter/billing/pricer/service/mutator/credits.go`:
- Around line 37-42: Replace the raw sentinel return inside the
creditValueRemaining.IsPositive() branch with a typed validation error using the
billing.ValidationError type so this surface is treated as a validation issue
rather than an internal failure; locate the branch that currently returns
billing.ErrInvoiceLineCreditsNotConsumedFully (after
creditValueRemaining.IsPositive()) and return a billing.ValidationError that
wraps that sentinel (include a short context / field like "credits" or
"invoice_line" in the validation error message or field property) and return
that wrapped error along with pricerResult. Ensure you use the existing
billing.ValidationError constructor or struct pattern used elsewhere in the
codebase when constructing the wrapped error.
- Around line 24-28: The code currently appends a cloned credit even when
totalAmount is zero; update the branch handling totalAmount to skip zero-value
lines by checking totalAmount.IsZero() (or equivalent zero check) before
subtracting creditValueRemaining and appending to
pricerResult[idx].CreditsApplied via CloneWithAmount; i.e., ensure you only call
creditValueRemaining = creditValueRemaining.Sub(totalAmount) and
pricerResult[idx].CreditsApplied = append(...) when totalAmount is greater than
zero.
In `@openmeter/billing/service/gatheringinvoicependinglines.go`:
- Around line 632-649: The code is setting DeletedAt on the original variable
line instead of the value being written back (preSplitAtLine), so the
ReplaceByID call on gatheringInvoice.Lines still writes an undeleted segment;
update the empty-period branch to set preSplitAtLine.DeletedAt =
lo.ToPtr(clock.Now()) (and keep the subsequent validation/ReplaceByID logic
against preSplitAtLine) so the persisted record correctly reflects the deletion
when calling gatheringInvoice.Lines.ReplaceByID(preSplitAtLine).
---
Nitpick comments:
In `@openmeter/billing/adapter/stdinvoicelinediff.go`:
- Line 14: Remove the orphaned type alias amountLineDiscountManagedWithLine
(defined as entitydiff.EqualerNestedEntity[billing.AmountLineDiscountManaged,
*billing.StandardLine]) since the refactor moved AmountDiscounts handling to
DetailedLine and this alias is no longer referenced; locate the declaration of
amountLineDiscountManagedWithLine in stdinvoicelinediff.go and delete that
single line to clean up the unused symbol.
In `@openmeter/billing/httpdriver/invoiceline.go`:
- Around line 413-425: Add a focused regression test for mapDiscountsToAPI that
verifies the new usage-only behavior: create two cases using
billing.StandardLineDiscounts — one with empty Usage and one with a non-empty
Usage slice — and assert that mapDiscountsToAPI returns (nil, nil) for the empty
case and a non-nil *api.InvoiceLineDiscounts with the expected Usage contents
for the non-empty case; also include a test that simulates
mapInvoiceLineUsageDiscountsToAPI returning an error and assert the error is
propagated (i.e., mapDiscountsToAPI returns a wrapped error). Use the function
names mapDiscountsToAPI and mapInvoiceLineUsageDiscountsToAPI and validate the
returned api.InvoiceLineDiscounts.
In `@openmeter/billing/pricer/line.go`:
- Around line 27-43: StandardLineAccessor exposes billing.CreditsApplied,
billing.Discounts and billing.StandardLineDiscounts which leaks the billing
package across this public accessor; remove the direct dependency by either (a)
moving those shapes into this package (pricer) and updating the methods
GetCreditsApplied, GetRateCardDiscounts and GetStandardLineDiscounts to return
the new local types, or (b) make StandardLineAccessor non-public/internal until
the billing split is completed so callers do not depend on billing.*; update all
implementations and callers of StandardLineAccessor, GetCreditsApplied,
GetRateCardDiscounts and GetStandardLineDiscounts to use the new local types or
the internal accessor accordingly.
In `@openmeter/billing/pricer/service/mutator/commitments.go`:
- Around line 82-90: The loop advances totalBilled using the pre-mutation
variable line, causing the running total to diverge from the mutated
pricerResult entry; after calling pricerResult[idx] =
pricerResult[idx].AddDiscountForOverage(pricer.AddDiscountInput{...}) update
totalBilled using the mutated entry (e.g.,
pricerResult[idx].TotalAmount(i.CurrencyCalculator)) instead of
line.TotalAmount(...) so the running total reflects the actual billed line and
keeps state consistent for subsequent iterations.
In `@openmeter/billing/pricer/service/mutator/credits_test.go`:
- Around line 100-167: The test should assert that leftover credits are applied
to the tier-3 usage line: change the test case "credits mutator, tier 1 + 2 paid
fully in credits" (the call to testutil.RunCalculationTestCase /
testutil.CalculationTestCase) to provide CreditsApplied with an Amount just
above 150 (e.g. 155) so 100+50 flat fees are consumed and 5 carries to tier-3,
and update the expected pricer.DetailedLines entry for
"graduated-tiered-3-price-usage" to include a CreditsApplied entry with Amount 5
and the same Description (testCredit1Description) and set Totals.CreditsTotal to
5 and Totals.Total to 0 for that line; leave the other lines' expectations
unchanged.
In `@openmeter/billing/pricer/service/price/flat_test.go`:
- Around line 70-81: Add a new unit subtest that mirrors the existing "flat
price, in advance, mid period" case but uses the first-split line mode to
exercise the in-advance first-segment branch: call
testutil.RunCalculationTestCase with a CalculationTestCase whose Price is
productcatalog.NewPriceFrom(productcatalog.FlatPrice{Amount:
alpacadecimal.NewFromFloat(100), PaymentTerm:
productcatalog.InAdvancePaymentTerm}), set LineMode to
testutil.FirstSplitLineMode (the split-first segment mode used to trigger
IsFirstInPeriod()), provide a minimal FeatureUsageResponse (e.g., LinePeriodQty:
alpacadecimal.NewFromFloat(1)), and assert the expected pricer.DetailedLines
that represent the charged in-advance flat fee for the first split segment.
In `@openmeter/billing/pricer/service/price/package_test.go`:
- Around line 298-306: Add a test in TestGetNumberOfPackages to cover fractional
quantities: the current cases only test integers, so call p.GetNumberOfPackages
with a quantity slightly above a package size (e.g.,
alpacadecimal.NewFromFloat(10.01) with packageSize
alpacadecimal.NewFromFloat(10)) and assert the result is 2 to verify the ceiling
behavior of price.Package.GetNumberOfPackages; keep the new assertion consistent
with the existing require.Equal pattern and use InexactFloat64() like the other
assertions.
In `@openmeter/billing/pricer/service/price/tieredgraduated.go`:
- Around line 249-251: Update the comment above the variable total in the
tiered/graduated pricing loop: replace the misspelled word "cummulative" with
the correct spelling "cumulative" so the comment reads that it calculates the
cumulative total amount and calls the callback for each in-scope range (the
comment directly preceding the declaration of total := alpacadecimal.Zero).
In `@openmeter/billing/pricer/service/service.go`:
- Around line 5-9: Add a compile-time interface conformance check to ensure the
concrete type implements pricer.Service: declare a var or _ =
(pricer.Service)(&service{}) (or use "var _ pricer.Service = (*service)(nil)").
Place this near the type/service/New definitions so future changes to
pricer.Service fail to compile if service no longer satisfies the interface.
In `@test/billing/invoice_test.go`:
- Around line 2264-2272: The test is missing an assertion for applied credits on
the split/child usage line; update the lineExpectations for
pricer.UnitPriceUsageChildUniqueReferenceID inside the requireDetailedLines call
to include a CreditsApplied field (in the feeLineExpect struct) with the
expected numeric value that matches the invoice scenario (the amount of credits
applied to that split line). Ensure the expected CreditsApplied value
corresponds to how credits are allocated in the invoice under test so the
extraction validates the credit mutator end-to-end.
🪄 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: 74e6b4b2-559e-4f99-a5d5-a1a9182277ad
📒 Files selected for processing (67)
app/common/billing.goapp/common/openmeter_billingworker.gocmd/billing-worker/wire_gen.gocmd/jobs/internal/wire_gen.gocmd/server/wire_gen.goopenmeter/billing/adapter/stdinvoicelinediff.goopenmeter/billing/adapter/stdinvoicelinediff_test.goopenmeter/billing/adapter/stdinvoicelinemapper.goopenmeter/billing/adapter/stdinvoicelines.goopenmeter/billing/httpdriver/invoiceline.goopenmeter/billing/invoicelinediscount.goopenmeter/billing/pricer/const.goopenmeter/billing/pricer/detailedline.goopenmeter/billing/pricer/detailedline_test.goopenmeter/billing/pricer/line.goopenmeter/billing/pricer/service.goopenmeter/billing/pricer/service/billableperiod.goopenmeter/billing/pricer/service/detailledline.goopenmeter/billing/pricer/service/mutator/commitments.goopenmeter/billing/pricer/service/mutator/credits.goopenmeter/billing/pricer/service/mutator/credits_test.goopenmeter/billing/pricer/service/mutator/discountpercentage.goopenmeter/billing/pricer/service/mutator/discountusage.goopenmeter/billing/pricer/service/mutator/types.goopenmeter/billing/pricer/service/price/base.goopenmeter/billing/pricer/service/price/dynamic.goopenmeter/billing/pricer/service/price/dynamic_test.goopenmeter/billing/pricer/service/price/flat.goopenmeter/billing/pricer/service/price/flat_test.goopenmeter/billing/pricer/service/price/package.goopenmeter/billing/pricer/service/price/package_test.goopenmeter/billing/pricer/service/price/tiered.goopenmeter/billing/pricer/service/price/tieredgraduated.goopenmeter/billing/pricer/service/price/tieredgraduated_test.goopenmeter/billing/pricer/service/price/tieredvolume.goopenmeter/billing/pricer/service/price/tieredvolume_test.goopenmeter/billing/pricer/service/price/types.goopenmeter/billing/pricer/service/price/unit.goopenmeter/billing/pricer/service/price/unit_test.goopenmeter/billing/pricer/service/pricer.goopenmeter/billing/pricer/service/service.goopenmeter/billing/pricer/service/testutil/ubptest.goopenmeter/billing/service/gatheringinvoice.goopenmeter/billing/service/gatheringinvoicependinglines.goopenmeter/billing/service/invoice.goopenmeter/billing/service/invoicecalc/calculator.goopenmeter/billing/service/invoicecalc/details.goopenmeter/billing/service/lineservice/billableperiod.goopenmeter/billing/service/lineservice/commitments.goopenmeter/billing/service/lineservice/discountusage.goopenmeter/billing/service/lineservice/doc.goopenmeter/billing/service/lineservice/linebase.goopenmeter/billing/service/lineservice/meteredquantity.goopenmeter/billing/service/lineservice/pricemutate.goopenmeter/billing/service/lineservice/pricer.goopenmeter/billing/service/lineservice/service.goopenmeter/billing/service/lineservice/usagebasedline.goopenmeter/billing/service/lineservice/usagebasedline_test.goopenmeter/billing/service/lineservice/usagebasedlineflat.goopenmeter/billing/service/service.goopenmeter/billing/service/stdinvoicestate.goopenmeter/billing/stdinvoiceline.gotest/app/testenv.gotest/billing/invoice_test.gotest/billing/suite.gotest/customer/testenv.gotest/subscription/framework_test.go
💤 Files with no reviewable changes (15)
- openmeter/billing/adapter/stdinvoicelinediff_test.go
- openmeter/billing/adapter/stdinvoicelinemapper.go
- openmeter/billing/adapter/stdinvoicelines.go
- openmeter/billing/service/lineservice/usagebasedline_test.go
- openmeter/billing/service/lineservice/meteredquantity.go
- openmeter/billing/service/lineservice/service.go
- openmeter/billing/service/lineservice/commitments.go
- openmeter/billing/service/lineservice/billableperiod.go
- openmeter/billing/service/lineservice/pricemutate.go
- openmeter/billing/service/lineservice/linebase.go
- openmeter/billing/service/lineservice/discountusage.go
- openmeter/billing/service/lineservice/pricer.go
- openmeter/billing/service/lineservice/usagebasedlineflat.go
- openmeter/billing/service/lineservice/doc.go
- openmeter/billing/service/lineservice/usagebasedline.go
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/billing/service/invoicecalc/details.go`:
- Around line 121-123: Guard against a nil UsageBased before writing FinalUsage:
when in.FinalUsage != nil, first check parentLine.UsageBased is not nil and
return a standard error if it is (rather than dereferencing and panicking);
update the block that sets parentLine.UsageBased.Quantity and
parentLine.UsageBased.PreLinePeriodQuantity to perform this nil-check and error
return so callers get a clear error instead of a panic (referencing
in.FinalUsage, parentLine.UsageBased, and the UsageBasedLine member writes).
🪄 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: 922ab250-f194-4de2-9bff-50d638c0b614
📒 Files selected for processing (9)
openmeter/billing/pricer/service/detailedline.goopenmeter/billing/pricer/service/mutator/commitments.goopenmeter/billing/pricer/service/mutator/credits.goopenmeter/billing/pricer/service/price/base.goopenmeter/billing/pricer/service/price/tieredgraduated_test.goopenmeter/billing/pricer/service/price/tieredvolume.goopenmeter/billing/pricer/service/pricer.goopenmeter/billing/service/gatheringinvoicependinglines.goopenmeter/billing/service/invoicecalc/details.go
🚧 Files skipped from review as they are similar to previous changes (2)
- openmeter/billing/pricer/service/price/base.go
- openmeter/billing/pricer/service/mutator/commitments.go
Overview
Naming: using rating for the usage x price -> actual line translation as that's the industry standard:
This patch splits the pricing functionality from the billing service internals. The new pricer package can generate pricing/detailed lines from anything that implements the required interfaces (charges, ledger realtime engine).
The patch is not great as pricer should not depend on the billing package, but for now we can live with this approach. Once billing package is split into multiple subpackages this dependency can be solved for.
Logic changes
Standard lines no longer have amount discounts: they are applied to the detailed lines and never to the standard invoice lines.
Usage discount calculation: it was refactored to "assume" that the previous lines have already used the maximum possible amount. This is a better approach as we have outstanding bugs around progressively billed usage discounts on an edited discount ignoring the previously allocated values.
On the long term, charges will solve for this issue and we can get rid of cross invoice calculations.
Notes for reviewer
Summary by CodeRabbit
New Features
Changes