Skip to content

fix(api): non-existent tax code#4590

Merged
tothandras merged 1 commit into
mainfrom
fix/tax-code-500
Jun 28, 2026
Merged

fix(api): non-existent tax code#4590
tothandras merged 1 commit into
mainfrom
fix/tax-code-500

Conversation

@tothandras

@tothandras tothandras commented Jun 28, 2026

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Bug Fixes
    • Charge creation now validates that all referenced tax codes exist before proceeding, returning a clear validation error pointing to the tax configuration when missing or invalid.
    • Constraint violations during charge persistence are now mapped to consistent, user-friendly errors (validation for missing referenced resources; conflict for duplicate/unique reference cases), avoiding raw persistence failures.
  • New Features
    • Credit grant creation now declares Conflict as an additional possible response outcome.
  • Tests
    • Added unit and end-to-end coverage for missing tax codes and duplicate reference/conflict scenarios.

@tothandras
tothandras requested a review from a team as a code owner June 28, 2026 07:58
@tothandras tothandras added the release-note/bug-fix Release note: Bug Fixes label Jun 28, 2026
@coderabbitai

coderabbitai Bot commented Jun 28, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a3653c14-b9bf-4f70-af75-915ab501f524

📥 Commits

Reviewing files that changed from the base of the PR and between 76987b9 and 7c9be16.

⛔ Files ignored due to path filters (1)
  • api/v3/openapi.yaml is excluded by !**/openapi.yaml
📒 Files selected for processing (12)
  • api/spec/packages/aip/src/customers/credits/operations.tsp
  • api/v3/api.gen.go
  • e2e/customer_credits_v3_test.go
  • e2e/v3helpers_test.go
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/meta/adapter/errors.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/taxcode_test.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • test/credits/creditgrant_test.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/service/create.go
  • test/credits/creditgrant_test.go

📝 Walkthrough

Walkthrough

Charge creation now validates referenced tax codes before persistence, maps charge constraint failures to domain errors, updates the credit-grant API contract, and adds end-to-end and service tests for missing tax code handling.

Changes

Tax code validation and error mapping

Layer / File(s) Summary
V3 credit-grant contract and test flow
api/spec/packages/aip/src/customers/credits/operations.tsp, api/v3/api.gen.go, e2e/v3helpers_test.go, e2e/customer_credits_v3_test.go
The create-credit-grant contract adds Common.Conflict, the generated swagger payload is refreshed, a v3 client helper posts credit grants, and an end-to-end test checks the missing-tax-code response.
Intent tax code accessor and create validation
openmeter/billing/charges/charge.go, openmeter/billing/charges/service/create.go
ChargeIntent adds TaxCodeID(), default tax code handling uses that accessor, and charge creation validates referenced tax codes before starting the transaction.
Charge constraint error mapping
openmeter/billing/charges/meta/adapter/errors.go, openmeter/billing/charges/creditpurchase/adapter/charge.go, openmeter/billing/charges/flatfee/adapter/charge.go, openmeter/billing/charges/usagebased/adapter/charge.go
Charge persistence errors from create/save paths are routed through MapChargeConstraintError, which converts constraint violations into domain conflict or validation errors.
Missing tax code and duplicate reference tests
openmeter/billing/charges/service/taxcode_test.go, test/credits/creditgrant_test.go
New tests cover missing tax code validation on charge and credit grant creation, plus duplicate charge reference conflict handling.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • openmeterio/openmeter#4396 — Also changes charge creation tax-code defaulting and validation in openmeter/billing/charges/service/create.go.
  • openmeterio/openmeter#4534 — Directly overlaps with the ChargeIntent.TaxCodeID() and tax-code handling changes in the charge creation flow.

Suggested labels

area/api, area/billing

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% 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 title matches the main fix: handling non-existent tax code errors in the API flow.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/tax-code-500

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.

@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

🤖 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 `@test/credits/creditgrant_test.go`:
- Around line 634-635: The current assertion in the credit grant test only
checks for GenericValidationError, so it can miss regressions in the specific
tax-code validation path. Update the test around the error handling in the
credit grant case to unwrap the validation error and assert the underlying issue
is tax_code_not_found, and ideally verify the field path is tax_config.tax_code
as well. Keep the existing validation check, but make it tax-code-specific so
the test fails if the wrong validation code or path is returned.
🪄 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: c46390bb-b5f2-45f3-b6b5-4b3c1265d11b

📥 Commits

Reviewing files that changed from the base of the PR and between 2521ae0 and f010115.

📒 Files selected for processing (2)
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • test/credits/creditgrant_test.go

Comment thread test/credits/creditgrant_test.go
@greptile-apps

greptile-apps Bot commented Jun 28, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR improves tax-code handling for credit grants and charge creation. The main changes are:

  • Added upfront validation for referenced tax codes during charge creation.
  • Mapped charge persistence constraint errors to clearer domain errors.
  • Documented conflict responses for credit-grant creation.
  • Added tests for missing tax-code behavior through the v3 API and credit-grant paths.

Confidence Score: 5/5

This looks safe to merge.

  • No blocking issues found in the changed code.

Important Files Changed

Filename Overview
openmeter/billing/charges/service/create.go Adds default tax-code application and explicit tax-code existence validation before charges are persisted.
openmeter/billing/charges/meta/adapter/errors.go Adds shared translation for charge database constraint errors.
openmeter/billing/charges/charge.go Adds a charge-intent tax-code accessor used by defaulting and validation.
api/spec/packages/aip/src/customers/credits/operations.tsp Documents conflict responses for credit-grant creation.
e2e/customer_credits_v3_test.go Adds end-to-end coverage for missing tax-code handling on credit-grant creation.

Reviews (3): Last reviewed commit: "fix(api): non-existent tax code" | Re-trigger Greptile

@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)
openmeter/billing/charges/service/create.go (1)

73-103: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift

Consider batching the tax-code existence check.

This adds one GetTaxCode call per distinct tax code before create runs, so large batches now pay an extra N round trips on a hot DB path. A batched lookup would keep the validation and avoid scaling linearly with batch cardinality.

As per path instructions, "Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks."

🤖 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 `@openmeter/billing/charges/service/create.go` around lines 73 - 103, The
tax-code validation in validateTaxCodesExist currently performs one GetTaxCode
lookup per distinct taxCodeID, creating linear round trips on the create path.
Refactor this logic to batch the existence check for all collected tax codes at
once using the existing service/repository layer, then map missing IDs back to
the same tax_code_not_found validation error while preserving the current
deduping and empty-ID handling.

Source: Path instructions

🤖 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 `@openmeter/billing/charges/creditpurchase/adapter/charge.go`:
- Around line 93-98: Narrow the constraint-error remap in the charge adapters so
only missing foreign key violations become the “resource does not exist”
precondition. Update the `Charge` mapping logic in `charge.go` (and the matching
flat-fee and usage-based adapter code) to distinguish foreign-key failures from
other `db.IsConstraintError(err)` cases, and keep uniqueness or other constraint
errors flowing through their original handling instead of converting them in
`NewGenericPreConditionFailedError`.

---

Nitpick comments:
In `@openmeter/billing/charges/service/create.go`:
- Around line 73-103: The tax-code validation in validateTaxCodesExist currently
performs one GetTaxCode lookup per distinct taxCodeID, creating linear round
trips on the create path. Refactor this logic to batch the existence check for
all collected tax codes at once using the existing service/repository layer,
then map missing IDs back to the same tax_code_not_found validation error while
preserving the current deduping and empty-ID handling.
🪄 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: f50692ac-81b6-4a33-b9f3-4b3615957c76

📥 Commits

Reviewing files that changed from the base of the PR and between f010115 and 76987b9.

📒 Files selected for processing (6)
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • test/credits/creditgrant_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/credits/creditgrant_test.go

Comment thread openmeter/billing/charges/creditpurchase/adapter/charge.go Outdated
@tothandras
tothandras merged commit db0f5ef into main Jun 28, 2026
29 checks passed
@tothandras
tothandras deleted the fix/tax-code-500 branch June 28, 2026 20:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants