mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
Merge remote-tracking branch 'origin/dev2' into dev2
This commit is contained in:
commit
1d48010cc1
@ -18,6 +18,9 @@ import (
|
|||||||
// ErrProductNotFound is returned when a product does not exist.
|
// ErrProductNotFound is returned when a product does not exist.
|
||||||
var ErrProductNotFound = errors.New("product not found")
|
var ErrProductNotFound = errors.New("product not found")
|
||||||
|
|
||||||
|
// ErrCategoryNodeNotFound is returned when a category or product group node does not exist.
|
||||||
|
var ErrCategoryNodeNotFound = errors.New("category or group node not found")
|
||||||
|
|
||||||
// ErrSKUNotFound is returned when a SKU does not exist.
|
// ErrSKUNotFound is returned when a SKU does not exist.
|
||||||
var ErrSKUNotFound = errors.New("sku not found")
|
var ErrSKUNotFound = errors.New("sku not found")
|
||||||
|
|
||||||
@ -319,6 +322,168 @@ func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category Cat
|
|||||||
return createdCategory, nil
|
return createdCategory, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AddProductsToGroup binds every product to the requested category or product group in one transaction.
|
||||||
|
// Existing bindings are retained and duplicate bindings are ignored.
|
||||||
|
func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID string, bindingIDs, productIDs []string) error {
|
||||||
|
if len(productIDs) == 0 {
|
||||||
|
return errors.New("product_ids is required")
|
||||||
|
}
|
||||||
|
if len(bindingIDs) != len(productIDs) {
|
||||||
|
return errors.New("binding ids must match product ids")
|
||||||
|
}
|
||||||
|
|
||||||
|
parsedGroupID, err := parseID(groupID, "group_id")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
parsedProductIDs := make([]int64, len(productIDs))
|
||||||
|
parsedBindingIDs := make([]int64, len(bindingIDs))
|
||||||
|
for i := range productIDs {
|
||||||
|
parsedProductIDs[i], err = parseID(productIDs[i], "product_id")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
parsedBindingIDs[i], err = parseID(bindingIDs[i], "category binding id")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tx, err := r.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("begin add products to group: %w", err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
err = tx.QueryRowContext(ctx, `
|
||||||
|
SELECT id
|
||||||
|
FROM product.product_category
|
||||||
|
WHERE id = $1
|
||||||
|
`, parsedGroupID).Scan(&parsedGroupID)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("query category or group node %s: %w", groupID, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
productPlaceholders := make([]string, len(parsedProductIDs))
|
||||||
|
productArgs := make([]any, len(parsedProductIDs))
|
||||||
|
for i, productID := range parsedProductIDs {
|
||||||
|
productPlaceholders[i] = fmt.Sprintf("$%d", i+1)
|
||||||
|
productArgs[i] = productID
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
|
||||||
|
SELECT id
|
||||||
|
FROM product.products
|
||||||
|
WHERE deleted_at IS NULL
|
||||||
|
AND id IN (%s)
|
||||||
|
`, strings.Join(productPlaceholders, ", ")), productArgs...)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("query products for category or group binding: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
foundProducts := make(map[int64]struct{}, len(parsedProductIDs))
|
||||||
|
for rows.Next() {
|
||||||
|
var productID int64
|
||||||
|
if err := rows.Scan(&productID); err != nil {
|
||||||
|
return fmt.Errorf("scan product for category or group binding: %w", err)
|
||||||
|
}
|
||||||
|
foundProducts[productID] = struct{}{}
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return fmt.Errorf("iterate products for category or group binding: %w", err)
|
||||||
|
}
|
||||||
|
if err := rows.Close(); err != nil {
|
||||||
|
return fmt.Errorf("close products for category or group binding: %w", err)
|
||||||
|
}
|
||||||
|
for i, productID := range parsedProductIDs {
|
||||||
|
if _, ok := foundProducts[productID]; !ok {
|
||||||
|
return fmt.Errorf("%w: %s", ErrProductNotFound, productIDs[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
valuePlaceholders := make([]string, len(parsedProductIDs))
|
||||||
|
args := make([]any, 0, len(parsedProductIDs)*3)
|
||||||
|
for i, productID := range parsedProductIDs {
|
||||||
|
base := i * 3
|
||||||
|
valuePlaceholders[i] = fmt.Sprintf("($%d, $%d, $%d)", base+1, base+2, base+3)
|
||||||
|
args = append(args, parsedBindingIDs[i], productID, parsedGroupID)
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, fmt.Sprintf(`
|
||||||
|
INSERT INTO product.product_category_bindings (id, product_id, category_id)
|
||||||
|
VALUES %s
|
||||||
|
ON CONFLICT (product_id, category_id) DO NOTHING
|
||||||
|
`, strings.Join(valuePlaceholders, ", ")), args...)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("insert product category or group bindings: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return fmt.Errorf("commit add products to group: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveProductsFromGroup removes product bindings from the requested category or product group in one transaction.
|
||||||
|
// Missing bindings are ignored so callers can safely retry the same request.
|
||||||
|
func (r *ProductRepository) RemoveProductsFromGroup(ctx context.Context, groupID string, productIDs []string) error {
|
||||||
|
if len(productIDs) == 0 {
|
||||||
|
return errors.New("product_ids is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
parsedGroupID, err := parseID(groupID, "group_id")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
parsedProductIDs := make([]int64, len(productIDs))
|
||||||
|
for i := range productIDs {
|
||||||
|
parsedProductIDs[i], err = parseID(productIDs[i], "product_id")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tx, err := r.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("begin remove products from group: %w", err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
err = tx.QueryRowContext(ctx, `
|
||||||
|
SELECT id
|
||||||
|
FROM product.product_category
|
||||||
|
WHERE id = $1
|
||||||
|
`, parsedGroupID).Scan(&parsedGroupID)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("query category or group node %s: %w", groupID, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
placeholders := make([]string, len(parsedProductIDs))
|
||||||
|
args := make([]any, 0, len(parsedProductIDs)+1)
|
||||||
|
args = append(args, parsedGroupID)
|
||||||
|
for i, productID := range parsedProductIDs {
|
||||||
|
placeholders[i] = fmt.Sprintf("$%d", i+2)
|
||||||
|
args = append(args, productID)
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, fmt.Sprintf(`
|
||||||
|
DELETE FROM product.product_category_bindings
|
||||||
|
WHERE category_id = $1
|
||||||
|
AND product_id IN (%s)
|
||||||
|
`, strings.Join(placeholders, ", ")), args...)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("delete product category or group bindings: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return fmt.Errorf("commit remove products from group: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// UpdateProduct updates mutable SPU fields.
|
// UpdateProduct updates mutable SPU fields.
|
||||||
func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRecord) error {
|
func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRecord) error {
|
||||||
attrs, err := json.Marshal(product.Attrs)
|
attrs, err := json.Marshal(product.Attrs)
|
||||||
|
|||||||
@ -33,8 +33,9 @@ const (
|
|||||||
categoryNodeType = int32(0)
|
categoryNodeType = int32(0)
|
||||||
groupNodeType = int32(1)
|
groupNodeType = int32(1)
|
||||||
|
|
||||||
defaultNodeStatus = int32(1)
|
defaultNodeStatus = int32(1)
|
||||||
maxNodeNameLength = 100
|
maxNodeNameLength = 100
|
||||||
|
maxProductsPerGroupRequest = 100
|
||||||
)
|
)
|
||||||
|
|
||||||
// ProductServer implements productv1.ProductServiceServer.
|
// ProductServer implements productv1.ProductServiceServer.
|
||||||
@ -334,6 +335,84 @@ func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroup
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AddProductsToGroup adds one or more products to a category or product group.
|
||||||
|
func (s *ProductServer) AddProductsToGroup(ctx context.Context, req *productv1.AddProductsToGroupRequest) (*productv1.AddProductsToGroupResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
if s.idgen == nil {
|
||||||
|
return nil, status.Error(codes.Internal, "id generator is not configured")
|
||||||
|
}
|
||||||
|
|
||||||
|
groupID := strings.TrimSpace(req.GetGroupId())
|
||||||
|
if err := validatePositiveSnowflakeID(groupID, "group_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
productIDs, err := normalizeGroupProductIDs(req.GetProductIds())
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
bindingIDs := make([]string, len(productIDs))
|
||||||
|
for i := range productIDs {
|
||||||
|
// Each binding row receives its own Snowflake ID.
|
||||||
|
bindingIDs[i] = s.idgen.NextString()
|
||||||
|
}
|
||||||
|
|
||||||
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.group.add_products", trace.WithAttributes(
|
||||||
|
attribute.String("group.id", groupID),
|
||||||
|
attribute.Int("group.product_count", len(productIDs)),
|
||||||
|
))
|
||||||
|
defer dbSpan.End()
|
||||||
|
|
||||||
|
if err := s.repo.AddProductsToGroup(dbCtx, groupID, bindingIDs, productIDs); err != nil {
|
||||||
|
dbSpan.RecordError(err)
|
||||||
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||||
|
s.observer.Logger(ctx).Error("add products to group failed", zap.String("group_id", groupID), zap.Strings("product_ids", productIDs), zap.Error(err))
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, repository.ErrCategoryNodeNotFound), errors.Is(err, repository.ErrProductNotFound):
|
||||||
|
return nil, status.Error(codes.NotFound, err.Error())
|
||||||
|
default:
|
||||||
|
return nil, status.Errorf(codes.Internal, "add products to group: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &productv1.AddProductsToGroupResponse{Success: true}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveProductsFromGroup removes one or more products from a category or product group.
|
||||||
|
func (s *ProductServer) RemoveProductsFromGroup(ctx context.Context, req *productv1.RemoveProductsFromGroupRequest) (*productv1.RemoveProductsFromGroupResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
groupID := strings.TrimSpace(req.GetGroupId())
|
||||||
|
if err := validatePositiveSnowflakeID(groupID, "group_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
productIDs, err := normalizeGroupProductIDs(req.GetProductIds())
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.group.remove_products", trace.WithAttributes(
|
||||||
|
attribute.String("group.id", groupID),
|
||||||
|
attribute.Int("group.product_count", len(productIDs)),
|
||||||
|
))
|
||||||
|
defer dbSpan.End()
|
||||||
|
|
||||||
|
if err := s.repo.RemoveProductsFromGroup(dbCtx, groupID, productIDs); err != nil {
|
||||||
|
dbSpan.RecordError(err)
|
||||||
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||||
|
s.observer.Logger(ctx).Error("remove products from group failed", zap.String("group_id", groupID), zap.Strings("product_ids", productIDs), zap.Error(err))
|
||||||
|
if errors.Is(err, repository.ErrCategoryNodeNotFound) {
|
||||||
|
return nil, status.Error(codes.NotFound, err.Error())
|
||||||
|
}
|
||||||
|
return nil, status.Errorf(codes.Internal, "remove products from group: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &productv1.RemoveProductsFromGroupResponse{Success: true}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// LockInventory reserves sellable stock for a pending order.
|
// LockInventory reserves sellable stock for a pending order.
|
||||||
func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockInventoryRequest) (*productv1.LockInventoryResponse, error) {
|
func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockInventoryRequest) (*productv1.LockInventoryResponse, error) {
|
||||||
if req == nil || req.GetSkuId() == "" {
|
if req == nil || req.GetSkuId() == "" {
|
||||||
@ -713,6 +792,33 @@ func normalizeStringList(values []string) []string {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func normalizeGroupProductIDs(values []string) ([]string, error) {
|
||||||
|
productIDs := normalizeStringList(values)
|
||||||
|
if len(productIDs) == 0 {
|
||||||
|
return nil, errors.New("product_ids is required")
|
||||||
|
}
|
||||||
|
if len(productIDs) > maxProductsPerGroupRequest {
|
||||||
|
return nil, fmt.Errorf("product_ids must contain at most %d items", maxProductsPerGroupRequest)
|
||||||
|
}
|
||||||
|
for _, productID := range productIDs {
|
||||||
|
if err := validatePositiveSnowflakeID(productID, "product_id"); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return productIDs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validatePositiveSnowflakeID(raw, field string) error {
|
||||||
|
if strings.TrimSpace(raw) == "" {
|
||||||
|
return fmt.Errorf("%s is required", field)
|
||||||
|
}
|
||||||
|
id, err := strconv.ParseInt(raw, 10, 64)
|
||||||
|
if err != nil || id <= 0 {
|
||||||
|
return fmt.Errorf("%s must be a positive snowflake id", field)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func defaultInt32(value, fallback int32) int32 {
|
func defaultInt32(value, fallback int32) int32 {
|
||||||
if value == 0 {
|
if value == 0 {
|
||||||
return fallback
|
return fallback
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user