Skip to content

refactor: use invoicing api for creating upcoming changes - #3773

Merged
turip merged 2 commits into
mainfrom
refactor/use-invoice-upserts-for-new-pending-lines
Jan 13, 2026
Merged

turip merged 2 commits into
mainfrom
refactor/use-invoice-upserts-for-new-pending-lines

Conversation

@turip

@turip turip commented Jan 13, 2026 •

Copy link
Copy Markdown
Member

Overview

To make billing more uniform we should start using the Invoice object to manage specific invoices (we are already doing this on the subscription sync side).

This patch makes sure that we are using the invoicing API for this instead of bypassing it and directly manipulating lines.

Note: no additional tests, as we have ample of tests for this codepath.

Notes for reviewer

Summary by CodeRabbit

  • Refactor
    • Improved invoice line handling for more reliable creation and updates, reducing inconsistencies when adding or modifying lines.
    • Upsert flow streamlined to keep invoice state consistent without extra reloads.
  • Bug Fixes
    • Ensures deleted invoice lines are properly timestamped and handled.
    • Retrieval now reliably includes line items so invoice displays reflect current state.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Pre-generates ULID IDs for pending invoice lines, appends new lines to gathering invoices and updates them in-place (removing reload), maps final lines by those IDs using lo.SliceToMap, expands invoice fetches to include Lines, and timestamps lines when soft-deleting them on invoice deletion.

Changes

Cohort / File(s) Summary
Invoice line handling
openmeter/billing/service/invoiceline.go
Pre-generate ULID IDs for pending lines; switch from upsert path to appending new lines and updating the gathering invoice; remove invoice reload after upsert; derive final selection from map keyed by new line IDs; replace slicesx grouping with lo.SliceToMap; expand fetches to include Lines; add soft-delete timestamping for lines when invoice deleted; add explicit Expand for upsertGatheringInvoiceForCurrency.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant InvoiceService
  participant Repo/DB
  participant Clock

  Caller ->> InvoiceService: Request to create pending invoice lines
  InvoiceService ->> InvoiceService: Pre-generate ULID IDs for lines
  InvoiceService ->> Repo/DB: Fetch/Upsert gathering invoice (Expand Lines)
  InvoiceService ->> InvoiceService: Append new lines to invoice.Lines
  InvoiceService ->> Repo/DB: Update gathering invoice (with new Lines)
  Repo/DB -->> InvoiceService: Updated gathering invoice (with Lines)
  InvoiceService ->> InvoiceService: Map lines by ID (lo.SliceToMap)
  InvoiceService ->> Caller: Return created/selected lines
  alt invoice deleted with remaining lines
    InvoiceService ->> Clock: Now()
    InvoiceService ->> Repo/DB: Timestamp lines as deleted
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • tothandras
  • GAlexIHU
  • chrisgacsal
🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor: use invoicing api for creating upcoming changes' accurately describes the main refactoring change in the PR, which replaces direct invoice line manipulation with the invoicing API for managing pending lines.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/use-invoice-upserts-for-new-pending-lines

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b418f68 and c947935.

📒 Files selected for processing (1)
  • openmeter/billing/service/invoiceline.go
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

⚙️ CodeRabbit configuration file

