Skip to content

fix(billing-sync): fix aligned line generation - #2982

Merged
GAlexIHU merged 1 commit into
mainfrom
galexi/fix-aligned-line-generation
Jun 11, 2025
Merged

GAlexIHU merged 1 commit into
mainfrom
galexi/fix-aligned-line-generation

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Jun 11, 2025 •

Copy link
Copy Markdown
Contributor

Overview

  • Change InvoiceAt for in-advance items so they get billed together at billing period start (potentially outside service period)
  • Override "generationEnd" with the end of current billing period
  • When generating until boundary of aligned billing period, make sure all of next cycle's in-advance lines are also generated

Notes for reviewer

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of invoice date alignment for subscriptions, ensuring invoice dates for in-advance and in-arrears billing are correctly calculated and aligned with billing periods.
    • Refined logic to prevent generation of billing items beyond the intended period for aligned subscriptions.
    • Enhanced validation and error messages for billing period calculations, particularly for inactive or canceled subscriptions.
  • Tests

    • Expanded test coverage to include both in-advance and in-arrears billing scenarios for aligned subscriptions.
    • Updated test cases to reflect new invoice date alignment and extended billing periods.
    • Removed outdated test for aligned billing period calculation.
  • Refactor

    • Simplified validation logic and invoice date determination for improved clarity and maintainability.

@GAlexIHU GAlexIHU self-assigned this Jun 11, 2025
@GAlexIHU
GAlexIHU requested a review from a team as a code owner June 11, 2025 14:37
@GAlexIHU GAlexIHU added the release-note/bug-fix Release note: Bug Fixes label Jun 11, 2025
@GAlexIHU
GAlexIHU requested review from tothandras and turip June 11, 2025 14:37
@GAlexIHU
GAlexIHU enabled auto-merge (squash) June 11, 2025 14:37
@coderabbitai

coderabbitai Bot commented Jun 11, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change refines invoice timestamp validation, simplifies invoice date calculation for flat-fee items, and adjusts logic for aligned subscription billing and iteration. Test coverage is expanded to include both in-advance and in-arrears billing scenarios, and a test file for aligned billing period calculation is removed. Internal logic for determining billing periods is also updated.

Changes

Files/Paths Change Summary
openmeter/billing/invoiceline.go Removed validation enforcing "invoice at" timestamp to be after billing period start.
openmeter/billing/worker/subscription/phaseiterator.go Simplified invoice date logic for flat-fee in-advance items; refined aligned item iteration to avoid appending items past iteration end.
openmeter/billing/worker/subscription/phaseiterator_test.go Extended tests to include both in-advance and in-arrears recurring items; updated expected outputs and comments accordingly.
openmeter/billing/worker/subscription/sync.go Changed generation limit logic for aligned subscriptions to use current aligned billing period end.
openmeter/billing/worker/subscription/sync_test.go Updated tests for aligned invoicing, progressive billing, and discount synchronization; added helper for repeated timestamps.
openmeter/subscription/aligment_test.go Deleted test file for aligned billing period calculation.
openmeter/subscription/subscriptionspec.go Updated logic in GetAlignedBillingPeriodAt to allow querying after subscription active period and provide clearer error handling.

Possibly related PRs

Warning

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

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
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

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.

@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: 2

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

76-85: Comment typo & clarification in GetInvoiceAt

Minor, but worth fixing to avoid leaking into generated docs:

-       // For in advance invoicing we attempt to incoice at the start of the billing period
+       // For in-advance invoicing we attempt to invoice at the start of the billing period

283-289: invoiceAt boundary condition & loop structure

The “stop-when-past-iterationEnd” check uses After, meaning a line whose invoiceAt == iterationEnd will still be emitted.
If the caller expects generation up-to and including iterationEnd that’s fine; if the intention was strictly before the limit, change to !invAt.Before(iterationEnd) for clarity.

Also, you calculate newItem.GetInvoiceAt() twice – capture once to avoid extra work and keep logs consistent.

-               // Check if we have reached the iteration end based on invoiceAt
-               if newItem.GetInvoiceAt().After(iterationEnd) {
+               invAt := newItem.GetInvoiceAt()
+               // Stop once invoiceAt exceeds the iteration end
+               if invAt.After(iterationEnd) {
                        logger.DebugContext(ctx, "exiting loop due to iteration end", slog.Time("at", at), slog.Time("iterationEnd", iterationEnd), slog.Time("invoiceAt", invAt))
                        break
                }
-
-               *items = append(*items, newItem)
+               *items = append(*items, newItem)
openmeter/subscription/subscriptionspec.go (1)

219-233: Error messages & early-period handling polish

  1. Two error strings have trailing commas – looks accidental and will read oddly in logs / client responses.
-               return def, fmt.Errorf("phase %s is not active at %s, ", phaseKey, at)
+               return def, fmt.Errorf("phase %s is not active at %s", phaseKey, at)
  1. at.Before(subCad.ActiveFrom) path returns an error, but a timestamp slightly before ActiveFrom (e.g. customer tries to preview the first invoice) may be legitimate. Consider allowing a configurable “look-back” grace or documenting that consumers must always pass ≥ ActiveFrom.

(Not blocking but worth noting.)

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

677-698: Table-row is becoming unwieldy – factor out a helper for mixed cadence scenarios

This block adds a third “mega” test case that mixes in-advance and in-arrears items.
The raw literal construction of the items slice already spans ~20 lines and the
corresponding expected slice further below is >100 lines long. Updating or
debugging this by hand will be painful and very error-prone.

Consider introducing a small builder/helper that can produce:

func mkItem(key string, t productcatalog.PriceType, cad string,
            startAfter, endAfter *isodate.Period) subscriptionItemViewMock

and another helper that builds an expectedIterations slice from start/end
timestamps plus a template format for the Key. That keeps each test row
focused on intent rather than on copy-pasted boilerplate and will localise any
future cadence logic changes to one place.


748-764: Expectation comment is code – assert it

The inline comment

// As we want to generate all in advance items invoicable by end time, we get an extra in advance item

is useful, but the assertion does not make that guarantee explicit.
A quick win is to add:

s.Equal(4, lo.CountBy(outAsExpect, func(it expectedIterations) bool {
    return strings.Contains(it.Key, "item-key")
}), "expected 4 in-advance periods")

(or via a helper). That turns the rationale into a checked invariant and
guards against future regressions where the extra period accidentally
disappears.

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

1632-1683: Leverage the new generateSameNTimes helper to reduce duplication

Eight identical InvoiceAt timestamps are manually listed here.
Now that generateSameNTimes exists (see ~4105-4114), these four-line blocks can be collapsed into a single helper call, e.g.

- InvoiceAt: []time.Time{
-     s.mustParseTime("2024-01-01T00:00:00Z"),
-     s.mustParseTime("2024-01-01T00:00:00Z"),
-     s.mustParseTime("2024-01-01T00:00:00Z"),
-     s.mustParseTime("2024-01-01T00:00:00Z"),
-     s.mustParseTime("2024-01-29T00:00:00Z"),
-     s.mustParseTime("2024-01-29T00:00:00Z"),
-     s.mustParseTime("2024-01-29T00:00:00Z"),
-     s.mustParseTime("2024-01-29T00:00:00Z"),
- },
+ InvoiceAt: append(
+     s.generateSameNTimes("2024-01-01T00:00:00Z", 4),
+     s.generateSameNTimes("2024-01-29T00:00:00Z", 4)...,
+ ),

This removes boilerplate, keeps the test intent clear, and avoids the risk of mismatching counts when periods change.


1710-1738: Same duplication pattern for in-arrears line – apply helper

InvoiceAt is repeated four times with the same value. Consider the same refactor as above:

- InvoiceAt: []time.Time{
-     s.mustParseTime("2024-01-29T00:00:00Z"),
-     s.mustParseTime("2024-01-29T00:00:00Z"),
-     s.mustParseTime("2024-01-29T00:00:00Z"),
-     s.mustParseTime("2024-01-29T00:00:00Z"),
- },
+ InvoiceAt: s.generateSameNTimes("2024-01-29T00:00:00Z", 4),

This keeps the expectations DRY and consistent with the new helper.


4105-4114: Minor micro-optimisations in generateSameNTimes

The helper is neat, but we can eliminate unnecessary work inside tight loops:

  1. Parse the timestamp only once.
  2. Pre-allocate the slice capacity.
-func (s *SubscriptionHandlerTestSuite) generateSameNTimes(ts string, n int) []time.Time {
-    out := []time.Time{}
-    for n != 0 {
-        out = append(out, s.mustParseTime(ts))
-        n--
-    }
-    return out
+func (s *SubscriptionHandlerTestSuite) generateSameNTimes(ts string, n int) []time.Time {
+    t := s.mustParseTime(ts)
+    out := make([]time.Time, n)
+    for i := 0; i < n; i++ {
+        out[i] = t
+    }
+    return out
 }

Not critical for tests, but it’s a one-liner change that makes the helper both clearer and cheaper.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5dd1a38 and 47fdec5.

📒 Files selected for processing (7)
  • openmeter/billing/invoiceline.go (0 hunks)
  • openmeter/billing/worker/subscription/phaseiterator.go (2 hunks)
  • openmeter/billing/worker/subscription/phaseiterator_test.go (6 hunks)
  • openmeter/billing/worker/subscription/sync.go (1 hunks)
  • openmeter/billing/worker/subscription/sync_test.go (12 hunks)
  • openmeter/subscription/aligment_test.go (0 hunks)
  • openmeter/subscription/subscriptionspec.go (1 hunks)
💤 Files with no reviewable changes (2)
  • openmeter/billing/invoiceline.go
  • openmeter/subscription/aligment_test.go
🧰 Additional context used
🧠 Learnings (1)
openmeter/billing/worker/subscription/sync_test.go (1)

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>

🧬 Code Graph Analysis (2)
openmeter/subscription/subscriptionspec.go (1)
pkg/models/cadence.go (1)
  • CadencedModel (21-25)
openmeter/billing/worker/subscription/sync.go (4)
api/api.gen.go (2)
  • Alignment (999-1003)
  • SubscriptionPhase (6604-6637)
openmeter/productcatalog/alignment.go (1)
  • Alignment (7-10)
openmeter/ent/db/subscription/where.go (1)
  • BillablesMustAlign (101-103)
openmeter/ent/schema/subscription.go (5)
  • SubscriptionPhase (82-84)
  • SubscriptionPhase (86-93)
  • SubscriptionPhase (95-104)
  • SubscriptionPhase (106-112)
  • SubscriptionPhase (114-123)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Developer environment
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Commit hooks
  • GitHub Check: Lint
  • GitHub Check: Migration Checks
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (go)

@turip turip left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thank you looks good!

@GAlexIHU
GAlexIHU merged commit c8d16f2 into main Jun 11, 2025
@GAlexIHU
GAlexIHU deleted the galexi/fix-aligned-line-generation branch June 11, 2025 14:47
@coderabbitai coderabbitai Bot mentioned this pull request Feb 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants