Repository navigation
feat(backend): add tax code service - #3892
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review infoConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAdds 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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) andDeleteTaxCode(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
adapterorloggeris nil, this will happily create a service that panics on first use. The adapter'sNew()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 checkKeyorNamefor emptiness.The input types (
CreateTaxCodeInput,UpdateTaxCodeInput) validate these fields, so this is probably fine for the current usage. Just flagging in caseTaxCode.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
📒 Files selected for processing (8)
openmeter/taxcode/adapter/adapter.goopenmeter/taxcode/adapter/mapping.goopenmeter/taxcode/adapter/taxcode.goopenmeter/taxcode/errors.goopenmeter/taxcode/repository.goopenmeter/taxcode/service.goopenmeter/taxcode/service/taxcode.goopenmeter/taxcode/taxcode.go
There was a problem hiding this comment.
♻️ Duplicate comments (1)
openmeter/taxcode/adapter/taxcode.go (1)
66-69: Past review feedback addressed — nice!The not-found handling for
UpdateTaxCodeis now properly in place, matchingGetTaxCodeandDeleteTaxCode.🤖 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:GetTaxCodeInputandDeleteTaxCodeInputvalidators are identical — consider a shared helper.Both types embed
NamespacedIDand have identicalValidate()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 callAppType.Validate().The new method is clean and correct. Just worth noting that
AppBase.Validate()(line 117) doesn't invokea.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, andErrResourceNameEmptyare 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
📒 Files selected for processing (7)
openmeter/app/appbase.goopenmeter/productcatalog/tax.goopenmeter/taxcode/adapter/taxcode.goopenmeter/taxcode/errors.goopenmeter/taxcode/service.goopenmeter/taxcode/service/taxcode.goopenmeter/taxcode/taxcode.go
🚧 Files skipped from review as they are similar to previous changes (2)
- openmeter/taxcode/taxcode.go
- openmeter/taxcode/service/taxcode.go
Summary by CodeRabbit