**/*.go: In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them.

Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks.

Files:

  • openmeter/billing/service/invoiceline.go
🧬 Code graph analysis (1)
openmeter/billing/service/invoiceline.go (5)
openmeter/billing/invoiceline.go (2)
  • Lines (557-557)
  • Line (231-242)
openmeter/billing/invoice.go (1)
  • InvoiceExpand (220-229)
api/api.gen.go (1)
  • InvoiceExpand (4198-4198)
pkg/slicesx/map.go (1)
  • Map (8-21)
pkg/clock/clock.go (1)
  • Now (14-21)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Build
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Code Generators
  • GitHub Check: Test
  • GitHub Check: Analyze (go)
🔇 Additional comments (5)
openmeter/billing/service/invoiceline.go (5)

64-67: Nice approach for pre-generating IDs!

Pre-generating ULIDs to track lines through the create/update flow is a clean solution. This ensures the caller receives the correct lines after the invoice update, without needing to match on other potentially non-unique fields.


118-122: LGTM!

Appending lines directly to the gathering invoice and updating in-place is cleaner than the previous approach. This avoids an extra reload step while maintaining correctness.


139-148: LGTM!

Using lo.SliceToMap for the lookup map is a good choice here - cleaner than manual iteration. The logic correctly extracts only the newly created lines from the updated invoice, ensuring return values have all calculated fields populated.


189-191: LGTM!

Adding Lines: true to the expand is necessary since the code now checks and potentially modifies lines when restoring a deleted invoice. Good catch to ensure the data is available when needed.


233-242: LGTM! Nice edge case handling.

Good catch on this scenario - when restoring a previously deleted gathering invoice, any lines that weren't already deleted should be soft-deleted to prevent stale data from reappearing. The inner if l.DeletedAt == nil check correctly ensures we only timestamp lines that haven't already been deleted.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

To make billing more uniform we should start using the Invoice object
to manage specific invoices (we are already doing this on the subscription
sync side).

This patch makes sure that we are using the invoicing API for this instead
of bypassing it and directly manipulating lines.
@turip
turip force-pushed the refactor/use-invoice-upserts-for-new-pending-lines branch from d9f97cf to b418f68 Compare January 13, 2026 13:12
@turip turip added release-note/ignore Ignore this change when generating release notes area/billing labels Jan 13, 2026
@turip
turip marked this pull request as ready for review January 13, 2026 13:13
@turip
turip requested a review from a team as a code owner January 13, 2026 13:13
chrisgacsal
chrisgacsal previously approved these changes Jan 13, 2026

@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

🧹 Nitpick comments (2)
openmeter/billing/service/invoiceline.go (2)

118-136: Two sequential UpdateInvoice calls - intentional?

I see you're doing:

  1. UpdateInvoice (line 122) to persist the appended lines
  2. CalculateGatheringInvoice (line 129)
  3. UpdateInvoice again (line 133) to persist calculation results

If the calculation doesn't depend on DB-generated values from the first update, you might be able to consolidate this into a single DB round-trip by calculating before the first persist. Not a blocker, but worth considering if this path gets hit frequently.


238-247: Comment could be clearer about the intent.

The current comment says "to prevent them from being associated with the deleted invoice" but we're actually restoring the invoice here (clearing its DeletedAt). The logic is sound - cleaning up stale lines when reusing a previously-deleted gathering invoice - but the explanation is a bit confusing.

📝 Suggested comment clarification
-		// If the invoice was deleted, but has lines, we need to delete those lines to prevent
-		// them from being associated with the deleted invoice.
+		// If the invoice was previously deleted but still has non-deleted lines,
+		// soft-delete them to start fresh when reusing this gathering invoice.
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0531000 and b418f68.

📒 Files selected for processing (1)
  • openmeter/billing/service/invoiceline.go
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

⚙️ CodeRabbit configuration file

**/*.go: In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them.

Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks.

Files:

  • openmeter/billing/service/invoiceline.go
🧬 Code graph analysis (1)
openmeter/billing/service/invoiceline.go (3)
openmeter/billing/invoiceline.go (2)
  • Lines (557-557)
  • Line (231-242)
openmeter/billing/service/lineservice/service.go (2)
  • Lines (211-211)
  • Line (194-209)
openmeter/billing/invoice.go (1)
  • InvoiceExpand (220-229)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: Code Generators
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (5)
openmeter/billing/service/invoiceline.go (5)

8-8: LGTM on the new imports!

Nice choices - ulid/v2 for sortable unique IDs and clock for testable time handling are solid additions.

Also applies to: 15-15


144-153: LGTM on the lo.SliceToMap refactor.

Clean way to map lines by ID for the lookup. The iteration over linesToCreate (line 149) correctly ensures we only return the lines created in this operation.


194-196: Good catch including Lines: true in the expand.

Essential for the new flow - without this, appending to an existing gathering invoice would effectively discard its current lines.


64-66: Nice approach pre-assigning line IDs with ULID.

This makes tracking lines through the create flow much cleaner. Great news on the consistency front too — ulid.Make().String() is the standard pattern across the entire billing service, so you're in good company here. Keeping it uniform with the rest of the codebase.


120-120: No issue here—Append already handles nil safely.

The method has a pointer receiver and defensively calls OrEmpty() to handle uninitialized state, so gatheringInvoice.Lines.Append(...) will work fine even for brand new invoices.

@turip
turip merged commit d73dcff into main Jan 13, 2026
24 checks passed
@turip
turip deleted the refactor/use-invoice-upserts-for-new-pending-lines branch January 13, 2026 15:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants