Skip to content

refactor: simplify create pending lines - #2836

Merged
turip merged 3 commits into
mainfrom
refactor/simplify-create-pending-lines
May 16, 2025
Merged

turip merged 3 commits into
mainfrom
refactor/simplify-create-pending-lines

Conversation

@turip

@turip turip commented May 16, 2025 •

Copy link
Copy Markdown
Member

Overview

Remove support for multi customer, multi currency pending line creation as:

  • It simplifies pending line creation (so that later, for the collect on draft work we can reuse more code)
  • We never do multi currency, multi customer creates
  • This creates a new API /api/v1/billing/customers/{customerId}/invoices/pending-lines which allows us to later have an API for pending charges and hide some of the gathering invoice complexity

Summary by CodeRabbit

  • New Features

    • Introduced customer-specific endpoints for creating pending invoice line items and simulating invoices.
    • Restored invoice listing endpoint with filtering and pagination capabilities.
  • Improvements

    • Enhanced request and response models to include explicit customer and currency context.
    • Clearer distinction between creating pending invoice lines and invoice simulation.
    • Simplified invoice creation process with improved validation, error handling, and event publishing.
  • Bug Fixes

    • Resolved issues around currency mismatches and handling of empty invoices during creation.
  • Documentation

    • Updated API specifications and client schemas to reflect new endpoints, data models, and operation changes.
  • Tests

    • Updated test suites to accommodate revised API signatures and data structures for invoice line creation and simulation.

@coderabbitai

coderabbitai Bot commented May 16, 2025 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

The changes reorganize and enhance the billing API's handling of pending invoice lines. The creation of pending invoice lines is now explicitly scoped to a customer and currency, with new request and response models introduced. Endpoints and schemas are updated to reflect this structure, and corresponding service, handler, and test code are refactored to use the new types and logic. Validation and transaction logic are improved, and all affected tests are updated for compatibility.

Changes

Files/Paths Change Summary
api/openapi.cloud.yaml, api/openapi.yaml OpenAPI specifications reorganized: pending invoice line creation is now customer-scoped with new endpoints, request/response schemas, and explicit currency support. Simulation and listing endpoints updated or restored. Old endpoints and schemas deprecated or removed.
api/spec/src/billing/invoices.tsp, api/spec/src/cloud/main.tsp API interface and route structure refactored: pending line creation moved to a customer-specific interface and route; simulation and creation consolidated; new models for input and response added.
api/spec/src/billing/invoices/invoice.tsp Pending line creation models updated: currency and customerId fields removed from line creation types; omitted properties expanded for clarity.
openmeter/billing/invoiceline.go Core logic refactored: new input/output structs for pending line creation, validation updated, stricter constraints enforced, and legacy wrappers removed.
openmeter/billing/service.go, openmeter/billing/service/invoiceline.go Service interface and implementation updated: new input/output types, logic streamlined for customer/currency scoping, transaction and event handling improved, and helper methods simplified.
openmeter/billing/httpdriver/invoiceline.go HTTP handler refactored: new request/response types, explicit customer context, improved mapping and error handling, and handler signature updated.
openmeter/server/router/billing.go Router updated: route and handler signature changed to require customer ID for pending line creation.
openmeter/server/server_test.go Noop billing service updated to match new pending line creation interface and return type.
openmeter/billing/worker/subscription/sync.go Subscription worker updated: line mapping simplified, explicit customer/currency in service call, old wrappers removed.
openmeter/subscription/subscription.go Method GetCustomerID() added to Subscription struct for constructing customer ID.
test/app/custominvoicing/invocing_test.go, test/app/stripe/invoice_test.go, test/billing/discount_test.go, test/billing/invoice_test.go, test/billing/suite.go, test/billing/tax_test.go All affected tests updated: use new input/output structs for pending invoice line creation, remove legacy wrappers, explicitly set customer and currency, and update assertions to match new result shapes.
api/client/javascript/src/client/billing.ts, api/client/javascript/src/client/schemas.ts JavaScript client updated: method signatures and schema definitions changed to reflect new customer-scoped pending line creation endpoint and new request/response types; old endpoints and schemas removed or replaced.

