Skip to content

feat(backend): add tax code service - #3892

Merged
tothandras merged 6 commits into
mainfrom
feat/tax-codes-handlers
Feb 23, 2026
Merged

tothandras merged 6 commits into
mainfrom
feat/tax-codes-handlers

Conversation

@tothandras

@tothandras tothandras commented Feb 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features
    • Full tax code management: create, read, update, delete with namespace support, soft-delete, and pagination.
    • Service and repository surfaces for tax code operations with transaction support.
  • Improvements
    • Stronger input validation and domain-specific errors (not-found, conflict, field issues).
    • App type validation tightened and Stripe tax-code validation centralized.
    • App-mapping support and metadata handling for tax codes.

@tothandras
tothandras requested a review from a team as a code owner February 23, 2026 14:13
@tothandras tothandras added the release-note/ignore Ignore this change when generating release notes label Feb 23, 2026
@coderabbitai

coderabbitai Bot commented Feb 23, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4ca889f and e195d75.

⛔ Files ignored due to path filters (1)
  • openmeter/ent/db/app_create.go is excluded by !**/ent/db/**
📒 Files selected for processing (1)
  • test/billing/subscription_test.go

📝 Walkthrough

Walkthrough

Adds a new taxcode domain: public service and repository interfaces, domain models and errors, an Ent-backed, transaction-aware adapter with CRUD + mapping, and a service implementation wiring transactions and logging.

Changes

Cohort / File(s) Summary
Repository & Service Contracts
openmeter/taxcode/repository.go, openmeter/taxcode/service.go
Adds Repository and Service interfaces and five validated input types (Create/Update/List/Get/Delete). Repository embeds transaction creator contract.
Adapter core & plumbing
openmeter/taxcode/adapter/adapter.go
New Ent adapter Config (with Validate), constructor New, adapter struct, and transaction helpers Tx, WithTx, Self plus type assertions.
Adapter CRUD & mapping
openmeter/taxcode/adapter/taxcode.go, openmeter/taxcode/adapter/mapping.go
Implements Ent-backed CRUD (Create/Update/List/Get/Delete) using transactional helpers and entity→domain mapping (mapTaxCodeFromEntity). Handles not-found/conflict errors, app_mappings, and metadata mapping.
Domain models & validation
openmeter/taxcode/taxcode.go
Adds TaxCode, TaxCodeAppMapping(s) types with validation (required fields, unique app types, namespaced IDs) and validation helpers.
Domain errors
openmeter/taxcode/errors.go
Introduces taxcode-specific error codes and models.ValidationIssue variables plus NewTaxCodeNotFoundError.
Service implementation
openmeter/taxcode/service/taxcode.go
Service struct + New constructor that delegates repo calls inside transactional runners and logs operations.
App & product changes
openmeter/app/appbase.go, openmeter/productcatalog/tax.go, test/billing/subscription_test.go
Adds AppType.Validate() (allows custom_invoicing), centralizes Stripe tax-code regexp use, and updates a test to use AppTypeCustomInvoicing.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant Service as TaxCode Service
    participant Repo as TaxCode Repository (adapter)
    participant EntDB as entdb.Client
    participant SQL as SQL Tx

    Client->>Service: CreateTaxCode(input)
    Service->>Repo: CreateTaxCode(ctx, input)
    Repo->>EntDB: Begin transaction / persist entity
    EntDB->>SQL: Begin Tx (driver hijack)
    EntDB->>SQL: Insert TaxCode + app_mappings
    SQL-->>EntDB: Commit
    EntDB-->>Repo: Entity
    Repo-->>Service: Mapped TaxCode
    Service-->>Client: TaxCode
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested labels

release-note/feature, area/billing

Suggested reviewers

  • borbelyr-kong
  • hekike
  • turip
🚥 Pre-merge checks | ✅ 2 | ❌ 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 (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(backend): add tax code service' accurately describes the main change - introducing a new tax code service with repository, adapter, and CRUD operations.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/tax-codes-handlers

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.

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

🧹 Nitpick comments (3)
openmeter/taxcode/adapter/taxcode.go (1)

70-70: Consider breaking this long query chain for readability.

This line is getting pretty wide. Breaking it across multiple lines would make it easier to scan. Same applies to the queries in GetTaxCode (line 85) and DeleteTaxCode (line 104).

♻️ Example
-		entities, err := a.db.TaxCode.Query().Where(taxcodedb.Namespace(input.Namespace)).Where(taxcodedb.DeletedAtIsNil()).Paginate(ctx, input.Page)
+		entities, err := a.db.TaxCode.Query().
+			Where(taxcodedb.Namespace(input.Namespace)).
+			Where(taxcodedb.DeletedAtIsNil()).
+			Paginate(ctx, input.Page)

As per coding guidelines: "In general when reviewing the Golang code make readability and maintainability a priority."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/taxcode/adapter/taxcode.go` at line 70, The long chained Ent
queries (e.g., the call starting with a.db.TaxCode.Query() that uses
taxcodedb.Namespace, taxcodedb.DeletedAtIsNil() and Paginate(ctx, input.Page))
should be broken across multiple lines for readability; refactor that assignment
in the List/Query path and the similar chained calls inside GetTaxCode and
DeleteTaxCode so each call (Query(), Where(taxcodedb.Namespace(...)),
Where(taxcodedb.DeletedAtIsNil()), Paginate(...)/Only()/Delete()) is on its own
indented line, preserving the same method order and arguments but improving
scanability. Ensure you keep ctx and input.Page/IDs unchanged and run gofmt.
openmeter/taxcode/service/taxcode.go (1)

16-21: Constructor doesn't validate nil inputs.

If adapter or logger is nil, this will happily create a service that panics on first use. The adapter's New() validates its config — might be worth doing the same here for consistency, or at minimum a nil check on the adapter.

🛡️ Suggested guard
 func New(adapter taxcode.Repository, logger *slog.Logger) taxcode.Service {
+	if adapter == nil {
+		panic("taxcode: adapter is required")
+	}
+	if logger == nil {
+		panic("taxcode: logger is required")
+	}
 	return &service{
 		adapter: adapter,
 		logger:  logger,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/taxcode/service/taxcode.go` around lines 16 - 21, The constructor
New should guard against nil inputs to avoid later panics: add explicit nil
checks at the start of New for adapter (taxcode.Repository) and logger
(*slog.Logger) and raise a clear panic (e.g., panic("taxcode: adapter is nil") /
panic("taxcode: logger is nil")) or otherwise fail fast, then return the
&service{...}; ensure you reference the New function and service struct so
callers immediately see the validation consistent with the adapter's own New().
openmeter/taxcode/taxcode.go (1)

56-72: TaxCode.Validate() doesn't check Key or Name for emptiness.

The input types (CreateTaxCodeInput, UpdateTaxCodeInput) validate these fields, so this is probably fine for the current usage. Just flagging in case TaxCode.Validate() is ever called directly on a domain object constructed outside the normal flow — it would silently allow empty key/name.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/taxcode/taxcode.go` around lines 56 - 72, TaxCode.Validate()
currently omits checks for the Key and Name fields; add non-empty (e.g.,
strings.TrimSpace) checks for t.Key and t.Name inside TaxCode.Validate() and
append descriptive errors to errs (same slice used for
NamespacedID/ManagedModel/AppMappings checks) so the final
models.NewNillableGenericValidationError(errors.Join(errs...)) will include
missing-key/name errors when those fields are empty; reference the
TaxCode.Validate() method and the t.Key and t.Name fields when implementing the
checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@openmeter/taxcode/adapter/mapping.go`:
- Line 29: The code dereferences entity.AppMappings when building the mapping
object (AppMappings: *entity.AppMappings) which will panic if AppMappings is
nil; update the mapping construction in mapping.go to guard entity.AppMappings
(use entity.AppMappingsIsNil() or a nil check) and only dereference when
non-nil, otherwise set the resulting field to nil or an empty map as
appropriate; locate the assignment with AppMappings: *entity.AppMappings and
replace it with a conditional/nil-safe assignment to prevent the panic.

In `@openmeter/taxcode/adapter/taxcode.go`:
- Around line 42-62: The UpdateTaxCode function currently wraps any update error
generically; modify the error handling after Save(ctx) in UpdateTaxCode so that
if db.IsNotFound(err) returns true you return NewTaxCodeNotFoundError(err,
input.ID, input.Namespace) (matching GetTaxCode/DeleteTaxCode behavior),
otherwise wrap and return the original error as before; locate this in the
entutils.TransactingRepo closure around a.db.TaxCode.UpdateOneID(...) and adjust
the Save error branch accordingly so mapTaxCodeFromEntity is only called on
success.

---

Nitpick comments:
In `@openmeter/taxcode/adapter/taxcode.go`:
- Line 70: The long chained Ent queries (e.g., the call starting with
a.db.TaxCode.Query() that uses taxcodedb.Namespace, taxcodedb.DeletedAtIsNil()
and Paginate(ctx, input.Page)) should be broken across multiple lines for
readability; refactor that assignment in the List/Query path and the similar
chained calls inside GetTaxCode and DeleteTaxCode so each call (Query(),
Where(taxcodedb.Namespace(...)), Where(taxcodedb.DeletedAtIsNil()),
Paginate(...)/Only()/Delete()) is on its own indented line, preserving the same
method order and arguments but improving scanability. Ensure you keep ctx and
input.Page/IDs unchanged and run gofmt.

In `@openmeter/taxcode/service/taxcode.go`:
- Around line 16-21: The constructor New should guard against nil inputs to
avoid later panics: add explicit nil checks at the start of New for adapter
(taxcode.Repository) and logger (*slog.Logger) and raise a clear panic (e.g.,
panic("taxcode: adapter is nil") / panic("taxcode: logger is nil")) or otherwise
fail fast, then return the &service{...}; ensure you reference the New function
and service struct so callers immediately see the validation consistent with the
adapter's own New().

In `@openmeter/taxcode/taxcode.go`:
- Around line 56-72: TaxCode.Validate() currently omits checks for the Key and
Name fields; add non-empty (e.g., strings.TrimSpace) checks for t.Key and t.Name
inside TaxCode.Validate() and append descriptive errors to errs (same slice used
for NamespacedID/ManagedModel/AppMappings checks) so the final
models.NewNillableGenericValidationError(errors.Join(errs...)) will include
missing-key/name errors when those fields are empty; reference the
TaxCode.Validate() method and the t.Key and t.Name fields when implementing the
checks.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cf041a1 and 6d3da96.

📒 Files selected for processing (8)
  • openmeter/taxcode/adapter/adapter.go
  • openmeter/taxcode/adapter/mapping.go
  • openmeter/taxcode/adapter/taxcode.go
  • openmeter/taxcode/errors.go
  • openmeter/taxcode/repository.go
  • openmeter/taxcode/service.go
  • openmeter/taxcode/service/taxcode.go
  • openmeter/taxcode/taxcode.go

Comment thread openmeter/taxcode/adapter/mapping.go Resolved
Comment thread openmeter/taxcode/adapter/taxcode.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

66-69: Past review feedback addressed — nice!

The not-found handling for UpdateTaxCode is now properly in place, matching GetTaxCode and DeleteTaxCode.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/taxcode/adapter/taxcode.go` around lines 66 - 69, UpdateTaxCode's
error branch must mirror GetTaxCode/DeleteTaxCode: when db.IsNotFound(err)
return taxcode.TaxCode{} and taxcode.NewTaxCodeNotFoundError(input.ID). Locate
the error handling inside UpdateTaxCode (the db.IsNotFound(err) branch) and
ensure it returns the same typed not-found error; preserve the exact return
signature and message construction used by taxcode.NewTaxCodeNotFoundError so
callers receive consistent behavior.
🧹 Nitpick comments (4)
openmeter/taxcode/service.go (1)

107-130: GetTaxCodeInput and DeleteTaxCodeInput validators are identical — consider a shared helper.

Both types embed NamespacedID and have identical Validate() bodies. This is a very minor thing and totally fine as-is — just noting it since the pattern is exactly duplicated. If more input types follow this shape, a small embedded validator struct could reduce boilerplate.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/taxcode/service.go` around lines 107 - 130, Both
GetTaxCodeInput.Validate and DeleteTaxCodeInput.Validate duplicate the same
NamespacedID validation logic; refactor by extracting a shared validator (e.g.,
a small embedded type or helper function) that calls NamespacedID.Validate and
returns models.NewNillableGenericValidationError(errors.Join(...)), then have
GetTaxCodeInput and DeleteTaxCodeInput embed or call that shared validator so
their Validate methods delegate to the single implementation (referencing
GetTaxCodeInput, DeleteTaxCodeInput, NamespacedID, Validate, and
models.NewNillableGenericValidationError).
openmeter/app/appbase.go (1)

19-26: Looks good! One thought: AppBase.Validate() doesn't call AppType.Validate().

The new method is clean and correct. Just worth noting that AppBase.Validate() (line 117) doesn't invoke a.Type.Validate(), so the app type won't be validated unless callers explicitly do so. If that's intentional (e.g., validated elsewhere), no worries — just wanted to flag it in case it was overlooked.

💡 Optional: wire it into AppBase.Validate()
 func (a AppBase) Validate() error {
 	if err := a.ManagedResource.Validate(); err != nil {
 		return fmt.Errorf("error validating managed resource: %w", err)
 	}
+
+	if err := a.Type.Validate(); err != nil {
+		return fmt.Errorf("error validating app type: %w", err)
+	}
 
 	if a.ID == "" {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/app/appbase.go` around lines 19 - 26, AppBase.Validate currently
doesn't invoke AppType.Validate, so the app's Type (a.Type) isn't checked;
update the AppBase.Validate method to call a.Type.Validate() and return or wrap
that error (alongside existing validation) so invalid AppType values are
rejected; look for the AppBase.Validate function and add a.Type.Validate()
(handling its error) as part of the validation flow.
openmeter/taxcode/errors.go (1)

10-38: Consider whether these generic resource errors belong in a shared package.

ErrResourceNamespaceEmpty, ErrResourceKeyEmpty, and ErrResourceNameEmpty are pretty generic and likely useful across multiple domain packages. If other packages end up defining their own copies of these same errors, it'd be worth extracting them into a shared location to avoid duplication. Totally fine for now, just something to keep in mind as the codebase grows.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/taxcode/errors.go` around lines 10 - 38, These three generic
validation errors (ErrResourceNamespaceEmpty, ErrResourceKeyEmpty,
ErrResourceNameEmpty) should be evaluated for reuse and, if shared across
domains, extracted into a common/shared package (e.g., a new package like
common/errors or models/validation) so other packages can import them instead of
redefining; refactor by moving the NewValidationIssue declarations out of
openmeter/taxcode/errors.go into the shared package, export the same symbols
(ErrResourceNamespaceEmpty, ErrResourceKeyEmpty, ErrResourceNameEmpty), update
references/imports in taxcode to use the shared package, and remove any
duplicate definitions elsewhere to avoid drift.
openmeter/taxcode/adapter/taxcode.go (1)

121-151: Minor: two-step delete could be simplified to a single update.

The current fetch-then-update approach is correct within the transaction, but you could avoid the extra round-trip by doing a single conditional update and checking the affected row count. That said, the current code is clear and easy to follow, so this is totally optional.

💡 Single-step alternative
 func (a *adapter) DeleteTaxCode(ctx context.Context, input taxcode.DeleteTaxCodeInput) error {
 	return entutils.TransactingRepoWithNoValue(ctx, a, func(ctx context.Context, a *adapter) error {
 		if err := input.Validate(); err != nil {
 			return err
 		}
 
-		entity, err := a.db.TaxCode.Query().
-			Where(taxcodedb.Namespace(input.Namespace)).
-			Where(taxcodedb.ID(input.ID)).
-			Only(ctx)
+		affected, err := a.db.TaxCode.Update().
+			Where(taxcodedb.Namespace(input.Namespace)).
+			Where(taxcodedb.ID(input.ID)).
+			Where(taxcodedb.DeletedAtIsNil()).
+			SetDeletedAt(clock.Now()).
+			Save(ctx)
 		if err != nil {
-			if db.IsNotFound(err) {
-				return taxcode.NewTaxCodeNotFoundError(input.ID)
-			}
-
-			return fmt.Errorf("failed to get tax code: %w", err)
+			return fmt.Errorf("failed to delete tax code: %w", err)
 		}
 
-		if entity.DeletedAt == nil {
-			err := a.db.TaxCode.UpdateOneID(input.ID).
-				Where(taxcodedb.Namespace(input.Namespace)).
-				SetDeletedAt(clock.Now()).
-				Exec(ctx)
-			if err != nil {
-				return fmt.Errorf("failed to delete tax code: %w", err)
-			}
+		if affected == 0 {
+			return taxcode.NewTaxCodeNotFoundError(input.ID)
 		}
 
 		return nil
 	})
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/taxcode/adapter/taxcode.go` around lines 121 - 151, Replace the
fetch-then-update in DeleteTaxCode with a single conditional update: call
a.db.TaxCode.Update().Where(taxcodedb.ID(input.ID),
taxcodedb.Namespace(input.Namespace),
taxcodedb.DeletedAtIsNil()).SetDeletedAt(clock.Now()) (or the generated
predicate for DeletedAt nil) and execute it, then check the affected row count
(or result) — if zero, return taxcode.NewTaxCodeNotFoundError(input.ID);
otherwise return nil; keep input.Validate() and error wrapping consistent. This
removes the extra Query().Only round-trip while preserving the same
transactional semantics in adapter.DeleteTaxCode.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@openmeter/taxcode/adapter/taxcode.go`:
- Around line 66-69: UpdateTaxCode's error branch must mirror
GetTaxCode/DeleteTaxCode: when db.IsNotFound(err) return taxcode.TaxCode{} and
taxcode.NewTaxCodeNotFoundError(input.ID). Locate the error handling inside
UpdateTaxCode (the db.IsNotFound(err) branch) and ensure it returns the same
typed not-found error; preserve the exact return signature and message
construction used by taxcode.NewTaxCodeNotFoundError so callers receive
consistent behavior.

---

Nitpick comments:
In `@openmeter/app/appbase.go`:
- Around line 19-26: AppBase.Validate currently doesn't invoke AppType.Validate,
so the app's Type (a.Type) isn't checked; update the AppBase.Validate method to
call a.Type.Validate() and return or wrap that error (alongside existing
validation) so invalid AppType values are rejected; look for the
AppBase.Validate function and add a.Type.Validate() (handling its error) as part
of the validation flow.

In `@openmeter/taxcode/adapter/taxcode.go`:
- Around line 121-151: Replace the fetch-then-update in DeleteTaxCode with a
single conditional update: call
a.db.TaxCode.Update().Where(taxcodedb.ID(input.ID),
taxcodedb.Namespace(input.Namespace),
taxcodedb.DeletedAtIsNil()).SetDeletedAt(clock.Now()) (or the generated
predicate for DeletedAt nil) and execute it, then check the affected row count
(or result) — if zero, return taxcode.NewTaxCodeNotFoundError(input.ID);
otherwise return nil; keep input.Validate() and error wrapping consistent. This
removes the extra Query().Only round-trip while preserving the same
transactional semantics in adapter.DeleteTaxCode.

In `@openmeter/taxcode/errors.go`:
- Around line 10-38: These three generic validation errors
(ErrResourceNamespaceEmpty, ErrResourceKeyEmpty, ErrResourceNameEmpty) should be
evaluated for reuse and, if shared across domains, extracted into a
common/shared package (e.g., a new package like common/errors or
models/validation) so other packages can import them instead of redefining;
refactor by moving the NewValidationIssue declarations out of
openmeter/taxcode/errors.go into the shared package, export the same symbols
(ErrResourceNamespaceEmpty, ErrResourceKeyEmpty, ErrResourceNameEmpty), update
references/imports in taxcode to use the shared package, and remove any
duplicate definitions elsewhere to avoid drift.

In `@openmeter/taxcode/service.go`:
- Around line 107-130: Both GetTaxCodeInput.Validate and
DeleteTaxCodeInput.Validate duplicate the same NamespacedID validation logic;
refactor by extracting a shared validator (e.g., a small embedded type or helper
function) that calls NamespacedID.Validate and returns
models.NewNillableGenericValidationError(errors.Join(...)), then have
GetTaxCodeInput and DeleteTaxCodeInput embed or call that shared validator so
their Validate methods delegate to the single implementation (referencing
GetTaxCodeInput, DeleteTaxCodeInput, NamespacedID, Validate, and
models.NewNillableGenericValidationError).

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4611ade and 4ca889f.

📒 Files selected for processing (7)
  • openmeter/app/appbase.go
  • openmeter/productcatalog/tax.go
  • openmeter/taxcode/adapter/taxcode.go
  • openmeter/taxcode/errors.go
  • openmeter/taxcode/service.go
  • openmeter/taxcode/service/taxcode.go
  • openmeter/taxcode/taxcode.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • openmeter/taxcode/taxcode.go
  • openmeter/taxcode/service/taxcode.go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants