Skip to content

feat: collect usage on draft invoices - #2834

Merged
turip merged 4 commits into
mainfrom
feat/collect-on-draft
May 21, 2025
Merged

turip merged 4 commits into
mainfrom
feat/collect-on-draft

Conversation

@turip

@turip turip commented May 16, 2025 •

Copy link
Copy Markdown
Member

Overview

This patch ensures that if a line is billable, we are immediately moving it to a draft invoice and perform the collection there.

This makes sure that the gathering invoice only contains future (no yet billable) items, instead of a mix of two during the collection period.

The patch slightly changes the collection job to entirely rely on billing service to figure out the collected lines, thus removing some redundant logic.

The following will be implemented in separate PRs:

  • Support skipping the collection interval on API request
  • Support recalculating gathering invoices to fix inconsistencies during the collection job
  • Locked namespaces should be skipped by the collection job

Summary by CodeRabbit

  • New Features

    • Introduced new invoice statuses for collection phases, enabling more granular tracking of invoice state.
    • Added logic to calculate and set invoice collection times based on invoice lines and billing configuration.
    • Enhanced state machine to support collection-specific transitions and actions.
    • Added combined subscription synchronization and customer invoicing method for streamlined processing.
  • Bug Fixes

    • Improved error handling for scenarios with no invoice lines to bill, ensuring clearer feedback and robust processing.
  • Refactor

    • Simplified and streamlined invoice collection logic for better maintainability and type safety.
    • Removed outdated or redundant code related to invoice collection and updated method signatures for clarity.
    • Consolidated subscription synchronization and invoicing into a unified process with optional pre-sync invoicing.
    • Updated invoice processing to use structured customer IDs and current timestamps for collection operations.
  • Tests

    • Added comprehensive tests covering invoice collection flows, timing, state transitions, and editing scenarios.
    • Updated existing tests to reflect new collection logic and state transitions.
    • Enhanced test utilities for feature setup and cleanup, improving test reliability and clarity.
  • Chores

    • Updated configuration defaults to allow immediate invoice collection in tests, with the option to override per test case.

@coderabbitai

coderabbitai Bot commented May 16, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change introduces a new invoice collection flow in the billing system. It adds new invoice statuses for collection, restructures collection timestamp calculation, integrates collection logic into the invoice state machine, updates worker orchestration, and introduces comprehensive tests for collection scenarios. Several obsolete or redundant collection utilities are removed or refactored.

Changes

File(s) Change Summary
openmeter/billing/invoice.go, openmeter/ent/db/billinginvoice/billinginvoice.go, openmeter/ent/db/migrate/schema.go Added new invoice statuses (draft.waiting_for_collection, draft.collecting) to code, validation, and DB schema.
openmeter/billing/service/invoicecalc/collectionat.go, openmeter/billing/service/invoicecalc/calculator.go, openmeter/billing/service/invoicecalc/draftuntil.go Introduced and integrated new collection timestamp calculation logic for invoices; updated draft-until calculation to use CollectionAt if present.
openmeter/billing/service/invoice.go, openmeter/billing/service/invoiceline.go Refactored invoice and line services to remove legacy collection time update logic; integrated calculation calls and simplified flows; added snapshotQuantity method.
openmeter/billing/service/invoicestate.go Extended invoice state machine with new collection states, transitions, and snapshot logic; added methods for collection readiness and quantity snapshotting.
openmeter/billing/adapter/invoice.go Simplified UpdateInvoice logic for setting CollectionAt using a utility method.
openmeter/billing/service/collectionat.go Deleted obsolete collection timestamp utility functions.
openmeter/billing/worker/collect/collect.go Refactored invoice collection worker to use typed customer IDs, simplified collection logic, improved error handling, and updated batching.
openmeter/billing/worker/advance/advance.go Added logic to find invoices pending collection and include them in the auto-advancer workflow.
openmeter/billing/worker/subscription/handlers.go, openmeter/billing/worker/subscription/sync.go, openmeter/billing/worker/worker.go Removed legacy subscription-created handler, added new orchestration for synchronizing subscriptions and invoicing customers, updated event handlers to use new method.
cmd/jobs/billing/collect/collect.go Updated CLI logic to use structured customer IDs and current time for invoicing.
test/billing/collection_test.go Added comprehensive tests for the new collection flow, covering various scenarios including timing, state transitions, and editing.
test/billing/invoice_test.go, test/billing/suite.go, test/billing/profile.go Updated and refactored tests to use new helpers, explicit clock control, and immediate collection intervals.
openmeter/billing/worker/subscription/sync_test.go Added/updated tests for subscription and invoicing orchestration, including new test for uncollectable collection scenarios.

Possibly related PRs

  • openmeterio/openmeter#2829: Introduces and manages the QuantitySnapshotedAt field on invoices, directly relating to the new snapshot logic and invoice state transitions in this PR.
  • openmeterio/openmeter#2851: Refactors draft period calculation to depend on collection timestamps and workflow snapshots, closely related to invoice draft timing and collection handling.
  • openmeterio/openmeter#2827: Refactors locking and invoice manipulation functions to centralize locking and improve progressive billing consistency, aligning with this PR’s invoice collection and invoicing logic restructuring.

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.

✨ 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 feat/collect-on-draft branch 10 times, most recently from 938cab1 to 0667bbc Compare May 20, 2025 11:46
@turip
turip marked this pull request as ready for review May 20, 2025 11:46
@turip
turip requested a review from a team as a code owner May 20, 2025 11:46
@turip turip added release-note/feature Release note: Exciting New Features area/billing labels May 20, 2025

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

🧹 Nitpick comments (7)
cmd/jobs/billing/collect/collect.go (1)

71-76: Improved type safety in customer invoice collection.

The customer ID parameter has been upgraded from a simple string to a structured customer.CustomerID type with explicit namespace, improving type safety and making the code more robust.

The collection reference time is now explicitly set to the current time using time.Now().

Consider making the namespace configurable rather than hardcoding it to "default", especially if the system supports multiple namespaces:

-						CustomerID: customer.CustomerID{
-							Namespace: "default",
-							ID:        customerID,
-						},
+						CustomerID: customer.CustomerID{
+							Namespace: internal.GetDefaultNamespace(), // Or derive from configuration
+							ID:        customerID,
+						},
openmeter/billing/worker/worker.go (1)

139-148: Consider fixing typo in method name "SyncronizeSubscriptionAndInvoiceCustomer".

There appears to be a typo in the method name "Syncronize" which should be "Synchronize". Although this is likely consistent across the codebase, it might be worth addressing in a future PR.

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

3279-3279: Method call updated to use the new invoice orchestration

The method call has been updated from the now-removed HandleSubscriptionCreated to the new SyncronizeSubscriptionAndInvoiceCustomer method, which orchestrates invoicing pending lines before and after subscription synchronization. This change aligns with the PR objective to ensure billable lines are immediately moved to a draft invoice.

Minor note: There appears to be a typo in the method name - "Syncronize" should be "Synchronize". Consider fixing this in a future update.

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

121-155: Typo in public API – Syncronize* → Synchronize*

The newly exported method is spelled SyncronizeSubscriptionAndInvoiceCustomer.
A misspelling in a public symbol is hard to change later; recommend renaming before it propagates.

Example:

-func (h *Handler) SyncronizeSubscriptionAndInvoiceCustomer(
+func (h *Handler) SynchronizeSubscriptionAndInvoiceCustomer(

Same for related option types/builders.

openmeter/billing/worker/collect/collect.go (1)

59-75: AsOf is validated but never used

CollectCustomerInvoiceInput.AsOf is required (Validate rejects zero values) yet the field is ignored when calling InvoicePendingLines.
Either wire it through:

InvoicePendingLinesInput{
    Customer: params.CustomerID,
    AsOf:     &params.AsOf,
    // ...
}

or drop the parameter & its validation to avoid a misleading API.

Confirm whether downstream code needs AsOf; if not, pruning it keeps the contract minimal.

Also applies to: 83-90

openmeter/billing/service/invoice.go (2)

80-85: Clarify & centralize “time-sensitive” statuses

The hard-coded slice that controls whether we need to recompute StatusDetails has grown.
Keeping this list local means every new “time-sensitive” status will require touching this code path, increasing the chance of accidental omissions (e.g. a future InvoiceStatusDraftCollecting).

Consider extracting these statuses into:

var timeSensitiveStatuses = map[billing.InvoiceStatus]struct{}{
    billing.InvoiceStatusDraftWaitingForCollection: {},
    billing.InvoiceStatusDraftWaitingAutoApproval:  {},
}

and use _, ok := timeSensitiveStatuses[invoice.Status] for the lookup.
This makes future maintenance safer and conveys intent more clearly.


964-966: TODO merits an issue link or tracking reference

The comment highlights a missing StatusDetails update but gives no breadcrumb for follow-up.
Consider adding an issue/linear ticket reference so the debt is not lost.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d7c858b and 0667bbc.

📒 Files selected for processing (22)
  • cmd/jobs/billing/collect/collect.go (2 hunks)
  • openmeter/billing/adapter/invoice.go (1 hunks)
  • openmeter/billing/invoice.go (2 hunks)
  • openmeter/billing/service/collectionat.go (0 hunks)
  • openmeter/billing/service/invoice.go (5 hunks)
  • openmeter/billing/service/invoicecalc/calculator.go (2 hunks)
  • openmeter/billing/service/invoicecalc/collectionat.go (1 hunks)
  • openmeter/billing/service/invoicecalc/draftuntil.go (2 hunks)
  • openmeter/billing/service/invoiceline.go (1 hunks)
  • openmeter/billing/service/invoicestate.go (4 hunks)
  • openmeter/billing/worker/advance/advance.go (2 hunks)
  • openmeter/billing/worker/collect/collect.go (5 hunks)
  • openmeter/billing/worker/subscription/handlers.go (2 hunks)
  • openmeter/billing/worker/subscription/sync.go (2 hunks)
  • openmeter/billing/worker/subscription/sync_test.go (4 hunks)
  • openmeter/billing/worker/worker.go (1 hunks)
  • openmeter/ent/db/billinginvoice/billinginvoice.go (1 hunks)
  • openmeter/ent/db/migrate/schema.go (1 hunks)
  • test/billing/collection_test.go (1 hunks)
  • test/billing/invoice_test.go (8 hunks)
  • test/billing/profile.go (1 hunks)
  • test/billing/suite.go (2 hunks)
💤 Files with no reviewable changes (1)
  • openmeter/billing/service/collectionat.go
🧰 Additional context used
🧬 Code Graph Analysis (4)
openmeter/billing/adapter/invoice.go (2)
pkg/convert/ptr.go (1)
  • SafeToUTC (36-40)
openmeter/ent/db/billinginvoice/where.go (1)
  • CollectionAt (316-318)
openmeter/billing/worker/advance/advance.go (3)
openmeter/billing/invoice.go (4)
  • Invoice (336-347)
  • ListInvoicesInput (640-678)
  • InvoiceStatus (69-69)
  • InvoiceStatusDraftWaitingForCollection (77-77)
openmeter/ent/db/billinginvoice/where.go (1)
  • CollectionAt (316-318)
pkg/clock/clock.go (1)
  • Now (14-21)
openmeter/billing/service/invoice.go (4)
openmeter/billing/invoice.go (4)
  • InvoiceStatus (69-69)
  • InvoiceStatusDraftWaitingForCollection (77-77)
  • InvoiceStatusDraftWaitingAutoApproval (86-86)
  • Invoice (336-347)
openmeter/billing/service/lineservice/service.go (2)
  • Service (22-24)
  • Lines (174-174)
openmeter/billing/service/service.go (1)
  • Service (23-38)
pkg/clock/clock.go (1)
  • Now (14-21)
openmeter/billing/worker/collect/collect.go (3)
openmeter/customer/customer.go (2)
  • CustomerID (74-74)
  • Customer (15-23)
openmeter/billing/invoice.go (2)
  • InvoicePendingLinesInput (774-783)
  • Invoice (336-347)
openmeter/billing/errors.go (1)
  • ErrInvoiceCreateNoLines (51-51)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (37)
openmeter/billing/adapter/invoice.go (1)

451-451: Code simplification and standardization

The change simplifies the collection timestamp update by using the SetOrClearCollectionAt method with SafeToUTC conversion, replacing a previous conditional block that explicitly checked for non-nil and non-zero values.

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

314-314: New invoice collection statuses added

Two new intermediate draft statuses have been added: draft.waiting_for_collection and draft.collecting. These statuses extend the invoice lifecycle to include more granular collection states, supporting the new invoice collection flow introduced in this PR.

test/billing/profile.go (1)

19-21: Changed invoice collection interval for testing

The collection interval in the test profile has been changed from 2 hours to immediate (0 seconds), with a clear explanatory comment. This change properly supports testing the new invoice collection flow without waiting for a delay.

openmeter/billing/service/invoiceline.go (1)

286-286: Removed direct quantity snapshot time manipulation

The code now no longer sets the QuantitySnapshotedAt field directly, and the comment has been expanded to explain why. This aligns with the broader refactoring that moves collection timestamp handling and quantity snapshotting responsibility to the invoice state machine.

openmeter/ent/db/migrate/schema.go (1)

603-603: Schema updated to support new invoice collection states.

The billing_invoices table schema has been extended with two new enum values for the status field: "draft.waiting_for_collection" and "draft.collecting". These new statuses align with the PR objective to improve the invoice collection flow.

openmeter/billing/invoice.go (2)

75-79: New invoice status constants for collection flow.

Two new constants have been added to represent intermediate draft states in the invoice collection lifecycle:

  • InvoiceStatusDraftWaitingForCollection: Indicates an invoice waiting for collection to be possible
  • InvoiceStatusDraftCollecting: Indicates an invoice actively collecting items

This change properly documents the new statuses with explanatory comments.


117-118: Added new statuses to validation list.

The new collection-related statuses have been properly added to the validStatuses slice, ensuring they'll be recognized during validation checks.

openmeter/billing/service/invoicecalc/draftuntil.go (2)

3-7: Added lo package for pointer handling.

The import section has been updated to include the github.com/samber/lo package, which provides utility functions like FromPtrOr used in the updated calculation.


16-17: Improved draft period calculation based on collection timing.

The draft until date calculation has been enhanced to use the invoice's CollectionAt timestamp as the reference point when available, falling back to CreatedAt otherwise. This aligns the draft period with the collection schedule, creating a more accurate timeline for the invoice lifecycle.

This change supports the new collection workflow by ensuring draft timings are properly synchronized with collection events.

cmd/jobs/billing/collect/collect.go (2)

11-11: Added customer package import.

Added the customer package import to support the use of the strongly-typed CustomerID struct.


79-80: Improved error message for failed customer invoice collection.

The error message now includes the customer ID, making it easier to identify which customer's invoice collection failed.

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

139-139: Updated event handler to use unified synchronization method.

The code now uses the new consolidated SyncronizeSubscriptionAndInvoiceCustomer method instead of the previously separate methods, which aligns with the new invoice collection flow.


145-145: Consistent implementation for ContinuedEvent handling.

The handler now uses the same synchronization method as the CreatedEvent handler, ensuring consistent processing of subscription events.


148-148: Consistent implementation for UpdatedEvent handling.

Good change to use the unified SyncronizeSubscriptionAndInvoiceCustomer method for UpdatedEvent, maintaining consistency with other subscription event handlers while correctly passing the UpdatedView.

openmeter/billing/service/invoicecalc/calculator.go (3)

17-17: Added StandardInvoiceCollectionAt calculation for invoices.

Good addition of the collection timestamp calculation to the Invoice calculation pipeline, aligning with the new collection flow.


26-26: Added GatheringInvoiceCollectionAt calculation for gathering invoices.

This change properly integrates collection timestamp calculation into the gathering invoice calculation pipeline, ensuring collection timing is determined consistently.


30-32: Improved type declaration formatting.

The change to a type block format enhances code readability while maintaining the same functionality.

test/billing/suite.go (2)

407-410: Added TestFeature helper struct for test cleanup management.

Good addition of a helper struct to encapsulate test feature setup and cleanup, promoting better test organization.


412-457: Added comprehensive test helper for API requests feature setup.

The SetupApiRequestsTotalFeature method provides a robust way to set up test features with proper cleanup, which will be valuable for testing the new invoice collection flow.

One suggestion: Consider adding different event values in the mock streaming connector to test various quantity scenarios, as the current implementation only adds an event with value 0.

openmeter/billing/worker/advance/advance.go (3)

93-106: Added method to list invoices pending collection.

Good implementation of ListInvoicesPendingCollection that filters invoices by the new InvoiceStatusDraftWaitingForCollection status and collection timestamp.

Consider using a clock interface instead of time.Now() directly to improve testability:

-		CollectionAt:     lo.ToPtr(time.Now()),
+		CollectionAt:     lo.ToPtr(a.clock.Now()),

128-131: Added collection of pending collection invoices to advance logic.

Good integration of the collection status into the invoice advancement flow, with proper error handling.


139-139: Updated invoice combining logic to include collecting invoices.

The change correctly includes the collecting invoices in the list of all invoices to be processed for advancement.

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

21-23: Improved documentation for canceled events processing

Good clarification on why pre-sync invoice creation is skipped for canceled events. This helps other developers understand the rationale behind this approach.


26-26: Function usage updated for subscription synchronization

The code now uses SyncronizeSubscriptionAndInvoiceCustomer with the option to skip pre-sync invoice creation, which aligns with the new invoice collection flow.


35-35: Updated synchronization function call for canceled subscriptions

Consistently updated to use SyncronizeSubscriptionAndInvoiceCustomer with the parameter to skip pre-sync invoice creation.

openmeter/billing/service/invoicecalc/collectionat.go (2)

12-31: Well-implemented gathering invoice collection calculation

This function correctly sets the CollectionAt timestamp for gathering invoices by finding the earliest InvoiceAt among all invoice lines, ensuring timely collection of invoices as soon as any line is ready for invoicing.


33-59: Comprehensive standard invoice collection timestamp calculation

Good implementation that:

  1. Focuses only on usage-based lines for collection timing
  2. Falls back to invoice creation time if no usage-based lines exist
  3. Adds the configured collection interval to the latest usage-based InvoiceAt

This ensures correct timing for collections based on the most recent relevant invoice lines.

test/billing/invoice_test.go (6)

22-22: Updated import to use more specific package

Correctly updated to use the new invoicecalc package instead of the general billing service package.


327-328: Updated to use new collection timestamp calculation

The code now uses the new invoicecalc.GatheringInvoiceCollectionAt function with proper error handling, aligning with the restructured collection timestamp calculation approach.


1332-1332: Added proper clock reset in test cleanup

Good addition of a deferred clock reset to ensure test isolation and prevent clock state from affecting other tests.


1653-1654: Explicit clock time management in tests

Tests now explicitly set and manage the clock time before invoice operations, ensuring consistent and predictable test behavior with the time-dependent collection logic.

Also applies to: 1955-1956


3731-3732: Improved test feature setup with reusable method

The code now uses the new SetupApiRequestsTotalFeature method for consistent feature initialization across tests, improving maintainability.

Also applies to: 3832-3833


3900-3906: Testing progressive billing override functionality

Good test case that verifies the ability to override the progressive billing setting, ensuring that when disabled, only currently billable lines are included in invoices.

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

475-555: Well-structured test for handling uncollectible invoices

This test nicely validates that InvoicePendingLines properly returns ErrInvoiceCreateNoLines when a customer has a gathering invoice without billable lines. The test covers both scenarios: no gathering invoice and a gathering invoice with non-billable lines.

The clear "Given-When-Then" comments make the test's purpose easy to understand, which is especially important for these edge cases in the billing system.


3393-3393: Method call updated to use the new invoice orchestration

Similar to the other instance, the method call has been updated to use the new SyncronizeSubscriptionAndInvoiceCustomer method.

test/billing/collection_test.go (1)

72-74: Global clock.SetTime can leak between parallel tests

clock.SetTime mutates a package-level (global) clock.
If any other test in the same process also relies on clock.Now() (common across the repo), running the suite with the -parallel flag – or simply executing go test ./... where unrelated packages run in parallel – can lead to flaky tests because the clock value “bleeds” between goroutines / packages.

Consider one of these mitigations:

-clock.SetTime(periodStart)
+oldTime := clock.Now()
+clock.SetTime(periodStart)
 defer clock.ResetTime()

and inside ResetTime make sure it restores oldTime, or – even safer – provide a test-local clock abstraction that doesn’t affect the global state.

Would you double-check if any other package uses clock.SetTime in parallel tests?
If yes, we should guard the global clock with a mutex or switch to an injected clock in tests.

Also applies to: 245-247

openmeter/billing/service/invoice.go (1)

417-420: Verify gathering-invoice specific calculations

Here we recalculate live gathering invoices using the generic Calculate(&invoice).
If CalculateGatheringInvoice is now responsible for collection-related fields (e.g. CollectionAt), they will stay stale.

Please confirm with a quick grep that CalculateGatheringInvoice is invoked for all gathering invoices, or switch to it here:

- if err := s.invoiceCalculator.Calculate(&invoice); err != nil {
+ if err := s.invoiceCalculator.CalculateGatheringInvoice(&invoice); err != nil {

Comment thread openmeter/billing/service/invoice.go Resolved
Comment thread openmeter/billing/service/invoice.go Resolved
@turip
turip force-pushed the feat/collect-on-draft branch from 0667bbc to ffaebcf Compare May 20, 2025 12:00

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (3)
openmeter/billing/service/invoicestate.go (2)

673-684: ⚠️ Potential issue

isReadyForCollection still treats missing CollectionAt as “ready”, leading to downstream panics

The guard returns true when CollectionAt is nil, yet snapshotQuantityAsNeeded dereferences *m.Invoice.CollectionAt.
This was raised earlier and is still unresolved – a nil timestamp should keep the invoice in waiting_for_collection or fail fast.

 if m.Invoice.CollectionAt == nil {
-    m.Logger.Warn("invoice has no collection at set, assuming collection is not required", "invoice", m.Invoice.ID)
-    return true
+    m.Logger.Error("collectionAt is nil – invoice cannot be collected", "invoice", m.Invoice.ID)
+    return false
 }

686-705: ⚠️ Potential issue

Nil-pointer dereference in snapshotQuantityAsNeeded

*m.Invoice.CollectionAt is dereferenced twice without a preceding nil-check.
If the previous comment’s guard is not fixed, this will crash the worker when CollectionAt is nil.

 if m.Invoice.QuantitySnapshotedAt != nil && m.Invoice.CollectionAt != nil &&
-   !m.Invoice.QuantitySnapshotedAt.Before(*m.Invoice.CollectionAt) {
+   !m.Invoice.QuantitySnapshotedAt.Before(*m.Invoice.CollectionAt) {
     ...
 }

 // early-exit when collectionAt is nil OR in the future
-if m.Invoice.QuantitySnapshotedAt == nil && clock.Now().Before(*m.Invoice.CollectionAt) {
+if m.Invoice.CollectionAt == nil ||                                  // <- new nil guard
+   (m.Invoice.QuantitySnapshotedAt == nil && clock.Now().Before(*m.Invoice.CollectionAt)) {
     return nil
 }
openmeter/billing/worker/collect/collect.go (1)

190-205: ⚠️ Potential issue

Data-race & loop-variable capture in goroutines

The goroutine closes over the mutable loop variable customerID and the outer err variable, recreating the race flagged in the previous review. Each goroutine may end up processing the last customer and concurrently writing to the same err.

-for _, customerID := range batch {
-    wg.Add(1)
-    go func() {
+for _, cid := range batch {               // copy loop variable
+    cust := cid
+    wg.Add(1)
+    go func(c customer.CustomerID) {
         defer wg.Done()
 
-        _, err = a.CollectCustomerInvoice(ctx, CollectCustomerInvoiceInput{
-            CustomerID: customerID,
+        _, err := a.CollectCustomerInvoice(ctx, CollectCustomerInvoiceInput{
+            CustomerID: cust,
             AsOf:       time.Now(),
         })
         if err != nil {
-            err = fmt.Errorf("failed to collect invoice for customer [namespace=%s customer=%s]: %w", customerID.Namespace, customerID.ID, err)
+            err = fmt.Errorf("failed to collect invoice for customer [namespace=%s customer=%s]: %w", cust.Namespace, cust.ID, err)
         }
 
         errChan <- err
-    }()
+    }(cust)
 }
🧹 Nitpick comments (2)
openmeter/billing/worker/collect/collect.go (1)

83-90: AsOf parameter is accepted & validated but never used

CollectCustomerInvoice validates that AsOf is non-zero, yet the value is not passed further (only InvoicePendingLines is called without it). Either wire the parameter through or drop it to avoid dead fields and confusing API.

test/billing/collection_test.go (1)

245-247: Minor: reset the test clock in a defer immediately after setting

For consistency and to prevent accidental leakage between sub-tests, consider:

clock.SetTime(periodStart)
defer clock.ResetTime()   // move immediately after SetTime

This pattern is already used elsewhere in the suite; applying it uniformly avoids surprises if future early-returns are introduced.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0667bbc and ffaebcf.

📒 Files selected for processing (22)
  • cmd/jobs/billing/collect/collect.go (2 hunks)
  • openmeter/billing/adapter/invoice.go (1 hunks)
  • openmeter/billing/invoice.go (2 hunks)
  • openmeter/billing/service/collectionat.go (0 hunks)
  • openmeter/billing/service/invoice.go (5 hunks)
  • openmeter/billing/service/invoicecalc/calculator.go (2 hunks)
  • openmeter/billing/service/invoicecalc/collectionat.go (1 hunks)
  • openmeter/billing/service/invoicecalc/draftuntil.go (2 hunks)
  • openmeter/billing/service/invoiceline.go (1 hunks)
  • openmeter/billing/service/invoicestate.go (4 hunks)
  • openmeter/billing/worker/advance/advance.go (2 hunks)
  • openmeter/billing/worker/collect/collect.go (5 hunks)
  • openmeter/billing/worker/subscription/handlers.go (2 hunks)
  • openmeter/billing/worker/subscription/sync.go (2 hunks)
  • openmeter/billing/worker/subscription/sync_test.go (4 hunks)
  • openmeter/billing/worker/worker.go (1 hunks)
  • openmeter/ent/db/billinginvoice/billinginvoice.go (1 hunks)
  • openmeter/ent/db/migrate/schema.go (1 hunks)
  • test/billing/collection_test.go (1 hunks)
  • test/billing/invoice_test.go (8 hunks)
  • test/billing/profile.go (1 hunks)
  • test/billing/suite.go (2 hunks)
💤 Files with no reviewable changes (1)
  • openmeter/billing/service/collectionat.go
✅ Files skipped from review due to trivial changes (1)
  • openmeter/ent/db/migrate/schema.go
🚧 Files skipped from review as they are similar to previous changes (14)
  • openmeter/billing/service/invoiceline.go
  • test/billing/profile.go
  • openmeter/billing/adapter/invoice.go
  • openmeter/billing/service/invoicecalc/calculator.go
  • cmd/jobs/billing/collect/collect.go
  • openmeter/billing/invoice.go
  • test/billing/suite.go
  • openmeter/billing/service/invoicecalc/draftuntil.go
  • openmeter/ent/db/billinginvoice/billinginvoice.go
  • openmeter/billing/service/invoicecalc/collectionat.go
  • openmeter/billing/worker/advance/advance.go
  • openmeter/billing/service/invoice.go
  • openmeter/billing/worker/subscription/sync_test.go
  • openmeter/billing/worker/subscription/sync.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
openmeter/billing/worker/subscription/handlers.go (2)
openmeter/subscription/subscriptionview.go (1)
  • SubscriptionView (21-26)
openmeter/billing/worker/subscription/sync.go (1)
  • WithSkipPreSyncInvoiceCreation (115-119)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: Lint
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: Test
  • GitHub Check: Analyze (go)
  • GitHub Check: Build
🔇 Additional comments (8)
openmeter/billing/worker/worker.go (1)

139-149: Clean refactoring to unify subscription handling logic.

The changes consolidate different subscription event handlers to use the unified SyncronizeSubscriptionAndInvoiceCustomer method, which helps streamline the billing worker implementation. This aligns well with the PR's goal of improving invoice collection flow.

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

21-23: Good documentation explaining the skipped invoice creation.

The added comment clearly explains the reasoning behind skipping pre-sync invoice creation for canceled events, making the code more maintainable.


24-36: Nicely refactored cancellation handling.

The implementation now uses SyncronizeSubscriptionAndInvoiceCustomer with the WithSkipPreSyncInvoiceCreation() option, which creates a more consistent approach to subscription synchronization. This aligns with the PR's objective of moving billable lines directly to draft invoices.

test/billing/invoice_test.go (5)

22-22: Improved package import specificity.

Changing from the general billing/service to the more specific billing/service/invoicecalc package reflects the reorganization of the collection timestamp calculation logic, making the code more modular.


327-327: Better error handling in collection timestamp calculation.

Replacing direct timestamp updates with a call to invoicecalc.GatheringInvoiceCollectionAt with explicit error checking improves error handling and aligns with the new collection logic.


1332-1332: Ensures proper cleanup of global clock state.

Adding a deferred call to clock.ResetTime() ensures that global time state doesn't leak between tests, preventing potential test interactions.


1654-1654: Explicit time control for deterministic tests.

Setting the clock time explicitly before calling InvoicePendingLines ensures that tests are deterministic and predictable, particularly important for invoice collection which is time-sensitive.


3731-3733: Improved test utilities reuse.

Replacing the local helper method with a shared SetupApiRequestsTotalFeature from the test suite promotes code reuse and standardizes feature setup across tests.

@turip
turip force-pushed the feat/collect-on-draft branch from ffaebcf to 30e0e46 Compare May 20, 2025 13:21

@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 (3)
openmeter/billing/worker/worker.go (1)

138-149: Consider extracting a small helper to remove duplication and improve testability

The three anonymous functions for CreatedEvent, ContinuedEvent, and UpdatedEvent are identical apart from the concrete event type used to access the SubscriptionView.
A tiny wrapper such as

func (w *Worker) syncAndInvoice(ctx context.Context, view subscription.SubscriptionView) error {
    // NOTE: Consider injecting a clock interface to avoid hard-coding time.Now()
    return w.subscriptionSyncHandler.SyncronizeSubscriptionAndInvoiceCustomer(ctx, view, time.Now())
}

would:

  1. Eliminate the repetition (DRY).
  2. Centralise the time.Now() invocation, making it easier to swap for a deterministic clock in unit tests.
- grouphandler.NewGroupEventHandler(func(ctx context.Context, event *subscription.CreatedEvent) error {
-     return w.subscriptionSyncHandler.SyncronizeSubscriptionAndInvoiceCustomer(ctx, event.SubscriptionView, time.Now())
- }),
+ grouphandler.NewGroupEventHandler(func(ctx context.Context, event *subscription.CreatedEvent) error {
+     return w.syncAndInvoice(ctx, event.SubscriptionView)
+ }),

Not critical, but it will keep this list readable as more event types are added.

test/billing/collection_test.go (2)

34-56: Variable shadowing makes the test harder to read

Inside several s.Run(...) sub-tests a new variable named res is declared with :=, shadowing the outer collectionNSResult (res) returned by setupNS. The same happens with invoice and others.

While legal, the double meaning of res (namespace setup vs. pending-line result) forces readers to keep mental context and can lead to subtle mistakes if the outer variable is unexpectedly referenced.

Consider renaming the inner results, e.g.:

- res, err := s.BillingService.CreatePendingInvoiceLines(…
+ pendingRes, err := s.BillingService.CreatePendingInvoiceLines(…

(or give the outer one a clearer name such as nsSetup).

This small change dramatically improves test clarity.


135-139: Minor typo in comment

// Given a gatherting invoice exists → // Given a gathering invoice exists

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ffaebcf and 30e0e46.

📒 Files selected for processing (22)
  • cmd/jobs/billing/collect/collect.go (2 hunks)
  • openmeter/billing/adapter/invoice.go (1 hunks)
  • openmeter/billing/invoice.go (2 hunks)
  • openmeter/billing/service/collectionat.go (0 hunks)
  • openmeter/billing/service/invoice.go (5 hunks)
  • openmeter/billing/service/invoicecalc/calculator.go (2 hunks)
  • openmeter/billing/service/invoicecalc/collectionat.go (1 hunks)
  • openmeter/billing/service/invoicecalc/draftuntil.go (2 hunks)
  • openmeter/billing/service/invoiceline.go (1 hunks)
  • openmeter/billing/service/invoicestate.go (4 hunks)
  • openmeter/billing/worker/advance/advance.go (2 hunks)
  • openmeter/billing/worker/collect/collect.go (5 hunks)
  • openmeter/billing/worker/subscription/handlers.go (2 hunks)
  • openmeter/billing/worker/subscription/sync.go (2 hunks)
  • openmeter/billing/worker/subscription/sync_test.go (4 hunks)
  • openmeter/billing/worker/worker.go (1 hunks)
  • openmeter/ent/db/billinginvoice/billinginvoice.go (1 hunks)
  • openmeter/ent/db/migrate/schema.go (1 hunks)
  • test/billing/collection_test.go (1 hunks)
  • test/billing/invoice_test.go (8 hunks)
  • test/billing/profile.go (1 hunks)
  • test/billing/suite.go (2 hunks)
💤 Files with no reviewable changes (1)
  • openmeter/billing/service/collectionat.go
🚧 Files skipped from review as they are similar to previous changes (19)
  • openmeter/billing/adapter/invoice.go
  • openmeter/billing/service/invoiceline.go
  • openmeter/billing/service/invoicecalc/collectionat.go
  • test/billing/profile.go
  • openmeter/billing/invoice.go
  • openmeter/billing/worker/subscription/handlers.go
  • openmeter/billing/service/invoicecalc/calculator.go
  • test/billing/suite.go
  • openmeter/ent/db/migrate/schema.go
  • openmeter/billing/worker/advance/advance.go
  • openmeter/billing/service/invoicecalc/draftuntil.go
  • openmeter/billing/worker/subscription/sync.go
  • openmeter/billing/worker/subscription/sync_test.go
  • test/billing/invoice_test.go
  • openmeter/billing/service/invoicestate.go
  • openmeter/billing/service/invoice.go
  • openmeter/ent/db/billinginvoice/billinginvoice.go
  • openmeter/billing/worker/collect/collect.go
  • cmd/jobs/billing/collect/collect.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
openmeter/billing/worker/worker.go (3)
openmeter/subscription/subscriptionview.go (1)
  • SubscriptionView (21-26)
openmeter/watermill/grouphandler/grouphandler.go (1)
  • NewGroupEventHandler (29-31)
openmeter/subscription/events.go (1)
  • UpdatedEvent (167-171)
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Test
  • GitHub Check: Analyze (go)
  • GitHub Check: Build

Comment thread test/billing/collection_test.go Resolved
@turip
turip force-pushed the feat/collect-on-draft branch from 4a4fff6 to 110ea0a Compare May 21, 2025 09:53

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (2)
openmeter/billing/service/invoicestate.go (2)

672-683: ⚠️ Potential issue

Fix potential nil dereference issue in the collection readiness check.

The isReadyForCollection method incorrectly returns true when CollectionAt is nil, which can lead to downstream nil pointer dereferences in snapshotQuantityAsNeeded. This was previously flagged but still needs fixing.

func (m *InvoiceStateMachine) isReadyForCollection() bool {
	if m.Invoice.CollectionAt == nil {
-		m.Logger.Warn("invoice has no collection at set, assuming collection is not required", "invoice", m.Invoice.ID)
-		return true
+		m.Logger.Error("collectionAt is missing – invoice cannot be collected", "invoice", m.Invoice.ID)
+		return false
	}

	if clock.Now().Before(*m.Invoice.CollectionAt) {
		return false
	}

	return true
}

685-702: ⚠️ Potential issue

Add nil check for CollectionAt to prevent potential panic.

This method unconditionally dereferences m.Invoice.CollectionAt in multiple places but doesn't verify it's non-nil, creating a risk of panic.

func (m *InvoiceStateMachine) snapshotQuantityAsNeeded(ctx context.Context) error {
+	// Defensive guard – we cannot reason about snapshots without a collection time.
+	if m.Invoice.CollectionAt == nil {
+		m.Logger.WarnContext(ctx, "collectionAt is nil – skipping snapshot", "invoice", m.Invoice.ID)
+		return nil
+	}
+
	// Let's skip the snapshot if we already have the snapshot and it happened after the collection date
	if m.Invoice.QuantitySnapshotedAt != nil && !m.Invoice.QuantitySnapshotedAt.Before(lo.FromPtrOr(m.Invoice.CollectionAt, m.Invoice.CreatedAt)) {
		m.Logger.InfoContext(ctx, "skipping snapshot quantity as it already exists and was taken after the collection date",
			"invoice", m.Invoice.ID,
			"quantity_snapshoted_at", m.Invoice.QuantitySnapshotedAt,
			"collection_at", m.Invoice.CollectionAt,
		)
		return nil
	}

	// We don't have the snapshot and the collection date is in the future
	if m.Invoice.QuantitySnapshotedAt == nil && clock.Now().Before(*m.Invoice.CollectionAt) {
		return nil
	}

	return m.Service.snapshotQuantity(ctx, &m.Invoice)
}
🧹 Nitpick comments (1)
openmeter/billing/service/invoicestate.go (1)

686-702: Consider recalculating totals after snapshotting.

The snapshotQuantity method likely mutates line quantities, but calculateInvoice is executed before snapshotting in the allOf chain. Consider recalculating totals after snapshotting to ensure they reflect the updated quantities.

func (m *InvoiceStateMachine) snapshotQuantityAsNeeded(ctx context.Context) error {
	// [existing code...]

-	return m.Service.snapshotQuantity(ctx, &m.Invoice)
+	if err := m.Service.snapshotQuantity(ctx, &m.Invoice); err != nil {
+		return err
+	}
+	
+	// Recalculate invoice after snapshotting since quantities may have changed
+	return m.calculateInvoice(ctx)
}

Or alternatively, reorder the method calls in the allOf chain on lines 96-100:

OnActive(
	allOf(
-		out.snapshotQuantityAsNeeded,
-		out.calculateInvoice,
+		out.snapshotQuantityAsNeeded, // This already includes calculateInvoice
	),
)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 38f170c and 110ea0a.

📒 Files selected for processing (1)
  • openmeter/billing/service/invoicestate.go (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Test
  • GitHub Check: Quickstart
  • GitHub Check: Lint
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: CI
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (6)
openmeter/billing/service/invoicestate.go (6)

28-28: Good addition of the Service reference to the InvoiceStateMachine.

Adding this field appropriately enables the state machine to invoke service methods for collection-related operations.


76-76: Improved state transition workflow.

The transition from DraftCreated now correctly leads to WaitingForCollection rather than directly to validation, implementing the new collection flow.


82-89: Well-defined collection waiting state.

The new DraftWaitingForCollection state properly implements a conditional transition to DraftCollecting based on collection readiness.


91-101: Good integration of collection into workflow.

The DraftCollecting state correctly calls snapshotQuantityAsNeeded followed by calculateInvoice when activated, ensuring quantities are captured before calculations.


104-107: Proper workflow cycle update.

The DraftUpdating state now transitions back to DraftWaitingForCollection instead of validation, maintaining the collection-first workflow.


280-288: Proper service reference management.

Setting and clearing the Service reference along with other fields prevents memory leaks and ensures clean state machine reuse.

@turip
turip merged commit c4593ed into main May 21, 2025
@turip
turip deleted the feat/collect-on-draft branch May 21, 2025 13:38
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