Skip to content

feat(taxcode): add default guard to DeleteTaxCode - #4405

Merged
borbelyr-kong merged 3 commits into
mainfrom
feat/add-default-check-to-delete-tax-code
May 21, 2026
Merged

borbelyr-kong merged 3 commits into
mainfrom
feat/add-default-check-to-delete-tax-code

Conversation

@borbelyr-kong

@borbelyr-kong borbelyr-kong commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Bug Fixes
    • Prevent deletion of tax codes that are configured as organization defaults for invoicing or credit grants; attempts now return a conflict validation error and the tax code remains unchanged.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@borbelyr-kong has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 2 minutes and 32 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b3be4b11-3a46-42ae-b44a-41764ccd3ffc

📥 Commits

Reviewing files that changed from the base of the PR and between 38fab06 and 0709832.

📒 Files selected for processing (4)
  • openmeter/taxcode/errors.go
  • openmeter/taxcode/service/taxcode.go
  • openmeter/taxcode/service/taxcode_test.go
  • openmeter/taxcode/testutils/env.go
📝 Walkthrough

Walkthrough

Prevents deleting tax codes that are set as organization defaults. Adds a new 409 validation error and helper, updates DeleteTaxCode to check organization defaults before delete, and adds test helpers plus tests verifying the blocking behavior.

Changes

Organization Default Tax Code Deletion Prevention

Layer / File(s) Summary
Error validation contract for organization default conflict
openmeter/taxcode/errors.go
Introduces ErrCodeTaxCodeIsOrganizationDefault error code with HTTP 409, an exported ErrTaxCodeIsOrganizationDefault validation issue, and IsTaxCodeIsOrganizationDefaultError helper for detection.
Service deletion check, test utilities, and tests
openmeter/taxcode/service/taxcode.go, openmeter/taxcode/testutils/env.go, openmeter/taxcode/service/taxcode_test.go
DeleteTaxCode now loads organization default tax codes and blocks deletion if the target matches either invoicing or credit-grant default. Test utilities add context-aware CreateTaxCode and SetupNamespaceDefaults. Tests include an OrganizationDefault subtest asserting deletion is rejected for defaults and allowed for non-defaults.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • openmeterio/openmeter#4308: Refactors organization-default tax codes service API (GetOrganizationDefaultTaxCodes, UpsertOrganizationDefaultTaxCodes) used by this change.
  • openmeterio/openmeter#4390: Adds namespace provisioning that upserts organization default tax codes that this PR treats as non-deletable.
  • openmeterio/openmeter#4280: Related API/schema work for managing organization default tax codes complementing these validations.

Suggested labels

area/billing

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 accurately describes the main change: adding validation to prevent deletion of tax codes set as organization defaults.
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/add-default-check-to-delete-tax-code

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.

@borbelyr-kong borbelyr-kong added the release-note/misc Miscellaneous changes label May 21, 2026

@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/taxcode/service/taxcode_test.go (1)

83-132: ⚡ Quick win

Nice coverage here—add one “no defaults configured” delete case too.

Line 83+ covers the configured-default paths well. Adding a case where the namespace has no org defaults yet would lock in expected behavior and catch regressions in the delete guard.

🤖 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/taxcode/service/taxcode_test.go` around lines 83 - 132, Add a new
subtest that verifies deleting a tax code in a namespace with no organization
defaults succeeds: create a fresh namespace (e.g., otherNs), create a tax code
via env.CreateTaxCode, do NOT call taxcode.UpsertOrganizationDefaultTaxCodes for
that namespace, call env.Service.DeleteTaxCode with NamespacedID for that tax
code and assert NoError; reference the existing test pattern and symbols
DeleteTaxCode, UpsertOrganizationDefaultTaxCodes, and
ErrCodeTaxCodeIsOrganizationDefault (ensure this new test contrasts with the
"DeleteInvoicingDefaultIsBlocked"/"DeleteCreditGrantDefaultIsBlocked" cases).
🤖 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/taxcode/service/taxcode.go`:
- Around line 129-136: When calling s.adapter.GetOrganizationDefaultTaxCodes
(taxcode.GetOrganizationDefaultTaxCodesInput) handle the specific "organization
defaults not found" case as non-blocking: if the call returns
ErrCodeOrganizationDefaultTaxCodesNotFound, treat it as no defaults set (do not
return the error) and proceed with delete; only return err for other error
values. Keep the subsequent check that compares defaults.CreditGrantTaxCodeID or
defaults.InvoicingTaxCodeID against existing.ID and still return
models.NewGenericConflictError(taxcode.ErrTaxCodeIsOrganizationDefault) when a
match is found.

---

Nitpick comments:
In `@openmeter/taxcode/service/taxcode_test.go`:
- Around line 83-132: Add a new subtest that verifies deleting a tax code in a
namespace with no organization defaults succeeds: create a fresh namespace
(e.g., otherNs), create a tax code via env.CreateTaxCode, do NOT call
taxcode.UpsertOrganizationDefaultTaxCodes for that namespace, call
env.Service.DeleteTaxCode with NamespacedID for that tax code and assert
NoError; reference the existing test pattern and symbols DeleteTaxCode,
UpsertOrganizationDefaultTaxCodes, and ErrCodeTaxCodeIsOrganizationDefault
(ensure this new test contrasts with the
"DeleteInvoicingDefaultIsBlocked"/"DeleteCreditGrantDefaultIsBlocked" cases).
🪄 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: d69d2579-ada5-465d-9d15-225faf9e6263

📥 Commits

Reviewing files that changed from the base of the PR and between 470f7dd and 34901ea.

📒 Files selected for processing (4)
  • openmeter/taxcode/errors.go
  • openmeter/taxcode/service/taxcode.go
  • openmeter/taxcode/service/taxcode_test.go
  • openmeter/taxcode/testutils/env.go

Comment on lines +129 to +136
defaults, err := s.adapter.GetOrganizationDefaultTaxCodes(ctx, taxcode.GetOrganizationDefaultTaxCodesInput{Namespace: input.NamespacedID.Namespace})
if err != nil {
return err
}

if defaults.CreditGrantTaxCodeID == existing.ID || defaults.InvoicingTaxCodeID == existing.ID {
return models.NewGenericConflictError(taxcode.ErrTaxCodeIsOrganizationDefault)
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle “defaults not found” as a non-blocking delete path.

Right now, Line 130 returns on any lookup error. If org defaults are unset and the adapter returns ErrCodeOrganizationDefaultTaxCodesNotFound, deletes that should be allowed will fail.

Suggested fix
-		defaults, err := s.adapter.GetOrganizationDefaultTaxCodes(ctx, taxcode.GetOrganizationDefaultTaxCodesInput{Namespace: input.NamespacedID.Namespace})
-		if err != nil {
-			return err
-		}
-
-		if defaults.CreditGrantTaxCodeID == existing.ID || defaults.InvoicingTaxCodeID == existing.ID {
+		defaults, err := s.adapter.GetOrganizationDefaultTaxCodes(ctx, taxcode.GetOrganizationDefaultTaxCodesInput{
+			Namespace: input.NamespacedID.Namespace,
+		})
+		if err != nil && !taxcode.IsOrganizationDefaultTaxCodesNotFoundError(err) {
+			return err
+		}
+
+		if err == nil && (defaults.CreditGrantTaxCodeID == existing.ID || defaults.InvoicingTaxCodeID == existing.ID) {
 			return models.NewGenericConflictError(taxcode.ErrTaxCodeIsOrganizationDefault)
 		}
🤖 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/taxcode/service/taxcode.go` around lines 129 - 136, When calling
s.adapter.GetOrganizationDefaultTaxCodes
(taxcode.GetOrganizationDefaultTaxCodesInput) handle the specific "organization
defaults not found" case as non-blocking: if the call returns
ErrCodeOrganizationDefaultTaxCodesNotFound, treat it as no defaults set (do not
return the error) and proceed with delete; only return err for other error
values. Keep the subsequent check that compares defaults.CreditGrantTaxCodeID or
defaults.InvoicingTaxCodeID against existing.ID and still return
models.NewGenericConflictError(taxcode.ErrTaxCodeIsOrganizationDefault) when a
match is found.

@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

♻️ Duplicate comments (1)
openmeter/taxcode/service/taxcode.go (1)

129-136: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Handle "defaults not found" as a non-blocking case.

Right now if no organization defaults are configured, line 130 will return the "not found" error and block deletion of any tax code. The check should only apply when defaults actually exist.

Suggested fix
 		defaults, err := s.adapter.GetOrganizationDefaultTaxCodes(ctx, taxcode.GetOrganizationDefaultTaxCodesInput{Namespace: input.NamespacedID.Namespace})
-		if err != nil {
+		if err != nil && !taxcode.IsOrganizationDefaultTaxCodesNotFoundError(err) {
 			return err
 		}
 
-		if defaults.CreditGrantTaxCodeID == existing.ID || defaults.InvoicingTaxCodeID == existing.ID {
+		if err == nil && (defaults.CreditGrantTaxCodeID == existing.ID || defaults.InvoicingTaxCodeID == existing.ID) {
 			return models.NewGenericConflictError(taxcode.ErrTaxCodeIsOrganizationDefault)
 		}
🤖 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/taxcode/service/taxcode.go` around lines 129 - 136, The deletion
path currently blocks when GetOrganizationDefaultTaxCodes returns "not found";
change the error handling around s.adapter.GetOrganizationDefaultTaxCodes(ctx,
taxcode.GetOrganizationDefaultTaxCodesInput{Namespace:
input.NamespacedID.Namespace}) so that a not-found error is treated as
non-blocking (ignore it and proceed) while any other error is returned; if
defaults is nil after ignoring not-found, skip the conflict check against
defaults.CreditGrantTaxCodeID / defaults.InvoicingTaxCodeID and only call
models.NewGenericConflictError(taxcode.ErrTaxCodeIsOrganizationDefault) when
defaults actually exist and match existing.ID.
🤖 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/taxcode/service/taxcode_test.go`:
- Around line 84-133: Add a test that verifies DeleteTaxCode succeeds when an
organization has no defaults configured: create a fresh namespace via
testutils.NameGenerator.Generate().Key, create a tax code with
env.CreateTaxCode, call env.Service.DeleteTaxCode with that NamespacedID, and
assert require.NoError; name the subtest
"DeleteSucceedsWhenNoDefaultsConfigured" so it complements the existing
OrganizationDefault cases and ensures DeleteTaxCode behaves correctly when
UpsertOrganizationDefaultTaxCodes has not been called for that namespace.

---

Duplicate comments:
In `@openmeter/taxcode/service/taxcode.go`:
- Around line 129-136: The deletion path currently blocks when
GetOrganizationDefaultTaxCodes returns "not found"; change the error handling
around s.adapter.GetOrganizationDefaultTaxCodes(ctx,
taxcode.GetOrganizationDefaultTaxCodesInput{Namespace:
input.NamespacedID.Namespace}) so that a not-found error is treated as
non-blocking (ignore it and proceed) while any other error is returned; if
defaults is nil after ignoring not-found, skip the conflict check against
defaults.CreditGrantTaxCodeID / defaults.InvoicingTaxCodeID and only call
models.NewGenericConflictError(taxcode.ErrTaxCodeIsOrganizationDefault) when
defaults actually exist and match existing.ID.
🪄 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: 62a98c8d-7e35-438d-9c3d-f19648f2203e

📥 Commits

Reviewing files that changed from the base of the PR and between 34901ea and 9b3c2ec.

📒 Files selected for processing (4)
  • openmeter/taxcode/errors.go
  • openmeter/taxcode/service/taxcode.go
  • openmeter/taxcode/service/taxcode_test.go
  • openmeter/taxcode/testutils/env.go

Comment on lines +84 to +133
t.Run("OrganizationDefault", func(t *testing.T) {
// given:
// - two tax codes set as org defaults (invoicing + credit grant)
// - one extra tax code that is not a default
// when:
// - caller tries to delete an org default tax code
// then:
// - deletion is blocked with ErrCodeTaxCodeIsOrganizationDefault (409)
// - deletion of a non-default tax code succeeds
defaultNs := testutils.NameGenerator.Generate().Key
invoicing := env.CreateTaxCode(t.Context(), t, defaultNs)
creditGrant := env.CreateTaxCode(t.Context(), t, defaultNs)
other := env.CreateTaxCode(t.Context(), t, defaultNs)

_, err := env.Service.UpsertOrganizationDefaultTaxCodes(t.Context(), taxcode.UpsertOrganizationDefaultTaxCodesInput{
Namespace: defaultNs,
InvoicingTaxCodeID: invoicing.ID,
CreditGrantTaxCodeID: creditGrant.ID,
})
require.NoError(t, err)

t.Run("DeleteInvoicingDefaultIsBlocked", func(t *testing.T) {
err := env.Service.DeleteTaxCode(t.Context(), taxcode.DeleteTaxCodeInput{
NamespacedID: models.NamespacedID{Namespace: defaultNs, ID: invoicing.ID},
})
require.Error(t, err)

var vi models.ValidationIssue
require.ErrorAs(t, err, &vi)
assert.Equal(t, taxcode.ErrCodeTaxCodeIsOrganizationDefault, vi.Code())
})

t.Run("DeleteCreditGrantDefaultIsBlocked", func(t *testing.T) {
err := env.Service.DeleteTaxCode(t.Context(), taxcode.DeleteTaxCodeInput{
NamespacedID: models.NamespacedID{Namespace: defaultNs, ID: creditGrant.ID},
})
require.Error(t, err)

var vi models.ValidationIssue
require.ErrorAs(t, err, &vi)
assert.Equal(t, taxcode.ErrCodeTaxCodeIsOrganizationDefault, vi.Code())
})

t.Run("DeleteNonDefaultSucceeds", func(t *testing.T) {
err := env.Service.DeleteTaxCode(t.Context(), taxcode.DeleteTaxCodeInput{
NamespacedID: models.NamespacedID{Namespace: defaultNs, ID: other.ID},
})
require.NoError(t, err)
})
})

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.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add test coverage for deleting when no organization defaults exist.

The test verifies blocking behavior when defaults are configured, but doesn't cover the case where an organization has no defaults set at all. That's an important edge case—deletion should succeed when no defaults exist (even if the current service implementation might have a bug there).

Suggested additional test
t.Run("DeleteSucceedsWhenNoDefaultsConfigured", func(t *testing.T) {
	// given: namespace with no organization defaults
	freshNs := testutils.NameGenerator.Generate().Key
	tc := env.CreateTaxCode(t.Context(), t, freshNs)

	// when: deleting a tax code
	err := env.Service.DeleteTaxCode(t.Context(), taxcode.DeleteTaxCodeInput{
		NamespacedID: models.NamespacedID{Namespace: freshNs, ID: tc.ID},
	})

	// then: deletion succeeds
	require.NoError(t, err)
})
🤖 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/taxcode/service/taxcode_test.go` around lines 84 - 133, Add a test
that verifies DeleteTaxCode succeeds when an organization has no defaults
configured: create a fresh namespace via testutils.NameGenerator.Generate().Key,
create a tax code with env.CreateTaxCode, call env.Service.DeleteTaxCode with
that NamespacedID, and assert require.NoError; name the subtest
"DeleteSucceedsWhenNoDefaultsConfigured" so it complements the existing
OrganizationDefault cases and ensures DeleteTaxCode behaves correctly when
UpsertOrganizationDefaultTaxCodes has not been called for that namespace.

@borbelyr-kong
borbelyr-kong force-pushed the feat/add-default-check-to-delete-tax-code branch from 38fab06 to 0709832 Compare May 21, 2026 09:38

@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

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
openmeter/taxcode/testutils/env.go (1)

64-66: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Guard against silently ignored extra overrides

Nice helper overall. One small footgun: passing more than one opts value quietly ignores all but the first, which can hide test mistakes.

Suggested patch
 func (e *TestEnv) CreateTaxCode(ctx context.Context, t *testing.T, namespace string, opts ...taxcode.CreateTaxCodeInput) taxcode.TaxCode {
 	t.Helper()
+	require.LessOrEqual(t, len(opts), 1, "CreateTaxCode accepts at most one override input")
+
 	var input taxcode.CreateTaxCodeInput
 	if len(opts) > 0 {
 		input = opts[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 `@openmeter/taxcode/testutils/env.go` around lines 64 - 66, Currently extra
entries in the variadic opts slice are silently ignored (only opts[0] used);
change the guard to detect len(opts) > 1 and fail loudly—e.g., if len(opts) > 1
{ panic("env override: only one override allowed; got N") } then set input =
opts[0]; reference the existing variables input and opts in this function so the
code fails fast when callers pass more than one override.
🤖 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.

Outside diff comments:
In `@openmeter/taxcode/testutils/env.go`:
- Around line 64-66: Currently extra entries in the variadic opts slice are
silently ignored (only opts[0] used); change the guard to detect len(opts) > 1
and fail loudly—e.g., if len(opts) > 1 { panic("env override: only one override
allowed; got N") } then set input = opts[0]; reference the existing variables
input and opts in this function so the code fails fast when callers pass more
than one override.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a2472ee7-4a81-42ed-a67a-8a7532d1b741

📥 Commits

Reviewing files that changed from the base of the PR and between 9b3c2ec and 38fab06.

📒 Files selected for processing (1)
  • openmeter/taxcode/testutils/env.go

@borbelyr-kong
borbelyr-kong merged commit f0ef087 into main May 21, 2026
28 checks passed
@borbelyr-kong
borbelyr-kong deleted the feat/add-default-check-to-delete-tax-code branch May 21, 2026 10:41

This branch was previously deployed

1 inactive deployment
dev — 0709832a Deployed May 21, 2026 by borbelyr-kong via Migration Checks #14565
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants