Skip to content

Conversation

@turip
Copy link
Member

@turip turip commented Jan 23, 2026

Overview

Validations are moved to the standard line itself, as they are not strictly part of the calculation flow.

Summary by CodeRabbit

  • New Features

    • Added optional selective inclusion of invoice lines by explicit IDs.
  • Bug Fixes

    • Enforced currency consistency between invoice and its lines to prevent mismatches.
    • Added nil checks for required feature meter data to surface missing inputs earlier.
  • Improvements

    • Moved to per-line validation and processing for clearer, earlier error handling and more granular invoice simulation.
    • Simplified internal line processing interfaces for more predictable behavior.
  • Tests

    • Expanded test payloads for usage-based line scenarios.

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 23, 2026

📝 Walkthrough

Walkthrough

Refactors lineservice from stateful Service methods to package-level functions, removes context-based validation and meters.go feature-usage logic, updates invoice/calculator dependencies to drop LineService, and adds cross-line currency consistency validation.

Changes

Cohort / File(s) Summary
Lineservice core
openmeter/billing/service/lineservice/service.go, openmeter/billing/service/lineservice/linebase.go, openmeter/billing/service/lineservice/usagebasedline.go, openmeter/billing/service/lineservice/usagebasedlineflat.go, openmeter/billing/service/lineservice/meters.go (deleted)
Converted Service methods to package functions (FromEntity(s), FromEntities, UpdateTotalsFromDetailedLines), removed line Service receiver and Validate/context-based APIs, changed CanBeInvoicedAsOf and ResolveBillablePeriod signatures to be context-free, and deleted meters.go (feature usage logic removed).
Billing service surface
openmeter/billing/service/service.go, openmeter/billing/service/gatheringinvoicependinglines.go, openmeter/billing/service/stdinvoiceline.go, openmeter/billing/service/invoice.go
Removed Service.lineService field and all per-instance lineService usage; replaced with package-level lineservice functions and per-line validation (line.Validate()); added LinesToInclude field to gather input; added currency checks when moving lines between invoices.
Calculator & invoice calculation
openmeter/billing/service/invoicecalc/calculator.go, openmeter/billing/service/invoicecalc/details.go, openmeter/billing/service/stdinvoicestate.go
Dropped LineService from CalculatorDependencies and removed its import; updated call sites to use lineservice.FromEntities or per-line lineservice.FromEntity and pass only FeatureMeters into calculator flows.
Validation changes
openmeter/billing/stdinvoice.go, openmeter/billing/stdinvoiceline.go, openmeter/billing/service/gatheringinvoicependinglines.go
Added invoice/line currency consistency validation; moved many validations to per-line line.Validate() or inline checks (feature meter presence, detailed line currency, price/period validations); removed context-based Validate methods.
Meters / usage logic removed
openmeter/billing/service/lineservice/meters.go (deleted)
Removed getFeatureUsage input/response types and the Service.getFeatureUsage implementation that queried/aggregated meter data for lines (including split-line handling).
Tests
openmeter/billing/service/lineservice/usagebasedline_test.go
Added internal test struct featureUsageResponse to mirror removed meters.go response shape for tests.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant BillingSvc as Billing Service
  participant LinePkg as lineservice (package)
  participant Calculator
  participant DB
  Client->>BillingSvc: request (recalculate/simulate/create invoice)
  BillingSvc->>BillingSvc: resolve FeatureMeters
  BillingSvc->>LinePkg: FromEntities(inScopeLines, featureMeters)
  LinePkg-->>BillingSvc: Lines (no ctx)
  BillingSvc->>LinePkg: ResolveBillablePeriod(lines, input)
  LinePkg-->>BillingSvc: LinesWithBillablePeriod
  BillingSvc->>Calculator: Calculate(featureMeters, linesWithPeriods)
  Calculator-->>BillingSvc: Calculated invoice/lines
  BillingSvc->>DB: persist invoice and lines
  DB-->>BillingSvc: ack
  BillingSvc-->>Client: response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

kind/refactor, release-note/breaking-change

Suggested reviewers

  • chrisgacsal
  • tothandras
  • gergely-kurucz-konghq
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% 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
Title check ✅ Passed The title 'refactor: simplify line service' directly captures the main objective of this PR, which is a comprehensive refactor to simplify the line service by removing dependencies and moving validations.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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/simplify-lineservice

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 force-pushed the refactor/simplify-lineservice branch from f3a9c0c to 78d5c7a Compare January 27, 2026 15:46
@turip turip force-pushed the refactor/simplify-lineservice branch 3 times, most recently from 5113e3e to 5706397 Compare January 28, 2026 09:19
@turip turip force-pushed the refactor/simplify-lineservice branch from 5706397 to af00cc9 Compare January 28, 2026 19:28
@turip
Copy link
Member Author

turip commented Jan 29, 2026

@coderabbitai help

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 29, 2026

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

CodeRabbit commands

These commands are invoked using PR/Issue 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 evaluate custom pre-merge check --instructions <custom-checks-instructions> --name <custom-checks-title> [--mode <error|warning>] to validate the custom pre-merge checks instructions. Defaults to error when --mode is omitted.
    • @coderabbitai ignore pre-merge checks to override pre-merge checks and get an approval on PR.
    • @coderabbitai run pre-merge checks to run pre-merge checks on the pull request.
  • @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 generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve to resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai generate configuration to create a PR that adds the current resolved configuration as .coderabbit.yaml (or show it if already present).
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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.

Status, support, documentation and community

  • Visit our status page to check the current availability of CodeRabbit.
  • Create a ticket on our support page for assistance with any issues or questions.
  • Visit our documentation site for detailed information on how to use CodeRabbit.
  • Join our Discord community to connect with other users and get help from the community.
  • Follow us on X/Twitter for updates and announcements.

@turip
Copy link
Member Author

turip commented Jan 29, 2026

@coderabbitai full review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 29, 2026

✅ Actions performed

Full review triggered.

@turip turip marked this pull request as ready for review January 29, 2026 12:15
@turip turip requested a review from a team as a code owner January 29, 2026 12:15
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
openmeter/billing/service/gatheringinvoicependinglines.go (3)

200-210: Duplicate nil check for FeatureMeters.

There are two nil checks for FeatureMeters in the same Validate() method - one at lines 200-202 and another at lines 208-210. The error messages are also inconsistent ("cannot be nil" vs "are required").

🧹 Proposed fix to remove duplicate
 	if in.FeatureMeters == nil {
 		return fmt.Errorf("feature meters cannot be nil")
 	}

 	if len(in.InScopeLines) == 0 {
 		return fmt.Errorf("in scope lines must contain at least one line")
 	}

-	if in.FeatureMeters == nil {
-		return fmt.Errorf("feature meters are required")
-	}
-
 	return nil

378-388: Another duplicate nil check for FeatureMeters.

Same issue as in handleInvoicePendingLinesForCurrencyInput.Validate() - duplicate checks with inconsistent messages.

🧹 Proposed fix to remove duplicate
 	if i.FeatureMeters == nil {
 		errs = append(errs, fmt.Errorf("feature meters cannot be nil"))
 	}

 	if i.GatheringInvoice.Lines.IsAbsent() {
 		errs = append(errs, fmt.Errorf("gathering invoice must have lines expanded"))
 	}

-	if i.FeatureMeters == nil {
-		errs = append(errs, fmt.Errorf("feature meters are required"))
-	}
-
 	for _, line := range i.InScopeLines {

633-649: Third duplicate nil check for FeatureMeters.

Same pattern repeating in createStandardInvoiceFromGatheringLinesInput.Validate().

🧹 Proposed fix to remove duplicate
 	if in.FeatureMeters == nil {
 		errs = append(errs, fmt.Errorf("feature meters cannot be nil"))
 	}

 	if len(in.Lines) == 0 {
 		errs = append(errs, fmt.Errorf("lines must contain at least one line"))
 	}

 	for _, line := range in.Lines {
 		if err := line.Validate(); err != nil {
 			errs = append(errs, fmt.Errorf("line[%s]: %w", line.ID, err))
 		}
 	}

-	if in.FeatureMeters == nil {
-		errs = append(errs, fmt.Errorf("feature meters are required"))
-	}
-
 	return errors.Join(errs...)
openmeter/billing/service/invoice.go (1)

153-164: Duplicate nil check for customerProfile.Customer.

There are two identical nil checks at lines 153-155 and 162-164, both returning the same error message.

🧹 Proposed fix to remove duplicate
 	if customerProfile.Customer == nil {
 		return invoice, fmt.Errorf("customer profile is nil")
 	}

 	featureMeters, err := s.resolveFeatureMeters(ctx, invoice.Lines.OrEmpty())
 	if err != nil {
 		return invoice, fmt.Errorf("resolving feature meters: %w", err)
 	}

-	if customerProfile.Customer == nil {
-		return invoice, fmt.Errorf("customer profile is nil")
-	}
-
 	inScopeLines := lo.Filter(invoice.Lines.OrEmpty(), func(line *billing.StandardLine, _ int) bool {
🤖 Fix all issues with AI agents
In `@openmeter/billing/stdinvoiceline.go`:
- Around line 318-342: The code assumes i.UsageBased is non-nil but it’s a
pointer; add a nil-check before calling i.UsageBased.Validate() and before
accessing i.UsageBased.Price.Type(): if i.UsageBased == nil append a validation
error (e.g., a ValidationError indicating a missing UsageBased) and skip the
usage-based-specific checks, otherwise call i.UsageBased.Validate(), perform the
Price.Type() branching and period/invoice checks, and only call
RateCardDiscounts.ValidateForPrice with i.UsageBased.Price when UsageBased is
non-nil; update references around Validate, Price.Type(), and
RateCardDiscounts.ValidateForPrice accordingly.
🧹 Nitpick comments (2)
openmeter/billing/service/lineservice/service.go (1)

59-60: Minor typo in comment.

Small nit: "syncorinzed" → "synchronized".

📝 Suggested fix
-	// The usageBasedLine will never be syncorinzed directly to stripe or other apps, only the detailed lines.
+	// The usageBasedLine will never be synchronized directly to stripe or other apps, only the detailed lines.
openmeter/billing/stdinvoice.go (1)

294-300: Currency validation is a nice addition, but consider consistent error wrapping.

The cross-line currency consistency check is great for catching mismatches early. However, the error format differs from other validations in this method. Other errors use ValidationWithFieldPrefix, but this one uses a direct fmt.Errorf.

For consistency, consider:

♻️ Suggested refactor for consistent error formatting
 	if i.Lines.IsPresent() {
 		for _, line := range i.Lines.OrEmpty() {
 			if line.Currency != i.Currency {
-				outErr = errors.Join(outErr, fmt.Errorf("line[%s]: currency[%s] is not equal to invoice currency[%s]", line.ID, line.Currency, i.Currency))
+				outErr = errors.Join(outErr, ValidationWithFieldPrefix(fmt.Sprintf("line[%s]", line.ID),
+					fmt.Errorf("currency[%s] is not equal to invoice currency[%s]", line.Currency, i.Currency)))
 			}
 		}
 	}

@turip turip added release-note/misc Miscellaneous changes area/billing labels Jan 29, 2026
@turip turip enabled auto-merge (squash) January 29, 2026 13:02
@turip turip merged commit b33b7b1 into main Jan 29, 2026
25 checks passed
@turip turip deleted the refactor/simplify-lineservice branch January 29, 2026 13:02
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.

3 participants