Repository navigation
feat: implement ubp flat fee - #2886
Conversation
📝 WalkthroughWalkthroughThis 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
Possibly related PRs
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 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (12)
💤 Files with no reviewable changes (3)
⏰ Context from checks skipped due to timeout of 90000ms (2)
🔇 Additional comments (28)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
17d08b1 to
d7fbc55
Compare
There was a problem hiding this comment.
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
ubpLineCalculatorinterface enables clean testing of bothusageBasedLineandubpFlatFeeLineimplementations 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
flatFeefields to both structs is appropriate for the new architecture. TheubpPendingLines.flatFeefield is actively used in tests.Note: The
ubpFeatures.flatFeefield 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
⛔ Files ignored due to path filters (1)
tools/migrate/migrations/atlas.sumis 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_keycolumn 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_keycolumn nullable in theBillingInvoiceUsageBasedLineConfigstable 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()toOptional().Nillable()properly makes thefeature_keyfield 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
FeatureKeyIsNilandFeatureKeyNotNilpredicates 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
Quantityis 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.Quantitycorrectly 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
FeatureKeyfield 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
SetNillableFeatureKeymethod 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
FeatureKeyfield 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.Lineand 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
ubpFlatFeeLineimplementation. 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
UpdateTotalsFromDetailedLinesmethod 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
MeteredQuantityandMeteredPreLinePeriodQuantityfollows 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 supportThe return type change from
stringto*stringcorrectly implements nullable field support forfeature_key, aligning with the PR objectives to make this field optional.
21800-21810: LGTM: Proper implementation of clear/check methodsThe new
ClearFeatureKey()andFeatureKeyCleared()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 managementThe
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 enumerationThe
ClearedFields()method correctly includesfeature_keywhen it has been cleared, maintaining consistency with other nullable fields in the system.
22216-22218: LGTM: Complete integration with generic clear methodThe
ClearField()method correctly handles thefeature_keyfield by delegating to the specificClearFeatureKey()method, completing the nullable field implementation.
21786-22218:Details
✅ Verification successful
Verify breaking changes are addressed in dependent code
The change from
stringto*stringfor thefeature_keyfield is a breaking change. Ensure that all code usingOldFeatureKey()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 goLength of output: 49069
OldFeatureKey() usage verified—no action needed
All occurrences ofOldFeatureKey()are confined to the generated ent mutations, and there are no external callers that need to handle a*stringreturn. The mutation code already correctly returns and propagates a nullable*string.test/billing/suite.go (3)
458-471: Well-implemented functional options patternThe 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 implementationThe function correctly marshals both values to JSON and uses
require.JSONEqfor structural comparison. Thet.Helper()call is properly included to improve test failure reporting.
480-480:Details
❌ Incorrect review comment
Verify that MinimalCreateProfileInputTemplate is defined
The code references
MinimalCreateProfileInputTemplatebut 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 goLength of output: 397
No action required: MinimalCreateProfileInputTemplate is already defined
The identifier is declared intest/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:
- FlatFee lines maintain their original periods (not truncated like other usage-based lines)
- Detailed line calculations are accurate with quantity=1 and correct per-unit amounts
- 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:
- Period Consistency: FlatFee lines maintain original periods while usage-based lines are truncated
- Detailed Line Structure: Proper quantity=1 and amount=100 validation
- 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
PrepareForCreatemethod 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
CanBeInvoicedAsOflogic 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:
SnapshotQuantityas a no-op since flat fees have pre-set quantities- Pricing calculation using the appropriate
flatPricerwith 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
DependsOnMeteredQuantitymethod 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
NewUsageBasedFlatFeeLineconstructor:
- 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
FeatureKeyoptional 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.UpdateTotalsFromDetailedLinesensures consistent total calculation across different line types.
187-189: Consistent use of shared detailed line merging logic.Using the
mergeDetailedLineshelper 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
FlatPriceTypehandling fromgetPriceris correct sinceubpFlatFeeLinenow handles flat price usage-based lines. However, let's verify that the service layer properly routes flat price lines toubpFlatFeeLine.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
FlatPriceTypecase fromgetPriceris safe because the service layer now routes flat-price lines toubpFlatFeeLinebefore falling back tousageBasedLine. Tests inusagebasedline_test.goandpriceflat_test.goconfirm 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.
6ce6261 to
fb40eeb
Compare
fb40eeb to
1d422b9
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🔭 Outside diff range comments (2)
openmeter/billing/httpdriver/invoiceline.go (2)
180-216:⚠️ Potential issueAdd similar price validation to maintain consistency.
The
mapCreatePendingUsageBasedLineToEntityfunction should include the same price validation and conditional quantity initialization logic that was added tomapUsageBasedSimulationLineToEntity. 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 issueFix incorrect line type assignment.
The line type is incorrectly set to
billing.InvoiceLineTypeFeefor 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 copyThe implementation assigns
MinimalCreateProfileInputTemplatedirectly toclonedCreateProfileInput, 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
⛔ Files ignored due to path filters (1)
tools/migrate/migrations/atlas.sumis 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_keyfield nullable in thebilling_invoice_usage_based_line_configstable, 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*stringfor 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_keyoptional 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 inopenmeter/billing/invoiceline.go(lines 895–900) correctly enforces that:
- Non-flat-price lines (
i.Price.Type() != productcatalog.FlatPriceType) require a non-emptyfeatureKey.- Flat-fee lines skip the
featureKeycheck, 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()andFeatureKeyNotNil()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 ofalpacadecimal.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 fileThis 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 implementationAdding the
Quantityfield 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 consistencyUsing
periodStartandperiodEnddirectly instead of theexpected*variables improves test clarity and consistency.openmeter/ent/db/billinginvoiceusagebasedlineconfig_create.go (1)
1-1: Skip review for auto-generated fileThis file is auto-generated by Ent ORM and should not be manually edited. The changes here reflect the schema modifications making
FeatureKeyoptional 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
FeatureKeyfield 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
ubpFlatFeeLineimplementation, which is essential for the new usage-based flat fee feature.
154-193: Well-implemented helper method with excellent documentation.The
UpdateTotalsFromDetailedLinesmethod 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
ubpLineCalculatorinterface 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.Lineobject 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
ubpFlatFeeLineorusageBasedLinebased 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
flatPerUsagetoflatFee, making the test data setup consistent with the new terminology.
1539-1559: Excellent addition of flat fee period validation.The renaming from
flatPerUsagetoflatFeeimproves 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.flatFeefrom 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
flatPerUsagetoflatFeeis 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
flatPerUsagetoflatFeein bothubpPendingLinesandubpFeaturesstructs 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.Priceis 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
stringto*stringcorrectly reflects the schema change makingfeature_keynullable. This follows ent's standard pattern for nullable fields.
21800-21810: LGTM: Standard ent nullable field methods implemented correctly.The new methods
ClearFeatureKey()andFeatureKeyCleared()follow ent's established patterns for nullable field handling:
ClearFeatureKey()correctly sets the field to nil and marks it inclearedFieldsFeatureKeyCleared()properly checks theclearedFieldsmap
21815-21815: LGTM: Field reset correctly updated.The addition of
delete(m.clearedFields, billinginvoiceusagebasedlineconfig.FieldFeatureKey)ensures that the cleared state is properly reset whenResetFeatureKey()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 toClearFeatureKey()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
mergeDetailedLinesfunction 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
NewFlatFeeLinewhile 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
FeatureKeyoptional 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
newDetailedLineInputstruct 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
AddDiscountForOveragemethod 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.
1d422b9 to
460fa54
Compare
| } | ||
|
|
||
| if i.InvoiceAt.Before(i.Period.Truncate(DefaultMeterResolution).End) { | ||
| if i.DependsOnMeteredQuantity() && i.InvoiceAt.Before(i.Period.Truncate(DefaultMeterResolution).End) { |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Agree, that's on my bucket list ;-)
| func (i Line) DependsOnMeteredQuantity() bool { | ||
| if i.Type != InvoiceLineTypeUsageBased { | ||
| return false | ||
| } | ||
|
|
||
| if i.UsageBased.Price.Type() == productcatalog.FlatPriceType { | ||
| return false | ||
| } | ||
|
|
||
| return true | ||
| } |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Ah okay, I got the big picture now, TY!
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:
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]:
Summary by CodeRabbit