Possibly related PRs

  • refactor: simplify create pending lines #2836: Implements the same core refactor of renaming and repurposing the /api/v1/billing/customers/{customerId}/invoices/simulate endpoint to /api/v1/billing/customers/{customerId}/invoices/pending-lines with new request and response schemas, reorganizing billing API endpoints, service, and client code accordingly.

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

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 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 0c6eaf5 and 80232a2.

📒 Files selected for processing (6)
  • api/openapi.cloud.yaml (8 hunks)
  • api/openapi.yaml (8 hunks)
  • api/spec/src/billing/invoices.tsp (4 hunks)
  • openmeter/billing/service.go (1 hunks)
  • openmeter/billing/service/invoiceline.go (6 hunks)
  • openmeter/server/server_test.go (1 hunks)
✨ 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/simplify-create-pending-lines branch from 22cfa70 to e8ba10c Compare May 16, 2025 16:55
@turip
turip force-pushed the refactor/simplify-create-pending-lines branch from e8ba10c to 0c0105e Compare May 16, 2025 17:13
@turip
turip marked this pull request as ready for review May 16, 2025 17:13
@turip
turip requested a review from a team as a code owner May 16, 2025 17:13
@turip
turip requested a review from tothandras May 16, 2025 17:14

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

🔭 Outside diff range comments (1)
openmeter/billing/service/invoiceline.go (1)

240-248: 🛠️ Refactor suggestion

Restoring the wrong invoice when both deleted & active gathering invoices exist

pendingInvoiceList is ordered by createdAt ASC; picking Items[0] may revive an older, deleted invoice even when a newer active gathering invoice already exists for the same customer/currency.

Consider:

  1. Filter out deleted invoices first; or
  2. Sort DESC and choose the newest; or
  3. Prefer the first non-deleted invoice.

This prevents accidental resurrection of sunset invoices.

🧹 Nitpick comments (12)
openmeter/billing/worker/subscription/sync.go (1)

533-539: Improved API call with explicit customer context

The code now properly uses CreatePendingInvoiceLinesInput with explicit Customer and Currency fields, and includes a clean filter for nil lines. This makes the customer and currency context explicit and centralizes it at the request level.

Consider adding a brief comment explaining why some lines might be nil and need filtering, as this would help future maintainers understand the business logic.

  Lines: lo.Filter(newLines, func(l *billing.Line, _ int) bool {
+   // Filter out nil lines - these occur when the line has zero amount or when line generation has failed
    return l != nil
  }),
openmeter/billing/service/invoiceline.go (1)

23-28: Redundant mutation of line namespace / status / currency

Each input line is mutated twice – once before validation and again inside the lo.Map call.
The second assignment is sufficient because nothing touches the lines between these two points.

Removing the first loop avoids an extra pass and keeps mutation in one place:

-	for i := range input.Lines {
-		input.Lines[i].Namespace = input.Customer.Namespace
-		input.Lines[i].Status = billing.InvoiceLineStatusValid
-		input.Lines[i].Currency = input.Currency
-	}

Also applies to: 65-70

openmeter/billing/httpdriver/invoiceline.go (2)

30-33: Use strong type for CustomerID parameter

CreatePendingLineParams.CustomerID is a raw string; downstream you immediately wrap it in customer.CustomerID{ … }.
Accepting it as ulid.ULID (or at least validating format) at the handler boundary prevents malformed IDs from reaching the service layer.

- CustomerID string
+ CustomerID ulid.ULID

41-44: WithOperationName is now misleading

The handler registers "CreateInvoiceLineByCustomer" even though the route & spec were renamed to pending-lines.
Renaming keeps tracing / metrics consistent.

- httptransport.WithOperationName("CreateInvoiceLineByCustomer"),
+ httptransport.WithOperationName("CreatePendingInvoiceLine"),
api/openapi.cloud.yaml (3)

1531-1536: HTTP 201 usage for creation is appropriate
The switch to 201 Created and the new response schema reference is correct and follows REST conventions. Consider adding a Location header to point to the created resource.


