Skip to content

feat: invoice discounts api v2#2576

Merged
turip merged 2 commits intomainfrom
feat/invoice-discounts-api-v2
Apr 3, 2025
Merged

feat: invoice discounts api v2#2576
turip merged 2 commits intomainfrom
feat/invoice-discounts-api-v2

Conversation

@turip
Copy link
Member

@turip turip commented Apr 2, 2025

Overview

Changes:

  • Drop invoice level discounts (as we will not implement that yet)
  • Move all line specific user input that is present on the rate-card of product catalog to a rate-card object (more on that later)
  • Deprecate old fields that are on a rate-card
  • Discounts structure is updated to show usage discounts too (non-breaking change)
  • Remove charges, as they are represented as detailed lines

Rate-card

The issue is that the term discount is overloaded; it means two things in the context of invoicing:

  • The discount intent/spec (subscription terminology) (e.g. what's present on the plan and subscription)
  • The actual discount applied (e.g. the amount in USD, or the usage deducted from quantity)

By separating the intent (rate-card) and the calculated value (line itself) we are future-proofing the line as we have a staging area for the intent and the calculations itself.

Deprecating fields

The PR takes the following approach for the deprecated fields on the lines:

  • For Get/List requests, both the old and the new fields are populated
  • For Create/Update requests, only one of them can be non-empty, or a validation error is generated.

The line discount change is a breaking change, but it was not used before by our customers, and until usage discount is used the API will work as expected.

The invoice discounts API part is removed as is was never supported.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new, unified model for invoice charges and discounts that supports both fixed and usage-based pricing.
    • Rolled out enhanced rate card options for flat fee and usage-based billing scenarios.
  • Bug Fixes

    • Improved error handling during the mapping of discounts and invoice lines.
  • Refactor

    • Streamlined the invoicing system by removing legacy fields and deprecating outdated properties.
    • Enhanced validation processes for invoice-related data.
  • Tests

    • Added comprehensive tests to ensure robust mapping and validation of invoice billing details.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 2, 2025

📝 Walkthrough

Walkthrough

This pull request restructures billing and invoicing schema definitions across multiple project components. Changes include replacing the legacy BillingLineCharge with a new InvoiceLineCharge abstraction across client-side schemas and OpenAPI specs; updating invoice models by deprecating outdated fields and introducing rate card interfaces; and adding new TypeSpec files to standardize charge and discount types. Additionally, Go source files have been updated to include deprecation handling and validation functions for rate card fields, enhancing consistency and error management across the billing system.

Changes

File(s) Change Summary
api/client/.../schemas.ts, api/openapi{,.cloud}.yaml Removed the legacy BillingLineCharge schema/type; added InvoiceLineCharge, InvoiceLineChargeAmount, InvoiceLineDiscount (with its amount and usage variants), InvoiceFlatFeeRateCard, and InvoiceUsageBasedRateCard; removed or updated properties in the Invoice model; and marked several fields as deprecated to refine billing/invoice representations.
api/spec/.../invoices/{discounts.tsp,invoice.tsp,main.tsp} Introduced a new TypeSpec file (discounts.tsp) defining models, enums, and unions for invoice charges and discounts; removed the discounts property and the InvoiceDiscount model in invoice.tsp, renamed subscriptions to subscription, and added rate card properties; and added an import in main.tsp to incorporate the new discounts definitions.
openmeter/billing/httpdriver/{deprecations.go,deprecations_test.go,invoiceline.go} Added a new Go file (deprecations.go) with types, methods, and mapping functions to handle deprecated fields in flat fee and usage-based rate cards; introduced corresponding test cases in deprecations_test.go; and updated mapping functions and default constants in invoiceline.go to utilize the new deprecation handling and improve error management.

Warning

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

🔧 golangci-lint (1.64.8)

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

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai 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/invoice-discounts-api-v2 branch 3 times, most recently from 9537215 to 94d7246 Compare April 3, 2025 13:51
@turip turip added release-note/deprecation Release note: Deprecations area/billing labels Apr 3, 2025
@turip turip marked this pull request as ready for review April 3, 2025 14:00
@turip turip requested a review from a team as a code owner April 3, 2025 14:00
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

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

675-675: ⚠️ Potential issue

Likely bug: Wrong invoice line type set in usage-based line.

You appear to set Type: billing.InvoiceLineTypeFee while handling api.InvoiceUsageBasedLineReplaceUpdate at line 675. This is inconsistent and could cause logic errors or misclassifications. It should likely be Type: billing.InvoiceLineTypeUsageBased.

Apply this diff to fix the suspicious line:

-    Type: billing.InvoiceLineTypeFee,
+    Type: billing.InvoiceLineTypeUsageBased,
🧹 Nitpick comments (18)
api/spec/src/billing/invoices/invoice.tsp (1)

735-744: Deprecation of direct price and featureKey.
Good practice to mark these as deprecated and guide consumers toward rateCard.*. Ensure reciprocal references are documented for clarity.

api/openapi.yaml (4)

13966-13972: Subscription Reference Description Typo
The description for the subscription reference contains a typo ("subscritpions" instead of "subscriptions").

-          description: Subscription are the references to the subscritpions that this line is related to.
+          description: Subscription are the references to the subscriptions that this line is related to.

13980-14000: Deprecation of Legacy Fields and RateCard Integration
Multiple fields (the ones referencing Numeric, PricePaymentTerm, and Numeric for quantity) are now marked as deprecated, and a new rateCard property is introduced referencing InvoiceFlatFeeRateCard. This change is aligned with restructuring the rate-card object. Make sure that the validation for Create/Update requests enforces only one non-empty field as required by the API changes.


15175-15181: Subscription Reference Typo Revisited
The subscription reference in this section still contains the typo “subscritpions.”

-          description: Subscription are the references to the subscritpions that this line is related to.
+          description: Subscription are the references to the subscriptions that this line is related to.

15352-15414: Comprehensive Update for Invoice Usage-Based Models
This extensive update covers:

  • The InvoiceUsageBasedLineCreateWithCustomer model, which now includes a new customerId field.
  • The definition of InvoiceUsageBasedRateCard, detailing properties like featureKey, taxConfig, price, and discounts.

Review Note: The description for the discounts property currently states, "Flat fee rate cards only support percentage discounts." If this schema is intended for usage-based rate cards, please verify and update the description to accurately reflect the discount types applicable to usage-based pricing.

api/openapi.cloud.yaml (9)

13863-13869: Deprecated TaxConfig Field in This Block.
The TaxConfig property is now marked as deprecated. Ensure that API consumers are informed about this deprecation and that the documentation reflects the change.


13892-13898: Addition of Subscription Field with Minor Typo.
The new subscription property referencing InvoiceLineSubscriptionReference is now being added. Please correct the typo in the description by replacing "subscritpions" with "subscriptions" for clarity.


13906-13925: Transition from Deprecated Price Fields to New RateCard.
Several pricing-related fields (price, paymentTerm, and quantity) are now deprecated in favor of the new rateCard property (referencing InvoiceFlatFeeRateCard). Ensure that migration guidance is provided to clients and that documentation clearly explains the new structure.


13980-14000: Consistent Deprecation in Flat Fee Schema.
This section continues the pattern of deprecating price, paymentTerm, and quantity in favor of the new rateCard (which points to InvoiceFlatFeeRateCard). Double-check that all related documentation is updated accordingly.


14095-14137: Introduction of InvoiceFlatFeeRateCard Schema.
A new schema InvoiceFlatFeeRateCard is introduced with properties such as taxConfig, price, discounts, and quantity. Confirm that the price correctly ties to FlatPriceWithPaymentTerm and that the discounts are restricted to percentage discounts as intended.


14228-14405: Comprehensive Redefinition of Discount Schemas.
This segment lays out detailed definitions for both amount-based (InvoiceLineDiscountAmount) and usage-based (InvoiceLineDiscountUsage) discounts. The use of oneOf with a proper discriminator is well implemented. Please verify that numeric validations and the linkage of rateCardDiscount are consistent with the billing engine's expectations.


14714-14734: Deprecation of Flat Fee Price Fields.
This block reiterates the deprecation of pricing fields (price, paymentTerm, and quantity) in favor of using rateCard. It is essential to update the migration guides so that consumers can easily map legacy fields to the new schema.


15101-15107: Refinement Needed in Subscription Property Description.
The block adds a subscription property after the external IDs. Similar to an earlier hunk, please fix the typo in the description (“subscritpions” → “subscriptions”) to maintain clarity and consistency.


15196-15216: Reinforcement of Usage-based Pricing Updates.
This hunk mirrors previous changes by deprecating the legacy usage-based pricing fields and promoting the new rateCard definition for usage items. Confirm that the new pattern is thoroughly documented in both the API specification and client guides.

api/spec/src/billing/invoices/discounts.tsp (1)

1-31: Adopt consistent naming for clarity.

These declarations for InvoiceGenericCharge and its associated metadata look good. However, consider reviewing naming conventions for consistency across the codebase (e.g., preferring DiscountReason or ReasonCode consistently). This helps reduce confusion when other contributors consume these models.

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

126-135: Centralize validation to promote consistency.

You use mapAndValidateFlatFeeRateCardDeprecatedFields and mapAndValidateUsageBasedRateCardDeprecatedFields to parse and validate lines. This approach is consistent and clean. Verify that all possible deprecated fields and their validations are covered. If you anticipate expansions (e.g., new fields or more constraints), consider abstracting the common logic to reduce duplication.

Also applies to: 170-178


425-464: Consider performance implications when mapping each individual discount.

The loop in mapDiscountsToAPI calls mapDiscountToAPI for each discount. While it’s straightforward, if extremely large discount lists are possible, the repeated transformations could affect performance. For typical invoice volumes, this is fine, but if you anticipate thousands of line discounts, consider optimizing or batching transformations.

api/client/javascript/src/client/schemas.ts (1)

4849-4872: Leverage new rate card approach and remove dependence on deprecated fields.
Multiple fields (perUnitAmount, paymentTerm, quantity) are now marked @deprecated, replaced by a rateCard mechanism. Consider gradually removing dependencies on these deprecated fields for clarity and maintainability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9f8ea75 and 94d7246.

📒 Files selected for processing (9)
  • api/client/javascript/src/client/schemas.ts (22 hunks)
  • api/openapi.cloud.yaml (24 hunks)
  • api/openapi.yaml (24 hunks)
  • api/spec/src/billing/invoices/discounts.tsp (1 hunks)
  • api/spec/src/billing/invoices/invoice.tsp (7 hunks)
  • api/spec/src/billing/invoices/main.tsp (1 hunks)
  • openmeter/billing/httpdriver/deprecations.go (1 hunks)
  • openmeter/billing/httpdriver/deprecations_test.go (1 hunks)
  • openmeter/billing/httpdriver/invoiceline.go (21 hunks)
🧰 Additional context used
🧬 Code Definitions (4)
openmeter/billing/httpdriver/deprecations_test.go (2)
api/client/javascript/src/client/schemas.ts (7)
  • PricePaymentTerm (9250-9250)
  • RateCard (9253-9253)
  • InvoiceFlatFeeRateCard (9086-9087)
  • FlatPriceWithPaymentTerm (9047-9048)
  • RateCardUsageBasedPrice (9263-9264)
  • UnitPriceWithCommitments (9329-9330)
  • InvoiceUsageBasedRateCard (9141-9142)
api/client/go/client.gen.go (8)
  • PricePaymentTerm (4606-4606)
  • RateCard (4638-4640)
  • InvoiceFlatFeeRateCard (2977-2994)
  • FlatPriceWithPaymentTerm (2478-2488)
  • FlatPriceWithPaymentTermTypeFlat (272-272)
  • RateCardUsageBasedPrice (4789-4791)
  • UnitPriceWithCommitments (5463-5475)
  • InvoiceUsageBasedRateCard (3668-3684)
openmeter/billing/httpdriver/invoiceline.go (2)
openmeter/productcatalog/price.go (2)
  • InAdvancePaymentTerm (20-20)
  • Price (80-87)
openmeter/billing/invoiceline.go (8)
  • FlatFeeLine (251-258)
  • Price (682-682)
  • UsageBasedLine (684-693)
  • LineDiscount (726-736)
  • FlatFeeCategory (235-235)
  • FlatFeeCategory (244-249)
  • FlatFeeCategoryRegular (239-239)
  • Line (271-284)
api/client/javascript/src/client/schemas.ts (1)
api/client/go/client.gen.go (9)
  • InvoiceFlatFeeRateCard (2977-2994)
  • InvoiceLine (3012-3014)
  • InvoiceLineAppExternalIds (3017-3023)
  • InvoiceLineCharge (3026-3028)
  • InvoiceLineChargeAmount (3031-3055)
  • InvoiceLineDiscount (3061-3063)
  • InvoiceLineDiscountAmount (3066-3096)
  • InvoiceLineDiscountUsage (3104-3136)
  • InvoiceUsageBasedRateCard (3668-3684)
openmeter/billing/httpdriver/deprecations.go (3)
api/client/javascript/src/client/schemas.ts (5)
  • RateCard (9253-9253)
  • InvoiceFlatFeeRateCard (9086-9087)
  • TaxConfig (9320-9320)
  • InvoiceUsageBasedRateCard (9141-9142)
  • RateCardUsageBasedPrice (9263-9264)
api/api.gen.go (6)
  • RateCard (4960-4962)
  • InvoiceFlatFeeRateCard (3237-3254)
  • TaxConfig (5754-5763)
  • Price (4919-4921)
  • InvoiceUsageBasedRateCard (3928-3944)
  • RateCardUsageBasedPrice (5114-5116)
api/client/go/client.gen.go (5)
  • RateCard (4638-4640)
  • InvoiceFlatFeeRateCard (2977-2994)
  • TaxConfig (5400-5409)
  • InvoiceUsageBasedRateCard (3668-3684)
  • RateCardUsageBasedPrice (4789-4791)
🔇 Additional comments (71)
api/spec/src/billing/invoices/main.tsp (1)

16-16: Add import confirmed.
Importing ./discounts.tsp cleanly integrates discount-related models in this file. No issues found.

openmeter/billing/httpdriver/deprecations_test.go (3)

1-11: Good test structuring and dependencies.
The package declaration and import statements are organized and straightforward. No concerns about concurrency, security, or performance here.


13-114: Comprehensive flat fee tests.
Your TestFlatFeeLineParser thoroughly covers success and failure cases, ensuring deprecated vs. current field parity is validated. This fosters robust backwards compatibility.


116-195: Usage-based line coverage is excellent.
TestUsageBasedLineParser includes both positive and negative scenarios, verifying field presence and mismatched values. The approach is comprehensive, ensuring consistent handling of deprecated fields.

api/spec/src/billing/invoices/invoice.tsp (9)

648-648: Clear deprecation note.
Marking taxConfig as deprecated guides users toward rateCard.taxConfig. Ensure consistent usage in dependent code.


710-720: Introducing InvoiceUsageBasedRateCard.
This model neatly encapsulates usage-based rate card properties (discounts, taxConfig, featureKey, price). This aligns with the new design for usage-based lines.


745-752: New rateCard for usage-based lines.
This property centralizes line-level pricing data. Make sure external references to legacy fields are updated to use rateCard.


769-787: Introducing InvoiceFlatFeeRateCard.
Consistent with usage-based counterpart. Moves discounts and config into a dedicated structure, simplifying future expansions.


804-806: Deprecating perUnitAmount.
Linking it to rateCard.perUnitAmount keeps the new architecture uniform. Make sure internal calculations also reflect this change.


818-821: Deprecating inline quantity.
Noting the shift to rateCard.quantity is consistent with the newly introduced model. This ensures a single source of truth for quantity value.


822-828: New rateCard property for flat fee lines.
Well-aligned with usage-based lines. Helps unify discount handling under a single interface.


1034-1035: Documentation clarity.
Adding a descriptive comment for InvoiceLineSubscriptionReference provides better context around subscription-based lines. No issues found.


689-689:

Details

✅ Verification successful

Subscription reference adjustment.
Confirm that this line’s changes accurately reflect the new subscription reference logic. If this property’s usage changed upstream, verify references are updated accordingly.


🏁 Script executed:

#!/bin/bash
# Searching for references to `subscription?` in invoice lines
rg "subscription\?\:\s*InvoiceLineSubscriptionReference"

Length of output: 190


Subscription Reference Adjustment Verification
The update at line 689 appears intended to reflect the new subscription reference logic. Note that the initial regex command errored due to escape sequence issues. I've replaced it with a literal search command above. Please run this command and manually verify that:

  • The updated subscription reference (“subscription?: InvoiceLineSubscriptionReference”) is consistently applied across the codebase.
  • Upstream changes in the property’s usage are correctly reflected in all relevant references.

🏁 Script executed:

#!/bin/bash
# Re-run reference search for the updated subscription reference logic using literal search.
# This avoids regex escape issues that occurred with the previous command.
rg -F "subscription?: InvoiceLineSubscriptionReference" -n .

Length of output: 161


Subscription Reference Adjustment – Verified

The subscription reference update now uses the literal "subscription?: InvoiceLineSubscriptionReference" as expected. A literal search confirms that this property is defined in api/spec/src/billing/invoices/invoice.tsp (line 688), and no additional conflicting references were found. Please ensure that this change aligns with the upstream logic for subscription handling.

api/openapi.yaml (20)

13912-13918: InvoiceLineCharge Schema Reference Update
The changes introduce a new reference to InvoiceLineCharge for the charges array. This aligns with the new billing model that replaces the legacy BillingLineCharge schema.


13937-13943: Marking Tax Config as Deprecated
The addition of deprecated: true to the TaxConfig reference is consistent with the overall deprecation strategy defined in the PR objectives. Please ensure that API consumers are notified about these deprecated fields.


14032-14038: Tax Config Deprecation Consistency
The deprecation of the TaxConfig reference here is consistent with previous sections. Confirm that this deprecation is clearly documented for API consumers.


14054-14074: Consistent Deprecation and Replacement with RateCard
This block mirrors earlier changes by deprecating legacy pricing fields and introducing the rateCard reference for flat fee lines. Ensure that any related client documentation or downstream validation logic is also updated accordingly.


14120-14126: Tax Config Deprecation Revisited
The reintroduction of a deprecation marker on the TaxConfig field maintains consistency across the API spec.


14142-14163: Deprecation and New RateCard Mapping
This section applies the same deprecation strategy as earlier—retiring legacy fields in favor of the new rateCard mapping. It is important that all related documentation is updated so API users are clear about which properties are to be used.


14169-14215: Introduction of InvoiceFlatFeeRateCard Schema
A new InvoiceFlatFeeRateCard schema has been introduced to encapsulate the fee intent (including properties for taxConfig, price, discounts, and quantity). Verify that required fields (like price) and default values (such as the default quantity of 1) are properly validated in practice.


14257-14279: New InvoiceLineCharge and InvoiceLineChargeAmount Schemas
The new InvoiceLineCharge schema now uses a discriminator with a oneOf to refer to the InvoiceLineChargeAmount type, which is a robust strategy for future extensions. Ensure that if other charge types are introduced later, the discriminator and mapping are updated accordingly.


14302-14479: Comprehensive Definitions for Charge and Discount Schemas
This extensive section defines InvoiceLineChargeAmount, InvoiceLineDiscount, InvoiceLineDiscountAmount, and InvoiceLineDiscountUsage with detailed properties and proper readOnly markers. The use of discriminators for differentiating discount types (i.e. amount vs. usage) is well implemented. Please verify that all enum values and validation patterns (especially for ID formats) align with global API standards.


14522-14528: Clarification for Subscription Reference
The description update for InvoiceLineSubscriptionReference adds clarity to the relationship between invoice lines and subscriptions. This is a welcome improvement—ensure that any references in related client code are updated to reflect these changes.


14766-14772: Reiteration of Tax Config Deprecation
Reiterating the deprecation of TaxConfig in this block helps maintain a consistent policy across the specification. The approach looks solid.


14788-14808: Consistent Deprecation for Flat Fee Fields
This change continues the trend of deprecating legacy numeric and payment fields and replacing them with the new rateCard reference. Confirm that any client-side or downstream integrations are adjusted to ignore the deprecated fields.


14883-14889: Tax Config Deprecation Consistency Check
The deprecation marker for the TaxConfig property in this section once again follows the established pattern. No issues noted.


14905-14924: Usage-Based RateCard Structure Update
The schema changes for usage-based items include deprecating certain legacy fields and introducing a new rateCard reference for usage-based pricing. Verify that the regex pattern for featureKey is correct and that the description clearly distinguishes this model from flat fee rate cards.


15121-15127: Charges Array Consistency for Invoice Lines
The charges array is updated to reference InvoiceLineCharge, which is consistent with earlier changes. This ensures uniformity in how charges are recorded across different invoice line types.


15146-15152: Deprecation of Tax Config in Nested Structures
This block continues to mark the TaxConfig field as deprecated, now in a nested context. The clarity and consistency of deprecation throughout the document is commendable.


15189-15209: Usage-Based Item Details Update
This hunk updates properties for usage-based items, including deprecation of legacy fields and the introduction of a new rateCard structure. The description details are clear and consistent with previous patterns.


15248-15254: Reaffirming Tax Config Deprecation
The consistent deprecation of the TaxConfig property in this section reinforces the overall design pattern.


15270-15288: Addition of ID Field in Usage-Based Schema
This block adds an id field to the usage-based rate card schema along with deprecation markers and detailed descriptions. Please confirm that the regex pattern for the id field aligns with the intended global ID format.


15330-15336: Consistent Deprecation in Nested Tax Configs
The deprecation of TaxConfig remains consistent in this nested context as well. No further issues observed.

api/openapi.cloud.yaml (12)

13838-13844: Updated Charges Array with InvoiceLineCharge Reference.
The schema now specifies an array of charges using the new InvoiceLineCharge reference. Please verify that the downstream processing correctly supports the new charge schema.


13958-13963: Deprecation of TaxConfig is Consistently Applied.
The TaxConfig property in this block is marked as deprecated. Confirm that this aligns with the overall restructuring strategy and that clients are aware of the deprecation.


14046-14052: Marking TaxConfig as Deprecated Here, Too.
The TaxConfig field is again marked as deprecated. It is important that the deprecation notice is uniformly communicated across all schema sections.


14068-14088: Flat Fee Pricing Deprecation Consistency.
This fragment clearly deprecates the legacy pricing fields and introduces the new rateCard for flat fee lines. Please ensure that any client-side transformations or validations are updated to support the rateCard model.


14183-14205: New InvoiceLineCharge and InvoiceLineChargeAmount Schemas.
The legacy billing charge schema is replaced with InvoiceLineCharge (using a discriminator based on the type) and its detail defined in InvoiceLineChargeAmount. Ensure that all mandatory fields (such as createdAt, updatedAt, id, amount, and type) are correctly implemented in the service layer.


14448-14454: Enhanced Description for Subscription Reference.
The description for InvoiceLineSubscriptionReference has been enriched. Additionally, InvoiceLineTaxBehavior is declared appropriately. No further action is needed, but ensure that the enhanced messaging is propagated in documentation.


14692-14698: TaxConfig Deprecation in Subscription Section.
Tax configuration is again marked as deprecated here. Please confirm that this deprecation is communicated consistently to avoid confusion among API consumers.


14809-14815: Consistent Deprecation for TaxConfig.
The TaxConfig field is consistently marked as deprecated in this segment. Ensure that all client libraries and documentation reflect this change.


15047-15053: Ensuring Consistency in Charges Definition.
The charges property is redefined to use the new InvoiceLineCharge schema. Confirm that all related processing logic and validations have been updated to handle the new charge format.


15072-15078: Deprecation in Nested Structures for TaxConfig.
The TaxConfig property in this nested context is also marked as deprecated, with the children property remaining read-only. Ensure that any hierarchical processing respects these deprecations.


15174-15180: Deprecation Continuity for TaxConfig.
The deprecation of the TaxConfig field is applied consistently in this block. No additional changes are needed, but verify that your release notes clearly mention these deprecations.


15256-15262: TaxConfig Deprecation Reaffirmed.
The TaxConfig field continues its deprecation status in this section. This is consistent with previous deprecations; ensure that all related documentation is updated accordingly.

api/spec/src/billing/invoices/discounts.tsp (2)

33-75: Ensure alignment of “amount” vs “usage” functionalities.

The InvoiceLineGenericAmountCharge and InvoiceLineGenericUsageCharge definitions are clear in distinguishing types of charges. However, make sure there's a consistent approach to validating and applying these charge properties. For instance, if you implement advanced validation somewhere else (e.g., restricting negative or zero amounts), ensure it’s applied consistently to usage-based fields too.

Can you confirm that usage-based billing and amount-based billing rely on the same validation or if separate logic is desired?


76-175: Double-check the discount handling across all new union types.

The union definitions for InvoiceLineDiscount and InvoiceLineCharge successfully model multiple discount and charge subtypes. However, changes in discount or charge logic often ripple throughout the system. Ensure all references to InvoiceLineDiscountType and InvoiceLineChargeType in downstream usage have been updated to handle these new enumerations properly (e.g., data transformations, error handling, or specialized business logic).

Please verify that any code mapping from the old discount or charge interfaces to these new union types has been updated accordingly. If not, consider adding the necessary logic or validations.

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

31-34: Check backward-compatibility of default constants.

Defining defaultFlatFeePaymentTerm and defaultFlatFeeQuantity provides clear defaults, but verify if older code or existing data in the database might expect different defaults. Ensure applying these defaults does not introduce unexpected changes for existing lines.


263-310: Handle potential errors during discount mapping gracefully.

mapDiscountsToAPI and the discount logic in fee/usage-based lines add crucial error-checking. Confirm that callers handle these new error returns consistently (e.g., gracefully returning a 4xx to the user if discount mapping fails). Otherwise, discount errors may inadvertently trigger 5xx errors or incomplete data messages.

Also applies to: 344-348

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

1-94: Confirm environment supports errors.Join for aggregated error reporting.

Go’s errors.Join was introduced in Go 1.20. If the codebase or environment is pinned to an earlier Go version, this could break at runtime. Double-check your Go toolchain version to avoid unexpected panics or builds failing in older environments.


96-174: Overall structure for deprecations is solid.

These deprecation handler functions and validations (for both flat fee and usage-based rate cards) provide a straightforward approach to backward compatibility. Just ensure the reflection-based comparison for TaxConfig remains stable for all potential struct changes, especially if any fields are slices or maps (which might require deeper equality checks).

api/client/javascript/src/client/schemas.ts (20)

4898-4901: Redundant taxConfig deprecation comment.
This seems to be the same deprecation note as in previous segments. No additional concerns.


4919-4935: Repeated deprecation usage.
The perUnitAmount, paymentTerm, and quantity properties are again marked @deprecated. No new issues introduced here.


4967-4969: Again, taxConfig is marked as deprecated.
This repeats the earlier deprecation. No further action needed beyond prior notes.


4987-5003: Reiterated field deprecations.
All references to perUnitAmount, paymentTerm, and quantity remain consistent with earlier deprecations. No new concerns.


5015-5044: Introducing InvoiceFlatFeeRateCard.
This new interface consolidates flat-fee settings, including optional tax config, discounts, and price details. The structure looks coherent and aligns with the Go reference snippets provided.


5071-5074: Adopting InvoiceLineCharge and ChargeAmount.
The new InvoiceLineCharge points to InvoiceLineChargeAmount for pre-tax additions—this reflects the updated design pattern. Looks well-defined.


5235-5238: No concerns on subscription reference.
The introduced InvoiceLineSubscriptionReference property is straightforward.


5403-5407: Repeated taxConfig deprecation comment.
Matches earlier usage. No additional concerns.


5424-5440: Same set of deprecated fields.
This mirrors previous patterns for flat-fee lines. No further notes.


5486-5489: Reiterated taxConfig deprecation.
No fresh issues here.


5506-5519: Usage-based line deprecations: price, featureKey.
These references match prior deprecation patterns. No new concerns.


5643-5653: Charges & deprecated taxConfig repeated.
No new feedback beyond prior notes.


5672-5691: Again: price, featureKey, rateCard.
Consistent with the usage-based lines approach.


5718-5721: Still the same taxConfig deprecation.
No extra comments.


5738-5751: Repeated usage-based line shape.
The same pattern with deprecated price and featureKey; usage-based approach remains intact.


5777-5781: No new findings on deprecated taxConfig.
Same scenario here.


5797-5840: InvoiceUsageBasedRateCard interface introduced.
This new type clarifies usage-based pricing details, discounts, and tax config references. It’s consistent with the broader refactoring strategy.


9086-9100: Type exports for flat-fee charges and discounts.
These exports (InvoiceFlatFeeRateCard, InvoiceLineCharge, etc.) align with the updated schema.


9141-9142: Type export InvoiceUsageBasedRateCard.
The usage-based rate card export matches the new approach.


4820-4830:

Details

❓ Verification inconclusive

Confirm usage of newly added property & deprecation notice.
The new charges?: InvoiceLineCharge[] property is a good addition, enabling multiple charges to be encapsulated. The taxConfig field is now marked as @deprecated—please ensure any existing usage paths are updated or removed in favor of the new approach (e.g. using a rateCard).


🏁 Script executed:

#!/bin/bash
# Search for references to taxConfig in the codebase for potential cleanup
rg -A 3 'taxConfig'

Length of output: 25273


Review: Validate Deprecation of taxConfig & Confirm New charges Implementation

The new charges?: InvoiceLineCharge[] property is a well-considered enhancement for handling multiple charges. Meanwhile, the legacy taxConfig field is now marked as deprecated in the JavaScript client schema. However, our repository-wide search shows that taxConfig is still referenced broadly (in tests, API generation, OpenAPI specs, etc.).

Before finalizing, please ensure that:

  • The deprecation notice for taxConfig in api/client/javascript/src/client/schemas.ts (lines 4820-4830) is clearly documented and communicated to downstream consumers.
  • A migration path (e.g., leveraging rateCard.taxConfig) is defined and gradually implemented across all usage sites, including tests and server/API components, to avoid future inconsistencies.

GAlexIHU
GAlexIHU previously approved these changes Apr 3, 2025
@turip turip force-pushed the feat/invoice-discounts-api-v2 branch 2 times, most recently from 31b5f57 to 8f70b47 Compare April 3, 2025 16:22
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
api/client/javascript/src/client/schemas.ts (1)

5153-5157: ⚠️ Potential issue

Documentation for amount property references non-existent field

The documentation for the amount property in InvoiceLineDiscountAmount mentions "calculated if percent present", but there is no percent property defined in this interface or its parent interfaces.

Fix the documentation to remove the reference to a non-existent field:

/**
 * Amount in the currency of the invoice
- * @description Fixed discount amount to apply (calculated if percent present).
+ * @description Fixed discount amount to apply.
 */
readonly amount: components['schemas']['Numeric']
🧹 Nitpick comments (17)
api/openapi.yaml (5)

13966-13972: Hunk 3 – Subscription Field and Typo Fix
A new subscription field is introduced with a reference to subscription details; however, the description contains a typographical error ("subscritpions"). Consider correcting it to "subscriptions." A suggested diff is:

-          description: Subscription are the references to the subscritpions that this line is related to.
+          description: Subscription are the references to the subscriptions that this line is related to.

13980-14000: Hunk 4 – Deprecated Fields & New RateCard Integration (Flat Fee)
This block deprecates legacy fields such as paymentTerm and quantity and introduces the new rateCard referencing InvoiceFlatFeeRateCard. The restructuring is in line with the PR objectives. Please verify that a clear migration guide is provided so that API clients can smoothly transition.


14169-14213: Hunk 9 – Defining InvoiceFlatFeeRateCard Schema
The new InvoiceFlatFeeRateCard schema is well defined with required fields (including a nested taxConfig, price, and an array of discounts). The provided example in the price property further clarifies expected usage. Consider adding a note in the description regarding client migration to this new structure.


14788-14808: Hunk 14 – Flat Fee Line Deprecations Updated
The properties price, paymentTerm, and quantity are again marked as deprecated in favor of the new rateCard reference. This is consistent with the overall restructuring. Consider adding additional migration details in the release notes.


15175-15181: Hunk 19 – Reiterated Subscription Reference with Typo
Similar to Hunk 3, this section’s subscription field contains the same typographical error in "subscritpions." Please update the description as suggested:

-          description: Subscription are the references to the subscritpions that this line is related to.
+          description: Subscription are the references to the subscriptions that this line is related to.
api/openapi.cloud.yaml (2)

13892-13901: Typo in Subscription Description
In the subscription property description, the word “subscritpions” is misspelled. Consider updating it to “subscriptions” for clarity.

-          description: Subscription are the references to the subscritpions that this line is related to.
+          description: Subscription are the references to the subscriptions that this line is related to.

15101-15107: Subscription Field Typographical Correction Needed
The subscription field description again contains the typo “subscritpions.” Please update this description for consistency.

-          description: Subscription are the references to the subscritpions that this line is related to.
+          description: Subscription are the references to the subscriptions that this line is related to.
api/spec/src/billing/invoices/invoice.tsp (4)

710-719: Consider capturing payment term requirements.

This new InvoiceUsageBasedRateCard model omits a payment term field. If usage-based lines can have distinct payment terms, consider adding it here to ensure consistency across rate cards.


769-788: Unify usage-based and flat-fee approaches.

InvoiceFlatFeeRateCard largely mirrors InvoiceUsageBasedRateCard. To reduce complexity, consider a shared structure or patterns where possible.


819-821: Retire the old quantity field.

By marking quantity as deprecated, you should finalize its removal or fully transition to rateCard.quantity. Keeping both can lead to confusion.


824-827: Require the new rateCard field sooner rather than later.

Although you plan to make rateCard required in the future, consider an interim validation that warns or errors if the field is missing, speeding up adoption.

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

199-203: Encapsulate TaxConfig usage in a single place.

Implementing TaxConfig: rateCardParsed.TaxConfig is straightforward. If anything else modifies taxConfig, consider centralizing the logic for better maintainability.


502-511: Simulation line conversion for flat fees.

Reusing mapAndValidateFlatFeeRateCardDeprecatedFields ensures consistent behavior between regular and simulation flows. Consider adding logs or metrics for these transformations.

openmeter/billing/httpdriver/deprecations.go (4)

29-41: Ensure consistent validation for PaymentTerm and TaxConfig.

The ValidateDeprecatedFields() method only checks PerUnitAmount and Quantity. If PaymentTerm or TaxConfig are required in specific scenarios, consider adding their validations. Otherwise, clarify their optional status.


103-174: Consider reducing duplication or clarifying flow.

The function branches significantly between the deprecated approach (RateCard == nil) and the new approach (RateCard != nil). While this is understandable for transitional purposes, you may consider refactoring some common logic, or adding comments to clarify the deprecation flow for future maintainers.


201-241: Clarify error messages for usage-based rate cards.

The error messages (e.g., "price is required") might benefit from referencing usage-based context or the relevant field name to reduce confusion for users who mix up rate card fields.


249-294: Maintain consistency with flat-fee approach.

Similar to mapAndValidateFlatFeeRateCardDeprecatedFields, this function splits logic between old and new usage-based fields. Consider factoring out shared logic (e.g., repeated error handling) to ease future maintenance.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 94d7246 and 340ef71.

📒 Files selected for processing (9)
  • api/client/javascript/src/client/schemas.ts (22 hunks)
  • api/openapi.cloud.yaml (24 hunks)
  • api/openapi.yaml (24 hunks)
  • api/spec/src/billing/invoices/discounts.tsp (1 hunks)
  • api/spec/src/billing/invoices/invoice.tsp (7 hunks)
  • api/spec/src/billing/invoices/main.tsp (1 hunks)
  • openmeter/billing/httpdriver/deprecations.go (1 hunks)
  • openmeter/billing/httpdriver/deprecations_test.go (1 hunks)
  • openmeter/billing/httpdriver/invoiceline.go (21 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • api/spec/src/billing/invoices/main.tsp
  • openmeter/billing/httpdriver/deprecations_test.go
🧰 Additional context used
🧬 Code Definitions (2)
openmeter/billing/httpdriver/deprecations.go (3)
api/client/javascript/src/client/schemas.ts (5)
  • RateCard (9253-9253)
  • InvoiceFlatFeeRateCard (9086-9087)
  • TaxConfig (9320-9320)
  • InvoiceUsageBasedRateCard (9141-9142)
  • RateCardUsageBasedPrice (9263-9264)
api/api.gen.go (6)
  • RateCard (4960-4962)
  • InvoiceFlatFeeRateCard (3237-3254)
  • TaxConfig (5754-5763)
  • Price (4919-4921)
  • InvoiceUsageBasedRateCard (3928-3944)
  • RateCardUsageBasedPrice (5114-5116)
api/client/go/client.gen.go (5)
  • RateCard (4638-4640)
  • InvoiceFlatFeeRateCard (2977-2994)
  • TaxConfig (5400-5409)
  • InvoiceUsageBasedRateCard (3668-3684)
  • RateCardUsageBasedPrice (4789-4791)
openmeter/billing/httpdriver/invoiceline.go (3)
openmeter/productcatalog/price.go (2)
  • InAdvancePaymentTerm (20-20)
  • Price (80-87)
api/client/go/client.gen.go (6)
  • RateCard (4638-4640)
  • TaxConfig (5400-5409)
  • InvoiceFlatFeeCategory (2765-2765)
  • PricePaymentTerm (4606-4606)
  • InvoiceFlatFeeRateCard (2977-2994)
  • FlatPriceWithPaymentTerm (2478-2488)
openmeter/billing/invoiceline.go (8)
  • FlatFeeLine (251-258)
  • Price (682-682)
  • UsageBasedLine (684-693)
  • LineDiscounts (743-745)
  • LineDiscount (726-736)
  • FlatFeeCategory (235-235)
  • FlatFeeCategory (244-249)
  • Line (271-284)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: CI
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: Test
  • GitHub Check: Commit hooks
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint
🔇 Additional comments (79)
api/openapi.yaml (19)

13912-13918: Hunk 1 – Charges Array Schema Update
The updated array definition now correctly references the new InvoiceLineCharge schema. This change cleanly aligns with the removal of invoice-level discounts and the introduction of line-level charge abstractions.


13937-13942: Hunk 2 – Deprecating TaxConfig Property
The addition of deprecated: true for the TaxConfig reference is consistent with the new API structure. Ensure that related documentation clearly highlights this deprecation.


14032-14037: Hunk 5 – Consistent Deprecation for TaxConfig
The property using the TaxConfig reference is marked as deprecated here as well. This maintains consistency across the API; ensure documentation mirrors these changes.


14054-14074: Hunk 6 – Mirroring Flat Fee Line Deprecations
The deprecation of paymentTerm and quantity alongside the introduction of the new flat fee rateCard is consistent with the previously updated blocks. Confirm that these changes are uniformly applied throughout the spec.


14120-14126: Hunk 7 – TaxConfig Deprecation Consistency
This hunk reiterates the deprecation of the TaxConfig schema within the line item context. The change is clear and consistent.


14142-14163: Hunk 8 – Additional Flat Fee Line Updates
Again, the updated rateCard definition (referencing InvoiceFlatFeeRateCard) is introduced and deprecated fields are maintained. The consistency here is commendable.


14257-14269: Hunk 10 – Introducing InvoiceLineCharge with Discriminator
The new InvoiceLineCharge schema employs a discriminator mapping to choose between charge types (currently only amount). This is a clean approach that facilitates future extensibility. Verify that any future charge types are appropriately mapped as the API evolves.


14302-14403: Hunk 11 – Detailed Charge and Discount Schemas
This block defines:

  • InvoiceLineChargeAmount with essential properties (including ID, amount, and type).
  • InvoiceLineDiscount as a union (via oneOf) of InvoiceLineDiscountAmount and InvoiceLineDiscountUsage, with a discriminator for clarity.

The comprehensive structure supports both fixed and usage-based discounts. Please double-check that the required fields (and the ID pattern) align with business rules and that the definitions are consistent throughout the spec.


14522-14526: Hunk 12 – Subscription Reference Schema
The schema for InvoiceLineSubscriptionReference now leverages an allOf reference to IDResource. This appears well integrated; however, validate that its intended usage is clearly described in external documentation.


14766-14772: Hunk 13 – Additional TaxConfig Deprecation
Another instance where the TaxConfig property is marked as deprecated. The change is uniform with prior similar modifications.


14883-14889: Hunk 15 – Consistent Deprecation Reminder
This brief update for a TaxConfig reference reinforces the deprecation pattern throughout the document.


14905-14924: Hunk 16 – Usage-Based Pricing and Deprecation
This block introduces the usage-based pricing structure by referencing RateCardUsageBasedPrice and marks the featureKey as deprecated. Ensure that clients are aware of the new InvoiceUsageBasedRateCard mechanism replacing these legacy fields.


15121-15127: Hunk 17 – Charges Array for Usage-Based Lines
The charges field is again defined as an array referencing InvoiceLineCharge, maintaining consistency across both flat fee and usage-based items.


15146-15152: Hunk 18 – Nested Line Properties with TaxConfig and Children
The inclusion of the children field to represent nested line details, alongside a deprecated TaxConfig section, is clear. No issues were noted.


15189-15208: Hunk 20 – Usage-Based Rate Card Structure
This hunk mirrors the structure seen in Hunk 16. It defines properties for usage-based pricing by referencing RateCardUsageBasedPrice, deprecates the featureKey, and introduces a new rateCard that references InvoiceUsageBasedRateCard. This structured approach is well thought out; just ensure that any deprecation is clearly communicated.


15248-15254: Hunk 21 – Additional TaxConfig Deprecation Block
The TaxConfig reference is again marked as deprecated with an associated period property. This is consistent with similar sections.


15270-15289: Hunk 22 – Continuing Usage-Based Schema Enhancements
This block repeats the pattern of referencing RateCardUsageBasedPrice, deprecating the featureKey, and introducing the new usage-based rate card. Consistency here is key—please verify alignment with Hunk 20.


15330-15336: Hunk 23 – Yet Another TaxConfig Deprecation
The deprecation of the TaxConfig element is continued here without issue. Ensure that all these deprecations are documented in the changelog.


15352-15414: Hunk 24 – InvoiceUsageBasedLineCreateWithCustomer & InvoiceUsageBasedRateCard Schemas
This extensive change defines two new schemas:

  • InvoiceUsageBasedLineCreateWithCustomer, which now includes a customerId property (with an ID pattern and example) and a descriptive text clarifying its role in usage-based invoicing.
  • InvoiceUsageBasedRateCard, which outlines the intent for usage-based pricing and contains properties (e.g., featureKey, taxConfig, price, and an array of discounts).

Both schemas are comprehensive and align with the new API design. It is recommended to ensure that client-facing documentation and migration guides highlight these changes clearly.

api/openapi.cloud.yaml (22)

13838-13844: New Charges Definition Using InvoiceLineCharge
The charges property now specifies an array whose items reference InvoiceLineCharge. This change centralizes charge information to the new schema. Please ensure that the referenced schema is defined correctly and that client integrations are updated accordingly.


13863-13869: Deprecation of Tax Configuration Field
The TaxConfig object is now marked as deprecated here. Verify that this deprecation is documented in the migration guide and that downstream consumers are aware of the change.


13906-13926: Deprecation of Legacy Pricing Fields and Introduction of Rate Card
The properties for price, payment term, and quantity are now deprecated, and a new rateCard property referencing InvoiceFlatFeeRateCard has been added. This aligns with the new invoice discount model. Please ensure that client documentation reflects these deprecations and that migration steps are clearly communicated.


13958-13963: Consistent Deprecation of TaxConfig for Line Periods
Deprecating TaxConfig in this context is consistent with earlier changes. Confirm that any logic relying on the previous tax configuration is updated or properly migrated.


13980-14001: Reapplication of Deprecated Pricing Fields in a Different Context
This hunk reiterates the deprecation of Numeric (price), PricePaymentTerm, and quantity fields while introducing rateCard for flat-fee lines. It is important to verify consistency with similar definitions (see hunks 4 and 8) and update related documentation.


14046-14052: Deprecated TaxConfig with Period Field Specification
The TaxConfig object here is again marked as deprecated. Ensure that this deprecation is consistently communicated across the API specification and that the new fields fully replace its functionality where needed.


14068-14088: Uniform Deprecation of Legacy Pricing Attributes
Reiterates deprecation for pricing (Numeric), payment term, and quantity fields with the new rateCard for flat-fee items. Confirm that migration notes and documentation are updated to reflect these changes consistently.


14095-14138: Definition of InvoiceFlatFeeRateCard
A new schema, InvoiceFlatFeeRateCard, is introduced to represent the intent for flat fee lines. The schema defines properties such as taxConfig, price (nullable), discounts, and quantity. Please verify that the required structure (e.g., price being required but nullable) matches business logic and update client guides if needed.


14183-14206: InvoiceLineCharge and Discriminator Setup
The new InvoiceLineCharge schema is now defined using a oneOf composition with a discriminator on the type property. Ensure that:

  • The discriminator mapping (with key amount) properly resolves to InvoiceLineChargeAmount
  • All required fields in the charge amount schema are enforced
    This change should streamline charge representation in response objects.

14228-14404: Comprehensive Redefinition of InvoiceLineDiscount Schemas
The definitions for InvoiceLineDiscount, InvoiceLineDiscountAmount, and InvoiceLineDiscountUsage now clearly separate fixed-amount discounts from usage-based discounts. The use of a discriminator on the type property facilitates polymorphism. Please validate that all required properties (timestamps, IDs, etc.) are consistent with the rest of the API and that the examples and enums meet the business requirements.


14448-14453: Clarification for Subscription Reference Schema
The InvoiceLineSubscriptionReference is now described with an updated block, followed by the new InvoiceLineTaxBehavior. Ensure that the relationship between the subscription reference and other line items is well documented for consumers.


14692-14698: Further Deprecation of TaxConfig with Period Properties
Another instance where TaxConfig is marked as deprecated alongside the period field. The consistency is good; please double-check that every deprecation is accompanied by migration guides.


14714-14734: Legacy Pricing Fields Deprecation Revisited for Flat Fee Lines
This hunk further confirms the deprecation of old pricing fields (Numeric, payment terms, and quantity) in favor of the new rateCard. Consistency across the API is essential—ensure that all parts of the system adopt this change.


14809-14815: Repeated Deprecation of TaxConfig with Period Definition
Yet another instance where the TaxConfig property is deprecated. While it is consistent, verify that the repeated patterns are intentional and that documentation avoids redundancy for developers integrating with the API.


14831-14849: Usage-Based Price Fields Transition
For usage-based line items, the RateCardUsageBasedPrice and featureKey are now deprecated in favor of a new rateCard that references InvoiceUsageBasedRateCard. It is crucial to ensure that all associated clients and documentation reflect this schema change and that tests confirm the new behavior.


15047-15053: Reiteration of Charges Array for Invoice Lines
The charges property is reintroduced here (similar to hunk 1) for another context. Verify that the reference to InvoiceLineCharge is consistent and that no legacy charge definitions remain active.


15072-15078: Deprecated Tax Configuration and Children Field
The deprecation of TaxConfig along with the children field definition appears once more. Although similar to earlier hunks, confirm that the intended behavior for child lines is maintained and that deprecated fields are properly communicated.


15115-15135: Usage-Based Pricing Fields Consistency Check
This hunk again deprecates RateCardUsageBasedPrice and featureKey while introducing the new rateCard field for usage-based items. Ensure that the descriptions and deprecation notices match those in hunk 16 so that all usage-based pricing components are uniform across the API.


15174-15180: Further Deprecation of TaxConfig in Usage-Based Contexts
The pattern of deprecating the TaxConfig property for usage-based lines continues here. Verify that the same deprecation strategy applies everywhere and that this field is no longer relied upon by clients.


15196-15216: Addition of an ID Field in Usage-Based Pricing Schema
In this hunk, the usage-based pricing schema further deprecates RateCardUsageBasedPrice and featureKey and introduces an id field with a specific pattern. Please ensure the pattern is consistent with other IDs in the API and that the new property is documented accordingly.


15256-15262: Consistent Deprecation for TaxConfig and Period in Usage Context
This hunk deprecates the TaxConfig property yet again in the context of usage-based lines. The consistency is appreciated; just ensure the deprecation rationale is clearly documented in the migration notes.


15278-15338: Comprehensive Update for Usage-Based Line and RateCard Schemas
This extensive hunk covers two important changes:

  1. It deprecates the legacy usage-based pricing fields (RateCardUsageBasedPrice and featureKey) in favor of a new rateCard referencing InvoiceUsageBasedRateCard and introduces a customerId field.
  2. It defines the new InvoiceUsageBasedRateCard schema, including its required properties (featureKey, taxConfig, price, and discounts).

Make sure that:

  • The nullable price is handled correctly (signifying that the feature can be free).
  • The restrictions on discounts (flat fee rate cards only supporting percentage discounts) are well documented.
  • All field descriptions accurately convey the intended business logic and migration path.
api/spec/src/billing/invoices/invoice.tsp (6)

648-648: Confirm references to old property are removed.

You're deprecating this property in favor of rateCard.taxConfig. Please ensure there are no remaining references to the old property throughout the codebase.

Would you like me to generate a script to check for any lingering references?


688-688: Validate rename from subscriptions to subscription.

Double-check everywhere this property is used, to confirm that switching from plural to singular does not introduce any breaking changes.

Do you want me to generate a script to verify all references to the old property?


735-736: Ensure deprecated price field is fully phased out.

You're deprecating the standalone price field in favor of rateCard.price. Verify that no active code paths write or read from price.


741-743: Confirm featureKey references are updated.

Deprecating featureKey in favor of rateCard.featureKey may require a thorough check for any usage in older workflows or migrations.


748-753: Implement partial validation for rateCard.

You labeled rateCard with a TODO to make it required. Introducing optional usage of the new property can cause confusion. Consider validating or warning if rateCard is omitted.


804-806: For clarity, remove or replace uses of perUnitAmount.

Since you're deprecating perUnitAmount in favor of rateCard.perUnitAmount, confirm that any references to perUnitAmount in logic or tests are replaced or removed.

api/spec/src/billing/invoices/discounts.tsp (11)

1-6: Imports and namespace look fine.

No immediate concerns. Good separation of concerns within the Invoices namespace.


7-31: Revisit the necessity of “Generic” in the model’s name.

As previously mentioned in older reviews, consider whether “Generic” is adding clarity or if it can be removed to simplify naming.


33-49: Check for consistent naming with the rest of the codebase.

InvoiceLineGenericAmountCharge effectively extends InvoiceGenericCharge. Confirm all references align well with new or existing naming conventions for invoice lines and amounts.


50-74: Usage-based charge logic is clear.

This structure for applying usage-based discounts or surcharges before taxes is straightforward. Ensure that the usage units (quantities) match the meter’s definition in all references.


76-84: Enum type is adequately defined.

InvoiceLineDiscountType is simple and self-explanatory. No issues.


85-94: Double-check discriminators for InvoiceLineDiscount.

When used in complex unions, be sure that the type is correctly determined at runtime. Also test fallback cases if the discriminator is missing.


95-116: Usage-based discount handles progressive billing well.

Including preLinePeriodQuantity in InvoiceLineDiscountUsage is a good approach for partial or progressive usage. Make sure that the code applying these discounts properly accounts for splitting logic.


117-141: Amount-based discount structure is clear.

The InvoiceLineDiscountAmount model is straightforward. Confirm you have a plan for negative amounts, if they ever occur, or if partial refunds need special handling.


143-151: Charge type enum is limited but sufficient.

You commented out usage. If you plan to add usage-based charges later, keep an eye on potential overlap with existing discount usage-based logic.


152-161: Charge union cleanly references specialized models.

The InvoiceLineCharge union with amount covers typical scenarios. Reintroducing the usage variant is straightforward if needed.


162-175: InvoiceLineChargeAmount model is consistent.

Overall consistency is maintained. The design parallels that of InvoiceLineDiscountAmount, ensuring a cohesive approach to amounts on lines.

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

31-35: Good introduction of default constants.

Defining defaultFlatFeePaymentTerm and defaultFlatFeeQuantity clarifies your defaults. Consider validating scenarios where quantity is zero or uninitialized.


125-135: Validate error messaging on mapping flat fee rate card.

The consolidated call to mapAndValidateFlatFeeRateCardDeprecatedFields simplifies logic. Ensure that the returned error from the mapping function is descriptive enough for troubleshooting.


170-178: Consistent approach for usage-based lines.

Mirroring the flat fee approach helps maintain consistency. The new function call to parse usage-based rate card fields looks good.


263-267: Capture errors from discount mapping for flat-fee lines.

You have robust error handling for discount mapping. This ensures partial failures don’t silently slip through. Nicely done.


344-348: Apply same discount mapping approach to usage-based lines.

This mirrors the flat-fee flow, promoting consistency. Great job keeping the logic parallel.


425-444: mapDiscountsToAPI returns an error for better resilience.

Returning (*[]api.InvoiceLineDiscount, error) is a good design choice. It allows immediate handling of partial failures or unexpected discount states.


445-465: mapDiscountToAPI usage is consistent with new discount models.

Mapping single discounts individually is flexible. Double-check future expansions (e.g., usage-based discount) remain consistent with this approach.


541-549: Usage-based simulation line.

Again, consistent approach. Excellent reusability with the shared validation function.


551-559: Robust parsing of quantity fields.

You handle potential parsing errors gracefully for both Quantity and preLinePeriodQuantity. Keep an eye out for negative usage inputs if not supported.


612-620: Flat fee line updates in replace flow.

Invoking mapAndValidateFlatFeeRateCardDeprecatedFields here ensures uniform deprecation handling. Just confirm you handle partial updates at the calling layer.


656-663: Usage-based line updates in replace flow.

Same consistent approach as flat fee lines. Using the shared function ensures minimal duplication. Good job.

api/client/javascript/src/client/schemas.ts (5)

5015-5044: Well-structured rate card implementation

The new InvoiceFlatFeeRateCard interface looks good. It properly encapsulates the pricing components (price, discounts, quantity) along with tax configuration, following the PR objective of moving line-specific user input to a dedicated rate-card object.


5071-5115: Appropriate structure for line charges

The new charge interfaces (InvoiceLineCharge and InvoiceLineChargeAmount) are well-designed. The type discriminator pattern used here with the type: 'amount' ensures proper type narrowing for API consumers.


5116-5220: Well-designed discount interfaces

The new discount interfaces use a proper union type approach with type discriminators (type: 'amount' or type: 'usage'), allowing clients to distinguish between different discount types. The relationship with rate card discounts via the rateCardDiscount property provides good traceability.


5817-5840: Well-structured usage-based rate card

The InvoiceUsageBasedRateCard interface is well-designed, providing a clear distinction between flat fee and usage-based pricing models.


4857-4859: Consistent deprecation approach

All fields are consistently marked with @deprecated, which is good practice for backward compatibility. This follows the PR objective of deprecating old fields on the rate-card while introducing new structures.

Also applies to: 4867-4870, 4920-4922, 4930-4933, 4988-4990, 4998-5001, 5425-5427, 5435-5438, 5507-5510, 5512-5516, 5679-5682, 5684-5687, 5739-5742, 5744-5747, 5798-5801, 5803-5806

openmeter/billing/httpdriver/deprecations.go (5)

19-28: Confirm whether PaymentTerm must be verified.

The flatFeeRateCardItems struct includes the PaymentTerm field but does not treat it as required in ValidateDeprecatedFields. If it's optional, consider clarifying this within inline doc comments. If it's mandatory for certain use cases, add a corresponding validation check.


96-102: Struct layout looks good.

This struct clearly captures the parsed values for the flat-fee scenario.


178-185: Optional fields not validated.

The usageBasedRateCardItems struct includes TaxConfig, but it's not marked as required. If the legacy usage-based scenario needs a TaxConfig, consider validating this. Otherwise, clarify that it's optional.


187-199: Clear field requirements.

This method enforces price and featureKey but not taxConfig, indicating that taxConfig is optional. If that's intentional, no issue. Otherwise, consider adding a validation check to ensure completeness.


243-248: Struct approach is consistent.

This mirrors the flat-fee parsed struct, helping standardize the usage-based parsing flow.

@turip turip requested a review from GAlexIHU April 3, 2025 16:24
@turip turip enabled auto-merge (squash) April 3, 2025 16:26
@turip turip force-pushed the feat/invoice-discounts-api-v2 branch from 8f70b47 to 097583b Compare April 3, 2025 16:27
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🧹 Nitpick comments (33)
api/spec/src/billing/invoices/discounts.tsp (3)

7-9: Update documentation to remove references to charges

The documentation comment for InvoiceDiscountBase still mentions it represents "a charge or discount", but according to previous feedback, charges have been removed from this implementation. Consider updating to only reference discounts.

/**
- * InvoiceDiscountBase represents a charge or discount that can be applied to a line or the entire invoice.
+ * InvoiceDiscountBase represents a discount that can be applied to a line or the entire invoice.
 */

14-18: Update the ID documentation to be discount-specific

Since the model now only relates to discounts (not charges), update the ID field's documentation for clarity.

/**
- * ID of the charge or discount.
+ * ID of the discount.
 */

97-102: Clarify documentation for amount field

The comment refers to a "percent present" calculation, but there's no percent field in the model. Update the documentation to accurately reflect how the amount is determined.

/**
- * Fixed discount amount to apply (calculated if percent present).
+ * Fixed discount amount to apply.
 */
api/openapi.yaml (10)

13927-13933: Deprecation Flag on TaxConfig (Hunk 1):
A deprecated: true flag has been added for the TaxConfig reference. Consider updating the description’s grammar (e.g. “Tax config specifies the tax configuration…”) for clarity. Also, ensure that the deprecation rationale and migration path are documented in the API release notes.


13956-13962: Typo & Grammar in Subscription Description (Hunk 2):
The description on line 13962 contains a typo (“subscritpions”); it should be “subscriptions”. Also, consider adjusting the phrasing for correct subject–verb agreement (e.g. “Subscriptions are the references…”).


14022-14028: Additional Deprecation on TaxConfig (Hunk 4):
The TaxConfig reference is again marked as deprecated. As with Hunk 1, consider refining the description text (“specify” → “specifies”) and verify that the documentation fully explains the reason behind the deprecation.


14132-14152: Repeated Deprecated Pricing Attributes (Hunk 7):
The use of deprecated: true for pricing, payment, and quantity fields is repetitive. Consider whether these common configurations could be refactored into a shared component to reduce duplication in the spec.


14248-14271: Introduction of InvoiceLineDiscount with Discriminator (Hunk 9):
The new InvoiceLineDiscount schema utilizes a oneOf structure with a discriminator on the type property. This is a strong design choice that clearly separates discount amounts from usage discounts. Verify that the required fields and mappings are fully aligned with the API’s discount processing logic.


14294-14403: Detailed Discount Schemas (Hunk 10):
Both InvoiceLineDiscountAmount and InvoiceLineDiscountUsage are defined in detail with appropriate readOnly and example annotations. The overall structure is clear; however, consider whether common fields across discount schemas can be consolidated to reduce redundancy.


14446-14450: Clarification for InvoiceLineSubscriptionReference (Hunk 11):
The description has been updated to explain the relation to subscriptions. A minor improvement would be to adjust the phrasing (e.g. “...references to the subscriptions…” instead of “subscritpions”).


14712-14732: Repetitive Deprecated Fields for Pricing & Payment (Hunk 13):
The same legacy pricing and payment term fields are marked as deprecated here yet again. Consider abstracting these common patterns into reusable components within the spec to improve maintainability.


14829-14847: Usage-Based Rate Card for Flat Fee Items (Hunk 15):
Here, RateCardUsageBasedPrice is deprecated and a new rateCard reference is introduced for usage-based billing. Ensure that the distinctions between flat fee and usage-based rate cards are clearly documented, particularly regarding how discounts are applied differently.


15089-15095: Reiteration of Subscription Field (Hunk 17):
The subscription field is added again with the same description issue noted earlier. Please address the typo (“subscritpions”) and consider streamlining the description for clarity.

api/spec/src/billing/invoices/invoice.tsp (5)

639-639: Clarify deprecation timeline for taxConfig in InvoiceLineBase
Marking this property as deprecated is a sound approach. However, ensure that there's a clear timeline or plan for removing it to prevent confusion among users.


727-728: Deprecating price in InvoiceUsageBasedLine
Deprecation of price is straightforward, but ensure you communicate the new usage of rateCard.price to avoid confusion or data inconsistency across the codebase.


736-743: Introduce rateCard in InvoiceUsageBasedLine
The shift toward a single rateCard property is sensible. Consider implementing a validation check to ensure the deprecated fields (price, featureKey) do not conflict with rateCard data if both are set.


795-795: Deprecating perUnitAmount in InvoiceFlatFeeLine
Marking this as deprecated is reasonable. Just be sure to finalize the plan to remove or replace these fields in a future major version, so there’s no drift between old and new usage.


811-811: Preserving the old quantity field
Retaining this field alongside rateCard.quantity could introduce confusion if both are set. You might consider an explicit usage policy or validation to prevent mismatched values.

api/openapi.cloud.yaml (15)

13853-13859: Deprecation & Grammar – TaxConfig Field:
The addition of deprecated: true for the TaxConfig field is consistently applied. Consider updating the description to “Tax config specifies the tax configuration for this line” for improved grammar and clarity.


13882-13888: Typo in Subscription Description:
There is a typo in the subscription description ("subscritpions" should be "subscriptions"). Please correct the spelling to ensure clarity.


13948-13954: Consistent Deprecation of TaxConfig:
The TaxConfig field is again marked as deprecated here. Consider revising its description for clarity and correct grammar (e.g., “Tax config specifies the tax configuration for this line”).


13970-13990: Repetition in Deprecated Flat Fee Fields:
This block repeats the deprecation of price, paymentTerm, and quantity fields along with the introduction of the new rateCard field. Ensure consistency across schema definitions and consider consolidating these common elements to adhere to DRY principles.


14036-14042: TaxConfig Deprecation Consistency:
Again, the TaxConfig field is flagged as deprecated. A grammatical improvement in its description is recommended for clarity.


14220-14330: Detailed Discount Schemas for Amount & Usage:
The extended definitions for InvoiceLineDiscountAmount and InvoiceLineDiscountUsage include comprehensive metadata and readOnly flags. A minor wording refinement is recommended—for example, changing “an usage-based discount” to “a usage-based discount.” Please also verify that all fields (e.g., preLinePeriodQuantity) are appropriately documented and intended as read-only.


14616-14622: Reaffirming Deprecation of TaxConfig:
Once more, the TaxConfig field is marked as deprecated. Confirm that this deprecation is intentional and that the description is revised for grammatical clarity.


14638-14659: Repeating Deprecation for Flat Fee Fields:
This block repeats the deprecation of the flat fee fields and adds the new rateCard field as seen earlier. Please check for consistency with previous definitions and consider extracting common elements to minimize duplication if feasible.


14733-14739: TaxConfig Field – Clarity Improvement:
The deprecation flag remains consistent here; however, improving the description’s grammar (e.g., “Tax config specifies…”) would enhance clarity.


14986-14992: TaxConfig & Children Specification:
The deprecation of TaxConfig is applied here, and the children field is defined as readOnly. Consider explicitly specifying the type for children (e.g., an array) if that is intended in the schema.


15015-15021: Subscription Description – Typo Reminder:
This block updates the subscription reference; however, the typo “subscritpions” persists. Please correct it to “subscriptions” to ensure clarity and professionalism.


15029-15049: Consistency in Usage-Based Pricing Definitions:
This block mirrors the changes made in hunk 15 for usage-based pricing. Ensure that the deprecation and the new rateCard field definitions are consistent across all sections. Consolidating similar schema patterns where possible could enhance maintainability.


15088-15094: TaxConfig Deprecation Review:
The TaxConfig field is once again flagged as deprecated; please verify that this repeated pattern is intentional and consider revising the description text for improved clarity.


15170-15176: TaxConfig Field Repetition Notice:
Once again, the TaxConfig field is marked as deprecated with similar wording. Ensure that this repetition is intentional and consider a refactor to reuse common schema segments if possible.


15192-15254: New InvoiceUsageBasedRateCard Schema & Discounts Description:
This extensive block introduces the new InvoiceUsageBasedRateCard schema and updates usage-based pricing fields. A couple of points need attention:
• The discounts description includes “Flat fee rate cards only support percentage discounts,” which might be a copy–paste error if this schema is for usage-based lines. Please verify and update this text if necessary.
• Ensure that properties such as featureKey, taxConfig, and price are clearly defined and aligned with the intended usage-based pricing model.

🛑 Comments failed to post (1)
api/openapi.yaml (1)

15266-15328: ⚠️ Potential issue

New Schema for InvoiceUsageBasedRateCard & Customer-Specific Usage Line (Hunk 22):
This extensive hunk introduces:
• A new customerId field (with an ID pattern) in the usage-based line create model.
• The InvoiceUsageBasedRateCard schema with properties such as featureKey, taxConfig, price, and discounts.

Critical: The description under the discounts property currently states:
  “Flat fee rate cards only support percentage discounts.”
Given that this schema pertains to usage-based rate cards, the discount description should reflect their specific characteristics. Please update the description to accurately describe the discount capabilities for usage-based billing. For example:

-            Flat fee rate cards only support percentage discounts.
+            Usage-based rate cards support discounts calculated based on usage quantities.

This correction will prevent confusion among API consumers and ensure that the schema documentation accurately reflects the functionality.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        discounts:
          type: array
          items:
            $ref: '#/components/schemas/Discount'
          description: |-
            The discounts of the rate card.

            Usage-based rate cards support discounts calculated based on usage quantities.
          title: Discounts

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (1)
api/client/javascript/src/client/schemas.ts (1)

5104-5106: ⚠️ Potential issue

Fix docstring reference to non-existent property.

The documentation for amount states that it's "calculated if percent present", but no percent property exists in this interface.

Apply this diff to fix the docstring:

-       * @description Fixed discount amount to apply (calculated if percent present).
+       * @description Fixed discount amount to apply.
🧹 Nitpick comments (17)
api/openapi.yaml (12)

13927-13933: Deprecate Tax Config in Line Item.
The addition of deprecated: true to the TaxConfig property clarifies that this field is being phased out. Ensure that both documentation and client integrations are updated to reflect this deprecation.


13956-13962: Correct Typo in Subscription Description.
The description for the subscription property contains a typo ("subscritpions" instead of "subscriptions"). Please update the text for clarity.

-          description: Subscription are the references to the subscritpions that this line is related to.
+          description: Subscription references that this line is related to.

13970-13990: Deprecate Legacy Fields and Introduce RateCard.
This hunk marks the legacy fields (price, paymentTerm, and quantity) as deprecated and introduces a new rateCard property referencing InvoiceFlatFeeRateCard. Verify that all clients and documentation clearly delineate the migration to the new rate card model.


14044-14064: Consistent Deprecation for Line Attributes.
This segment deprecates the price, paymentTerm, and quantity properties while defining the new rateCard (InvoiceFlatFeeRateCard). Confirm that similar invoice line definitions use the same deprecation strategy.


14132-14153: Legacy Field Deprecation and RateCard Introduction.
This hunk reiterates deprecating price, paymentTerm, and quantity while adding the new rateCard for invoice lines. Verify that transitions to the new model are clearly documented for consumers.


14159-14202: Add New InvoiceFlatFeeRateCard Schema.
A new schema, InvoiceFlatFeeRateCard, is introduced with fields for tax configuration, price details, discounts, and quantity. Ensure that required fields (like price) and default values (e.g., quantity default of 1) are clearly documented in client references and migration guides.


14294-14404: Detail InvoiceLineDiscountAmount and InvoiceLineDiscountUsage Schemas.
This extensive hunk details properties for both discount amount and usage schemas, including read-only flags and specific field definitions. Make sure that the descriptions (e.g., for preLinePeriodQuantity and usage quantity) are consistent with the business logic and that the discriminator values align with the intended design.


14446-14450: Clarify Subscription Reference Description.
The description for InvoiceLineSubscriptionReference has been updated. For added clarity, consider ending with a period and verifying consistency with other subscription-related descriptions.


14712-14732: Reiterate Deprecation and Transition to RateCard.
The deprecation of legacy fields (price, paymentTerm, and quantity) and the introduction of a new rateCard property in this block should be cross-checked against other similar schema definitions for consistency and clarity.


15060-15066: Deprecate TaxConfig and Introduce Child Lines.
The deprecation of TaxConfig combined with the introduction of the children property indicates a shift toward a more hierarchical invoice structure. Confirm that this design change is reflected in both the API documentation and client SDKs.


15089-15095: Fix Typo in Subscription Field Description (Repeated).
This block again includes the subscription property with the same typo ("subscritpions"). Please make sure this typo is corrected consistently across all occurrences.


15285-15325: Define InvoiceUsageBasedRateCard Schema.
The new InvoiceUsageBasedRateCard schema defines critical properties like featureKey, taxConfig, price, and discounts. Ensure that the required price field and the constraints on other fields (e.g., string length, regex patterns) are clearly documented in the API reference documentation.

api/openapi.cloud.yaml (3)

13882-13888: Typo in Subscription Description
There's a spelling error in the description ("subscritpions" should be "subscriptions"). Correcting this will improve clarity in the API docs.


14085-14131: Definition of InvoiceFlatFeeRateCard
This hunk introduces the InvoiceFlatFeeRateCard object with properties such as taxConfig, price, discounts, and quantity. The structure is well-defined. Consider adding an explicit default value for the quantity property (currently only mentioned in the description) if that is intended behavior.


15110-15130: Usage-Based Pricing Details and ID Formatting
This block continues the deprecation of usage-based legacy fields and introduces an id property with a defined pattern. Ensure that the description for featureKey (now marked deprecated) clearly communicates its role. The new elements should be tested for format consistency.

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

19-28: Struct looks good but consider clarifying deprecation strategy.

This struct effectively groups rateCard logic with its deprecated counterparts. To improve maintainability, consider documenting (in comments or docstrings) the intended migration path away from these deprecated fields.


103-138: Fallback logic is well-structured but verify consistent defaults.

When RateCard is nil, this logic gracefully falls back to deprecated fields. Ensure any default fallback (e.g., payment term at line 134) is documented so that consumers know the default behavior.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f70b47 and 097583b.

📒 Files selected for processing (9)
  • api/client/javascript/src/client/schemas.ts (22 hunks)
  • api/openapi.cloud.yaml (22 hunks)
  • api/openapi.yaml (22 hunks)
  • api/spec/src/billing/invoices/discounts.tsp (1 hunks)
  • api/spec/src/billing/invoices/invoice.tsp (7 hunks)
  • api/spec/src/billing/invoices/main.tsp (1 hunks)
  • openmeter/billing/httpdriver/deprecations.go (1 hunks)
  • openmeter/billing/httpdriver/deprecations_test.go (1 hunks)
  • openmeter/billing/httpdriver/invoiceline.go (21 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • api/spec/src/billing/invoices/main.tsp
  • openmeter/billing/httpdriver/deprecations_test.go
  • api/spec/src/billing/invoices/discounts.tsp
🧰 Additional context used
🧬 Code Definitions (3)
api/client/javascript/src/client/schemas.ts (2)
api/client/go/client.gen.go (7)
  • InvoiceFlatFeeRateCard (2966-2983)
  • InvoiceLine (3001-3003)
  • InvoiceLineAppExternalIds (3006-3012)
  • InvoiceLineDiscount (3015-3017)
  • InvoiceLineDiscountAmount (3020-3050)
  • InvoiceLineDiscountUsage (3058-3090)
  • InvoiceUsageBasedRateCard (3616-3632)
api/api.gen.go (7)
  • InvoiceFlatFeeRateCard (3226-3243)
  • InvoiceLine (3261-3263)
  • InvoiceLineAppExternalIds (3266-3272)
  • InvoiceLineDiscount (3275-3277)
  • InvoiceLineDiscountAmount (3280-3310)
  • InvoiceLineDiscountUsage (3318-3350)
  • InvoiceUsageBasedRateCard (3876-3892)
openmeter/billing/httpdriver/deprecations.go (3)
api/client/javascript/src/client/schemas.ts (5)
  • RateCard (9195-9195)
  • InvoiceFlatFeeRateCard (9031-9032)
  • TaxConfig (9262-9262)
  • InvoiceUsageBasedRateCard (9083-9084)
  • RateCardUsageBasedPrice (9205-9206)
api/api.gen.go (6)
  • RateCard (4908-4910)
  • InvoiceFlatFeeRateCard (3226-3243)
  • TaxConfig (5702-5711)
  • Price (4867-4869)
  • InvoiceUsageBasedRateCard (3876-3892)
  • RateCardUsageBasedPrice (5062-5064)
api/client/go/client.gen.go (5)
  • RateCard (4586-4588)
  • InvoiceFlatFeeRateCard (2966-2983)
  • TaxConfig (5348-5357)
  • InvoiceUsageBasedRateCard (3616-3632)
  • RateCardUsageBasedPrice (4737-4739)
openmeter/billing/httpdriver/invoiceline.go (4)
openmeter/productcatalog/price.go (2)
  • InAdvancePaymentTerm (20-20)
  • Price (80-87)
api/client/go/client.gen.go (6)
  • RateCard (4586-4588)
  • TaxConfig (5348-5357)
  • PricePaymentTerm (4554-4554)
  • InvoiceFlatFeeRateCard (2966-2983)
  • FlatPriceWithPaymentTerm (2473-2483)
  • InvoiceUsageBasedRateCard (3616-3632)
api/client/javascript/src/client/schemas.ts (6)
  • RateCard (9195-9195)
  • TaxConfig (9262-9262)
  • PricePaymentTerm (9192-9192)
  • InvoiceFlatFeeRateCard (9031-9032)
  • FlatPriceWithPaymentTerm (8992-8993)
  • InvoiceUsageBasedRateCard (9083-9084)
openmeter/billing/invoiceline.go (8)
  • FlatFeeLine (251-258)
  • Price (682-682)
  • UsageBasedLine (684-693)
  • LineDiscounts (743-745)
  • LineDiscount (726-736)
  • FlatFeeCategory (235-235)
  • FlatFeeCategory (244-249)
  • Line (271-284)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Developer environment
  • GitHub Check: Analyze (go)
🔇 Additional comments (60)
api/openapi.yaml (9)

14022-14028: Deprecate Tax Config in This Block.
Once again, TaxConfig is marked as deprecated, and the period field is introduced. Ensure consistency in deprecation messaging across all similar schema blocks.


14110-14116: Reaffirm Deprecation of TaxConfig.
Here the TaxConfig property is again flagged as deprecated. It is important to ensure that all references to TaxConfig in the API are uniformly updated and communicated.


14690-14696: Consistent Deprecation of TaxConfig.
This block once again deprecates the TaxConfig field. Uniform communication across the API will help ensure clear migration paths.


14807-14813: Deprecate TaxConfig Consistently.
Tax configuration is again marked as deprecated here. Verify that similar warnings are present in all instances where TaxConfig is used.


15162-15168: Uniformly Deprecate TaxConfig.
The deprecation of TaxConfig is consistently applied here. No additional action is needed, but ensure that the migration guidelines are updated accordingly.


15244-15250: Deprecate TaxConfig in Final Invoice Line Section.
Again, TaxConfig is marked as deprecated. This repetition reinforces the migration path; ensure all instances across the spec are updated.


15326-15328: InvoiceWorkflowInvoicingSettingsReplaceUpdate Stub.
The schema InvoiceWorkflowInvoicingSettingsReplaceUpdate begins here. Verify that its properties and intended use align with the new API design for workflow in invoicing, even though the diff does not show its complete implementation.


15266-15284:

Details

❓ Verification inconclusive

Update and Deprecate Usage-Based Pricing Fields.
This block deprecates RateCardUsageBasedPrice and featureKey while adding the new rateCard referencing InvoiceUsageBasedRateCard and introducing a validated customerId. The changes here form a comprehensive update for usage-based line creation. Verify that these modifications are mirrored in all related API endpoints and client implementations.


Attention: Ensure Consistent Update of Usage-Based Pricing Fields

Please confirm that the deprecation of RateCardUsageBasedPrice and featureKey, along with the new addition of rateCard (referencing InvoiceUsageBasedRateCard) and the validated customerId, are consistently applied across all API endpoints and client implementations. Double-check any related endpoints or client-side schema references to ensure the comprehensive update is mirrored throughout the codebase.


14248-14261:

Details

❓ Verification inconclusive

Introduce InvoiceLineDiscount with Discriminator.
The schema InvoiceLineDiscount is redefined as a union (using oneOf) with a discriminator on the type property. This is a robust way to support multiple discount types (amount and usage). Confirm that consumers of the API can correctly interpret the discriminator mapping.


InvoiceLineDiscount Schema Update – Verify API Consumer Integration

The schema in api/openapi.yaml now defines InvoiceLineDiscount as a oneOf union with a discriminator on the type property that distinguishes between the discount types (InvoiceLineDiscountAmount for "amount" and InvoiceLineDiscountUsage for "usage"). This refactor is implemented as expected, offering a robust mechanism for handling multiple discount types.

Please ensure that all consumers of the API can correctly interpret the discriminator mapping defined here. In particular, verify that your client integrations handle the following mapping correctly:

  • amount → InvoiceLineDiscountAmount

  • usage → InvoiceLineDiscountUsage

  • Location: api/openapi.yaml, lines 14248–14261


🏁 Script executed:

#!/bin/bash
# Display the InvoiceLineDiscount snippet to confirm the presence of the discriminator mapping.
rg "InvoiceLineDiscount:" -A 15 api/openapi.yaml

Length of output: 758


Verify Discriminator Integration in InvoiceLineDiscount Schema

The updated schema in api/openapi.yaml now correctly defines InvoiceLineDiscount using a union (oneOf) with a discriminator on the type property to distinguish between InvoiceLineDiscountAmount and InvoiceLineDiscountUsage. Please ensure that all API consumers properly handle the following mapping:

  • amount → InvoiceLineDiscountAmount
  • usage → InvoiceLineDiscountUsage

Confirmed location: api/openapi.yaml, lines 14248–14261

api/spec/src/billing/invoices/invoice.tsp (8)

639-641: Proper deprecation of taxConfig property

The code correctly deprecates the taxConfig property and directs users to use rateCard.taxConfig instead, aligning with the PR's goal of moving line-specific fields to the rate-card object.


679-679: Field renamed from plural to singular

The property has been renamed from subscriptions to subscription, reflecting a change from potentially multiple subscriptions to a single subscription reference. This aligns with the PR objective to restructure the API model.


700-710: New InvoiceUsageBasedRateCard model properly structured

The new model effectively encapsulates the rate card for usage-based lines, containing essential properties like discounts, taxConfig, featureKey, and price. This implementation aligns with the PR objective to move line-specific user input to a dedicated rate-card object.

Note the TODO comment indicating featureKey and price should be made required after deprecation. Consider adding a ticket to track this future change.


726-735: Appropriate deprecation of usage-based line properties

The price and featureKey properties are correctly deprecated with clear migration guidance, directing users to the corresponding properties on the new rateCard object.


736-744: New rateCard property added to InvoiceUsageBasedLine

The addition of the rateCard property successfully implements the PR objective of restructuring the rate-card object within the product catalog. Making it optional initially allows for a non-breaking transition.

Note the TODO comment on line 742 regarding making the rateCard required after deprecation is complete. Consider creating a ticket to track this future change.


760-778: New InvoiceFlatFeeRateCard model properly implemented

The new model correctly encapsulates the rate card for flat fee lines, with appropriate properties for discounts, taxConfig, price, and quantity. This supports the PR's goal of restructuring the rate-card object.

Similar to the usage-based rate card, there's a TODO comment about making price required later. Consider tracking this in the same ticket as the other TODOs.


795-811: Appropriate deprecation of flat fee line properties

The perUnitAmount, paymentTerm, and quantity properties are properly deprecated with clear directives to use their equivalents in the new rateCard object. This consistent approach will help API consumers understand the migration path.


813-819: New rateCard property added to InvoiceFlatFeeLine

The addition of the rateCard property to the InvoiceFlatFeeLine model completes the implementation of the rate card restructuring for both major line types. Making it optional initially ensures backward compatibility.

As with the other rate card properties, there's a TODO comment about making this required after deprecation. Ensure this is tracked for future implementation.

api/openapi.cloud.yaml (19)

13853-13859: Deprecation of TaxConfig Property
The addition of deprecated: true for the TaxConfig reference appears to be intentional as part of the API restructuring. Please ensure that this deprecation is clearly documented and communicated to clients so that they know to migrate to the new configurations if applicable.


13896-13916: Transition from Legacy Fields to rateCard
Deprecated fields, such as price, paymentTerm, and quantity, are being replaced by a new rateCard reference (pointing to InvoiceFlatFeeRateCard). This change aligns with the migration strategy. Make sure that the documentation (and any client code) reflects these updates to avoid confusion during integration.


13948-13953: Consistent Deprecation of TaxConfig
The TaxConfig reference is again flagged as deprecated in this block. Ensure that this deprecation is applied uniformly throughout the schema and that any fallback behavior is well documented.


13970-13990: Repetition of Deprecation & Introduction of rateCard
This hunk mirrors the earlier pattern of deprecating price, paymentTerm, and quantity while introducing the rateCard property. The change is consistent; just double-check that the deprecation schedule and migration guides cover all legacy fields accordingly.


14036-14042: Uniform Deprecation of TaxConfig
The deprecation of the TaxConfig reference is repeated here. Confirm that the update plan for clients includes all areas where TaxConfig is used.


14058-14079: Consistent Schema Update for Pricing Elements
Once again, fields like price, paymentTerm, and quantity are deprecated and replaced by the new rateCard construct. The changes are clear and consistent; ensure that API consumers are informed about the new pattern.


14174-14197: New InvoiceLineDiscount Schema & Variants
The new InvoiceLineDiscount schema using a oneOf discriminator (with mappings for amount and usage) is set up correctly. Please verify that the discriminator property (type) covers all intended discount types and that client libraries are updated appropriately.


14220-14330: Detailed Discount Schemas Defined
The definitions for InvoiceLineDiscountAmount and InvoiceLineDiscountUsage are comprehensive. They include proper type definitions, read-only flags, and examples. Ensure that the enum values (e.g., "amount" in one and "usage" in the other) match what clients expect and are reflected in the API documentation.


14372-14378: Clarification on Subscription Reference and Tax Behavior
The description for InvoiceLineSubscriptionReference is updated here. For the subsequent InvoiceLineTaxBehavior, please confirm that its enum values are defined elsewhere in the specification and that its purpose is clearly documented.


14616-14622: Repeated Deprecation of TaxConfig Validated
Again, the TaxConfig reference is marked as deprecated. The consistency is good; just ensure that any legacy behaviors are fully replaced in the migration guide.


14638-14659: Legacy Fields Deprecated in This Block
The deprecation of fields like Numeric (for price and quantity) and PricePaymentTerm (including the default for paymentTerm) is handled as before. The integration of the new rateCard property should be referenced in the migration documentation.


14733-14739: TaxConfig Deprecation Consistency Check
This hunk continues to deprecate the TaxConfig reference. It is recommended to verify that all instances of TaxConfig deprecation follow the same pattern in both behavior and documentation.


14755-14775: Transition for Usage-Based Pricing Fields
Here, RateCardUsageBasedPrice and featureKey are deprecated in favor of a new rateCard that references InvoiceUsageBasedRateCard. This follows the intended API update for usage-based items. Ensure that any client or migration guides reference this change clearly.


14986-14992: Deprecation and Preservation of Child Elements
The deprecation of TaxConfig is paired with the preservation of the children property. Verify that child elements’ behavior remains correct after the deprecation.


15015-15021: Duplicate Subscription Block with Persistent Typo
This block repeats the subscription property definition seen earlier. The description still contains "subscritpions" instead of "subscriptions." This duplication of both the field and the typo should be corrected to ensure consistency across the schema.


15029-15049: Usage-Based Pricing Block Consistency
This hunk mirrors the earlier usage-based pricing changes (deprecating RateCardUsageBasedPrice and featureKey, replacing them with InvoiceUsageBasedRateCard). It appears consistent with prior changes. Just verify that all related clients are updated accordingly.


15088-15094: TaxConfig and Period Properties for Usage-Based Items
The deprecation of TaxConfig (with the addition of a period reference) in this block is consistent. No further issues are noted here.


15170-15176: Consistent Deprecation of TaxConfig (Repeated)
This hunk further confirms the deprecation of TaxConfig. It is consistent with previous implementations.


15192-15253: 🛠️ Refactor suggestion

⚠️ Potential issue

Critical: Duplicate Description Keys in Usage-Based Schema Block
In this extensive hunk, there appears to be a duplication of the description key:

  • At line 15214, a description defines InvoiceUsageBasedLineCreateWithCustomer and
  • Immediately at line 15215, another description for InvoiceUsageBasedRateCard is provided.

YAML mappings do not support duplicate keys, so the latter will override the former. This is likely an error in schema documentation. It is recommended to remove or merge these duplicate description entries so that each schema has a single, clear description. For example:

-      description: InvoiceUsageBasedLineCreateWithCustomer represents the create model for an invoice line that is sold to the customer based on usage.
-      description: InvoiceUsageBasedRateCard represents the rate card (intent) for an usage-based line.
+      description: |
+        InvoiceUsageBasedLineCreateWithCustomer represents the create model for an invoice line sold to the customer based on usage.

Then, ensure that the InvoiceUsageBasedRateCard schema has its own dedicated description within its block (which starts at line 15216).

Likely an incorrect or invalid review comment.

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

31-34: Good addition of constants for default values.

Adding constants for default flat fee payment term and quantity improves maintainability by centralizing these values, making them easier to update in the future.


125-135: Improved field mapping with centralized validation.

The refactoring to use mapAndValidateFlatFeeRateCardDeprecatedFields centralizes the mapping and validation logic, which is consistent with the PR objective of restructuring rate-card handling. This allows for better handling of both old and new fields during the transition period.


169-178: Consistent approach for usage-based lines.

This change applies the same refactoring pattern to usage-based lines, maintaining consistency in the codebase and ensuring both types of invoice lines are handled similarly during the rate-card restructuring.


263-267: Enhanced error handling for discount mapping.

The updated code now properly handles errors from discount mapping operations, improving robustness. This change ensures that any issues during discount mapping will be properly reported up the call stack.


300-309: New RateCard field implementation follows the design intent.

The addition of the RateCard field to flat fee lines implements the restructuring plan described in the PR objectives. This populates both old and new fields in Get/List responses, providing a smooth transition path.


344-348: Improved error handling consistency.

Similar to the flat fee line changes, this update enhances error handling for the usage-based line discount mapping, maintaining a consistent approach throughout the codebase.


382-387: RateCard field for usage-based lines.

Adding the RateCard field to usage-based lines follows the same pattern as flat fee lines, ensuring consistency across different line types. This implements the API restructuring plan outlined in the PR objectives.


425-443: Updated discount mapping with error handling.

The function now returns both the mapped discounts and any error that occurred during mapping, allowing callers to properly handle failures. The function correctly handles absent discounts by returning nil.


445-464: Improved discount mapping API.

The updated function signature returns both the mapped discount and any error, consistent with the changes to mapDiscountsToAPI. The function directly returns the error from FromInvoiceLineDiscountAmount, which simplifies error handling.


502-549: Consistent pattern in simulation functions.

The changes to the simulation functions follow the same pattern established in the main mapping functions, ensuring consistency across the codebase. These changes support the transition from old fields to the new rate-card structure.


612-726: Consistent handling in update functions.

The replacement of direct field mapping with helper functions in the update logic ensures a consistent approach across the entire codebase. This is crucial for maintaining backward compatibility during the transition period while enforcing validation rules for the new API structure.

api/client/javascript/src/client/schemas.ts (7)

5066-5069: Well-structured discount type implementation.

The use of a union type for InvoiceLineDiscount provides a clean approach to represent different discount types (amount-based vs usage-based), aligning with the PR objective of restructuring the discount system.


4853-4865: Consistent deprecation approach for fields moved to rate cards.

The PR properly marks all fields being moved to rate card objects as deprecated, which maintains backward compatibility while encouraging migration to the new structure. This approach allows for a gradual transition.

Also applies to: 4915-4928, 4983-4996, 5455-5465, 5624-5632, 5683-5692, 5742-5751


5010-5039: Clear separation of rate card and line item concerns.

The new InvoiceFlatFeeRateCard interface effectively separates the intent (rate card configuration) from the actual values (line items), as mentioned in the PR objectives. The structure is well-documented and includes all necessary properties.


5762-5785: Comprehensive implementation of usage-based rate card.

The InvoiceUsageBasedRateCard interface properly captures all the necessary properties for usage-based billing scenarios and provides clear documentation. The inclusion of discounts as an array of Discount objects allows for flexible discount application.


5117-5170: Well-defined usage-based discount structure.

The InvoiceLineDiscountUsage interface provides a complete implementation for usage-based discounts, including properties for tracking quantities across billing periods. This aligns with the PR objective of including usage discounts as a non-breaking change.


4866-4867: Consistent addition of rate card references.

The addition of the rateCard property across multiple interfaces ensures a consistent approach to accessing rate card information, which simplifies API usage and improves maintainability.

Also applies to: 4929-4930, 4997-4998, 5466-5469, 5633-5636, 5693-5696, 5752-5755


4844-4844: Consistent subscription reference implementation.

The subscription property has been updated to use the new InvoiceLineSubscriptionReference type, ensuring consistency across the codebase.

Also applies to: 5617-5617

openmeter/billing/httpdriver/deprecations.go (6)

29-41: Validation ensures mandatory deprecated fields are present.

Your checks for PerUnitAmount and Quantity being non-nil correctly enforce the mandatory requirement for those fields. The simple errors.Join usage is concise and clean.


43-94: Consider numeric comparison for amounts ().

As highlighted in your past review comment, comparing rateCard.Price.Amount to *i.PerUnitAmount (line 60) might produce false mismatches if the strings differ by formatting (e.g., "10.00" vs. "10"). A more robust approach is to parse both strings into decimals and compare them numerically.


178-185: Usage-based struct is well-defined.

Defining usage-based items separately helps keep flat-fee and usage-based logic distinct. This improves clarity of domain modeling. No immediate issues noted here.


187-199: Consistent validation approach for usage-based deprecated fields.

Similar to the flat fee approach, you explicitly require Price and FeatureKey. This consistency is good.


249-293: Well-rounded mapping for usage-based rate cards.

This final fallback ensures usage-based invoice lines rely on the new RateCard if available or otherwise gracefully consume deprecated fields. The errors wrap remains coherent.


201-241:

Details

✅ Verification successful

Ensure numeric parity of usage-based prices.

Your approach of comparing derived prices in ValidateRateCard() is solid. However, confirm that all planhttpdriver.AsPrice usage returns consistent decimal values—especially if dealing with fractional usage rates.


🏁 Script executed:

#!/bin/bash
# Confirm usage-based price calculations call planhttpdriver.AsPrice consistently
rg -A 3 'AsPrice'

Length of output: 3123


Numeric Parity Verification for AsPrice Conversions

I confirmed via our search that every call to planhttpdriver.AsPrice—across billing, product catalog, and test files—applies a consistent conversion strategy. In your ValidateRateCard() method, comparing the derived prices using the .Equal() method appears robust, and the handling of potential fractional values aligns with how it's done elsewhere. No further changes are necessary.

Comment on lines 14829 to 14847
allOf:
- $ref: '#/components/schemas/RateCardUsageBasedPrice'
description: Price of the usage-based item being sold.
deprecated: true
featureKey:
type: string
minLength: 1
maxLength: 64
pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$
description: The feature that the usage is based on.
deprecated: true
rateCard:
allOf:
- $ref: '#/components/schemas/InvoiceUsageBasedRateCard'
description: |-
The rate card that is used for this line.

The rate card captures the intent of the price and discounts for the usage-based item.
quantity:
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Transition to InvoiceUsageBasedRateCard for Usage-Based Items.
This hunk deprecates RateCardUsageBasedPrice and featureKey while introducing a reference to InvoiceUsageBasedRateCard for usage-based pricing. Ensure that the migration strategy for usage-based elements is clearly documented and that legacy clients are notified of these changes.

Comment on lines 15103 to 15121
allOf:
- $ref: '#/components/schemas/RateCardUsageBasedPrice'
description: Price of the usage-based item being sold.
deprecated: true
featureKey:
type: string
minLength: 1
maxLength: 64
pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$
description: The feature that the usage is based on.
deprecated: true
rateCard:
allOf:
- $ref: '#/components/schemas/InvoiceUsageBasedRateCard'
description: |-
The rate card that is used for this line.

The rate card captures the intent of the price and discounts for the usage-based item.
quantity:
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update Usage-Based RateCard Schema.
This segment deprecates the legacy usage-based price schema and the featureKey in favor of a new rateCard property referencing InvoiceUsageBasedRateCard. Verify that the updated schema correctly reflects the intended pricing and discount logic for usage-based items.

Comment on lines 15184 to 15204
allOf:
- $ref: '#/components/schemas/RateCardUsageBasedPrice'
description: Price of the usage-based item being sold.
deprecated: true
featureKey:
type: string
minLength: 1
maxLength: 64
pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$
description: The feature that the usage is based on.
deprecated: true
rateCard:
allOf:
- $ref: '#/components/schemas/InvoiceUsageBasedRateCard'
description: |-
The rate card that is used for this line.

The rate card captures the intent of the price and discounts for the usage-based item.
id:
type: string
pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refine Usage-Based Schema with ID Specification.
This hunk continues the pattern for usage-based pricing by deprecating legacy fields and introducing a new rateCard property. The addition of the id field with a specific regex validation is a good detail—confirm that this pattern fits all expected IDs.

@turip turip merged commit 3bece3e into main Apr 3, 2025
29 checks passed
@turip turip deleted the feat/invoice-discounts-api-v2 branch April 3, 2025 16:40
@coderabbitai coderabbitai bot mentioned this pull request Oct 16, 2025
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