Skip to content

feat: add amount discount support - #2596

Merged
turip merged 1 commit into
mainfrom
feat/add-amount-discount-support
Apr 7, 2025
Merged

turip merged 1 commit into
mainfrom
feat/add-amount-discount-support

Conversation

@turip

@turip turip commented Apr 4, 2025 •

Copy link
Copy Markdown
Member

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

    • Enhanced discount processing to better support amount-based and usage-based discounts.
    • Introduced additional discount attributes for invoices, such as rounding, quantity, and external discount details.
  • Refactor / Bug Fixes

    • Streamlined validation and error reporting in discount calculations during invoice creation and updates.
    • Improved consistency in discount mapping and merging for accurate invoice totals.
  • Tests

    • Strengthened test coverage to ensure robust discount handling and reliable invoicing outcomes.

@coderabbitai

coderabbitai Bot commented Apr 4, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This 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

File(s) Change Summary
openmeter/app/stripe/entity/app/invoice.go Updated discount retrieval in createInvoice and updateInvoice methods; modified function signatures to use billing.AmountLineDiscountManaged.
openmeter/billing/adapter/{invoicelinediff.go, invoicelinediff_test.go, invoicelinemapper.go, invoicelines.go, app.go, httpdriver/invoiceline.go, invoiceline.go} Refactored discount mapping, cloning, and update logic; replaced outdated discount methods; enhanced error handling and modified discount mutation routines.
openmeter/billing/invoicelinediscount.go Introduced a new file defining discount types, validations, cloning and mutation methods, and a collection type for managing line discounts.
openmeter/billing/service/lineservice/{feeline.go, usagebasedline.go, usagebasedline_test.go} Revised discount total calculations, updated discount processing for usage‑based lines, and refactored tests to use new discount initialization functions.
openmeter/ent/db/{billinginvoicediscount.go, billinginvoicediscount_create.go, billinginvoicediscount_update.go, invoicelinediscount.go, invoicelinediscount/*, mutation.go, predicate/predicate.go, runtime.go, setorclear.go} Changed discount field types from strings to enums (billing.LineDiscountType); added new fields (rounding amount, quantity, pre‑line period quantity, source discount); updated mutation, predicate, and field descriptor functions accordingly.
openmeter/ent/db/migrate/migrations/*_billing-line-discount-unit-support*.sql Provided SQL migration scripts to alter the “billing_invoice_line_discounts” table by allowing NULL values on the amount, adding new columns, and adjusting constraints.
pkg/{equal,equal.go, models/model.go} Added a new Equaler interface and Equal methods for comparing discount and model entities; updated pointer equality functions (using hasher.Hash) for robust comparison.
openmeter/productcatalog/discount.go Added an Equal method to compare Discount instances and updated the Discounts type to use hash-based equality checks.
test/{app/stripe/invoice_test.go, billing/adapter_test.go, billing/invoice_test.go} Updated tests to use new discount creation and retrieval methods (e.g. NewLineDiscounts, NewLineDiscountFrom, and a helper for discount descriptions) and adjusted comparisons based on the revised discount structure.
openmeter/ent/schema/{billing.go, productcatalog.go} Modified schema definitions by replacing string fields with enums for discount types/reasons, and added new fields with appropriate database types and value scanners for discounts.

Possibly related PRs

  • feat: persist rate card discounts #2588: Addresses similar modifications in discount management by introducing a new field for rate card discounts in invoice lines, with strong code-level parallels in discount processing.
  • feat: add discount reason #2606: Involves adjustments to discount handling including the addition of a discount reason and structural improvements, aligning closely with the refactor of discount types and error handling.
  • refactor: simplify discount handling #2599: Focuses on updating discount handling within the createInvoice and updateInvoice methods, mirroring changes made to streamline and directly access discount data.

Warning

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

🔧 golangci-lint (1.64.8)

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

🔧 SQLFluff (3.3.0)
tools/migrate/migrations/20250407191828_billing-line-discount-unit-support.up.sql

User Error: No dialect was specified. You must configure a dialect or specify one on the command line using --dialect after the command. Available dialects:
ansi, athena, bigquery, clickhouse, databricks, db2, duckdb, exasol, greenplum, hive, impala, mariadb, materialize, mysql, oracle, postgres, redshift, snowflake, soql, sparksql, sqlite, starrocks, teradata, trino, tsql, vertica

tools/migrate/migrations/20250407191828_billing-line-discount-unit-support.down.sql

User Error: No dialect was specified. You must configure a dialect or specify one on the command line using --dialect after the command. Available dialects:
ansi, athena, bigquery, clickhouse, databricks, db2, duckdb, exasol, greenplum, hive, impala, mariadb, materialize, mysql, oracle, postgres, redshift, snowflake, soql, sparksql, sqlite, starrocks, teradata, trino, tsql, vertica

✨ Finishing Touches
  • 📝 Generate Docstrings

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@turip
turip force-pushed the feat/add-amount-discount-support branch 3 times, most recently from 05c8ef6 to a8cfe4b Compare April 6, 2025 21:38
@turip
turip changed the base branch from main to feat/add-discount-reason April 6, 2025 22:15
@turip
turip force-pushed the feat/add-amount-discount-support branch 2 times, most recently from 424042d to c0ee90d Compare April 6, 2025 22:19
@turip
turip force-pushed the feat/add-discount-reason branch from fe90ce9 to 4cf7f1d Compare April 7, 2025 07:24
Base automatically changed from feat/add-discount-reason to main April 7, 2025 08:29
@turip
turip force-pushed the feat/add-amount-discount-support branch 2 times, most recently from b9d89fc to 669ef43 Compare April 7, 2025 17:46
@turip turip added release-note/misc Miscellaneous changes area/billing labels Apr 7, 2025
@turip
turip force-pushed the feat/add-amount-discount-support branch 4 times, most recently from c66bd85 to ad55a27 Compare April 7, 2025 19:21
@turip
turip force-pushed the feat/add-amount-discount-support branch from ad55a27 to dc269c2 Compare April 7, 2025 19:27
@turip
turip marked this pull request as ready for review April 7, 2025 19:27
@turip
turip requested a review from a team as a code owner April 7, 2025 19:27
@turip
turip requested a review from tothandras April 7, 2025 19:31

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
test/billing/adapter_test.go (1)

552-552: Reusing child references again.
Similar test coverage for ChildrenWithIDReuse. No further concerns.

🧹 Nitpick comments (9)
openmeter/ent/db/predicate/predicate.go (1)

84-93: Good addition maintaining consistent error handling pattern.

The BillingInvoiceLineDiscountOrErr function 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:
  1. Concurrent modifications are prevented or handled transactionally.
  2. 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.Mutate with MarkDiscountDeleted and returns a new discountWithLine. 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 field LineSetDiscountMangedFields suggests a possible typo in “Manged”. Consider renaming to “ManagedFields” throughout the code for clarity.

- LineSetDiscountMangedFields
+ LineSetDiscountManagedFields
openmeter/billing/adapter/invoicelinediff_test.go (2)

48-50: Add an assertion for discount usage in tests.

Defining FlatFee and Discounts with newDiscountsWithIDs("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.SetDiscountMangedFields might be a small typo. If it’s not auto-generated, rename it to SetDiscountManagedFields for 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=%v in 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: storing source_discount as 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

📥 Commits

Reviewing files that changed from the base of the PR and between b8a6867 and dc269c2.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is 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 type

The addition of the type field 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 capabilities

The changes to BillingInvoiceLineDiscountsColumns implement a comprehensive approach to handling different discount types:

  1. Adding a type enum field with "amount" and "usage" values
  2. Making the amount field nullable since it might not be required for all discount types
  3. 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 references

The 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 check

The Equal method provides a thorough comparison of ManagedModel instances by checking all fields:

  • Properly uses time.Equal() for time comparisons
  • Correctly handles nil pointer comparison for DeletedAt using equal.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 type

The new DiscountValueScanner follows 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 migration

The down migration correctly reverts all schema changes by:

  1. Dropping all newly added columns (source_discount, pre_line_period_quantity, quantity, rounding_amount, type)
  2. Restoring the NOT NULL constraint on the amount column

This ensures a clean rollback path if needed.

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

83-91: Well-implemented validator for discount types.

The TypeValidator function 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_discount field, allowing the ORM to correctly handle the productcatalog.Discount type 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 PtrEqual function 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 HasherPtrEqual function 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 as PtrEqual.

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

48-48: Code simplification looks good.

The change from using lo.Map to directly calling l.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 billing package import enables the use of more specific domain types.


40-40: Enhanced type safety with domain-specific type.

Replacing string with billing.LineDiscountType improves 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.LineDiscountType properly 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:

  1. Simplified the code by directly accessing external IDs from the result
  2. Used a structured approach with Mutate and SetDiscountInvoicingExternalID
  3. 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 equal package enables more robust equality checks for discount types.


219-232: Solid implementation of equality comparison.

The addition of the Equal method provides a structured way to compare discount instances based on their type and content. The type-specific comparison is handled appropriately using equal.HasherPtrEqual for 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 properties

The code now uses the helper method getDiscountDecription instead of directly accessing discount.Description, and calls GetID() instead of accessing discount.ID directly. This change supports the new union type structure for discounts that accommodates both amount and unit discounts.


1118-1129: Well-structured discount description extraction

The 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 mapping

The code now uses slicesx.MapWithErr instead of lo.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 handling

The new mapInvoiceLineDiscountFromDB method provides a clean separation of concerns for mapping different discount types. It includes:

  1. Proper validation for required fields (amount for amount discounts, quantity for usage discounts)
  2. Type-specific handling for amount and usage discounts
  3. Clear error messages for different validation failures
  4. 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 discounts

The migration properly alters the billing_invoice_line_discounts table to support the new union type discount structure:

  1. Makes amount nullable for usage-based discounts
  2. Adds type discriminator column to distinguish discount types
  3. Adds necessary columns for each discount type (rounding_amount, quantity, pre_line_period_quantity, source_discount)
  4. 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 structure

The test cases now correctly use the new discount structure with factory methods billing.NewLineDiscounts and billing.NewLineDiscountFrom. This ensures that the tests validate the behavior with the new union type model.


594-604: Consistent discount creation pattern across test cases

The discount creation follows a consistent pattern throughout the test file, making the tests more maintainable and clear. The structured approach with LineDiscountBase properly separates common discount properties from type-specific ones.


839-848: Comprehensive discount property coverage in tests

The 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:

  1. Throws an error if a discount isn’t found in the DB.
  2. Updates the discount only when ContentsEqual is false.

This approach is effective. However, confirm that ContentsEqual logs 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 when ContentsEqual() returns false. However, please ensure that:

  • The ContentsEqual() method (defined in openmeter/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 valid line.Discounts object, 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 both openmeter/billing/adapter/invoicelinediff.go and other parts of the codebase) correctly handle errors, and consistent error checking is applied. The utility method on LineDiscounts returns 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.DBState to avoid nil dereference or partial discount states.

Please confirm initialization logic for line.DBState references is always present by searching for references to line.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.DBState initialization:


Attention: Manual Verification for line.DBState Initialization

The 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 that line.DBState is 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.DBState that 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.DBState Initialization

The 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 to line.DBState did 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.DBState is 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.ID is 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 InvoicingAppExternalID to the base discount’s ID, you unify external references. This is good for traceability. If the discount's .Invoicing field 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 (amount vs. 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 the Equal method looks appropriate for comparing the Invoicing field.


401-402: Cloning discounts when not skipping.
This logic correctly ensures that Discounts are 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 new LineChildren. 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 of ContentsEqual.


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 helper findDiscountByDescription improves 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 of require.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 (amount vs usage) with detailed error checks is commendable. This section thoroughly maps each discount type to distinct API models, ensuring type-specific fields (like Amount vs Quantity) 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 childrenWithIDReuse produces 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 EditAmountDiscount and lo.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 productcatalog is consistent with extending discount functionality. No issues found.


32-33: Use of typed discount field.

Replacing a generic type with billing.LineDiscountType improves type safety. This change aligns well with the new discount handling approach.


36-37: Explicitly tracking the line ID.

Introducing LineID clarifies 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-based SourceDiscount allows 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.NullScanner and *alpacadecimal.Decimal is 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.LineDiscountType and 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 LineID directly 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_id in the String() 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 discounts

The addition of enum fields type and reason tied to billing.LineDiscountType and billing.LineDiscountReason respectively 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 types

Making amount optional and nillable while adding new fields like rounding_amount, quantity, and pre_line_period_quantity provides 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 field

The addition of the source_discount field 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 compatibility

The update to the BillingInvoiceDiscount.type field to use enum type instead of string maintains consistency with the newer BillingInvoiceLineDiscount schema while preserving backwards compatibility.

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

16-16: Added necessary import for type safety

Adding the billing package import is essential for using the strongly-typed LineDiscountType enum.


108-112: Improved type safety with strongly-typed parameters

Replacing string parameter with billing.LineDiscountType in the SetType method enforces type safety at compile time, preventing invalid discount types from being used.


214-218: Added robust validation for discount types

The added validation ensures that only valid discount types (as defined by billinginvoicediscount.TypeValidator) can be stored, protecting data integrity.


291-293: Consistent field type specification

Changing the field type to field.TypeEnum in the createSpec method aligns with the schema definition, ensuring proper data handling in the database.


445-448: Consistent type handling throughout the codebase

The parameter type change in the SetType method for BillingInvoiceDiscountUpsert maintains 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 field

The SetOrClearAmount methods follow a consistent pattern used throughout the codebase, providing a clean way to handle nullable decimal values.


1206-1218: Proper handling for rounding amounts

The SetOrClearRoundingAmount methods ensure proper handling of optional rounding values, consistent with the project's pattern for handling nullable fields.


1220-1246: Consistent handling of quantity fields

Both SetOrClearQuantity and SetOrClearPreLinePeriodQuantity methods 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 data

The SetOrClearSourceDiscount methods 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 safety

Including the billing package import enables the use of strongly-typed enum values for discount types.


121-132: Enhanced type safety in update operations

Changing parameter types for SetType and SetNillableType methods from string to billing.LineDiscountType ensures type safety during update operations, preventing invalid values.


207-215: Added robust validation for update operations

The new check method ensures that only valid discount types can be stored in the database, protecting data integrity during updates.


218-220: Integrated validation into save flow

The validation is properly integrated into the save flow, ensuring that invalid updates are rejected before reaching the database.


257-258: Consistent field type specification

Using field.TypeEnum instead of field.TypeString ensures proper data handling in the database, consistent with the schema definition.


479-492: Consistent validation across structs

The validation logic is correctly duplicated in the BillingInvoiceDiscountUpdateOne struct, 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 GetAmountDiscounts

This 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 retrieval

Good 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 method

The change to use the retrieved amountDiscountsById array is consistent with the other discount handling changes and allows for better error handling.


430-431: Updated discount parameter type to AmountLineDiscountManaged

The parameter type change from billing.LineDiscount to billing.AmountLineDiscountManaged improves type safety and aligns with the PR's goal of using more specific discount types.


440-440: Updated getDiscountStripeInvoiceItemParams function signature

The parameter type change to billing.AmountLineDiscountManaged ensures type safety and consistency with the other discount handling changes.


457-457: Updated getDiscountStripeAddInvoiceItemParams function signature

The parameter type change to billing.AmountLineDiscountManaged completes the consistent update across all discount-related functions.


543-543: Updated getDiscountLineName function signature

This 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 import

This import is required to support the new billing.LineDiscountType type used in the updated functions.


520-523: Enhanced TypeEQ to use LineDiscountType instead of string

This change improves type safety by using the specific billing.LineDiscountType enum instead of a generic string, preventing potential errors from using invalid discount types.


526-529: Enhanced TypeNEQ to use LineDiscountType instead of string

Consistent implementation of type safety improvements using the specific enum type for the not-equals predicate.


532-538: Enhanced TypeIn to use LineDiscountType instead of string

Type 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 string

Completes 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 _type looks consistent.
No functional or logical issues detected here.


14279-14284: Set and Get methods for _type are standard.
They follow typical Ent mutation patterns, ensuring type safety with the new billing.LineDiscountType.


14295-14295: OldType method for _type is correctly restricted to UpdateOne.
This prevents accidental lookups in multi-update operations.


14610-14613: FieldType case logic is valid.
Casting to billing.LineDiscountType is safe and consistent with Ent’s approach.


18088-18088: Addition of _type in 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.
Using make([]string, 0, 15) is a minor optimization and fine as is.


18954-18963: Appending _type and billing_invoice_line fields 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 for entgo.io/ent/schema/field and github.com/openmeterio/openmeter/openmeter/productcatalog are 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.
Expanding Columns to include FieldType, FieldLineID, FieldRoundingAmount, etc., is consistent with the schema changes.


105-108: Introduced ValueScanner for SourceDiscount is beneficial for complex scanning logic.
Including a field.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.
The TypeValidator function enforces valid discount types effectively, preventing invalid enum usage.


159-162: New ByType ordering function is straightforward.
The function adds ordering by FieldType, beneficial for sorting by discount type in queries.


169-172: ByLineID ordering is consistent with the underlying line reference logic.
This matches the new line_id field. Useful for sorting BillingInvoiceLineDiscounts by 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 by quantity can be valuable for usage-based discounts.


204-208: BySourceDiscount ordering ensures sorting by discount source.
This new ordering function helps query results by the source_discount field, 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.
Defining LineMaximumSpendReferenceID clarifies 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. The Values() 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). The Validate and Equal methods are straightforward.


62-70: LineDiscountBase structure is well-defined.
Holds references to Description, Reason, and the new SourceDiscount.
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 composes LineSetDiscountMangedFields + LineDiscountBase.
This layering keeps managed fields separate from the discount’s descriptive fields.


100-108: AmountLineDiscount with RoundingAmount.
Inclusion of RoundingAmount is a nice approach to handle multi-discount rounding corrections.


110-122: Validate checks for non-negative amounts.
Properly raises errors if the discount Amount is negative. The same logic extends to RoundingAmount if needed.


124-138: Equality checks.
Comparing embedded fields and decimal amounts ensures correctness. The reflect.DeepEqual for the LineDiscountBase also 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 of Quantity and optional PreLinePeriodQuantity makes sense for usage-based lines.


193-209: Validation for usage discounts.
Checks negative Quantity or PreLinePeriodQuantity. 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 via equal.PtrEqual is robust.


235-238: UsageLineDiscountManaged aggregator.
Remains consistent with the approach taken in AmountLineDiscountManaged.


273-285: LineDiscountType enum (amount, usage) with Values.
Clear approach that matches the earlier TypeValidator.


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. Using errors.New for unknown discount types is a good guard.


622-678: ReuseIDsFrom maintains existing discount IDs for idempotency.
Implementation with lo.GroupBy + lo.Filter is a neat approach. This logic is correct for reusing the ID if the childUniqueReferenceID matches.


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 to billing.LineDiscountType decreases the chance of invalid discount types.


90-94: SetLineID matches the new “line_id” property.
Ensures BillingInvoiceLineDiscount correctly 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 uses SourceDiscount *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 as field.TypeOther for decimals is typical in Ent.


346-347: type assignment in createSpec.
Ensures FieldType is stored as an enum, matching the new billing.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 using BillingInvoiceLineDiscountCreateBulk leads 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 with SourceDiscount changes.
No issues identified; this import is needed for the new SetSourceDiscount functionality.


61-63: SetType method looks good.
This straightforward setter delegates validation to TypeValidator in the check() method. No issues identified.


67-70: Nillable setter is consistent with the pattern.
Allows optional assignment for the type field and is aligned with existing patterns.


89-93: SetLineID method is fine.
Wrapper for line ID assignment. Looks consistent with other setters.


95-101: SetNillableLineID is correctly implemented.
No performance or security concerns here.


157-161: ClearAmount method is consistent.
Properly clears the decimal field by calling the mutation’s clear method.


163-167: SetRoundingAmount method is valid.
Uses alpacadecimal.Decimal with no issues identified.


169-175: Nillable rounding amount setter is consistent.
Allows optional assignment; no logical problems noted.


177-181: ClearRoundingAmount is straightforward.
Properly clears the value in the mutation.


183-187: SetQuantity method is consistent.
Matches the pattern for setting a decimal field.


189-195: SetNillableQuantity is correct.
Follows the same nillable pattern. No concerns.


197-201: ClearQuantity method is valid.
Clears the underlying decimal field. Looks good.


203-207: SetPreLinePeriodQuantity method 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: ClearPreLinePeriodQuantity follows established pattern.
Correctly clears the field from the mutation.


223-227: SetSourceDiscount method is appropriate.
Integrates the productcatalog.Discount reference. Validation is done in the check() method.


229-233: ClearSourceDiscount method is valid.
Correctly resets the source_discount field. No issues noted.


313-319: check() method’s validation for type is correct.
Ensures discount type remains valid according to the domain rules. No further changes needed.


325-329: check() method’s validation for source_discount is appropriate.
Calls v.Validate() to ensure a valid Discount. This is good defensive programming.


357-359: Applying the type field in sqlSave is consistent.
Proper usage of SetField with field.TypeEnum. No concerns.


378-380: Clearing the amount field is implemented correctly.
Consistent with the ClearAmount mutation logic. Looks good.


381-383: Setting the RoundingAmount field is correct.
Aligns with the decimal type and existing code style.


384-386: Clearing the RoundingAmount field is consistent.
Makes use of ClearField without issues. Approved.


387-389: Setting the Quantity field is straightforward.
No issues found. The decimal field is properly handled.


390-392: Clearing the Quantity field is done correctly.
Follows the same approach as other optional decimal fields.


393-395: Setting PreLinePeriodQuantity is correct.
No concerns with the usage.


396-398: Clearing PreLinePeriodQuantity is fine.
Operates similarly to other clear methods.


399-405: Storing source_discount using ValueScanner is well-structured.
Properly checks for errors and sets the appropriate field type in _spec.


406-408: Clearing the source_discount field is consistent.
No issues identified; pattern matches other optional fields.


490-493: SetType in 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: SetLineID in the single-update builder.
No logic or security concerns; identical approach to multi-update version.


524-530: Nillable SetLineID is fine.
Consistent with usage in other fields as well.


586-590: Single-update ClearAmount method is correct.
Mirrors the multi-update approach with no issues.


592-596: Single-update SetRoundingAmount is 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-update ClearRoundingAmount is fine.
The approach matches other fields.


612-616: Single-update SetQuantity method 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-update ClearQuantity is fine.
Consistent pattern with clearing optional fields.


632-636: SetPreLinePeriodQuantity in single-update is valid.
No issues; usage is consistent with multi-update.


638-644: Nillable SetPreLinePeriodQuantity is correct.
Proper optional assignment handling with decimals.


646-650: ClearPreLinePeriodQuantity in single-update is fine.
Matches the established pattern for clearing.


652-656: SetSourceDiscount in single-update is consistent.
No issues; properly references productcatalog.Discount.


658-662: ClearSourceDiscount in single-update is valid.
No further concerns; pattern is consistent.


757-761: check() method validation for type is correct.
Consistent with the multi-update approach, using TypeValidator.


768-771: Validation for source_discount is fully correct.
Ensures v.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: AmountIsNil predicate function is correct.
Allows filtering by null amounts. No issues with the approach.


645-649: AmountNotNil is valid.
No concerns; effectively the “NOT NULL” variant.


650-654: RoundingAmountEQ is implemented properly.
Same approach used in other field-based predicates.


655-659: RoundingAmountNEQ is likewise consistent.
Continues the shared naming/predicate style.


660-663: RoundingAmountIn is correct.
Supports multi-value filtering as seen in other fields.


664-667: RoundingAmountNotIn is fine.
No issues or improvements needed.


668-671: RoundingAmountGT is consistent.
Uses correct lexical comparison for the decimal field.


672-675: RoundingAmountGTE is valid.
Same pattern as the GT variant, just inclusive.


676-679: RoundingAmountLT is correct.
Maps to standard < usage.


680-683: RoundingAmountLTE is consistent.
Parallel to other boundary predicates. Approved.


690-693: RoundingAmountIsNil is fine.
Negates the need for a separate numeric check if field is null.


695-698: RoundingAmountNotNil is valid.
Adheres to established patterns for checking NOT NULL.


700-703: QuantityEQ function is properly mirrored.
Ensures consistent usage of decimal equality checks.


705-708: QuantityNEQ is also correct.
Functions as the inverse for equality checks.


710-713: QuantityIn is valid.
No issues flagged. Handy for multi-value filtering.


715-718: QuantityNotIn is consistent with the preceding patterns.
Follows the same approach as In.


720-723: QuantityGT is standard.
Properly references the correct field for > comparisons.


725-728: QuantityGTE does what it should.
Aligns with typical “>=” usage for decimals.


730-733: QuantityLT is fine.
Identical pattern for < with numeric fields.


735-738: QuantityLTE is parallel to the LT version.
No issues or suggestions here.


740-743: QuantityIsNil is consistent.
This is the null-check approach for the quantity field.


745-748: QuantityNotNil mirrors the IsNil logic.
Equivalent usage for the 'NOT NULL' case.


750-753: PreLinePeriodQuantityEQ is correct.
Simple equality predicate. No improvements needed.


755-758: PreLinePeriodQuantityNEQ is consistent.
Standard approach to the “not equals” condition.


760-763: PreLinePeriodQuantityIn extends multi-value filtering.
Matches other _In methods. No concerns.


765-768: PreLinePeriodQuantityNotIn is done correctly.
No anomalies; it’s the negated version of _In.


770-773: PreLinePeriodQuantityGT is valid.
Uses the correct operator for numeric comparisons.


775-778: PreLinePeriodQuantityGTE looks good.
Follows the established _GTE naming.


780-783: PreLinePeriodQuantityLT is consistent.
Implements standard < handling.


785-788: PreLinePeriodQuantityLTE is properly mirrored.
No issues discovered.


790-793: PreLinePeriodQuantityIsNil is correct.
Ensures we can filter discount records without that quantity set.


795-798: PreLinePeriodQuantityNotNil follows established pattern.
Checks the existence of a quantity. Good consistency.


800-803: SourceDiscountIsNil is valid.
Allows filtering for rows without a source discount.


805-808: SourceDiscountNotNil is the expected counterpart.
No changes required; well-structured.

test/billing/invoice_test.go (5)

2083-2085: Updated discount handling using GetID() method

The 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 conversion

Good 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 upsertInvoice

Changed from using line.DiscountsByID() method to directly accessing the Discounts field, which aligns with the new discount model being implemented in this PR.


2233-2235: Consistent discount ID handling in final_upsert

Updated 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 verification

Added 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.

@turip
turip merged commit 0075285 into main Apr 7, 2025
@turip
turip deleted the feat/add-amount-discount-support branch April 7, 2025 19:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants