ids-svc-product/internal/repository/product_batch.go

414 lines
12 KiB
Go

package repository
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
)
// ErrNoActiveSKU is returned when a product has no sellable/active SKUs for batch price.
var ErrNoActiveSKU = errors.New("product has no active sku")
// ErrInvalidCatalogCategory is returned when a filter target is not a catalog category.
var ErrInvalidCatalogCategory = errors.New("category must be an existing catalog category")
const maxProductBatchSize = 100
// ValidateCatalogCategory ensures categoryID is a storefront catalog category (node_type=1).
func (r *ProductRepository) ValidateCatalogCategory(ctx context.Context, categoryID string, scope StoreScope) error {
if err := requireWriteScope(scope); err != nil {
return err
}
id, err := parseID(categoryID, "category_id")
if err != nil {
return err
}
var nodeType int16
err = r.db.QueryRowContext(ctx, `
SELECT node_type
FROM product.catalog_category
WHERE id = $1 AND store_id = $2
`, id, scope.StoreID).Scan(&nodeType)
if errors.Is(err, sql.ErrNoRows) {
return ErrInvalidCatalogCategory
}
if err != nil {
return fmt.Errorf("validate catalog category: %w", err)
}
if nodeType != 1 {
return ErrInvalidCatalogCategory
}
return nil
}
func parseBatchProductIDs(productIDs []string) ([]int64, []string, error) {
if len(productIDs) == 0 {
return nil, nil, errors.New("product_ids is required")
}
seen := make(map[string]struct{}, len(productIDs))
unique := make([]string, 0, len(productIDs))
for _, raw := range productIDs {
id := strings.TrimSpace(raw)
if id == "" {
continue
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
unique = append(unique, id)
}
if len(unique) == 0 {
return nil, nil, errors.New("product_ids is required")
}
if len(unique) > maxProductBatchSize {
return nil, nil, fmt.Errorf("product_ids must contain at most %d items", maxProductBatchSize)
}
parsed := make([]int64, len(unique))
for i, id := range unique {
n, err := parseID(id, "product_id")
if err != nil {
return nil, nil, err
}
parsed[i] = n
}
return parsed, unique, nil
}
func productIDPlaceholders(ids []int64, start int) (string, []any) {
placeholders := make([]string, len(ids))
args := make([]any, len(ids))
for i, id := range ids {
placeholders[i] = fmt.Sprintf("$%d", start+i)
args[i] = id
}
return strings.Join(placeholders, ", "), args
}
func (r *ProductRepository) lockProductsInStore(ctx context.Context, tx *sql.Tx, productIDs []int64, originalIDs []string, scope StoreScope) error {
ph, args := productIDPlaceholders(productIDs, 2)
queryArgs := append([]any{scope.StoreID}, args...)
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
SELECT id
FROM product.products
WHERE store_id = $1
AND deleted_at IS NULL
AND id IN (%s)
FOR UPDATE
`, ph), queryArgs...)
if err != nil {
return fmt.Errorf("lock products: %w", err)
}
defer rows.Close()
found := make(map[int64]struct{}, len(productIDs))
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return fmt.Errorf("scan locked product: %w", err)
}
found[id] = struct{}{}
}
if err := rows.Err(); err != nil {
return fmt.Errorf("iterate locked products: %w", err)
}
for i, id := range productIDs {
if _, ok := found[id]; !ok {
return fmt.Errorf("%w: %s", ErrProductNotFound, originalIDs[i])
}
}
return nil
}
// BatchUpdateProductStatus sets status for every listed product using the current row version.
func (r *ProductRepository) BatchUpdateProductStatus(ctx context.Context, productIDs []string, next productv1.ProductStatus, scope StoreScope) (int32, error) {
if err := requireWriteScope(scope); err != nil {
return 0, err
}
if next != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY &&
next != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE &&
next != productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT {
return 0, fmt.Errorf("unsupported product status")
}
parsed, originals, err := parseBatchProductIDs(productIDs)
if err != nil {
return 0, err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return 0, fmt.Errorf("begin batch update product status: %w", err)
}
defer tx.Rollback()
if err := r.lockProductsInStore(ctx, tx, parsed, originals, scope); err != nil {
return 0, err
}
updated := int32(0)
for i, id := range parsed {
var previousDBStatus int16
var currentVersion int32
err := tx.QueryRowContext(ctx, `
SELECT status, version
FROM product.products
WHERE id = $1 AND deleted_at IS NULL AND store_id = $2
`, id, scope.StoreID).Scan(&previousDBStatus, &currentVersion)
if errors.Is(err, sql.ErrNoRows) {
return 0, fmt.Errorf("%w: %s", ErrProductNotFound, originals[i])
}
if err != nil {
return 0, fmt.Errorf("load product %s: %w", originals[i], err)
}
previous := statusFromDB(previousDBStatus)
if previous == next {
updated++
continue
}
if next == productv1.ProductStatus_PRODUCT_STATUS_ON_SALE {
sellable, err := hasSellableSKU(ctx, tx, id)
if err != nil {
return 0, err
}
if !sellable {
return 0, fmt.Errorf("cannot put product on sale without a sellable sku: %s", originals[i])
}
}
res, err := tx.ExecContext(ctx, `
UPDATE product.products
SET status = $2, version = version + 1, updated_at = NOW()
WHERE id = $1 AND version = $3 AND deleted_at IS NULL AND store_id = $4
`, id, statusToDB(next), currentVersion, scope.StoreID)
if err != nil {
return 0, fmt.Errorf("update product status %s: %w", originals[i], err)
}
affected, err := res.RowsAffected()
if err != nil {
return 0, fmt.Errorf("rows affected for %s: %w", originals[i], err)
}
if affected == 0 {
return 0, ErrProductVersionConflict
}
updated++
}
if err := tx.Commit(); err != nil {
return 0, fmt.Errorf("commit batch update product status: %w", err)
}
return updated, nil
}
// BatchDeleteProducts soft-deletes products and their SKUs in one store transaction.
func (r *ProductRepository) BatchDeleteProducts(ctx context.Context, productIDs []string, scope StoreScope) error {
if err := requireWriteScope(scope); err != nil {
return err
}
parsed, originals, err := parseBatchProductIDs(productIDs)
if err != nil {
return err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin batch delete products: %w", err)
}
defer tx.Rollback()
if err := r.lockProductsInStore(ctx, tx, parsed, originals, scope); err != nil {
return err
}
ph, args := productIDPlaceholders(parsed, 2)
queryArgs := append([]any{scope.StoreID}, args...)
res, err := tx.ExecContext(ctx, fmt.Sprintf(`
UPDATE product.products
SET deleted_at = COALESCE(deleted_at, NOW()), updated_at = NOW()
WHERE store_id = $1
AND deleted_at IS NULL
AND id IN (%s)
`, ph), queryArgs...)
if err != nil {
return fmt.Errorf("batch delete products: %w", err)
}
affected, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("rows affected: %w", err)
}
if affected != int64(len(parsed)) {
return ErrProductNotFound
}
skuPH, skuArgs := productIDPlaceholders(parsed, 1)
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`
UPDATE product.product_items
SET deleted_at = COALESCE(deleted_at, NOW()), updated_at = NOW()
WHERE deleted_at IS NULL
AND product_id IN (%s)
`, skuPH), skuArgs...); err != nil {
return fmt.Errorf("batch delete product skus: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit batch delete products: %w", err)
}
return nil
}
// BatchUpdateProductPricesResult counts products and SKUs updated by BatchUpdateProductPrices.
type BatchUpdateProductPricesResult struct {
UpdatedProductCount int32
UpdatedSKUCount int32
}
// BatchUpdateProductPrices sets price on every active SKU of the listed products.
func (r *ProductRepository) BatchUpdateProductPrices(ctx context.Context, productIDs []string, price int64, scope StoreScope) (*BatchUpdateProductPricesResult, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
if price <= 0 {
return nil, errors.New("price must be greater than 0")
}
parsed, originals, err := parseBatchProductIDs(productIDs)
if err != nil {
return nil, err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin batch update product prices: %w", err)
}
defer tx.Rollback()
if err := r.lockProductsInStore(ctx, tx, parsed, originals, scope); err != nil {
return nil, err
}
result := &BatchUpdateProductPricesResult{}
for i, id := range parsed {
res, err := tx.ExecContext(ctx, `
UPDATE product.product_items
SET price = $2, version = version + 1, updated_at = NOW()
WHERE product_id = $1
AND deleted_at IS NULL
AND is_archived = FALSE
`, id, price)
if err != nil {
return nil, fmt.Errorf("update sku prices for %s: %w", originals[i], err)
}
skuCount, err := res.RowsAffected()
if err != nil {
return nil, fmt.Errorf("sku rows affected for %s: %w", originals[i], err)
}
if skuCount == 0 {
return nil, fmt.Errorf("%w: %s", ErrNoActiveSKU, originals[i])
}
if _, err := tx.ExecContext(ctx, `
UPDATE product.products
SET version = version + 1, updated_at = NOW()
WHERE id = $1 AND deleted_at IS NULL AND store_id = $2
`, id, scope.StoreID); err != nil {
return nil, fmt.Errorf("bump product version %s: %w", originals[i], err)
}
result.UpdatedProductCount++
result.UpdatedSKUCount += int32(skuCount)
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit batch update product prices: %w", err)
}
return result, nil
}
// ReplaceProductsGroup clears all group bindings for the products and binds them to groupID.
func (r *ProductRepository) ReplaceProductsGroup(ctx context.Context, productIDs []string, groupID string, bindingIDs []string, scope StoreScope) (int32, error) {
if err := requireWriteScope(scope); err != nil {
return 0, err
}
parsed, originals, err := parseBatchProductIDs(productIDs)
if err != nil {
return 0, err
}
if len(bindingIDs) != len(parsed) {
return 0, errors.New("binding ids must match product ids")
}
parsedGroupID, err := parseID(groupID, "group_id")
if err != nil {
return 0, err
}
parsedBindingIDs := make([]int64, len(bindingIDs))
for i, bindingID := range bindingIDs {
parsedBindingIDs[i], err = parseID(bindingID, "category binding id")
if err != nil {
return 0, err
}
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return 0, fmt.Errorf("begin replace products group: %w", err)
}
defer tx.Rollback()
err = tx.QueryRowContext(ctx, `
SELECT c.id
FROM product.catalog_category AS c
WHERE c.id = $1
AND c.node_type = 2
AND c.store_id = $2
AND NOT EXISTS (
SELECT 1
FROM product.catalog_category child
WHERE child.parent_id = c.id
AND child.store_id = $2
AND child.node_type = 2
)
`, parsedGroupID, scope.StoreID).Scan(&parsedGroupID)
if errors.Is(err, sql.ErrNoRows) {
return 0, fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID)
}
if err != nil {
return 0, fmt.Errorf("query group %s: %w", groupID, err)
}
if err := r.lockProductsInStore(ctx, tx, parsed, originals, scope); err != nil {
return 0, err
}
ph, args := productIDPlaceholders(parsed, 2)
queryArgs := append([]any{scope.StoreID}, args...)
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`
DELETE FROM product.product_catalog_bindings pcb
USING product.catalog_category pc
WHERE pcb.category_id = pc.id
AND pc.node_type = 2
AND pc.store_id = $1
AND pcb.product_id IN (%s)
`, ph), queryArgs...); err != nil {
return 0, fmt.Errorf("clear group bindings: %w", err)
}
valuePlaceholders := make([]string, len(parsed))
insertArgs := make([]any, 0, len(parsed)*3)
for i, productID := range parsed {
base := i * 3
valuePlaceholders[i] = fmt.Sprintf("($%d, $%d, $%d)", base+1, base+2, base+3)
insertArgs = append(insertArgs, parsedBindingIDs[i], productID, parsedGroupID)
}
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`
INSERT INTO product.product_catalog_bindings (id, product_id, category_id)
VALUES %s
ON CONFLICT (product_id, category_id) DO NOTHING
`, strings.Join(valuePlaceholders, ", ")), insertArgs...); err != nil {
return 0, fmt.Errorf("insert group bindings: %w", err)
}
if err := tx.Commit(); err != nil {
return 0, fmt.Errorf("commit replace products group: %w", err)
}
return int32(len(parsed)), nil
}