Skip to content

feat(taxcode): add organization default tax codes service and refactor to taxcode.Service - #4308

Merged
borbelyr-kong merged 7 commits into
mainfrom
feat/org-tax-config-service
May 11, 2026
Merged

borbelyr-kong merged 7 commits into
mainfrom
feat/org-tax-config-service

Conversation

@borbelyr-kong

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

Copy link
Copy Markdown
Contributor

@coderabbitai

Summary by CodeRabbit

  • New Features

    • Added organization default tax code management (retrieve & upsert defaults, optional expanded tax-code details).
    • New public types/validation for organization default tax codes and service API; comprehensive tests added.
  • Bug Fixes

    • Improved tax code service initialization and startup wiring with explicit error propagation to prevent silent failures.

@coderabbitai

coderabbitai Bot commented May 6, 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: 95e5d238-2bad-47a6-b0fc-878cc8f6ed92

📥 Commits

Reviewing files that changed from the base of the PR and between 2147f08 and eda5875.

📒 Files selected for processing (3)
  • cmd/billing-worker/wire_gen.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • cmd/billing-worker/wire_gen.go
  • cmd/server/wire_gen.go

📝 Walkthrough

Walkthrough

This PR implements per-organization default tax codes: new domain types and errors, repository/service interface extensions, Ent adapter Get/Upsert, service implementations with a Config-based factory that returns errors, updated startup/test wiring, and comprehensive tests and stubs.

Changes

Organization Default Tax Codes Implementation

Layer / File(s) Summary
Domain Models & Error Definitions
openmeter/taxcode/taxcode.go, openmeter/taxcode/errors.go
OrganizationDefaultTaxCodes type and OrganizationDefaultTaxCodesExpand; Validate(); new error codes resource_id_empty and organization_default_tax_codes_not_found with helpers.
Repository & Service Interfaces
openmeter/taxcode/repository.go, openmeter/taxcode/service.go
Repository extended with GetOrganizationDefaultTaxCodes and UpsertOrganizationDefaultTaxCodes; Service embeds OrganizationDefaultTaxCodesService; new input types and validators added.
Adapter Implementation
openmeter/taxcode/adapter/organizationdefaulttaxcodes.go
Ent-backed Get and Upsert with namespace-scoped queries excluding soft-deleted rows, conditional edge expansion, mapping, and conflict-aware upsert logic.
Service Factory & Core
openmeter/taxcode/service/service.go, openmeter/taxcode/service/taxcode.go, openmeter/taxcode/service/organizationdefaulttaxcodes.go
New public Service and Config; New(config) factory returning (Service, error); refactor methods to *Service receiver; implement organization-defaults methods with validation and transactional checks.
Application Wiring & Startup
app/common/taxcode.go, cmd/billing-worker/wire_gen.go, cmd/jobs/internal/wire_gen.go, cmd/server/wire_gen.go
NewTaxCodeService now returns (taxcode.Service, error) and is called with a taxcodeservice.Config; generated wiring constructs adapters first and propagates errors through cleanup paths.
Test Utilities & Stubs
openmeter/taxcode/testutils/env.go, test/*, openmeter/productcatalog/*, openmeter/subscription/testutils/*
Test envs and fixtures updated to use Config-based taxcode service creation with explicit org-defaults adapter wiring and error handling; test stubs updated to implement expanded interface.
Service Tests
openmeter/taxcode/service/organizationdefaulttaxcodes_test.go
New test suite covering validation, not-found, namespace ownership, create/update/idempotency, same-ID allowance, and expand behavior.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Service
  participant Adapter
  participant EntDB
  Client->>Service: GetOrganizationDefaultTaxCodes / UpsertOrganizationDefaultTaxCodes
  Service->>Adapter: validate + transaction-wrapped call
  Adapter->>EntDB: query / upsert (OnConflict)
  EntDB-->>Adapter: entity / error
  Adapter-->>Service: domain result
  Service-->>Client: response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

area/product-catalog, area/billing

Suggested reviewers

  • tothandras
  • mark-vass-konghq
  • 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 title accurately describes the main changes: adding organization default tax codes service and refactoring to taxcode.Service, which is reflected throughout the changeset.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/org-tax-config-service

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 force-pushed the feat/org-tax-config-service branch from 6e325ea to 231ba12 Compare May 7, 2026 08:30
@borbelyr-kong
borbelyr-kong marked this pull request as ready for review May 7, 2026 08:30
@borbelyr-kong
borbelyr-kong requested a review from a team as a code owner May 7, 2026 08:30

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

🧹 Nitpick comments (5)
openmeter/taxcode/taxcode.go (1)

148-180: 💤 Low value

Validate() looks solid — one design note worth considering

The validation correctly enforces non-empty InvoicingTaxCodeID and CreditGrantTaxCodeID, matching the pattern from TaxCode.Validate(). Just worth double-checking: is it intentional that both IDs must always be set? If a future use case needs only one default (e.g. invoicing-only org with no credit grants), this validation would need to be revisited. If that's by design, maybe a quick comment on the struct would help future readers.

🤖 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/taxcode.go` around lines 148 - 180, The Validate method
currently enforces that both InvoicingTaxCodeID and CreditGrantTaxCodeID must be
non-empty; if this is intentional, add a concise doc comment on the
OrganizationDefaultTaxCodes type stating that both IDs are required by design
(reference InvoicingTaxCodeID, CreditGrantTaxCodeID and
OrganizationDefaultTaxCodes.Validate) so future readers know why both fields are
mandatory; if the requirement is different, update
OrganizationDefaultTaxCodes.Validate to only require the appropriate ID(s)
instead (e.g., allow empty CreditGrantTaxCodeID for invoicing-only orgs) and
adjust tests accordingly.
openmeter/taxcode/service.go (1)

207-243: 💤 Low value

Tiny consistency nit on Validate() style.

GetOrganizationDefaultTaxCodesInput.Validate returns immediately on empty namespace, while every other Validate in this file (including the sibling UpsertOrganizationDefaultTaxCodesInput) uses the errs []error + errors.Join accumulator. Functionally identical here since there's only one rule, but using the same shape across the file makes future additions easier:

♻️ Optional consistency tweak
 func (i GetOrganizationDefaultTaxCodesInput) Validate() error {
-	if i.Namespace == "" {
-		return models.NewNillableGenericValidationError(ErrResourceNamespaceEmpty)
-	}
-
-	return nil
+	var errs []error
+
+	if i.Namespace == "" {
+		errs = append(errs, ErrResourceNamespaceEmpty)
+	}
+
+	return models.NewNillableGenericValidationError(errors.Join(errs...))
 }
🤖 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.go` around lines 207 - 243,
GetOrganizationDefaultTaxCodesInput.Validate uses an early-return for namespace
validation while other validators (e.g.,
UpsertOrganizationDefaultTaxCodesInput.Validate) accumulate errors into errs and
call models.NewNillableGenericValidationError(errors.Join(errs...)); update
GetOrganizationDefaultTaxCodesInput.Validate to follow the same pattern: create
errs []error, append ErrResourceNamespaceEmpty when Namespace == "", then return
models.NewNillableGenericValidationError(errors.Join(errs...)) so it matches the
style of UpsertOrganizationDefaultTaxCodesInput.Validate and is ready for future
rules.
openmeter/taxcode/adapter/organizationdefaulttaxcodes.go (2)

100-104: 💤 Low value

Tiny nit: re-using GetOrganizationDefaultTaxCodes re-validates and re-wraps.

Calling the public GetOrganizationDefaultTaxCodes here is convenient and keeps mapping logic in one place — totally fine. Just be aware it will re-run input.Validate() and start another entutils.TransactingRepo scope (which will reuse the existing tx via context, so no real harm). If you want to skip the redundant work, you could extract the inner query+map into an unexported helper and call it from both places. Pure polish; happy as-is too.

🤖 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/adapter/organizationdefaulttaxcodes.go` around lines 100 -
104, The public GetOrganizationDefaultTaxCodes call here re-runs
input.Validate() and opens another entutils.TransactingRepo scope; to avoid that
redundant validation/transaction-wrapping extract the inner query+mapping logic
into an unexported helper (e.g., organizationDefaultTaxCodesQuery or
getOrganizationDefaultTaxCodesNoValidate) that accepts ctx and the
already-validated input struct, then have both the public
GetOrganizationDefaultTaxCodes and this internal caller invoke that helper
instead of calling GetOrganizationDefaultTaxCodes directly.

64-98: 💤 Low value

Optional: handle namespace race on create-time conflicts.

The unique partial index on namespace (WHERE deleted_at IS NULL) means two concurrent upserts for a new namespace can both see existing == nil, hit Create, and one returns a conflict error instead of succeeding. Since this is meant to be idempotent, a friendly improvement would retry the read-then-update path on constraint errors from Create:

♻️ Suggested retry on create-time conflict
 		} else {
 			_, err = a.db.OrganizationDefaultTaxCodes.Create().
 				SetNamespace(input.Namespace).
 				SetInvoicingTaxCodeID(input.InvoicingTaxCodeID).
 				SetCreditGrantTaxCodeID(input.CreditGrantTaxCodeID).
 				Save(ctx)
 			if err != nil {
 				if db.IsConstraintError(err) {
-					return taxcode.OrganizationDefaultTaxCodes{}, models.NewGenericConflictError(fmt.Errorf("invalid tax code reference"))
+					// Could be a unique-namespace race with a concurrent insert,
+					// or a real FK violation. Re-read and update if a row now exists.
+					if row, qerr := a.db.OrganizationDefaultTaxCodes.Query().
+						Where(orgdefaultsdb.NamespaceEQ(input.Namespace)).
+						Where(orgdefaultsdb.DeletedAtIsNil()).
+						Only(ctx); qerr == nil && row != nil {
+						if _, uerr := a.db.OrganizationDefaultTaxCodes.UpdateOneID(row.ID).
+							SetInvoicingTaxCodeID(input.InvoicingTaxCodeID).
+							SetCreditGrantTaxCodeID(input.CreditGrantTaxCodeID).
+							Save(ctx); uerr == nil {
+							return a.GetOrganizationDefaultTaxCodes(ctx, taxcode.GetOrganizationDefaultTaxCodesInput{
+								Namespace: input.Namespace,
+								Expand:    input.Expand,
+							})
+						}
+					}
+					return taxcode.OrganizationDefaultTaxCodes{}, models.NewGenericConflictError(fmt.Errorf("invalid tax code reference"))
 				}

Also worth noting: db.IsConstraintError catches both FK violations and unique-constraint violations, but the error message "invalid tax code reference" only hints at the FK case. When it's actually a namespace race, operators might be confused. Consider a more neutral message or distinguishing the two.

🤖 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/adapter/organizationdefaulttaxcodes.go` around lines 64 -
98, The create branch can race on the partial-unique index (namespace WHERE
deleted_at IS NULL), causing a constraint error even though the intended result
exists; update the logic in the adapter transaction (the
entutils.TransactingRepo closure working with
a.db.OrganizationDefaultTaxCodes.Create/UpdateOneID) so that when Create returns
a db.IsConstraintError you distinguish FK vs unique-constraint cases and, for
the unique-constraint (namespace race), re-query the record (same
Query().Where(orgdefaultsdb.NamespaceEQ(input.Namespace)).Where(orgdefaultsdb.DeletedAtIsNil()).Only(ctx))
and then perform the UpdateOneID(existing.ID) path to set the tax code IDs and
Save(ctx); only if the re-query shows no existing record or the constraint is an
FK should you return models.NewGenericConflictError(fmt.Errorf("invalid tax code
reference")) (or a neutral conflict message for namespace-unique violations),
otherwise return the update result or the original error.
openmeter/taxcode/service/organizationdefaulttaxcodes.go (1)

21-42: 💤 Low value

Optional: skip the second lookup when both IDs are the same.

If a caller passes the same value for InvoicingTaxCodeID and CreditGrantTaxCodeID (which the test SameTaxCodeForBothFields shows is a valid case), you'll do two identical GetTaxCode round trips. A tiny short-circuit avoids that:

♻️ Proposed micro-optimization
 	return transaction.Run(ctx, s.orgDefaultsAdapter, func(ctx context.Context) (taxcode.OrganizationDefaultTaxCodes, error) {
 		// Ensure both tax code IDs belong to the namespace.
 		if _, err := s.GetTaxCode(ctx, taxcode.GetTaxCodeInput{
 			NamespacedID: models.NamespacedID{Namespace: input.Namespace, ID: input.InvoicingTaxCodeID},
 		}); err != nil {
 			return taxcode.OrganizationDefaultTaxCodes{}, err
 		}
 
-		if _, err := s.GetTaxCode(ctx, taxcode.GetTaxCodeInput{
-			NamespacedID: models.NamespacedID{Namespace: input.Namespace, ID: input.CreditGrantTaxCodeID},
-		}); err != nil {
-			return taxcode.OrganizationDefaultTaxCodes{}, err
+		if input.CreditGrantTaxCodeID != input.InvoicingTaxCodeID {
+			if _, err := s.GetTaxCode(ctx, taxcode.GetTaxCodeInput{
+				NamespacedID: models.NamespacedID{Namespace: input.Namespace, ID: input.CreditGrantTaxCodeID},
+			}); err != nil {
+				return taxcode.OrganizationDefaultTaxCodes{}, err
+			}
 		}

Pure nit — the existing version is perfectly correct, just slightly chatty with the DB.

🤖 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/organizationdefaulttaxcodes.go` around lines 21 -
42, The UpsertOrganizationDefaultTaxCodes method currently calls GetTaxCode
twice even when input.InvoicingTaxCodeID == input.CreditGrantTaxCodeID; modify
the function so after validating input you call GetTaxCode once for the
invoicing ID (using s.GetTaxCode with taxcode.GetTaxCodeInput/NamespacedID) and
only call s.GetTaxCode for the creditGrant ID if input.CreditGrantTaxCodeID !=
input.InvoicingTaxCodeID; keep the same error handling and final return of
s.orgDefaultsAdapter.UpsertOrganizationDefaultTaxCodes.
🤖 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.

Nitpick comments:
In `@openmeter/taxcode/adapter/organizationdefaulttaxcodes.go`:
- Around line 100-104: The public GetOrganizationDefaultTaxCodes call here
re-runs input.Validate() and opens another entutils.TransactingRepo scope; to
avoid that redundant validation/transaction-wrapping extract the inner
query+mapping logic into an unexported helper (e.g.,
organizationDefaultTaxCodesQuery or getOrganizationDefaultTaxCodesNoValidate)
that accepts ctx and the already-validated input struct, then have both the
public GetOrganizationDefaultTaxCodes and this internal caller invoke that
helper instead of calling GetOrganizationDefaultTaxCodes directly.
- Around line 64-98: The create branch can race on the partial-unique index
(namespace WHERE deleted_at IS NULL), causing a constraint error even though the
intended result exists; update the logic in the adapter transaction (the
entutils.TransactingRepo closure working with
a.db.OrganizationDefaultTaxCodes.Create/UpdateOneID) so that when Create returns
a db.IsConstraintError you distinguish FK vs unique-constraint cases and, for
the unique-constraint (namespace race), re-query the record (same
Query().Where(orgdefaultsdb.NamespaceEQ(input.Namespace)).Where(orgdefaultsdb.DeletedAtIsNil()).Only(ctx))
and then perform the UpdateOneID(existing.ID) path to set the tax code IDs and
Save(ctx); only if the re-query shows no existing record or the constraint is an
FK should you return models.NewGenericConflictError(fmt.Errorf("invalid tax code
reference")) (or a neutral conflict message for namespace-unique violations),
otherwise return the update result or the original error.

In `@openmeter/taxcode/service.go`:
- Around line 207-243: GetOrganizationDefaultTaxCodesInput.Validate uses an
early-return for namespace validation while other validators (e.g.,
UpsertOrganizationDefaultTaxCodesInput.Validate) accumulate errors into errs and
call models.NewNillableGenericValidationError(errors.Join(errs...)); update
GetOrganizationDefaultTaxCodesInput.Validate to follow the same pattern: create
errs []error, append ErrResourceNamespaceEmpty when Namespace == "", then return
models.NewNillableGenericValidationError(errors.Join(errs...)) so it matches the
style of UpsertOrganizationDefaultTaxCodesInput.Validate and is ready for future
rules.

In `@openmeter/taxcode/service/organizationdefaulttaxcodes.go`:
- Around line 21-42: The UpsertOrganizationDefaultTaxCodes method currently
calls GetTaxCode twice even when input.InvoicingTaxCodeID ==
input.CreditGrantTaxCodeID; modify the function so after validating input you
call GetTaxCode once for the invoicing ID (using s.GetTaxCode with
taxcode.GetTaxCodeInput/NamespacedID) and only call s.GetTaxCode for the
creditGrant ID if input.CreditGrantTaxCodeID != input.InvoicingTaxCodeID; keep
the same error handling and final return of
s.orgDefaultsAdapter.UpsertOrganizationDefaultTaxCodes.

In `@openmeter/taxcode/taxcode.go`:
- Around line 148-180: The Validate method currently enforces that both
InvoicingTaxCodeID and CreditGrantTaxCodeID must be non-empty; if this is
intentional, add a concise doc comment on the OrganizationDefaultTaxCodes type
stating that both IDs are required by design (reference InvoicingTaxCodeID,
CreditGrantTaxCodeID and OrganizationDefaultTaxCodes.Validate) so future readers
know why both fields are mandatory; if the requirement is different, update
OrganizationDefaultTaxCodes.Validate to only require the appropriate ID(s)
instead (e.g., allow empty CreditGrantTaxCodeID for invoicing-only orgs) and
adjust tests accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f02bee52-3152-4587-bc2c-de63a824311a

📥 Commits

Reviewing files that changed from the base of the PR and between 77577d3 and 231ba12.

📒 Files selected for processing (24)
  • app/common/taxcode.go
  • cmd/billing-worker/wire_gen.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
  • openmeter/productcatalog/tax_test.go
  • openmeter/productcatalog/testutils/env.go
  • openmeter/server/server_test.go
  • openmeter/subscription/testutils/service.go
  • openmeter/taxcode/adapter/adapter.go
  • openmeter/taxcode/adapter/organizationdefaulttaxcodes.go
  • openmeter/taxcode/errors.go
  • openmeter/taxcode/repository.go
  • openmeter/taxcode/service.go
  • openmeter/taxcode/service/organizationdefaulttaxcodes.go
  • openmeter/taxcode/service/organizationdefaulttaxcodes_test.go
  • openmeter/taxcode/service/service.go
  • openmeter/taxcode/service/taxcode.go
  • openmeter/taxcode/taxcode.go
  • openmeter/taxcode/testutils/env.go
  • test/app/testenv.go
  • test/billing/subscription_suite.go
  • test/billing/suite.go
  • test/customer/testenv.go
  • test/subscription/framework_test.go

var _ taxcode.OrganizationDefaultTaxCodesRepository = (*adapter)(nil)

// NewOrganizationDefaultTaxCodesAdapter creates an adapter satisfying OrganizationDefaultTaxCodesRepository.
func NewOrganizationDefaultTaxCodesAdapter(config Config) (taxcode.OrganizationDefaultTaxCodesRepository, error) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feel free to add this to the original adapter. This is just a db abstraction.

Comment on lines +65 to +148
existing, err := a.db.OrganizationDefaultTaxCodes.Query().
Where(orgdefaultsdb.NamespaceEQ(input.Namespace)).
Where(orgdefaultsdb.DeletedAtIsNil()).
Only(ctx)
if err != nil && !db.IsNotFound(err) {
return taxcode.OrganizationDefaultTaxCodes{}, fmt.Errorf("failed to query organization default tax codes: %w", err)
}

if existing != nil {
_, err = a.db.OrganizationDefaultTaxCodes.UpdateOneID(existing.ID).
SetInvoicingTaxCodeID(input.InvoicingTaxCodeID).
SetCreditGrantTaxCodeID(input.CreditGrantTaxCodeID).
Save(ctx)
if err != nil {
if db.IsConstraintError(err) {
return taxcode.OrganizationDefaultTaxCodes{}, models.NewGenericConflictError(fmt.Errorf("invalid tax code reference"))
}

return taxcode.OrganizationDefaultTaxCodes{}, fmt.Errorf("failed to update organization default tax codes: %w", err)
}
} else {
_, err = a.db.OrganizationDefaultTaxCodes.Create().
SetNamespace(input.Namespace).
SetInvoicingTaxCodeID(input.InvoicingTaxCodeID).
SetCreditGrantTaxCodeID(input.CreditGrantTaxCodeID).
Save(ctx)
if err != nil {
if db.IsConstraintError(err) {
return taxcode.OrganizationDefaultTaxCodes{}, models.NewGenericConflictError(fmt.Errorf("invalid tax code reference"))
}

return taxcode.OrganizationDefaultTaxCodes{}, fmt.Errorf("failed to create organization default tax codes: %w", err)
}
}

return a.GetOrganizationDefaultTaxCodes(ctx, taxcode.GetOrganizationDefaultTaxCodesInput{
Namespace: input.Namespace,
Expand: input.Expand,
})
})
}

func mapOrganizationDefaultTaxCodesFromEntity(entity *db.OrganizationDefaultTaxCodes, expand taxcode.OrganizationDefaultTaxCodesExpand) (taxcode.OrganizationDefaultTaxCodes, error) {
result := taxcode.OrganizationDefaultTaxCodes{
NamespacedID: models.NamespacedID{
Namespace: entity.Namespace,
ID: entity.ID,
},
ManagedModel: models.ManagedModel{
CreatedAt: entity.CreatedAt,
UpdatedAt: entity.UpdatedAt,
DeletedAt: entity.DeletedAt,
},
InvoicingTaxCodeID: entity.InvoicingTaxCodeID,
CreditGrantTaxCodeID: entity.CreditGrantTaxCodeID,
}

if expand.InvoicingTaxCode {
invoicingEdge, err := entity.Edges.InvoicingTaxCodeOrErr()
if err != nil {
return taxcode.OrganizationDefaultTaxCodes{}, fmt.Errorf("failed to load invoicing_tax_code edge: %w", err)
}

invoicingTaxCode, err := MapTaxCodeFromEntity(invoicingEdge)
if err != nil {
return taxcode.OrganizationDefaultTaxCodes{}, err
}

result.InvoicingTaxCode = &invoicingTaxCode
}

if expand.CreditGrantTaxCode {
creditGrantEdge, err := entity.Edges.CreditGrantTaxCodeOrErr()
if err != nil {
return taxcode.OrganizationDefaultTaxCodes{}, fmt.Errorf("failed to load credit_grant_tax_code edge: %w", err)
}

creditGrantTaxCode, err := MapTaxCodeFromEntity(creditGrantEdge)
if err != nil {
return taxcode.OrganizationDefaultTaxCodes{}, err
}

result.CreditGrantTaxCode = &creditGrantTaxCode
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of this please use the insert into on conflict update clause like documented here: https://entgo.io/docs/crud/#upsert-one

@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 `@openmeter/taxcode/adapter/organizationdefaulttaxcodes.go`:
- Around line 63-66: The current constraint error handling in the upsert path
(organizationdefaulttaxcodes.go) treats all constraint failures the same,
returning a misleading "invalid tax code reference" for both FK and
unique-constraint violations; update the error branch in the function handling
this DB upsert to distinguish FK vs unique constraint (or broaden the message):
use the DB helper that detects foreign-key violations (e.g.,
db.IsForeignKeyError or check Postgres code 23503) to return a clear "invalid
tax code reference" / not-found style error, and for unique constraint
violations (e.g., db.IsUniqueConstraintError or code 23505) return a
GenericConflictError with a message indicating a namespace/unique constraint
conflict (or a neutral message like "constraint violation"), referencing the
existing error handling block that currently calls
models.NewGenericConflictError(fmt.Errorf("invalid tax code reference")) so you
replace that single branch with conditional checks for FK vs unique and produce
appropriate error messages.
🪄 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: 2a8bc938-75fd-46c5-817e-9e88917852c4

📥 Commits

Reviewing files that changed from the base of the PR and between 231ba12 and b8c5dab.

📒 Files selected for processing (16)
  • app/common/taxcode.go
  • cmd/billing-worker/wire_gen.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
  • openmeter/productcatalog/testutils/env.go
  • openmeter/subscription/testutils/service.go
  • openmeter/taxcode/adapter/organizationdefaulttaxcodes.go
  • openmeter/taxcode/repository.go
  • openmeter/taxcode/service/organizationdefaulttaxcodes.go
  • openmeter/taxcode/service/service.go
  • openmeter/taxcode/testutils/env.go
  • test/app/testenv.go
  • test/billing/subscription_suite.go
  • test/billing/suite.go
  • test/customer/testenv.go
  • test/subscription/framework_test.go
🚧 Files skipped from review as they are similar to previous changes (13)
  • openmeter/subscription/testutils/service.go
  • openmeter/taxcode/testutils/env.go
  • test/billing/suite.go
  • openmeter/productcatalog/testutils/env.go
  • test/customer/testenv.go
  • openmeter/taxcode/repository.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
  • test/subscription/framework_test.go
  • test/billing/subscription_suite.go
  • openmeter/taxcode/service/organizationdefaulttaxcodes.go
  • app/common/taxcode.go
  • test/app/testenv.go

Comment on lines +63 to +66
if err != nil {
if db.IsConstraintError(err) {
return taxcode.OrganizationDefaultTaxCodes{}, models.NewGenericConflictError(fmt.Errorf("invalid tax code reference"))
}

@coderabbitai coderabbitai Bot May 7, 2026 •

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 | 🟡 Minor | ⚡ Quick win

Constraint error handling conflates FK and unique violations 🤔

db.IsConstraintError catches both foreign-key failures (invalid tax code ID) and unique constraint violations (e.g. namespace already has a non-deleted row, which won't match the partial-index conflict target). Both currently return the same GenericConflictError with the message "invalid tax code reference", which would be confusing to a caller whose upsert failed because of a soft-deleted namespace collision, not a bad tax code ID.

Consider distinguishing between the two, or at minimum broadening the error message so it doesn't mislead:

✏️ Suggested tweak
-			return taxcode.OrganizationDefaultTaxCodes{}, models.NewGenericConflictError(fmt.Errorf("invalid tax code reference"))
+			return taxcode.OrganizationDefaultTaxCodes{}, models.NewGenericConflictError(fmt.Errorf("constraint violation: check tax code references and namespace uniqueness"))
📝 Committable suggestion

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

Suggested change
if err != nil {
if db.IsConstraintError(err) {
return taxcode.OrganizationDefaultTaxCodes{}, models.NewGenericConflictError(fmt.Errorf("invalid tax code reference"))
}
if err != nil {
if db.IsConstraintError(err) {
return taxcode.OrganizationDefaultTaxCodes{}, models.NewGenericConflictError(fmt.Errorf("constraint violation: check tax code references and namespace uniqueness"))
}
🤖 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/adapter/organizationdefaulttaxcodes.go` around lines 63 -
66, The current constraint error handling in the upsert path
(organizationdefaulttaxcodes.go) treats all constraint failures the same,
returning a misleading "invalid tax code reference" for both FK and
unique-constraint violations; update the error branch in the function handling
this DB upsert to distinguish FK vs unique constraint (or broaden the message):
use the DB helper that detects foreign-key violations (e.g.,
db.IsForeignKeyError or check Postgres code 23503) to return a clear "invalid
tax code reference" / not-found style error, and for unique constraint
violations (e.g., db.IsUniqueConstraintError or code 23505) return a
GenericConflictError with a message indicating a namespace/unique constraint
conflict (or a neutral message like "constraint violation"), referencing the
existing error handling block that currently calls
models.NewGenericConflictError(fmt.Errorf("invalid tax code reference")) so you
replace that single branch with conditional checks for FK vs unique and produce
appropriate error messages.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We won't soft-delete these configs in practice, so the soft-deleted-row scenario doesn't apply.

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.

@borbelyr-kong That makes total sense! If these records are never soft-deleted in practice, then the only real constraint violation hitting that branch would be FK failures (invalid tax code IDs), so the "invalid tax code reference" message is accurate. Happy to close this one out. 👍


✏️ Learnings added
Learnt from: borbelyr-kong
Repo: openmeterio/openmeter PR: 4308
File: openmeter/taxcode/adapter/organizationdefaulttaxcodes.go:63-66
Timestamp: 2026-05-07T19:32:35.491Z
Learning: In openmeter/taxcode/adapter/organizationdefaulttaxcodes.go, organization default tax code records (OrganizationDefaultTaxCodes) are never soft-deleted in practice. The partial-index conflict target using `sql.ConflictWhere(sql.IsNull(orgdefaultsdb.FieldDeletedAt))` is a guard rather than a soft-delete workflow. Therefore, in the upsert path the only realistic constraint error is a foreign-key violation (invalid tax code ID reference), and returning `models.NewGenericConflictError(fmt.Errorf("invalid tax code reference"))` for all constraint errors is intentional and correct — do not flag it as conflating FK vs unique-constraint violations.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: turip
Repo: openmeterio/openmeter PR: 4053
File: openmeter/billing/charges/usagebased/adapter/charge.go:117-121
Timestamp: 2026-04-01T15:31:02.589Z
Learning: In this codebase, database transactions are propagated through `context.Context` using `entutils.TransactingRepo` / `entutils.TransactingRepoWithNoValue` together with `SetDriverOnContext` / `GetDriverFromContext`. When a nested call also uses these helpers and the same `ctx` is threaded through, it should automatically join/reuse the existing transaction (including when an adapter field such as `metaAdapter` is not explicitly wrapped with the tx). During code review, do not flag a call as “outside the transaction” solely because a specific adapter instance isn’t wrapped, as long as the transaction driver is obtainable from the provided `ctx` via these helpers.

Learnt from: borosr
Repo: openmeterio/openmeter PR: 4245
File: openmeter/productcatalog/addon/httpdriver/addon.go:55-60
Timestamp: 2026-04-28T15:03:41.943Z
Learning: In this repo, treat Go type aliases correctly when reviewing type-mismatch complaints. If a symbol is declared as a type alias (e.g., `type CurrencyCode = string`), then it is identical to the aliased type—so `[]api.CurrencyCode` is directly assignable to `[]string` (and vice versa) with no explicit conversion needed. Do not flag direct assignments between slices of a type alias and slices of the underlying aliased type as type mismatch errors. Only require conversions when the symbol is a new defined type (e.g., `type CurrencyCode string`), not when it is an alias (`type CurrencyCode = string`).

@borbelyr-kong
borbelyr-kong merged commit cae0526 into main May 11, 2026
27 checks passed
@borbelyr-kong
borbelyr-kong deleted the feat/org-tax-config-service branch May 11, 2026 10:53

This branch was previously deployed

1 inactive deployment
dev — eda5875f Deployed May 7, 2026 by borbelyr-kong via Migration Checks #14201
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