Skip to content

Conversation

@turip
Copy link
Member

@turip turip commented May 23, 2025

Overview

Minor refactor on flat fee line creation.

Summary by CodeRabbit

  • New Features

    • Introduced a streamlined way to create flat fee invoice lines, making invoice line creation more consistent and user-friendly.
  • Refactor

    • Simplified and unified the creation of flat fee invoice lines across the application and tests for improved maintainability and clarity.

No changes to existing functionality or business logic.

@turip turip requested a review from a team as a code owner May 23, 2025 14:04
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 23, 2025

📝 Walkthrough

Walkthrough

This change adds a new input struct and constructor function for creating flat fee invoice lines in a centralized manner. It refactors all existing manual constructions of flat fee invoice lines in production and test code to use this new constructor, improving consistency and reducing explicit field assignments across the codebase.

Changes

Files/Areas Change Summary
openmeter/billing/invoiceline.go Added NewFlatFeeLineInput struct and NewFlatFeeLine constructor function to encapsulate flat fee invoice line creation.
openmeter/notification/internal/rule.go Refactored to replace manual flat fee invoice line struct construction with a call to billing.NewFlatFeeLine using input struct.
test/app/custominvoicing/invocing_test.go Updated tests to use billing.NewFlatFeeLine constructor instead of manual struct literals for flat fee invoice lines.
test/billing/collection_test.go, test/billing/invoice_test.go, test/billing/tax_test.go Refactored tests to use billing.NewFlatFeeLine constructor for flat fee invoice lines, replacing explicit struct initializations.

Possibly related PRs

  • fix: notification issues/test message #2763: Both PRs modify notification event handling and test invoice payload generation, sharing a direct connection through the use and enhancement of billing invoice line creation and simulation in notification internal code.

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
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e83bd74 and 089b21f.

📒 Files selected for processing (6)
  • openmeter/billing/invoiceline.go (1 hunks)
  • openmeter/notification/internal/rule.go (1 hunks)
  • test/app/custominvoicing/invocing_test.go (2 hunks)
  • test/billing/collection_test.go (2 hunks)
  • test/billing/invoice_test.go (3 hunks)
  • test/billing/tax_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • test/app/custominvoicing/invocing_test.go
  • test/billing/collection_test.go
  • openmeter/notification/internal/rule.go
  • test/billing/invoice_test.go
  • openmeter/billing/invoiceline.go
  • test/billing/tax_test.go
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: Lint
  • GitHub Check: Developer environment
  • GitHub Check: Test
  • GitHub Check: Analyze (go)
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@turip turip force-pushed the refactor/flat-fee-line-creation branch from 0f501a8 to e83bd74 Compare May 23, 2025 14:06
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: 0

🔭 Outside diff range comments (1)
test/billing/invoice_test.go (1)

645-667: 🛠️ Refactor suggestion

Complete the refactoring for consistency.

This section still uses manual struct construction while other parts of the file have been refactored to use the new billing.NewLine(billing.NewFlatFeeLineInput{...}) pattern. For consistency with the PR objectives, consider refactoring this to use the new constructor as well.

Apply this diff to maintain consistency:

-					{
-						LineBase: billing.LineBase{
-							Namespace: namespace,
-							Period:    billing.Period{Start: periodStart, End: periodEnd},
-
-							InvoiceAt: line1IssueAt,
-
-							Type:      billing.InvoiceLineTypeFee,
-							ManagedBy: billing.ManuallyManagedLine,
-
-							Name: "Test item1",
-
-							Metadata: map[string]string{
-								"key": "value",
-							},
-						},
-						FlatFee: &billing.FlatFeeLine{
-							PerUnitAmount: alpacadecimal.NewFromFloat(100),
-							Quantity:      alpacadecimal.NewFromFloat(1),
-							Category:      billing.FlatFeeCategoryRegular,
-							PaymentTerm:   productcatalog.InAdvancePaymentTerm,
-						},
-					},
+					billing.NewLine(billing.NewFlatFeeLineInput{
+						Namespace: namespace,
+						Period:    billing.Period{Start: periodStart, End: periodEnd},
+						InvoiceAt: line1IssueAt,
+						ManagedBy: billing.ManuallyManagedLine,
+						Name:      "Test item1",
+						Metadata: map[string]string{
+							"key": "value",
+						},
+						PerUnitAmount: alpacadecimal.NewFromFloat(100),
+						Quantity:      alpacadecimal.NewFromFloat(1),
+						PaymentTerm:   productcatalog.InAdvancePaymentTerm,
+					}),
🧹 Nitpick comments (2)
test/billing/collection_test.go (1)

359-372: Good usage with minor consistency suggestion.

This usage properly includes context-specific fields like Namespace, Currency, and InvoiceID which are appropriate when adding a line to an existing invoice. The new constructor pattern is being used correctly.

Consider adding the ManagedBy field for consistency with other usages, unless the constructor handles this default appropriately.

openmeter/billing/invoiceline.go (1)

591-599: Consider improving the generic type switching approach.

While the generic function works, the current implementation using any() type conversions and runtime type switching feels awkward and loses some type safety benefits of generics.

Consider these alternative approaches:

Option 1: Interface-based approach

+type LineInput interface {
+	NewFlatFeeLineInput
+}
+
-func NewLine[T NewFlatFeeLineInput](input T) *Line {
-	switch any(input).(type) {
-	case NewFlatFeeLineInput:
-		v, _ := any(input).(NewFlatFeeLineInput)
-		return newFlatFeeLine(v)
-	}
-
-	return nil
-}
+func NewLine[T LineInput](input T) *Line {
+	switch v := any(input).(type) {
+	case NewFlatFeeLineInput:
+		return newFlatFeeLine(v)
+	default:
+		return nil
+	}
+}

Option 2: Direct function approach (if only one type is expected)

-func NewLine[T NewFlatFeeLineInput](input T) *Line {
-	switch any(input).(type) {
-	case NewFlatFeeLineInput:
-		v, _ := any(input).(NewFlatFeeLineInput)
-		return newFlatFeeLine(v)
-	}
-
-	return nil
-}
+func NewFlatFeeLine(input NewFlatFeeLineInput) *Line {
+	return newFlatFeeLine(input)
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b8272d9 and e83bd74.

📒 Files selected for processing (6)
  • openmeter/billing/invoiceline.go (1 hunks)
  • openmeter/notification/internal/rule.go (1 hunks)
  • test/app/custominvoicing/invocing_test.go (2 hunks)
  • test/billing/collection_test.go (2 hunks)
  • test/billing/invoice_test.go (3 hunks)
  • test/billing/tax_test.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
test/billing/tax_test.go (2)
openmeter/billing/invoiceline.go (4)
  • NewLine (591-599)
  • NewFlatFeeLineInput (563-589)
  • Period (84-87)
  • ManuallyManagedLine (70-70)
openmeter/productcatalog/price.go (1)
  • InAdvancePaymentTerm (20-20)
openmeter/notification/internal/rule.go (2)
openmeter/billing/invoiceline.go (4)
  • NewLine (591-599)
  • NewFlatFeeLineInput (563-589)
  • ManuallyManagedLine (70-70)
  • Period (84-87)
openmeter/productcatalog/price.go (1)
  • InAdvancePaymentTerm (20-20)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: Test
  • GitHub Check: Quickstart
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: CI
  • GitHub Check: Commit hooks
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (9)
test/billing/tax_test.go (1)

289-303: LGTM! Clean refactoring to use centralized constructor pattern.

The refactoring successfully replaces manual billing.Line struct construction with the new billing.NewLine constructor using NewFlatFeeLineInput. This change:

  • Encapsulates flat fee line creation logic in a single place
  • Reduces boilerplate code and improves maintainability
  • Maintains all the same field values, preserving test behavior
  • Follows a consistent pattern across the codebase

All necessary fields are properly set through the input struct, and the semantic content of the test remains unchanged.

test/app/custominvoicing/invocing_test.go (1)

185-196: LGTM! Consistent application of the new constructor pattern.

Both test methods have been properly refactored to use the new billing.NewLine(billing.NewFlatFeeLineInput{...}) constructor instead of manual struct construction. The changes:

  • Apply the same beneficial refactoring pattern consistently across test methods
  • Maintain identical field values, preserving all test logic and assertions
  • Improve code readability and reduce boilerplate
  • Align with the broader codebase refactoring mentioned in the PR summary

The semantic content of both TestInvoicingFlowHooksEnabled and TestInvoicingFlowPaymentStatusOnly remains unchanged while benefiting from the improved code organization.

Also applies to: 354-365

test/billing/invoice_test.go (3)

141-157: LGTM! Proper usage of the new constructor pattern.

This is a good example of the refactored flat fee line creation using billing.NewLine with billing.NewFlatFeeLineInput. All necessary fields are properly provided and the change improves consistency.


172-183: Verify namespace field consistency.

This usage of the new constructor is missing the Namespace field that was included in the previous usage (lines 141-157). Please verify:

  1. Does the constructor handle namespace defaults appropriately in this context?
  2. Should the namespace field be explicitly provided for consistency?

This inconsistency could lead to unexpected behavior if the namespace isn't properly set.


467-498: LGTM! Consistent usage of the new constructor.

Both instances in TestCreateInvoice properly use the new constructor pattern with all necessary fields including the namespace. The implementation is consistent and follows the refactoring approach correctly.

test/billing/collection_test.go (1)

253-261: Verify field completeness and constructor defaults.

This usage of the new constructor appears to be missing some fields (like Namespace and ManagedBy) that were explicitly provided in other test files. Please verify:

  1. Does the constructor properly handle defaults for these fields in this test context?
  2. Are the defaults appropriate for this test scenario?
  3. Should these fields be explicitly provided for consistency?
openmeter/notification/internal/rule.go (1)

188-206: LGTM! Clean refactoring to use the new factory constructor.

The refactoring successfully replaces manual struct construction with the new billing.NewLine factory function. This approach:

  • Consolidates flat fee line creation logic in one place
  • Automatically handles the Type and Status field defaults
  • Improves code readability and maintainability
  • Reduces boilerplate code

All required fields are properly mapped from the previous manual construction to the new NewFlatFeeLineInput struct.

openmeter/billing/invoiceline.go (2)

562-589: Well-designed input struct for flat fee line creation.

The NewFlatFeeLineInput struct appropriately captures all necessary fields for creating flat fee lines. The field organization is logical and covers all required aspects (identification, timing, billing details, etc.).

Note: The commented TODO about the Category field at line 585 suggests this might need future consideration, but the current hardcoded approach in the constructor is reasonable for now.


601-634: Solid constructor implementation with appropriate defaults.

The newFlatFeeLine function properly initializes all required fields with sensible defaults:

  • ✅ Correctly sets Status to InvoiceLineStatusValid
  • ✅ Properly sets Type to InvoiceLineTypeFee
  • ✅ Uses lo.CoalesceOrEmpty for ManagedBy defaulting to SystemManagedLine
  • ✅ Hardcodes Category to FlatFeeCategoryRegular (consistent with the TODO comment)

The field mapping from input to output is comprehensive and correct.

@turip turip marked this pull request as draft May 23, 2025 14:10
@turip turip added release-note/ignore Ignore this change when generating release notes area/billing labels May 23, 2025
@turip turip force-pushed the refactor/flat-fee-line-creation branch from e83bd74 to 089b21f Compare May 23, 2025 14:12
@turip turip marked this pull request as ready for review May 23, 2025 14:14
@turip turip merged commit e281913 into main May 23, 2025
22 checks passed
@turip turip deleted the refactor/flat-fee-line-creation branch May 23, 2025 14:23
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.

2 participants