1586-1604: Customer-scope simulation endpoint is well-defined
The POST /api/v1/billing/customers/{customerId}/invoices/simulate endpoint correctly scopes simulation to a customer and returns the Invoice schema. To reduce repetition, you could extract the customerId parameter into components/parameters and reference it here.


1752-1756: Add description for 201 response
The 201 response schema is defined but lacks a description field. Please include a brief description, for example:

'201':
  description: An array of created invoices.
  content:
    application/json:
      schema:
        type: array
        items:
          $ref: '#/components/schemas/Invoice'
api/openapi.yaml (5)

1530-1536: Include a Location header in 201 response

For resource creation, it is best practice to return a Location header pointing to the newly created resource. Please add:

 '201':
   description: The request has succeeded and a new resource has been created as a result.
+  headers:
+    Location:
+      description: URL of the newly created invoice
+      schema:
+        type: string
+      example: '/api/v1/billing/customers/{customerId}/invoices/{invoiceId}'
   content:
     application/json:
       schema:
         $ref: '#/components/schemas/InvoicePendingLineCreateResponse'

1662-1687: Align listInvoices description with capabilities

The GET /api/v1/billing/invoices endpoint summary is “List invoices” but the description suggests it only lists invoices for a specific customer, even though a customers query parameter exists. To avoid confusion, update the description to reflect that invoices can be filtered by customer and other criteria:

-summary: List invoices
-description: List invoices for a specific customer
+summary: List invoices
+description: List invoices with optional filters (e.g., by customer, status, date range)

1728-1745: Refine invoicePendingLinesAction path and cleanup parameters

The path /invoices/invoice is ambiguous and the empty parameters: [] block can be removed. Consider renaming this endpoint to be more RESTful (e.g., /invoices/actions/pending-lines) and drop the empty array:

-/api/v1/billing/invoices/invoice:
-  post:
-    parameters: []
+ /api/v1/billing/invoices/actions/pending-lines:
+  post:

16491-16506: Add a minimum item constraint for lines array

In the InvoicePendingLineCreateInput schema, the lines array is required but can be empty. To guard against empty payloads, consider adding minItems: 1:

   lines:
     type: array
+    minItems: 1
     items:
       $ref: '#/components/schemas/InvoicePendingLineCreate'
     description: The lines to be created.

16507-16530: Provide example values for the create response

Adding an example block to InvoicePendingLineCreateResponse will help clients understand the payload structure. For instance:

InvoicePendingLineCreateResponse:
  example:
    lines:
      - id: "01G65Z755AFWAKHE12NY0CQ9FH"
        description: "One-time setup fee"
        amount: 100
    invoice:
      id: "01G65Z755AFWAKHE12NY0CQ9FH"
      total: 100
      status: "pending"
    isInvoiceNew: true
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d312570 and 0c0105e.

📒 Files selected for processing (19)
  • api/openapi.cloud.yaml (8 hunks)
  • api/openapi.yaml (8 hunks)
  • api/spec/src/billing/invoices.tsp (4 hunks)
  • api/spec/src/billing/invoices/invoice.tsp (2 hunks)
  • api/spec/src/cloud/main.tsp (1 hunks)
  • openmeter/billing/httpdriver/invoiceline.go (6 hunks)
  • openmeter/billing/invoiceline.go (2 hunks)
  • openmeter/billing/service.go (1 hunks)
  • openmeter/billing/service/invoiceline.go (4 hunks)
  • openmeter/billing/worker/subscription/sync.go (1 hunks)
  • openmeter/server/router/billing.go (1 hunks)
  • openmeter/server/server_test.go (1 hunks)
  • openmeter/subscription/subscription.go (2 hunks)
  • test/app/custominvoicing/invocing_test.go (2 hunks)
  • test/app/stripe/invoice_test.go (2 hunks)
  • test/billing/discount_test.go (2 hunks)
  • test/billing/invoice_test.go (11 hunks)
  • test/billing/suite.go (1 hunks)
  • test/billing/tax_test.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
openmeter/billing/service.go (1)
openmeter/billing/invoiceline.go (2)
  • CreatePendingInvoiceLinesInput (770-775)
  • CreatePendingInvoiceLinesResult (812-816)
openmeter/server/router/billing.go (2)
openmeter/server/router/router.go (1)
  • Router (208-232)
openmeter/billing/httpdriver/invoiceline.go (1)
  • CreatePendingLineParams (30-32)
openmeter/server/server_test.go (1)
openmeter/billing/invoiceline.go (2)
  • CreatePendingInvoiceLinesInput (770-775)
  • CreatePendingInvoiceLinesResult (812-816)
openmeter/billing/service/invoiceline.go (11)
openmeter/billing/service/lineservice/service.go (3)
  • Service (22-24)
  • Lines (174-174)
  • Line (157-172)
openmeter/billing/service/service.go (1)
  • Service (23-38)
openmeter/billing/invoiceline.go (5)
  • CreatePendingInvoiceLinesInput (770-775)
  • CreatePendingInvoiceLinesResult (812-816)
  • InvoiceLineStatusValid (47-47)
  • Line (280-294)
  • UpsertInvoiceLinesAdapterInput (818-821)
api/api.gen.go (5)
  • Customer (2129-2176)
  • InvoiceLineStatusValid (406-406)
  • Currency (1866-1878)
  • ValidationError (6969-6978)
  • Invoice (3300-3411)
openmeter/customer/customer.go (1)
  • Customer (15-23)
openmeter/billing/errors.go (1)
  • ValidationError (119-119)
openmeter/billing/customeroverride.go (3)
  • GetCustomerOverrideInput (165-168)
  • CustomerOverrideExpand (259-265)
  • CustomerOverrideWithDetails (216-223)
openmeter/billing/invoice.go (6)
  • Invoice (330-341)
  • InvoiceID (207-207)
  • GetInvoiceByIdInput (535-538)
  • InvoiceExpandAll (225-230)
  • DeleteInvoicesAdapterInput (570-570)
  • ListInvoicesInput (634-672)
pkg/slicesx/map.go (1)
  • Map (6-19)
openmeter/billing/service/collectionat.go (1)
  • UpdateInvoiceCollectionAt (15-40)
openmeter/billing/events.go (1)
  • NewInvoiceCreatedEvent (97-104)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Test
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Analyze (go)
🔇 Additional comments (38)
openmeter/subscription/subscription.go (1)

75-80: Clean implementation of customer ID getter

The addition of the GetCustomerID() method provides a convenient way to construct a typed customer.CustomerID struct from the subscription data. This supports the broader refactoring effort to simplify the pending line creation process by using consistent customer ID representation across the system.

openmeter/server/router/billing.go (1)

128-134: API route updated to align with customer-scoped endpoint pattern

The endpoint for creating pending invoice lines has been updated to follow the customer-scoped pattern, which aligns with the PR objective of simplifying pending line creation and supporting future enhancements.

The route change from /api/v1/billing/invoices/lines to /api/v1/billing/customers/{customerId}/pending-lines makes the API more RESTful by explicitly scoping operations to a customer.

openmeter/billing/service.go (1)

43-43: Method signature updated to support simplified pending line creation

The CreatePendingInvoiceLines method signature has been updated to accept a CreatePendingInvoiceLinesInput struct (which contains explicit Customer and Currency fields) and return a more informative CreatePendingInvoiceLinesResult structure.

This change supports the simplified approach to pending line creation by making the customer and currency context explicit at the input level, rather than embedded within individual line items.

api/spec/src/billing/invoices/invoice.tsp (2)

486-486: Updated property omission to support customer-scoped endpoint

The currency property has been added to the list of omitted properties for the InvoiceUsageBasedPendingLineCreate model, which aligns with the refactoring to move currency specification to the parent request structure rather than individual line items.

This change supports the simplified approach where currency is specified once at the request level for all pending lines.


498-499: Updated property omission to support customer-scoped endpoint

Similar to the usage-based model, the currency property has been added to the list of omitted properties for the InvoiceFlatFeePendingLineCreate model. This ensures consistency in how currency is specified across different types of pending lines.

This change maintains consistency with the refactoring pattern applied throughout the codebase.

openmeter/server/server_test.go (1)

1401-1402: Method signature updated to match the new billing service interface

The CreatePendingInvoiceLines method has been correctly updated to reflect the new input and output types. The method now accepts a structured CreatePendingInvoiceLinesInput with explicit customer and currency fields, and returns a structured CreatePendingInvoiceLinesResult that encapsulates created lines and invoice information.

api/spec/src/cloud/main.tsp (1)

213-216: Interface renamed to reflect expanded functionality

The interface has been appropriately renamed from InvoiceSimulationEndpoints to CustomerInvoiceEndpoints to reflect its broader purpose. The route path has also been updated from .../invoices/simulate to .../invoices, indicating this endpoint now handles more general invoice operations. This aligns with the PR objective of simplifying and reorganizing the billing API.

test/billing/tax_test.go (5)

214-219: Input structure updated to use explicit customer and currency fields

The test has been correctly updated to use the new CreatePendingInvoiceLinesInput structure with explicit Customer and Currency fields at the top level, aligning with the simplified API design that scopes pending line creation to a single customer and currency.


220-246: Line structure flattened and simplified

The line structure has been properly refactored to use direct field initialization instead of nested wrappers. This simplification improves code readability while maintaining all the necessary information like tax configuration and metadata.


252-253: Updated result access pattern

The assertion now correctly accesses the lines via the res.Lines field of the structured result, reflecting the new return type.


284-312: Helper method updated to use the new API structure

The generateDraftInvoice helper method has been properly updated to use the new input structure with explicit customer and currency fields, maintaining consistency throughout the test file.


316-317: Result assertion pattern updated consistently

The assertion pattern has been updated consistently to access lines via the structured result's Lines field.

test/billing/discount_test.go (4)

94-126: Input structure updated for discount tests

The discount tests have been correctly updated to use the new CreatePendingInvoiceLinesInput structure with explicit customer and currency fields, maintaining consistency with the simplified API design.


128-133: Result access pattern updated for correlation ID tests

The code now correctly accesses the discount information through the structured result's Lines field, demonstrating proper adaptation to the API changes while preserving the test's behavior.


287-320: Usage discount test updated with new API structure

The usage discount test case has been properly updated to use the new input structure, maintaining the same test logic while adapting to the API changes.


324-326: Correlation ID check updated for new result structure

The correlation ID check logic has been correctly updated to access fields through the structured result's Lines field, preserving the test behavior while adapting to the API changes.

test/billing/suite.go (2)

326-375: Properly refactored test helper to use the new API structure

The refactoring correctly implements the new customer-scoped approach by:

  1. Using CreatePendingInvoiceLinesInput with explicit Customer and Currency fields
  2. Replacing the previous LineWithCustomer wrapper with direct *billing.Line instances
  3. Maintaining all required line details while simplifying the structure

This refactoring aligns with the new API design where customer and currency context is centralized at the request level rather than duplicated in each line.


378-380: Updated result access to match new return type

The code now correctly accesses pending lines via res.Lines property instead of directly on the result, matching the new CreatePendingInvoiceLinesResult return type.

test/app/stripe/invoice_test.go (2)

298-301: Properly updated test to use the new customer-scoped API structure

The test now correctly uses CreatePendingInvoiceLinesInput with explicit Customer and Currency fields at the top level, aligning with the refactored billing API.


447-447: Correctly adjusted assertion to use new result structure

The assertion now correctly checks pendingLines.Lines instead of the previous direct slice, matching the new CreatePendingInvoiceLinesResult return type.

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

181-184: Customer-scoped API structure correctly implemented

The test now properly uses CreatePendingInvoiceLinesInput with explicit Customer and Currency fields at the top level, aligning with the refactored billing API.

openmeter/billing/worker/subscription/sync.go (1)

520-532: Simplified line creation in subscription sync logic

The subscription synchronization logic now correctly maps to *billing.Line pointers directly, removing the previous LineWithCustomer wrapper structure. This aligns with the new API design while maintaining the same business logic.

openmeter/billing/invoiceline.go (3)

770-775: Well-structured refactoring with explicit scoping.

The refactoring from the previous CreateInvoiceLinesInput to CreatePendingInvoiceLinesInput improves clarity by making customer and currency parameters explicit. This aligns with the PR objective to simplify the pending line creation process by moving away from multi-customer, multi-currency scenarios.


777-809: Thorough validation logic for the new input structure.

The validation logic has been updated to properly validate the customer ID and currency while ensuring that pending lines don't have an invoice ID, children, or a parent line ID. This enforces the constraints needed for the simplified pending line creation flow.


812-816: Good addition of a structured result type.

The new CreatePendingInvoiceLinesResult struct provides more context to the caller about what happened during the operation, including whether a new invoice was created. This enhancement will make it easier for consumers of this API to handle different scenarios.

test/billing/invoice_test.go (9)

135-171: Tests properly updated to use the new API structure.

The test code has been correctly refactored to use the new CreatePendingInvoiceLinesInput structure with explicit Customer and Currency fields, rather than the previous approach with LineWithCustomer. The assertions properly check the returned Lines field from the result.


172-232: Good coverage of multiple currency scenarios.

The test creates pending lines with different currencies (USD and HUF) to verify that separate gathering invoices are created for each currency. This ensures the refactored API maintains proper currency isolation while simplifying the API.


473-527: Comprehensive test for invoice creation flow.

This test case thoroughly validates that invoice creation works correctly with the refactored API, covering both the happy path and edge cases like line identification and invoice ID management.


661-695: Proper testing of gathering invoice reuse.

This test verifies that when staging more lines, the old gathering invoice gets reused appropriately, ensuring that the refactored API maintains backward compatibility in terms of behavioral expectations.


1491-1605: Thorough testing of progressive billing scenarios.

The test code extensively covers complex scenarios like progressive billing with different price types, ensuring the refactored API continues to support all the required billing use cases.


2394-2440: Good test coverage for tiered pricing with graduated flat fees.

This test case verifies that the refactored API correctly handles complex pricing scenarios like tiered pricing with both per-unit and flat components, ensuring billing accuracy is maintained.


2727-2838: Comprehensive test for non-progressive invoicing scenarios.

The test validates that the refactored API properly handles non-progressive invoicing with various pricing models, ensuring that all billing scenarios continue to work correctly.


3435-3583: Edge case testing for zero-price invoicing.

The test verifies that the refactored API correctly handles the edge case of empty invoices with zero pricing, ensuring that validation logic doesn't reject valid zero-amount billing scenarios.


3560-3583: Verify consistent handling of empty periods and zero amounts.

The test cases for zero-amount and zero-price invoicing ensure that the refactored API maintains consistent behavior even in edge cases, which is important for billing systems to handle all possible customer scenarios.

api/spec/src/billing/invoices.tsp (2)

220-234: Potential duplicate operationId – confirm uniqueness across the spec

@operationId("createPendingInvoiceLine") was already used by the (now-removed) un-scoped “POST /billing/invoices/lines” endpoint.
If that old path is still present in downstream OpenAPI docs or client code-gen, the clash will break generation.

Please grep the whole spec and confirm this is the only remaining occurrence, or rename it (e.g. createCustomerPendingInvoiceLine).


658-671: Check for field duplication between request-level and per-line currency

InvoicePendingLineCreateInput carries a top-level mandatory currency, but the referenced Invoice.InvoicePendingLineCreate model historically also contained its own currency.
If the nested model has not been cleaned up, client requests will be forced to send the same value twice and the service could receive conflicting data.

Please verify the nested model and, if the field is still present, deprecate / remove it or document precedence clearly.

api/openapi.yaml (2)

1751-1755: Responses correctly return an array of invoices

The response schema for the invoicePendingLinesAction operation correctly defines a type: array of Invoice objects. LGTM.


1801-1804: ⚠️ Potential issue

Reorder requestBody before responses

OpenAPI requires requestBody to come before responses. The InvoicePendingLinesActionInput schema is currently placed after the responses section. Please move it above:

-  responses:
-    '201':
-      description: ...
-  content:
-    application/json:
-      schema:
-        $ref: '#/components/schemas/InvoicePendingLinesActionInput'
+  requestBody:
+    required: true
+    content:
+      application/json:
+        schema:
+          $ref: '#/components/schemas/InvoicePendingLinesActionInput'
+  responses:
+    '201':
+      description: ...

Likely an incorrect or invalid review comment.

Comment thread api/openapi.cloud.yaml Resolved
Comment thread api/openapi.cloud.yaml Resolved
Comment thread api/openapi.cloud.yaml Resolved
Comment thread api/openapi.cloud.yaml Resolved
Comment thread api/openapi.cloud.yaml Resolved
Comment thread api/openapi.yaml Resolved
Comment thread api/openapi.yaml Resolved
Comment thread api/openapi.yaml Resolved
Comment thread api/openapi.yaml Resolved

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

🔭 Outside diff range comments (1)
api/client/javascript/src/client/schemas.ts (1)

12923-12931: 🛠️ Refactor suggestion

Same issue in the operation object – customerId missing again

The createPendingInvoiceLine operation repeats the omission of the mandatory customerId path param (path?: never). The fix mirrors the previous snippet:

-      path?: never
+      path: {
+        customerId: string
+      }

Without this, client code can neither type-safely nor ergonomically call the endpoint.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0c0105e and 0c6eaf5.

📒 Files selected for processing (2)
  • api/client/javascript/src/client/billing.ts (2 hunks)
  • api/client/javascript/src/client/schemas.ts (10 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
api/client/javascript/src/client/schemas.ts (2)
api/api.gen.go (2)
  • InvoicePendingLineCreateInput (3982-3988)
  • InvoicePendingLineCreateResponse (3991-4000)
api/client/go/client.gen.go (2)
  • InvoicePendingLineCreateInput (3577-3583)
  • InvoicePendingLineCreateResponse (3586-3595)
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: Artifacts / Container image
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: Lint
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Test
  • GitHub Check: Migration Checks
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (7)
api/client/javascript/src/client/billing.ts (4)

7-7: Import type correctly updated to match the new API model.

The import has been updated from InvoicePendingLineCreate to InvoicePendingLineCreateInput to reflect the new type used in the refactored API, which aligns with the simplification goal of the PR.


364-372: JSDoc documentation clearly explains the new customer-scoped behavior.

The enhanced JSDoc properly documents the new customer-scoped approach and provides clear explanations about when new gathering invoices will be created. This documentation is crucial for developers to understand the simplified behavior.


377-380: Method signature properly updated for customer-scoped API.

The method signature has been correctly updated to:

  1. Accept a customerId parameter (required for the new customer-scoped endpoint)
  2. Change the body parameter from an array to a single InvoicePendingLineCreateInput object

This change aligns with the PR objective of simplifying the creation of pending lines by removing multi-customer support.


382-389:

Details

❓ Verification inconclusive

API endpoint correctly updated to use the new customer-scoped path.

The implementation has been properly updated to use the new customer-scoped endpoint /api/v1/billing/customers/{customerId}/invoices/pending-lines and correctly passes the customerId in the path parameters.

Let's verify that any existing client code that uses this method has been updated to accommodate the new signature:


🏁 Script executed:

#!/bin/bash
# Search for direct calls to createLineItems to ensure they've been updated
rg -A 2 -B 2 "createLineItems\(" --type js --type ts

Length of output: 482


Verify consumer call sites for updated createLineItems signature

I ran a search across the repo and did not find any internal calls to createLineItems( outside its definition in billing.ts. Please ensure that all code (applications or documentation) invoking this client method has been updated to pass the new customerId path parameter along with the request body.

• No occurrences of createLineItems( found beyond its declaration in:

  • api/client/javascript/src/client/billing.ts
api/client/javascript/src/client/schemas.ts (3)

5773-5791: Schema additions look consistent

InvoicePendingLineCreateInput / Response mirror the Go structs and align with the new endpoint design. No issues spotted.


10582-10585: Exports correctly expose new types

The additional re-exports ensure consumers can reference the new models; looks good.


13102-13138: List-invoices filter expansion LGTM

The enriched query parameters preserve backwards compatibility while adding clarity. No concerns.

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