Skip to content

Feat: Customer create charges - #4503

Merged
borosr merged 9 commits into
mainfrom
feat/customer-create-charges
Jun 17, 2026
Merged

borosr merged 9 commits into
mainfrom
feat/customer-create-charges

Conversation

@borosr

@borosr borosr commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Notes for reviewer

Summary by CodeRabbit

  • New Features

    • Create customer charges (flat-fee and usage-based) via a new POST endpoint
    • JavaScript client & SDK support for creating customer charges
  • Documentation

    • Added docs for the new customer charge creation operation and route

@borosr borosr self-assigned this Jun 10, 2026
@borosr
borosr requested a review from a team as a code owner June 10, 2026 13:10
@borosr borosr added the release-note/feature Release note: Exciting New Features label Jun 10, 2026
@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds a complete customer charge creation endpoint at POST /openmeter/customers/{customerId}/charges, supporting flat-fee and usage-based variants with proration, amount-before-proration, discounts, tax parsing, generated TypeScript client/SDK/types/schemas, and Go handler/converter and route wiring.

Changes

Customer Charge Creation Feature

Layer / File(s) Summary
TypeSpec API service definition
api/spec/packages/aip/src/customers/charges/charges.tsp, api/spec/packages/aip/src/customers/charges/operations.tsp
ChargeBase lifecycle visibility expanded to allow creation for many fields; FlatFeeCharge adds amount_before_proration; adds CreateCharge discriminated union and POST create operation.
TypeScript types and Zod schemas
api/spec/packages/aip-client-javascript/src/models/types.ts, api/spec/packages/aip-client-javascript/src/models/schemas.ts, api/spec/packages/aip-client-javascript/src/index.ts
Adds CreateFlatFeeChargeRequest and CreateUsageBasedChargeRequest interfaces/schemas, createChargeRequest discriminated union, inserts amount_before_proration in FlatFee schemas/types, and exports endpoint wiring types.
Generated JS client and SDK
api/spec/packages/aip-client-javascript/src/funcs/customers.ts, api/spec/packages/aip-client-javascript/src/sdk/customers.ts, api/spec/packages/aip-client-javascript/src/models/operations/customers.ts, api/spec/packages/aip-client-javascript/README.md
Generated createCustomerCharges function and operation types, SDK CustomersCharges.create() wrapper, re-exported request types and README row documenting POST /openmeter/customers/{customerId}/charges.
Go backend converters, handler, and routes
api/v3/handlers/customers/charges/convert.go, api/v3/handlers/customers/charges/create.go, api/v3/handlers/customers/charges/handler.go, api/v3/server/routes.go
Adds conversion helpers mapping API requests to billing charge intents (tax/discount/proration/price handling), CreateCustomerCharge HTTP handler validating/parsing discriminated body and calling service, handler interface method, and server route wiring.

Sequence Diagram

sequenceDiagram
  participant Client
  participant Server
  participant ChargesHandler
  participant BillingChargeService
  Client->>Server: POST /openmeter/customers/{customerId}/charges (createCharge)
  Server->>ChargesHandler: invoke CreateCustomerCharge handler (parsed body)
  ChargesHandler->>BillingChargeService: Create(namespace, ChargeIntent)
  BillingChargeService-->>ChargesHandler: created Charge
  ChargesHandler-->>Server: respond 201 with BillingCharge
  Server-->>Client: HTTP 201 BillingCharge
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested labels

area/api, area/billing, kind/feature

Suggested reviewers

  • tothandras
  • turip
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'Feat: Customer create charges' directly and clearly summarizes the main feature being added across all the changes—a customer charge creation capability.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/customer-create-charges

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.

@borosr
borosr force-pushed the feat/customer-create-charges branch from 6ef7ba0 to 5f36f3e Compare June 10, 2026 13:15

@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

🧹 Nitpick comments (1)
api/v3/handlers/customers/charges/create.go (1)

124-136: ⚡ Quick win

Consider using structured errors for service validation.

The validation checks on lines 129-134 use plain errors.New(), but other validation errors in the request parser use apierrors.NewBadRequestError(). For consistency and better error responses to clients, consider wrapping these in structured API errors too.

These cases represent contract violations from the service layer (unexpected result cardinality), so they could be Internal Server Errors rather than Bad Requests, but structured errors would still be clearer.

♻️ Proposed refactor
 		res, err := h.service.Create(ctx, request)
 		if err != nil {
 			return CreateCustomerChargesResponse{}, err
 		}
 		if len(res) < 1 {
-			return CreateCustomerChargesResponse{}, errors.New("no charge created")
+			return CreateCustomerChargesResponse{}, apierrors.NewInternalServerError(ctx, errors.New("no charge created"))
 		}
 		if len(res) > 1 {
-			return CreateCustomerChargesResponse{}, errors.New("too many results")
+			return CreateCustomerChargesResponse{}, apierrors.NewInternalServerError(ctx, errors.New("too many results"))
 		}
 		return convertChargeToAPI(res[0])
🤖 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 `@api/v3/handlers/customers/charges/create.go` around lines 124 - 136, Replace
the plain errors.New calls used for unexpected result cardinality in the Create
handler with structured API errors (use apierrors.NewInternalServerError with a
clear message and wrap the original context), i.e., where the anonymous handler
checks len(res) < 1 and len(res) > 1 after calling h.service.Create, return
apierrors.NewInternalServerError(...) instead of errors.New so the client
receives a consistent structured error; keep the rest of the flow (calling
convertChargeToAPI) unchanged.
🤖 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 `@api/v3/handlers/customers/charges/create.go`:
- Around line 102-109: The default switch branch returns
CreateCustomerChargesRequest{} and calls apierrors.NewBadRequestError(ctx, err,
...), but err is nil there; replace the second argument with either nil or a
newly constructed descriptive error (e.g., errors.New("unexpected charge type
discriminator: <value>")) so the BadRequestError contains meaningful context;
update the default path that produces the apierrors.NewBadRequestError(...) to
pass a proper error value and include the actual discriminator value in the
message for apierrors.NewBadRequestError, referencing the same
switch/discriminator variable used in this function.

---

Nitpick comments:
In `@api/v3/handlers/customers/charges/create.go`:
- Around line 124-136: Replace the plain errors.New calls used for unexpected
result cardinality in the Create handler with structured API errors (use
apierrors.NewInternalServerError with a clear message and wrap the original
context), i.e., where the anonymous handler checks len(res) < 1 and len(res) > 1
after calling h.service.Create, return apierrors.NewInternalServerError(...)
instead of errors.New so the client receives a consistent structured error; keep
the rest of the flow (calling convertChargeToAPI) unchanged.
🪄 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: 2ebf7386-9c98-4c37-8924-e5d5cc07b837

📥 Commits

Reviewing files that changed from the base of the PR and between dc07897 and 6ef7ba0.

⛔ Files ignored due to path filters (1)
  • api/v3/openapi.yaml is excluded by !**/openapi.yaml
📒 Files selected for processing (16)
  • api/spec/packages/aip-client-javascript/README.md
  • api/spec/packages/aip-client-javascript/src/funcs/customers.ts
  • api/spec/packages/aip-client-javascript/src/index.ts
  • api/spec/packages/aip-client-javascript/src/models/operations/customers.ts
  • api/spec/packages/aip-client-javascript/src/models/operations/subscriptions.ts
  • api/spec/packages/aip-client-javascript/src/models/schemas.ts
  • api/spec/packages/aip-client-javascript/src/models/types.ts
  • api/spec/packages/aip-client-javascript/src/sdk/customers.ts
  • api/spec/packages/aip/src/customers/charges/charges.tsp
  • api/spec/packages/aip/src/customers/charges/operations.tsp
  • api/spec/packages/aip/src/productcatalog/ratecard.tsp
  • api/v3/api.gen.go
  • api/v3/handlers/customers/charges/convert.go
  • api/v3/handlers/customers/charges/create.go
  • api/v3/handlers/customers/charges/handler.go
  • api/v3/server/routes.go
👮 Files not reviewed due to content moderation or server errors (6)
  • api/spec/packages/aip-client-javascript/src/models/schemas.ts
  • api/spec/packages/aip/src/customers/charges/charges.tsp
  • api/spec/packages/aip/src/productcatalog/ratecard.tsp
  • api/spec/packages/aip-client-javascript/src/models/operations/subscriptions.ts
  • api/spec/packages/aip-client-javascript/src/index.ts
  • api/v3/handlers/customers/charges/convert.go

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

🤖 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 `@api/spec/packages/aip-client-javascript/src/models/schemas.ts`:
- Around line 4924-4927: The operation request type for the Create Customer
Charges endpoint is still using Record<string, never> even though
createCustomerChargesBody is mapped to createChargeRequest; regenerate or resync
the operation types so CreateCustomerChargesRequest.body references the
create-charge schema (createChargeRequest) instead of Record<string, never>.
Locate the operations file that defines CreateCustomerChargesRequest
(customers.ts) and either re-run the OpenAPI/typegen to update the generated
types or replace the body type to the createChargeRequest schema type used in
models/schemas.ts so CustomersCharges.create() accepts the new payload shape.

In `@api/spec/packages/aip-client-javascript/src/models/types.ts`:
- Around line 2820-2860: The operation request body type for
create-customer-charges is still typed as Record<string, never>, which prevents
using the new charge models; update the CreateCustomerChargesRequest.body (in
customers.ts) to accept the appropriate create-charge types such as
CreateFlatFeeChargeRequest (and the analogous create types for other charge
kinds you added) or a discriminated union of those types so the SDK contract
reflects the new models; ensure the union uses the same discriminator fields
(e.g., type and managed_by) as defined on CreateFlatFeeChargeRequest so existing
callers compile against CreateCustomerChargesRequest.body.
- Around line 2763-2765: The JSDoc for the amount_before_proration field is
incorrect (it currently repeats "amount after proration"); update the comment
for the amount_before_proration property (type CurrencyAmount) to read "The
amount before proration of the charge." and make the same correction for the
other duplicate occurrence of amount_before_proration around the second block
(the one near lines 2857-2858) so generated SDK docs correctly reflect it is the
pre-proration amount.
🪄 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: 3f5c01ef-46d6-4b03-b458-27fd72ae2345

📥 Commits

Reviewing files that changed from the base of the PR and between 6ef7ba0 and 5f36f3e.

⛔ Files ignored due to path filters (1)
  • api/v3/openapi.yaml is excluded by !**/openapi.yaml
📒 Files selected for processing (15)
  • api/spec/packages/aip-client-javascript/README.md
  • api/spec/packages/aip-client-javascript/src/funcs/customers.ts
  • api/spec/packages/aip-client-javascript/src/index.ts
  • api/spec/packages/aip-client-javascript/src/models/operations/customers.ts
  • api/spec/packages/aip-client-javascript/src/models/schemas.ts
  • api/spec/packages/aip-client-javascript/src/models/types.ts
  • api/spec/packages/aip-client-javascript/src/sdk/customers.ts
  • api/spec/packages/aip/src/customers/charges/charges.tsp
  • api/spec/packages/aip/src/customers/charges/operations.tsp
  • api/spec/packages/aip/src/productcatalog/ratecard.tsp
  • api/v3/api.gen.go
  • api/v3/handlers/customers/charges/convert.go
  • api/v3/handlers/customers/charges/create.go
  • api/v3/handlers/customers/charges/handler.go
  • api/v3/server/routes.go
✅ Files skipped from review due to trivial changes (1)
  • api/spec/packages/aip-client-javascript/README.md
🚧 Files skipped from review as they are similar to previous changes (10)
  • api/v3/handlers/customers/charges/handler.go
  • api/spec/packages/aip/src/productcatalog/ratecard.tsp
  • api/spec/packages/aip-client-javascript/src/models/operations/customers.ts
  • api/spec/packages/aip-client-javascript/src/sdk/customers.ts
  • api/spec/packages/aip/src/customers/charges/operations.tsp
  • api/spec/packages/aip/src/customers/charges/charges.tsp
  • api/v3/handlers/customers/charges/create.go
  • api/spec/packages/aip-client-javascript/src/funcs/customers.ts
  • api/v3/server/routes.go
  • api/v3/handlers/customers/charges/convert.go

@greptile-apps

greptile-apps Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a POST /openmeter/customers/{customerId}/charges endpoint for creating flat-fee and usage-based customer charges manually, along with TypeSpec model changes, Go handler/converter logic, and TypeScript SDK support.

  • Go side: New create.go handler correctly dispatches by discriminator, validates cross-field constraints (currency match on amount_before_proration, independent discount branches), and maps intents via two new converter functions.
  • TypeScript SDK: The fix for body: Record<string, never> and the new CreateCustomerChargesRequest union type are correct, but amount_before_proration was incorrectly added as a required field to the flatFeeCharge Zod schema and FlatFeeCharge TypeScript interface — both used for read responses — even though the TypeSpec marks it @visibility(Lifecycle.Create) only and neither the OpenAPI spec nor the Go handler return it.

Confidence Score: 4/5

The Go handler and converter are well-structured and address previous review findings, but the TypeScript SDK ships with amount_before_proration as a required field on the read-response type when the API never returns it.

The flatFeeCharge Zod schema and FlatFeeCharge TypeScript interface both declare amount_before_proration as required, yet neither the OpenAPI response schema nor the Go handler ever populate this field. Any consumer that performs runtime Zod validation or relies on TypeScript's type guarantees for flat fee charge reads will encounter failures or undefined values for a field the types claim is always present.

api/spec/packages/aip-client-javascript/src/models/schemas.ts and api/spec/packages/aip-client-javascript/src/models/types.ts — the amount_before_proration field needs to be removed from or made optional on the flatFeeCharge / FlatFeeCharge response type.

Important Files Changed

Filename Overview
api/v3/handlers/customers/charges/create.go New POST handler that parses, discriminates, and delegates flat-fee or usage-based charge creation; defensive len checks on the service result are correct. No new issues found.
api/v3/handlers/customers/charges/convert.go Adds convertFlatFeeChargeAPIToIntent and convertUsageBaseChargeAPIToIntent; cross-field currency validation and independent discount if-blocks address prior review comments.
api/spec/packages/aip-client-javascript/src/models/schemas.ts Adds createFlatFeeChargeRequest, createUsageBasedChargeRequest, and createCustomerChargesResponse; however, amount_before_proration is incorrectly added as a required field to flatFeeCharge (used by read responses), causing Zod validation failures and incorrect TypeScript types.
api/spec/packages/aip-client-javascript/src/models/types.ts Adds CreateFlatFeeChargeRequest and CreateUsageBasedChargeRequest interfaces; mirrors the schema bug by declaring amount_before_proration as required on the FlatFeeCharge response interface when the API never returns it.
api/spec/packages/typespec-typescript/src/request-types.ts Fixes the Record<string, never> body-type fallback by resolving the HTTP operation body type from the TypeSpec program, consistent with patterns elsewhere in the codebase.
api/spec/packages/aip/src/customers/charges/charges.tsp Adds CreateFlatFeeCharge and CreateUsageBasedCharge models with correct visibility annotations; moves price to Lifecycle.Read for flat fee and Read+Create for usage-based.
api/v3/server/routes.go Adds CreateCustomerCharges route handler with correct unimplemented fallback and parameter forwarding.
api/spec/packages/aip-client-javascript/src/models/operations/customers.ts Adds CreateCustomerChargesRequest with the correct union body type CreateFlatFeeChargeRequest

Sequence Diagram

sequenceDiagram
    participant Client
    participant Router as routes.go
    participant Handler as create.go
    participant Converter as convert.go
    participant Service as billing.Service

    Client->>Router: "POST /customers/{customerId}/charges"
    Router->>Handler: CreateCustomerCharge().With(params)
    Handler->>Handler: ParseBody → CreateChargeRequest
    Handler->>Handler: "body.Discriminator() → flat_fee | usage_based"
    alt flat_fee
        Handler->>Converter: convertFlatFeeChargeAPIToIntent(customerID, flatFee)
        Converter->>Converter: validate currency match
        Converter-->>Handler: ChargeIntent
    else usage_based
        Handler->>Converter: convertUsageBaseChargeAPIToIntent(customerID, usageBased)
        Converter->>Converter: build discounts (independent if-checks)
        Converter-->>Handler: ChargeIntent
    end
    Handler->>Handler: input.Validate()
    Handler->>Service: Create(ctx, input)
    Service-->>Handler: []BillingCharge
    Handler->>Converter: convertChargeToAPI(res[0])
    Converter-->>Handler: BillingFlatFeeCharge / BillingUsageBasedCharge
    Handler-->>Client: 201 BillingCharge JSON
Loading

Comments Outside Diff (1)

  1. api/spec/packages/aip-client-javascript/src/models/types.ts, line 2817-2819 (link)

    P1 amount_before_proration required in the response TS interface but absent from the response contract

    FlatFeeCharge is the TypeScript interface for read responses (list, create 201). Adding amount_before_proration: CurrencyAmount as a non-optional property here (instead of just in CreateFlatFeeChargeRequest) means TypeScript consumers are told the field is always present — but neither the OpenAPI BillingFlatFeeCharge schema nor the Go handler populates it. Code that destructures or indexes this field will silently get undefined at runtime even though the type says it is guaranteed. This should either be amount_before_proration?: CurrencyAmount (optional) on the response type or removed from FlatFeeCharge entirely in favor of CreateFlatFeeChargeRequest, where it already exists.

    Fix in Claude Code

Fix All in Claude Code

Reviews (5): Last reviewed commit: "fix(aip): fix typespec-typescript genera..." | Re-trigger Greptile

@borosr
borosr force-pushed the feat/customer-create-charges branch from 7bd7ecc to 19a65ae Compare June 15, 2026 08:02
@borosr
borosr merged commit d8b5c00 into main Jun 17, 2026
41 of 44 checks passed
@borosr
borosr deleted the feat/customer-create-charges branch June 17, 2026 07:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants