diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 224a4ed..587f2d5 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -69,6 +69,8 @@ var ErrProductVersionConflict = errors.New("product version conflict") // ErrSKUVersionConflict indicates that a concurrent SKU or inventory change won the optimistic-lock race. var ErrSKUVersionConflict = errors.New("sku version conflict") +var ErrInvalidSKUUpdate = errors.New("invalid sku update") + // ErrSKUArchived is returned when an operation attempts to modify an archived SKU. var ErrSKUArchived = errors.New("sku is archived") @@ -230,6 +232,7 @@ type SKUChangeMode int32 const ( SKUChangeModePatchExisting SKUChangeMode = 1 SKUChangeModeReplaceAll SKUChangeMode = 2 + SKUChangeModeSync SKUChangeMode = 3 ) // SKUUpdate contains mutable fields for one existing current SKU. @@ -254,6 +257,13 @@ type SKUChange struct { Mode SKUChangeMode PatchItems []SKUUpdate ReplaceItems []SKURecord + SyncItems []SKUSyncItem +} + +type SKUSyncItem struct { + SKU SKURecord + ExpectedSKUVersion int32 + ExpectedInventoryVersion int32 } // ProductUpdateInput is the atomically persisted product update payload. @@ -1886,6 +1896,14 @@ WHERE id = $1 AND version = $25 AND deleted_at IS NULL AND store_id = $26 if input.SKUChange != nil { result.Mode = input.SKUChange.Mode switch input.SKUChange.Mode { + case SKUChangeModeSync: + ids, err := syncProductSKUs(ctx, tx, productID, input.Product.ID, input.SKUChange.SyncItems) + if err != nil { + return nil, err + } + result.CreatedSKUIds = ids.CreatedSKUIds + result.UpdatedSKUIds = ids.UpdatedSKUIds + result.ArchivedSKUIds = ids.ArchivedSKUIds case SKUChangeModePatchExisting: for _, item := range input.SKUChange.PatchItems { if err := updateCurrentSKU(ctx, tx, productID, item); err != nil { @@ -2586,6 +2604,121 @@ RETURNING id return ids, nil } +// syncProductSKUs reconciles a non-empty complete active SKU snapshot. +func syncProductSKUs(ctx context.Context, tx *sql.Tx, productID int64, productIDText string, items []SKUSyncItem) (*SKUChangeResult, error) { + if len(items) == 0 { + return &SKUChangeResult{}, nil + } + rows, err := tx.QueryContext(ctx, `SELECT pi.id, pi.version, inv.version, inv.stock_quantity, inv.locked_quantity +FROM product.product_items pi JOIN product.product_item_inventory inv ON inv.sku_id = pi.id +WHERE pi.product_id=$1 AND pi.deleted_at IS NULL AND pi.is_archived=FALSE +ORDER BY pi.id FOR UPDATE OF pi, inv`, productID) + if err != nil { + return nil, fmt.Errorf("lock current skus: %w", err) + } + type current struct{ skuVersion, inventoryVersion, stock, locked int32 } + existing := make(map[string]current) + for rows.Next() { + var id int64 + var row current + if err := rows.Scan(&id, &row.skuVersion, &row.inventoryVersion, &row.stock, &row.locked); err != nil { + rows.Close() + return nil, err + } + existing[formatID(id)] = row + } + if err := rows.Err(); err != nil { + rows.Close() + return nil, err + } + rows.Close() + result := &SKUChangeResult{Mode: SKUChangeModeSync} + seen := make(map[string]bool, len(items)) + for _, item := range items { + sku := item.SKU + attrs, err := normalizeAttributesJSON(sku.AttributesJSON) + if err != nil { + return nil, err + } + if seen[sku.ID] { + return nil, fmt.Errorf("duplicate sku_id %s", sku.ID) + } + seen[sku.ID] = true + old, found := existing[sku.ID] + if !found { + if sku.Inventory == nil { + return nil, ErrSKUNotFound + } + created, err := insertSKU(ctx, tx, productIDText, sku) + if err != nil { + return nil, err + } + result.CreatedSKUIds = append(result.CreatedSKUIds, created.ID) + continue + } + if old.skuVersion != item.ExpectedSKUVersion { + return nil, ErrSKUVersionConflict + } + if sku.StockQuantity != old.stock && old.inventoryVersion != item.ExpectedInventoryVersion { + return nil, ErrSKUVersionConflict + } + if sku.StockQuantity < old.locked { + return nil, fmt.Errorf("%w: stock_quantity cannot be less than locked_quantity", ErrInvalidSKUUpdate) + } + id, err := parseID(sku.ID, "sku_id") + if err != nil { + return nil, err + } + var changedID int64 + err = tx.QueryRowContext(ctx, `UPDATE product.product_items SET + sku_no=$3, name=$4, price=$5, supply_price=$6, weight_kg=$7, barcode=$8, + image_ids=$9, attributes=$10::jsonb, status=$11, version=version+1, updated_at=NOW() + WHERE id=$1 AND product_id=$2 AND version=$12 AND is_archived=FALSE AND ( + sku_no IS DISTINCT FROM $3 OR name IS DISTINCT FROM $4 OR price IS DISTINCT FROM $5 OR + supply_price IS DISTINCT FROM $6 OR weight_kg IS DISTINCT FROM $7 OR barcode IS DISTINCT FROM $8 OR + image_ids IS DISTINCT FROM $9 OR attributes IS DISTINCT FROM $10::jsonb OR status IS DISTINCT FROM $11) + RETURNING id`, id, productID, nullString(sku.SKUNo), sku.Name, sku.Price, nullableInt64(sku.SupplyPrice), nullableFloat64(sku.WeightKg), nullString(sku.Barcode), stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status), item.ExpectedSKUVersion).Scan(&changedID) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("update sku %s: %w", sku.ID, err) + } + changed := err == nil + if sku.StockQuantity != old.stock { + res, err := tx.ExecContext(ctx, `UPDATE product.product_item_inventory SET stock_quantity=$2, version=version+1, updated_at=NOW() WHERE sku_id=$1 AND version=$3`, id, sku.StockQuantity, item.ExpectedInventoryVersion) + if err != nil { + return nil, err + } + n, err := res.RowsAffected() + if err != nil { + return nil, err + } + if n != 1 { + return nil, ErrSKUVersionConflict + } + changed = true + } + if changed { + if _, err := tx.ExecContext(ctx, `UPDATE product.product_item_inventory SET sku_no=$2 WHERE sku_id=$1 AND sku_no IS DISTINCT FROM $2`, id, nullString(sku.SKUNo)); err != nil { + return nil, err + } + result.UpdatedSKUIds = append(result.UpdatedSKUIds, sku.ID) + } + } + for id := range existing { + if seen[id] { + continue + } + parsed, err := parseID(id, "sku_id") + if err != nil { + return nil, err + } + if _, err := tx.ExecContext(ctx, `UPDATE product.product_items SET status=0, is_archived=TRUE, archived_at=NOW(), version=version+1, updated_at=NOW() WHERE id=$1 AND product_id=$2 AND is_archived=FALSE`, parsed, productID); err != nil { + return nil, err + } + result.ArchivedSKUIds = append(result.ArchivedSKUIds, id) + } + return result, nil +} + func hasSellableSKU(ctx context.Context, tx *sql.Tx, productID int64) (bool, error) { var exists bool err := tx.QueryRowContext(ctx, ` diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 88afc72..80695a7 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -448,10 +448,19 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } + if len(req.GetSkus()) > 0 && req.GetSkuChange() != nil { + return nil, status.Error(codes.InvalidArgument, "skus and sku_change cannot be sent together") + } skuChange, err := skuChangeFromProto(req.GetSkuChange(), s.idgen) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } + if len(req.GetSkus()) > 0 { + skuChange, err = skuSyncFromProto(req.GetSkus(), s.idgen) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + } if len(req.GetUpdateMask().GetPaths()) == 0 && skuChange == nil { return nil, status.Error(codes.InvalidArgument, "at least one product field or sku_change is required") } @@ -528,6 +537,8 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update return nil, status.Error(codes.FailedPrecondition, err.Error()) case errors.Is(err, repository.ErrSKUNotFound), errors.Is(err, repository.ErrSKUArchived): return nil, status.Error(codes.NotFound, err.Error()) + case errors.Is(err, repository.ErrInvalidSKUUpdate): + return nil, status.Error(codes.InvalidArgument, err.Error()) case errors.Is(err, repository.ErrInvalidLeafCategory): return nil, status.Error(codes.InvalidArgument, err.Error()) case errors.Is(err, repository.ErrInvalidProductGroup): @@ -550,6 +561,45 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update }, nil } +func skuSyncFromProto(items []*productv1.UpdateProductSKU, generator *idgen.Generator) (*repository.SKUChange, error) { + if generator == nil { + return nil, errors.New("id generator is not configured") + } + change := &repository.SKUChange{Mode: repository.SKUChangeModeSync} + seen := make(map[string]bool, len(items)) + seenSpecs := make(map[string]bool, len(items)) + for i, item := range items { + if item == nil { + return nil, fmt.Errorf("skus[%d] is required", i) + } + create := &productv1.CreateProductSKU{SkuNo: item.GetSkuNo(), Name: item.GetName(), Price: item.GetPrice(), SupplyPrice: item.SupplyPrice, WeightKg: item.WeightKg, Barcode: item.GetBarcode(), StockQuantity: item.GetStockQuantity(), Status: item.GetStatus(), K1: item.GetK1(), V1: item.GetV1(), K2: item.GetK2(), V2: item.GetV2(), K3: item.GetK3(), V3: item.GetV3(), ImageIds: item.GetImageIds()} + sku, err := skuFromCreateInput(create) + if err != nil { + return nil, fmt.Errorf("skus[%d]: %w", i, err) + } + if seenSpecs[sku.AttributesJSON] { + return nil, fmt.Errorf("skus[%d] duplicates another specification combination", i) + } + seenSpecs[sku.AttributesJSON] = true + id := strings.TrimSpace(item.GetSkuId()) + if id == "" { + sku.ID = generator.NextString() + sku.Inventory = &repository.InventoryRecord{ID: generator.NextString()} + } else { + if err := validatePositiveID(id, "sku_id"); err != nil { + return nil, err + } + if seen[id] { + return nil, fmt.Errorf("duplicate sku_id %s", id) + } + seen[id] = true + sku.ID = id + } + change.SyncItems = append(change.SyncItems, repository.SKUSyncItem{SKU: sku, ExpectedSKUVersion: item.GetExpectedSkuVersion(), ExpectedInventoryVersion: item.GetExpectedInventoryVersion()}) + } + return change, nil +} + // UpdateProductFreightCharge updates only one product's freight configuration, // locating it by the store-scoped SPU business number. func (s *ProductServer) UpdateProductFreightCharge(ctx context.Context, req *productv1.UpdateProductFreightChargeRequest) (*productv1.UpdateProductFreightChargeResponse, error) { diff --git a/internal/server/product_sku_sync_test.go b/internal/server/product_sku_sync_test.go new file mode 100644 index 0000000..e624bc8 --- /dev/null +++ b/internal/server/product_sku_sync_test.go @@ -0,0 +1,21 @@ +package server + +import ( + productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" + "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/idgen" + "testing" +) + +func TestSkuSyncFromProtoKeepsExistingIdentityAndSpecs(t *testing.T) { + generator, err := idgen.NewFromEnv() + if err != nil { + t.Fatal(err) + } + change, err := skuSyncFromProto([]*productv1.UpdateProductSKU{{SkuId: "2120054989786189824", ExpectedSkuVersion: 1, ExpectedInventoryVersion: 1, Name: "黑12/m12", Price: 0, Status: 1, K1: "口味12", V1: "黑12"}}, generator) + if err != nil { + t.Fatal(err) + } + if len(change.SyncItems) != 1 || change.SyncItems[0].SKU.ID != "2120054989786189824" || change.SyncItems[0].SKU.AttributesJSON == "" { + t.Fatalf("bad sync: %+v", change) + } +}