Skip to content

feat: implement percentage discounts - #2632

Merged
turip merged 1 commit into
mainfrom
feat/percentage-discounts
Apr 9, 2025
Merged

turip merged 1 commit into
mainfrom
feat/percentage-discounts

Conversation

@turip

@turip turip commented Apr 8, 2025 •

Copy link
Copy Markdown
Member

Overview

Percentage discounts are both supported for feeLine and usage based lines. Given this is the only discount for fee lines we are not using the middleware/pricer system there.

Summary by CodeRabbit

  • New Features

    • Introduced dynamic percentage-based discount functionality for improved pricing flexibility in fee-based and usage-based billing scenarios.
    • Added support for associating discounts with unique identifiers.
  • Bug Fixes

    • Adjusted discount calculations to incorporate rounding adjustments, ensuring accuracy in final invoice amounts.
  • Refactor

    • Enhanced discount calculation logic to ensure accurate totals through refined rounding and discount limit handling.
    • Updated discount data representation for clearer and more reliable invoicing.

These enhancements deliver more precise and fair billing outcomes for end users.

@coderabbitai

coderabbitai Bot commented Apr 8, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request modifies the billing service’s discount handling and pricing calculations. It updates the JSON tag for the RoundingAmount field, introduces a new mutator type for applying percentage-based discounts, and adds a method to apply these discounts to fee lines. The pricing calculation is refactored to utilize a helper function with a new input type and constant for discount integration. Additionally, several test cases and new test files are created or updated to validate discount logic across fee lines, unit pricing, and usage-based calculations.

Changes

File(s) Change Summary
openmeter/billing/invoicelinediscount.go Updated JSON tag for RoundingAmount field from "rounding" to "roundingAmount".
openmeter/billing/service/lineservice/discountpercentage.go
openmeter/billing/service/lineservice/feeline.go
openmeter/billing/service/lineservice/usagebasedline.go
Introduced discount percentage logic: added new discountPercentageMutator type with methods (Mutate, getDiscounts, getLineDiscounts); added applyPercentageDiscounts method in feeLine; in usage-based lines, added constant RateCardDiscountChildUniqueReferenceID, integrated discount mutator into the pricer configuration, and refactored TotalAmount calculation using a new helper with inputs encapsulated in getTotalAmountInput.
openmeter/billing/service/lineservice/feeline_test.go
openmeter/billing/service/lineservice/priceunit_test.go
openmeter/billing/service/lineservice/usagebasedline_test.go
Added and updated tests: new test file for feeLine discount application checking JSON equality, extended price unit tests with scenarios for multiple discount percentages and maximum spend cases, and updated usage-based pricing tests to incorporate a new discounts field in test cases.
openmeter/app/stripe/entity/app/invoice.go Modified getDiscountStripeInvoiceItemParams function to adjust the Amount field by incorporating RoundingAmount into the discount calculation.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@turip
turip force-pushed the feat/percentage-discounts branch from 247eabf to 00117c3 Compare April 8, 2025 21:26
@turip turip added release-note/feature Release note: Exciting New Features area/billing labels Apr 8, 2025
@turip
turip marked this pull request as ready for review April 8, 2025 21:26
@turip
turip requested a review from a team as a code owner April 8, 2025 21:26

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
openmeter/billing/service/lineservice/feeline_test.go (1)

17-44: Test coverage looks good but could be expanded.

The test case validates the basic functionality of applying a 50% discount to a fee line, with proper assertions to ensure the discount is correctly calculated and stored.

Consider adding additional test cases to cover:

  • Multiple discounts applied simultaneously
  • Edge cases like 0% or 100% discounts
  • Validation of error cases (e.g., when discount percentage exceeds 100%)
t.Run("should apply multiple discounts", func(t *testing.T) {
    line := generateFeeLine(t, generateFeeLineInput{
        Quantity: 1,
        Amount:   100,
        RateCardDiscounts: []productcatalog.PercentageDiscount{
            {
                Percentage: models.NewPercentage(25),
            },
            {
                Percentage: models.NewPercentage(15),
            },
        },
    })

    require.NoError(t, line.CalculateDetailedLines())

    // Assert on expected discounts
    // ...
})
openmeter/billing/service/lineservice/discountpercentage.go (2)

108-122: Complex rounding logic should be documented.

The rounding logic handles edge cases where the sum of individual discounts doesn't match the total expected discount due to rounding errors. However, this complex logic would benefit from additional documentation.

Add explanatory comments to clarify the purpose and functioning of the rounding logic:

- // Rounding support (e.g. a 100% of discount composed of 33%, 33%, 34% of 0.01$ should yield 0.0$)
+ // Handle rounding discrepancies to ensure the sum of individual discount amounts 
+ // matches the total expected discount amount.
+ // Example: A 100% discount composed of 33%, 33%, 34% applied to $0.01 should 
+ // yield exactly $0.01 in total discounts, even if individual calculations 
+ // might result in rounding errors.

112-122: Consider adding a safeguard for the rounding distribution.

The current implementation assigns any rounding difference to the last discount that can accommodate it. In extreme cases where no discount can accommodate the rounding difference, this could lead to unexpected behavior.

Add a fallback case to handle situations where the rounding amount can't be distributed:

if !roundingAmount.IsZero() {
    var adjustedDiscount bool = false
    for i := len(lineDiscounts) - 1; i >= 0; i-- {
        discount := lineDiscounts[i]

        if discount.Amount.Add(roundingAmount).GreaterThanOrEqual(alpacadecimal.Zero) {
            discount.RoundingAmount = roundingAmount
            lineDiscounts[i] = discount
            adjustedDiscount = true
            break
        }
    }
+    // If we couldn't distribute the rounding amount to any discount
+    // (extremely rare case), we can add it as a separate adjustment
+    if !adjustedDiscount && len(lineDiscounts) > 0 {
+        // Create a rounding adjustment on the first discount
+        lineDiscounts[0].RoundingAmount = roundingAmount
+    }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bfb8127 and 00117c3.

📒 Files selected for processing (7)
  • openmeter/billing/invoicelinediscount.go (1 hunks)
  • openmeter/billing/service/lineservice/discountpercentage.go (1 hunks)
  • openmeter/billing/service/lineservice/feeline.go (1 hunks)
  • openmeter/billing/service/lineservice/feeline_test.go (1 hunks)
  • openmeter/billing/service/lineservice/priceunit_test.go (2 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (3 hunks)
  • openmeter/billing/service/lineservice/usagebasedline_test.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (7)
openmeter/billing/service/lineservice/usagebasedline_test.go (5)
api/client/javascript/src/client/schemas.ts (1)
  • Discount (9290-9290)
api/api.gen.go (2)
  • Discount (1925-1927)
  • InvoiceLineStatusValid (378-378)
openmeter/productcatalog/discount.go (1)
  • Discount (54-58)
api/client/go/client.gen.go (2)
  • Discount (1790-1792)
  • InvoiceLineStatusValid (342-342)
openmeter/billing/invoiceline.go (2)
  • InvoiceLineTypeUsageBased (32-32)
  • InvoiceLineStatusValid (46-46)
openmeter/billing/service/lineservice/priceunit_test.go (5)
openmeter/productcatalog/discount.go (3)
  • NewDiscountFrom (234-247)
  • PercentageDiscount (255-258)
  • Discounts (346-346)
pkg/models/percentage.go (1)
  • NewPercentage (15-28)
openmeter/productcatalog/price.go (2)
  • NewPriceFrom (342-364)
  • UnitPrice (426-431)
openmeter/billing/service/lineservice/usagebasedline.go (1)
  • UnitPriceUsageChildUniqueReferenceID (27-27)
openmeter/billing/invoicelinediscount.go (1)
  • NewLineDiscounts (693-695)
openmeter/billing/invoicelinediscount.go (1)
openmeter/ent/db/billinginvoicelinediscount/where.go (1)
  • RoundingAmount (111-113)
openmeter/billing/service/lineservice/feeline.go (4)
openmeter/billing/service/invoicecalc/calculator.go (1)
  • Calculator (19-21)
pkg/currencyx/currency.go (1)
  • Calculator (36-39)
openmeter/billing/service/lineservice/usagebasedline.go (1)
  • TotalAmount (352-358)
openmeter/productcatalog/discount.go (1)
  • Discounts (346-346)
openmeter/billing/service/lineservice/usagebasedline.go (4)
openmeter/productcatalog/discount.go (1)
  • Discounts (346-346)
openmeter/billing/service/invoicecalc/calculator.go (1)
  • Calculator (19-21)
pkg/currencyx/currency.go (1)
  • Calculator (36-39)
openmeter/billing/invoicelinediscount.go (1)
  • LineDiscounts (691-691)
openmeter/billing/service/lineservice/feeline_test.go (4)
openmeter/productcatalog/discount.go (2)
  • PercentageDiscount (255-258)
  • NewDiscountFrom (234-247)
pkg/models/percentage.go (1)
  • NewPercentage (15-28)
openmeter/billing/invoicelinediscount.go (4)
  • LineDiscount (290-328)
  • NewLineDiscountFrom (402-429)
  • AmountLineDiscount (101-109)
  • LineDiscountBase (63-70)
openmeter/billing/invoiceline.go (1)
  • FlatFeeLine (259-266)
openmeter/billing/service/lineservice/discountpercentage.go (8)
openmeter/billing/service/lineservice/pricemutate.go (1)
  • PostCalculationMutator (10-12)
openmeter/billing/service/lineservice/pricer.go (1)
  • PricerCalculateInput (16-21)
pkg/slicesx/map.go (1)
  • MapWithErr (23-47)
openmeter/billing/service/lineservice/usagebasedline.go (1)
  • TotalAmount (352-358)
openmeter/productcatalog/discount.go (3)
  • Discounts (346-346)
  • PercentageDiscount (255-258)
  • PercentageDiscountType (16-16)
openmeter/ent/db/app/where.go (1)
  • Type (100-103)
openmeter/billing/invoicelinediscount.go (3)
  • AmountLineDiscount (101-109)
  • LineDiscountBase (63-70)
  • LineDiscountReasonRatecardDiscount (29-29)
openmeter/ent/db/billinginvoicelinediscount/where.go (1)
  • RoundingAmount (111-113)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Lint
  • GitHub Check: Commit hooks
  • GitHub Check: Developer environment
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (16)
openmeter/billing/invoicelinediscount.go (1)

108-108:

Details

❓ Verification inconclusive

JSON tag updated from "rounding" to "roundingAmount"

The JSON tag for the RoundingAmount field has been changed from json:"rounding" to json:"roundingAmount". This change aligns the field name with its usage in the database predicates (as seen in the billinginvoicelinediscount/where.go file) and improves naming consistency.

Have you verified that this change won't break backward compatibility for existing API clients that might be relying on the "rounding" field name? Consider if a migration strategy is needed.


🏁 Script executed:

#!/bin/bash
# Look for API usages of the rounding field in JSON
rg -i "rounding\"\s*:" --type json

Length of output: 35


Action Required: Verify Backward Compatibility for JSON Tag Renaming

The JSON tag for the RoundingAmount field was updated from "rounding" to "roundingAmount" in openmeter/billing/invoicelinediscount.go (line 108) to align with naming in the predicates used in billinginvoicelinediscount/where.go. An automated scan for JSON usages of "rounding" did not return any hits, but this result isn’t conclusive for confirming that no external API clients rely on the old field name.

  • Ensure that no serialized JSON payloads (from API responses or configuration files) continue to use the "rounding" field.
  • Manually verify potential client dependencies—particularly those not captured by the repository-wide JSON search.
  • Consider documenting or implementing a migration strategy (or providing a fallback) if any legacy API clients expect "rounding".

Please re-check API contracts and external integrations to confirm that this change won’t cause breaking changes.

openmeter/billing/service/lineservice/usagebasedline_test.go (2)

33-33: Field addition supports percentage discount testing

The new discounts field in the test case struct enables testing the discount functionality for usage-based pricing, which is key for implementing the percentage discounts feature described in the PR objectives.


55-55: Added rate card discounts integration

The test now correctly passes the discount information from the test case to the line's billing structure, enabling proper testing of discount calculations during test execution.

openmeter/billing/service/lineservice/feeline.go (2)

35-39: Updated method to support percentage discounts

The CalculateDetailedLines method has been refactored to use the new percentage discount implementation, aligning with the PR objective of implementing percentage discounts for fee lines.


41-72: Well-structured implementation of percentage discount logic

The new applyPercentageDiscounts method properly handles:

  1. Retrieving discounts from the rate card
  2. Calculating the currency and total amount
  3. Applying the discounts to the line
  4. Appropriate error handling throughout

The implementation correctly applies percentage discounts to fee lines without using the middleware/pricer system as mentioned in the PR objectives.

openmeter/billing/service/lineservice/priceunit_test.go (3)

11-11: Added models package import

The models package is required for creating percentage discount instances in the new test cases.


205-265: Comprehensive test case for discount percentage with maximum spend

This test case thoroughly validates the interaction between percentage discounts and maximum spend limits. The detailed comments explaining the calculation logic are helpful for understanding the expected behavior:

  • 50% discount on a usage amount
  • Maximum spend limit that gets exceeded
  • Verification that both discounts are properly applied

The test ensures that percentage discounts are calculated before the maximum spend discount is applied, which is the correct order of operations.


267-331: Thorough test for cumulative discounts and rounding behavior

This test case validates an important edge case: when multiple percentage discounts (33%+33%+34%) sum to 100%, the final amount should be zero. The test verifies:

  1. Correct application of multiple percentage discounts
  2. Proper handling of rounding amounts to ensure the sum is accurate
  3. The expected behavior when discounts completely offset the original amount

The test includes appropriate assertions to verify the correctness of the rounding amount field, which aligns with the JSON tag change in invoicelinediscount.go.

openmeter/billing/service/lineservice/feeline_test.go (1)

75-85: Well-implemented test helper function.

The ExpectJSONEqual function is a clean helper for comparing complex objects in tests. It properly marshals both objects to JSON and uses require.JSONEq for comparison.

openmeter/billing/service/lineservice/usagebasedline.go (4)

38-38: Good addition of a constant for reference ID format.

Adding the RateCardDiscountChildUniqueReferenceID constant eliminates magic strings and provides consistency with other reference ID constants in the codebase.


270-270: Valid integration of discount percentage mutator.

The discountPercentageMutator is correctly added to the PostCalculation slice, ensuring that percentage discounts will be applied during the pricing calculation workflow.


336-343: Good refactoring for improved reusability.

The TotalAmount method has been refactored to use a new helper function, which enhances code reusability and maintainability.


345-358: Effective extraction of calculation logic.

The introduction of the getTotalAmountInput struct and TotalAmount function is a good refactoring that makes the code more modular and easier to maintain. The function clearly separates the calculation steps for better readability.

openmeter/billing/service/lineservice/discountpercentage.go (3)

21-50: Well-structured mutator implementation.

The Mutate method is well-implemented with proper error handling and early returns for the case when no discounts are available. The use of slicesx.MapWithErr for transforming the pricerResult is also a good pattern.


57-76: Effective discount extraction and filtering.

The getDiscounts method correctly filters for percentage discounts and associates them with unique reference IDs. The error handling for invalid discount types is also appropriate.


85-87: Good validation for discount percentage limit.

The code correctly validates that the total discount percentage doesn't exceed 100%, which is an important business rule to prevent negative prices.

@turip
turip force-pushed the feat/percentage-discounts branch from 00117c3 to f3f242c Compare April 9, 2025 08:03
@turip
turip force-pushed the feat/percentage-discounts branch from f3f242c to 158a3a5 Compare April 9, 2025 08:03

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
openmeter/billing/service/lineservice/usagebasedline.go (1)

345-359: Consider clamping negative totals to zero.
If the sum of discounts exceeds the product of PerUnitAmount * Quantity, the resulting total becomes negative. You may want to clamp it to zero to avoid negative charges.

Apply this optional diff:

 func TotalAmount(in getTotalAmountInput) alpacadecimal.Decimal {
  total := in.Currency.RoundToPrecision(in.PerUnitAmount.Mul(in.Quantity))
  total = total.Sub(in.Discounts.SumAmount(in.Currency))
+ if total.IsNegative() {
+   total = alpacadecimal.Zero
+ }
  return total
 }
openmeter/billing/service/lineservice/discountpercentage.go (2)

57-76: Validate individual discount ranges.
You might consider validating each discount’s percentage (e.g., ensuring it’s between 0% and 100%) inside getDiscounts so you can fail early if any single discount is invalid.

 for idx, discount := range discounts {
   if discount.Type() != productcatalog.PercentageDiscountType {
     continue
   }
   percentage, err := discount.AsPercentage()
   if err != nil {
     return nil, err
   }
+  if percentage.GreaterThan(alpacadecimal.NewFromInt(100)) || percentage.IsNegative() {
+    return nil, fmt.Errorf("invalid discount percentage at index %%d: %%s", idx, percentage.String())
+  }
   ...
 }

78-130: Review the rounding distribution logic.
The current approach applies the rounding difference to the first discount from the end that can handle it. If none satisfy the check, the rounding difference is discarded. Consider a fallback or distributing the difference across multiple discounts.

Would you like me to propose a more robust distribution approach for the rounding difference?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 00117c3 and 158a3a5.

📒 Files selected for processing (8)
  • openmeter/app/stripe/entity/app/invoice.go (1 hunks)
  • openmeter/billing/invoicelinediscount.go (1 hunks)
  • openmeter/billing/service/lineservice/discountpercentage.go (1 hunks)
  • openmeter/billing/service/lineservice/feeline.go (1 hunks)
  • openmeter/billing/service/lineservice/feeline_test.go (1 hunks)
  • openmeter/billing/service/lineservice/priceunit_test.go (2 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (3 hunks)
  • openmeter/billing/service/lineservice/usagebasedline_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • openmeter/billing/service/lineservice/usagebasedline_test.go
  • openmeter/billing/invoicelinediscount.go
🧰 Additional context used
🧬 Code Graph Analysis (6)
openmeter/app/stripe/entity/app/invoice.go (2)
openmeter/ent/db/billinginvoicediscount/where.go (1)
  • Amount (105-107)
openmeter/ent/db/billinginvoicelinediscount/where.go (1)
  • Amount (106-108)
openmeter/billing/service/lineservice/priceunit_test.go (5)
openmeter/productcatalog/discount.go (3)
  • NewDiscountFrom (234-247)
  • PercentageDiscount (255-258)
  • Discounts (346-346)
pkg/models/percentage.go (1)
  • NewPercentage (15-28)
openmeter/productcatalog/price.go (2)
  • NewPriceFrom (342-364)
  • UnitPrice (426-431)
openmeter/billing/service/lineservice/usagebasedline.go (1)
  • UnitPriceUsageChildUniqueReferenceID (27-27)
openmeter/billing/invoicelinediscount.go (1)
  • NewLineDiscounts (693-695)
openmeter/billing/service/lineservice/feeline_test.go (3)
openmeter/productcatalog/discount.go (1)
  • PercentageDiscount (255-258)
pkg/models/percentage.go (1)
  • NewPercentage (15-28)
openmeter/billing/invoicelinediscount.go (3)
  • LineDiscount (290-328)
  • LineDiscountBase (63-70)
  • LineDiscountReasonRatecardDiscount (29-29)
openmeter/billing/service/lineservice/usagebasedline.go (4)
openmeter/productcatalog/discount.go (1)
  • Discounts (346-346)
openmeter/billing/service/invoicecalc/calculator.go (1)
  • Calculator (19-21)
pkg/currencyx/currency.go (1)
  • Calculator (36-39)
openmeter/billing/invoicelinediscount.go (1)
  • LineDiscounts (691-691)
openmeter/billing/service/lineservice/discountpercentage.go (6)
openmeter/billing/service/lineservice/pricemutate.go (1)
  • PostCalculationMutator (10-12)
openmeter/billing/service/lineservice/pricer.go (1)
  • PricerCalculateInput (16-21)
pkg/slicesx/map.go (1)
  • MapWithErr (23-47)
openmeter/billing/service/lineservice/usagebasedline.go (2)
  • TotalAmount (352-358)
  • RateCardDiscountChildUniqueReferenceID (38-38)
openmeter/productcatalog/discount.go (3)
  • Discounts (346-346)
  • PercentageDiscount (255-258)
  • PercentageDiscountType (16-16)
openmeter/billing/invoicelinediscount.go (3)
  • AmountLineDiscount (101-109)
  • LineDiscountBase (63-70)
  • LineDiscountReasonRatecardDiscount (29-29)
openmeter/billing/service/lineservice/feeline.go (4)
openmeter/billing/service/invoicecalc/calculator.go (1)
  • Calculator (19-21)
pkg/currencyx/currency.go (1)
  • Calculator (36-39)
openmeter/billing/service/lineservice/usagebasedline.go (1)
  • TotalAmount (352-358)
openmeter/productcatalog/discount.go (1)
  • Discounts (346-346)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Analyze (go)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Build
🔇 Additional comments (14)
openmeter/app/stripe/entity/app/invoice.go (1)

446-446: Enhancement to include rounding amount in discount calculation

The change adds discount.RoundingAmount to the discount amount calculation, ensuring more accurate representation of percentage-based discounts where rounding adjustments are needed.

openmeter/billing/service/lineservice/feeline.go (2)

35-39: Good implementation of percentage discounts for fee lines

The comment clearly explains that fee lines only have percentage discounts, and the method now delegates to the new applyPercentageDiscounts() method.


41-72: Well-structured implementation of percentage discount application

This new method handles the application of percentage discounts to fee lines with proper error handling at each step. The implementation follows a clear logical flow:

  1. Initialize the discount percentage mutator
  2. Get applicable discounts from rate card
  3. Early return if no discounts
  4. Get currency calculator
  5. Calculate total amount
  6. Get line discounts
  7. Add discounts to the line
openmeter/billing/service/lineservice/priceunit_test.go (3)

11-11: Added models package import for percentage discount functionality

The import enables the use of percentage models needed for discount calculations in the tests.


204-265: Comprehensive test for percentage discount with maximum spend limit

The test thoroughly validates the interaction between percentage discounts and maximum spend limits, with detailed comments explaining the expected calculations:

  • 50% discount applied to usage amount
  • Maximum spend limit enforced
  • Appropriate discount line items generated with correct amounts

The test ensures that both discount types work correctly together, which is an important edge case.


267-331: Great edge case test for cumulative discounts

This test validates that multiple percentage discounts (33%+33%+34%) applied to a small amount (0.01) correctly handle rounding behavior. The test includes:

  • Detailed comments explaining the expected calculation
  • Validation of rounding amount field for precise accounting
  • Verification that the combined discounts total to the original amount

This is exactly the kind of edge case that needs testing for financial calculations.

openmeter/billing/service/lineservice/feeline_test.go (4)

17-44: Well-structured test for fee line percentage discount

The test effectively validates the basic scenario of applying a 50% discount to a fee line. It:

  1. Creates a fee line with appropriate test data
  2. Applies discount calculation
  3. Verifies the resulting discount structure and amount

46-50: Clean type definition for test input

The generateFeeLineInput type provides a clear structure for test parameters, making test cases easy to understand and maintain.


52-73: Good test helper implementation

The generateFeeLine function creates a properly structured test object with all necessary fields, including:

  • Currency configuration
  • Time period
  • Rate card discounts conversion
  • Flat fee configuration

This makes test setup cleaner and more maintainable.


75-85: Useful JSON comparison utility

The ExpectJSONEqual function provides a clean way to compare complex objects by converting them to JSON. This approach:

  • Simplifies assertions for complex nested structures
  • Provides clear error messages when comparison fails
  • Marks itself as a test helper for better test output
openmeter/billing/service/lineservice/usagebasedline.go (3)

38-38: Constant introduction looks good.
This new constant correctly aligns with naming for discount child references.


270-270: Verify the mutator ordering.
Please confirm the desired calculation order of the discount percentage mutator relative to the other mutators. The current order is discount first, then max/min commitments. Depending on your pricing business rules, you may want to apply discount after or before other mutators.

Would you like me to generate a script to locate references to these mutators across the codebase and summarize how they interact?


337-343: Ensure discount logic is not double-applied.
The call to TotalAmount subtracts discounts from the line total. Double-check that you aren’t subtracting discounts again in other downstream logic. Otherwise, this looks well-structured.

openmeter/billing/service/lineservice/discountpercentage.go (1)

21-50: Discount application logic looks solid.
Using MapWithErr to transform line inputs ensures that each line is processed independently and avoids partial failures. Good approach!

@turip
turip merged commit 5e64648 into main Apr 9, 2025
@turip
turip deleted the feat/percentage-discounts branch April 9, 2025 08:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants