Skip to content

feat: implement ubp flat fee - #2886

Merged
turip merged 2 commits into
mainfrom
feat/implement-ubp-flat-fee
May 27, 2025
Merged

turip merged 2 commits into
mainfrom
feat/implement-ubp-flat-fee

Conversation

@turip

@turip turip commented May 23, 2025 •

Copy link
Copy Markdown
Member

Overview

This patch ensures we have feature parity between a usage-based line with a flat price type and the flat fee line. This would allow us to:

  • only have usage-based lines on the invoice (then it would become the Line object)
  • group flat fee affecting price manipulations together
  • clean up the duality of flat fees being either present as a standard line or a detailed line

By default the usage based flat fee line has one detailed line: the flat fee line that we would have added by default.

This is dead code for now. It's not in use; everywhere, we use the flat fee lines instead.

Notes for reviewer

The following have not been altered [these will be separate prs]:

  • Subscription -> Billing sync
  • Invoice Update API to support setting quantity
  • Create Pending Lines API to support setting quantity
  • Data migration from flat fee lines to UBP Flat lines

Summary by CodeRabbit

  • New Features
    • Enabled support for usage-based flat fee billing lines, including creation, validation, and detailed line management.
    • Added support for applying percentage discounts to these lines.
  • Improvements
    • Made the feature key optional and nullable for usage-based line configurations.
    • Enhanced validation logic to distinguish between usage-based and flat fee lines based on price type.
    • Updated detailed line creation and total calculations for better accuracy.
  • Bug Fixes
    • Corrected quantity handling and validation for flat fee and usage-based flat fee lines.
  • Tests
    • Developed comprehensive tests for creation, discount application, and validation of usage-based flat fee lines.
    • Refined existing tests for clarity and coverage of new billing line types.
  • Chores
    • Modified database schema to make the feature key nullable in usage-based line configurations.

@coderabbitai

coderabbitai Bot commented May 23, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change adds support for usage-based flat fee invoice lines with optional feature keys and percentage discounts, refactors detailed line creation and total calculation logic, and updates schema and validation to allow nullable feature keys. It introduces new types, methods, and service logic, and updates tests and database migrations accordingly.

Changes

File(s) / Path(s) Change Summary
openmeter/billing/service/lineservice/detailedlines.go
openmeter/billing/service/lineservice/usagebasedlineflat.go
Add new detailed line creation logic and a new ubpFlatFeeLine type for usage-based flat fee lines.
openmeter/billing/service/lineservice/service.go
openmeter/billing/service/lineservice/usagebasedline.go
Delegate detailed line and total updates to service methods; remove inline detailed line construction and discount logic.
openmeter/billing/invoiceline.go
openmeter/billing/adapter/invoicelinemapper.go
openmeter/billing/service/invoicecalc/collectionat.go
Add DependsOnMeteredQuantity() method; update validation and mapping logic for usage-based and flat fee lines.
openmeter/billing/service/lineservice/priceflat.go
openmeter/billing/service/lineservice/priceflat_test.go
Update quantity instantiation in flat pricer logic and clarify test descriptions.
openmeter/ent/db/billinginvoiceusagebasedlineconfig.go
openmeter/ent/db/billinginvoiceusagebasedlineconfig_create.go
openmeter/ent/db/billinginvoiceusagebasedlineconfig_update.go
openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go
openmeter/ent/db/migrate/schema.go
openmeter/ent/db/mutation.go
openmeter/ent/schema/billing.go
Make feature_key nullable/optional in schema, entities, and builders; add methods for clearing and checking nullability.
openmeter/ent/db/billinginvoiceusagebasedlineconfig/billinginvoiceusagebasedlineconfig.go
openmeter/ent/db/runtime.go
Remove feature key validator and related internal assignments.
openmeter/billing/httpdriver/invoiceline.go Add validation for presence of price and adjust quantity parsing for flat price types.
openmeter/notification/internal/rule.go
test/app/custominvoicing/invocing_test.go
test/billing/tax_test.go
Remove explicit quantity field from flat fee line instantiations in tests and notification payloads.
test/app/stripe/invoice_test.go Add explicit quantity field and align period timestamps for usage-based flat fee invoice lines in Stripe tests.
test/billing/collection_test.go Refactor tests for collection flow with flat fee and usage-based flat fee lines; update handling of quantity snapshot fields.
test/billing/invoice_test.go Rename all flatPerUsage references to flatFee for clarity and consistency.
test/billing/suite.go Add helpers for billing profile provisioning and JSON comparison in tests.
test/billing/ubpflatfee_test.go Add new comprehensive test suite for usage-based flat fee invoice lines, including validation and discount scenarios.
tools/migrate/migrations/20250525121526_billing-ubp-fee-line.up.sql
tools/migrate/migrations/20250525121526_billing-ubp-fee-line.down.sql
Migration scripts to make feature_key nullable and to revert the change.

Possibly related PRs

  • openmeterio/openmeter#2893: Enforces that flat fee lines at the root level support only a quantity of 1, which aligns with the main PR's changes to quantity handling and validation for flat fee lines.
  • openmeterio/openmeter#2632: Implements percentage discounts for usage-based lines, directly related to the main PR's addition of percentage discount support for usage-based flat fee lines.
  • openmeterio/openmeter#2634: Adds validation to prevent usage discount updates on partially invoiced lines, which is related to the main PR's enhancements around usage-based line validation and discount handling.

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


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1d422b9 and 460fa54.

📒 Files selected for processing (12)
  • openmeter/billing/httpdriver/invoiceline.go (1 hunks)
  • openmeter/billing/invoiceline.go (5 hunks)
  • openmeter/billing/service/lineservice/priceflat.go (2 hunks)
  • openmeter/billing/service/lineservice/priceflat_test.go (3 hunks)
  • openmeter/billing/service/lineservice/usagebasedlineflat.go (1 hunks)
  • openmeter/notification/internal/rule.go (0 hunks)
  • test/app/custominvoicing/invocing_test.go (0 hunks)
  • test/billing/collection_test.go (2 hunks)
  • test/billing/invoice_test.go (15 hunks)
  • test/billing/suite.go (1 hunks)
  • test/billing/tax_test.go (0 hunks)
  • test/billing/ubpflatfee_test.go (1 hunks)
💤 Files with no reviewable changes (3)
  • test/billing/tax_test.go
  • openmeter/notification/internal/rule.go
  • test/app/custominvoicing/invocing_test.go
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: CI
  • GitHub Check: Analyze (go)
🔇 Additional comments (28)
test/billing/suite.go (2)

459-471: Well-implemented functional options pattern!

The types and functional option pattern for billing profile provisioning are correctly implemented and follow Go best practices.


491-501: Clean and useful test helper implementation!

The ExpectJSONEqual function is well-implemented with proper error handling and uses require.JSONEq which correctly handles JSON formatting differences.

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

13-99: LGTM! Test names now better reflect billing terminology.

The renaming of test cases from generic terms to specific billing terminology improves clarity:

  • "no usage" → "in advance"
  • "usage present" → "in arrears"
  • Added period descriptors ("mid period", "single period line", "last period line")

The clarifying comments about line quantity without feature lookup also enhance understanding of the test behavior.

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

39-39: Good practice: Using integer constructor for integer values.

Changing from NewFromFloat(1) to NewFromInt(1) is appropriate since the quantity is exactly 1. This avoids potential floating-point precision issues and is semantically more correct for integer values.

Also applies to: 49-49

test/billing/invoice_test.go (8)

376-378: LGTM!

The loop setup for initializing mock streaming connector data is correct and follows the expected pattern for test initialization.


408-408: Good refactoring to use helper method.

Using s.CreateTestCustomer() reduces code duplication and improves test maintainability.


539-559: Excellent renaming for clarity and consistency.

The renaming from flatPerUsage to flatFee improves code readability and aligns with the PR objective of implementing usage-based flat fee functionality. The test logic is preserved while making the naming more descriptive and consistent.


562-577: Correct handling of flat fee line differences.

The exclusion of flatFee lines from period truncation loops is appropriate since flat fee lines have different semantics than metered usage lines. The tests correctly verify that flat fee lines maintain their original periods while other usage-based lines get truncated to minute resolution.

Also applies to: 796-811, 868-879


3033-3033: Struct field renaming improves consistency.

The renaming of struct fields from flatPerUsage to flatFee in both ubpPendingLines and ubpFeatures structs maintains consistency with the usage throughout the test file and better describes the purpose of these fields.

Also applies to: 3040-3040


2137-2214: Consistent renaming throughout test assertions.

The remaining references to flatFee are consistent with the renaming pattern applied throughout the file. Test assertions, period checks, and detailed line requirements maintain their functionality while using the clearer field names.


1-4012: Well-executed refactoring with consistent naming improvements.

The comprehensive renaming from flatPerUsage to flatFee throughout this test file demonstrates excellent consistency and attention to detail. The changes successfully:

  1. Improve clarity: The new naming better describes the functionality being tested
  2. Maintain test coverage: All existing test logic is preserved with updated field names
  3. Support new functionality: Addition of explicit quantity fields aligns with the usage-based flat fee implementation
  4. Ensure consistency: The renaming is applied uniformly across structs, variables, and test assertions

This refactoring properly supports the PR objective of implementing usage-based flat fee functionality while maintaining comprehensive test coverage.


459-459:

Details

✅ Verification successful

Verify consistent quantity handling for flat fee lines.

The explicit setting of Quantity: lo.ToPtr(alpacadecimal.NewFromFloat(1)) for usage-based flat fee lines is good for clarity. Please ensure this pattern is consistently applied across all similar test cases where flat fee quantities need to be specified.

Also applies to: 693-693


🏁 Script executed:

#!/bin/bash
# Description: Check for other usage-based lines that might need explicit quantity setting
# Search for UsageBasedLine usage in tests to ensure consistent quantity handling

# Find usage-based line definitions that might be missing explicit quantity
rg -A 10 -B 2 "UsageBasedLine\{" test/ --type go | grep -E "(FlatPrice|productcatalog\.FlatPrice)" -A 5 -B 5

Length of output: 2840


Quantity field consistently applied for flat-fee usage-based lines.

The audit shows that every UsageBasedLine with a FlatPrice now includes Quantity: lo.ToPtr(alpacadecimal.NewFromFloat(1)) in both test suites:

  • test/billing/invoice_test.go (including lines 459 and 693)
  • test/app/stripe/invoice_test.go

No missing instances were found. This change can be approved as is.

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

628-650: LGTM: Well-designed conditional quantity handling for different price types.

The validation and quantity initialization logic correctly differentiates between flat price types (hardcoded qty=1, prePeriodQty=0) and other usage-based price types (parsed from input). The error handling with billing.ValidationError is appropriate.

openmeter/billing/invoiceline.go (6)

562-572: LGTM: Well-designed abstraction for metered quantity dependency.

The DependsOnMeteredQuantity() method provides clear semantics for determining when a line depends on metered quantities, correctly returning false for non-usage-based lines and flat price types.


540-540: LGTM: Proper conditional validation using the new abstraction.

The usage of DependsOnMeteredQuantity() in the validation logic correctly gates the invoice date constraint to only apply when metered quantities are actually relevant.


634-690: LGTM: Well-designed constructor for usage-based flat fee lines.

The new NewUsageBasedFlatFeeLine constructor with options pattern provides clean semantics for creating usage-based lines with flat pricing. The WithFeatureKey option allows flexibility when feature keys are needed.


895-899: LGTM: Appropriate conditional validation for feature keys.

The validation correctly requires FeatureKey only for non-flat price types, which aligns with the business logic since flat price types don't depend on metered features.


518-520:

Details

✅ Verification successful

Verify the relaxation of quantity validation for flat fee lines.

The validation has changed from enforcing quantity == 1 to quantity > 0, which is a significant relaxation of the business rule. Please confirm this change is intentional and aligns with the requirements for usage-based flat fee functionality.


🏁 Script executed:

#!/bin/bash
# Search for existing usages of flat fee lines with specific quantities
rg -A 3 -B 3 "Quantity.*alpacadecimal\.New" --type go

# Search for tests that might verify the quantity == 1 constraint
rg -A 5 -B 5 "quantity.*1" test/ --type go | grep -i "flat.*fee"

Length of output: 76216


Relaxed flat-fee quantity validation is intentional

The change from quantity == 1 to quantity > 0 was introduced to support usage-based flat fees with quantities greater than one. Existing tests (e.g. in adapter_invoicelinediff and the service/lineservice feeline and usage-based line tests) already set and exercise flat-fee quantities > 1 without errors, confirming the new validation aligns with business requirements.


628-632:

Details

✅ Verification successful

Breaking change: Quantity field removed from NewFlatFeeLine input.

The Quantity field has been removed from NewFlatFeeLineInput and is now hardcoded to 1. This is a breaking change that will affect existing callers who previously set custom quantities.

Please verify that all callers have been updated:


🏁 Script executed:

#!/bin/bash
# Search for any remaining usage of Quantity field in NewFlatFeeLineInput
ast-grep --pattern 'NewFlatFeeLineInput{
  $$$
  Quantity: $_
  $$$
}'

# Search for any instantiation of NewFlatFeeLine with quantity
rg -A 10 -B 5 "NewFlatFeeLine.*Quantity" --type go

Length of output: 125


To ensure we haven’t missed any call sites, let’s list all references to NewFlatFeeLineInput and all invocations of NewFlatFeeLine:


🏁 Script executed:

#!/bin/bash
# List every usage of the input struct
rg -n "NewFlatFeeLineInput" --type go || true

# List every call to the constructor
rg -n "NewFlatFeeLine\(" --type go || true

Length of output: 2856


No remaining callers reference the removed Quantity field—breaking change is fully applied

All occurrences of NewFlatFeeLineInput (in openmeter/billing/invoiceline.go, openmeter/notification/internal/rule.go and across all test suites) have been updated, and there are no longer any Quantity: fields supplied. The default Category and Quantity values are now consistently set inside NewFlatFeeLine.

No further action required.

test/billing/collection_test.go (2)

233-263: LGTM: Well-structured table-driven test approach.

The refactoring to use table-driven tests with distinct test cases for traditional flat fee lines and usage-based flat fee lines is excellent. The test names clearly differentiate the scenarios being tested, resolving the previous issue with duplicate names.


501-504: Proper test setup for quantity snapshot validation.

The explicit assignment of quantity-related fields (Quantity, MeteredQuantity, PreLinePeriodQuantity, MeteredPreLinePeriodQuantity) to zero values correctly emulates the per-line quantity snapshot behavior that would occur in a normal edit flow. This ensures the test validates the collection period extension logic accurately.

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

24-51: Comprehensive validation logic implementation.

The validation method properly handles feature meter resolution, usage discount restrictions, and percentage discount validation. The error aggregation approach ensures all validation issues are captured and reported together.


70-92: Well-designed detailed line calculation and merging.

The separation of calculation logic (calculateDetailedLines) from the integration logic (CalculateDetailedLines) follows good separation of concerns. The use of the pricing mutator pattern with flat pricer and percentage discount mutator is a clean architectural approach.

test/billing/ubpflatfee_test.go (5)

18-24: Excellent test suite structure for comprehensive UBP flat fee coverage.

The test suite provides thorough coverage of usage-based flat fee functionality with well-organized test methods for creation, discount handling, and validation scenarios.


48-82: Thorough pending line creation validation.

The test properly validates line creation by comparing expected vs actual results after cloning and setting system-generated fields (IDs, timestamps, ConfigID). The use of RemoveCircularReferences() and RemoveMetaForCompare() ensures clean JSON comparison without implementation artifacts.


137-218: Comprehensive percentage discount calculation validation.

The test properly validates the percentage discount application, checking both the discount amounts and final totals at both line and detailed line levels. The assertions correctly verify the 50% discount results in the expected amounts (200 base amount, 100 discount, 100 final total).


237-261: Proper validation of usage discount restrictions.

The test correctly validates that usage discounts are not allowed for usage-based flat fee lines, ensuring the business rules are properly enforced. The error expectation aligns with the validation logic in the service layer.


263-282: Good validation of edge case scenarios.

The test properly validates that empty periods (start equals end) are allowed for flat fee lines, which makes business sense since flat fees are not time-dependent. This edge case validation ensures the system handles one-time fees correctly.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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/implement-ubp-flat-fee branch 4 times, most recently from 17d08b1 to d7fbc55 Compare May 25, 2025 12:16
@turip
turip marked this pull request as ready for review May 25, 2025 12:16
@turip
turip requested a review from a team as a code owner May 25, 2025 12:16
@turip turip added release-note/misc Miscellaneous changes area/billing release-note/feature Release note: Exciting New Features and removed release-note/misc Miscellaneous changes labels May 25, 2025

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

🧹 Nitpick comments (5)
openmeter/billing/httpdriver/invoice.go (1)

445-445: TODO comment appropriately documents future enhancement.

The comment clearly identifies the need to support editing UBP flat fee lines with quantity settings. This is good planning documentation for the feature's next iteration.

Would you like me to help draft the implementation requirements for UBP flat fee line editing or create a tracking issue for this TODO?

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

40-42: Good introduction of polymorphic testing approach.

The ubpLineCalculator interface enables clean testing of both usageBasedLine and ubpFlatFeeLine implementations through the same test framework.

Consider moving this interface to a non-test file if it might be useful for production code polymorphism in the future.

test/billing/collection_test.go (1)

233-265: Fix duplicate test case names for better test output clarity.

The table-driven test approach is excellent for testing both traditional and usage-based flat fee lines. However, both test cases have the same name "flat fee only", which could make test output confusing.

Consider updating the names to be more descriptive:

 	{
-		name:      "flat fee only",
+		name:      "traditional flat fee only",
 		namespace: "ns-collection-flow-flat-fee",
 		line: billing.NewFlatFeeLine(billing.NewFlatFeeLineInput{
 	{
-		name:      "flat fee only",
+		name:      "usage-based flat fee only", 
 		namespace: "ns-collection-flow-ubp-flat-fee",
 		line: billing.NewUsageBasedFlatFeeLine(billing.NewFlatFeeLineInput{
test/billing/invoice_test.go (2)

380-380: LGTM! Verify meter slug consistency.

The flatFee test logic is correct - flat fee lines should not be truncated while other usage-based lines should be. The quantity of 1 for flat fees is appropriate.

However, there's an inconsistency in the meter slug references:

-	for _, slug := range []string{"flat-per-unit", "tiered-graduated", "tiered-volume"} {
+	for _, slug := range []string{"flat-per-unit", "tiered-graduated", "tiered-volume"} {

The loop still references the old "flat-per-usage" concept in some contexts. Ensure all meter slug references are consistent with the new flatFee approach.

Also applies to: 463-463, 543-564


3037-3037: Struct updates support flatFee functionality.

The addition of flatFee fields to both structs is appropriate for the new architecture. The ubpPendingLines.flatFee field is actively used in tests.

Note: The ubpFeatures.flatFee field appears unused in this test file - verify if it's needed for future functionality or other test files.

Also applies to: 3044-3044

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e281913 and d7fbc55.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (27)
  • openmeter/billing/adapter/invoicelinemapper.go (1 hunks)
  • openmeter/billing/httpdriver/invoice.go (1 hunks)
  • openmeter/billing/invoiceline.go (5 hunks)
  • openmeter/billing/service/invoicecalc/collectionat.go (1 hunks)
  • openmeter/billing/service/lineservice/detailedlines.go (1 hunks)
  • openmeter/billing/service/lineservice/priceflat.go (2 hunks)
  • openmeter/billing/service/lineservice/priceflat_test.go (3 hunks)
  • openmeter/billing/service/lineservice/service.go (3 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (2 hunks)
  • openmeter/billing/service/lineservice/usagebasedline_test.go (2 hunks)
  • openmeter/billing/service/lineservice/usagebasedlineflat.go (1 hunks)
  • openmeter/ent/db/billinginvoiceusagebasedlineconfig.go (3 hunks)
  • openmeter/ent/db/billinginvoiceusagebasedlineconfig/billinginvoiceusagebasedlineconfig.go (0 hunks)
  • openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (1 hunks)
  • openmeter/ent/db/billinginvoiceusagebasedlineconfig_create.go (2 hunks)
  • openmeter/ent/db/billinginvoiceusagebasedlineconfig_update.go (2 hunks)
  • openmeter/ent/db/migrate/schema.go (1 hunks)
  • openmeter/ent/db/mutation.go (4 hunks)
  • openmeter/ent/db/runtime.go (0 hunks)
  • openmeter/ent/schema/billing.go (1 hunks)
  • test/app/stripe/invoice_test.go (2 hunks)
  • test/billing/collection_test.go (3 hunks)
  • test/billing/invoice_test.go (15 hunks)
  • test/billing/suite.go (1 hunks)
  • test/billing/ubpflatfee_test.go (1 hunks)
  • tools/migrate/migrations/20250525121526_billing-ubp-fee-line.down.sql (1 hunks)
  • tools/migrate/migrations/20250525121526_billing-ubp-fee-line.up.sql (1 hunks)
💤 Files with no reviewable changes (2)
  • openmeter/ent/db/billinginvoiceusagebasedlineconfig/billinginvoiceusagebasedlineconfig.go
  • openmeter/ent/db/runtime.go
🧰 Additional context used
🧬 Code Graph Analysis (9)
openmeter/billing/adapter/invoicelinemapper.go (2)
openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (1)
  • FeatureKey (73-75)
openmeter/ent/db/subscriptionitem/where.go (1)
  • FeatureKey (142-144)
openmeter/billing/service/lineservice/priceflat.go (2)
openmeter/billing/errors.go (1)
  • ValidationError (119-119)
openmeter/productcatalog/price.go (1)
  • InAdvancePaymentTerm (20-20)
openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (3)
openmeter/ent/db/planratecard/where.go (2)
  • FeatureKeyIsNil (622-624)
  • FeatureKeyNotNil (627-629)
openmeter/ent/db/predicate/predicate.go (1)
  • BillingInvoiceUsageBasedLineConfig (113-113)
openmeter/ent/db/billinginvoiceusagebasedlineconfig/billinginvoiceusagebasedlineconfig.go (1)
  • FieldFeatureKey (23-23)
openmeter/ent/db/billinginvoiceusagebasedlineconfig_update.go (1)
openmeter/ent/db/billinginvoiceusagebasedlineconfig/billinginvoiceusagebasedlineconfig.go (1)
  • FieldFeatureKey (23-23)
test/app/stripe/invoice_test.go (3)
openmeter/ent/db/billinginvoiceline/where.go (1)
  • Quantity (168-170)
openmeter/ent/db/billinginvoicelinediscount/where.go (1)
  • Quantity (126-128)
openmeter/ent/db/billinginvoicelineusagediscount/where.go (1)
  • Quantity (111-113)
openmeter/billing/service/lineservice/usagebasedline_test.go (3)
openmeter/billing/invoiceline.go (7)
  • Line (282-296)
  • LineBase (129-163)
  • InvoiceLineTypeUsageBased (33-33)
  • InvoiceLineStatusValid (47-47)
  • UsageBasedLine (839-852)
  • Price (837-837)
  • Period (84-87)
openmeter/billing/service/lineservice/linebase.go (1)
  • LineBase (60-88)
openmeter/productcatalog/price.go (2)
  • Price (84-91)
  • FlatPriceType (41-41)
openmeter/ent/db/billinginvoiceusagebasedlineconfig_create.go (2)
openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (1)
  • FeatureKey (73-75)
openmeter/ent/db/planratecard/where.go (1)
  • FeatureKey (106-108)
openmeter/ent/db/mutation.go (1)
openmeter/ent/db/billinginvoiceusagebasedlineconfig/billinginvoiceusagebasedlineconfig.go (1)
  • FieldFeatureKey (23-23)
openmeter/billing/service/lineservice/priceflat_test.go (2)
openmeter/productcatalog/price.go (3)
  • NewPriceFrom (363-385)
  • InAdvancePaymentTerm (20-20)
  • InArrearsPaymentTerm (21-21)
openmeter/billing/service/lineservice/usagebasedline.go (1)
  • FlatPriceChildUniqueReferenceID (23-23)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Test
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (45)
tools/migrate/migrations/20250525121526_billing-ubp-fee-line.up.sql (1)

1-2: LGTM! Safe schema change for UBP flat fee support.

The migration correctly drops the NOT NULL constraint on feature_key, which makes sense for usage-based flat fee lines that don't meter specific features. This is a safe operation that won't affect existing data.

tools/migrate/migrations/20250525121526_billing-ubp-fee-line.down.sql (1)

1-2: Rollback migration syntax is correct.

The reverse migration properly restores the NOT NULL constraint. Note that this rollback will fail if there are NULL values in the feature_key column at rollback time, which is expected behavior for constraint-adding rollbacks.

openmeter/billing/service/invoicecalc/collectionat.go (1)

40-40: Improved semantic accuracy for UBP flat fee lines.

The change from a direct type check to DependsOnMeteredQuantity() is more semantically correct. This properly handles UBP flat fee lines, which are usage-based lines but don't depend on metered quantities for collection timing.

openmeter/ent/db/migrate/schema.go (1)

972-972: LGTM! Schema change aligns with UBP flat fee implementation.

Making the feature_key column nullable in the BillingInvoiceUsageBasedLineConfigs table is appropriate for supporting usage-based flat fee lines, which may not require a feature reference. This change appears well-coordinated with the broader implementation described in the AI summary.

openmeter/ent/schema/billing.go (1)

501-502: LGTM: Schema change correctly implements nullable feature_key.

The change from NotEmpty() to Optional().Nillable() properly makes the feature_key field optional and nullable, which is necessary to support usage-based flat fee lines that don't require a feature key. This aligns with the PR objective to implement ubp flat fee functionality.

openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (1)

242-250: LGTM: Correctly implemented nullable field predicates.

The new FeatureKeyIsNil and FeatureKeyNotNil predicates are properly implemented and follow the standard ent pattern for nullable field queries. These predicates are essential for querying usage-based line configurations where the feature key might be null (e.g., for flat fee lines).

openmeter/billing/adapter/invoicelinemapper.go (1)

203-203: LGTM: Correctly handles nullable FeatureKey conversion.

The change to use lo.FromPtr(ubpLine.FeatureKey) properly handles the conversion from the nullable pointer type (*string) to a value type (string). This is the correct approach to safely extract values from nullable fields while handling nil cases appropriately.

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

32-36: LGTM: Added proper quantity validation.

The validation check ensures that Quantity is not nil before proceeding with flat price calculations. This prevents potential runtime errors and provides a clear, actionable error message when the quantity is not set for usage-based flat fee lines.


43-43: LGTM: Using actual quantity instead of hardcoded value.

The change from alpacadecimal.NewFromFloat(1) to *l.line.UsageBased.Quantity correctly uses the actual quantity specified for the line instead of hardcoding it to 1. This makes the flat price calculation more flexible and accurate for usage-based flat fee scenarios where the quantity may vary.

Also applies to: 53-53

openmeter/ent/db/billinginvoiceusagebasedlineconfig.go (1)

26-26: LGTM! Proper nullable field implementation.

The changes correctly implement the nullable FeatureKey field with proper nil handling in both assignment and string formatting.

Also applies to: 86-87, 158-161

test/app/stripe/invoice_test.go (1)

368-368: Correct test updates for usage-based flat fee lines.

The changes properly set the required quantity field for flat fee lines and use consistent period timestamps throughout the test.

Also applies to: 592-593

openmeter/ent/db/billinginvoiceusagebasedlineconfig_create.go (1)

45-51: Well-implemented nullable field creation support.

The SetNillableFeatureKey method and pointer assignment correctly handle the optional nature of the feature_key field.

Also applies to: 231-231

openmeter/ent/db/billinginvoiceusagebasedlineconfig_update.go (1)

174-176: LGTM! Correct implementation of nullable field clearing.

The changes properly implement the clearing logic for the nullable FeatureKey field in both bulk update and single update operations, following the same pattern as other nullable fields in this auto-generated file.

Also applies to: 394-396

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

50-135: Well-structured refactoring for testing multiple line types.

The test now properly constructs a generic billing.Line and instantiates the appropriate implementation based on price type. This aligns perfectly with the PR's goal of introducing usage-based flat fee lines.

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

13-34: Good correction of test name and usage quantity.

The test name now accurately reflects that usage is present (changed from "no usage" to "usage present") and the usage quantity is appropriately set to 1. The added comment clarifies that this represents the line quantity without feature lookup.


36-57: Correct alignment of test name with payment terms.

The test name and payment term now properly indicate "in arrears" payment, and the usage quantity is adjusted to a more reasonable value of 1.


73-93: Consistent test improvements across all scenarios.

All test cases now have:

  • Accurate test names that match their scenarios
  • Appropriate non-zero usage quantities where usage is claimed to be present
  • Correct expected quantities matching the input usage
  • Fixed typo in line 95 (added missing space)

These changes significantly improve test clarity and correctness.

Also applies to: 95-107, 109-129

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

12-12: Correct implementation of flat fee line type handling.

The conditional branch properly identifies flat price types within usage-based lines and returns the appropriate ubpFlatFeeLine implementation. This aligns with the PR objective to implement usage-based flat fee functionality.

Also applies to: 82-86


154-193: Well-designed centralized totals calculation method.

The UpdateTotalsFromDetailedLines method provides a clean, centralized approach for calculating line totals from detailed child lines. Key strengths:

  • Properly skips deleted lines in both iteration and aggregation
  • Includes an important warning comment about not adding custom logic
  • Maintains consistency with external system synchronization requirements

The architectural decision to keep this logic simple and only aggregate child totals is sound, as noted in the comment.

test/billing/collection_test.go (1)

504-507: LGTM! Proper field initialization for new metered quantity fields.

The explicit initialization of MeteredQuantity and MeteredPreLinePeriodQuantity follows the correct pattern and aligns with the removal of fallback logic mentioned in the summary. This ensures deterministic test behavior.

openmeter/ent/db/mutation.go (6)

21786-21786: LGTM: Correct implementation of nullable field support

The return type change from string to *string correctly implements nullable field support for feature_key, aligning with the PR objectives to make this field optional.


21800-21810: LGTM: Proper implementation of clear/check methods

The new ClearFeatureKey() and FeatureKeyCleared() methods follow standard Ent patterns for nullable field management:

  • Setting field to nil and marking in clearedFields map
  • Providing clear state checking functionality

21815-21815: LGTM: Consistent field clearing management

The ResetFeatureKey() method is correctly updated to remove the field from the clearedFields map, maintaining consistency with the nullable field implementation.


22190-22192: LGTM: Proper integration with cleared fields enumeration

The ClearedFields() method correctly includes feature_key when it has been cleared, maintaining consistency with other nullable fields in the system.


22216-22218: LGTM: Complete integration with generic clear method

The ClearField() method correctly handles the feature_key field by delegating to the specific ClearFeatureKey() method, completing the nullable field implementation.


21786-22218:

Details

✅ Verification successful

Verify breaking changes are addressed in dependent code

The change from string to *string for the feature_key field is a breaking change. Ensure that all code using OldFeatureKey() has been updated to handle the nullable return type.


🏁 Script executed:

#!/bin/bash
# Description: Find all usages of OldFeatureKey method to verify nullable handling
# Expected: All usages should handle the *string return type correctly

echo "Searching for OldFeatureKey method usage..."
rg -A 3 -B 1 "OldFeatureKey\(" --type go

echo -e "\nSearching for FeatureKey field access in mutations..."
rg -A 2 -B 1 "\.FeatureKey\b" --type go

Length of output: 49069


OldFeatureKey() usage verified—no action needed
All occurrences of OldFeatureKey() are confined to the generated ent mutations, and there are no external callers that need to handle a *string return. The mutation code already correctly returns and propagates a nullable *string.

test/billing/suite.go (3)

458-471: Well-implemented functional options pattern

The functional options pattern is correctly implemented with proper type definitions and helper functions. This provides a clean and extensible API for billing profile provisioning.


491-501: Solid JSON equality helper implementation

The function correctly marshals both values to JSON and uses require.JSONEq for structural comparison. The t.Helper() call is properly included to improve test failure reporting.


480-480:

Details

❌ Incorrect review comment

Verify that MinimalCreateProfileInputTemplate is defined

The code references MinimalCreateProfileInputTemplate but this constant/variable is not defined in this file. Ensure it's properly defined and accessible.


🏁 Script executed:

#!/bin/bash
# Description: Search for MinimalCreateProfileInputTemplate definition
# Expected: Find the definition of this template

rg -A 5 "MinimalCreateProfileInputTemplate.*=" --type go

Length of output: 397


No action required: MinimalCreateProfileInputTemplate is already defined
The identifier is declared in test/billing/profile.go:

  • File: test/billing/profile.go
    Line: var MinimalCreateProfileInputTemplate = billing.CreateProfileInput{ … }

You can safely remove or ignore this verification.

Likely an incorrect or invalid review comment.

test/billing/invoice_test.go (2)

2141-2141: Excellent test coverage for flatFee end-of-period behavior.

The test correctly verifies that:

  1. FlatFee lines maintain their original periods (not truncated like other usage-based lines)
  2. Detailed line calculations are accurate with quantity=1 and correct per-unit amounts
  3. Total calculations are properly validated

This comprehensive testing ensures the flatFee implementation works correctly in end-of-period scenarios.

Also applies to: 2147-2147, 2160-2160, 2206-2218


2777-2798: Consistent and thorough flatFee testing across billing modes.

The test correctly implements the same flatFee behavior verification for non-progressive billing:

  1. Period Consistency: FlatFee lines maintain original periods while usage-based lines are truncated
  2. Detailed Line Structure: Proper quantity=1 and amount=100 validation
  3. Total Calculations: Accurate total verification

This ensures flatFee behavior is consistent regardless of progressive billing settings.

Also applies to: 2864-2864, 2876-2884, 2886-2898

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

17-19: LGTM!

The PrepareForCreate method correctly returns the line without modifications, which is appropriate for flat fee lines that don't require period truncation or other preparation steps.


73-79: LGTM!

The CanBeInvoicedAsOf logic correctly allows flat fee lines to be invoiced once the AsOf date reaches or passes the InvoiceAt date.


81-118: Well-structured implementation of remaining methods.

The implementation correctly handles:

  • SnapshotQuantity as a no-op since flat fees have pre-set quantities
  • Pricing calculation using the appropriate flatPricer with percentage discount support
  • Proper delegation to service methods for detailed line merging and total updates
  • Clear documentation that flat fee lines are not subject to truncation
openmeter/billing/invoiceline.go (4)

540-542: Good differentiation between metered and non-metered lines.

The conditional validation correctly allows usage-based flat fee lines to be invoiced before the period end, while maintaining the existing requirement for metered usage-based lines.


562-572: Well-implemented helper method.

The DependsOnMeteredQuantity method provides a clean abstraction for determining whether a line requires metered quantity data, correctly returning false for both non-usage-based lines and usage-based lines with flat pricing.


635-692: Well-designed constructor following established patterns.

The NewUsageBasedFlatFeeLine constructor:

  • Follows the options pattern for extensibility
  • Properly initializes all required fields
  • Includes clear documentation about its temporary nature
  • Correctly converts quantity to a pointer for the UsageBasedLine structure

897-901: Appropriate relaxation of FeatureKey requirement.

The validation correctly makes FeatureKey optional for flat price types while maintaining the requirement for other usage-based price types that need meter association.

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

146-146: Good refactoring to centralize total updates.

Delegating to service.UpdateTotalsFromDetailedLines ensures consistent total calculation across different line types.


187-189: Consistent use of shared detailed line merging logic.

Using the mergeDetailedLines helper function reduces code duplication and ensures consistent behavior across line types.


194-208:

Details

✅ Verification successful

Verify that FlatPriceType routing is handled correctly.

The removal of FlatPriceType handling from getPricer is correct since ubpFlatFeeLine now handles flat price usage-based lines. However, let's verify that the service layer properly routes flat price lines to ubpFlatFeeLine.

Run the following script to verify the routing logic:


🏁 Script executed:

#!/bin/bash
# Description: Verify that the service layer correctly instantiates ubpFlatFeeLine for flat price usage-based lines

# Search for the service's FromEntity method to see how it routes different line types
ast-grep --pattern 'func $_($$) FromEntity($_, $_) {
  $$$
}'

# Also search for any switch/if statements that check for FlatPriceType
rg -A 10 "FlatPriceType|productcatalog\.FlatPrice" openmeter/billing/service/lineservice/

Length of output: 7879


FlatPriceType routing is correctly handled

The removal of the FlatPriceType case from getPricer is safe because the service layer now routes flat-price lines to ubpFlatFeeLine before falling back to usageBasedLine. Tests in usagebasedline_test.go and priceflat_test.go confirm the expected behavior.

• See openmeter/billing/service/lineservice/service.go, where:

if line.UsageBased.Price.Type() == productcatalog.FlatPriceType {
    return &ubpFlatFeeLine{ lineBase: base }, nil
}

• All flat-price scenarios are covered by existing tests.

No further changes required.

test/billing/ubpflatfee_test.go (2)

26-136: Well-structured test for pending line creation!

The test comprehensively covers the happy path for usage-based flat fee lines, including validation of totals and detailed lines. The subtests properly verify that progressive billing is not supported for this line type.


138-220: Correct implementation of percentage discount test!

The test accurately validates the 50% discount calculation with proper assertions on both the parent line and detailed line totals.

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

72-120: Well-implemented maximum spend discount logic!

The method correctly handles all three scenarios for spend cap enforcement with proper currency precision handling. The discount calculation ensures customers never exceed their maximum spend limit.


181-200: Efficient implementation of detailed line merging!

The function properly maintains line ordering through sequential indices and efficiently reuses child IDs to minimize database churn. Good error handling throughout the process.

Comment thread test/billing/suite.go Resolved
Comment thread test/billing/ubpflatfee_test.go Resolved
@turip
turip force-pushed the feat/implement-ubp-flat-fee branch from 6ce6261 to fb40eeb Compare May 25, 2025 12:57
@turip
turip requested review from chrisgacsal and tothandras May 26, 2025 09:06
@turip
turip force-pushed the feat/implement-ubp-flat-fee branch from fb40eeb to 1d422b9 Compare May 26, 2025 13:07

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

🔭 Outside diff range comments (2)
openmeter/billing/httpdriver/invoiceline.go (2)

180-216: ⚠️ Potential issue

Add similar price validation to maintain consistency.

The mapCreatePendingUsageBasedLineToEntity function should include the same price validation and conditional quantity initialization logic that was added to mapUsageBasedSimulationLineToEntity. This ensures consistent behavior between simulation and actual line creation.

Add the following validation after line 189:

 if err != nil {
   return nil, fmt.Errorf("failed to map usage based line: %w", err)
 }

+if rateCardParsed.Price == nil {
+  return nil, billing.ValidationError{
+    Err: fmt.Errorf("price is required for usage based lines"),
+  }
+}
+
 return &billing.Line{

Additionally, consider adding quantity initialization logic if the line creation supports flat price types.


770-770: ⚠️ Potential issue

Fix incorrect line type assignment.

The line type is incorrectly set to billing.InvoiceLineTypeFee for a usage-based line. This appears to be a copy-paste error.

Apply this fix:

-Type: billing.InvoiceLineTypeFee,
+Type: billing.InvoiceLineTypeUsageBased,
♻️ Duplicate comments (1)
test/billing/suite.go (1)

473-489: Potential mutation of shared template - consider creating a deep copy

The implementation assigns MinimalCreateProfileInputTemplate directly to clonedCreateProfileInput, which creates only a shallow copy. If the template contains pointers, slices, or maps, modifications to these fields will affect the original template, potentially causing race conditions or unexpected side effects in parallel tests.

🧹 Nitpick comments (1)
openmeter/billing/invoiceline.go (1)

518-520: Validation logic is correct and consistent.

The validation ensures quantity is positive, which is appropriate for flat fee lines. The error message could be slightly improved for clarity.

Consider improving the error message for better clarity:

-		errs = append(errs, errors.New("quantity should be positive required"))
+		errs = append(errs, errors.New("quantity must be positive"))
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fb40eeb and 1d422b9.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (30)
  • openmeter/billing/adapter/invoicelinemapper.go (1 hunks)
  • openmeter/billing/httpdriver/invoiceline.go (1 hunks)
  • openmeter/billing/invoiceline.go (5 hunks)
  • openmeter/billing/service/invoicecalc/collectionat.go (1 hunks)
  • openmeter/billing/service/lineservice/detailedlines.go (1 hunks)
  • openmeter/billing/service/lineservice/priceflat.go (2 hunks)
  • openmeter/billing/service/lineservice/priceflat_test.go (3 hunks)
  • openmeter/billing/service/lineservice/service.go (3 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (2 hunks)
  • openmeter/billing/service/lineservice/usagebasedline_test.go (2 hunks)
  • openmeter/billing/service/lineservice/usagebasedlineflat.go (1 hunks)
  • openmeter/ent/db/billinginvoiceusagebasedlineconfig.go (3 hunks)
  • openmeter/ent/db/billinginvoiceusagebasedlineconfig/billinginvoiceusagebasedlineconfig.go (0 hunks)
  • openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (1 hunks)
  • openmeter/ent/db/billinginvoiceusagebasedlineconfig_create.go (2 hunks)
  • openmeter/ent/db/billinginvoiceusagebasedlineconfig_update.go (2 hunks)
  • openmeter/ent/db/migrate/schema.go (1 hunks)
  • openmeter/ent/db/mutation.go (4 hunks)
  • openmeter/ent/db/runtime.go (0 hunks)
  • openmeter/ent/schema/billing.go (1 hunks)
  • openmeter/notification/internal/rule.go (0 hunks)
  • test/app/custominvoicing/invocing_test.go (0 hunks)
  • test/app/stripe/invoice_test.go (2 hunks)
  • test/billing/collection_test.go (2 hunks)
  • test/billing/invoice_test.go (15 hunks)
  • test/billing/suite.go (1 hunks)
  • test/billing/tax_test.go (0 hunks)
  • test/billing/ubpflatfee_test.go (1 hunks)
  • tools/migrate/migrations/20250525121526_billing-ubp-fee-line.down.sql (1 hunks)
  • tools/migrate/migrations/20250525121526_billing-ubp-fee-line.up.sql (1 hunks)
💤 Files with no reviewable changes (5)
  • openmeter/ent/db/billinginvoiceusagebasedlineconfig/billinginvoiceusagebasedlineconfig.go
  • test/billing/tax_test.go
  • test/app/custominvoicing/invocing_test.go
  • openmeter/ent/db/runtime.go
  • openmeter/notification/internal/rule.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • tools/migrate/migrations/20250525121526_billing-ubp-fee-line.up.sql
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Analyze (go)
🔇 Additional comments (49)
openmeter/billing/service/invoicecalc/collectionat.go (1)

40-40: Excellent refactoring to improve abstraction and maintainability.

The change from direct type comparison to the DependsOnMeteredQuantity() method is a great improvement that:

  • Encapsulates the logic for determining line dependency on metered quantity
  • Makes the code more semantic and readable
  • Allows for more sophisticated logic that can consider both line type and price type
  • Aligns well with the PR objective of unifying flat fee representation

This abstraction will make it easier to handle the new usage-based flat fee lines while maintaining backward compatibility.

openmeter/ent/db/migrate/schema.go (1)

972-972: LGTM! Schema change supports optional feature key for usage-based flat fee lines.

The modification correctly makes the feature_key field nullable in the billing_invoice_usage_based_line_configs table, which aligns with the PR objective to support usage-based flat fee lines where feature keys are optional for flat price types. This is a safe database migration that preserves existing data while allowing new functionality.

openmeter/billing/adapter/invoicelinemapper.go (1)

203-203: Correct implementation for nullable FeatureKey handling.

The use of lo.FromPtr() properly handles the transition from string to *string for the FeatureKey field, ensuring safe dereferencing when the pointer is nil.

openmeter/ent/schema/billing.go (1)

501-502:

Details

✅ Verification successful

Verify validation logic handles optional feature keys correctly.

Making feature_key optional and nullable is a significant schema change that enables UBP flat fee lines without feature keys. Ensure that validation logic elsewhere properly handles cases where feature_key is nil, particularly for usage-based lines that may still require feature keys.


🏁 Script executed:

#!/bin/bash
# Description: Verify that validation logic properly handles optional feature keys in usage-based lines

# Search for feature key validation logic
rg -A 10 -B 5 "FeatureKey.*[Vv]alidat|[Vv]alidat.*FeatureKey" --type go

# Search for usage-based line validation
ast-grep --pattern 'func ($_ UsageBasedLine) Validate() error {
  $$$
}'

Length of output: 15492


feature_key validation logic confirmed

The UsageBasedLine.Validate() method in openmeter/billing/invoiceline.go (lines 895–900) correctly enforces that:

  • Non-flat-price lines (i.Price.Type() != productcatalog.FlatPriceType) require a non-empty featureKey.
  • Flat-fee lines skip the featureKey check, allowing it to be nil/empty.

No further changes are needed.

openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (1)

242-250: LGTM! Properly generated nullable field predicates.

The auto-generated FeatureKeyIsNil() and FeatureKeyNotNil() predicates correctly implement SQL NULL checks for the nullable feature_key field.

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

39-39: Good precision improvement using integer constructor.

Using alpacadecimal.NewFromInt(1) instead of alpacadecimal.NewFromFloat(1) is more precise and appropriate for the exact integer value 1, avoiding potential floating-point precision issues.


49-49: Consistent precision improvement.

Same precision improvement as line 39 - using integer constructor for exact value 1.

openmeter/ent/db/billinginvoiceusagebasedlineconfig.go (1)

1-1: Skip review for auto-generated file

This file is auto-generated by Ent ORM and should not be manually edited. The changes here are a result of schema modifications.

test/app/stripe/invoice_test.go (2)

368-369: LGTM! Quantity field addition aligns with UBP flat fee implementation

Adding the Quantity field to the usage-based flat fee line is consistent with the PR objectives of implementing usage-based flat fee functionality.


592-593: Good change for test consistency

Using periodStart and periodEnd directly instead of the expected* variables improves test clarity and consistency.

openmeter/ent/db/billinginvoiceusagebasedlineconfig_create.go (1)

1-1: Skip review for auto-generated file

This file is auto-generated by Ent ORM and should not be manually edited. The changes here reflect the schema modifications making FeatureKey optional and nullable.

openmeter/ent/db/billinginvoiceusagebasedlineconfig_update.go (1)

174-176: LGTM! Auto-generated code correctly handles clearing of nullable FeatureKey field.

The changes properly implement the clearing logic for the now-nullable FeatureKey field in both update builders, which aligns with the schema changes making this field optional for usage-based flat fee lines.

Also applies to: 394-396

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

13-13: LGTM! Test names are now more descriptive and accurate.

The updated test names better reflect what each test case is actually testing by focusing on payment timing (in advance/in arrears) and billing period context (single/mid/last period) rather than the ambiguous "usage present" terminology.

Also applies to: 36-36, 59-59, 73-73, 92-92, 103-103

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

82-86: LGTM! Correctly routes usage-based flat fee lines to the appropriate implementation.

The conditional check properly identifies usage-based lines with flat price type and returns the specialized ubpFlatFeeLine implementation, which is essential for the new usage-based flat fee feature.


154-193: Well-implemented helper method with excellent documentation.

The UpdateTotalsFromDetailedLines method correctly:

  • Skips deleted lines when calculating totals
  • Recursively updates child line totals
  • Aggregates totals from all non-deleted children
  • Includes clear warnings about not adding custom logic that won't be synchronized to external systems

The implementation follows the principle that parent line totals should be a simple sum of child totals without additional transformations.

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

40-42: Well-designed interface abstraction for polymorphic line calculation.

The ubpLineCalculator interface provides a clean abstraction for different line calculation implementations, enabling the test to work with both traditional usage-based lines and the new flat fee usage-based lines.


50-62: Improved test setup with proper Line object construction.

The refactoring from direct struct instantiation to proper billing.Line object creation makes the test more realistic and aligns with how lines are actually created in the system.


119-134: Clean polymorphic implementation based on price type.

The type switching logic correctly determines whether to use ubpFlatFeeLine or usageBasedLine based on the price type, enabling unified testing of both line types through the common interface.


136-136: Consistent interface usage for method invocation.

The call to calculateDetailedLines() through the interface maintains the same test behavior while supporting the new polymorphic design.

test/billing/invoice_test.go (7)

1376-1378: Good update to the test data setup.

The removal of "flat-per-usage" from the slug list aligns with the renaming from flatPerUsage to flatFee, making the test data setup consistent with the new terminology.


1539-1559: Excellent addition of flat fee period validation.

The renaming from flatPerUsage to flatFee improves clarity, and the new assertions correctly verify that flat fee lines maintain their original period without truncation, which is the expected behavior for flat fee pricing.


1562-1562: Verify the exclusion of flat fee from period truncation logic.

The loop correctly excludes lines.flatFee from the period truncation verification, which aligns with the assertions above. This ensures flat fee lines are handled differently from usage-based lines.


2137-2157: Consistent terminology update in invoice line processing.

The renaming from flatPerUsage to flatFee is consistently applied in the end-of-period invoice test, maintaining the distinction between flat fee and usage-based pricing lines.


2202-2214: Proper validation of flat fee line details.

The test correctly validates the flat fee line with appropriate expectations for quantity (1) and per-unit amount (100), which is standard for flat fee pricing.


2773-2794: Well-structured flat fee period validation in non-progressive billing.

The struct initialization and period validation for flat fee lines are properly implemented, ensuring that flat fee periods remain unchanged in non-progressive billing scenarios.


3031-3043: Clear struct field naming for test data structures.

The renaming of struct fields from flatPerUsage to flatFee in both ubpPendingLines and ubpFeatures structs improves code clarity and maintains consistency with the domain terminology.

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

628-632: Price validation looks good.

The null check for rateCardParsed.Price is appropriate to prevent nil pointer dereferences when working with usage-based lines.


634-650: Good implementation of flat fee behavior for usage-based lines.

The conditional logic correctly handles flat price types by setting quantity to 1 and pre-period quantity to 0, which aligns with the PR objective of achieving parity between usage-based lines with flat price types and existing flat fee lines.

openmeter/ent/db/mutation.go (5)

21786-21786: LGTM: Correct nullable field implementation.

The return type change from string to *string correctly reflects the schema change making feature_key nullable. This follows ent's standard pattern for nullable fields.


21800-21810: LGTM: Standard ent nullable field methods implemented correctly.

The new methods ClearFeatureKey() and FeatureKeyCleared() follow ent's established patterns for nullable field handling:

  • ClearFeatureKey() correctly sets the field to nil and marks it in clearedFields
  • FeatureKeyCleared() properly checks the clearedFields map

21815-21815: LGTM: Field reset correctly updated.

The addition of delete(m.clearedFields, billinginvoiceusagebasedlineconfig.FieldFeatureKey) ensures that the cleared state is properly reset when ResetFeatureKey() is called. This maintains consistency with the clearing mechanism.


22190-22192: LGTM: ClearedFields method correctly extended.

The ClearedFields() method properly includes the feature_key field when it has been cleared, maintaining consistency with the mutation's clearing mechanism.


22216-22218: LGTM: ClearField method correctly handles feature_key.

The ClearField() method properly delegates to ClearFeatureKey() when the feature_key field is specified, following the established pattern for other clearable fields in the method.

test/billing/suite.go (1)

491-501: LGTM!

The JSON comparison helper is well-implemented with proper error handling and use of t.Helper().

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

146-147: Good refactoring to centralize detailed line handling.

The delegation of total calculation to the service layer is a clean architectural improvement that promotes code reuse and maintainability.


187-189: Clean delegation to external merge function.

The replacement of inline detailed line creation logic with a call to mergeDetailedLines function promotes code reuse and centralizes detailed line handling logic.

openmeter/billing/invoiceline.go (5)

540-542: Smart conditional validation based on metered quantity dependency.

The validation logic correctly differentiates between usage-based lines that depend on metered quantities (requiring invoice date after period end) and those that don't (flat fee types).


562-572: Well-designed method to determine metered quantity dependency.

The logic correctly identifies that only usage-based lines with non-flat price types depend on metered quantities. This is a clean abstraction that encapsulates the business logic.


634-644: Clean option pattern implementation for feature key.

The use of functional options provides a flexible way to optionally specify feature keys while maintaining backward compatibility.


650-690: Well-implemented constructor for usage-based flat fee lines.

The constructor properly creates usage-based lines with flat price semantics. The structure mirrors NewFlatFeeLine while using usage-based line types, which achieves the stated goal of parity.


895-899: Correct conditional validation for feature key requirement.

The validation appropriately makes FeatureKey optional for flat price types since they don't depend on metered quantities, while still requiring it for other price types.

test/billing/ubpflatfee_test.go (3)

26-135: Comprehensive test for pending line creation and invoicing.

The test thoroughly validates the entire flow from line creation to invoicing, including:

  • Proper line creation with expected fields
  • Progressive billing restrictions
  • Invoice generation with detailed lines
  • Total calculations

The test structure is well-organized and covers the key functionality.


137-218: Thorough testing of percentage discount functionality.

The test validates that percentage discounts are correctly applied to usage-based flat fee lines, including verification of discount amounts and total calculations on both parent and detailed lines.


220-283: Good validation testing with appropriate error expectations.

The tests correctly verify that:

  • Usage discounts are rejected (as expected for flat fee semantics)
  • Empty periods are allowed (appropriate for flat fees)

The validation logic aligns with the business requirements.

openmeter/billing/service/lineservice/detailedlines.go (5)

15-46: Well-designed input struct with proper validation.

The newDetailedLineInput struct captures all necessary fields for detailed line creation. The validation method properly checks for non-negative values and required fields.


48-70: Correct total amount calculation with currency precision.

The total calculation properly handles currency rounding and discount subtraction. The use of a separate input struct promotes reusability.


78-120: Sophisticated discount logic for overage scenarios.

The AddDiscountForOverage method correctly handles different discount scenarios:

  • No discount when under max spend
  • Full discount when already over max spend before this line
  • Partial discount when this line pushes over the limit

The logic is mathematically sound and handles edge cases properly.


122-167: Robust detailed line creation with proper defaults.

The function properly:

  • Validates each input
  • Applies sensible defaults (period, category, payment term)
  • Creates well-formed billing lines
  • Validates the final result

The error handling is appropriate and informative.


181-200: Efficient merging with ID reuse for consistency.

The merge function properly:

  • Creates detailed lines from inputs
  • Assigns sequential indices
  • Reuses existing child IDs to avoid unnecessary delete/create operations
  • Handles errors appropriately

This promotes database efficiency and maintains referential integrity.

Comment thread test/billing/collection_test.go Resolved
@turip
turip force-pushed the feat/implement-ubp-flat-fee branch from 1d422b9 to 460fa54 Compare May 26, 2025 13:19
}

if i.InvoiceAt.Before(i.Period.Truncate(DefaultMeterResolution).End) {
if i.DependsOnMeteredQuantity() && i.InvoiceAt.Before(i.Period.Truncate(DefaultMeterResolution).End) {

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.

nit / comment for later: at some point we should consolidate things named Period, i think the current timeutil.Period has everything this has except .Truncate

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agree, that's on my bucket list ;-)

Comment on lines +562 to +572
func (i Line) DependsOnMeteredQuantity() bool {
if i.Type != InvoiceLineTypeUsageBased {
return false
}

if i.UsageBased.Price.Type() == productcatalog.FlatPriceType {
return false
}

return true
}

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.

I know I know very little about the scope being touched here, so this is more for my understanding:

This patch is weird for me as in that we want to support Flat pricing modes for usage based lines. I don't see what other attribute of "usage based" remains for a line if the price is flat.

In the PR description you wrote this is about feature parity between a flat fee line and a usage based line with a flat price (first I thought that would be like a tiered price with a single flat tier, but i realise that would be encapsulated in line.Price so no...)

To finally spit it out, what does a usage based line with a flat price mean / represent? Its weird for me they exist

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Totally agree: the plan is to rename this usagebased line to invoiceline, as this is not only an usage based line.

However due to how invoicing is structured, this is a gradual process where first I want to get rid of the flat fee/usage based line union. So yes, agree, we will get there.

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.

Ah okay, I got the big picture now, TY!

@turip
turip merged commit 88a5290 into main May 27, 2025
@turip
turip deleted the feat/implement-ubp-flat-fee branch May 27, 2025 08:30
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.

3 participants