From 7ab1dbb85cb3cb714f2e0bb459be53b52d983da6 Mon Sep 17 00:00:00 2001 From: BXY <103352887+BXY0414@users.noreply.github.com> Date: Wed, 23 Sep 2026 16:34:15 +0800 Subject: [PATCH] feat: add suppliers and brands management to product catalog - Introduced new tables for suppliers and brands in the product schema with necessary fields and constraints. - Implemented CRUD operations for suppliers and brands in the catalog master server. - Added validation for supplier and brand references in product creation and update processes. - Updated SQL scripts to recreate product tables with new suppliers and brands structure. - Enhanced permissions for the new tables in the database. --- .../repository/catalog_master_repository.go | 469 ++++++++++++++++ internal/repository/product_repository.go | 41 ++ internal/server/catalog_master_server.go | 501 ++++++++++++++++++ internal/server/product_server.go | 6 + scripts/sql/recreate-product-tables.sql | 45 ++ 5 files changed, 1062 insertions(+) create mode 100644 internal/repository/catalog_master_repository.go create mode 100644 internal/server/catalog_master_server.go diff --git a/internal/repository/catalog_master_repository.go b/internal/repository/catalog_master_repository.go new file mode 100644 index 0000000..715993c --- /dev/null +++ b/internal/repository/catalog_master_repository.go @@ -0,0 +1,469 @@ +package repository + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "github.com/jackc/pgx/v5/pgconn" +) + +var ( + ErrSupplierNotFound = errors.New("supplier not found") + ErrBrandNotFound = errors.New("brand not found") + ErrSupplierVersionConflict = errors.New("supplier version conflict") + ErrBrandVersionConflict = errors.New("brand version conflict") + ErrDuplicateSupplierCode = errors.New("supplier_code already exists") + ErrDuplicateBrandCode = errors.New("brand_code already exists") + ErrSupplierHasBrands = errors.New("supplier has non-deleted brands") + ErrSupplierHasActiveBrands = errors.New("supplier has active brands") + ErrBrandInUse = errors.New("brand is referenced by products") + ErrSupplierInactive = errors.New("supplier must be enabled") +) + +type SupplierAttachmentRecord struct { + FileID string `json:"file_id"` + FileName string `json:"file_name"` + FileType string `json:"file_type"` +} + +type SupplierRecord struct { + ID string + Name, Alias, SupplierCode string + Attachments []SupplierAttachmentRecord + ContactName, ContactPhone, Remark string + Status, Version int32 + Scope StoreScope + CreatedAt, UpdatedAt time.Time + DeletedAt *time.Time +} + +type BrandRecord struct { + ID string + Name, Alias, BrandCode, SupplierID string + Status, Version int32 + Scope StoreScope + CreatedAt, UpdatedAt time.Time + DeletedAt *time.Time +} + +type SupplierListFilter struct { + Query string + Status *int32 + Page, PageSize int32 +} +type BrandListFilter struct { + Query, SupplierID string + Status *int32 + Page, PageSize int32 +} + +type SupplierPatch struct { + ExpectedVersion int32 + Name, Alias, SupplierCode *string + Attachments *[]SupplierAttachmentRecord + ContactName, ContactPhone, Remark *string +} +type BrandPatch struct { + ExpectedVersion int32 + Name, Alias, BrandCode, SupplierID *string +} + +func (r *ProductRepository) CreateSupplier(ctx context.Context, supplier SupplierRecord) (*SupplierRecord, error) { + if err := requireWriteScope(supplier.Scope); err != nil { + return nil, err + } + attachments, err := json.Marshal(supplier.Attachments) + if err != nil { + return nil, fmt.Errorf("marshal supplier attachments: %w", err) + } + _, err = r.db.ExecContext(ctx, `INSERT INTO product.suppliers + (id,name,alias,supplier_code,attachments,contact_name,contact_phone,remark,status,tenant_id,store_id) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`, supplier.ID, supplier.Name, supplier.Alias, supplier.SupplierCode, attachments, supplier.ContactName, supplier.ContactPhone, supplier.Remark, supplier.Status, supplier.Scope.TenantID, supplier.Scope.StoreID) + if err != nil { + return nil, mapCatalogWriteError(err, ErrDuplicateSupplierCode) + } + return r.GetSupplier(ctx, supplier.ID, supplier.Scope) +} + +func (r *ProductRepository) GetSupplier(ctx context.Context, id string, scope StoreScope) (*SupplierRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + row := r.db.QueryRowContext(ctx, supplierSelect+` WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL`, id, scope.TenantID, scope.StoreID) + supplier, err := scanSupplier(row) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrSupplierNotFound + } + return supplier, err +} + +func (r *ProductRepository) ListSuppliers(ctx context.Context, filter SupplierListFilter, scope StoreScope) ([]SupplierRecord, int64, error) { + if err := requireWriteScope(scope); err != nil { + return nil, 0, err + } + where, args := catalogWhere(scope, filter.Query, filter.Status, "", false) + var total int64 + if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.suppliers`+where, args...).Scan(&total); err != nil { + return nil, 0, fmt.Errorf("count suppliers: %w", err) + } + args = append(args, filter.PageSize, (filter.Page-1)*filter.PageSize) + rows, err := r.db.QueryContext(ctx, supplierSelect+where+fmt.Sprintf(" ORDER BY created_at DESC, id DESC LIMIT $%d OFFSET $%d", len(args)-1, len(args)), args...) + if err != nil { + return nil, 0, fmt.Errorf("list suppliers: %w", err) + } + defer rows.Close() + out := make([]SupplierRecord, 0) + for rows.Next() { + value, err := scanSupplier(rows) + if err != nil { + return nil, 0, err + } + out = append(out, *value) + } + return out, total, rows.Err() +} + +func (r *ProductRepository) UpdateSupplier(ctx context.Context, id string, patch SupplierPatch, scope StoreScope) (*SupplierRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + sets, args := []string{}, []any{} + add := func(column string, value any) { + args = append(args, value) + sets = append(sets, fmt.Sprintf("%s=$%d", column, len(args))) + } + if patch.Name != nil { + add("name", *patch.Name) + } + if patch.Alias != nil { + add("alias", *patch.Alias) + } + if patch.SupplierCode != nil { + add("supplier_code", *patch.SupplierCode) + } + if patch.Attachments != nil { + raw, err := json.Marshal(*patch.Attachments) + if err != nil { + return nil, err + } + add("attachments", raw) + } + if patch.ContactName != nil { + add("contact_name", *patch.ContactName) + } + if patch.ContactPhone != nil { + add("contact_phone", *patch.ContactPhone) + } + if patch.Remark != nil { + add("remark", *patch.Remark) + } + if len(sets) == 0 { + return nil, errors.New("update_mask must contain at least one mutable field") + } + sets = append(sets, "updated_at=NOW()", "version=version+1") + args = append(args, id, scope.TenantID, scope.StoreID, patch.ExpectedVersion) + query := fmt.Sprintf(`UPDATE product.suppliers SET %s WHERE id=$%d AND tenant_id=$%d AND store_id=$%d AND version=$%d AND deleted_at IS NULL`, strings.Join(sets, ","), len(args)-3, len(args)-2, len(args)-1, len(args)) + result, err := r.db.ExecContext(ctx, query, args...) + if err != nil { + return nil, mapCatalogWriteError(err, ErrDuplicateSupplierCode) + } + changed, _ := result.RowsAffected() + if changed == 0 { + return nil, r.supplierUpdateMiss(ctx, id, patch.ExpectedVersion, scope) + } + return r.GetSupplier(ctx, id, scope) +} + +func (r *ProductRepository) UpdateSupplierStatus(ctx context.Context, id string, statusValue, expectedVersion int32, scope StoreScope) (*SupplierRecord, error) { + if statusValue == 0 { + var active int64 + err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.brands WHERE supplier_id=$1 AND tenant_id=$2 AND store_id=$3 AND status=1 AND deleted_at IS NULL`, id, scope.TenantID, scope.StoreID).Scan(&active) + if err != nil { + return nil, err + } + if active > 0 { + return nil, ErrSupplierHasActiveBrands + } + } + result, err := r.db.ExecContext(ctx, `UPDATE product.suppliers SET status=$1,updated_at=NOW(),version=version+1 WHERE id=$2 AND tenant_id=$3 AND store_id=$4 AND version=$5 AND deleted_at IS NULL`, statusValue, id, scope.TenantID, scope.StoreID, expectedVersion) + if err != nil { + return nil, err + } + changed, _ := result.RowsAffected() + if changed == 0 { + return nil, r.supplierUpdateMiss(ctx, id, expectedVersion, scope) + } + return r.GetSupplier(ctx, id, scope) +} + +func (r *ProductRepository) DeleteSupplier(ctx context.Context, id string, expectedVersion int32, scope StoreScope) (*time.Time, error) { + var brands int64 + if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.brands WHERE supplier_id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL`, id, scope.TenantID, scope.StoreID).Scan(&brands); err != nil { + return nil, err + } + if brands > 0 { + return nil, ErrSupplierHasBrands + } + var deleted time.Time + err := r.db.QueryRowContext(ctx, `UPDATE product.suppliers 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`, id, scope.TenantID, scope.StoreID, expectedVersion).Scan(&deleted) + if errors.Is(err, sql.ErrNoRows) { + return nil, r.supplierUpdateMiss(ctx, id, expectedVersion, scope) + } + return &deleted, err +} + +func (r *ProductRepository) CreateBrand(ctx context.Context, brand BrandRecord) (*BrandRecord, error) { + if err := requireWriteScope(brand.Scope); err != nil { + return nil, err + } + if err := r.ensureEnabledSupplier(ctx, brand.SupplierID, brand.Scope); err != nil { + return nil, err + } + _, err := r.db.ExecContext(ctx, `INSERT INTO product.brands (id,name,alias,brand_code,supplier_id,status,tenant_id,store_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`, brand.ID, brand.Name, brand.Alias, brand.BrandCode, brand.SupplierID, brand.Status, brand.Scope.TenantID, brand.Scope.StoreID) + if err != nil { + return nil, mapCatalogWriteError(err, ErrDuplicateBrandCode) + } + return r.GetBrand(ctx, brand.ID, brand.Scope) +} +func (r *ProductRepository) GetBrand(ctx context.Context, id string, scope StoreScope) (*BrandRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + row := r.db.QueryRowContext(ctx, brandSelect+` WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL`, id, scope.TenantID, scope.StoreID) + value, err := scanBrand(row) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrBrandNotFound + } + return value, err +} +func (r *ProductRepository) ListBrands(ctx context.Context, filter BrandListFilter, scope StoreScope) ([]BrandRecord, int64, error) { + if err := requireWriteScope(scope); err != nil { + return nil, 0, err + } + where, args := catalogWhere(scope, filter.Query, filter.Status, filter.SupplierID, true) + var total int64 + if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.brands`+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, brandSelect+where+fmt.Sprintf(" ORDER BY created_at DESC,id DESC LIMIT $%d OFFSET $%d", len(args)-1, len(args)), args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + out := []BrandRecord{} + for rows.Next() { + value, err := scanBrand(rows) + if err != nil { + return nil, 0, err + } + out = append(out, *value) + } + return out, total, rows.Err() +} +func (r *ProductRepository) UpdateBrand(ctx context.Context, id string, patch BrandPatch, scope StoreScope) (*BrandRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + if patch.SupplierID != nil { + if err := r.ensureEnabledSupplier(ctx, *patch.SupplierID, scope); err != nil { + return nil, err + } + } + sets, args := []string{}, []any{} + add := func(c string, v any) { + args = append(args, v) + sets = append(sets, fmt.Sprintf("%s=$%d", c, len(args))) + } + if patch.Name != nil { + add("name", *patch.Name) + } + if patch.Alias != nil { + add("alias", *patch.Alias) + } + if patch.BrandCode != nil { + add("brand_code", *patch.BrandCode) + } + if patch.SupplierID != nil { + add("supplier_id", *patch.SupplierID) + } + if len(sets) == 0 { + return nil, errors.New("update_mask must contain at least one mutable field") + } + sets = append(sets, "updated_at=NOW()", "version=version+1") + args = append(args, id, scope.TenantID, scope.StoreID, patch.ExpectedVersion) + query := fmt.Sprintf(`UPDATE product.brands SET %s WHERE id=$%d AND tenant_id=$%d AND store_id=$%d AND version=$%d AND deleted_at IS NULL`, strings.Join(sets, ","), len(args)-3, len(args)-2, len(args)-1, len(args)) + result, err := r.db.ExecContext(ctx, query, args...) + if err != nil { + return nil, mapCatalogWriteError(err, ErrDuplicateBrandCode) + } + changed, _ := result.RowsAffected() + if changed == 0 { + return nil, r.brandUpdateMiss(ctx, id, patch.ExpectedVersion, scope) + } + return r.GetBrand(ctx, id, scope) +} +func (r *ProductRepository) UpdateBrandStatus(ctx context.Context, id string, statusValue, expectedVersion int32, scope StoreScope) (*BrandRecord, error) { + result, err := r.db.ExecContext(ctx, `UPDATE product.brands SET status=$1,updated_at=NOW(),version=version+1 WHERE id=$2 AND tenant_id=$3 AND store_id=$4 AND version=$5 AND deleted_at IS NULL`, statusValue, id, scope.TenantID, scope.StoreID, expectedVersion) + if err != nil { + return nil, err + } + changed, _ := result.RowsAffected() + if changed == 0 { + return nil, r.brandUpdateMiss(ctx, id, expectedVersion, scope) + } + return r.GetBrand(ctx, id, scope) +} +func (r *ProductRepository) DeleteBrand(ctx context.Context, id string, expectedVersion int32, scope StoreScope) (*time.Time, error) { + var used int64 + if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.products WHERE brand_id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL`, id, scope.TenantID, scope.StoreID).Scan(&used); err != nil { + return nil, err + } + if used > 0 { + return nil, ErrBrandInUse + } + var deleted time.Time + err := r.db.QueryRowContext(ctx, `UPDATE product.brands 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`, id, scope.TenantID, scope.StoreID, expectedVersion).Scan(&deleted) + if errors.Is(err, sql.ErrNoRows) { + return nil, r.brandUpdateMiss(ctx, id, expectedVersion, scope) + } + return &deleted, err +} + +const supplierSelect = `SELECT id,name,alias,supplier_code,attachments,contact_name,contact_phone,remark,status,tenant_id,store_id,version,created_at,updated_at,deleted_at FROM product.suppliers` +const brandSelect = `SELECT id,name,alias,brand_code,supplier_id,status,tenant_id,store_id,version,created_at,updated_at,deleted_at FROM product.brands` + +type scanner interface{ Scan(...any) error } + +func scanSupplier(row scanner) (*SupplierRecord, error) { + var value SupplierRecord + var raw []byte + var deleted sql.NullTime + err := row.Scan(&value.ID, &value.Name, &value.Alias, &value.SupplierCode, &raw, &value.ContactName, &value.ContactPhone, &value.Remark, &value.Status, &value.Scope.TenantID, &value.Scope.StoreID, &value.Version, &value.CreatedAt, &value.UpdatedAt, &deleted) + if err != nil { + return nil, err + } + if err := json.Unmarshal(raw, &value.Attachments); err != nil { + return nil, fmt.Errorf("decode supplier attachments: %w", err) + } + if deleted.Valid { + value.DeletedAt = &deleted.Time + } + return &value, nil +} +func scanBrand(row scanner) (*BrandRecord, error) { + var value BrandRecord + var deleted sql.NullTime + err := row.Scan(&value.ID, &value.Name, &value.Alias, &value.BrandCode, &value.SupplierID, &value.Status, &value.Scope.TenantID, &value.Scope.StoreID, &value.Version, &value.CreatedAt, &value.UpdatedAt, &deleted) + if err != nil { + return nil, err + } + if deleted.Valid { + value.DeletedAt = &deleted.Time + } + return &value, nil +} +func catalogWhere(scope StoreScope, query string, statusValue *int32, supplierID string, isBrand bool) (string, []any) { + args := []any{scope.TenantID, scope.StoreID} + where := ` WHERE tenant_id=$1 AND store_id=$2 AND deleted_at IS NULL` + if strings.TrimSpace(query) != "" { + args = append(args, "%"+strings.TrimSpace(query)+"%") + where += fmt.Sprintf(" AND (name ILIKE $%d OR alias ILIKE $%d OR %s ILIKE $%d)", len(args), len(args), map[bool]string{true: "brand_code", false: "supplier_code"}[isBrand], len(args)) + } + if statusValue != nil { + args = append(args, *statusValue) + where += fmt.Sprintf(" AND status=$%d", len(args)) + } + if isBrand && strings.TrimSpace(supplierID) != "" { + args = append(args, supplierID) + where += fmt.Sprintf(" AND supplier_id=$%d", len(args)) + } + return where, args +} +func (r *ProductRepository) ensureEnabledSupplier(ctx context.Context, id string, scope StoreScope) error { + var statusValue int32 + err := r.db.QueryRowContext(ctx, `SELECT status FROM product.suppliers WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL`, id, scope.TenantID, scope.StoreID).Scan(&statusValue) + if errors.Is(err, sql.ErrNoRows) { + return ErrSupplierNotFound + } + if err != nil { + return err + } + if statusValue != 1 { + return ErrSupplierInactive + } + return nil +} + +// ValidateProductMasterRefs verifies that optional product supplier and brand +// references are live in the same store and that a supplied pair is related. +func (r *ProductRepository) ValidateProductMasterRefs(ctx context.Context, supplierID, brandID string, scope StoreScope) error { + if err := requireWriteScope(scope); err != nil { + return err + } + if supplierID != "" { + if err := r.ensureEnabledSupplier(ctx, supplierID, scope); err != nil { + return err + } + } + if brandID == "" { + return nil + } + var brandSupplierID string + var brandStatus int32 + err := r.db.QueryRowContext(ctx, `SELECT supplier_id, status FROM product.brands WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL`, brandID, scope.TenantID, scope.StoreID).Scan(&brandSupplierID, &brandStatus) + if errors.Is(err, sql.ErrNoRows) { + return ErrBrandNotFound + } + if err != nil { + return err + } + if brandStatus != 1 { + return ErrSupplierInactive + } + if err := r.ensureEnabledSupplier(ctx, brandSupplierID, scope); err != nil { + return err + } + if supplierID != "" && supplierID != brandSupplierID { + return errors.New("brand does not belong to supplier") + } + return nil +} +func (r *ProductRepository) supplierUpdateMiss(ctx context.Context, id string, version int32, scope StoreScope) error { + current, err := r.GetSupplier(ctx, id, scope) + if errors.Is(err, ErrSupplierNotFound) { + return ErrSupplierNotFound + } + if err != nil { + return err + } + if current.Version != version { + return ErrSupplierVersionConflict + } + return ErrSupplierNotFound +} +func (r *ProductRepository) brandUpdateMiss(ctx context.Context, id string, version int32, scope StoreScope) error { + current, err := r.GetBrand(ctx, id, scope) + if errors.Is(err, ErrBrandNotFound) { + return ErrBrandNotFound + } + if err != nil { + return err + } + if current.Version != version { + return ErrBrandVersionConflict + } + return ErrBrandNotFound +} +func mapCatalogWriteError(err error, duplicate error) error { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && pgErr.Code == "23505" { + return duplicate + } + return err +} diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 71b470f..4ecdb0b 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -422,6 +422,47 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_store_sku_no_active ON product.product_items (store_id, sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE; CREATE INDEX IF NOT EXISTS idx_product_items_store_id ON product.product_items (store_id) WHERE deleted_at IS NULL; +CREATE TABLE IF NOT EXISTS product.suppliers ( + id BIGINT PRIMARY KEY, + name VARCHAR(100) NOT NULL, + alias VARCHAR(100) NOT NULL DEFAULT '', + supplier_code VARCHAR(64) NOT NULL, + attachments JSONB NOT NULL DEFAULT '[]'::JSONB, + contact_name VARCHAR(100) NOT NULL DEFAULT '', + contact_phone VARCHAR(32) NOT NULL DEFAULT '', + remark VARCHAR(1000) NOT NULL DEFAULT '', + status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), + tenant_id BIGINT NOT NULL, + store_id BIGINT NOT NULL, + 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_suppliers_store_code_active + ON product.suppliers (store_id, supplier_code) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_suppliers_store_list + ON product.suppliers (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL; +CREATE TABLE IF NOT EXISTS product.brands ( + id BIGINT PRIMARY KEY, + name VARCHAR(100) NOT NULL, + alias VARCHAR(100) NOT NULL DEFAULT '', + brand_code VARCHAR(64) NOT NULL, + supplier_id BIGINT NOT NULL, + status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), + tenant_id BIGINT NOT NULL, + store_id BIGINT NOT NULL, + 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_brands_store_code_active + ON product.brands (store_id, brand_code) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_brands_store_list + ON product.brands (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_brands_supplier + ON product.brands (store_id, supplier_id) WHERE deleted_at IS NULL; ` if _, err := r.db.ExecContext(ctx, ddl); err != nil { return fmt.Errorf("ensure product tables: %w", err) diff --git a/internal/server/catalog_master_server.go b/internal/server/catalog_master_server.go new file mode 100644 index 0000000..c42a166 --- /dev/null +++ b/internal/server/catalog_master_server.go @@ -0,0 +1,501 @@ +package server + +import ( + "context" + "errors" + "fmt" + "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" +) + +const maxCatalogMasterNameLength = 100 +const maxCatalogMasterCodeLength = 64 + +func (s *ProductServer) CreateSupplier(ctx context.Context, req *productv1.CreateSupplierRequest) (*productv1.CreateSupplierResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + record, err := supplierFromCreate(req) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } + record.ID = s.idgen.NextString() + record.Scope = scope + created, err := s.repo.CreateSupplier(ctx, record) + if err != nil { + return nil, catalogGRPCError(err) + } + return &productv1.CreateSupplierResponse{Supplier: toProtoSupplier(created)}, nil +} +func (s *ProductServer) GetSupplier(ctx context.Context, req *productv1.GetSupplierRequest) (*productv1.GetSupplierResponse, 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 := validatePositiveID(req.GetSupplierId(), "supplier_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + value, err := s.repo.GetSupplier(ctx, req.GetSupplierId(), scope) + if err != nil { + return nil, catalogGRPCError(err) + } + return &productv1.GetSupplierResponse{Supplier: toProtoSupplier(value)}, nil +} +func (s *ProductServer) ListSuppliers(ctx context.Context, req *productv1.ListSuppliersRequest) (*productv1.ListSuppliersResponse, 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, err := catalogPagination(req.GetPage(), req.GetPageSize()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + var statusValue *int32 + if req.Status != nil { + if err := validateCatalogStatus(*req.Status); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + statusValue = req.Status + } + values, total, err := s.repo.ListSuppliers(ctx, repository.SupplierListFilter{Query: strings.TrimSpace(req.GetQuery()), Status: statusValue, Page: page, PageSize: size}, scope) + if err != nil { + return nil, catalogGRPCError(err) + } + out := make([]*productv1.Supplier, 0, len(values)) + for i := range values { + out = append(out, toProtoSupplier(&values[i])) + } + return &productv1.ListSuppliersResponse{Suppliers: out, Page: page, PageSize: size, Total: total, TotalPages: catalogTotalPages(total, size)}, nil +} +func (s *ProductServer) UpdateSupplier(ctx context.Context, req *productv1.UpdateSupplierRequest) (*productv1.UpdateSupplierResponse, 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 := validatePositiveID(req.GetSupplierId(), "supplier_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + patch, err := supplierPatch(req) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + value, err := s.repo.UpdateSupplier(ctx, req.GetSupplierId(), patch, scope) + if err != nil { + return nil, catalogGRPCError(err) + } + return &productv1.UpdateSupplierResponse{Supplier: toProtoSupplier(value)}, nil +} +func (s *ProductServer) UpdateSupplierStatus(ctx context.Context, req *productv1.UpdateSupplierStatusRequest) (*productv1.UpdateSupplierStatusResponse, 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 := validatePositiveID(req.GetSupplierId(), "supplier_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if err := validateCatalogStatus(req.GetStatus()); 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") + } + value, err := s.repo.UpdateSupplierStatus(ctx, req.GetSupplierId(), req.GetStatus(), req.GetExpectedVersion(), scope) + if err != nil { + return nil, catalogGRPCError(err) + } + return &productv1.UpdateSupplierStatusResponse{Supplier: toProtoSupplier(value)}, nil +} +func (s *ProductServer) DeleteSupplier(ctx context.Context, req *productv1.DeleteSupplierRequest) (*productv1.DeleteSupplierResponse, 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 := validatePositiveID(req.GetSupplierId(), "supplier_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") + } + deleted, err := s.repo.DeleteSupplier(ctx, req.GetSupplierId(), req.GetExpectedVersion(), scope) + if err != nil { + return nil, catalogGRPCError(err) + } + return &productv1.DeleteSupplierResponse{SupplierId: req.GetSupplierId(), DeletedAt: timeToMillisString(*deleted)}, nil +} + +func (s *ProductServer) CreateBrand(ctx context.Context, req *productv1.CreateBrandRequest) (*productv1.CreateBrandResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + record, err := brandFromCreate(req) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } + record.ID = s.idgen.NextString() + record.Scope = scope + created, err := s.repo.CreateBrand(ctx, record) + if err != nil { + return nil, catalogGRPCError(err) + } + return &productv1.CreateBrandResponse{Brand: toProtoBrand(created)}, nil +} +func (s *ProductServer) GetBrand(ctx context.Context, req *productv1.GetBrandRequest) (*productv1.GetBrandResponse, 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 := validatePositiveID(req.GetBrandId(), "brand_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + value, err := s.repo.GetBrand(ctx, req.GetBrandId(), scope) + if err != nil { + return nil, catalogGRPCError(err) + } + return &productv1.GetBrandResponse{Brand: toProtoBrand(value)}, nil +} +func (s *ProductServer) ListBrands(ctx context.Context, req *productv1.ListBrandsRequest) (*productv1.ListBrandsResponse, 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, err := catalogPagination(req.GetPage(), req.GetPageSize()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if req.GetSupplierId() != "" { + if err := validatePositiveID(req.GetSupplierId(), "supplier_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + } + var statusValue *int32 + if req.Status != nil { + if err := validateCatalogStatus(*req.Status); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + statusValue = req.Status + } + values, total, err := s.repo.ListBrands(ctx, repository.BrandListFilter{Query: strings.TrimSpace(req.GetQuery()), SupplierID: strings.TrimSpace(req.GetSupplierId()), Status: statusValue, Page: page, PageSize: size}, scope) + if err != nil { + return nil, catalogGRPCError(err) + } + out := make([]*productv1.Brand, 0, len(values)) + for i := range values { + out = append(out, toProtoBrand(&values[i])) + } + return &productv1.ListBrandsResponse{Brands: out, Page: page, PageSize: size, Total: total, TotalPages: catalogTotalPages(total, size)}, nil +} +func (s *ProductServer) UpdateBrand(ctx context.Context, req *productv1.UpdateBrandRequest) (*productv1.UpdateBrandResponse, 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 := validatePositiveID(req.GetBrandId(), "brand_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + patch, err := brandPatch(req) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + value, err := s.repo.UpdateBrand(ctx, req.GetBrandId(), patch, scope) + if err != nil { + return nil, catalogGRPCError(err) + } + return &productv1.UpdateBrandResponse{Brand: toProtoBrand(value)}, nil +} +func (s *ProductServer) UpdateBrandStatus(ctx context.Context, req *productv1.UpdateBrandStatusRequest) (*productv1.UpdateBrandStatusResponse, 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 := validatePositiveID(req.GetBrandId(), "brand_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if err := validateCatalogStatus(req.GetStatus()); 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") + } + value, err := s.repo.UpdateBrandStatus(ctx, req.GetBrandId(), req.GetStatus(), req.GetExpectedVersion(), scope) + if err != nil { + return nil, catalogGRPCError(err) + } + return &productv1.UpdateBrandStatusResponse{Brand: toProtoBrand(value)}, nil +} +func (s *ProductServer) DeleteBrand(ctx context.Context, req *productv1.DeleteBrandRequest) (*productv1.DeleteBrandResponse, 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 := validatePositiveID(req.GetBrandId(), "brand_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") + } + deleted, err := s.repo.DeleteBrand(ctx, req.GetBrandId(), req.GetExpectedVersion(), scope) + if err != nil { + return nil, catalogGRPCError(err) + } + return &productv1.DeleteBrandResponse{BrandId: req.GetBrandId(), DeletedAt: timeToMillisString(*deleted)}, nil +} + +func supplierFromCreate(req *productv1.CreateSupplierRequest) (repository.SupplierRecord, error) { + statusValue := int32(1) + if req.Status != nil { + statusValue = *req.Status + } + if err := validateCatalogStatus(statusValue); err != nil { + return repository.SupplierRecord{}, err + } + attachments, err := attachmentsFromProto(req.GetAttachments()) + if err != nil { + return repository.SupplierRecord{}, err + } + return repository.SupplierRecord{Name: catalogName(req.GetName(), "name"), Alias: strings.TrimSpace(req.GetAlias()), SupplierCode: catalogCode(req.GetSupplierCode(), "supplier_code"), Attachments: attachments, ContactName: strings.TrimSpace(req.GetContactName()), ContactPhone: strings.TrimSpace(req.GetContactPhone()), Remark: strings.TrimSpace(req.GetRemark()), Status: statusValue}, validateCatalogMasterFields(catalogName(req.GetName(), "name"), catalogCode(req.GetSupplierCode(), "supplier_code")) +} +func brandFromCreate(req *productv1.CreateBrandRequest) (repository.BrandRecord, error) { + statusValue := int32(1) + if req.Status != nil { + statusValue = *req.Status + } + if err := validateCatalogStatus(statusValue); err != nil { + return repository.BrandRecord{}, err + } + if err := validatePositiveID(req.GetSupplierId(), "supplier_id"); err != nil { + return repository.BrandRecord{}, err + } + name, code := catalogName(req.GetName(), "name"), catalogCode(req.GetBrandCode(), "brand_code") + if err := validateCatalogMasterFields(name, code); err != nil { + return repository.BrandRecord{}, err + } + return repository.BrandRecord{Name: name, Alias: strings.TrimSpace(req.GetAlias()), BrandCode: code, SupplierID: req.GetSupplierId(), Status: statusValue}, nil +} +func supplierPatch(req *productv1.UpdateSupplierRequest) (repository.SupplierPatch, error) { + if req.GetSupplier() == nil { + return repository.SupplierPatch{}, errors.New("supplier is required") + } + if req.GetExpectedVersion() < 0 { + return repository.SupplierPatch{}, errors.New("expected_version must be non-negative") + } + out := repository.SupplierPatch{ExpectedVersion: req.GetExpectedVersion()} + for _, field := range req.GetUpdateMask().GetPaths() { + switch field { + case "name": + v := catalogName(req.GetSupplier().GetName(), "name") + if err := validateCatalogName(v); err != nil { + return out, err + } + out.Name = &v + case "alias": + v := strings.TrimSpace(req.GetSupplier().GetAlias()) + out.Alias = &v + case "supplier_code": + v := catalogCode(req.GetSupplier().GetSupplierCode(), "supplier_code") + if err := validateCatalogCode(v); err != nil { + return out, err + } + out.SupplierCode = &v + case "attachments": + v, err := attachmentsFromProto(req.GetSupplier().GetAttachments()) + if err != nil { + return out, err + } + out.Attachments = &v + case "contact_name": + v := strings.TrimSpace(req.GetSupplier().GetContactName()) + out.ContactName = &v + case "contact_phone": + v := strings.TrimSpace(req.GetSupplier().GetContactPhone()) + out.ContactPhone = &v + case "remark": + v := strings.TrimSpace(req.GetSupplier().GetRemark()) + out.Remark = &v + default: + return out, fmt.Errorf("unsupported update_mask path: %s", field) + } + } + return out, nil +} +func brandPatch(req *productv1.UpdateBrandRequest) (repository.BrandPatch, error) { + if req.GetBrand() == nil { + return repository.BrandPatch{}, errors.New("brand is required") + } + if req.GetExpectedVersion() < 0 { + return repository.BrandPatch{}, errors.New("expected_version must be non-negative") + } + out := repository.BrandPatch{ExpectedVersion: req.GetExpectedVersion()} + for _, field := range req.GetUpdateMask().GetPaths() { + switch field { + case "name": + v := catalogName(req.GetBrand().GetName(), "name") + if err := validateCatalogName(v); err != nil { + return out, err + } + out.Name = &v + case "alias": + v := strings.TrimSpace(req.GetBrand().GetAlias()) + out.Alias = &v + case "brand_code": + v := catalogCode(req.GetBrand().GetBrandCode(), "brand_code") + if err := validateCatalogCode(v); err != nil { + return out, err + } + out.BrandCode = &v + case "supplier_id": + v := strings.TrimSpace(req.GetBrand().GetSupplierId()) + if err := validatePositiveID(v, "supplier_id"); err != nil { + return out, err + } + out.SupplierID = &v + default: + return out, fmt.Errorf("unsupported update_mask path: %s", field) + } + } + return out, nil +} +func attachmentsFromProto(values []*productv1.SupplierAttachment) ([]repository.SupplierAttachmentRecord, error) { + out := make([]repository.SupplierAttachmentRecord, 0, len(values)) + for _, item := range values { + if item == nil || strings.TrimSpace(item.GetFileId()) == "" { + return nil, errors.New("attachments[].file_id is required") + } + out = append(out, repository.SupplierAttachmentRecord{FileID: strings.TrimSpace(item.GetFileId()), FileName: strings.TrimSpace(item.GetFileName()), FileType: strings.TrimSpace(item.GetFileType())}) + } + return out, nil +} +func catalogName(value, _ string) string { return strings.TrimSpace(value) } +func catalogCode(value, _ string) string { return strings.TrimSpace(value) } +func validateCatalogMasterFields(name, code string) error { + if err := validateCatalogName(name); err != nil { + return err + } + return validateCatalogCode(code) +} +func validateCatalogName(value string) error { + if value == "" { + return errors.New("name is required") + } + if len([]rune(value)) > maxCatalogMasterNameLength { + return fmt.Errorf("name must be at most %d characters", maxCatalogMasterNameLength) + } + return nil +} +func validateCatalogCode(value string) error { + if value == "" { + return errors.New("code is required") + } + if len([]rune(value)) > maxCatalogMasterCodeLength { + return fmt.Errorf("code must be at most %d characters", maxCatalogMasterCodeLength) + } + return nil +} +func validateCatalogStatus(value int32) error { + if value != 0 && value != 1 { + return errors.New("status must be 0 or 1") + } + return nil +} +func catalogPagination(page, size int32) (int32, int32, error) { + if page == 0 { + page = 1 + } + if size == 0 { + size = defaultPageSize + } + if page < 1 { + return 0, 0, errors.New("page must be positive") + } + if size < 1 || size > maxPageSize { + return 0, 0, fmt.Errorf("page_size must be between 1 and %d", maxPageSize) + } + return page, size, nil +} +func catalogTotalPages(total int64, size int32) int32 { + if total == 0 { + return 0 + } + return int32((total + int64(size) - 1) / int64(size)) +} +func toProtoSupplier(value *repository.SupplierRecord) *productv1.Supplier { + if value == nil { + return nil + } + out := &productv1.Supplier{SupplierId: value.ID, Name: value.Name, Alias: value.Alias, SupplierCode: value.SupplierCode, ContactName: value.ContactName, ContactPhone: value.ContactPhone, Remark: value.Remark, Status: value.Status, TenantId: fmt.Sprint(value.Scope.TenantID), StoreId: fmt.Sprint(value.Scope.StoreID), CreatedAt: timeToMillisString(value.CreatedAt), UpdatedAt: timeToMillisString(value.UpdatedAt), Version: value.Version} + for _, item := range value.Attachments { + out.Attachments = append(out.Attachments, &productv1.SupplierAttachment{FileId: item.FileID, FileName: item.FileName, FileType: item.FileType}) + } + out.DeletedAt = timePtrToMillisString(value.DeletedAt) + return out +} +func toProtoBrand(value *repository.BrandRecord) *productv1.Brand { + if value == nil { + return nil + } + return &productv1.Brand{BrandId: value.ID, Name: value.Name, Alias: value.Alias, BrandCode: value.BrandCode, SupplierId: value.SupplierID, Status: value.Status, TenantId: fmt.Sprint(value.Scope.TenantID), StoreId: fmt.Sprint(value.Scope.StoreID), CreatedAt: timeToMillisString(value.CreatedAt), UpdatedAt: timeToMillisString(value.UpdatedAt), DeletedAt: timePtrToMillisString(value.DeletedAt), Version: value.Version} +} +func catalogGRPCError(err error) error { + switch { + case errors.Is(err, repository.ErrSupplierNotFound), errors.Is(err, repository.ErrBrandNotFound): + return status.Error(codes.NotFound, err.Error()) + case errors.Is(err, repository.ErrSupplierVersionConflict), errors.Is(err, repository.ErrBrandVersionConflict): + return status.Error(codes.Aborted, err.Error()) + case errors.Is(err, repository.ErrDuplicateSupplierCode), errors.Is(err, repository.ErrDuplicateBrandCode): + return status.Error(codes.AlreadyExists, err.Error()) + case errors.Is(err, repository.ErrSupplierHasBrands), errors.Is(err, repository.ErrSupplierHasActiveBrands), errors.Is(err, repository.ErrBrandInUse), errors.Is(err, repository.ErrSupplierInactive): + return status.Error(codes.FailedPrecondition, err.Error()) + case errors.Is(err, repository.ErrStoreScopeRequired): + return status.Error(codes.InvalidArgument, err.Error()) + default: + return status.Error(codes.Internal, "catalog master operation failed") + } +} diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 091a6c3..391f5e2 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -84,6 +84,9 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create return nil, status.Error(codes.InvalidArgument, err.Error()) } product.Scope = scope + if err := s.repo.ValidateProductMasterRefs(ctx, product.SupplierID, product.BrandID, scope); err != nil { + return nil, catalogGRPCError(err) + } if s.idgen == nil { return nil, status.Error(codes.Internal, "id generator is not configured") } @@ -315,6 +318,9 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update if err := validateProductForUpdate(merged); err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } + if err := s.repo.ValidateProductMasterRefs(ctx, merged.SupplierID, merged.BrandID, scope); err != nil { + return nil, catalogGRPCError(err) + } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.update", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) defer dbSpan.End() diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index c83d36f..cecc4ab 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -237,6 +237,49 @@ COMMENT ON COLUMN product.product_item_inventory.version IS '库存乐观锁版 COMMENT ON TABLE product.inventory_adjustments IS '订单库存动作幂等表:记录确认成交和释放锁定库存'; COMMENT ON COLUMN product.inventory_adjustments.action IS '库存动作:confirm 支付成功确认成交;release 待支付取消/超时释放锁定'; +CREATE TABLE IF NOT EXISTS product.suppliers ( + id BIGINT PRIMARY KEY, + name VARCHAR(100) NOT NULL, + alias VARCHAR(100) NOT NULL DEFAULT '', + supplier_code VARCHAR(64) NOT NULL, + attachments JSONB NOT NULL DEFAULT '[]'::JSONB, + contact_name VARCHAR(100) NOT NULL DEFAULT '', + contact_phone VARCHAR(32) NOT NULL DEFAULT '', + remark VARCHAR(1000) NOT NULL DEFAULT '', + status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), + tenant_id BIGINT NOT NULL, + store_id BIGINT NOT NULL, + 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_suppliers_store_code_active ON product.suppliers (store_id, supplier_code) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_suppliers_store_list ON product.suppliers (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL; + +CREATE TABLE IF NOT EXISTS product.brands ( + id BIGINT PRIMARY KEY, + name VARCHAR(100) NOT NULL, + alias VARCHAR(100) NOT NULL DEFAULT '', + brand_code VARCHAR(64) NOT NULL, + supplier_id BIGINT NOT NULL, + status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), + tenant_id BIGINT NOT NULL, + store_id BIGINT NOT NULL, + 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_brands_store_code_active ON product.brands (store_id, brand_code) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_brands_store_list ON product.brands (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_brands_supplier ON product.brands (store_id, supplier_id) WHERE deleted_at IS NULL; + +DROP TRIGGER IF EXISTS set_suppliers_updated_at ON product.suppliers; +CREATE TRIGGER set_suppliers_updated_at BEFORE UPDATE ON product.suppliers FOR EACH ROW EXECUTE FUNCTION public.set_updated_at(); +DROP TRIGGER IF EXISTS set_brands_updated_at ON product.brands; +CREATE TRIGGER set_brands_updated_at BEFORE UPDATE ON product.brands FOR EACH ROW EXECUTE FUNCTION public.set_updated_at(); + DROP TRIGGER IF EXISTS set_products_updated_at ON product.products; CREATE TRIGGER set_products_updated_at BEFORE UPDATE ON product.products @@ -258,3 +301,5 @@ GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_category_bindings TO svc GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_items TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_item_inventory TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.inventory_adjustments TO svc_product; +GRANT SELECT, INSERT, UPDATE, DELETE ON product.suppliers TO svc_product; +GRANT SELECT, INSERT, UPDATE, DELETE ON product.brands TO svc_product;