Skip to content

chore: add lineupdater - #4300

Merged
turip merged 2 commits into
mainfrom
chore/add-lineupdater
May 6, 2026
Merged

turip merged 2 commits into
mainfrom
chore/add-lineupdater

Conversation

@turip

@turip turip commented May 6, 2026 •

Copy link
Copy Markdown
Member

Overview

Copy lineupdater from subscription sync and drop the splitlinegroup handling.

This will be used later to change charges (that's why we are not reusing the previous version, which is on subscription sync granuality).

Notes for reviewer

Summary by CodeRabbit

  • New Features
    • Added an invoice line patching system to create, delete, and update line items across invoice types.
    • Introduced flat-fee per-unit detection, extraction, and update capability for billing lines.
    • Delivered a comprehensive invoice updater that applies patches, validates changes, and logs patch operations.
  • Improvements
    • Pre-fetching of invoices for batch updates for more reliable and efficient per-invoice processing.

@turip
turip requested a review from a team as a code owner May 6, 2026 12:32
@turip turip added the release-note/ignore Ignore this change when generating release notes label May 6, 2026
@coderabbitai

coderabbitai Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 94c24a71-9715-40f3-96d2-01e918eecb63

📥 Commits

Reviewing files that changed from the base of the PR and between 242c0c0 and 5f71636.

📒 Files selected for processing (3)
  • openmeter/billing/charges/invoiceupdater/feehelper.go
  • openmeter/billing/charges/invoiceupdater/invoiceupdate.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/invoiceupdater/invoiceupdate.go

📝 Walkthrough

Walkthrough

Adds an invoice patching system: a Patch abstraction for line operations, flat-fee helpers for per-unit amounts, and an Updater service that parses patches, provisions upcoming lines, fetches invoices, and applies updates to gathering, mutable standard, or immutable invoices with validation and logging.

Changes

Invoice Patching System

Layer / File(s) Summary
Patch Data Structure
openmeter/billing/charges/invoiceupdater/patch.go
Introduces Patch and PatchOperation with constructors and accessors for line_create, line_delete, and line_update payloads and a Log helper.
Fee Utilities
openmeter/billing/charges/invoiceupdater/feehelper.go
Adds IsFlatFee, GetFlatFeePerUnitAmount, and SetFlatFeePerUnitAmount to detect flat-price lines, read per-unit amounts from price metadata, and update flat per-unit amounts using alpacadecimal.Decimal.
Updater Public Surface
openmeter/billing/charges/invoiceupdater/invoiceupdate.go
Adds Updater type, New(...) *Updater, ApplyPatches(...) error, and LogPatches(...) to orchestrate patch application.
Patch Parsing & Provisioning
openmeter/billing/charges/invoiceupdater/invoiceupdate.go
parsePatches aggregates patches by invoice; provisionUpcomingLines groups by currency and provisions pending invoice lines via billing service.
Invoice Fetching / Wiring
openmeter/billing/charges/invoiceupdater/invoiceupdate.go, .../worker/.../invoiceupdate.go
Adds listInvoicesByID to batch-fetch invoices and converts to generic form; caller uses prefetched map and errors if expected invoice missing.
Mutable Invoice Path
openmeter/billing/charges/invoiceupdater/invoiceupdate.go
updateMutableStandardInvoice applies deletions/updates, recalculates quantities, replaces lines, handles empty-invoice deletion and split-group upserts.
Gathering Invoice Path
openmeter/billing/charges/invoiceupdater/invoiceupdate.go
updateGatheringInvoice applies deletions and updates to gathering lines and persists changes.
Immutable Invoice Path & Validation
openmeter/billing/charges/invoiceupdater/invoiceupdate.go
updateImmutableInvoice loads full invoice, validates per-line constraints (flat-fee, service period, quantity), builds/merges validation issues, and upserts issues when changed.
Helpers: Validation & Utilities
openmeter/billing/charges/invoiceupdater/invoiceupdate.go
newValidationIssueOnLine, mergeValidationIssues, isMutableInvoice, isCurrentBillingPeriod, and log-eligibility helpers for dry-run reporting.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Updater
    participant PatchParser
    participant BillingService
    participant InvoiceStore

    Client->>Updater: ApplyPatches(customerID, patches)
    Updater->>PatchParser: parsePatches(patches)
    PatchParser-->>Updater: patchesParsed

    Updater->>BillingService: provisionUpcomingLines(customerID, currencies)
    BillingService-->>Updater: provisioned lines / pending IDs

    Updater->>BillingService: listInvoicesByID(invoiceIDs)
    BillingService-->>Updater: invoices map (by ID)

    Updater->>InvoiceStore: determine invoice type (gathering/standard)
    alt Gathering
        Updater->>InvoiceStore: updateGatheringInvoice(invoiceID, patches)
        InvoiceStore-->>Updater: OK
    else Mutable Standard
        Updater->>InvoiceStore: updateMutableStandardInvoice(invoiceID, patches)
        InvoiceStore->>BillingService: upsertSplitLineGroups(...)
        BillingService-->>InvoiceStore: OK
        InvoiceStore-->>Updater: OK
    else Immutable
        Updater->>InvoiceStore: updateImmutableInvoice(invoiceID, patches)
        InvoiceStore->>InvoiceStore: validate lines, merge validation issues
        InvoiceStore-->>Updater: upserted validation issues (if any)
    end

    Updater-->>Client: result (error or nil)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested labels

area/billing

Suggested reviewers

  • tothandras
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'chore: add lineupdater' is vague and doesn't clearly convey what the lineupdater component does or its purpose, despite being related to the changeset. Consider a more descriptive title like 'chore: add invoice line updater for charge modifications' to better communicate the component's purpose and function.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/add-lineupdater

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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.

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

🧹 Nitpick comments (1)
openmeter/billing/charges/invoiceupdater/invoiceupdate.go (1)

318-321: ⚡ Quick win

return err is always nil here — let's say what we mean.

By the time execution reaches line 320, the outer err from UpdateStandardInvoice was already checked at line 294, and the inner err from DeleteInvoice is shadowed inside the if block (declared with := on line 303). So this is effectively return nil dressed up to look like error propagation. A quick swap makes the control flow obvious.

♻️ Suggested change
-	return err
+	return nil
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/invoiceupdater/invoiceupdate.go` around lines 318 -
321, The final "return err" in UpdateStandardInvoice is always nil because the
inner DeleteInvoice call used ":=" which shadowed the outer err; change the
DeleteInvoice invocation so it assigns to the existing err (use "=" instead of
":=") or simply return the DeleteInvoice error directly (e.g., if err =
i.DeleteInvoice(...); err != nil { return err }) so the function propagates the
actual DeleteInvoice error instead of returning nil.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@openmeter/billing/charges/invoiceupdater/feehelper.go`:
- Line 33: Update the misleading error text in
openmeter/billing/charges/invoiceupdater/feehelper.go where fmt.Errorf("line
misses usage based metadata") is returned alongside alpacadecimal.Zero; change
the message to clearly reference flat-fee metadata (e.g., "line missing flat-fee
metadata" or similar) so it accurately reflects that these helpers are for
flat-fee lines—apply the same replacement to the other fmt.Errorf occurrence in
the same file.

In `@openmeter/billing/charges/invoiceupdater/invoiceupdate.go`:
- Around line 83-86: Remove the dead split-line-group scaffolding: delete the
splitLineGroups field usage (patchesParsed.splitLineGroups and
splitLineGroupPatches), the ApplyPatches call to upsertSplitLineGroups and the
upsertSplitLineGroups method itself, and remove the unused models import if
nothing else references it; search for symbols upsertSplitLineGroups,
splitLineGroups, splitLineGroupPatches and eliminate their declarations/usages
so the file no longer contains unreachable split-line-group handling
scaffolding.
- Around line 415-428: The comparison currently uses
lo.FromPtr(existingLine.UsageBased.Quantity) which treats a nil Quantity as
zero; update the check in the invoice update flow (around SnapshotLineQuantity
call and the existingLine / targetStateWithUpdatedQty variables) to explicitly
treat a nil existingLine.UsageBased.Quantity as a change: first check if
existingLine.UsageBased.Quantity == nil and append the validation issue if so,
otherwise compare the dereferenced value with
targetStateWithUpdatedQty.UsageBased.Quantity (e.g. if existingQty :=
existingLine.UsageBased.Quantity; existingQty == nil ||
!targetStateWithUpdatedQty.UsageBased.Quantity.Equal(*existingQty) {
newValidationIssueOnLine(...) } ), removing lo.FromPtr usage so nil is not
silently coalesced.
- Around line 44-81: Collect all invoice IDs from
patchesParsed.updatedLinesByInvoiceID before the loop, call the billing service
batch fetch (use u.billingService.ListInvoices or ListStandardInvoices with the
IDs filter) to retrieve all invoices in one round-trip, build a map[id]invoice
from the returned slice, and then in the existing loop replace the per-iteration
GetInvoiceById call with a lookup into that map; if an invoice is missing return
an error similar to the current GetInvoiceById error path. Keep the rest of the
logic intact (use invoice.Type(), AsStandardInvoice(), and call
updateGatheringInvoice, updateMutableStandardInvoice, updateImmutableInvoice)
but use the batched-result map instead of calling
u.billingService.GetInvoiceById for each invoice.

---

Nitpick comments:
In `@openmeter/billing/charges/invoiceupdater/invoiceupdate.go`:
- Around line 318-321: The final "return err" in UpdateStandardInvoice is always
nil because the inner DeleteInvoice call used ":=" which shadowed the outer err;
change the DeleteInvoice invocation so it assigns to the existing err (use "="
instead of ":=") or simply return the DeleteInvoice error directly (e.g., if err
= i.DeleteInvoice(...); err != nil { return err }) so the function propagates
the actual DeleteInvoice error instead of returning nil.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 76d409bb-1973-4e07-823f-7d319768eddb

📥 Commits

Reviewing files that changed from the base of the PR and between 80d86ac and 242c0c0.

📒 Files selected for processing (3)
  • openmeter/billing/charges/invoiceupdater/feehelper.go
  • openmeter/billing/charges/invoiceupdater/invoiceupdate.go
  • openmeter/billing/charges/invoiceupdater/patch.go

This branch was previously deployed

1 inactive deployment
dev — 5f71636f Deployed May 6, 2026 by turip via Migration Checks #14134
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants