From 10034dbcee56ca0f591c3f4a31ecca60a13b570e Mon Sep 17 00:00:00 2001 From: BXY <103352887+BXY0414@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:58:01 +0800 Subject: [PATCH] feat: add exact match search and handle freight template name conflicts --- .../repository/freight_template_repository.go | 51 ++++++++++++++----- .../freight_template_repository_test.go | 48 +++++++++++++++++ internal/server/freight_template_server.go | 4 +- .../server/freight_template_server_test.go | 17 +++++++ 4 files changed, 107 insertions(+), 13 deletions(-) create mode 100644 internal/repository/freight_template_repository_test.go create mode 100644 internal/server/freight_template_server_test.go diff --git a/internal/repository/freight_template_repository.go b/internal/repository/freight_template_repository.go index b106cf7..83d1635 100644 --- a/internal/repository/freight_template_repository.go +++ b/internal/repository/freight_template_repository.go @@ -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) diff --git a/internal/repository/freight_template_repository_test.go b/internal/repository/freight_template_repository_test.go new file mode 100644 index 0000000..3a55072 --- /dev/null +++ b/internal/repository/freight_template_repository_test.go @@ -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) + } +} diff --git a/internal/server/freight_template_server.go b/internal/server/freight_template_server.go index 5419476..815f6ee 100644 --- a/internal/server/freight_template_server.go +++ b/internal/server/freight_template_server.go @@ -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) } diff --git a/internal/server/freight_template_server_test.go b/internal/server/freight_template_server_test.go new file mode 100644 index 0000000..294cf1a --- /dev/null +++ b/internal/server/freight_template_server_test.go @@ -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) + } +}