Repository navigation
feat: collect usage on draft invoices - #2834
Conversation
📝 WalkthroughWalkthroughThis 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
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 Note ⚡️ AI Code Reviews for VS Code, Cursor, WindsurfCodeRabbit 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. Note ⚡️ Faster reviews with cachingCodeRabbit 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 ✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
938cab1 to
0667bbc
Compare
There was a problem hiding this comment.
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.CustomerIDtype 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 orchestrationThe method call has been updated from the now-removed
HandleSubscriptionCreatedto the newSyncronizeSubscriptionAndInvoiceCustomermethod, 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:AsOfis validated but never used
CollectCustomerInvoiceInput.AsOfis required (Validaterejects zero values) yet the field is ignored when callingInvoicePendingLines.
Either wire it through:InvoicePendingLinesInput{ Customer: params.CustomerID, AsOf: ¶ms.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” statusesThe hard-coded slice that controls whether we need to recompute
StatusDetailshas 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 futureInvoiceStatusDraftCollecting).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 referenceThe comment highlights a missing
StatusDetailsupdate 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
📒 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 standardizationThe change simplifies the collection timestamp update by using the
SetOrClearCollectionAtmethod withSafeToUTCconversion, 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 addedTwo new intermediate draft statuses have been added:
draft.waiting_for_collectionanddraft.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 testingThe 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 manipulationThe code now no longer sets the
QuantitySnapshotedAtfield 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 possibleInvoiceStatusDraftCollecting: Indicates an invoice actively collecting itemsThis 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
validStatusesslice, 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/lopackage, which provides utility functions likeFromPtrOrused 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
CollectionAttimestamp as the reference point when available, falling back toCreatedAtotherwise. 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
SyncronizeSubscriptionAndInvoiceCustomermethod 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
SyncronizeSubscriptionAndInvoiceCustomermethod 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
SetupApiRequestsTotalFeaturemethod 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
ListInvoicesPendingCollectionthat filters invoices by the newInvoiceStatusDraftWaitingForCollectionstatus 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 processingGood 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 synchronizationThe code now uses
SyncronizeSubscriptionAndInvoiceCustomerwith the option to skip pre-sync invoice creation, which aligns with the new invoice collection flow.
35-35: Updated synchronization function call for canceled subscriptionsConsistently updated to use
SyncronizeSubscriptionAndInvoiceCustomerwith the parameter to skip pre-sync invoice creation.openmeter/billing/service/invoicecalc/collectionat.go (2)
12-31: Well-implemented gathering invoice collection calculationThis function correctly sets the
CollectionAttimestamp for gathering invoices by finding the earliestInvoiceAtamong all invoice lines, ensuring timely collection of invoices as soon as any line is ready for invoicing.
33-59: Comprehensive standard invoice collection timestamp calculationGood implementation that:
- Focuses only on usage-based lines for collection timing
- Falls back to invoice creation time if no usage-based lines exist
- Adds the configured collection interval to the latest usage-based
InvoiceAtThis 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 packageCorrectly updated to use the new
invoicecalcpackage instead of the general billing service package.
327-328: Updated to use new collection timestamp calculationThe code now uses the new
invoicecalc.GatheringInvoiceCollectionAtfunction with proper error handling, aligning with the restructured collection timestamp calculation approach.
1332-1332: Added proper clock reset in test cleanupGood 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 testsTests 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 methodThe code now uses the new
SetupApiRequestsTotalFeaturemethod for consistent feature initialization across tests, improving maintainability.Also applies to: 3832-3833
3900-3906: Testing progressive billing override functionalityGood 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 invoicesThis test nicely validates that
InvoicePendingLinesproperly returnsErrInvoiceCreateNoLineswhen 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 orchestrationSimilar to the other instance, the method call has been updated to use the new
SyncronizeSubscriptionAndInvoiceCustomermethod.test/billing/collection_test.go (1)
72-74: Globalclock.SetTimecan leak between parallel tests
clock.SetTimemutates a package-level (global) clock.
If any other test in the same process also relies onclock.Now()(common across the repo), running the suite with the-parallelflag – or simply executinggo 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
ResetTimemake sure it restoresoldTime, 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.SetTimein 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 calculationsHere we recalculate live gathering invoices using the generic
Calculate(&invoice).
IfCalculateGatheringInvoiceis now responsible for collection-related fields (e.g.CollectionAt), they will stay stale.Please confirm with a quick grep that
CalculateGatheringInvoiceis 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 {
0667bbc to
ffaebcf
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (3)
openmeter/billing/service/invoicestate.go (2)
673-684:⚠️ Potential issue
isReadyForCollectionstill treats missingCollectionAtas “ready”, leading to downstream panicsThe guard returns
truewhenCollectionAtisnil, yetsnapshotQuantityAsNeededdereferences*m.Invoice.CollectionAt.
This was raised earlier and is still unresolved – aniltimestamp should keep the invoice inwaiting_for_collectionor 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 issueNil-pointer dereference in
snapshotQuantityAsNeeded
*m.Invoice.CollectionAtis dereferenced twice without a preceding nil-check.
If the previous comment’s guard is not fixed, this will crash the worker whenCollectionAtis 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 issueData-race & loop-variable capture in goroutines
The goroutine closes over the mutable loop variable
customerIDand the outererrvariable, recreating the race flagged in the previous review. Each goroutine may end up processing the last customer and concurrently writing to the sameerr.-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:AsOfparameter is accepted & validated but never used
CollectCustomerInvoicevalidates thatAsOfis non-zero, yet the value is not passed further (onlyInvoicePendingLinesis 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 adeferimmediately after settingFor consistency and to prevent accidental leakage between sub-tests, consider:
clock.SetTime(periodStart) defer clock.ResetTime() // move immediately after SetTimeThis 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
📒 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
SyncronizeSubscriptionAndInvoiceCustomermethod, 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
SyncronizeSubscriptionAndInvoiceCustomerwith theWithSkipPreSyncInvoiceCreation()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/serviceto the more specificbilling/service/invoicecalcpackage 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.GatheringInvoiceCollectionAtwith 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
InvoicePendingLinesensures 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
SetupApiRequestsTotalFeaturefrom the test suite promotes code reuse and standardizes feature setup across tests.
ffaebcf to
30e0e46
Compare
There was a problem hiding this comment.
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 testabilityThe three anonymous functions for
CreatedEvent,ContinuedEvent, andUpdatedEventare identical apart from the concrete event type used to access theSubscriptionView.
A tiny wrapper such asfunc (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:
- Eliminate the repetition (DRY).
- 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 readInside several
s.Run(...)sub-tests a new variable namedresis declared with:=, shadowing the outercollectionNSResult(res) returned bysetupNS. The same happens withinvoiceand 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
📒 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
4a4fff6 to
110ea0a
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
openmeter/billing/service/invoicestate.go (2)
672-683:⚠️ Potential issueFix potential nil dereference issue in the collection readiness check.
The
isReadyForCollectionmethod incorrectly returnstruewhenCollectionAtisnil, which can lead to downstream nil pointer dereferences insnapshotQuantityAsNeeded. 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 issueAdd nil check for CollectionAt to prevent potential panic.
This method unconditionally dereferences
m.Invoice.CollectionAtin 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
snapshotQuantitymethod likely mutates line quantities, butcalculateInvoiceis executed before snapshotting in theallOfchain. 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
allOfchain 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
📒 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
DraftCreatednow correctly leads toWaitingForCollectionrather than directly to validation, implementing the new collection flow.
82-89: Well-defined collection waiting state.The new
DraftWaitingForCollectionstate properly implements a conditional transition toDraftCollectingbased on collection readiness.
91-101: Good integration of collection into workflow.The
DraftCollectingstate correctly callssnapshotQuantityAsNeededfollowed bycalculateInvoicewhen activated, ensuring quantities are captured before calculations.
104-107: Proper workflow cycle update.The
DraftUpdatingstate now transitions back toDraftWaitingForCollectioninstead 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.
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:
Summary by CodeRabbit
New Features
Bug Fixes
Refactor
Tests
Chores