Skip to content

fix: invoice app serialization - #2724

Merged
turip merged 1 commit into
mainfrom
chore/invoice-app-serialization
Apr 28, 2025
Merged

turip merged 1 commit into
mainfrom
chore/invoice-app-serialization

Conversation

@turip

@turip turip commented Apr 25, 2025 •

Copy link
Copy Markdown
Member

Overview

Given we should not serialize the App type as it's:

  • not json serializable
  • it has dependencies that might not be initialized

We should rather extract the metadata as contextual information into the event payload.

Summary by CodeRabbit

  • New Features
    • Enhanced invoice event structure to include detailed app base information for tax, payment, and invoicing.
  • Bug Fixes
    • Corrected event metadata to accurately reference nested invoice fields.
  • Tests
    • Added comprehensive tests to verify invoice event creation, serialization, and app base context accuracy.
  • Refactor
    • Improved internal structure and validation of invoice events for greater consistency and reliability.
    • Updated invoice handling to align with the new event invoice structure.

@coderabbitai

coderabbitai Bot commented Apr 25, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The changes refactor the representation of invoice events in the billing system by introducing a new EventInvoice struct that embeds both the original Invoice and a new InvoiceAppBases struct, which holds application base data for tax, payment, and invoicing. Validation methods are added for both new structs. Event creation and metadata handling are updated to accommodate the new structure, including bumping the event version. Downstream usage in the subscription handler is updated to reference the nested Invoice fields. A new test suite is introduced to verify event creation, serialization, and the correctness of embedded app base data.

Changes

Files / Areas Change Summary
openmeter/billing/events.go Refactored EventInvoice from a type alias to a struct containing Invoice and new InvoiceAppBases fields; added validation methods; updated event creation and metadata to use new structure; bumped event version to v2.
openmeter/billing/worker/subscription/handlers.go Updated HandleInvoiceCreation to accept and use the new EventInvoice struct, renaming parameter and updating field references accordingly.
test/billing/event_test.go Added InvoicingEventTestSuite with tests for invoice event creation, JSON serialization, and verification of embedded app base data.

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 ff9a3ba and 3516ced.

📒 Files selected for processing (3)
  • openmeter/billing/events.go (3 hunks)
  • openmeter/billing/worker/subscription/handlers.go (2 hunks)
  • test/billing/event_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • openmeter/billing/worker/subscription/handlers.go
  • test/billing/event_test.go
  • openmeter/billing/events.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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 chore/invoice-app-serialization branch from 0f2894f to 70fce20 Compare April 25, 2025 20:40
@turip turip added release-note/ignore Ignore this change when generating release notes area/billing labels Apr 25, 2025
@turip
turip marked this pull request as ready for review April 25, 2025 20:42
@turip
turip requested a review from a team as a code owner April 25, 2025 20:42
@turip
turip force-pushed the chore/invoice-app-serialization branch from 70fce20 to 9e46b91 Compare April 25, 2025 20:44

@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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 2

🧹 Nitpick comments (1)
openmeter/billing/events.go (1)

32-34: Validation field name inconsistency

The validation error message uses "invocing" which should be updated if the field name is corrected to "Invoicing".

-	if err := a.Invocing.Validate(); err != nil {
-		errs = append(errs, fmt.Errorf("invocing: %w", err))
+	if err := a.Invoicing.Validate(); err != nil {
+		errs = append(errs, fmt.Errorf("invoicing: %w", err))
🛑 Comments failed to post (2)
openmeter/billing/events.go (2)

15-19: ⚠️ Potential issue

New structure to store app base information

The InvoiceAppBases struct is a good approach to extract and store only the necessary app information without serializing the entire App object.

However, there's a typo in the field name: "Invocing" should be "Invoicing".

-	Invocing app.AppBase `json:"invocing"`
+	Invoicing app.AppBase `json:"invoicing"`
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

type InvoiceAppBases struct {
	Tax       app.AppBase `json:"tax"`
	Payment   app.AppBase `json:"payment"`
	Invoicing app.AppBase `json:"invoicing"`
}

67-80: 💡 Verification agent

🧩 Analysis chain

Improved event creation with app base extraction

The function correctly extracts app base information from the invoice workflow apps and includes it in the event.

However, there's an inconsistency between the field name "Invocing" in the struct and "Invoicing" used when extracting the app base.

-			Invocing: invoice.Workflow.Apps.Invoicing.GetAppBase(),
+			Invoicing: invoice.Workflow.Apps.Invoicing.GetAppBase(),

Additionally, the comment on line 68 states "Apps are always present" but there's still a nil check on line 69, which is contradictory.

Please clarify whether apps are always present or if the nil check is necessary.


🏁 Script executed:

#!/bin/bash
set -e

echo "1. Locate InvoiceAppBases definition"
rg -n "type InvoiceAppBases" -A5 .

echo
echo "2. Locate Workflow struct and inspect its Apps field"
rg -n "type Workflow" -A10 .

echo
echo "3. Confirm Apps field type (pointer vs non-pointer)"
rg -n "Apps" -n .

Length of output: 74930


Fix InvoiceAppBases typo & clarify nil check

There are two related issues in openmeter/billing/events.go:

  • The InvoiceAppBases struct defines the field as Invocing (and JSON tag "invocing"), but you’re populating it from invoice.Workflow.Apps.Invoicing.
  • The TODO comment “Apps are always present” contradicts the subsequent if invoice.Workflow.Apps != nil guard.

Please address both:

• Rename the struct field and JSON tag, then update the literal assignment:

--- a/openmeter/billing/events.go
@@ type InvoiceAppBases struct {
-   Invocing app.AppBase `json:"invocing"`
+   Invoicing app.AppBase `json:"invoicing"`
}

...

@@ func EventInvoice(invoice billing.Invoice) EventInvoice {
-       Invocing: invoice.Workflow.Apps.Invoicing.GetAppBase(),
+       Invoicing: invoice.Workflow.Apps.Invoicing.GetAppBase(),

• Decide whether Workflow.Apps is indeed always non-nil. If so, remove the nil check (and/or update the TODO); otherwise, refine the comment to reflect when nil can occur.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

// openmeter/billing/events.go

type InvoiceAppBases struct {
    Tax       app.AppBase `json:"tax"`
    Payment   app.AppBase `json:"payment"`
    Invoicing app.AppBase `json:"invoicing"`
}

func EventInvoice(invoice billing.Invoice) EventInvoice {
    appBases := InvoiceAppBases{}
    // TODO[later]: Apps are always present, so we should only use the struct without a pointer
    if invoice.Workflow.Apps != nil {
        appBases = InvoiceAppBases{
            Tax:       invoice.Workflow.Apps.Tax.GetAppBase(),
            Payment:   invoice.Workflow.Apps.Payment.GetAppBase(),
            Invoicing: invoice.Workflow.Apps.Invoicing.GetAppBase(),
        }
    }

    return EventInvoice{
        Invoice:  payload,
        AppBases: appBases,
    }
}

@turip
turip force-pushed the chore/invoice-app-serialization branch from 9e46b91 to ff9a3ba Compare April 28, 2025 07:13

@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 (4)
openmeter/billing/events.go (4)

15-19: Fix typo in field name: "Invocing" should be "Invoicing"

There's a typo in the field name "Invocing" which should be "Invoicing" to maintain consistency with the usage at line 73 where the app base is extracted from invoice.Workflow.Apps.Invoicing.

type InvoiceAppBases struct {
	Tax      app.AppBase `json:"tax"`
	Payment  app.AppBase `json:"payment"`
-	Invocing app.AppBase `json:"invocing"`
+	Invoicing app.AppBase `json:"invoicing"`
}

32-34: Update field reference to match corrected field name

Update the validation error message to match the corrected field name "Invoicing".

-	if err := a.Invocing.Validate(); err != nil {
-		errs = append(errs, fmt.Errorf("invocing: %w", err))
+	if err := a.Invoicing.Validate(); err != nil {
+		errs = append(errs, fmt.Errorf("invoicing: %w", err))

73-73: Field name mismatch between assignment and struct declaration

There's an inconsistency between the field name in the struct (Invocing) and the source field name (Invoicing). This will work but is confusing. Update this line after fixing the struct field name.

-			Invocing: invoice.Workflow.Apps.Invoicing.GetAppBase(),
+			Invoicing: invoice.Workflow.Apps.Invoicing.GetAppBase(),

68-68: Consider addressing TODO comment in future PR

The TODO comment indicates that Apps are always present and shouldn't need to be a pointer. This seems like a good improvement for a future PR to simplify the code structure.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9e46b91 and ff9a3ba.

📒 Files selected for processing (3)
  • openmeter/billing/events.go (3 hunks)
  • openmeter/billing/worker/subscription/handlers.go (2 hunks)
  • test/billing/event_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/billing/event_test.go
  • openmeter/billing/worker/subscription/handlers.go
⏰ Context from checks skipped due to timeout of 90000ms (14)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
  • GitHub Check: Developer environment
  • GitHub Check: Analyze (actions)
  • GitHub Check: Commit hooks
  • GitHub Check: Test
  • GitHub Check: Migration Checks
  • GitHub Check: Build
  • GitHub Check: Lint
🔇 Additional comments (3)
openmeter/billing/events.go (3)

58-81: LGTM! Good refactoring to avoid serialization issues

The refactoring elegantly solves the serialization issue with App types by:

  1. Clearing the Apps field to avoid circular references
  2. Extracting only the necessary metadata via AppBase
  3. Structuring the event to include both invoice data and app metadata

This approach aligns perfectly with the PR objective of avoiding serialization problems while maintaining necessary contextual information.


95-95: LGTM! Appropriate version bump for structural changes

Good job bumping the event version from "v1" to "v2" to reflect the significant structural changes to the event payload. This ensures consumers are aware of the changed format.


101-102: LGTM! Correctly updated field references

The metadata method references have been properly updated to access fields through the embedded Invoice struct, maintaining the same functionality while working with the new structure.

@turip
turip force-pushed the chore/invoice-app-serialization branch from ff9a3ba to 3516ced Compare April 28, 2025 08:10
@turip
turip merged commit 2e0d1f5 into main Apr 28, 2025
@turip
turip deleted the chore/invoice-app-serialization branch April 28, 2025 08:35
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