Repository navigation
feat(taxcode): add organization default tax codes service and refactor to taxcode.Service - #4308
Conversation
|
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughThis 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. ChangesOrganization Default Tax Codes Implementation
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 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 |
c01ac92 to
4b73858
Compare
6e325ea to
231ba12
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (5)
openmeter/taxcode/taxcode.go (1)
148-180: 💤 Low value
Validate()looks solid — one design note worth consideringThe validation correctly enforces non-empty
InvoicingTaxCodeIDandCreditGrantTaxCodeID, matching the pattern fromTaxCode.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 valueTiny consistency nit on
Validate()style.
GetOrganizationDefaultTaxCodesInput.Validatereturns immediately on empty namespace, while every otherValidatein this file (including the siblingUpsertOrganizationDefaultTaxCodesInput) uses theerrs []error+errors.Joinaccumulator. 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 valueTiny nit: re-using
GetOrganizationDefaultTaxCodesre-validates and re-wraps.Calling the public
GetOrganizationDefaultTaxCodeshere is convenient and keeps mapping logic in one place — totally fine. Just be aware it will re-runinput.Validate()and start anotherentutils.TransactingReposcope (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 valueOptional: 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.IsConstraintErrorcatches 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 valueOptional: skip the second lookup when both IDs are the same.
If a caller passes the same value for
InvoicingTaxCodeIDandCreditGrantTaxCodeID(which the testSameTaxCodeForBothFieldsshows is a valid case), you'll do two identicalGetTaxCoderound 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
📒 Files selected for processing (24)
app/common/taxcode.gocmd/billing-worker/wire_gen.gocmd/jobs/internal/wire_gen.gocmd/server/wire_gen.goopenmeter/productcatalog/tax_test.goopenmeter/productcatalog/testutils/env.goopenmeter/server/server_test.goopenmeter/subscription/testutils/service.goopenmeter/taxcode/adapter/adapter.goopenmeter/taxcode/adapter/organizationdefaulttaxcodes.goopenmeter/taxcode/errors.goopenmeter/taxcode/repository.goopenmeter/taxcode/service.goopenmeter/taxcode/service/organizationdefaulttaxcodes.goopenmeter/taxcode/service/organizationdefaulttaxcodes_test.goopenmeter/taxcode/service/service.goopenmeter/taxcode/service/taxcode.goopenmeter/taxcode/taxcode.goopenmeter/taxcode/testutils/env.gotest/app/testenv.gotest/billing/subscription_suite.gotest/billing/suite.gotest/customer/testenv.gotest/subscription/framework_test.go
| var _ taxcode.OrganizationDefaultTaxCodesRepository = (*adapter)(nil) | ||
|
|
||
| // NewOrganizationDefaultTaxCodesAdapter creates an adapter satisfying OrganizationDefaultTaxCodesRepository. | ||
| func NewOrganizationDefaultTaxCodesAdapter(config Config) (taxcode.OrganizationDefaultTaxCodesRepository, error) { |
There was a problem hiding this comment.
Feel free to add this to the original adapter. This is just a db abstraction.
| 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 | ||
| } |
There was a problem hiding this comment.
Instead of this please use the insert into on conflict update clause like documented here: https://entgo.io/docs/crud/#upsert-one
There was a problem hiding this comment.
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
📒 Files selected for processing (16)
app/common/taxcode.gocmd/billing-worker/wire_gen.gocmd/jobs/internal/wire_gen.gocmd/server/wire_gen.goopenmeter/productcatalog/testutils/env.goopenmeter/subscription/testutils/service.goopenmeter/taxcode/adapter/organizationdefaulttaxcodes.goopenmeter/taxcode/repository.goopenmeter/taxcode/service/organizationdefaulttaxcodes.goopenmeter/taxcode/service/service.goopenmeter/taxcode/testutils/env.gotest/app/testenv.gotest/billing/subscription_suite.gotest/billing/suite.gotest/customer/testenv.gotest/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
| if err != nil { | ||
| if db.IsConstraintError(err) { | ||
| return taxcode.OrganizationDefaultTaxCodes{}, models.NewGenericConflictError(fmt.Errorf("invalid tax code reference")) | ||
| } |
There was a problem hiding this comment.
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.
| 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.
There was a problem hiding this comment.
We won't soft-delete these configs in practice, so the soft-deleted-row scenario doesn't apply.
There was a problem hiding this comment.
@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`).
@coderabbitai
Summary by CodeRabbit
New Features
Bug Fixes