diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 57e098a..9dcb1ee 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -55,6 +55,12 @@ var ErrSKUArchived = errors.New("sku is archived") // ErrSKUReplacementRequiresNotOnSale is returned when replacing SKUs for an on-sale product. var ErrSKUReplacementRequiresNotOnSale = errors.New("sku replacement requires inventory or off-sale product status") +// ErrSameStore is returned when a store transfer targets the product's current store. +var ErrSameStore = errors.New("target store is the current store") + +// ErrDuplicateSKUNo is returned when the destination store already has an active SKU number. +var ErrDuplicateSKUNo = errors.New("sku_no already exists in target store") + // ProductRecord is the persistence model for product.products (SPU). type ProductRecord struct { ID string @@ -1265,6 +1271,120 @@ RETURNING version, updated_at return result, nil } +// TransferProductStoreResult is the identity after a same-tenant store move. +type TransferProductStoreResult struct { + ProductID string + TenantID int64 + StoreID int64 +} + +// TransferProductStore moves a product and its SKUs to another store. Tenant stays unchanged. +// Category bindings are dropped because categories are store-scoped. +func (r *ProductRepository) TransferProductStore(ctx context.Context, productID string, targetStoreID int64, scope StoreScope) (*TransferProductStoreResult, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + if targetStoreID <= 0 { + return nil, fmt.Errorf("target store id must be a positive snowflake id") + } + if targetStoreID == scope.StoreID { + return nil, ErrSameStore + } + id, err := parseID(productID, "product id") + if err != nil { + return nil, err + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin transfer product store: %w", err) + } + defer tx.Rollback() + + var tenantID int64 + var spuNo string + err = tx.QueryRowContext(ctx, ` +SELECT tenant_id, spu_no +FROM product.products +WHERE id = $1 AND deleted_at IS NULL AND store_id = $2 AND tenant_id = $3 +FOR UPDATE +`, id, scope.StoreID, scope.TenantID).Scan(&tenantID, &spuNo) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrProductNotFound + } + if err != nil { + return nil, fmt.Errorf("lock product %s: %w", productID, err) + } + + var taken int + if err := tx.QueryRowContext(ctx, ` +SELECT 1 +FROM product.products +WHERE store_id = $1 AND spu_no = $2 AND deleted_at IS NULL AND id <> $3 +LIMIT 1 +`, targetStoreID, spuNo, id).Scan(&taken); err != nil && !errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("check target spu_no: %w", err) + } + if taken == 1 { + return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, spuNo) + } + + var conflictSKU string + if err := tx.QueryRowContext(ctx, ` +SELECT pi.sku_no +FROM product.product_items pi +WHERE pi.product_id = $1 + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE + AND pi.sku_no IS NOT NULL + AND EXISTS ( + SELECT 1 + FROM product.product_items other + WHERE other.store_id = $2 + AND other.sku_no = pi.sku_no + AND other.deleted_at IS NULL + AND other.is_archived = FALSE + AND other.product_id <> $1 + ) +LIMIT 1 +`, id, targetStoreID).Scan(&conflictSKU); err != nil && !errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("check target sku_no: %w", err) + } + if conflictSKU != "" { + return nil, fmt.Errorf("%w: %s", ErrDuplicateSKUNo, conflictSKU) + } + + if _, err := tx.ExecContext(ctx, ` +UPDATE product.products +SET store_id = $2, version = version + 1, updated_at = NOW() +WHERE id = $1 AND store_id = $3 AND tenant_id = $4 AND deleted_at IS NULL +`, id, targetStoreID, scope.StoreID, tenantID); err != nil { + if isPostgresConstraintError(err, "23505", "uq_products_store_spu_no") { + return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, spuNo) + } + return nil, fmt.Errorf("update product store: %w", err) + } + if _, err := tx.ExecContext(ctx, ` +UPDATE product.product_items +SET store_id = $2 +WHERE product_id = $1 AND store_id = $3 +`, id, targetStoreID, scope.StoreID); err != nil { + if isPostgresConstraintError(err, "23505", "uq_product_items_store_sku_no_active") { + return nil, ErrDuplicateSKUNo + } + return nil, fmt.Errorf("update sku store: %w", err) + } + if _, err := tx.ExecContext(ctx, ` +DELETE FROM product.product_category_bindings +WHERE product_id = $1 +`, id); err != nil { + return nil, fmt.Errorf("detach product categories: %w", err) + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit transfer product store: %w", err) + } + return &TransferProductStoreResult{ProductID: productID, TenantID: tenantID, StoreID: targetStoreID}, nil +} + func updateCurrentSKU(ctx context.Context, tx *sql.Tx, productID int64, input SKUUpdate) error { if input.ExpectedSKUVersion < 0 || input.ExpectedInventoryVersion < 0 { return fmt.Errorf("expected sku and inventory versions must be non-negative") diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 403be47..3e07a2f 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -394,6 +394,44 @@ func (s *ProductServer) UpdateProductStatus(ctx context.Context, req *productv1. }, nil } +// TransferProductStore moves a product to another store without changing tenant. +func (s *ProductServer) TransferProductStore(ctx context.Context, req *productv1.TransferProductStoreRequest) (*productv1.TransferProductStoreResponse, error) { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if req.GetProductId() == "" { + return nil, status.Error(codes.InvalidArgument, "product_id is required") + } + targetStoreID, err := parsePositiveID(strings.TrimSpace(req.GetTargetStoreId()), "target_store_id") + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.store.transfer", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) + defer dbSpan.End() + updated, err := s.repo.TransferProductStore(dbCtx, req.GetProductId(), targetStoreID, scope) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + switch { + case errors.Is(err, repository.ErrProductNotFound): + return nil, status.Error(codes.NotFound, "product not found") + case errors.Is(err, repository.ErrSameStore): + return nil, status.Error(codes.InvalidArgument, "target store is the current store") + case errors.Is(err, repository.ErrDuplicateSPUNo), errors.Is(err, repository.ErrDuplicateSKUNo): + return nil, status.Error(codes.AlreadyExists, err.Error()) + default: + s.observer.Logger(ctx).Error("transfer product store failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "transfer product store: %v", err) + } + } + return &productv1.TransferProductStoreResponse{ + ProductId: updated.ProductID, + TenantId: strconv.FormatInt(updated.TenantID, 10), + StoreId: strconv.FormatInt(updated.StoreID, 10), + }, nil +} + // ListProducts returns a paginated list of all non-deleted products. func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListProductsRequest) (*productv1.ListProductsResponse, error) { scope, err := requireStoreScope(req)