Repository navigation
feat: add amount discount support - #2596
Conversation
📝 WalkthroughWalkthroughThis pull request implements a comprehensive refactoring of discount handling throughout the invoicing codebase. It updates discount retrieval methods, function signatures, and error handling, and replaces generic discount types with more specific ones (e.g. from billing.LineDiscount to billing.AmountLineDiscountManaged). In addition, new discount types, mutation methods, and validation functions have been introduced. The database schema and migration scripts have been modified to support new discount fields (including type, rounding amount, quantity, pre‑line period quantity, and source discount). Test cases and utility packages have also been updated to reflect these changes. 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 🔧 SQLFluff (3.3.0)tools/migrate/migrations/20250407191828_billing-line-discount-unit-support.up.sqlUser Error: No dialect was specified. You must configure a dialect or specify one on the command line using --dialect after the command. Available dialects: tools/migrate/migrations/20250407191828_billing-line-discount-unit-support.down.sqlUser Error: No dialect was specified. You must configure a dialect or specify one on the command line using --dialect after the command. Available dialects: ✨ 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:
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 (
|
05c8ef6 to
a8cfe4b
Compare
424042d to
c0ee90d
Compare
fe90ce9 to
4cf7f1d
Compare
b9d89fc to
669ef43
Compare
c66bd85 to
ad55a27
Compare
ad55a27 to
dc269c2
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
test/billing/adapter_test.go (1)
552-552: Reusing child references again.
Similar test coverage forChildrenWithIDReuse. No further concerns.
🧹 Nitpick comments (9)
openmeter/ent/db/predicate/predicate.go (1)
84-93: Good addition maintaining consistent error handling pattern.The
BillingInvoiceLineDiscountOrErrfunction correctly implements the error handling pattern used throughout the file, ensuring that errors are properly propagated to the SQL selector.Note: There's a typo in the comment "nit" should be "nil", but this appears to be consistent with other similar function comments in the file.
openmeter/billing/adapter/invoicelinediff.go (1)
379-400: Ensure correctness of discount creation and deletion flow.This block implements a "difference" approach to manage discounts:
- Missing in current → delete from DB.
- New in current → create in DB.
The logic appears sound, but ensure:
- Concurrent modifications are prevented or handled transactionally.
- Tests confirm each path (create, delete, unchanged) is verified.
You could augment test coverage to verify partial updates (e.g., changing only the discount reason) do not incorrectly trigger re-creation or deletion.
openmeter/billing/adapter/invoicelines.go (1)
244-252: Properly mark a discount as deleted.This code uses
d.Discount.MutatewithMarkDiscountDeletedand returns a newdiscountWithLine. The approach is concise and clear. Confirm that the time used for deletion is consistent across all discount deletions (UTC-based) to prevent time-zone confusion.Consider logging or auditing discount deletions to assist with debugging or regulatory requirements.
test/billing/adapter_test.go (1)
703-704: Naming consistency check.
The struct fieldLineSetDiscountMangedFieldssuggests a possible typo in “Manged”. Consider renaming to “ManagedFields” throughout the code for clarity.- LineSetDiscountMangedFields + LineSetDiscountManagedFieldsopenmeter/billing/adapter/invoicelinediff_test.go (2)
48-50: Add an assertion for discount usage in tests.Defining
FlatFeeandDiscountswithnewDiscountsWithIDs("D2.1.1")is fine, but consider adding assertions to verify that the discount is actually recognized by the diff logic. This helps ensure the discount IDs are correctly tracked in invoice line diffing.
177-179: Consider fixing the “Manged” spelling in method naming (if not generated).Using
billing.SetDiscountMangedFieldsmight be a small typo. If it’s not auto-generated, rename it toSetDiscountManagedFieldsfor clarity. Otherwise, everything looks fine here for testing mutation of discount fields.openmeter/ent/db/billinginvoicelinediscount.go (1)
267-269: String representation for discount type.Including
type=%vin the string builder is a good practice for debugging.You might want to wrap the discount type with quotes or brackets (“type=<%v>”) for uniform logging style, although this is optional.
openmeter/ent/db/mutation.go (1)
18604-18816: New fields (rounding_amount, quantity, pre_line_period_quantity, source_discount) are properly introduced.
All methods (Set, Get, Old, Clear, Reset) are consistent with Ent’s conventions.
A minor note: storingsource_discountas a pointer to a pointer (**productcatalog.Discount) is unusual. If not strictly necessary, consider using a single pointer to reduce potential confusion.openmeter/billing/invoicelinediscount.go (1)
757-765: GetDiscountByChildUniqueReferenceID method.
Linear search is likely fine for typical discount list sizes. For large sets, consider a map-based approach, but YAGNI might apply.
📜 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 (37)
openmeter/app/stripe/entity/app/invoice.go(6 hunks)openmeter/billing/adapter/invoicelinediff.go(3 hunks)openmeter/billing/adapter/invoicelinediff_test.go(7 hunks)openmeter/billing/adapter/invoicelinemapper.go(2 hunks)openmeter/billing/adapter/invoicelines.go(2 hunks)openmeter/billing/app.go(1 hunks)openmeter/billing/httpdriver/invoiceline.go(1 hunks)openmeter/billing/invoiceline.go(5 hunks)openmeter/billing/invoicelinediscount.go(1 hunks)openmeter/billing/service/lineservice/feeline.go(1 hunks)openmeter/billing/service/lineservice/usagebasedline.go(4 hunks)openmeter/billing/service/lineservice/usagebasedline_test.go(9 hunks)openmeter/ent/db/billinginvoicediscount.go(4 hunks)openmeter/ent/db/billinginvoicediscount/billinginvoicediscount.go(2 hunks)openmeter/ent/db/billinginvoicediscount/where.go(2 hunks)openmeter/ent/db/billinginvoicediscount_create.go(7 hunks)openmeter/ent/db/billinginvoicediscount_update.go(7 hunks)openmeter/ent/db/billinginvoicelinediscount.go(7 hunks)openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go(6 hunks)openmeter/ent/db/billinginvoicelinediscount/where.go(3 hunks)openmeter/ent/db/billinginvoicelinediscount_create.go(21 hunks)openmeter/ent/db/billinginvoicelinediscount_update.go(13 hunks)openmeter/ent/db/migrate/schema.go(4 hunks)openmeter/ent/db/mutation.go(21 hunks)openmeter/ent/db/predicate/predicate.go(1 hunks)openmeter/ent/db/runtime.go(1 hunks)openmeter/ent/db/setorclear.go(1 hunks)openmeter/ent/schema/billing.go(3 hunks)openmeter/ent/schema/productcatalog.go(1 hunks)openmeter/productcatalog/discount.go(3 hunks)pkg/equal/equal.go(2 hunks)pkg/models/model.go(2 hunks)test/app/stripe/invoice_test.go(2 hunks)test/billing/adapter_test.go(5 hunks)test/billing/invoice_test.go(5 hunks)tools/migrate/migrations/20250407191828_billing-line-discount-unit-support.down.sql(1 hunks)tools/migrate/migrations/20250407191828_billing-line-discount-unit-support.up.sql(1 hunks)
🧰 Additional context used
🧬 Code Definitions (20)
openmeter/ent/db/predicate/predicate.go (2)
openmeter/ent/db/billinginvoicelinediscount.go (2)
BillingInvoiceLineDiscount(20-58)BillingInvoiceLineDiscount(81-98)openmeter/ent/schema/billing.go (5)
BillingInvoiceLineDiscount(500-502)BillingInvoiceLineDiscount(504-510)BillingInvoiceLineDiscount(512-576)BillingInvoiceLineDiscount(578-587)BillingInvoiceLineDiscount(589-597)
openmeter/billing/service/lineservice/feeline.go (1)
openmeter/productcatalog/discount.go (1)
Discounts(346-346)
openmeter/billing/app.go (2)
openmeter/productcatalog/discount.go (1)
Discounts(346-346)openmeter/billing/invoicelinediscount.go (1)
SetDiscountInvoicingExternalID(537-563)
openmeter/billing/adapter/invoicelinemapper.go (4)
openmeter/billing/invoicelinediscount.go (7)
LineDiscount(289-325)LineDiscountBase(62-69)LineSetDiscountMangedFields(38-41)AmountLineDiscountManaged(148-151)AmountLineDiscount(100-108)UsageLineDiscountManaged(235-238)UsageLineDiscount(186-191)openmeter/ent/schema/billing.go (5)
BillingInvoiceLineDiscount(500-502)BillingInvoiceLineDiscount(504-510)BillingInvoiceLineDiscount(512-576)BillingInvoiceLineDiscount(578-587)BillingInvoiceLineDiscount(589-597)openmeter/billing/invoiceline.go (1)
LineExternalIDs(234-236)pkg/models/model.go (1)
ManagedModel(107-113)
openmeter/billing/adapter/invoicelines.go (3)
openmeter/ent/db/billinginvoicelinediscount.go (2)
BillingInvoiceLineDiscount(20-58)BillingInvoiceLineDiscount(81-98)openmeter/ent/schema/billing.go (5)
BillingInvoiceLineDiscount(500-502)BillingInvoiceLineDiscount(504-510)BillingInvoiceLineDiscount(512-576)BillingInvoiceLineDiscount(578-587)BillingInvoiceLineDiscount(589-597)openmeter/billing/invoicelinediscount.go (3)
LineDiscountTypeAmount(276-276)LineDiscountTypeUsage(277-277)MarkDiscountDeleted(613-620)
openmeter/billing/httpdriver/invoiceline.go (3)
openmeter/billing/invoicelinediscount.go (2)
LineDiscountTypeAmount(276-276)LineDiscountTypeUsage(277-277)api/api.gen.go (5)
InvoiceLineDiscount(3291-3293)InvoiceLineDiscountAmount(3296-3326)InvoiceDiscountReason(3023-3023)InvoiceLineAppExternalIds(3282-3288)InvoiceLineDiscountUsage(3334-3369)api/client/go/client.gen.go (5)
InvoiceLineDiscount(3031-3033)InvoiceLineDiscountAmount(3036-3066)InvoiceDiscountReason(2763-2763)InvoiceLineAppExternalIds(3022-3028)InvoiceLineDiscountUsage(3074-3109)
openmeter/billing/service/lineservice/usagebasedline_test.go (1)
openmeter/billing/invoicelinediscount.go (6)
NewLineDiscounts(625-627)NewLineDiscountFrom(334-361)AmountLineDiscount(100-108)LineDiscountBase(62-69)LineMaximumSpendReferenceID(21-21)LineDiscountReasonMaximumSpend(27-27)
openmeter/billing/adapter/invoicelinediff.go (1)
openmeter/productcatalog/discount.go (1)
Discounts(346-346)
openmeter/ent/schema/billing.go (3)
openmeter/billing/invoicelinediscount.go (4)
LineDiscountType(273-273)LineDiscountType(280-285)LineDiscountReason(24-24)LineDiscountReason(31-36)openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (1)
ValueScanner(106-108)openmeter/ent/schema/productcatalog.go (1)
DiscountValueScanner(218-218)
openmeter/billing/invoiceline.go (1)
openmeter/productcatalog/discount.go (1)
Discounts(346-346)
openmeter/ent/db/billinginvoicediscount_create.go (2)
openmeter/billing/invoicelinediscount.go (2)
LineDiscountType(273-273)LineDiscountType(280-285)openmeter/ent/db/billinginvoicediscount/billinginvoicediscount.go (1)
TypeValidator(84-91)
openmeter/app/stripe/entity/app/invoice.go (2)
openmeter/billing/invoicelinediscount.go (1)
AmountLineDiscountManaged(148-151)openmeter/billing/invoiceline.go (1)
Line(278-291)
openmeter/ent/db/billinginvoicelinediscount.go (3)
openmeter/billing/invoicelinediscount.go (4)
LineDiscountType(273-273)LineDiscountType(280-285)LineDiscountReason(24-24)LineDiscountReason(31-36)openmeter/productcatalog/discount.go (1)
Discount(54-58)openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (5)
FieldRoundingAmount(42-42)FieldQuantity(44-44)FieldPreLinePeriodQuantity(46-46)FieldSourceDiscount(48-48)ValueScanner(106-108)
openmeter/billing/invoicelinediscount.go (4)
pkg/models/model.go (1)
ManagedModel(107-113)openmeter/billing/invoiceline.go (1)
LineExternalIDs(234-236)pkg/equal/equal.go (1)
Equaler(9-11)pkg/slicesx/empty.go (1)
EmptyAsNil(6-11)
openmeter/ent/db/billinginvoicediscount/where.go (3)
openmeter/billing/invoicelinediscount.go (2)
LineDiscountType(273-273)LineDiscountType(280-285)openmeter/ent/schema/billing.go (4)
BillingInvoiceDiscount(600-602)BillingInvoiceDiscount(604-608)BillingInvoiceDiscount(610-628)BillingInvoiceDiscount(630-634)openmeter/ent/db/billinginvoicediscount/billinginvoicediscount.go (1)
FieldType(35-35)
openmeter/ent/db/mutation.go (3)
openmeter/billing/invoicelinediscount.go (2)
LineDiscountType(273-273)LineDiscountType(280-285)openmeter/ent/db/billinginvoicediscount/billinginvoicediscount.go (1)
FieldType(35-35)openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (5)
FieldRoundingAmount(42-42)FieldQuantity(44-44)FieldPreLinePeriodQuantity(46-46)FieldSourceDiscount(48-48)FieldType(30-30)
openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (3)
openmeter/ent/db/billinginvoicediscount/billinginvoicediscount.go (4)
FieldType(35-35)TypeValidator(84-91)ByType(137-139)OrderOption(94-94)openmeter/productcatalog/discount.go (1)
Discount(54-58)openmeter/billing/invoicelinediscount.go (2)
LineDiscountType(273-273)LineDiscountType(280-285)
openmeter/ent/db/billinginvoicelinediscount_create.go (4)
openmeter/ent/db/billinginvoicediscount/billinginvoicediscount.go (2)
TypeValidator(84-91)FieldType(35-35)openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (4)
TypeValidator(112-119)FieldType(30-30)FieldSourceDiscount(48-48)FieldLineID(34-34)openmeter/ent/db/billinginvoicelinediscount/where.go (5)
LineID(91-93)Amount(106-108)RoundingAmount(111-113)Quantity(116-118)PreLinePeriodQuantity(121-123)openmeter/ent/db/billinginvoicelinediscount.go (2)
BillingInvoiceLineDiscount(20-58)BillingInvoiceLineDiscount(81-98)
openmeter/ent/db/billinginvoicelinediscount_update.go (5)
openmeter/billing/invoicelinediscount.go (2)
LineDiscountType(273-273)LineDiscountType(280-285)openmeter/productcatalog/discount.go (1)
Discount(54-58)openmeter/ent/db/billinginvoicediscount/billinginvoicediscount.go (3)
TypeValidator(84-91)FieldType(35-35)FieldAmount(37-37)openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (8)
TypeValidator(112-119)ReasonValidator(122-129)FieldType(30-30)FieldAmount(40-40)FieldRoundingAmount(42-42)FieldQuantity(44-44)FieldPreLinePeriodQuantity(46-46)FieldSourceDiscount(48-48)openmeter/ent/db/billinginvoicelinediscount/where.go (3)
RoundingAmount(111-113)Quantity(116-118)PreLinePeriodQuantity(121-123)
openmeter/ent/db/billinginvoicelinediscount/where.go (5)
openmeter/ent/db/billinginvoicelinediscount.go (2)
BillingInvoiceLineDiscount(20-58)BillingInvoiceLineDiscount(81-98)openmeter/ent/db/predicate/predicate.go (1)
BillingInvoiceLineDiscount(82-82)openmeter/ent/schema/billing.go (5)
BillingInvoiceLineDiscount(500-502)BillingInvoiceLineDiscount(504-510)BillingInvoiceLineDiscount(512-576)BillingInvoiceLineDiscount(578-587)BillingInvoiceLineDiscount(589-597)openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (7)
FieldRoundingAmount(42-42)FieldQuantity(44-44)FieldPreLinePeriodQuantity(46-46)FieldType(30-30)FieldReason(32-32)FieldAmount(40-40)FieldSourceDiscount(48-48)openmeter/ent/db/billinginvoicediscount/billinginvoicediscount.go (2)
FieldType(35-35)FieldAmount(37-37)
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: CI
- GitHub Check: Quickstart
- GitHub Check: E2E
- GitHub Check: Developer environment
- GitHub Check: Lint
- GitHub Check: Commit hooks
- GitHub Check: Test
- GitHub Check: Build
- GitHub Check: Analyze (go)
🔇 Additional comments (278)
openmeter/ent/db/migrate/schema.go (3)
625-625: Enhancing discount flexibility with enum typeThe addition of the
typefield as an enum with values "amount" and "usage" provides better type safety and clearly distinguishes between different discount types.
818-826: Good schema design for enhanced discount capabilitiesThe changes to
BillingInvoiceLineDiscountsColumnsimplement a comprehensive approach to handling different discount types:
- Adding a type enum field with "amount" and "usage" values
- Making the amount field nullable since it might not be required for all discount types
- Adding new fields for supporting unit-based discounts:
- rounding_amount: For handling rounding adjustments
- quantity: For unit-based discount amounts
- pre_line_period_quantity: For tracking pre-period quantities
- source_discount: For storing the original discount information
This schema design enables the flexibility needed to support both amount-based and unit-based discounts.
836-866: Properly updated foreign key referencesThe updates to foreign key references and indexes correctly accommodate the new columns in the schema, ensuring database integrity is maintained.
pkg/models/model.go (1)
139-153: Clean implementation of model equality checkThe
Equalmethod provides a thorough comparison ofManagedModelinstances by checking all fields:
- Properly uses
time.Equal()for time comparisons- Correctly handles nil pointer comparison for
DeletedAtusingequal.PtrEqual- Returns early if any field doesn't match
This is a valuable addition for model comparison in validation, testing, and business logic.
openmeter/ent/schema/productcatalog.go (1)
218-218: Added consistent JSON scanner for Discount typeThe new
DiscountValueScannerfollows the established pattern in the codebase, facilitating JSON serialization/deserialization for the Discount type. This supports the new discount structure introduced in this PR.tools/migrate/migrations/20250407191828_billing-line-discount-unit-support.down.sql (1)
1-2: Properly structured down migrationThe down migration correctly reverts all schema changes by:
- Dropping all newly added columns (
source_discount,pre_line_period_quantity,quantity,rounding_amount,type)- Restoring the NOT NULL constraint on the
amountcolumnThis ensures a clean rollback path if needed.
openmeter/ent/db/billinginvoicediscount/billinginvoicediscount.go (1)
83-91: Well-implemented validator for discount types.The
TypeValidatorfunction cleanly enforces the valid values for the discount type field, ensuring that only "amount" or "usage" values are accepted. This is aligned with the PR objective of supporting amount discounts via a union type.openmeter/ent/db/runtime.go (1)
515-517: Correctly configured schema descriptor for source_discount field.The addition properly sets up the value scanner for the
source_discountfield, allowing the ORM to correctly handle theproductcatalog.Discounttype in database operations. This aligns with the broader discount support improvements in the PR.pkg/equal/equal.go (3)
7-11: Well-designed generic interface for equality comparisons.The
Equaler[T any]interface provides a clean, reusable contract for objects that can be compared for equality. The comment explaining the duplication to avoid circular dependencies shows good architectural awareness.
13-23: Good adaptation of the equality function to use the new interface.The
PtrEqualfunction correctly handles nil pointer cases and leverages the object's own equality implementation, providing a consistent pattern for pointer equality checks.
25-35: Excellent addition of hash-based equality checking.The
HasherPtrEqualfunction provides an efficient way to compare objects based on their hash values. This is particularly useful for complex objects where direct field-by-field comparison would be expensive. The implementation properly handles nil cases and follows the same pattern asPtrEqual.openmeter/billing/service/lineservice/feeline.go (1)
48-48: Code simplification looks good.The change from using
lo.Mapto directly callingl.line.Discounts.SumAmount(calc)improves readability and encapsulates the discount calculation logic in a single method call.openmeter/ent/db/billinginvoicediscount.go (4)
14-14: Import addition for stronger typing.Adding the
billingpackage import enables the use of more specific domain types.
40-40: Enhanced type safety with domain-specific type.Replacing
stringwithbilling.LineDiscountTypeimproves type safety and makes the code more self-documenting by clearly indicating what values are valid for this field.
138-138: Consistent type casting for DB values.The adaptation to cast the string value to
billing.LineDiscountTypeproperly maintains the new typing throughout the data flow.
219-219: Updated string representation for typed value.Using
fmt.Sprintf("%v", bid.Type)ensures proper string representation of the typed value in debug output.openmeter/billing/app.go (1)
215-229: Improved discount handling with better error reporting.The refactored approach for handling line discount IDs is cleaner and more direct. You've:
- Simplified the code by directly accessing external IDs from the result
- Used a structured approach with
MutateandSetDiscountInvoicingExternalID- Added detailed error messages that include the discount ID
This makes the code more maintainable and provides better debugging information.
openmeter/productcatalog/discount.go (3)
10-10: Import addition for equality comparison.Adding the
equalpackage enables more robust equality checks for discount types.
219-232: Solid implementation of equality comparison.The addition of the
Equalmethod provides a structured way to compare discount instances based on their type and content. The type-specific comparison is handled appropriately usingequal.HasherPtrEqualfor robust value comparison.
368-376: Refined discount collection equality check.Using hash-based comparison for discount collections is an efficient approach that ensures proper equality checks regardless of discount order in the collections.
test/app/stripe/invoice_test.go (2)
561-564: Consistent access pattern for discount propertiesThe code now uses the helper method
getDiscountDecriptioninstead of directly accessingdiscount.Description, and callsGetID()instead of accessingdiscount.IDdirectly. This change supports the new union type structure for discounts that accommodates both amount and unit discounts.
1118-1129: Well-structured discount description extractionThe new helper method properly handles the extraction of discount descriptions by converting to the base discount type first and includes appropriate error handling. This abstraction cleanly supports the union type approach for discounts.
openmeter/billing/adapter/invoicelinemapper.go (2)
214-220: Improved error handling in discount mappingThe code now uses
slicesx.MapWithErrinstead oflo.Map, providing proper error propagation when mapping invoice line discounts. The descriptive error messages will help with debugging issues related to discount mapping.
226-279: Well-structured discount type handlingThe new
mapInvoiceLineDiscountFromDBmethod provides a clean separation of concerns for mapping different discount types. It includes:
- Proper validation for required fields (
amountfor amount discounts,quantityfor usage discounts)- Type-specific handling for amount and usage discounts
- Clear error messages for different validation failures
- Thorough field mapping for each discount type
This structured approach supports the union type model for discounts while maintaining strong validation and error reporting.
tools/migrate/migrations/20250407191828_billing-line-discount-unit-support.up.sql (1)
1-5: Database schema correctly updated for union type discountsThe migration properly alters the
billing_invoice_line_discountstable to support the new union type discount structure:
- Makes
amountnullable for usage-based discounts- Adds
typediscriminator column to distinguish discount types- Adds necessary columns for each discount type (
rounding_amount,quantity,pre_line_period_quantity,source_discount)- Correctly handles default values
This change forms the database foundation for the discount type enhancements.
openmeter/billing/service/lineservice/usagebasedline_test.go (3)
403-413: Tests updated to use the new discount structureThe test cases now correctly use the new discount structure with factory methods
billing.NewLineDiscountsandbilling.NewLineDiscountFrom. This ensures that the tests validate the behavior with the new union type model.
594-604: Consistent discount creation pattern across test casesThe discount creation follows a consistent pattern throughout the test file, making the tests more maintainable and clear. The structured approach with
LineDiscountBaseproperly separates common discount properties from type-specific ones.
839-848: Comprehensive discount property coverage in testsThe test discounts include all relevant properties:
- Amount for the discount value
- Description for human-readable context
- ChildUniqueReferenceID for tracking relationships
- Reason to categorize the discount type
This ensures thorough testing of the discount functionality.
openmeter/billing/adapter/invoicelinediff.go (3)
404-419:Details
❓ Verification inconclusive
Validate the equality check for discount updates.
Here, the code:
- Throws an error if a discount isn’t found in the DB.
- Updates the discount only when
ContentsEqualis false.This approach is effective. However, confirm that
ContentsEquallogs or captures any sub-field mismatches for debugging. If floating-point amounts are involved, consider possible rounding issues or approximate comparisons.
🏁 Script executed:
#!/bin/bash # Searching for ContentsEqual across the codebase to see if there's any specialized float comparison rg -A 5 "ContentsEqual"Length of output: 2822
Attention: Enhance Debug Logging and Handle Float Comparisons in Discount Equality Check
The current implementation in
openmeter/billing/adapter/invoicelinediff.go(lines 404-419) correctly verifies discount presence and triggers an update whenContentsEqual()returns false. However, please ensure that:
- The
ContentsEqual()method (defined inopenmeter/billing/invoicelinediscount.go) is updated to capture or log the specific sub-field mismatches, to aid debugging when differences occur.- If any floating-point fields are compared within discounts, verify that the implementation either uses approximate comparisons or accounts for potential rounding issues.
These improvements will clarify mismatch details and reduce the risk of false negatives in equality checks.
369-372:Details
✅ Verification successful
Check for null or invalid discount collection before retrieval.
This code correctly retrieves discount IDs via
DiscountsByID()and handles potential errors. Ensure that all callers provide a validline.Discountsobject, and consider adding defensive checks for unexpected nil or malformed discount collections if needed.Would you like me to generate a quick script to confirm there are no other unguarded calls to
DiscountsByID()in the codebase?
🏁 Script executed:
#!/bin/bash rg -A 5 $'DiscountsByID()'Length of output: 3099
Review Confirmation: Code Usage of DiscountsByID Verified
After running the search for
DiscountsByID(), all invocations (in bothopenmeter/billing/adapter/invoicelinediff.goand other parts of the codebase) correctly handle errors, and consistent error checking is applied. The utility method onLineDiscountsreturns non‑nil maps by design, so unless a caller inadvertently passes a nil or malformed discount collection, additional nil checks at the call site aren’t strictly necessary. That being said, ensure that discount collections are always initialized properly at their source to maintain this invariant.
374-377:Details
❓ Verification inconclusive
Maintain consistency between in-memory and DB discount references.
Similar to the previous block, this section also retrieves discount IDs from the DB state and gracefully handles errors. Verify that upstream code guarantees a valid
line.DBStateto avoid nil dereference or partial discount states.Please confirm initialization logic for
line.DBStatereferences is always present by searching for references toline.DBState =.
🏁 Script executed:
#!/bin/bash rg -A 3 $'line\\.DBState ='Length of output: 27
Below is a revised review comment that highlights the need for manual verification of the
line.DBStateinitialization:
Attention: Manual Verification for
line.DBStateInitializationThe snippet in
openmeter/billing/adapter/invoicelinediff.go(lines 374–377) retrieves discount IDs and handles errors as follows:dbDiscountIDs, err := line.DBState.Discounts.DiscountsByID() if err != nil { return fmt.Errorf("failed to get line discounts by ID: %w", err) }Our initial automated search using the literal pattern
line.DBState =did not return any matches. This might mean that the assignment is handled indirectly (for example, through a constructor or helper function), or it might be missing altogether. To be absolutely certain thatline.DBStateis always initialized and that there’s no risk of nil dereferences or partial discount states, please verify the initialization logic manually.
Below is an additional shell script with a more flexible regex pattern to help us capture any assignment to
line.DBStatethat might use different spacing:If this search still yields no evidence of an explicit assignment, a manual review of the upstream initialization (e.g., in constructors or initialization functions) is warranted.
🏁 Script executed:
#!/bin/bash rg -A 3 $'line\\s*\\.\\s*DBState\\s*=' .Length of output: 159
Action Required: Manual Verification of
line.DBStateInitializationThe snippet in
openmeter/billing/adapter/invoicelinediff.go(lines 374–377) handles retrieving discount IDs and error handling correctly. However, our automated search using regex for assignments toline.DBStatedid not return any matches. This result suggests that the initialization may occur indirectly—perhaps in constructor methods or helper functions—or might be missing.Please manually verify that every usage of
line.DBStateis preceded by a safe and complete initialization. Check any initialization logic (e.g., constructors, initializer functions, or indirect assignment patterns) to ensure no nil dereference or partial state can occur.openmeter/billing/adapter/invoicelines.go (4)
184-187: Graceful handling of base discount conversion.If
AsDiscountBase()fails, the function promptly returns an error with context. This is good practice. Verify that upstream logic ensures only valid discounts flow through this path to reduce avoidable runtime errors.
189-202: Initialize and populate discount record with a generated ID if missing.Setting a ULID when
base.IDis empty is consistent with how lines are handled. The assignment of discount fields (type, reason, deletion info, etc.) also looks correct. Just ensure the discount’s reason aligns with your usage in higher-level logic, especially for custom discount reasons.
203-204: Invoicing app external ID usage.By setting
InvoicingAppExternalIDto the base discount’s ID, you unify external references. This is good for traceability. If the discount's.Invoicingfield can be empty, confirm that no unintended empty records are created in the DB.
206-229: Validate type-specific discount logic.This switch covers current discount types (
amountvs.usage). It cleanly delegates to the correct discount structure.
- Potential expansion: Ensure the relevant code path is tested if you add new discount types (e.g. “spread,” “prorated,” etc.).
- Default case returns an error, which helps avoid silent failures.
openmeter/billing/invoiceline.go (5)
238-240: Straightforward equality check.
The implementation of theEqualmethod looks appropriate for comparing theInvoicingfield.
401-402: Cloning discounts when not skipping.
This logic correctly ensures thatDiscountsare deeply cloned unless explicitly skipped.
428-430: Ensuring discount validation.
Adding discount validation errors into the common error slice maintains consistency with other validation checks.
665-670: Reusing discount IDs for updated children.
This approach properly retains existing IDs to avoid unnecessary create/delete cycles. Ensure that any test covering ID reuse includes edge cases (e.g., mismatched discount sets).
674-674: Final return for child lines.
This concise return statement correctly produces the newLineChildren. No issues noted.test/billing/adapter_test.go (22)
477-477: Reuse children in test.
Verifying child line ID reuse in tests helps ensure consistent behavior when reattaching child lines.
480-481: Persisting reused children.
Good practice to check for errors and then store the reused children in the parent line.
555-556: Assert no error before setting children.
The pattern is consistent with your previous checks and maintains clarity in tests.
706-706: Iterating over persisted discounts.
The loop effectively searches for a matching discount. No issues noted.
710-710: Manual discount name check.
Straightforward conditional for identifying the “manual” discount. Looks good.
714-714: Empty-string fallback.
The fallback ensures a valid return path when the discount is not found. No issues here.
718-718: Specifying discount details.
Populating the discount with updated fields is consistent with your logic.
723-723: Updating discount description.
The discount's description is correctly updated to reflect the new text.
727-727: Introducing a new discount.
Adding a new discount entry is handled cleanly. Looks correct.
731-731: Verifying discount content equality.
This ensures the updated discount matches expected data. Proper usage ofContentsEqual.
735-735: Comparing the managed fields.
Verifying that the managed field state remains consistent (created vs updated).
759-760: Retrieve discount by reference ID.
This confirms the discount is fetched correctly, ensuring no ID mismatch.
762-763: Locate discount by description and check content.
The test ensures the newly updated discount is properly recognized.
765-766: Confirming ID retention.
Requiring that the current version reuses the same ID, preventing unintentional discounted item duplication.
775-776: Verifying second discount's content match and fields.
The approach is uniform with the prior discount updates. Looks good.
783-784: Ensuring new discount consistency.
Checks that the third discount and the final set of discounts match. Ideal coverage.
803-804: New helper for discount retrieval.
Adding a dedicated test helperfindDiscountByDescriptionimproves test readability.
808-808: Returning fallback discount.
Ensures a default discount object if none is found. Good fallback design.
810-810: “notfound” placeholder.
Clear placeholder for the fallback discount's description.
812-812: Constructing the fallback discount.
Completes the fallback path for missing discounts. Straightforward approach.
814-815: Extracting discount base and handling errors.
Checking the discount base is valid before continuing. Proper usage ofrequire.NoError.
817-817: Matching discount description.
Final condition ensures the correct discount is returned. Implementation aligns with expectations.openmeter/billing/httpdriver/invoiceline.go (1)
444-502: Robust switch-case for discount mapping.
The move to handle multiple discount types (amountvsusage) with detailed error checks is commendable. This section thoroughly maps each discount type to distinct API models, ensuring type-specific fields (likeAmountvsQuantity) are handled accurately. Consider adding unit tests for edge cases (e.g., unknown discount types) to further solidify this logic.openmeter/billing/service/lineservice/usagebasedline.go (1)
234-239: Ensure test coverage and defensive checks for reused child IDs.This logic properly reuses child IDs and handles errors gracefully. Consider adding a dedicated test scenario to confirm that
childrenWithIDReuseproduces the expected results under edge cases (e.g., reusing IDs when children have been partially updated).openmeter/billing/adapter/invoicelinediff_test.go (2)
227-232: Mutational approach looks good.Assigning a new discount amount via
EditAmountDiscountandlo.Must()is appropriate in test code. This ensures that any errors immediately fail the test. No changes needed here.
253-260: Good demonstration of re-creating a discount.By clearing the discount ID and setting a new description, you test the “delete old discount / create new one” logic. This is a strong coverage for discount lifecycle changes.
openmeter/ent/db/billinginvoicelinediscount.go (19)
16-16: Importing productcatalog package.This new import for
productcatalogis consistent with extending discount functionality. No issues found.
32-33: Use of typed discount field.Replacing a generic type with
billing.LineDiscountTypeimproves type safety. This change aligns well with the new discount handling approach.
36-37: Explicitly tracking the line ID.Introducing
LineIDclarifies the discount’s association with its line. The approach is consistent and straightforward.
43-51: Pointer fields for advanced discount data.Switching to pointer-based decimals (e.g.,
*alpacadecimal.Decimal) and a pointer-basedSourceDiscountallows these fields to be optional. This aligns with supporting partial or null discount data in the database.
85-87: Using sql.NullScanner for numeric fields.Mapping numeric columns to
sql.NullScannerand*alpacadecimal.Decimalis an appropriate solution for handling nullable decimal fields in Ent-generated code. Good choice for robust DB interaction.
92-92: Custom scan for SourceDiscount.Calling
billinginvoicelinediscount.ValueScanner.SourceDiscount.ScanValue()neatly encapsulates how the discount is read from the database. This is clean and consistent with the new discount approach.
139-144: New case for the FieldType in assignValues.Casting the string to
billing.LineDiscountTypeand returning a descriptive error if the type is unexpected ensures correctness. This is a straightforward, safe approach.
152-156: Properly assigning LineID from the scanned value.No concerns. The test for nil vs. valid is standard, and storing
LineIDdirectly is correct.
172-178: Assigning Amount from sql.NullScanner.The code cleanly handles the potential null decimal. Good use of pointers to avoid extraneous zero values.
179-185: Assigning RoundingAmount from sql.NullScanner.Same pattern as Amount. Good for controlling null vs. zero states in discount calculations.
186-192: Assigning Quantity from sql.NullScanner.Maintaining pointer-based quantity is consistent with the rest of the discount fields.
193-199: Assigning PreLinePeriodQuantity.Again, this approach is consistent with pointer-based decimal fields.
200-205: Handling SourceDiscount in assignValues.By calling
.FromValue(values[i]), the code properly decodes the embedded discount object. Excellent approach for storing structured discount data.
273-275: Line ID string output.Including
line_idin theString()method helps quickly identify which line the discount belongs to. No issues here.
286-289: Show amount in string builder.Properly checks for nil pointer before writing. This is consistent with the other discount fields.
291-294: Show rounding_amount in string builder.Consistent approach for optional decimal fields. Looks good.
296-299: Show quantity in string builder.Matches the pattern for all pointer-based decimal fields. No further suggestions.
301-304: Show pre_line_period_quantity in string builder.Again, consistent with the pointer-based approach. No concerns.
306-309: Show source_discount in string builder.Exposing discount details is helpful when debugging. Just be mindful of any sensitive data in SourceDiscount.
Consider verifying that this approach doesn’t inadvertently expose confidential discount info when logs are shared externally.
openmeter/ent/schema/billing.go (4)
514-519: Improved type safety with enum fields for discountsThe addition of enum fields
typeandreasontied tobilling.LineDiscountTypeandbilling.LineDiscountReasonrespectively enhances type safety and validation for discount operations. This aligns with the PR objective of supporting a union type for discounts.
533-559: Enhanced flexibility for different discount typesMaking
amountoptional and nillable while adding new fields likerounding_amount,quantity, andpre_line_period_quantityprovides the necessary structure to support both amount-based and usage-based discounts. This implementation allows for more precise discount calculations.
561-569: Well-structured source discount fieldThe addition of the
source_discountfield with proper JSON type handling and value scanning capability is a good approach for storing the original discount configuration, ensuring data integrity and traceability.
617-618: Consistent type handling for backward compatibilityThe update to the
BillingInvoiceDiscount.typefield to use enum type instead of string maintains consistency with the newerBillingInvoiceLineDiscountschema while preserving backwards compatibility.openmeter/ent/db/billinginvoicediscount_create.go (5)
16-16: Added necessary import for type safetyAdding the billing package import is essential for using the strongly-typed
LineDiscountTypeenum.
108-112: Improved type safety with strongly-typed parametersReplacing string parameter with
billing.LineDiscountTypein theSetTypemethod enforces type safety at compile time, preventing invalid discount types from being used.
214-218: Added robust validation for discount typesThe added validation ensures that only valid discount types (as defined by
billinginvoicediscount.TypeValidator) can be stored, protecting data integrity.
291-293: Consistent field type specificationChanging the field type to
field.TypeEnumin thecreateSpecmethod aligns with the schema definition, ensuring proper data handling in the database.
445-448: Consistent type handling throughout the codebaseThe parameter type change in the
SetTypemethod forBillingInvoiceDiscountUpsertmaintains consistency with other method changes, ensuring uniform type handling throughout the codebase.openmeter/ent/db/setorclear.go (4)
1192-1204: Well-designed helper methods for amount fieldThe
SetOrClearAmountmethods follow a consistent pattern used throughout the codebase, providing a clean way to handle nullable decimal values.
1206-1218: Proper handling for rounding amountsThe
SetOrClearRoundingAmountmethods ensure proper handling of optional rounding values, consistent with the project's pattern for handling nullable fields.
1220-1246: Consistent handling of quantity fieldsBoth
SetOrClearQuantityandSetOrClearPreLinePeriodQuantitymethods maintain consistency with the project's approach to handling optional decimal values, critical for usage-based discounts.
1248-1260: Proper management of complex discount source dataThe
SetOrClearSourceDiscountmethods correctly handle the pointer-to-pointer pattern required for complex JSON objects, ensuring proper serialization and deserialization of discount configuration data.openmeter/ent/db/billinginvoicediscount_update.go (6)
16-16: Added necessary import for type safetyIncluding the billing package import enables the use of strongly-typed enum values for discount types.
121-132: Enhanced type safety in update operationsChanging parameter types for
SetTypeandSetNillableTypemethods from string tobilling.LineDiscountTypeensures type safety during update operations, preventing invalid values.
207-215: Added robust validation for update operationsThe new
checkmethod ensures that only valid discount types can be stored in the database, protecting data integrity during updates.
218-220: Integrated validation into save flowThe validation is properly integrated into the save flow, ensuring that invalid updates are rejected before reaching the database.
257-258: Consistent field type specificationUsing
field.TypeEnuminstead offield.TypeStringensures proper data handling in the database, consistent with the schema definition.
479-492: Consistent validation across structsThe validation logic is correctly duplicated in the
BillingInvoiceDiscountUpdateOnestruct, ensuring consistent validation regardless of which update method is used.openmeter/app/stripe/entity/app/invoice.go (7)
187-187: Changed discount retrieval from DiscountsByID to GetAmountDiscountsThis method change aligns with the PR's goal of enhancing discount types, now specifically retrieving amount-based discounts instead of using the generic method.
296-299: Added proper error handling for amount discounts retrievalGood addition of error handling for the
GetAmountDiscountsByID()call. This improves robustness and provides a clear error message if retrieval fails.
302-302: Updated discount retrieval in updateInvoice methodThe change to use the retrieved
amountDiscountsByIdarray is consistent with the other discount handling changes and allows for better error handling.
430-431: Updated discount parameter type to AmountLineDiscountManagedThe parameter type change from
billing.LineDiscounttobilling.AmountLineDiscountManagedimproves type safety and aligns with the PR's goal of using more specific discount types.
440-440: Updated getDiscountStripeInvoiceItemParams function signatureThe parameter type change to
billing.AmountLineDiscountManagedensures type safety and consistency with the other discount handling changes.
457-457: Updated getDiscountStripeAddInvoiceItemParams function signatureThe parameter type change to
billing.AmountLineDiscountManagedcompletes the consistent update across all discount-related functions.
543-543: Updated getDiscountLineName function signatureThis parameter type change maintains consistency with all other discount-related functions, completing the refactoring to use the more specific discount type.
openmeter/ent/db/billinginvoicediscount/where.go (5)
10-10: Added billing package importThis import is required to support the new
billing.LineDiscountTypetype used in the updated functions.
520-523: Enhanced TypeEQ to use LineDiscountType instead of stringThis change improves type safety by using the specific
billing.LineDiscountTypeenum instead of a generic string, preventing potential errors from using invalid discount types.
526-529: Enhanced TypeNEQ to use LineDiscountType instead of stringConsistent implementation of type safety improvements using the specific enum type for the not-equals predicate.
532-538: Enhanced TypeIn to use LineDiscountType instead of stringType safety improvement for the "in" predicate, properly converting the enum values to interface type for the SQL predicate.
541-547: Enhanced TypeNotIn to use LineDiscountType instead of stringCompletes the consistent type safety improvements across all type-related predicates, ensuring the same handling pattern for all functions.
openmeter/ent/db/mutation.go (20)
13837-13837: Pointer usage for_typelooks consistent.
No functional or logical issues detected here.
14279-14284: Set and Get methods for_typeare standard.
They follow typical Ent mutation patterns, ensuring type safety with the newbilling.LineDiscountType.
14295-14295: OldType method for_typeis correctly restricted to UpdateOne.
This prevents accidental lookups in multi-update operations.
14610-14613: FieldType case logic is valid.
Casting tobilling.LineDiscountTypeis safe and consistent with Ent’s approach.
18088-18088: Addition of_typein BillingInvoiceLineDiscountMutation struct is fine.
Pointer usage aligns with the rest of the mutation struct pattern.
18367-18401: SetType, GetType, OldType, and ResetType are correctly implemented.
All reflect the usual Ent mutation generator pattern for new fields.
18439-18473: LineID mutation methods look standard.
They properly handle setting, retrieving, and resetting the line identifier.
18590-18593: OldAmount usage.
No issues found; the logic for ensuring UpdateOne is correct.
18941-18941: Fields() capacity adjustment.
Usingmake([]string, 0, 15)is a minor optimization and fine as is.
18954-18963: Appending_typeandbilling_invoice_linefields to Fields() is correct.
No concerns here.
18972-18983: Appending rounding_amount, quantity, pre_line_period_quantity, and source_discount fields to Fields().
Properly ensures these fields appear in the mutation process.
19003-19025: Retrieving mutated fields: FieldType, FieldLineID, etc.
The code is consistent with the mutation contract.
19042-19064: Old retrieval for_type, line ID, rounding amount, and others.*
The logic to fetch old values only in UpdateOne is correct.
19101-19107: Case for setting_type.
Type assertion and assignment are correctly handled.
19115-19122: Case for setting line ID.
String assertion is straightforward.
19143-19170: Case for rounding_amount, quantity, pre_line_period_quantity, source_discount.
Type assertions align with declared fields and pointer usage.
19217-19231: Clearing fields logic is consistent.
Properly appends fields to be cleared in the mutation.
19258-19273: Clearing fields (amount, rounding_amount, quantity, etc.).
No concerns; standard Ent approach.
19296-19305: Resetting type, line ID, etc.
Implements correct resets in the same pattern as other fields.
19314-19325: Final reset logic is consistent.
Resetting rounding_amount, quantity, pre_line_period_quantity, source_discount follows Ent norms.openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (11)
11-13: Consider grouping imports more explicitly.
The new imports forentgo.io/ent/schema/fieldandgithub.com/openmeterio/openmeter/openmeter/productcatalogare fine. If more packages are added in the future, consider grouping or structuring them to clarify external vs. internal dependencies.
29-48: All field constants look consistent with the new discount fields.
Defining these constants ensures clarity and matches the new discount design (e.g.FieldType,FieldLineID,FieldRoundingAmount,FieldQuantity, etc.). This approach is consistent with Ent’s standard patterns.
71-82: Column slice updates align with newly introduced fields.
ExpandingColumnsto includeFieldType,FieldLineID,FieldRoundingAmount, etc., is consistent with the schema changes.
105-108: Introduced ValueScanner for SourceDiscount is beneficial for complex scanning logic.
Including afield.TypeValueScanner[*productcatalog.Discount]is appropriate for scanning nested struct data. Just ensure that any nil pointers externally are handled gracefully.
111-119: Validator ensures only “amount” or “usage” discount types.
TheTypeValidatorfunction enforces valid discount types effectively, preventing invalid enum usage.
159-162: New ByType ordering function is straightforward.
The function adds ordering byFieldType, beneficial for sorting by discount type in queries.
169-172: ByLineID ordering is consistent with the underlying line reference logic.
This matches the newline_idfield. Useful for sortingBillingInvoiceLineDiscountsby the associated line.
189-192: ByRoundingAmount ordering complements the “rounding_amount” field.
Allows sorting on the rounding-amount dimension, which can be relevant in invoice computations.
199-202: ByQuantity ordering is aligned with usage discount flows.
Sorting byquantitycan be valuable for usage-based discounts.
204-208: BySourceDiscount ordering ensures sorting by discount source.
This new ordering function helps query results by thesource_discountfield, mirroring the updated schema.
209-212: ByPreLinePeriodQuantity function allows chronological or usage-based sorting.
This extension completes the set of ordering functions for newly introduced discount-related fields.openmeter/billing/invoicelinediscount.go (24)
1-18: Initial package, imports, and constants look consistent.
This file introduces the domain logic for line discounts. The chosen imports (lo,reflect,alpacadecimal, etc.) align with your new discount approach.
19-22: LineMaximumSpendReferenceID constant.
DefiningLineMaximumSpendReferenceIDclarifies the unique reference for a maximum spend style discount. This approach is correct for referencing in your calculations.
26-36: LineDiscountReason enum and its Values method.
Defining these reasons ensures clarity and type safety. TheValues()method returning string slices is a clean approach for usage checks.
38-60: LineSetDiscountMangedFields captures ID and ManagedModel.
Good approach for storing creation, update, and potential deletion timestamps (soft-delete). TheValidateandEqualmethods are straightforward.
62-70: LineDiscountBase structure is well-defined.
Holds references toDescription,Reason, and the newSourceDiscount.
Ensure any external references (e.g.,SourceDiscount) are thoroughly tested for nil usage.
71-85: Validation merges errors with errors.Join, providing cohesive error messages.
The pattern is neat. Just ensure you handle corner cases, e.g.,Reason == "".
95-98: LineDiscountBaseManaged composesLineSetDiscountMangedFields+LineDiscountBase.
This layering keeps managed fields separate from the discount’s descriptive fields.
100-108: AmountLineDiscount with RoundingAmount.
Inclusion ofRoundingAmountis a nice approach to handle multi-discount rounding corrections.
110-122: Validate checks for non-negative amounts.
Properly raises errors if the discountAmountis negative. The same logic extends toRoundingAmountif needed.
124-138: Equality checks.
Comparing embedded fields and decimal amounts ensures correctness. Thereflect.DeepEqualfor theLineDiscountBasealso covers the rest.
140-147: Clone method returns a copy of the discount.
Maintaining immutability is a strong design choice, especially for line-based calculations.
153-165: AmountLineDiscountManaged aggregator.
Encapsulates both discount base fields and the managed fields. The validation hooking into the embedded structs fosters DRY.
186-192: UsageLineDiscount with quantity-based discount logic.
Introduction ofQuantityand optionalPreLinePeriodQuantitymakes sense for usage-based lines.
193-209: Validation for usage discounts.
Checks negativeQuantityorPreLinePeriodQuantity. This captures common pitfalls in usage-based billing.
211-225: Equality and clone for UsageLineDiscount.
Similar approach as in amount discount ensures consistency. The pointer check viaequal.PtrEqualis robust.
235-238: UsageLineDiscountManaged aggregator.
Remains consistent with the approach taken inAmountLineDiscountManaged.
273-285: LineDiscountType enum (amount, usage) with Values.
Clear approach that matches the earlierTypeValidator.
287-325: LineDiscount interface and reference to typed discount fields.
Well-structured interface allowing different discount subtypes. This approach fosters extension for future discount kinds.
327-361: NewLineDiscountFrom factory function.
Generically constructs lineDiscount from typed discount structs. This is a flexible approach, ensuring minimal duplication.
430-443: Equal method checks pointer equality for sub-discounts.
It’s a succinct approach to handle the union type scenario: either usage discount or amount discount.
470-482: Mutate applies functional transformations.
Permits stacking mutators in a user-friendly manner. Potential concurrency concerns typically mitigated by immutability of the discount object.
510-519: Validate method dispatches by discount type.
Helps ensure each subtype’s logic is applied. Usingerrors.Newfor unknown discount types is a good guard.
622-678: ReuseIDsFrom maintains existing discount IDs for idempotency.
Implementation withlo.GroupBy+lo.Filteris a neat approach. This logic is correct for reusing the ID if thechildUniqueReferenceIDmatches.
680-717: SumAmount method sums discount and rounding amounts.
Straightforward summation across amount-based discounts. Ensure usage-based discounts do not mistakenly land here.openmeter/ent/db/billinginvoicelinediscount_create.go (18)
19-19: New import for productcatalog ensures references to SourceDiscount.
This aligns with the code in the new discount logic.
78-82: SetType uses a strongly typed enum approach.
Switching from string tobilling.LineDiscountTypedecreases the chance of invalid discount types.
90-94: SetLineID matches the new “line_id” property.
EnsuresBillingInvoiceLineDiscountcorrectly references the line object.
130-150: Nillable fields for Amount and RoundingAmount.
Allowing these fields to be set conditionally is consistent with the optional pointer types in the schema.
152-178: Nillable fields for Quantity and PreLinePeriodQuantity.
Same pattern as Amount, enabling usage-based values to be absent. This is aligned with the pointer usage in the entity.
180-184: SetSourceDiscount references the new pointer-based discount.
Matching the code that usesSourceDiscount *productcatalog.Discount.
290-297: Check for mandatory “type” field with TypeValidator.
Ensures the discount must specify a valid type (amount or usage).
306-308: Check for mandatory “line_id”.
Forbids creating a discount with no associated line.
309-313: Validation for SourceDiscount with sourceDiscount.Validate().
If an external discount is provided, it’s verified as well.
324-327: createSpec usage ensures new fields are set with correct types in the DB.
Storing them asfield.TypeOtherfor decimals is typical in Ent.
346-347: type assignment in createSpec.
EnsuresFieldTypeis stored as an enum, matching the newbilling.LineDiscountType.
922-929: The upsert logic includes ClearQuantity, ClearAmount, etc.
Your upsert expansions handle toggling discount fields if needed. This is consistent with the new pointer-based schema design.
952-975: SetSourceDiscount with upsert.
Allows toggling or clearing that field upon conflicts, retaining consistency.
1253-1265: SetType and UpdateType in the bulk upsert.
Again, strongly typed approach for the discount type is consistent.
1281-1293: SetLineID / UpdateLineID in the bulk upsert.
These fields match your line-association logic, ensuring bulk insertion and conflict resolution.
1351-1398: ClearAmount, ClearRoundingAmount, ClearQuantity…
Ability to clear these fields in a bulk upsert scenario helps handle partial discount override logic.
1400-1440: Set/Update/ClearPreLinePeriodQuantity and SourceDiscount
Completes the coverage of all new discount attributes in upsert mode.
1469-1471: Note on OnConflict usage.
Attempting to set OnConflict on an individual builder when usingBillingInvoiceLineDiscountCreateBulkleads to an error. This is typical of Ent’s bulk creation constraints.openmeter/ent/db/billinginvoicelinediscount_update.go (47)
19-19: Import usage is consistent withSourceDiscountchanges.
No issues identified; this import is needed for the newSetSourceDiscountfunctionality.
61-63:SetTypemethod looks good.
This straightforward setter delegates validation toTypeValidatorin thecheck()method. No issues identified.
67-70: Nillable setter is consistent with the pattern.
Allows optional assignment for thetypefield and is aligned with existing patterns.
89-93:SetLineIDmethod is fine.
Wrapper for line ID assignment. Looks consistent with other setters.
95-101:SetNillableLineIDis correctly implemented.
No performance or security concerns here.
157-161:ClearAmountmethod is consistent.
Properly clears the decimal field by calling the mutation’s clear method.
163-167:SetRoundingAmountmethod is valid.
Usesalpacadecimal.Decimalwith no issues identified.
169-175: Nillable rounding amount setter is consistent.
Allows optional assignment; no logical problems noted.
177-181:ClearRoundingAmountis straightforward.
Properly clears the value in the mutation.
183-187:SetQuantitymethod is consistent.
Matches the pattern for setting a decimal field.
189-195:SetNillableQuantityis correct.
Follows the same nillable pattern. No concerns.
197-201:ClearQuantitymethod is valid.
Clears the underlying decimal field. Looks good.
203-207:SetPreLinePeriodQuantitymethod is correct.
Aligns with new field usage for pre-line period quantity.
209-215: Nillable pre-line period quantity logic is consistent.
Optional assignment pattern is appropriately handled.
217-221:ClearPreLinePeriodQuantityfollows established pattern.
Correctly clears the field from the mutation.
223-227:SetSourceDiscountmethod is appropriate.
Integrates theproductcatalog.Discountreference. Validation is done in thecheck()method.
229-233:ClearSourceDiscountmethod is valid.
Correctly resets thesource_discountfield. No issues noted.
313-319:check()method’s validation fortypeis correct.
Ensures discount type remains valid according to the domain rules. No further changes needed.
325-329:check()method’s validation forsource_discountis appropriate.
Callsv.Validate()to ensure a validDiscount. This is good defensive programming.
357-359: Applying thetypefield insqlSaveis consistent.
Proper usage ofSetFieldwithfield.TypeEnum. No concerns.
378-380: Clearing theamountfield is implemented correctly.
Consistent with theClearAmountmutation logic. Looks good.
381-383: Setting theRoundingAmountfield is correct.
Aligns with the decimal type and existing code style.
384-386: Clearing theRoundingAmountfield is consistent.
Makes use ofClearFieldwithout issues. Approved.
387-389: Setting theQuantityfield is straightforward.
No issues found. The decimal field is properly handled.
390-392: Clearing theQuantityfield is done correctly.
Follows the same approach as other optional decimal fields.
393-395: SettingPreLinePeriodQuantityis correct.
No concerns with the usage.
396-398: ClearingPreLinePeriodQuantityis fine.
Operates similarly to other clear methods.
399-405: Storingsource_discountusingValueScanneris well-structured.
Properly checks for errors and sets the appropriate field type in_spec.
406-408: Clearing thesource_discountfield is consistent.
No issues identified; pattern matches other optional fields.
490-493:SetTypein the single-update builder is good.
Consistent with the multi-update logic. Approved.
496-502: Nillable type setter in the single-update builder is valid.
Matches established patterns for optional fields.
518-522:SetLineIDin the single-update builder.
No logic or security concerns; identical approach to multi-update version.
524-530: NillableSetLineIDis fine.
Consistent with usage in other fields as well.
586-590: Single-updateClearAmountmethod is correct.
Mirrors the multi-update approach with no issues.
592-596: Single-updateSetRoundingAmountis appropriate.
No anomalies; matches the multi-update pattern.
598-604: Nillable rounding amount logic is consistent here.
No correctness or style issues detected.
606-610: Single-updateClearRoundingAmountis fine.
The approach matches other fields.
612-616: Single-updateSetQuantitymethod is correct.
Implements the decimal setter consistently.
618-624: Nillable quantity logic is consistent.
Granular handling of optional decimals is well-applied.
626-630: Single-updateClearQuantityis fine.
Consistent pattern with clearing optional fields.
632-636:SetPreLinePeriodQuantityin single-update is valid.
No issues; usage is consistent with multi-update.
638-644: NillableSetPreLinePeriodQuantityis correct.
Proper optional assignment handling with decimals.
646-650:ClearPreLinePeriodQuantityin single-update is fine.
Matches the established pattern for clearing.
652-656:SetSourceDiscountin single-update is consistent.
No issues; properly referencesproductcatalog.Discount.
658-662:ClearSourceDiscountin single-update is valid.
No further concerns; pattern is consistent.
757-761:check()method validation fortypeis correct.
Consistent with the multi-update approach, usingTypeValidator.
768-771: Validation forsource_discountis fully correct.
Ensuresv.Validate()is called and gracefully handles errors.openmeter/ent/db/billinginvoicelinediscount/where.go (37)
110-113:RoundingAmount(alias for RoundingAmountEQ) is good.
Matches existing naming and usage patterns for predicate functions.
115-118:Quantity(alias for QuantityEQ) is well-defined.
No discrepancies with other predicate definitions.
120-123:PreLinePeriodQuantity(alias for PreLinePeriodQuantityEQ) is consistent.
Reaffirms the pattern of direct equality predicate generators.
640-644:AmountIsNilpredicate function is correct.
Allows filtering by null amounts. No issues with the approach.
645-649:AmountNotNilis valid.
No concerns; effectively the “NOT NULL” variant.
650-654:RoundingAmountEQis implemented properly.
Same approach used in other field-based predicates.
655-659:RoundingAmountNEQis likewise consistent.
Continues the shared naming/predicate style.
660-663:RoundingAmountInis correct.
Supports multi-value filtering as seen in other fields.
664-667:RoundingAmountNotInis fine.
No issues or improvements needed.
668-671:RoundingAmountGTis consistent.
Uses correct lexical comparison for the decimal field.
672-675:RoundingAmountGTEis valid.
Same pattern as the GT variant, just inclusive.
676-679:RoundingAmountLTis correct.
Maps to standard<usage.
680-683:RoundingAmountLTEis consistent.
Parallel to other boundary predicates. Approved.
690-693:RoundingAmountIsNilis fine.
Negates the need for a separate numeric check if field is null.
695-698:RoundingAmountNotNilis valid.
Adheres to established patterns for checkingNOT NULL.
700-703:QuantityEQfunction is properly mirrored.
Ensures consistent usage of decimal equality checks.
705-708:QuantityNEQis also correct.
Functions as the inverse for equality checks.
710-713:QuantityInis valid.
No issues flagged. Handy for multi-value filtering.
715-718:QuantityNotInis consistent with the preceding patterns.
Follows the same approach asIn.
720-723:QuantityGTis standard.
Properly references the correct field for>comparisons.
725-728:QuantityGTEdoes what it should.
Aligns with typical “>=” usage for decimals.
730-733:QuantityLTis fine.
Identical pattern for<with numeric fields.
735-738:QuantityLTEis parallel to the LT version.
No issues or suggestions here.
740-743:QuantityIsNilis consistent.
This is the null-check approach for the quantity field.
745-748:QuantityNotNilmirrors the IsNil logic.
Equivalent usage for the'NOT NULL'case.
750-753:PreLinePeriodQuantityEQis correct.
Simple equality predicate. No improvements needed.
755-758:PreLinePeriodQuantityNEQis consistent.
Standard approach to the “not equals” condition.
760-763:PreLinePeriodQuantityInextends multi-value filtering.
Matches other_Inmethods. No concerns.
765-768:PreLinePeriodQuantityNotInis done correctly.
No anomalies; it’s the negated version of_In.
770-773:PreLinePeriodQuantityGTis valid.
Uses the correct operator for numeric comparisons.
775-778:PreLinePeriodQuantityGTElooks good.
Follows the established_GTEnaming.
780-783:PreLinePeriodQuantityLTis consistent.
Implements standard<handling.
785-788:PreLinePeriodQuantityLTEis properly mirrored.
No issues discovered.
790-793:PreLinePeriodQuantityIsNilis correct.
Ensures we can filter discount records without that quantity set.
795-798:PreLinePeriodQuantityNotNilfollows established pattern.
Checks the existence of a quantity. Good consistency.
800-803:SourceDiscountIsNilis valid.
Allows filtering for rows without a source discount.
805-808:SourceDiscountNotNilis the expected counterpart.
No changes required; well-structured.test/billing/invoice_test.go (5)
2083-2085: Updated discount handling using GetID() methodThe code now correctly uses
GetID()method to obtain the discount ID, which aligns with the broader PR changes in discount type management. This makes the code more consistent with the new discount type system.
2212-2217: Enhanced discount validation with proper type conversionGood improvement in discount validation using
AsDiscountBase()method for type conversion with error handling. The change improves robustness by verifying the conversion succeeded before accessing the external ID.
2222-2222: Simplified discount ID validation in upsertInvoiceChanged from using
line.DiscountsByID()method to directly accessing theDiscountsfield, which aligns with the new discount model being implemented in this PR.
2233-2235: Consistent discount ID handling in final_upsertUpdated to use the same discount handling pattern as elsewhere in the codebase, using
GetID()method to retrieve discount IDs consistently.
2263-2268: Robust discount external ID verificationAdded proper type conversion using
AsDiscountBase()with error handling, followed by a verification of the discount's external ID. This is consistent with the more typesafe approach to discounts implemented across the PR.
Overview
This patch adds a union type over the previous amount based discounts to support unit discounts, so that we can persist both amount and unit based discounts for lines.
The current implementation uses a single table, as for line diffing that's the preferred, and makes implementation easier.
We are also using immutable types (contrary to lines) as we don't need to maintain parent/child references in this codepath.
Summary by CodeRabbit
New Features
Refactor / Bug Fixes
Tests