feat: add exact match search and handle freight template name conflicts

This commit is contained in:
BXY 2026-10-29 09:58:01 +08:00
parent 5934f1b5cf
commit 10034dbcee
4 changed files with 107 additions and 13 deletions

View File

@ -13,6 +13,7 @@ var (
ErrFreightTemplateNotFound = errors.New("freight template not found")
ErrFreightTemplateVersionConflict = errors.New("freight template version conflict")
ErrFreightTemplateInUse = errors.New("freight template is referenced by products")
ErrFreightTemplateNameExists = errors.New("freight template name already exists")
)
// FreightTemplateRecord is product.freight_templates.
@ -33,6 +34,7 @@ type FreightTemplateRecord struct {
// FreightTemplateListFilter pages store-scoped templates.
type FreightTemplateListFilter struct {
Keyword string
ExactMatch bool
Status *int32
Page, PageSize int32
}
@ -66,6 +68,8 @@ CREATE TABLE IF NOT EXISTS product.freight_templates (
);
CREATE INDEX IF NOT EXISTS idx_freight_templates_store
ON product.freight_templates (store_id) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_freight_templates_store_normalized_name_active
ON product.freight_templates (store_id, LOWER(BTRIM(name))) WHERE deleted_at IS NULL;
`)
return err
}
@ -88,7 +92,11 @@ INSERT INTO product.freight_templates (id, tenant_id, store_id, name, pricing_mo
VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8)
RETURNING id::text, name, pricing_mode, default_fee, rules_json, status, version, created_at, updated_at, deleted_at
`, id, rec.Scope.TenantID, rec.Scope.StoreID, rec.Name, rec.PricingMode, nullableInt64(rec.DefaultFee), rules, rec.Status)
return scanFreightTemplate(row, rec.Scope)
created, err := scanFreightTemplate(row, rec.Scope)
if freightTemplateNameConflictError(err) != nil {
return nil, ErrFreightTemplateNameExists
}
return created, err
}
// GetFreightTemplate loads one non-deleted template.
@ -127,17 +135,7 @@ func (r *ProductRepository) ListFreightTemplates(ctx context.Context, filter Fre
if pageSize > 100 {
pageSize = 100
}
args := []any{scope.StoreID}
where := []string{"store_id = $1", "deleted_at IS NULL"}
if kw := strings.TrimSpace(filter.Keyword); kw != "" {
args = append(args, "%"+kw+"%")
where = append(where, fmt.Sprintf("name ILIKE $%d", len(args)))
}
if filter.Status != nil {
args = append(args, *filter.Status)
where = append(where, fmt.Sprintf("status = $%d", len(args)))
}
whereSQL := strings.Join(where, " AND ")
whereSQL, args := freightTemplateListWhere(filter, scope)
var total int64
if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.freight_templates WHERE `+whereSQL, args...).Scan(&total); err != nil {
return nil, 0, fmt.Errorf("count freight templates: %w", err)
@ -208,6 +206,9 @@ SET name = $1, pricing_mode = $2, default_fee = $3, rules_json = $4::jsonb, stat
WHERE id = $6 AND store_id = $7 AND version = $8 AND deleted_at IS NULL
`, name, mode, nullableInt64(fee), rules, st, id, scope.StoreID, patch.ExpectedVersion)
if err != nil {
if freightTemplateNameConflictError(err) != nil {
return nil, ErrFreightTemplateNameExists
}
return nil, fmt.Errorf("update freight template: %w", err)
}
n, _ := res.RowsAffected()
@ -217,6 +218,32 @@ WHERE id = $6 AND store_id = $7 AND version = $8 AND deleted_at IS NULL
return r.GetFreightTemplate(ctx, templateID, scope)
}
func freightTemplateListWhere(filter FreightTemplateListFilter, scope StoreScope) (string, []any) {
args := []any{scope.StoreID}
where := []string{"store_id = $1", "deleted_at IS NULL"}
if kw := strings.TrimSpace(filter.Keyword); kw != "" {
args = append(args, kw)
if filter.ExactMatch {
where = append(where, fmt.Sprintf("LOWER(BTRIM(name)) = LOWER($%d)", len(args)))
} else {
args[len(args)-1] = "%" + kw + "%"
where = append(where, fmt.Sprintf("name ILIKE $%d", len(args)))
}
}
if filter.Status != nil {
args = append(args, *filter.Status)
where = append(where, fmt.Sprintf("status = $%d", len(args)))
}
return strings.Join(where, " AND "), args
}
func freightTemplateNameConflictError(err error) error {
if isPostgresConstraintError(err, "23505", "uq_freight_templates_store_normalized_name_active") {
return ErrFreightTemplateNameExists
}
return nil
}
// DeleteFreightTemplate soft-deletes when unused.
func (r *ProductRepository) DeleteFreightTemplate(ctx context.Context, templateID string, expectedVersion int32, scope StoreScope) (*FreightTemplateRecord, error) {
current, err := r.GetFreightTemplate(ctx, templateID, scope)

View File

@ -0,0 +1,48 @@
package repository
import (
"errors"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgconn"
)
func TestFreightTemplateListWhereUsesFuzzySearchByDefault(t *testing.T) {
where, args := freightTemplateListWhere(FreightTemplateListFilter{Keyword: " 华东 "}, StoreScope{StoreID: 20})
if !strings.Contains(where, "name ILIKE $2") {
t.Fatalf("where = %q, want fuzzy name predicate", where)
}
if strings.Contains(where, "LOWER(BTRIM(name))") {
t.Fatalf("where = %q, must not use exact predicate by default", where)
}
if len(args) != 2 || args[0] != int64(20) || args[1] != "%华东%" {
t.Fatalf("args = %#v, want [20 %%华东%%]", args)
}
}
func TestFreightTemplateListWhereUsesNormalizedExactSearch(t *testing.T) {
status := int32(1)
where, args := freightTemplateListWhere(FreightTemplateListFilter{
Keyword: " 华东包邮 ", ExactMatch: true, Status: &status,
}, StoreScope{StoreID: 20})
if !strings.Contains(where, "LOWER(BTRIM(name)) = LOWER($2)") {
t.Fatalf("where = %q, want exact normalized name predicate", where)
}
if strings.Contains(where, "ILIKE") {
t.Fatalf("where = %q, must not use fuzzy predicate", where)
}
if !strings.Contains(where, "status = $3") {
t.Fatalf("where = %q, want status predicate", where)
}
if len(args) != 3 || args[1] != "华东包邮" || args[2] != int32(1) {
t.Fatalf("args = %#v, want [20 华东包邮 1]", args)
}
}
func TestFreightTemplateNameConflictError(t *testing.T) {
err := &pgconn.PgError{Code: "23505", ConstraintName: "uq_freight_templates_store_normalized_name_active"}
if !errors.Is(freightTemplateNameConflictError(err), ErrFreightTemplateNameExists) {
t.Fatalf("error = %v, want %v", freightTemplateNameConflictError(err), ErrFreightTemplateNameExists)
}
}

View File

@ -79,7 +79,7 @@ func (s *ProductServer) ListFreightTemplates(ctx context.Context, req *productv1
statusValue = req.Status
}
values, total, err := s.repo.ListFreightTemplates(ctx, repository.FreightTemplateListFilter{
Keyword: strings.TrimSpace(req.GetKeyword()), Status: statusValue, Page: page, PageSize: size,
Keyword: strings.TrimSpace(req.GetKeyword()), ExactMatch: req.GetExactMatch(), Status: statusValue, Page: page, PageSize: size,
}, scope)
if err != nil {
return nil, freightTemplateGRPCError(err)
@ -274,6 +274,8 @@ func freightTemplateGRPCError(err error) error {
return status.Error(codes.Aborted, err.Error())
case errors.Is(err, repository.ErrFreightTemplateInUse):
return status.Error(codes.FailedPrecondition, err.Error())
case errors.Is(err, repository.ErrFreightTemplateNameExists):
return status.Error(codes.AlreadyExists, err.Error())
default:
return status.Errorf(codes.Internal, "%v", err)
}

View File

@ -0,0 +1,17 @@
package server
import (
"testing"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
)
func TestFreightTemplateNameConflictMapsToAlreadyExists(t *testing.T) {
err := freightTemplateGRPCError(repository.ErrFreightTemplateNameExists)
if status.Code(err) != codes.AlreadyExists {
t.Fatalf("code = %v, want %v", status.Code(err), codes.AlreadyExists)
}
}