diff --git a/cmd/main.go b/cmd/main.go index b97fb8a..9a6913a 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -93,9 +93,11 @@ func main() { grpc.UnaryInterceptor(observer.UnaryServerInterceptor()), ) productv1.RegisterProductServiceServer(grpcServer, productServer) + productv1.RegisterProductCategoryServiceServer(grpcServer, productServer) healthServer := health.NewServer() healthServer.SetServingStatus("", healthpb.HealthCheckResponse_SERVING) healthServer.SetServingStatus(productv1.ProductService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_SERVING) + healthServer.SetServingStatus(productv1.ProductCategoryService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_SERVING) healthServer.SetServingStatus(observability.ServiceName, healthpb.HealthCheckResponse_SERVING) healthpb.RegisterHealthServer(grpcServer, healthServer) reflection.Register(grpcServer) @@ -117,6 +119,7 @@ func main() { healthServer.SetServingStatus("", healthpb.HealthCheckResponse_NOT_SERVING) healthServer.SetServingStatus(productv1.ProductService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_NOT_SERVING) + healthServer.SetServingStatus(productv1.ProductCategoryService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_NOT_SERVING) healthServer.SetServingStatus(observability.ServiceName, healthpb.HealthCheckResponse_NOT_SERVING) grpcServer.GracefulStop() shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) diff --git a/internal/repository/product_category_repository.go b/internal/repository/product_category_repository.go new file mode 100644 index 0000000..be1a3a0 --- /dev/null +++ b/internal/repository/product_category_repository.go @@ -0,0 +1,490 @@ +package repository + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + "time" +) + +var ( + ErrProductCategoryNotFound = errors.New("product category not found") + ErrProductCategoryVersionConflict = errors.New("product category version conflict") + ErrProductCategoryHasChildren = errors.New("product category has children") + ErrProductCategoryInUse = errors.New("product category is bound to products") + ErrDuplicateProductCategory = errors.New("product category code or sibling name already exists") +) + +// ProductCategoryRecord is the standard product taxonomy node. It is distinct +// from CatalogCategoryRecord (the storefront classification tree). +type ProductCategoryRecord struct { + ID, CategoryCode, Name, ParentID, Remark string + Level, SortNum, Status, Version int32 + StatusSet bool + IsLeaf bool + ProductCount int64 + CreatedAt, UpdatedAt time.Time + DeletedAt *time.Time + Children []*ProductCategoryRecord +} + +type ProductCategoryPatch struct { + CategoryCode, Name, ParentID, Remark *string + SortNum, Status *int32 + ExpectedVersion int32 +} + +type ProductCategoryListFilter struct { + Keyword string + Status *int32 + Page, PageSize int32 +} + +func (r *ProductRepository) CreateProductCategory(ctx context.Context, root *ProductCategoryRecord, scope StoreScope) (*ProductCategoryRecord, error) { + if root == nil || !scope.Valid() { + return nil, errors.New("product category and store scope are required") + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin create product category: %w", err) + } + defer tx.Rollback() + created, err := createProductCategoryNode(ctx, tx, root, root.ParentID, scope) + if err != nil { + return nil, err + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit create product category: %w", err) + } + return created, nil +} + +func createProductCategoryNode(ctx context.Context, tx *sql.Tx, input *ProductCategoryRecord, parentID string, scope StoreScope) (*ProductCategoryRecord, error) { + if input == nil { + return nil, errors.New("product category is required") + } + level := int32(1) + parent := sql.NullInt64{} + if strings.TrimSpace(parentID) != "" { + parsed, err := parseID(parentID, "parent_id") + if err != nil { + return nil, err + } + var parentLevel int32 + var parentStatus int32 + err = tx.QueryRowContext(ctx, `SELECT level,status FROM product.product_category WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL FOR UPDATE`, parsed, scope.TenantID, scope.StoreID).Scan(&parentLevel, &parentStatus) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrProductCategoryNotFound + } + if err != nil { + return nil, fmt.Errorf("load product category parent: %w", err) + } + if parentStatus != 1 { + return nil, errors.New("parent product category must be enabled") + } + level = parentLevel + 1 + parent = sql.NullInt64{Int64: parsed, Valid: true} + } + if level > 4 { + return nil, errors.New("product category depth cannot exceed 4") + } + id, err := parseID(input.ID, "product_category_id") + if err != nil { + return nil, err + } + statusValue := input.Status + if !input.StatusSet { + statusValue = 1 + } + row := tx.QueryRowContext(ctx, `INSERT INTO product.product_category + (id,tenant_id,store_id,category_code,name,parent_id,level,is_leaf,sort_num,status,remark) + VALUES ($1,$2,$3,$4,$5,$6,$7,true,$8,$9,$10) + RETURNING id,category_code,name,parent_id,level,is_leaf,sort_num,status,remark,version,created_at,updated_at,deleted_at`, + id, scope.TenantID, scope.StoreID, input.CategoryCode, input.Name, parent, level, input.SortNum, statusValue, input.Remark) + created, err := scanProductCategory(row) + if err != nil { + return nil, mapProductCategoryWriteError(err) + } + for _, child := range input.Children { + createdChild, err := createProductCategoryNode(ctx, tx, child, created.ID, scope) + if err != nil { + return nil, err + } + created.Children = append(created.Children, createdChild) + } + if len(created.Children) > 0 { + if _, err := tx.ExecContext(ctx, `UPDATE product.product_category SET is_leaf=false,updated_at=NOW(),version=version+1 WHERE id=$1`, id); err != nil { + return nil, err + } + created.IsLeaf = false + created.Version++ + } + return created, nil +} + +func (r *ProductRepository) ListProductCategories(ctx context.Context, filter ProductCategoryListFilter, scope StoreScope) ([]*ProductCategoryRecord, int64, error) { + if !scope.Valid() { + return nil, 0, errors.New("store scope is required") + } + where := `tenant_id=$1 AND store_id=$2 AND deleted_at IS NULL AND parent_id IS NULL` + args := []any{scope.TenantID, scope.StoreID} + if strings.TrimSpace(filter.Keyword) != "" { + args = append(args, "%"+strings.TrimSpace(filter.Keyword)+"%") + where += fmt.Sprintf(" AND (category_code ILIKE $%d OR name ILIKE $%d)", len(args), len(args)) + } + if filter.Status != nil { + args = append(args, *filter.Status) + where += fmt.Sprintf(" AND status=$%d", len(args)) + } + var total int64 + if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.product_category WHERE `+where, args...).Scan(&total); err != nil { + return nil, 0, err + } + args = append(args, filter.PageSize, (filter.Page-1)*filter.PageSize) + rows, err := r.db.QueryContext(ctx, fmt.Sprintf(`SELECT id FROM product.product_category WHERE %s ORDER BY sort_num,id LIMIT $%d OFFSET $%d`, where, len(args)-1, len(args)), args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + rootIDs := []string{} + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return nil, 0, err + } + rootIDs = append(rootIDs, formatID(id)) + } + if err := rows.Err(); err != nil { + return nil, 0, err + } + roots := make([]*ProductCategoryRecord, 0, len(rootIDs)) + for _, id := range rootIDs { + root, err := r.loadProductCategoryTree(ctx, id, scope) + if err != nil { + return nil, 0, err + } + roots = append(roots, root) + } + return roots, total, nil +} + +func (r *ProductRepository) GetProductCategory(ctx context.Context, id string, scope StoreScope) (*ProductCategoryRecord, error) { + return r.loadProductCategoryTree(ctx, id, scope) +} + +func (r *ProductRepository) loadProductCategoryTree(ctx context.Context, id string, scope StoreScope) (*ProductCategoryRecord, error) { + parsed, err := parseID(id, "product_category_id") + if err != nil { + return nil, err + } + row := r.db.QueryRowContext(ctx, productCategorySelect+` WHERE c.id=$1 AND c.tenant_id=$2 AND c.store_id=$3 AND c.deleted_at IS NULL`, parsed, scope.TenantID, scope.StoreID) + root, err := scanProductCategory(row) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrProductCategoryNotFound + } + if err != nil { + return nil, err + } + rows, err := r.db.QueryContext(ctx, `WITH RECURSIVE descendants AS ( + SELECT id FROM product.product_category WHERE parent_id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL + UNION ALL SELECT c.id FROM product.product_category c JOIN descendants d ON c.parent_id=d.id WHERE c.tenant_id=$2 AND c.store_id=$3 AND c.deleted_at IS NULL + ) SELECT c.id,c.category_code,c.name,c.parent_id,c.level,c.is_leaf,c.sort_num,c.status,c.remark,c.version,c.created_at,c.updated_at,c.deleted_at, + (SELECT COUNT(*) FROM product.product_category_bindings b WHERE b.product_category_id=c.id AND b.deleted_at IS NULL) + FROM product.product_category c JOIN descendants d ON d.id=c.id ORDER BY c.level,c.sort_num,c.id`, parsed, scope.TenantID, scope.StoreID) + if err != nil { + return nil, err + } + defer rows.Close() + byID := map[string]*ProductCategoryRecord{root.ID: root} + for rows.Next() { + child, err := scanProductCategory(rows) + if err != nil { + return nil, err + } + byID[child.ID] = child + } + if err := rows.Err(); err != nil { + return nil, err + } + for _, node := range byID { + if node.ParentID != "" { + if parent := byID[node.ParentID]; parent != nil { + parent.Children = append(parent.Children, node) + } + } + } + sortProductCategoryTree(root) + return root, nil +} + +func (r *ProductRepository) UpdateProductCategory(ctx context.Context, id string, patch ProductCategoryPatch, scope StoreScope) (*ProductCategoryRecord, error) { + parsed, err := parseID(id, "product_category_id") + if err != nil { + return nil, err + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, err + } + defer tx.Rollback() + var oldLevel int32 + err = tx.QueryRowContext(ctx, `SELECT level FROM product.product_category WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL FOR UPDATE`, parsed, scope.TenantID, scope.StoreID).Scan(&oldLevel) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrProductCategoryNotFound + } + if err != nil { + return nil, err + } + parent := sql.NullInt64{} + newLevel := oldLevel + if patch.ParentID != nil { + if strings.TrimSpace(*patch.ParentID) != "" { + parentID, err := parseID(*patch.ParentID, "parent_id") + if err != nil { + return nil, err + } + if parentID == parsed { + return nil, errors.New("parent_id cannot be self") + } + var parentLevel, parentStatus int32 + err = tx.QueryRowContext(ctx, `SELECT level,status FROM product.product_category WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL FOR UPDATE`, parentID, scope.TenantID, scope.StoreID).Scan(&parentLevel, &parentStatus) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrProductCategoryNotFound + } + if err != nil { + return nil, err + } + if parentStatus != 1 { + return nil, errors.New("parent product category must be enabled") + } + var cycle bool + if err := tx.QueryRowContext(ctx, `WITH RECURSIVE d AS (SELECT id FROM product.product_category WHERE parent_id=$1 AND deleted_at IS NULL UNION ALL SELECT c.id FROM product.product_category c JOIN d ON c.parent_id=d.id WHERE c.deleted_at IS NULL) SELECT EXISTS(SELECT 1 FROM d WHERE id=$2)`, parsed, parentID).Scan(&cycle); err != nil { + return nil, err + } + if cycle { + return nil, errors.New("parent_id cannot be a descendant") + } + parent = sql.NullInt64{Int64: parentID, Valid: true} + newLevel = parentLevel + 1 + } + if newLevel > 4 { + return nil, errors.New("product category depth cannot exceed 4") + } + var maxDescendantLevel int32 + if err := tx.QueryRowContext(ctx, `WITH RECURSIVE d AS (SELECT id,level FROM product.product_category WHERE id=$1 UNION ALL SELECT c.id,c.level FROM product.product_category c JOIN d ON c.parent_id=d.id WHERE c.deleted_at IS NULL) SELECT COALESCE(MAX(level),$2) FROM d`, parsed, oldLevel).Scan(&maxDescendantLevel); err != nil { + return nil, err + } + if newLevel+(maxDescendantLevel-oldLevel) > 4 { + return nil, errors.New("moving this category exceeds maximum depth") + } + } + result, err := tx.ExecContext(ctx, `UPDATE product.product_category SET + category_code=COALESCE($1,category_code),name=COALESCE($2,name),parent_id=CASE WHEN $3 THEN $4 ELSE parent_id END, + sort_num=COALESCE($5,sort_num),status=COALESCE($6,status),remark=COALESCE($7,remark),level=$8,version=version+1,updated_at=NOW() + WHERE id=$9 AND tenant_id=$10 AND store_id=$11 AND version=$12 AND deleted_at IS NULL`, patch.CategoryCode, patch.Name, patch.ParentID != nil, parent, patch.SortNum, patch.Status, patch.Remark, newLevel, parsed, scope.TenantID, scope.StoreID, patch.ExpectedVersion) + if err != nil { + return nil, mapProductCategoryWriteError(err) + } + changed, _ := result.RowsAffected() + if changed == 0 { + return nil, ErrProductCategoryVersionConflict + } + if newLevel != oldLevel { + delta := newLevel - oldLevel + if _, err := tx.ExecContext(ctx, `WITH RECURSIVE d AS (SELECT id FROM product.product_category WHERE parent_id=$1 AND deleted_at IS NULL UNION ALL SELECT c.id FROM product.product_category c JOIN d ON c.parent_id=d.id WHERE c.deleted_at IS NULL) UPDATE product.product_category SET level=level+$2,version=version+1,updated_at=NOW() WHERE id IN (SELECT id FROM d)`, parsed, delta); err != nil { + return nil, err + } + } + if err := tx.Commit(); err != nil { + return nil, err + } + return r.GetProductCategory(ctx, id, scope) +} + +func (r *ProductRepository) DeleteProductCategory(ctx context.Context, id string, expectedVersion int32, scope StoreScope) (*time.Time, error) { + parsed, err := parseID(id, "product_category_id") + if err != nil { + return nil, err + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, err + } + defer tx.Rollback() + var children, bindings int64 + if err := tx.QueryRowContext(ctx, `SELECT (SELECT COUNT(*) FROM product.product_category WHERE parent_id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL),(SELECT COUNT(*) FROM product.product_category_bindings WHERE product_category_id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, parsed, scope.TenantID, scope.StoreID).Scan(&children, &bindings); err != nil { + return nil, err + } + if children > 0 { + return nil, ErrProductCategoryHasChildren + } + if bindings > 0 { + return nil, ErrProductCategoryInUse + } + var deleted time.Time + err = tx.QueryRowContext(ctx, `UPDATE product.product_category SET deleted_at=NOW(),updated_at=NOW(),version=version+1 WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND version=$4 AND deleted_at IS NULL RETURNING deleted_at`, parsed, scope.TenantID, scope.StoreID, expectedVersion).Scan(&deleted) + if errors.Is(err, sql.ErrNoRows) { + var exists bool + _ = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, parsed, scope.TenantID, scope.StoreID).Scan(&exists) + if exists { + return nil, ErrProductCategoryVersionConflict + } + return nil, ErrProductCategoryNotFound + } + if err != nil { + return nil, err + } + if err := tx.Commit(); err != nil { + return nil, err + } + return &deleted, nil +} + +func (r *ProductRepository) BindProductsToProductCategory(ctx context.Context, categoryID string, bindingIDs, productIDs []string, scope StoreScope) (int32, int32, error) { + if len(productIDs) == 0 { + return 0, 0, errors.New("product_ids is required") + } + parsedCategory, err := parseID(categoryID, "product_category_id") + if err != nil { + return 0, 0, err + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return 0, 0, err + } + defer tx.Rollback() + var leaf, statusValue int32 + err = tx.QueryRowContext(ctx, `SELECT CASE WHEN is_leaf THEN 1 ELSE 0 END,status FROM product.product_category WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL FOR UPDATE`, parsedCategory, scope.TenantID, scope.StoreID).Scan(&leaf, &statusValue) + if errors.Is(err, sql.ErrNoRows) { + return 0, 0, ErrProductCategoryNotFound + } + if err != nil { + return 0, 0, err + } + if leaf != 1 || statusValue != 1 { + return 0, 0, errors.New("product category must be an enabled leaf") + } + var bound, already int32 + for i, productID := range productIDs { + product, err := parseID(productID, "product_id") + if err != nil { + return 0, 0, err + } + var exists bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.products WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, product, scope.TenantID, scope.StoreID).Scan(&exists); err != nil { + return 0, 0, err + } + if !exists { + return 0, 0, ErrProductNotFound + } + var active bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category_bindings WHERE product_id=$1 AND product_category_id=$2 AND deleted_at IS NULL)`, product, parsedCategory).Scan(&active); err != nil { + return 0, 0, err + } + if active { + already++ + continue + } + if _, err := tx.ExecContext(ctx, `UPDATE product.product_category_bindings SET deleted_at=NULL,updated_at=NOW() WHERE product_id=$1 AND product_category_id=$2 AND deleted_at IS NOT NULL`, product, parsedCategory); err != nil { + return 0, 0, err + } + var restored bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category_bindings WHERE product_id=$1 AND product_category_id=$2 AND deleted_at IS NULL)`, product, parsedCategory).Scan(&restored); err != nil { + return 0, 0, err + } + if !restored { + binding, err := parseID(bindingIDs[i], "product_category_binding_id") + if err != nil { + return 0, 0, err + } + if _, err := tx.ExecContext(ctx, `INSERT INTO product.product_category_bindings (id,tenant_id,store_id,product_id,product_category_id) VALUES ($1,$2,$3,$4,$5)`, binding, scope.TenantID, scope.StoreID, product, parsedCategory); err != nil { + return 0, 0, err + } + } + bound++ + } + if err := tx.Commit(); err != nil { + return 0, 0, err + } + return bound, already, nil +} + +func (r *ProductRepository) UnbindProductsFromProductCategory(ctx context.Context, categoryID string, productIDs []string, scope StoreScope) (int32, error) { + if err := requireWriteScope(scope); err != nil { + return 0, err + } + parsed, err := parseID(categoryID, "product_category_id") + if err != nil { + return 0, err + } + var exists bool + if err := r.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, parsed, scope.TenantID, scope.StoreID).Scan(&exists); err != nil { + return 0, err + } + if !exists { + return 0, ErrProductCategoryNotFound + } + var count int32 + for _, productID := range productIDs { + product, err := parseID(productID, "product_id") + if err != nil { + return 0, err + } + result, err := r.db.ExecContext(ctx, `UPDATE product.product_category_bindings SET deleted_at=NOW(),updated_at=NOW() WHERE product_id=$1 AND product_category_id=$2 AND tenant_id=$3 AND store_id=$4 AND deleted_at IS NULL`, product, parsed, scope.TenantID, scope.StoreID) + if err != nil { + return 0, err + } + affected, _ := result.RowsAffected() + count += int32(affected) + } + return count, nil +} + +const productCategorySelect = `SELECT c.id,c.category_code,c.name,c.parent_id,c.level,c.is_leaf,c.sort_num,c.status,c.remark,c.version,c.created_at,c.updated_at,c.deleted_at,(SELECT COUNT(*) FROM product.product_category_bindings b WHERE b.product_category_id=c.id AND b.deleted_at IS NULL) FROM product.product_category c` + +type productCategoryScanner interface{ Scan(...any) error } + +func scanProductCategory(row productCategoryScanner) (*ProductCategoryRecord, error) { + var id sql.NullInt64 + var parent sql.NullInt64 + var deleted sql.NullTime + value := &ProductCategoryRecord{} + if err := row.Scan(&id, &value.CategoryCode, &value.Name, &parent, &value.Level, &value.IsLeaf, &value.SortNum, &value.Status, &value.Remark, &value.Version, &value.CreatedAt, &value.UpdatedAt, &deleted, &value.ProductCount); err != nil { + return nil, err + } + value.ID = formatID(id.Int64) + if parent.Valid { + value.ParentID = formatID(parent.Int64) + } + if deleted.Valid { + value.DeletedAt = &deleted.Time + } + return value, nil +} +func sortProductCategoryTree(node *ProductCategoryRecord) { + if node == nil { + return + } + for _, child := range node.Children { + sortProductCategoryTree(child) + } + for i := 0; i < len(node.Children); i++ { + for j := i + 1; j < len(node.Children); j++ { + if node.Children[j].SortNum < node.Children[i].SortNum || (node.Children[j].SortNum == node.Children[i].SortNum && node.Children[j].ID < node.Children[i].ID) { + node.Children[i], node.Children[j] = node.Children[j], node.Children[i] + } + } + } +} +func mapProductCategoryWriteError(err error) error { + if err == nil { + return nil + } + var text = err.Error() + if strings.Contains(text, "uq_product_category_store_code_active") || strings.Contains(text, "uq_product_category_store_parent_name_active") { + return ErrDuplicateProductCategory + } + return err +} diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index d162176..b0f6142 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -280,7 +280,7 @@ type ProductListFilter struct { PriceMax *int64 } -// CategoryRecord is the persistence model for product.product_category. +// CategoryRecord is the persistence model for product.catalog_category. type CategoryRecord struct { ID string NodeType int32 @@ -328,16 +328,28 @@ func NewProductRepository(db *sql.DB) *ProductRepository { // EnsureSchema adds the SKU table when missing; products is provisioned by infra init-scripts. func (r *ProductRepository) EnsureSchema(ctx context.Context) error { const ddl = ` +DO $$ +BEGIN + IF to_regclass('product.catalog_category') IS NULL + AND to_regclass('product.product_category') IS NOT NULL THEN + ALTER TABLE product.product_category RENAME TO catalog_category; + END IF; + IF to_regclass('product.product_catalog_bindings') IS NULL + AND to_regclass('product.product_category_bindings') IS NOT NULL THEN + ALTER TABLE product.product_category_bindings RENAME TO product_catalog_bindings; + END IF; +END $$; + ALTER TABLE product.products ALTER COLUMN id DROP DEFAULT; -ALTER TABLE product.product_category_bindings +ALTER TABLE product.product_catalog_bindings ALTER COLUMN id DROP DEFAULT; -ALTER TABLE product.product_category +ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; -ALTER TABLE product.product_category +ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS version INTEGER NOT NULL DEFAULT 0; DO $$ @@ -347,7 +359,7 @@ BEGIN WHERE conname = 'chk_product_category_version' AND connamespace = 'product'::regnamespace ) THEN - ALTER TABLE product.product_category + ALTER TABLE product.catalog_category ADD CONSTRAINT chk_product_category_version CHECK (version >= 0); END IF; END $$; @@ -358,11 +370,11 @@ BEGIN SELECT 1 FROM information_schema.columns WHERE table_schema = 'product' - AND table_name = 'product_category' + AND table_name = 'catalog_category' AND column_name = 'image_json' ) THEN EXECUTE $migration$ - UPDATE product.product_category + UPDATE product.catalog_category SET image_ids = CASE WHEN jsonb_typeof(image_json) = 'array' THEN COALESCE( (SELECT array_agg(image_id) @@ -376,9 +388,50 @@ BEGIN END IF; END $$; -ALTER TABLE product.product_category +ALTER TABLE product.catalog_category DROP COLUMN IF EXISTS image_json; +CREATE TABLE IF NOT EXISTS product.product_category ( + id BIGINT PRIMARY KEY, + tenant_id BIGINT NOT NULL, + store_id BIGINT NOT NULL, + category_code VARCHAR(64) NOT NULL, + name VARCHAR(100) NOT NULL, + parent_id BIGINT REFERENCES product.product_category(id) ON DELETE RESTRICT, + level SMALLINT NOT NULL CHECK (level BETWEEN 1 AND 4), + is_leaf BOOLEAN NOT NULL DEFAULT TRUE, + sort_num INTEGER NOT NULL DEFAULT 0, + status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), + remark VARCHAR(500) NOT NULL DEFAULT '', + version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_store_code_active + ON product.product_category (store_id, category_code) WHERE deleted_at IS NULL; +CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_store_parent_name_active + ON product.product_category (store_id, COALESCE(parent_id, 0), lower(btrim(name))) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_product_category_store_parent_sort + ON product.product_category (store_id, parent_id, sort_num, id) WHERE deleted_at IS NULL; + +CREATE TABLE IF NOT EXISTS product.product_category_bindings ( + id BIGINT PRIMARY KEY, + tenant_id BIGINT NOT NULL, + store_id BIGINT NOT NULL, + product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, + product_category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE RESTRICT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_bindings_active + ON product.product_category_bindings (product_id, product_category_id) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category + ON product.product_category_bindings (store_id, product_category_id) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_product_category_bindings_product + ON product.product_category_bindings (store_id, product_id) WHERE deleted_at IS NULL; + CREATE TABLE IF NOT EXISTS product.product_items ( id BIGINT PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, @@ -435,25 +488,25 @@ CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(pric CREATE INDEX IF NOT EXISTS idx_products_active_created_id ON product.products(created_at DESC, id DESC) WHERE deleted_at IS NULL; ALTER TABLE product.products ADD COLUMN IF NOT EXISTS tenant_id BIGINT; ALTER TABLE product.products ADD COLUMN IF NOT EXISTS store_id BIGINT; -ALTER TABLE product.product_category ADD COLUMN IF NOT EXISTS tenant_id BIGINT; -ALTER TABLE product.product_category ADD COLUMN IF NOT EXISTS store_id BIGINT; -ALTER TABLE product.product_category ADD COLUMN IF NOT EXISTS campaign_id BIGINT; +ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS tenant_id BIGINT; +ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS store_id BIGINT; +ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS campaign_id BIGINT; ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS tenant_id BIGINT; ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS store_id BIGINT; DROP INDEX IF EXISTS product.uq_products_spu_no; CREATE UNIQUE INDEX IF NOT EXISTS uq_products_store_spu_no ON product.products (store_id, spu_no) WHERE deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_products_store_id ON product.products (store_id) WHERE deleted_at IS NULL; -CREATE INDEX IF NOT EXISTS idx_product_category_store_id ON product.product_category (store_id); +CREATE INDEX IF NOT EXISTS idx_catalog_category_store_id ON product.catalog_category (store_id); CREATE INDEX IF NOT EXISTS idx_product_category_campaign_id - ON product.product_category (campaign_id) WHERE campaign_id IS NOT NULL; + ON product.catalog_category (campaign_id) WHERE campaign_id IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_group_normalized_name - ON product.product_category ( + ON product.catalog_category ( store_id, lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g'))) ) WHERE node_type = 2; CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_sibling_normalized_name - ON product.product_category ( + ON product.catalog_category ( store_id, COALESCE(parent_id, 0), lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g'))) @@ -734,7 +787,7 @@ func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID strin rows, err := tx.QueryContext(ctx, ` SELECT id, node_type, name, parent_id, level, COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, campaign_id, version -FROM product.product_category +FROM product.catalog_category WHERE parent_id = $1 AND store_id = $2 FOR UPDATE `, targetID, scope.StoreID) @@ -782,23 +835,23 @@ FOR UPDATE } if err := tx.QueryRowContext(ctx, fmt.Sprintf(` SELECT COUNT(DISTINCT product_id), COUNT(*) -FROM product.product_category_bindings +FROM product.product_catalog_bindings WHERE category_id IN (%s) `, whereIDs), args...).Scan(&result.UnboundProductCount, &result.UnboundBindingCount); err != nil { return nil, fmt.Errorf("count category bindings for delete: %w", err) } if _, err := tx.ExecContext(ctx, fmt.Sprintf(` -DELETE FROM product.product_category_bindings +DELETE FROM product.product_catalog_bindings WHERE category_id IN (%s) `, whereIDs), args...); err != nil { return nil, fmt.Errorf("delete category bindings: %w", err) } if target.Level == 1 { - if _, err := tx.ExecContext(ctx, `DELETE FROM product.product_category WHERE parent_id = $1 AND store_id = $2`, targetID, scope.StoreID); err != nil { + if _, err := tx.ExecContext(ctx, `DELETE FROM product.catalog_category WHERE parent_id = $1 AND store_id = $2`, targetID, scope.StoreID); err != nil { return nil, fmt.Errorf("delete child categories: %w", err) } } - if _, err := tx.ExecContext(ctx, `DELETE FROM product.product_category WHERE id = $1 AND store_id = $2`, targetID, scope.StoreID); err != nil { + if _, err := tx.ExecContext(ctx, `DELETE FROM product.catalog_category WHERE id = $1 AND store_id = $2`, targetID, scope.StoreID); err != nil { return nil, fmt.Errorf("delete category: %w", err) } if err := tx.Commit(); err != nil { @@ -818,7 +871,7 @@ func loadCategoryForUpdate(ctx context.Context, tx *sql.Tx, categoryID string, s row := tx.QueryRowContext(ctx, ` SELECT id, node_type, name, parent_id, level, COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, campaign_id, version -FROM product.product_category +FROM product.catalog_category WHERE id = $1 AND store_id = $2 FOR UPDATE`, id, scope.StoreID) category, err := scanCategory(row) @@ -844,7 +897,7 @@ func updateCategoryFields(ctx context.Context, tx *sql.Tx, update CategoryFieldU return nil, err } row := tx.QueryRowContext(ctx, ` -UPDATE product.product_category +UPDATE product.catalog_category SET name = CASE WHEN $3 THEN $4 ELSE name END, image_ids = CASE WHEN $5 THEN $6 ELSE image_ids END, sort_num = CASE WHEN $7 THEN $8 ELSE sort_num END, @@ -954,7 +1007,7 @@ func (r *ProductRepository) addProductsToCategoryNode(ctx context.Context, nodeI err = tx.QueryRowContext(ctx, ` SELECT id -FROM product.product_category +FROM product.catalog_category WHERE id = $1 AND node_type = $2 AND store_id = $3 @@ -1013,7 +1066,7 @@ WHERE deleted_at IS NULL args = append(args, parsedBindingIDs[i], productID, parsedNodeID) } _, err = tx.ExecContext(ctx, fmt.Sprintf(` -INSERT INTO product.product_category_bindings (id, product_id, category_id) +INSERT INTO product.product_catalog_bindings (id, product_id, category_id) VALUES %s ON CONFLICT (product_id, category_id) DO NOTHING `, strings.Join(valuePlaceholders, ", ")), args...) @@ -1057,7 +1110,7 @@ func (r *ProductRepository) RemoveProductsFromGroup(ctx context.Context, groupID err = tx.QueryRowContext(ctx, ` SELECT id -FROM product.product_category +FROM product.catalog_category WHERE id = $1 AND node_type = 2 AND store_id = $2 `, parsedGroupID, scope.StoreID).Scan(&parsedGroupID) if errors.Is(err, sql.ErrNoRows) { @@ -1075,7 +1128,7 @@ WHERE id = $1 AND node_type = 2 AND store_id = $2 args = append(args, productID) } _, err = tx.ExecContext(ctx, fmt.Sprintf(` -DELETE FROM product.product_category_bindings +DELETE FROM product.product_catalog_bindings WHERE category_id = $1 AND product_id IN (%s) `, strings.Join(placeholders, ", ")), args...) @@ -1278,7 +1331,7 @@ func replaceProductLeafCategoryBindings(ctx context.Context, tx *sql.Tx, product return err } if _, duplicate := seenCategoryIDs[parsedLeafCategoryIDs[index]]; duplicate { - return errors.New("leaf_category_ids must not contain duplicates") + return errors.New("leaf_catalog_category_ids must not contain duplicates") } seenCategoryIDs[parsedLeafCategoryIDs[index]] = struct{}{} if _, err := parseID(bindingIDs[index], "category binding id"); err != nil { @@ -1295,7 +1348,7 @@ func replaceProductLeafCategoryBindings(ctx context.Context, tx *sql.Tx, product } rows, err := tx.QueryContext(ctx, fmt.Sprintf(` SELECT id -FROM product.product_category +FROM product.catalog_category WHERE node_type = 1 AND level = 2 AND store_id = $%d @@ -1327,8 +1380,8 @@ FOR KEY SHARE } if _, err := tx.ExecContext(ctx, ` -DELETE FROM product.product_category_bindings AS b -USING product.product_category AS c +DELETE FROM product.product_catalog_bindings AS b +USING product.catalog_category AS c WHERE b.product_id = $1 AND b.category_id = c.id AND c.node_type = 1 @@ -1383,7 +1436,7 @@ func replaceProductGroupBindings(ctx context.Context, tx *sql.Tx, productID stri } rows, err := tx.QueryContext(ctx, fmt.Sprintf(` SELECT id -FROM product.product_category +FROM product.catalog_category WHERE node_type = 2 AND store_id = $%d AND id IN (%s) @@ -1414,8 +1467,8 @@ FOR KEY SHARE } if _, err := tx.ExecContext(ctx, ` -DELETE FROM product.product_category_bindings AS b -USING product.product_category AS c +DELETE FROM product.product_catalog_bindings AS b +USING product.catalog_category AS c WHERE b.product_id = $1 AND b.category_id = c.id AND c.node_type = 2 @@ -1604,7 +1657,7 @@ WHERE product_id = $1 AND store_id = $3 return nil, fmt.Errorf("update sku store: %w", err) } if _, err := tx.ExecContext(ctx, ` -DELETE FROM product.product_category_bindings +DELETE FROM product.product_catalog_bindings WHERE product_id = $1 `, id); err != nil { return nil, fmt.Errorf("detach product categories: %w", err) @@ -2410,8 +2463,8 @@ func (r *ProductRepository) listProductLeafCategoryIDs(ctx context.Context, prod } rows, err := r.db.QueryContext(ctx, ` SELECT c.id -FROM product.product_category_bindings AS b -JOIN product.product_category AS c ON c.id = b.category_id +FROM product.product_catalog_bindings AS b +JOIN product.catalog_category AS c ON c.id = b.category_id WHERE b.product_id = $1 AND c.node_type = 1 AND c.level = 2 @@ -2446,8 +2499,8 @@ func (r *ProductRepository) listProductGroupIDs(ctx context.Context, productID s } rows, err := r.db.QueryContext(ctx, ` SELECT c.id -FROM product.product_category_bindings AS b -JOIN product.product_category AS c ON c.id = b.category_id +FROM product.product_catalog_bindings AS b +JOIN product.catalog_category AS c ON c.id = b.category_id WHERE b.product_id = $1 AND c.node_type = 2 AND c.store_id = $2 @@ -2546,7 +2599,7 @@ func (r *ProductRepository) ValidateProductGroup(ctx context.Context, groupID st var found int64 err = r.db.QueryRowContext(ctx, ` SELECT id -FROM product.product_category +FROM product.catalog_category WHERE id = $1 AND node_type = 2 AND store_id = $2 `, parsedGroupID, scope.StoreID).Scan(&found) if errors.Is(err, sql.ErrNoRows) { @@ -2654,8 +2707,8 @@ func productListWhere(filter ProductListFilter, scope StoreScope) (string, []any if filter.GroupID != "" { add(`EXISTS ( SELECT 1 - FROM product.product_category_bindings pcb - JOIN product.product_category pc ON pc.id = pcb.category_id + FROM product.product_catalog_bindings pcb + JOIN product.catalog_category pc ON pc.id = pcb.category_id WHERE pcb.product_id = p.id AND pcb.category_id = $%d AND pc.node_type = 2 @@ -2821,8 +2874,8 @@ func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID if err := r.db.QueryRowContext(ctx, ` SELECT COUNT(*) FROM product.products p -JOIN product.product_category_bindings b ON b.product_id = p.id -JOIN product.product_category c ON c.id = b.category_id +JOIN product.product_catalog_bindings b ON b.product_id = p.id +JOIN product.catalog_category c ON c.id = b.category_id WHERE b.category_id = $1 AND p.deleted_at IS NULL AND p.store_id = $5 @@ -2839,8 +2892,8 @@ WHERE b.category_id = $1 idRows, err := r.db.QueryContext(ctx, ` SELECT p.id FROM product.products p -JOIN product.product_category_bindings b ON b.product_id = p.id -JOIN product.product_category c ON c.id = b.category_id +JOIN product.product_catalog_bindings b ON b.product_id = p.id +JOIN product.catalog_category c ON c.id = b.category_id WHERE b.category_id = $1 AND p.deleted_at IS NULL AND p.store_id = $5 @@ -2879,8 +2932,8 @@ SELECT p.updated_at, COALESCE(sku_summary.stock_quantity, 0), COALESCE(sku_summary.locked_quantity, 0) FROM product.products p -JOIN product.product_category_bindings b ON b.product_id = p.id -JOIN product.product_category c ON c.id = b.category_id +JOIN product.product_catalog_bindings b ON b.product_id = p.id +JOIN product.catalog_category c ON c.id = b.category_id LEFT JOIN LATERAL ( SELECT MIN(pi.price) AS price, SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, @@ -2936,7 +2989,7 @@ SELECT id, status, campaign_id, version -FROM product.product_category +FROM product.catalog_category WHERE node_type = 1 AND store_id = $2 AND ($1 = false OR status = 1) @@ -2979,8 +3032,8 @@ SELECT c.id, c.campaign_id, c.version, COUNT(p.id) AS product_count -FROM product.product_category AS c -LEFT JOIN product.product_category_bindings AS b ON b.category_id = c.id +FROM product.catalog_category AS c +LEFT JOIN product.product_catalog_bindings AS b ON b.category_id = c.id LEFT JOIN product.products AS p ON p.id = b.product_id AND p.store_id = c.store_id AND p.deleted_at IS NULL @@ -3322,7 +3375,7 @@ func insertCategoryBinding(ctx context.Context, tx *sql.Tx, bindingID, productID } _, err = tx.ExecContext(ctx, ` -INSERT INTO product.product_category_bindings (id, product_id, category_id) +INSERT INTO product.product_catalog_bindings (id, product_id, category_id) VALUES ($1, $2, $3) ON CONFLICT (product_id, category_id) DO NOTHING `, parsedBindingID, parsedProductID, parsedCategoryID) @@ -3355,7 +3408,7 @@ func insertCategoryNode(ctx context.Context, tx *sql.Tx, category CategoryRecord } row := tx.QueryRowContext(ctx, ` -INSERT INTO product.product_category ( +INSERT INTO product.catalog_category ( id, tenant_id, store_id, diff --git a/internal/server/product_category_server.go b/internal/server/product_category_server.go new file mode 100644 index 0000000..60ce373 --- /dev/null +++ b/internal/server/product_category_server.go @@ -0,0 +1,274 @@ +package server + +import ( + "context" + "errors" + "strings" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" + "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" +) + +func (s *ProductServer) CreateProductCategory(ctx context.Context, req *productv1.CreateProductCategoryRequest) (*productv1.CreateProductCategoryResponse, error) { + if req == nil || req.GetProductCategory() == nil { + return nil, status.Error(codes.InvalidArgument, "product_category is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } + root, err := s.productCategoryFromCreate(req.GetProductCategory(), true) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if err := assignProductCategoryIDs(root, s); err != nil { + return nil, err + } + created, err := s.repo.CreateProductCategory(ctx, root, scope) + if err != nil { + return nil, productCategoryGRPCError(err) + } + return &productv1.CreateProductCategoryResponse{ProductCategory: toProtoProductCategory(created)}, nil +} + +func (s *ProductServer) GetProductCategory(ctx context.Context, req *productv1.GetProductCategoryRequest) (*productv1.GetProductCategoryResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if _, err := parsePositiveID(req.GetProductCategoryId(), "product_category_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + value, err := s.repo.GetProductCategory(ctx, req.GetProductCategoryId(), scope) + if err != nil { + return nil, productCategoryGRPCError(err) + } + return &productv1.GetProductCategoryResponse{ProductCategory: toProtoProductCategory(value)}, nil +} + +func (s *ProductServer) ListProductCategories(ctx context.Context, req *productv1.ListProductCategoriesRequest) (*productv1.ListProductCategoriesResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + page, size := normalizedPage(req.GetPage(), req.GetPageSize()) + var state *int32 + if req.Status != nil { + value := req.GetStatus() + if value != 0 && value != 1 { + return nil, status.Error(codes.InvalidArgument, "status must be 0 or 1") + } + state = &value + } + values, total, err := s.repo.ListProductCategories(ctx, repository.ProductCategoryListFilter{Keyword: strings.TrimSpace(req.GetKeyword()), Status: state, Page: page, PageSize: size}, scope) + if err != nil { + return nil, productCategoryGRPCError(err) + } + out := make([]*productv1.ProductCategory, 0, len(values)) + for _, value := range values { + out = append(out, toProtoProductCategory(value)) + } + return &productv1.ListProductCategoriesResponse{ProductCategories: out, Page: page, PageSize: size, Total: total, TotalPages: totalPages(total, size)}, nil +} + +func (s *ProductServer) UpdateProductCategory(ctx context.Context, req *productv1.UpdateProductCategoryRequest) (*productv1.UpdateProductCategoryResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if _, err := parsePositiveID(req.GetProductCategoryId(), "product_category_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if req.GetExpectedVersion() < 0 { + return nil, status.Error(codes.InvalidArgument, "expected_version must be non-negative") + } + patch := repository.ProductCategoryPatch{ExpectedVersion: req.GetExpectedVersion()} + if req.CategoryCode != nil { + value := strings.TrimSpace(req.GetCategoryCode()) + patch.CategoryCode = &value + } + if req.Name != nil { + value := strings.TrimSpace(req.GetName()) + patch.Name = &value + } + if req.ParentId != nil { + value := strings.TrimSpace(req.GetParentId()) + patch.ParentID = &value + } + if req.SortNum != nil { + value := req.GetSortNum() + patch.SortNum = &value + } + if req.Status != nil { + value := req.GetStatus() + if value != 0 && value != 1 { + return nil, status.Error(codes.InvalidArgument, "status must be 0 or 1") + } + patch.Status = &value + } + if req.Remark != nil { + value := strings.TrimSpace(req.GetRemark()) + patch.Remark = &value + } + if patch.CategoryCode == nil && patch.Name == nil && patch.ParentID == nil && patch.SortNum == nil && patch.Status == nil && patch.Remark == nil { + return nil, status.Error(codes.InvalidArgument, "at least one mutable field is required") + } + value, err := s.repo.UpdateProductCategory(ctx, req.GetProductCategoryId(), patch, scope) + if err != nil { + return nil, productCategoryGRPCError(err) + } + return &productv1.UpdateProductCategoryResponse{ProductCategory: toProtoProductCategory(value)}, nil +} + +func (s *ProductServer) DeleteProductCategory(ctx context.Context, req *productv1.DeleteProductCategoryRequest) (*productv1.DeleteProductCategoryResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + deleted, err := s.repo.DeleteProductCategory(ctx, req.GetProductCategoryId(), req.GetExpectedVersion(), scope) + if err != nil { + return nil, productCategoryGRPCError(err) + } + return &productv1.DeleteProductCategoryResponse{DeletedProductCategoryId: req.GetProductCategoryId(), DeletedAt: deleted.Format("2006-01-02T15:04:05Z07:00")}, nil +} + +func (s *ProductServer) BindProductsToProductCategory(ctx context.Context, req *productv1.BindProductsToProductCategoryRequest) (*productv1.BindProductsToProductCategoryResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + ids, err := normalizeGroupProductIDs(req.GetProductIds()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + bindingIDs := make([]string, len(ids)) + for i := range ids { + bindingIDs[i] = s.idgen.NextString() + } + bound, already, err := s.repo.BindProductsToProductCategory(ctx, req.GetProductCategoryId(), bindingIDs, ids, scope) + if err != nil { + return nil, productCategoryGRPCError(err) + } + return &productv1.BindProductsToProductCategoryResponse{BoundCount: bound, AlreadyBoundCount: already}, nil +} + +func (s *ProductServer) UnbindProductsFromProductCategory(ctx context.Context, req *productv1.UnbindProductsFromProductCategoryRequest) (*productv1.UnbindProductsFromProductCategoryResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + ids, err := normalizeGroupProductIDs(req.GetProductIds()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + count, err := s.repo.UnbindProductsFromProductCategory(ctx, req.GetProductCategoryId(), ids, scope) + if err != nil { + return nil, productCategoryGRPCError(err) + } + return &productv1.UnbindProductsFromProductCategoryResponse{UnboundCount: count}, nil +} + +func (s *ProductServer) productCategoryFromCreate(input *productv1.CreateProductCategoryInput, root bool) (*repository.ProductCategoryRecord, error) { + if input == nil { + return nil, errors.New("product category is required") + } + code := strings.TrimSpace(input.GetCategoryCode()) + name := strings.TrimSpace(input.GetName()) + if code == "" || len(code) > 64 { + return nil, errors.New("category_code must contain between 1 and 64 characters") + } + if name == "" || len(name) > 100 { + return nil, errors.New("name must contain between 1 and 100 characters") + } + if !root && input.ParentId != nil { + return nil, errors.New("children must not specify parent_id") + } + value := &repository.ProductCategoryRecord{CategoryCode: code, Name: name, SortNum: input.GetSortNum(), Status: 1, StatusSet: true, Remark: strings.TrimSpace(input.GetRemark())} + if len(value.Remark) > 500 { + return nil, errors.New("remark must contain at most 500 characters") + } + if input.Status != nil { + value.Status = input.GetStatus() + if value.Status != 0 && value.Status != 1 { + return nil, errors.New("status must be 0 or 1") + } + } + if input.ParentId != nil { + value.ParentID = strings.TrimSpace(input.GetParentId()) + } + for _, child := range input.GetChildren() { + item, err := s.productCategoryFromCreate(child, false) + if err != nil { + return nil, err + } + value.Children = append(value.Children, item) + } + return value, nil +} +func assignProductCategoryIDs(node *repository.ProductCategoryRecord, s *ProductServer) error { + if node == nil { + return nil + } + node.ID = s.idgen.NextString() + for _, child := range node.Children { + if err := assignProductCategoryIDs(child, s); err != nil { + return err + } + } + return nil +} +func toProtoProductCategory(value *repository.ProductCategoryRecord) *productv1.ProductCategory { + if value == nil { + return nil + } + out := &productv1.ProductCategory{ProductCategoryId: value.ID, CategoryCode: value.CategoryCode, Name: value.Name, Level: value.Level, IsLeaf: value.IsLeaf, SortNum: value.SortNum, Status: value.Status, Remark: value.Remark, Version: value.Version, CreatedAt: value.CreatedAt.Format("2006-01-02T15:04:05Z07:00"), UpdatedAt: value.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"), ProductCount: value.ProductCount} + if value.ParentID != "" { + out.ParentId = &value.ParentID + } + if value.DeletedAt != nil { + formatted := value.DeletedAt.Format("2006-01-02T15:04:05Z07:00") + out.DeletedAt = &formatted + } + for _, child := range value.Children { + out.Children = append(out.Children, toProtoProductCategory(child)) + } + return out +} +func productCategoryGRPCError(err error) error { + switch { + case errors.Is(err, repository.ErrProductCategoryNotFound): + return status.Error(codes.NotFound, "product category not found") + case errors.Is(err, repository.ErrProductCategoryVersionConflict): + return status.Error(codes.Aborted, "product category version conflict") + case errors.Is(err, repository.ErrDuplicateProductCategory): + return status.Error(codes.AlreadyExists, "product category code or sibling name already exists") + case errors.Is(err, repository.ErrProductCategoryHasChildren), errors.Is(err, repository.ErrProductCategoryInUse): + return status.Error(codes.FailedPrecondition, err.Error()) + default: + return status.Error(codes.InvalidArgument, err.Error()) + } +} diff --git a/internal/server/product_server.go b/internal/server/product_server.go index fb1d39c..79611ea 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -47,6 +47,7 @@ const ( // ProductServer implements productv1.ProductServiceServer. type ProductServer struct { productv1.UnimplementedProductServiceServer + productv1.UnimplementedProductCategoryServiceServer repo *repository.ProductRepository idgen *idgen.Generator @@ -369,7 +370,7 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update var categoryBindingIDs []string var groupIDs *[]string var groupBindingIDs []string - if containsUpdatePath(req.GetUpdateMask().GetPaths(), "leaf_category_ids") { + if containsUpdatePath(req.GetUpdateMask().GetPaths(), "leaf_catalog_category_ids") { leafCategoryIDs = &merged.LeafCategoryIDs if s.idgen == nil { return nil, status.Error(codes.Internal, "id generator is not configured") @@ -1644,7 +1645,7 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1), ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()), } - leafCategoryIDs, err := normalizeLeafCategoryIDs(req.GetLeafCategoryIds()) + leafCategoryIDs, err := normalizeLeafCategoryIDs(req.GetLeafCatalogCategoryIds()) if err != nil { return repository.ProductRecord{}, nil, err } @@ -1735,8 +1736,8 @@ func mergeProductUpdate(current *repository.ProductRecord, update *productv1.Pro merged.ScheduledSaleTime = timestampToTime(update.GetScheduledSaleTime()) case "goods_type": merged.GoodsType = update.GetGoodsType() - case "leaf_category_ids": - leafCategoryIDs, err := normalizeLeafCategoryIDs(update.GetLeafCategoryIds()) + case "leaf_catalog_category_ids": + leafCategoryIDs, err := normalizeLeafCategoryIDs(update.GetLeafCatalogCategoryIds()) if err != nil { return repository.ProductRecord{}, err } @@ -2045,20 +2046,20 @@ func normalizeStringList(values []string) []string { func normalizeLeafCategoryIDs(values []string) ([]string, error) { if len(values) > 100 { - return nil, errors.New("leaf_category_ids must contain at most 100 items") + return nil, errors.New("leaf_catalog_category_ids must contain at most 100 items") } leafCategoryIDs := make([]string, 0, len(values)) seen := make(map[string]struct{}, len(values)) for _, value := range values { categoryID := strings.TrimSpace(value) if categoryID == "" { - return nil, errors.New("leaf_category_ids must not contain an empty id") + return nil, errors.New("leaf_catalog_category_ids must not contain an empty id") } - if _, err := normalizeCategoryID(categoryID, "leaf_category_ids"); err != nil { + if _, err := normalizeCategoryID(categoryID, "leaf_catalog_category_ids"); err != nil { return nil, err } if _, duplicate := seen[categoryID]; duplicate { - return nil, errors.New("leaf_category_ids must not contain duplicates") + return nil, errors.New("leaf_catalog_category_ids must not contain duplicates") } seen[categoryID] = struct{}{} leafCategoryIDs = append(leafCategoryIDs, categoryID) @@ -2190,32 +2191,32 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco } return &productv1.Product{ - ProductId: product.ID, - SpuNo: product.SPUNo, - Title: product.Title, - SellingPoint: product.SellingPoint, - Status: product.Status, - Skus: protoSKUs, - CreatedAt: timeToMillisString(product.CreatedAt), - UpdatedAt: timeToMillisString(product.UpdatedAt), - ImageIds: product.ImageIDs, - BrandId: product.BrandID, - SupplierId: product.SupplierID, - DetailHtml: product.DetailHTML, - MemberDiscountEnabled: product.MemberDiscountEnabled, - GoodsType: product.GoodsType, - ServiceGuarantees: product.ServiceGuarantees, - CrossBorderJson: product.CrossBorderJSON, - CrossBorderInfo: toProtoCrossBorderInfo(product.CrossBorderJSON), - FreightChargeType: product.FreightChargeType, - FreightFixedAmount: product.FreightFixedAmount, - FreightTemplateId: product.FreightTemplateID, - SaleTimeType: product.SaleTimeType, - ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime), - Version: product.Version, - DeletedAt: timePtrToMillisString(product.DeletedAt), - LeafCategoryIds: append([]string(nil), product.LeafCategoryIDs...), - GroupIds: append([]string(nil), product.GroupIDs...), + ProductId: product.ID, + SpuNo: product.SPUNo, + Title: product.Title, + SellingPoint: product.SellingPoint, + Status: product.Status, + Skus: protoSKUs, + CreatedAt: timeToMillisString(product.CreatedAt), + UpdatedAt: timeToMillisString(product.UpdatedAt), + ImageIds: product.ImageIDs, + BrandId: product.BrandID, + SupplierId: product.SupplierID, + DetailHtml: product.DetailHTML, + MemberDiscountEnabled: product.MemberDiscountEnabled, + GoodsType: product.GoodsType, + ServiceGuarantees: product.ServiceGuarantees, + CrossBorderJson: product.CrossBorderJSON, + CrossBorderInfo: toProtoCrossBorderInfo(product.CrossBorderJSON), + FreightChargeType: product.FreightChargeType, + FreightFixedAmount: product.FreightFixedAmount, + FreightTemplateId: product.FreightTemplateID, + SaleTimeType: product.SaleTimeType, + ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime), + Version: product.Version, + DeletedAt: timePtrToMillisString(product.DeletedAt), + LeafCatalogCategoryIds: append([]string(nil), product.LeafCategoryIDs...), + GroupIds: append([]string(nil), product.GroupIDs...), } } diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 4047d3b..a981da9 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -3,6 +3,8 @@ -- -- Tables: -- product.products +-- product.catalog_category +-- product.product_catalog_bindings -- product.product_category -- product.product_category_bindings -- product.product_items @@ -15,6 +17,7 @@ -- Drop order, if needed: -- DROP TABLE IF EXISTS product.product_item_inventory; -- DROP TABLE IF EXISTS product.product_category_bindings; +-- DROP TABLE IF EXISTS product.product_catalog_bindings; -- DROP TABLE IF EXISTS product.product_items; -- DROP TABLE IF EXISTS product.product_category; -- DROP TABLE IF EXISTS product.products; @@ -109,11 +112,11 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no ON product.products (spu_no) WHERE deleted_at IS NULL; -CREATE TABLE IF NOT EXISTS product.product_category ( +CREATE TABLE IF NOT EXISTS product.catalog_category ( id BIGINT PRIMARY KEY, node_type SMALLINT NOT NULL DEFAULT 1, name VARCHAR(100) NOT NULL, - parent_id BIGINT REFERENCES product.product_category(id), + parent_id BIGINT REFERENCES product.catalog_category(id), level SMALLINT NOT NULL, image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], sort_num INTEGER NOT NULL DEFAULT 0, @@ -129,37 +132,71 @@ CREATE TABLE IF NOT EXISTS product.product_category ( CHECK (version >= 0) ); -COMMENT ON TABLE product.product_category IS '商品类别表:存储商品分类和商品分组,通过 node_type 区分分类或分组'; -COMMENT ON COLUMN product.product_category.id IS '类别/分组节点主键'; -COMMENT ON COLUMN product.product_category.node_type IS '节点类型:1 分类,2 分组'; -COMMENT ON COLUMN product.product_category.name IS '节点展示名称'; -COMMENT ON COLUMN product.product_category.parent_id IS '上级节点 ID,顶级节点为空;子节点通过 parent_id 反向查询'; -COMMENT ON COLUMN product.product_category.level IS '节点层级,如 1、2、3'; -COMMENT ON COLUMN product.product_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示'; -COMMENT ON COLUMN product.product_category.sort_num IS '排序值,数值越小越靠前'; -COMMENT ON COLUMN product.product_category.status IS '节点状态:0 隐藏,1 显示'; -COMMENT ON COLUMN product.product_category.version IS '节点乐观锁版本号,更新时递增'; +COMMENT ON TABLE product.catalog_category IS '商品目录分类表:存储原商品分类和商品分组,通过 node_type 区分分类或分组'; +COMMENT ON COLUMN product.catalog_category.id IS '类别/分组节点主键'; +COMMENT ON COLUMN product.catalog_category.node_type IS '节点类型:1 分类,2 分组'; +COMMENT ON COLUMN product.catalog_category.name IS '节点展示名称'; +COMMENT ON COLUMN product.catalog_category.parent_id IS '上级节点 ID,顶级节点为空;子节点通过 parent_id 反向查询'; +COMMENT ON COLUMN product.catalog_category.level IS '节点层级,如 1、2、3'; +COMMENT ON COLUMN product.catalog_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示'; +COMMENT ON COLUMN product.catalog_category.sort_num IS '排序值,数值越小越靠前'; +COMMENT ON COLUMN product.catalog_category.status IS '节点状态:0 隐藏,1 显示'; +COMMENT ON COLUMN product.catalog_category.version IS '节点乐观锁版本号,更新时递增'; -CREATE INDEX IF NOT EXISTS idx_product_category_parent_id - ON product.product_category (parent_id); +CREATE INDEX IF NOT EXISTS idx_catalog_category_parent_id + ON product.catalog_category (parent_id); -CREATE INDEX IF NOT EXISTS idx_product_category_node_status_sort - ON product.product_category (node_type, status, sort_num); +CREATE INDEX IF NOT EXISTS idx_catalog_category_node_status_sort + ON product.catalog_category (node_type, status, sort_num); -CREATE TABLE IF NOT EXISTS product.product_category_bindings ( +CREATE TABLE IF NOT EXISTS product.product_catalog_bindings ( id BIGINT PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, - category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE CASCADE, + category_id BIGINT NOT NULL REFERENCES product.catalog_category(id) ON DELETE CASCADE, CONSTRAINT uq_product_category_bindings_product_category UNIQUE (product_id, category_id) ); -COMMENT ON TABLE product.product_category_bindings IS '商品类别/分组绑定表:存储商品 SPU 与分类/分组节点的多对多绑定关系'; -COMMENT ON COLUMN product.product_category_bindings.id IS '商品类别/分组绑定主键'; -COMMENT ON COLUMN product.product_category_bindings.product_id IS '绑定商品 SPU ID,对应 product.products.id'; -COMMENT ON COLUMN product.product_category_bindings.category_id IS '绑定分类/分组节点 ID,对应 product.product_category.id'; +COMMENT ON TABLE product.product_catalog_bindings IS '商品目录分类/分组绑定表:存储商品 SPU 与分类/分组节点的多对多绑定关系'; +COMMENT ON COLUMN product.product_catalog_bindings.id IS '商品类别/分组绑定主键'; +COMMENT ON COLUMN product.product_catalog_bindings.product_id IS '绑定商品 SPU ID,对应 product.products.id'; +COMMENT ON COLUMN product.product_catalog_bindings.category_id IS '绑定分类/分组节点 ID,对应 product.catalog_category.id'; -CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_id - ON product.product_category_bindings (category_id); +CREATE INDEX IF NOT EXISTS idx_product_catalog_bindings_category_id + ON product.product_catalog_bindings (category_id); + +CREATE TABLE IF NOT EXISTS product.product_category ( + id BIGINT PRIMARY KEY, + tenant_id BIGINT NOT NULL, + store_id BIGINT NOT NULL, + category_code VARCHAR(64) NOT NULL, + name VARCHAR(100) NOT NULL, + parent_id BIGINT REFERENCES product.product_category(id) ON DELETE RESTRICT, + level SMALLINT NOT NULL CHECK (level BETWEEN 1 AND 4), + is_leaf BOOLEAN NOT NULL DEFAULT TRUE, + sort_num INTEGER NOT NULL DEFAULT 0, + status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), + remark VARCHAR(500) NOT NULL DEFAULT '', + version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_store_code_active + ON product.product_category (store_id, category_code) WHERE deleted_at IS NULL; +CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_store_parent_name_active + ON product.product_category (store_id, COALESCE(parent_id, 0), lower(btrim(name))) WHERE deleted_at IS NULL; +CREATE TABLE IF NOT EXISTS product.product_category_bindings ( + id BIGINT PRIMARY KEY, + tenant_id BIGINT NOT NULL, + store_id BIGINT NOT NULL, + product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, + product_category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE RESTRICT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_bindings_active + ON product.product_category_bindings (product_id, product_category_id) WHERE deleted_at IS NULL; CREATE TABLE IF NOT EXISTS product.product_items ( id BIGINT PRIMARY KEY, @@ -298,6 +335,8 @@ CREATE TRIGGER set_product_item_inventory_updated_at FOR EACH ROW EXECUTE FUNCTION public.set_updated_at(); GRANT SELECT, INSERT, UPDATE, DELETE ON product.products TO svc_product; +GRANT SELECT, INSERT, UPDATE, DELETE ON product.catalog_category TO svc_product; +GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_catalog_bindings TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_category TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_category_bindings TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_items TO svc_product;