Skip to content

Conversation

@turip
Copy link
Member

@turip turip commented Jul 9, 2025

Overview

Add correctPeriodStartForUpcomingLines into billing subscription sync, that corrects the period start for the upcoming lines, it will adjust the period start for the lines.

The adjustment only happens if the line is subscription managed and has billing.subscription.sync.ignore annotation. This esentially allows for reanchoring if the period calculation changes.

Summary by CodeRabbit

  • New Features

    • Improved handling of service period alignment for upcoming subscription invoice lines, ensuring new periods start exactly at the end of previous periods when applicable.
    • Enhanced metadata tracking for subscription billing items with additional phase key, period index, and item version details.
  • Bug Fixes

    • Adjusted synchronization logic to prevent duplicate upcoming lines and ensure accurate period correction after manual updates.
  • Tests

    • Added a new test to verify correct adjustment of invoice line periods following changes to period calculation algorithms.

@turip turip requested a review from a team as a code owner July 9, 2025 12:05
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 9, 2025

📝 Walkthrough

Walkthrough

The changes introduce new methods and fields to support more precise handling and correction of service periods for subscription invoice lines. Logic is added to adjust upcoming invoice line periods based on previous lines when period calculation algorithms change. Related data structures and tests are updated to reflect and verify this behavior.

Changes

File(s) Change Summary
openmeter/billing/invoicelinesplitgroup.go Added ServicePeriod() method to LineOrHierarchy for unified access to the service period, handling both Line and SplitLineHierarchy cases.
openmeter/billing/worker/subscription/phaseiterator.go Extended subscriptionItemWithPeriods struct with PhaseKey, PeriodIndex, and ItemVersion fields; updated related methods to populate these fields.
openmeter/billing/worker/subscription/sync.go Added methods to correct the start of upcoming service periods based on previous lines, with eligibility checks; updated synchronization logic to apply these corrections before uniqueness checks.
openmeter/billing/worker/subscription/sync_test.go Added a test (TestSyncronizeSubscriptionPeriodAlgorithmChange) to verify period correction behavior when the period calculation algorithm changes for subscriptions.

📜 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 aaccef9 and 7c6480d.

📒 Files selected for processing (4)
  • openmeter/billing/invoicelinesplitgroup.go (1 hunks)
  • openmeter/billing/worker/subscription/phaseiterator.go (3 hunks)
  • openmeter/billing/worker/subscription/sync.go (3 hunks)
  • openmeter/billing/worker/subscription/sync_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • openmeter/billing/invoicelinesplitgroup.go
  • openmeter/billing/worker/subscription/phaseiterator.go
  • openmeter/billing/worker/subscription/sync.go
  • openmeter/billing/worker/subscription/sync_test.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • GitHub Check: CI
  • GitHub Check: Lint
  • GitHub Check: Build
  • GitHub Check: E2E
  • GitHub Check: Quickstart
  • GitHub Check: Commit hooks
  • GitHub Check: Developer environment
  • GitHub Check: Migration Checks
  • GitHub Check: Test
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
✨ 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 added release-note/feature Release note: Exciting New Features area/billing labels Jul 9, 2025
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: 2

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

4465-4465: Fix typo in test method name.

The test method name has a typo - "Syncronize" should be "Synchronize" to be consistent with the rest of the codebase.

-func (s *SubscriptionHandlerTestSuite) TestSyncronizeSubscriptionPeriodAlgorithmChange() {
+func (s *SubscriptionHandlerTestSuite) TestSynchronizeSubscriptionPeriodAlgorithmChange() {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3552f8e and aaccef9.

📒 Files selected for processing (4)
  • openmeter/billing/invoicelinesplitgroup.go (1 hunks)
  • openmeter/billing/worker/subscription/phaseiterator.go (3 hunks)
  • openmeter/billing/worker/subscription/sync.go (3 hunks)
  • openmeter/billing/worker/subscription/sync_test.go (1 hunks)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: chrisgacsal
PR: openmeterio/openmeter#2699
File: openmeter/productcatalog/planaddon/service/service_test.go:210-211
Timestamp: 2025-04-21T08:32:31.689Z
Learning: In `productcatalog.UsageBasedRateCard`, the `BillingCadence` field is a non-pointer `isodate.Period`, while in `productcatalog.FlatFeeRateCard`, `BillingCadence` is a pointer type (`*isodate.Period`). This means `MonthPeriod` should be used directly for `UsageBasedRateCard` (not `&MonthPeriod`).
openmeter/billing/invoicelinesplitgroup.go (1)
Learnt from: chrisgacsal
PR: openmeterio/openmeter#2699
File: openmeter/productcatalog/planaddon/service/service_test.go:210-211
Timestamp: 2025-04-21T08:32:31.689Z
Learning: In `productcatalog.UsageBasedRateCard`, the `BillingCadence` field is a non-pointer `isodate.Period`, while in `productcatalog.FlatFeeRateCard`, `BillingCadence` is a pointer type (`*isodate.Period`). This means `MonthPeriod` should be used directly for `UsageBasedRateCard` (not `&MonthPeriod`).
openmeter/billing/worker/subscription/sync_test.go (2)

undefined

<retrieved_learning>
Learnt from: chrisgacsal
PR: #2699
File: openmeter/productcatalog/planaddon/service/service_test.go:210-211
Timestamp: 2025-04-21T08:32:31.689Z
Learning: In productcatalog.UsageBasedRateCard, the BillingCadence field is a non-pointer isodate.Period, while in productcatalog.FlatFeeRateCard, BillingCadence is a pointer type (*isodate.Period). This means MonthPeriod should be used directly for UsageBasedRateCard (not &MonthPeriod).
</retrieved_learning>

<retrieved_learning>
Learnt from: GAlexIHU
PR: #2383
File: openmeter/entitlement/metered/lateevents_test.go:37-45
Timestamp: 2025-03-07T12:17:43.129Z
Learning: In the OpenMeter codebase, test files like openmeter/entitlement/metered/lateevents_test.go may use variables like meterSlug and namespace without explicit declarations visible in the same file. This appears to be an accepted pattern in their test structure.
</retrieved_learning>

openmeter/billing/worker/subscription/phaseiterator.go (1)
Learnt from: chrisgacsal
PR: openmeterio/openmeter#2699
File: openmeter/productcatalog/planaddon/service/service_test.go:210-211
Timestamp: 2025-04-21T08:32:31.689Z
Learning: In `productcatalog.UsageBasedRateCard`, the `BillingCadence` field is a non-pointer `isodate.Period`, while in `productcatalog.FlatFeeRateCard`, `BillingCadence` is a pointer type (`*isodate.Period`). This means `MonthPeriod` should be used directly for `UsageBasedRateCard` (not `&MonthPeriod`).
openmeter/billing/worker/subscription/sync.go (1)
Learnt from: chrisgacsal
PR: openmeterio/openmeter#2699
File: openmeter/productcatalog/planaddon/service/service_test.go:210-211
Timestamp: 2025-04-21T08:32:31.689Z
Learning: In `productcatalog.UsageBasedRateCard`, the `BillingCadence` field is a non-pointer `isodate.Period`, while in `productcatalog.FlatFeeRateCard`, `BillingCadence` is a pointer type (`*isodate.Period`). This means `MonthPeriod` should be used directly for `UsageBasedRateCard` (not `&MonthPeriod`).
🧬 Code Graph Analysis (2)
openmeter/billing/invoicelinesplitgroup.go (1)
openmeter/billing/invoiceline.go (1)
  • Period (81-84)
openmeter/billing/worker/subscription/sync.go (4)
pkg/slicesx/groupby.go (1)
  • UniqueGroupBy (5-18)
openmeter/billing/invoicelinesplitgroup.go (4)
  • LineOrHierarchy (281-285)
  • LineOrHierarchyTypeLine (277-277)
  • LineOrHierarchyTypeHierarchy (278-278)
  • SplitLineHierarchy (193-196)
openmeter/billing/invoiceline.go (3)
  • Line (304-318)
  • SubscriptionManagedLine (63-63)
  • Period (81-84)
openmeter/billing/annotations.go (1)
  • AnnotationSubscriptionSyncIgnore (4-4)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (13)
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Developer environment
  • GitHub Check: Quickstart
  • GitHub Check: Lint
  • GitHub Check: Commit hooks
  • GitHub Check: CI
  • GitHub Check: E2E
  • GitHub Check: Test
  • GitHub Check: Migration Checks
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (10)
openmeter/billing/worker/subscription/phaseiterator.go (3)

48-54: LGTM! Well-structured metadata enhancement.

The addition of PhaseKey, PeriodIndex, and ItemVersion fields provides better structured access to subscription item metadata that was previously only available in the UniqueID string. This supports the period correction logic mentioned in the PR objectives.


382-385: LGTM! Consistent field population.

The new fields are properly populated with the appropriate values from the function parameters and iterator context. The implementation maintains consistency with how these values are used in the UniqueID construction.


476-479: LGTM! Appropriate handling for one-time items.

The field population is consistent with the recurring item generation method. Setting PeriodIndex to 0 for one-time items is appropriate since they don't have multiple billing periods.

openmeter/billing/invoicelinesplitgroup.go (1)

337-346: LGTM! Clean abstraction for service period access.

The new ServicePeriod() method provides a unified interface to access service periods from both Line and SplitLineHierarchy types. The implementation correctly handles both types and follows the same pattern as the existing ChildUniqueReferenceID() method. This abstraction supports the synchronization logic mentioned in the PR objectives.

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

4465-4575: Excellent test implementation for period correction feature.

This test provides comprehensive coverage for the new correctPeriodStartForUpcomingLines functionality. It properly:

  • Sets up a realistic scenario with a monthly subscription
  • Simulates period algorithm changes through manual invoice updates
  • Uses the correct annotation (billing.AnnotationSubscriptionSyncIgnore) to mark manually adjusted lines
  • Verifies that subsequent periods are correctly aligned to the previous period's end
  • Follows the existing test patterns and conventions

The test directly validates the core requirement from the PR objectives: "adjusts the period start for upcoming billing lines to ensure continuity in their generation."


4490-4490: No action needed: isodate.MustParse is correct for UsageBasedRateCard’s BillingCadence

In the sync_test.go patch, that BillingCadence: isodate.MustParse(s.T(), "P1M") lives inside a &productcatalog.UsageBasedRateCard{…} block. Since UsageBasedRateCard.BillingCadence is a non-pointer isodate.Period, using isodate.MustParse here matches the field’s type. All other BillingCadence fields in this file use datetime.MustParse (with or without lo.ToPtr) to satisfy pointer or different period types.

openmeter/billing/worker/subscription/sync.go (4)

9-9: LGTM: Import addition is appropriate.

The strings package import is correctly added to support string operations in the new period correction logic.


286-297: LGTM: Period correction integration is well-structured.

The integration correctly applies period correction before the uniqueness check, which is the right sequence since corrections might affect line uniqueness. The error handling and flow control are appropriate.


342-409: LGTM: Period correction logic is sound with proper validation.

The function correctly:

  • Skips the first period (index 0) as it doesn't need correction
  • Constructs unique IDs for previous periods using a consistent format
  • Handles both line and hierarchy types appropriately
  • Validates that period starts are aligned before applying corrections
  • Maintains consistency across service, billing, and full service periods

The logic aligns well with the PR objective of ensuring continuity in billing periods.


432-443: LGTM: Hierarchy scope checking logic is correct.

The function correctly identifies the last line in the hierarchy by matching the service period end and delegates the actual scope checking to isLineInScopeForPeriodCorrection. The implementation is clean and follows the expected pattern.

@turip turip force-pushed the feat/make-sure-lines-are-continous branch from aaccef9 to 7c6480d Compare July 9, 2025 12:38
Copy link
Contributor

@GAlexIHU GAlexIHU left a comment

Choose a reason for hiding this comment

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

👍

@turip turip requested a review from a team July 9, 2025 13:23
@turip turip merged commit fb231e1 into main Jul 9, 2025
23 checks passed
@turip turip deleted the feat/make-sure-lines-are-continous branch July 9, 2025 13:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants