Skip to content

feat: add gathering/standard invoice update functions - #3860

Merged
turip merged 2 commits into
mainfrom
refactor/update-invoice-type-specific
Feb 12, 2026
Merged

turip merged 2 commits into
mainfrom
refactor/update-invoice-type-specific

Conversation

@turip

@turip turip commented Feb 11, 2026 •

Copy link
Copy Markdown
Member

Overview

Invoice Update has 3 flavors:

  • UpdateGatheringInvoice
  • UpdateStandardInvoice
  • UpdateInvoice: this is only used by web, otherwise in most of the places we know exactly what type of invoice we want to edit

Notes for reviewer

Summary by CodeRabbit

  • New Features

    • Added support for Gathering invoices alongside Standard invoices with type-aware APIs.
    • Introduced generic invoice interfaces for unified access and mutation across invoice types.
    • Added a retrieval endpoint for Gathering invoices by ID.
  • Refactor

    • Reworked invoice update/edit flows to dispatch by invoice type (Standard vs Gathering).
    • Split and clarified line-merge/update paths for each invoice type and updated tests/helpers to the generic model.

@coderabbitai

coderabbitai Bot commented Feb 11, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR splits invoice handling by type (Standard vs Gathering), adds type-aware mapping and update flows, introduces generic invoice/line interfaces, and updates adapters, services, HTTP mapping, and many tests to use the new typed APIs and helpers.

Changes

Cohort / File(s) Summary
Service & core types
openmeter/billing/service.go, openmeter/billing/invoice.go, openmeter/billing/service/*.go, openmeter/billing/stdinvoice.go, openmeter/billing/gatheringinvoice.go
Introduce generic Invoice surface, UpdateInvoice → returns Invoice, add UpdateStandardInvoice/GetGatheringInvoiceById, UpdateStandardInvoiceInput, GetInvoiceType adapter alias and input types, and generic line accessors (SetLines, GetGenericLines, AsGenericInvoice).
Adapter & persistence
openmeter/billing/adapter.go, openmeter/billing/adapter/invoice.go
Add GetInvoiceType to InvoiceAdapter and implement type resolution transactionally.
HTTP mapping & handlers
openmeter/billing/httpdriver/invoice.go, openmeter/billing/httpdriver/invoice_test.go, openmeter/app/custominvoicing/httpdriver/custominvoicing.go
Add MapInvoiceToAPI(ctx, billing.Invoice) dispatcher, MapStandardInvoiceToAPI, wire mapping dispatch across endpoints; update handler edit function signature to accept/return generic billing.Invoice; test and custom-invoicing call sites updated to MapStandardInvoiceToAPI where applicable.
Invoice line merge & mapping
openmeter/billing/httpdriver/invoiceline.go, openmeter/billing/invoiceline.go, openmeter/billing/stdinvoiceline.go, openmeter/billing/gatheringinvoice.go
Split merge/mapping paths for Standard vs Gathering: mergeStandardInvoiceLinesFromAPI, mergeGatheringInvoiceLinesFromAPI, separate builders/mergers and validations; add quantity/accessor and child ID setters; add public helpers for Gathering lines.
Derived equality & helpers
openmeter/billing/derived.gen.go
Refactor internal derived equality helpers and helper signatures used across invoice/line comparisons.
Workers & tests
openmeter/billing/worker/..., test/..., openmeter/server/server_test.go, test/app/stripe/invoice_test.go
Update many tests and worker code to use UpdateStandardInvoice or UpdateGatheringInvoice inputs, switch from InvoiceID() to GetInvoiceID(), migrate fixtures/helpers to GenericInvoiceReader/GenericInvoiceLine, and adapt assertions to new types.
Misc
openmeter/productcatalog/price.go, go.mod
Minor: Price.MarshalJSON receiver changed to value; small manifest updates.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Service
    participant Adapter
    participant DB

    Client->>Service: UpdateInvoice(ctx, UpdateInvoiceInput)
    Service->>Adapter: GetInvoiceType(ctx, invoiceID)
    Adapter->>DB: Query invoice by id/namespace
    DB-->>Adapter: Invoice record (status/type)
    Adapter-->>Service: InvoiceType

    alt Type == Gathering
        Service->>Service: UpdateGatheringInvoice(ctx, EditFn)
        Service->>DB: Apply gathering-specific merge/update
    else Type == Standard
        Service->>Service: UpdateStandardInvoice(ctx, EditFn)
        Service->>DB: Apply standard-specific merge/update
    end

    DB-->>Service: Updated invoice
    Service-->>Client: Return mapped api.Invoice via MapInvoiceToAPI
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

area/billing, release-note/misc

Suggested reviewers

  • tothandras
  • chrisgacsal
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 56.25% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change—adding invoice update functions for both gathering and standard invoice types—and aligns well with the extensive refactoring across the codebase.

✏️ 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/update-invoice-type-specific

No actionable comments were generated in the recent review. 🎉

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


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.

@turip
turip marked this pull request as ready for review February 11, 2026 16:45
@turip
turip requested a review from a team as a code owner February 11, 2026 16:45

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

🤖 Fix all issues with AI agents
In `@openmeter/billing/httpdriver/invoiceline.go`:
- Around line 790-854: mergeGatheringLineFromInvoiceLineReplaceUpdate currently
assigns existing.Price = lo.FromPtr(rateCardParsed.Price) without handling a nil
rateCardParsed.Price, which will overwrite the value with zero instead of
preserving or rejecting it; update the function
mergeGatheringLineFromInvoiceLineReplaceUpdate to check rateCardParsed.Price for
nil and either preserve existing.Price when nil or return a
billing.ValidationError (consistent with
gatheringLineFromInvoiceLineReplaceUpdate behavior), referencing
rateCardParsed.Price and existing.Price to locate the change.

In `@openmeter/billing/service/gatheringinvoice.go`:
- Around line 209-213: GetGatheringInvoiceById is missing input validation like
other methods; call input.Validate() at the start of
Service.GetGatheringInvoiceById and return an empty billing.GatheringInvoice
plus the error if validation fails, before invoking transaction.Run with
s.adapter and s.adapter.GetGatheringInvoiceById, so the method follows the same
validation pattern as ListGatheringInvoices and UpdateGatheringInvoice.

In `@openmeter/billing/service/invoice.go`:
- Around line 820-899: UpdateInvoice ignores input.IncludeDeletedLines so edit
callbacks can't see deleted lines; pass input.IncludeDeletedLines through into
the type-specific update calls by adding IncludeDeletedLines:
input.IncludeDeletedLines to the UpdateGatheringInvoice call
(UpdateGatheringInvoiceInput) and to the UpdateStandardInvoice call
(UpdateStandardInvoiceInput), and also include input.IncludeDeletedLines when
refetching the invoice (e.g., the s.adapter.GetGatheringInvoiceById /
GetStandardInvoiceById call) if those retrieval inputs support that flag so the
returned invoice matches the requested visibility.
🧹 Nitpick comments (4)
openmeter/billing/httpdriver/invoiceline.go (1)

923-968: Gathering line merge flow looks solid, with one note on duplication.

The logic here parallels mergeStandardInvoiceLinesFromAPI closely, which is fine given the different underlying types. The absence of SnapshotLineQuantity calls is correct for gathering invoices since they don't need quantity snapshots.

One thing: the two merge*InvoiceLinesFromAPI functions share the same pattern (group by ID → iterate → create-or-merge → mark deletions). If this pattern grows more complex over time, consider extracting the shared orchestration via generics. Not urgent though — the current approach is clear and type-safe.

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

890-894: Use invoice.Type directly instead of inferring from status.

The invoice entity already stores a Type field (set during creation, validated as immutable). Inferring the type from invoice.Status == billing.StandardInvoiceStatusGathering duplicates that source of truth. Other parts of the codebase use invoice.Type directly (e.g., line 282 in gatheringinvoice.go and line 645 in adapter/invoice.go), so using it here would be more consistent and robust.

test/billing/invoice_test.go (1)

773-782: Add a test for the generic UpdateInvoice dispatcher

Right now the test exercises UpdateStandardInvoice directly, which is great. But the generic UpdateInvoice method—which dispatches to either UpdateStandardInvoice or UpdateGatheringInvoice based on invoice type—doesn't have direct test coverage. This dispatcher has real logic (type checking, EditFn wrapping), so a focused test hitting the StandardInvoice path through UpdateInvoice would help keep the public API from drifting.

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

505-523: Avoid the extra customer override lookup for standard invoices. UpdateInvoice now always fetches overrides, but the standard mapper doesn’t need them; branching by invoice type keeps the standard path lean and saves a DB roundtrip.

💡 Suggested refactor
-	genericInvoice, err := invoice.AsGenericInvoice()
-	if err != nil {
-		return UpdateInvoiceResponse{}, fmt.Errorf("converting invoice to generic invoice: %w", err)
-	}
-
-	// TODO: For the V3 api let's make sure that we don't return gathering invoice customer data (or even gathering invoices)
-	mergedProfile, err := h.service.GetCustomerOverride(ctx, billing.GetCustomerOverrideInput{
-		Customer: genericInvoice.GetCustomerID(),
-		Expand: billing.CustomerOverrideExpand{
-			Customer: true,
-			Apps:     true,
-		},
-	})
-	if err != nil {
-		return UpdateInvoiceResponse{}, fmt.Errorf("failed to get customer override: %w", err)
-	}
-
-	return MapInvoiceToAPI(invoice, mergedProfile.Customer, mergedProfile.MergedProfile)
+	if invoice.Type() == billing.InvoiceTypeStandard {
+		stdInvoice, err := invoice.AsStandardInvoice()
+		if err != nil {
+			return UpdateInvoiceResponse{}, fmt.Errorf("converting invoice to standard invoice: %w", err)
+		}
+
+		return MapStandardInvoiceToAPI(stdInvoice)
+	}
+
+	genericInvoice, err := invoice.AsGenericInvoice()
+	if err != nil {
+		return UpdateInvoiceResponse{}, fmt.Errorf("converting invoice to generic invoice: %w", err)
+	}
+
+	// TODO: For the V3 api let's make sure that we don't return gathering invoice customer data (or even gathering invoices)
+	mergedProfile, err := h.service.GetCustomerOverride(ctx, billing.GetCustomerOverrideInput{
+		Customer: genericInvoice.GetCustomerID(),
+		Expand: billing.CustomerOverrideExpand{
+			Customer: true,
+			Apps:     true,
+		},
+	})
+	if err != nil {
+		return UpdateInvoiceResponse{}, fmt.Errorf("failed to get customer override: %w", err)
+	}
+
+	return MapInvoiceToAPI(invoice, mergedProfile.Customer, mergedProfile.MergedProfile)

Comment thread openmeter/billing/service/invoice.go Resolved
@turip
turip force-pushed the refactor/update-invoice-type-specific branch from 1e38ad7 to 29b59c3 Compare February 12, 2026 09:17
@turip turip added release-note/misc Miscellaneous changes area/billing labels Feb 12, 2026
@turip
turip merged commit c18d674 into main Feb 12, 2026
26 of 28 checks passed
@turip
turip deleted the refactor/update-invoice-type-specific branch February 12, 2026 11:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants