Skip to content

feat: usage discounts - #2634

Merged
turip merged 1 commit into
mainfrom
feat/usage-discounts
Apr 15, 2025
Merged

turip merged 1 commit into
mainfrom
feat/usage-discounts

Conversation

@turip

@turip turip commented Apr 9, 2025 •

Copy link
Copy Markdown
Member

Overview

This patch implements the usage discount support.

If a line is progressive billed (e.g. there's already a line split happened) we are not allowing to change the usage discount for consistency purposes.

Summary by CodeRabbit

  • New Features

    • Enhanced usage-based billing by incorporating actual metered data into pricing and discount calculations.
    • Introduced pre-calculation steps to ensure billing quantities align accurately with metered usage.
    • Added a new error for invoice line processing to enhance validation.
    • Enabled cloning and merging of usage line discounts for improved discount management.
  • Refactor

    • Optimized logic for progressive billing to prevent unintended discount updates on partially invoiced lines.
    • Standardized the approach across various pricing models for more reliable billing outcomes.
    • Streamlined the calculation process by integrating additional pre-calculation logic.
    • Refined progressive billing hierarchy handling and net amount summation for clarity and maintainability.
  • Tests

    • Added comprehensive tests covering progressive billing scenarios to verify accurate discount and usage calculations.

@coderabbitai

coderabbitai Bot commented Apr 9, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request introduces multiple changes to the billing system. A new error is added for handling updates to usage discounts on partially invoiced lines, along with validation logic in invoice line processing. The management of discounts is enhanced through the implementation of cloning and merging methods. Various pricing functions are refactored to utilize new getters for usage data, and new pre-calculation mutators are integrated into the pricing flow. Additionally, one method is removed, and a test is added to verify unit discount behavior under progressive billing scenarios.

Changes

File(s) Change Summary
openmeter/.../errors.go Added new error variable ErrInvoiceLineProgressiveBillingUsageDiscountUpdateForbidden for usage discount updates on partially invoiced lines.
openmeter/.../httpdriver/invoiceline.go Introduced validation in mergeLineFromInvoiceLineReplaceUpdate to prevent rate card discount updates on progressively billed lines (checks for ParentLineID and uses equal.PtrEqual).
openmeter/.../invoicelinediscount.go Enhanced UsageLineDiscountsManaged by asserting Clonable interface and adding Clone and MergeDiscountsByChildUniqueReferenceID methods.
openmeter/.../invoicelineprogressive.go Updated SumNetAmountInput: renamed field from UpTo to PeriodEndLTE; refactored SumNetAmount to use a callback via new ForEachChild method.
openmeter/.../lineservice/commitments.go Renamed parameter in getPreviouslyBilledAmount from UpTo to PeriodEndLTE.
openmeter/.../lineservice/discountusage.go,
openmeter/.../lineservice/meteredquantity.go
New files: Added discountUsageMutator (with methods for discount mutation, removal, retrieval, and usage quantity calculations) and setQuantityToMeteredQuantity mutator to reset quantities using metered values.
openmeter/.../lineservice/pricedynamic.go,
openmeter/.../lineservice/pricegraduatedtiered.go,
openmeter/.../lineservice/pricepackage.go,
openmeter/.../lineservice/priceunit.go,
openmeter/.../lineservice/pricevolumetiered.go
Modified pricing Calculate methods to obtain usage data via GetUsage(), shifting quantity references from direct fields to usage-based values and enhancing error handling.
openmeter/.../lineservice/pricemutate.go Added new PreCalculationMutator interface and a PreCalculation slice field to priceMutator, iterating mutators in the calculation flow.
openmeter/.../lineservice/pricer.go Updated PricerCalculateInput to be a type alias for usageBasedLine; introduced new usage struct with LinePeriodQuantity and PreLinePeriodQuantity fields along with GetUsage and LinePeriodQuantity methods.
openmeter/.../lineservice/usagebasedline.go Removed the asPricerCalculateInput method and updated calculateDetailedLines to use a direct type conversion; enhanced getPricer to incorporate pre-calculation mutators.
test/.../discount_test.go Added test function TestUnitDiscountProgressiveBilling to validate multiple scenarios for unit discounts under progressive billing.

Possibly related PRs

  • feat: discount correlation ID #2636: Introduces discount correlation IDs for tracking discounts across invoices, related to managing usage discount consistency and correlation IDs in billing discounts.
  • refactor: allow single discount per type #2639: Refactors discount data structures to separate usage and amount discounts and restricts discounts per type, related to restructuring and validation of usage discounts on invoice lines.

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 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/usage-discounts branch from fefc04f to 23ec5ca Compare April 9, 2025 13:17
@turip
turip changed the base branch from main to feat/discount-groups April 9, 2025 13:17
@turip
turip force-pushed the feat/discount-groups branch 2 times, most recently from 095ed01 to 5507a83 Compare April 9, 2025 14:33
@turip
turip force-pushed the feat/usage-discounts branch 2 times, most recently from 7005b61 to b954137 Compare April 9, 2025 15:20
@turip
turip force-pushed the feat/discount-groups branch from 6969b17 to b9aad73 Compare April 9, 2025 15:23
Base automatically changed from feat/discount-groups to main April 9, 2025 15:46
@turip
turip force-pushed the feat/usage-discounts branch 4 times, most recently from 4a5b2c0 to 344d466 Compare April 11, 2025 13:31
@turip
turip changed the base branch from main to feat/record-pre-line-metered-quantity April 11, 2025 13:31
Base automatically changed from feat/record-pre-line-metered-quantity to main April 11, 2025 13:48
@turip
turip force-pushed the feat/usage-discounts branch 2 times, most recently from 4aaedc7 to 24d4f51 Compare April 11, 2025 14:16
@turip turip changed the title Feat/usage discounts feat: usage discounts Apr 11, 2025
@turip
turip force-pushed the feat/usage-discounts branch from 24d4f51 to 37dfe26 Compare April 11, 2025 14:19
@turip turip added release-note/feature Release note: Exciting New Features area/billing labels Apr 11, 2025
@turip
turip marked this pull request as ready for review April 11, 2025 14:20
@turip
turip requested a review from a team as a code owner April 11, 2025 14:20
@turip
turip requested a review from chrisgacsal April 11, 2025 14:20

@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: 2

🧹 Nitpick comments (5)
openmeter/billing/service/lineservice/pricemutate.go (3)

6-6: Add a short doc comment for the PreCalculation field.

It's beneficial to clearly describe when and how the PreCalculation mutators should be used. This helps future maintainers understand its purpose within the struct.


15-17: Document the PreCalculationMutator interface.

Providing a brief doc comment for the newly introduced interface clarifies the contract and expectations for any future implementations.


22-30: Consider customized error handling or rollback logic for partial failures.

Currently, if any mutator in the loop fails, the entire calculation returns immediately. Depending on business requirements, you may want to roll back changes from previously successful mutators or allow partial application. Ensure this approach aligns with the desired user experience.

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

17-19: Be mindful of non-idempotent mutation logic.
Since this mutator directly manipulates the usage-based line rather than derived lines, multiple calls could result in inconsistent states if the function is incorrectly re-invoked. Consider clarifying usage patterns or providing safeguards to avoid repeated mutation calls.


58-60: Handle overcommitted usage discounts more gracefully.
Currently, the function returns an error if the discount is overcommitted. Depending on business requirements, you may want to provide a fallback, such as automatically removing or reducing the discount instead of failing outright.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f637134 and 37dfe26.

📒 Files selected for processing (16)
  • openmeter/billing/errors.go (1 hunks)
  • openmeter/billing/httpdriver/invoiceline.go (2 hunks)
  • openmeter/billing/invoicelinediscount.go (1 hunks)
  • openmeter/billing/invoicelineprogressive.go (3 hunks)
  • openmeter/billing/service/lineservice/commitments.go (1 hunks)
  • openmeter/billing/service/lineservice/discountusage.go (1 hunks)
  • openmeter/billing/service/lineservice/meteredquantity.go (1 hunks)
  • openmeter/billing/service/lineservice/pricedynamic.go (1 hunks)
  • openmeter/billing/service/lineservice/pricegraduatedtiered.go (2 hunks)
  • openmeter/billing/service/lineservice/pricemutate.go (2 hunks)
  • openmeter/billing/service/lineservice/pricepackage.go (1 hunks)
  • openmeter/billing/service/lineservice/pricer.go (2 hunks)
  • openmeter/billing/service/lineservice/priceunit.go (1 hunks)
  • openmeter/billing/service/lineservice/pricevolumetiered.go (2 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (2 hunks)
  • test/billing/discount_test.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (11)
openmeter/billing/service/lineservice/commitments.go (1)
openmeter/billing/invoiceline.go (1)
  • Period (83-86)
openmeter/billing/errors.go (1)
openmeter/billing/validationissue.go (1)
  • NewValidationError (75-81)
openmeter/billing/service/lineservice/pricemutate.go (1)
openmeter/billing/service/lineservice/pricer.go (2)
  • PricerCalculateInput (17-17)
  • Pricer (45-51)
openmeter/billing/httpdriver/invoiceline.go (3)
openmeter/billing/discount.go (1)
  • Discounts (78-81)
pkg/equal/equal.go (1)
  • PtrEqual (13-23)
openmeter/billing/errors.go (2)
  • ValidationError (117-117)
  • ErrInvoiceLineProgressiveBillingUsageDiscountUpdateForbidden (50-50)
openmeter/billing/invoicelineprogressive.go (2)
openmeter/billing/invoiceline.go (2)
  • Line (279-293)
  • Period (83-86)
openmeter/billing/totals.go (1)
  • Totals (9-26)
openmeter/billing/service/lineservice/meteredquantity.go (3)
openmeter/billing/service/lineservice/pricemutate.go (1)
  • PreCalculationMutator (15-17)
openmeter/billing/service/lineservice/pricer.go (1)
  • PricerCalculateInput (17-17)
openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (2)
  • MeteredPreLinePeriodQuantity (83-85)
  • MeteredQuantity (88-90)
openmeter/billing/service/lineservice/usagebasedline.go (2)
openmeter/billing/service/lineservice/pricemutate.go (1)
  • PreCalculationMutator (15-17)
openmeter/billing/service/lineservice/pricer.go (1)
  • PricerCalculateInput (17-17)
test/billing/discount_test.go (3)
openmeter/billing/invoiceline.go (5)
  • Line (279-293)
  • LineBase (128-162)
  • Period (83-86)
  • UsageBasedLine (703-716)
  • Price (701-701)
openmeter/billing/discount.go (2)
  • Discounts (78-81)
  • UsageDiscount (49-53)
openmeter/billing/invoice.go (1)
  • InvoicePendingLinesInput (761-766)
openmeter/billing/service/lineservice/discountusage.go (5)
openmeter/billing/service/lineservice/pricemutate.go (1)
  • PreCalculationMutator (15-17)
openmeter/billing/service/lineservice/pricer.go (1)
  • PricerCalculateInput (17-17)
openmeter/billing/invoicelinediscount.go (3)
  • UsageLineDiscountManaged (254-257)
  • UsageLineDiscount (205-210)
  • LineDiscountBase (22-27)
openmeter/billing/discount.go (1)
  • RatecardUsageDiscountReason (133-133)
openmeter/billing/service/lineservice/usagebasedline.go (1)
  • RateCardDiscountChildUniqueReferenceID (38-38)
openmeter/billing/service/lineservice/pricevolumetiered.go (2)
openmeter/billing/errors.go (1)
  • ErrInvoiceLineVolumeSplitNotSupported (45-45)
openmeter/productcatalog/price.go (1)
  • UnitPrice (426-431)
openmeter/billing/invoicelinediscount.go (2)
pkg/models/clonable.go (1)
  • Clonable (3-5)
pkg/models/model.go (2)
  • ManagedModelWithID (155-158)
  • ManagedModel (107-113)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (37)
openmeter/billing/service/lineservice/commitments.go (1)

104-104: Parameter name change aligns with broader refactoring.

The parameter rename from UpTo to PeriodEndLTE in the SumNetAmountInput struct enhances clarity and aligns with similar changes elsewhere in the codebase. This standardization improves code consistency in how billing periods are handled.

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

21-24: Good addition of usage data retrieval with error handling.

Retrieving usage data through GetUsage() with proper error handling improves robustness and follows good software engineering practices. This encapsulation allows for better data access control and validation.


26-26: Consistent usage of the retrieved usage object.

The implementation correctly uses the obtained usage data for calculations, replacing direct access to line quantities with structured usage properties. This change is consistent with the other pricer implementations in the codebase.

Also applies to: 30-30

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

18-21: Improved error handling with GetUsage() implementation.

The addition of proper error handling when retrieving usage data follows good practices. This approach consistently handles potential errors that might occur during usage data retrieval, enhancing the robustness of the package pricer.


28-28: Consistent usage of encapsulated usage data.

The implementation correctly transitions from direct access to properly using the encapsulated usage data properties. This maintains the same calculation logic while improving the overall architecture.

Also applies to: 30-30

openmeter/billing/errors.go (1)

50-50: New error for usage discount updates on progressively billed lines.

This new error definition properly implements the requirement to prevent usage discount changes on partially invoiced lines. It follows the established error pattern in the codebase and provides a clear, specific error message to end users.

The error is appropriately integrated into the validation framework and supports the PR objective of implementing usage discounts with restrictions on progressively billed lines.

openmeter/billing/httpdriver/invoiceline.go (1)

17-17: Import usage looks correct.

The equal package is referenced below for pointer equality checks, aligning with the new discount validation logic. No issues here.

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

18-21: Check for unexpected nil or zero usage cases.

While retrieving usage data here is correct, consider verifying upstream that the usage will not be nil or otherwise invalid. If usage retrieval can fail in other ways, adding more specific error handling might improve debuggability.


28-30: Logic to calculate amounts based on usage data looks good.

Switching to usage.LinePeriodQuantity for the main calculation aligns well with usage-based pricing. This improves clarity concerning how the system determines the relevant quantity.

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

19-22: Enhanced error handling with GetUsage

The addition of the usage retrieval step improves the code by centralizing access to usage data and providing immediate error handling.


37-38: Consistent usage data access pattern

These changes ensure quantities are properly sourced from the usage object, making the calculation more accurate and maintainable by using a consistent data access pattern.

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

9-14: Well-documented mutator purpose

The comment clearly explains the purpose of the mutator - to reset quantities to metered values before discount application, which helps maintain code clarity.


15-35: Thorough validation in Mutate method

The implementation correctly validates all required fields before performing updates and provides clear error messages that include the specific line ID for easier debugging.

The approach of copying decimal values with .Copy() rather than direct assignment prevents potential issues with shared references.

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

33-37: Proper usage data retrieval and error handling

The addition of usage data retrieval with immediate error propagation improves error handling and maintains consistency with other pricing implementations.


38-41: Important validation check preserved

The condition checking has been migrated to use the new usage object while maintaining the critical validation that prevents inappropriate use of progressive billing with volume tiered pricing.


45-45: Consistent usage of retrieved quantities

These line changes ensure that all quantity references throughout the pricer use the same source of truth from the usage object, maintaining consistency across the calculation flow.

Also applies to: 65-65, 68-68

test/billing/discount_test.go (6)

205-228: Comprehensive test scenario description

The test header provides a clear explanation of the scenario and expected outcomes for each of the three invoices, making the test purpose and validation criteria easy to understand.


229-282: Well-structured test setup

The test preparation is thorough, creating all necessary prerequisites including a billing profile with progressive billing enabled, a test customer, and appropriate meter setup with the correct feature configuration.


283-326: Proper discount initialization

This section correctly sets up the initial state with a usage discount of 110 units and verifies that the system generates a correlation ID as expected.


327-366: First invoice validation

The first test case correctly validates:

  1. The metered quantity of 50 vs quantity of 0
  2. The usage discount application with quantity 50
  3. The correlation ID preservation
  4. The absence of child lines when no billable usage exists

This is a critical test case that verifies the initial discount behavior.


368-410: Second invoice progressive validation

This test case thoroughly verifies the correct handling of accumulated usage across invoices:

  1. The metered quantity of 75 vs billable quantity of 15
  2. The usage discount with correct quantity (60) and proper tracking of pre-period quantity (50)
  3. The preservation of the original discount amount (110) in the correlation metadata
  4. The existence of a child line with the correct quantity (15)

This properly tests the progressive nature of the discount application.


412-442: Final invoice exhaust-discount validation

The final test case correctly validates the exhaustion of the discount:

  1. The metered quantity equals the billable quantity (30)
  2. The absence of any usage discount (fully consumed by previous invoices)
  3. The proper tracking of pre-period quantities
  4. The child line with correct quantity (30)

This scenario completes the end-to-end testing of the discount lifecycle.

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

256-259: Added new pre-calculation mutators for better discount handling

The addition of discountUsageMutator to the PreCalculation mutators enhances the pricing flow by allowing usage discounts to be applied systematically. This is a good architectural approach that maintains separation of concerns and makes the discount logic more maintainable.


275-275: Simplified calculation input by using direct type conversion

The code now uses PricerCalculateInput(l) directly instead of calling the previously existing asPricerCalculateInput() method. This simplification is possible due to the type alias definition in pricer.go, making the code more concise while maintaining functionality.

Let's verify that this change maintains all the validation logic that was previously in the asPricerCalculateInput() method:

#!/bin/bash
# Search for any validation logic in the removed asPricerCalculateInput method
rg -A 10 -B 10 "func \(l usageBasedLine\) asPricerCalculateInput\(\)" 
openmeter/billing/service/lineservice/pricer.go (4)

17-17: Changed PricerCalculateInput to a type alias for better encapsulation

Converting PricerCalculateInput from a struct to a type alias for usageBasedLine simplifies the code by removing duplication and improving maintainability. This change enables direct type conversion in the calculateDetailedLines method.


19-22: Added new usage struct to encapsulate quantity data

The new usage struct provides better encapsulation of quantity-related data, making the code more maintainable and the data structure clearer.


24-39: Added GetUsage method with proper validation

This method provides robust validation for quantity data, ensuring both Quantity and PreLinePeriodQuantity are properly set before calculations proceed. The error messages are clear and include the line ID for easier debugging.


41-43: Added convenience method for accessing LinePeriodQuantity

This helper method provides a cleaner way to access the line period quantity directly, which improves code readability in places where only this value is needed without full validation.

openmeter/billing/invoicelinediscount.go (3)

303-303: Added type assertion for Clonable interface implementation

This explicit type assertion ensures that UsageLineDiscountsManaged properly implements the models.Clonable interface, which is good practice for maintaining type safety.


307-311: Implemented Clone method for UsageLineDiscountsManaged

The Clone method creates a proper deep copy of the discount collection, which is essential for preserving data integrity when manipulating discounts.


313-343: Added MergeDiscountsByChildUniqueReferenceID for discount management

This method implements a sophisticated discount merging strategy that maintains entity identity while updating content. The approach ensures:

  1. Existing discounts are preserved with their ID and creation timestamp
  2. New discounts are properly integrated
  3. Discounts are matched by their unique reference ID
  4. Soft-deletion flags aren't carried over

This is critical functionality for handling usage discounts in the context of progressive billing.

Let's verify the implementation with a test case:

#!/bin/bash
# Check for test coverage of the new merging functionality
rg -A 5 -B 5 "TestUnitDiscountProgressiveBilling" 
openmeter/billing/invoicelineprogressive.go (4)

37-37: Renamed field to PeriodEndLTE for better semantic clarity

Renaming UpTo to PeriodEndLTE improves the clarity of the API by making it explicit that the comparison uses less than or equal to logic on the period end time.


47-61: Refactored SumNetAmount to use ForEachChild pattern

This refactoring improves code organization by delegating the child iteration logic to a specialized method. The callback pattern used here makes the code more maintainable and enables future enhancements without changing the core traversal logic.


63-66: Added ForEachChildInput struct for callback-based processing

This new struct provides a clear contract for iterating over children with callbacks, promoting better code reusability and maintainability.


68-91: Implemented ForEachChild to standardize child line iteration

This method centralizes the logic for filtering and processing child lines based on specific criteria. It handles:

  1. Period end time filtering
  2. Skipping deleted lines
  3. Skipping lines from deleted invoices
  4. Applying the provided callback to valid lines

This is an excellent refactoring that follows the Single Responsibility Principle and will reduce code duplication across the codebase.

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

79-91: Usage discount merge logic appears correct.
Quality merging of usage discounts by child unique reference ID. This ensures the discount is neatly tracked and combined. No additional concerns here.


128-140: Progressive line hierarchy traversal is well-structured.
The method correctly iterates over child lines, checks for discount correlation, and aggregates used quantities. The approach appears robust for identifying partial usage in previously billed lines.

@turip
turip force-pushed the feat/usage-discounts branch from 37dfe26 to 353682c Compare April 11, 2025 15:26
@turip
turip enabled auto-merge (squash) April 11, 2025 15:26
@turip
turip requested a review from hekike April 11, 2025 15: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 (1)
openmeter/billing/invoicelineprogressive.go (1)

68-91: Well-implemented child iteration method

The ForEachChild method properly filters child lines based on the provided criteria and handles errors appropriately. This abstraction will make it easier to perform various operations on filtered child lines.

Note that line 71 now uses PeriodEndLTE instead of UpTo (as mentioned in the method's documentation on line 42), which is consistent with the rename in the SumNetAmountInput struct.

The documentation comment for SumNetAmount (lines 41-43) still references in.UpTo and should be updated to reference PeriodEndLTE for consistency:

// SumNetAmount returns the sum of the net amount (pre-tax) of the progressive billed line and its children
- // containing the values for all lines whose period's end is <= in.UpTo and are not deleted or not part of
+ // containing the values for all lines whose period's end is <= in.PeriodEndLTE and are not deleted or not part of
// an invoice that has been deleted.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 37dfe26 and 353682c.

📒 Files selected for processing (16)
  • openmeter/billing/errors.go (1 hunks)
  • openmeter/billing/httpdriver/invoiceline.go (2 hunks)
  • openmeter/billing/invoicelinediscount.go (1 hunks)
  • openmeter/billing/invoicelineprogressive.go (3 hunks)
  • openmeter/billing/service/lineservice/commitments.go (1 hunks)
  • openmeter/billing/service/lineservice/discountusage.go (1 hunks)
  • openmeter/billing/service/lineservice/meteredquantity.go (1 hunks)
  • openmeter/billing/service/lineservice/pricedynamic.go (1 hunks)
  • openmeter/billing/service/lineservice/pricegraduatedtiered.go (2 hunks)
  • openmeter/billing/service/lineservice/pricemutate.go (2 hunks)
  • openmeter/billing/service/lineservice/pricepackage.go (1 hunks)
  • openmeter/billing/service/lineservice/pricer.go (2 hunks)
  • openmeter/billing/service/lineservice/priceunit.go (1 hunks)
  • openmeter/billing/service/lineservice/pricevolumetiered.go (2 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (2 hunks)
  • test/billing/discount_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (10)
  • openmeter/billing/service/lineservice/commitments.go
  • openmeter/billing/service/lineservice/priceunit.go
  • openmeter/billing/service/lineservice/pricedynamic.go
  • openmeter/billing/service/lineservice/pricepackage.go
  • openmeter/billing/httpdriver/invoiceline.go
  • openmeter/billing/service/lineservice/pricevolumetiered.go
  • openmeter/billing/service/lineservice/pricemutate.go
  • openmeter/billing/service/lineservice/pricegraduatedtiered.go
  • openmeter/billing/service/lineservice/pricer.go
  • openmeter/billing/service/lineservice/discountusage.go
🧰 Additional context used
🧬 Code Graph Analysis (6)
openmeter/billing/errors.go (1)
openmeter/billing/validationissue.go (1)
  • NewValidationError (75-81)
test/billing/discount_test.go (4)
openmeter/billing/profile.go (1)
  • WorkflowConfig (36-40)
openmeter/billing/invoiceline.go (3)
  • Line (279-293)
  • LineBase (128-162)
  • UsageBasedLine (703-716)
openmeter/billing/discount.go (2)
  • Discounts (78-81)
  • UsageDiscount (49-53)
openmeter/billing/invoice.go (1)
  • InvoicePendingLinesInput (761-766)
openmeter/billing/service/lineservice/usagebasedline.go (2)
openmeter/billing/service/lineservice/pricemutate.go (1)
  • PreCalculationMutator (15-17)
openmeter/billing/service/lineservice/pricer.go (1)
  • PricerCalculateInput (17-17)
openmeter/billing/invoicelineprogressive.go (2)
openmeter/billing/invoiceline.go (2)
  • Line (279-293)
  • Period (83-86)
openmeter/billing/totals.go (1)
  • Totals (9-26)
openmeter/billing/service/lineservice/meteredquantity.go (3)
openmeter/billing/service/lineservice/pricemutate.go (1)
  • PreCalculationMutator (15-17)
openmeter/billing/service/lineservice/pricer.go (1)
  • PricerCalculateInput (17-17)
openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (2)
  • MeteredPreLinePeriodQuantity (83-85)
  • MeteredQuantity (88-90)
openmeter/billing/invoicelinediscount.go (2)
pkg/models/clonable.go (1)
  • Clonable (3-5)
pkg/models/model.go (2)
  • ManagedModelWithID (155-158)
  • ManagedModel (107-113)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Test
  • GitHub Check: Migration Checks
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Build
  • GitHub Check: Lint
  • GitHub Check: Analyze (go)
🔇 Additional comments (11)
openmeter/billing/errors.go (1)

50-50: Added new validation error for usage discount updates.

This error prevents updates to usage discounts on partially invoiced lines, which aligns with the PR objective of ensuring that usage discounts cannot be modified once progressive billing has begun.

test/billing/discount_test.go (1)

205-443: Comprehensive test for unit discount behavior in progressive billing.

This test thoroughly validates the behavior of unit discounts through three stages of progressive billing:

  1. First invoice with 50 units usage (fully discounted)
  2. Second invoice with 75 units usage (partially discounted)
  3. Final invoice with 30 units usage (no discount remaining)

The test verifies that the discount is correctly applied across invoices and that the correlation ID remains consistent.

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

9-35: New mutator to reset quantity to metered quantity before discount application.

This mutator ensures that discounts are applied to the metered quantity rather than the original quantity, which is critical for correct pricing calculations with usage discounts. The implementation includes proper error handling for missing quantities and preserves value integrity through copying.

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

256-259: Added pre-calculation mutators to the pricing flow.

The code now includes both setQuantityToMeteredQuantity and discountUsageMutator in the pre-calculation step, ensuring that quantities are properly reset to metered values and usage discounts are correctly applied before price calculations.


275-275: Simplified calculateDetailedLines method.

The previous asPricerCalculateInput method call has been replaced with a direct type conversion, making the code more straightforward.

openmeter/billing/invoicelinediscount.go (3)

303-303: Type assertion ensures interface compliance

Good practice using the type assertion to ensure UsageLineDiscountsManaged implements the models.Clonable interface at compile time.


307-311: Clone implementation looks good

The implementation properly creates a deep copy of the slice by cloning each item, following Go best practices.


313-343: Merge implementation is well-structured

The method correctly handles the merging logic based on ChildUniqueReferenceID. When updating an existing discount, it preserves the original ID and creation timestamp while updating the content. This aligns with the PR objective of supporting usage discounts.

One consideration: when merging, if an existing discount is found, the method replaces it entirely with the new discount (except for ID and creation timestamp). Be aware that any other fields present in the old discount that aren't in the new discount will be lost.

Make sure this complete replacement behavior is intended rather than selectively updating fields. If you need more selective updates, consider modifying the implementation.

openmeter/billing/invoicelineprogressive.go (3)

37-37: Improved field naming for clarity

Changing from UpTo to PeriodEndLTE is a good improvement as it more clearly communicates that the field is used to filter lines whose period end is less than or equal to the specified time.


44-61: Good refactoring to callback-based approach

Refactoring SumNetAmount to use a callback-based approach with the new ForEachChild method improves code organization and separation of concerns. This makes the code more maintainable and extensible.


63-66: Well-structured input struct

The ForEachChildInput struct is cleanly designed for its purpose, making the API clear and self-documenting.

@turip
turip force-pushed the feat/usage-discounts branch from 353682c to f76e5cd Compare April 15, 2025 11:10

@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 (1)
openmeter/billing/service/lineservice/discountusage.go (1)

126-129: Typo in documentation comment

There's a minor typo in the documentation comment.

// calculateUsedQtyByCorrelationID calculates the used quantity by correlation ID for the previously billed lines
// by checking the UBP line's discounts. This works because usage discounts are presisted to the UBP line's discounts
-// by checking the UBP line's discounts. This works because usage discounts are presisted to the UBP line's discounts
+// by checking the UBP line's discounts. This works because usage discounts are persisted to the UBP line's discounts
// as they are affecting all the detailed lines.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 353682c and f76e5cd.

📒 Files selected for processing (16)
  • openmeter/billing/errors.go (1 hunks)
  • openmeter/billing/httpdriver/invoiceline.go (2 hunks)
  • openmeter/billing/invoicelinediscount.go (1 hunks)
  • openmeter/billing/invoicelineprogressive.go (3 hunks)
  • openmeter/billing/service/lineservice/commitments.go (1 hunks)
  • openmeter/billing/service/lineservice/discountusage.go (1 hunks)
  • openmeter/billing/service/lineservice/meteredquantity.go (1 hunks)
  • openmeter/billing/service/lineservice/pricedynamic.go (1 hunks)
  • openmeter/billing/service/lineservice/pricegraduatedtiered.go (2 hunks)
  • openmeter/billing/service/lineservice/pricemutate.go (2 hunks)
  • openmeter/billing/service/lineservice/pricepackage.go (1 hunks)
  • openmeter/billing/service/lineservice/pricer.go (2 hunks)
  • openmeter/billing/service/lineservice/priceunit.go (1 hunks)
  • openmeter/billing/service/lineservice/pricevolumetiered.go (2 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (2 hunks)
  • test/billing/discount_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (15)
  • openmeter/billing/service/lineservice/pricedynamic.go
  • openmeter/billing/errors.go
  • openmeter/billing/service/lineservice/pricepackage.go
  • openmeter/billing/service/lineservice/pricegraduatedtiered.go
  • openmeter/billing/service/lineservice/commitments.go
  • openmeter/billing/service/lineservice/pricevolumetiered.go
  • openmeter/billing/service/lineservice/pricer.go
  • openmeter/billing/httpdriver/invoiceline.go
  • openmeter/billing/service/lineservice/pricemutate.go
  • openmeter/billing/invoicelinediscount.go
  • openmeter/billing/service/lineservice/priceunit.go
  • openmeter/billing/service/lineservice/usagebasedline.go
  • test/billing/discount_test.go
  • openmeter/billing/invoicelineprogressive.go
  • openmeter/billing/service/lineservice/meteredquantity.go
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Lint
  • GitHub Check: Developer environment
  • GitHub Check: Test
  • GitHub Check: Commit hooks
  • GitHub Check: Migration Checks
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (9)
openmeter/billing/service/lineservice/discountusage.go (9)

17-23: Good warning comment about non-idempotence

The comment clearly explains that this mutator modifies the usage based line directly rather than the detailed lines. This is important for maintainers to understand the behavior and potential side effects.


34-38: Good defensive programming for null usage discount case

Properly handling the case when no usage discount is intended by removing any existing usage discounts ensures consistency in the billing system.


40-59: Clear error handling for overcommitted discount quantities

The code properly calculates used discount quantities for progressive billing scenarios and provides a clear error message when the discount is overcommitted. This prevents inconsistent billing states.


61-75: Robust discount quantity calculation logic

The implementation correctly handles edge cases:

  1. Applying the full discount quantity when possible
  2. Applying partial discount when remaining amount is less than needed
  3. Removing discount entirely when no quantity is available
  4. Maintaining consistent state with pre-line period quantities

This ensures correct discount application in all scenarios.


77-91: Clean implementation of discount merging and quantity updates

The code efficiently:

  1. Merges discounts by child reference ID
  2. Sets up the proper discount structure with reason and quantities
  3. Updates the line quantities to reflect the applied discount

This maintains consistency between discount records and actual billing quantities.


96-102: Efficient usage discount removal logic

The use of lo.Filter with a type-based condition makes for clean, maintainable code when removing usage discounts.


116-118: Good validation for missing correlation IDs

Validating that correlation IDs exist before proceeding prevents potential data inconsistencies later in the process.


136-165: Thorough child line processing for discount calculations

The implementation correctly:

  1. Iterates through child lines in the progressive billing hierarchy
  2. Filters discounts by type and correlation ID
  3. Validates discount consistency through child unique reference IDs
  4. Accumulates used quantities

This ensures accurate tracking of discount usage across billing periods.


150-158: Comprehensive validation for discount correlation consistency

The code includes important validation to ensure that:

  1. Correlation IDs exist and match the expected value
  2. Child unique reference IDs are consistent with the source discount

This helps maintain data integrity and prevent subtle billing errors.

@turip
turip merged commit 1569fe9 into main Apr 15, 2025
@turip
turip deleted the feat/usage-discounts branch April 15, 2025 11:43
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