Skip to content

fix: phase iterator in advance/in arreas - #2860

Merged
turip merged 1 commit into
mainfrom
fix/in-advance-in-arreas-phase-iterator
May 21, 2025
Merged

turip merged 1 commit into
mainfrom
fix/in-advance-in-arreas-phase-iterator

Conversation

@turip

@turip turip commented May 20, 2025 •

Copy link
Copy Markdown
Member

Overview

If in advance and in arreas items are mixed on an invoice, the current phase iterator does not generate the in advance item for the next phase.

This results in the in advance and in arreas items to be included in seperate invoices.

This patch fixes this by considering the invoice_at property of the soon to be generated lines.

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of billing periods and invoice dates to ensure extra billing periods are generated when the end time meets or exceeds invoice dates.
  • Tests
    • Enhanced and extended test cases to cover scenarios with extra billing periods, mixed in-advance and in-arrears billing rules, and updated expected invoice schedules.
  • Refactor
    • Unified invoice date calculation and improved data handling for generated billing periods.

@coderabbitai

coderabbitai Bot commented May 20, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough
## Walkthrough

The changes centralize invoice date calculation logic for subscription billing periods, introduce a struct to encapsulate generated period metadata, and update iteration logic to account for invoice dates in termination checks. Corresponding test cases are adjusted and extended to reflect the new logic, including additional billing periods and scenarios involving mixed in-advance and in-arrears billing rules.

## Changes

| Files/Paths                                                                 | Change Summary                                                                                                                                                                                                                   |
|-----------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| openmeter/billing/worker/subscription/phaseiterator.go                      | Centralized invoice date calculation with a new `getInvoiceAt` method; introduced `generatedVersionPeriodItem` struct; updated period generation and iteration logic to consider invoice dates; refined method signatures.         |
| openmeter/billing/worker/subscription/phaseiterator_test.go                 | Renamed test cases for clarity; extended existing tests with additional billing periods triggered by invoice dates; added new tests covering mixed in-advance and in-arrears billing rules for aligned and unaligned subscriptions. |
| openmeter/billing/worker/subscription/sync_test.go                          | Extended expected billing period ranges and invoice timestamps by one unit in multiple assertions across various in-advance and in-arrears billing scenarios, including aligned subscriptions and prorated amounts.               |

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

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 30th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a2de83e and 258ce09.

📒 Files selected for processing (3)
  • openmeter/billing/worker/subscription/phaseiterator.go (8 hunks)
  • openmeter/billing/worker/subscription/phaseiterator_test.go (7 hunks)
  • openmeter/billing/worker/subscription/sync_test.go (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • openmeter/billing/worker/subscription/sync_test.go
  • openmeter/billing/worker/subscription/phaseiterator.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
openmeter/billing/worker/subscription/phaseiterator_test.go (3)
openmeter/ent/db/subscriptionitem/where.go (1)
  • Key (105-107)
api/api.gen.go (2)
  • FlatPriceType (3171-3171)
  • UnitPriceType (6925-6925)
api/client/go/client.gen.go (2)
  • FlatPriceType (2876-2876)
  • UnitPriceType (6348-6348)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Test
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (7)
openmeter/billing/worker/subscription/phaseiterator_test.go (7)

72-73: Improved test case naming for clarity.

The test case names now explicitly indicate whether they're testing aligned or unaligned scenarios, making the test suite more readable and easier to understand.

Also applies to: 78-79


311-337: Good extension of test coverage for unaligned flat-fee recurring items.

The test case now includes an additional billing period that was previously missing. The added comment on line 332 clearly explains that this period is included because the end time is >= invoice_at only at this point, which directly addresses the issue mentioned in the PR description.


391-395: Extended test coverage for flat-fee recurring edited items.

Added an additional billing period to verify that the phase iterator correctly generates subsequent periods after an item has been edited. This helps ensure the iterator continues to work properly even after subscription changes.


434-439: Added test coverage for aligned items with explicit comment.

The added comment clearly explains that the extra in-advance item is included because of the iterator's behavior. This period tests that the phase iterator continues to generate periods for aligned items correctly.


492-497: Extended test coverage for aligned one-time with cadence.

The additional test period verifies that the phase iterator correctly generates subsequent periods even when there's a mix of one-time and recurring items. The comment on line 493 explains the inclusion criteria clearly.


555-588: Added test case for aligned subscriptions with mixed billing rules.

This new test case directly addresses the issue mentioned in the PR objectives - handling invoices with both in-advance and in-arrears items. It verifies that:

  1. Multiple billing periods are generated for in-advance items (both current and next month)
  2. A single period is generated for in-arrears items

This tests that in-advance items for the next phase are correctly generated when mixed with in-arrears items, fixing the described issue.


589-621: Added test case for unaligned subscriptions with mixed billing rules.

This complementary test case verifies the same behavior as the aligned test but for unaligned subscriptions. Having both test cases ensures that the fix works properly regardless of the alignment setting.

Both test cases demonstrate that in-advance and in-arrears items generate the expected periods and would be included in the same invoice, resolving the issue described in the PR.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@turip
turip force-pushed the fix/in-advance-in-arreas-phase-iterator branch 2 times, most recently from 215b21e to ff00f90 Compare May 21, 2025 11:59
@turip turip added release-note/bug-fix Release note: Bug Fixes area/billing labels May 21, 2025
@turip
turip force-pushed the fix/in-advance-in-arreas-phase-iterator branch from ff00f90 to a2de83e Compare May 21, 2025 12:01
@turip
turip marked this pull request as ready for review May 21, 2025 12:01
@turip
turip requested a review from a team as a code owner May 21, 2025 12:01

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
openmeter/billing/worker/subscription/phaseiterator.go (1)

625-640: Good abstraction – consider promoting to a utility package

getInvoiceAt cleanly encapsulates invoice-date rules and eliminates scattered conditionals elsewhere (once the duplication above is removed).
If other parts of the billing pipeline need the same logic, consider moving this helper to a shared util to prevent future drift.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b65470a and a2de83e.

📒 Files selected for processing (3)
  • openmeter/billing/worker/subscription/phaseiterator.go (8 hunks)
  • openmeter/billing/worker/subscription/phaseiterator_test.go (7 hunks)
  • openmeter/billing/worker/subscription/sync_test.go (7 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
openmeter/billing/worker/subscription/phaseiterator_test.go (3)
openmeter/ent/db/subscriptionitem/where.go (1)
  • Key (105-107)
api/api.gen.go (2)
  • FlatPriceType (3171-3171)
  • UnitPriceType (6925-6925)
api/client/go/client.gen.go (2)
  • FlatPriceType (2876-2876)
  • UnitPriceType (6348-6348)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: CI
  • GitHub Check: E2E
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Analyze (go)
🔇 Additional comments (19)
openmeter/billing/worker/subscription/phaseiterator_test.go (9)

72-73: Improved test case naming for clarity.

The test case names have been clarified to explicitly indicate they're testing unaligned scenarios, which helps improve test readability and understanding of what each test is validating.


78-79: Improved test case naming for clarity.

Renamed "empty-aligned" to "aligned empty" for better consistency in naming conventions.


311-312: Improved test name for clarity of testing context.

Renamed "flat-fee recurring" to "unaligned flat-fee recurring" to explicitly identify the test's context, making it clearer what scenario is being tested.


331-337: Added extra test period for correct invoice date handling.

This addition properly tests the fix for the phase iterator to account for invoice dates in termination checks. The extra period represents the case where the in-advance item for the next phase should be included because the end date is greater than or equal to the invoice date.


391-396: Added additional test period for "flat-fee recurring, edited" test.

This change extends the test to include an additional billing period, correctly validating that the phase iterator continues iteration when the invoice date is considered, even for edited items.


434-440: Added extra test period for aligned in-advance billing.

This change adds an important test case to verify that aligned subscriptions correctly generate the in-advance item for the next phase when the invoice date is considered in the termination check.


492-498: Added test period for aligned one-time with cadence.

The additional test period correctly validates that an extra billing period is generated based on the invoice date logic, ensuring that the phase iterator continues until both the period start and invoice date exceed the iteration end.


555-588: Added critical test case for mixed in-advance and in-arrears billing.

This new test case directly addresses the PR objective by testing the scenario where a subscription has both in-advance and in-arrears items in an aligned context. It verifies that the phase iterator correctly generates two periods for the in-advance item (current and next) and one period for the in-arrears item.


589-621: Added complementary test for unaligned mixed billing items.

This test complements the previous aligned test case by validating the same functionality in an unaligned context. Together, these two tests comprehensively cover the fix for the issue where in-advance and in-arrears items were being incorrectly separated into different invoices.

openmeter/billing/worker/subscription/sync_test.go (9)

703-704: Updated test expectations for additional billing period.

The PeriodMax value has been increased from 4 to 5 to account for the additional billing period that should be generated when invoice dates are considered in the termination check.


708-710: Updated period and invoice timestamp expectations.

Extended the expected periods and invoice timestamps arrays with an additional entry to reflect the corrected phase iterator logic that now continues iteration until both the period start and invoice date exceed the iteration end.


799-800: Updated PeriodMax for gathering sync test expectations.

Increased PeriodMax to 5 to correctly account for the extended period generation in the phase iterator, ensuring the test validates the fixed behavior where in-advance items are properly included.


804-806: Updated period and invoice timestamp arrays for non-billable amount test.

Extended the expected periods and invoice timestamps arrays to reflect the corrected phase iterator behavior, validating that in-advance items are properly generated for the next billing cycle.


992-993: Updated PeriodMax for prorated test expectations.

Increased the PeriodMax value from 3 to 4 to account for the extended period generation in the phase iterator when handling prorated billing scenarios.


997-999: Added expected periods and invoice timestamps for prorated test.

Extended the expected test data to validate that the phase iterator correctly handles prorated billing with the fixed iteration logic.


1103-1109: Updated test expectations for draft invoice prorated test.

Increased the PeriodMax value and extended the expected periods and invoice timestamps arrays to account for the additional billing period, ensuring the corrected phase iterator behavior is properly validated for draft invoices.


1245-1252: Updated test expectations for issued invoice prorating test.

Increased the PeriodMax value and extended the expected periods and invoice timestamps arrays to account for the fixed phase iterator behavior, ensuring that issued invoices with prorated items are correctly handled.


1523-1533: Updated expected periods for aligned subscription invoicing test.

Extended the expected period and invoice timestamp arrays to include an additional weekly period and invoice date for in-advance items, properly validating the fix for the phase iterator when handling aligned subscriptions.

openmeter/billing/worker/subscription/phaseiterator.go (1)

273-276: Iteration-end guard may still over-generate for mixed in-advance / in-arrears lines

The loop exits only when both at (period end) and invoiceAt are not before iterationEnd.
For in-advance items invoiceAt == period.From, so the loop will keep running until period.From ≥ iterationEnd.
That behaviour matches the comment at the top of the file, but please double-check that downstream code indeed needs both dates to pass the boundary – otherwise you may continue generating extra periods for usage-based items whose invoice is already due.

No change suggested; just confirm the requirement.

If in advance and in arreas items are mixed on an invoice, the
current phase iterator does not generate the in advance item
for the next phase.

This results in the in advance and in arreas items to be included in
seperate invoices.

This patch fixes this by considering the invoice_at property of the
soon to be generated lines.
@turip
turip force-pushed the fix/in-advance-in-arreas-phase-iterator branch from a2de83e to 258ce09 Compare May 21, 2025 12:35
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