mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
feat: implement product group update and delete functionalities
This commit is contained in:
parent
f28df52a12
commit
cdc47d888f
@ -876,6 +876,101 @@ WHERE category_id IN (%s)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GroupDeleteResult summarizes a destructive product-group deletion.
|
||||
type GroupDeleteResult struct {
|
||||
DeletedGroupID string
|
||||
UnboundProductCount int64
|
||||
UnboundBindingCount int64
|
||||
}
|
||||
|
||||
// UpdateGroup applies a field patch to one product group (node_type=2).
|
||||
func (r *ProductRepository) UpdateGroup(ctx context.Context, update CategoryFieldUpdate, scope StoreScope) (*CategoryRecord, error) {
|
||||
if err := requireWriteScope(scope); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if update.ExpectedVersion < 0 {
|
||||
return nil, errors.New("expected_version must be non-negative")
|
||||
}
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin update group: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
current, err := loadCategoryForUpdate(ctx, tx, update.ID, scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if current.NodeType != 2 {
|
||||
return nil, ErrInvalidProductGroup
|
||||
}
|
||||
if current.Version != update.ExpectedVersion {
|
||||
return nil, ErrCategoryVersionConflict
|
||||
}
|
||||
updated, err := updateCategoryFields(ctx, tx, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, fmt.Errorf("commit update group: %w", err)
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
// DeleteGroup hard-deletes one product group and its bindings. Products are retained.
|
||||
func (r *ProductRepository) DeleteGroup(ctx context.Context, groupID string, expectedVersion int32, scope StoreScope) (*GroupDeleteResult, error) {
|
||||
if err := requireWriteScope(scope); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if expectedVersion < 0 {
|
||||
return nil, errors.New("expected_version must be non-negative")
|
||||
}
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin delete group: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
target, err := loadCategoryForUpdate(ctx, tx, groupID, scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if target.NodeType != 2 {
|
||||
return nil, ErrInvalidProductGroup
|
||||
}
|
||||
if target.Version != expectedVersion {
|
||||
return nil, ErrCategoryVersionConflict
|
||||
}
|
||||
targetID, err := parseID(target.ID, "group_id")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &GroupDeleteResult{DeletedGroupID: target.ID}
|
||||
if err := tx.QueryRowContext(ctx, `
|
||||
SELECT COUNT(DISTINCT product_id), COUNT(*)
|
||||
FROM product.product_catalog_bindings
|
||||
WHERE category_id = $1
|
||||
`, targetID).Scan(&result.UnboundProductCount, &result.UnboundBindingCount); err != nil {
|
||||
return nil, fmt.Errorf("count group bindings for delete: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM product.product_catalog_bindings
|
||||
WHERE category_id = $1
|
||||
`, targetID); err != nil {
|
||||
return nil, fmt.Errorf("delete group bindings: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM product.catalog_category
|
||||
WHERE id = $1 AND store_id = $2 AND node_type = 2
|
||||
`, targetID, scope.StoreID); err != nil {
|
||||
return nil, fmt.Errorf("delete group: %w", err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, fmt.Errorf("commit delete group: %w", err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func loadCategoryForUpdate(ctx context.Context, tx *sql.Tx, categoryID string, scope StoreScope) (*CategoryRecord, error) {
|
||||
id, err := parseID(categoryID, "category_id")
|
||||
if err != nil {
|
||||
|
||||
@ -1181,6 +1181,86 @@ func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGr
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UpdateGroup updates mutable fields on one product group.
|
||||
func (s *ProductServer) UpdateGroup(ctx context.Context, req *productv1.UpdateGroupRequest) (*productv1.UpdateGroupResponse, error) {
|
||||
if req == nil {
|
||||
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||
}
|
||||
scope, err := requireStoreScope(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
groupID, err := normalizeCategoryID(req.GetGroupId(), "group_id")
|
||||
if 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")
|
||||
}
|
||||
update, err := groupFieldUpdateFromRequest(req)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.group.update", trace.WithAttributes(attribute.String("group.id", groupID)))
|
||||
defer dbSpan.End()
|
||||
updated, err := s.repo.UpdateGroup(dbCtx, *update, scope)
|
||||
if err != nil {
|
||||
dbSpan.RecordError(err)
|
||||
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||
switch {
|
||||
case errors.Is(err, repository.ErrCategoryNodeNotFound), errors.Is(err, repository.ErrInvalidProductGroup):
|
||||
return nil, status.Error(codes.NotFound, "group not found")
|
||||
case errors.Is(err, repository.ErrCategoryVersionConflict):
|
||||
return nil, status.Error(codes.Aborted, "group version conflict")
|
||||
case errors.Is(err, repository.ErrGroupNameExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "group name already exists")
|
||||
default:
|
||||
s.observer.Logger(ctx).Error("update group failed", zap.String("group_id", groupID), zap.Error(err))
|
||||
return nil, status.Errorf(codes.Internal, "update group: %v", err)
|
||||
}
|
||||
}
|
||||
return &productv1.UpdateGroupResponse{Group: toProtoGroupNode(updated)}, nil
|
||||
}
|
||||
|
||||
// DeleteGroup hard-deletes one product group and its bindings.
|
||||
func (s *ProductServer) DeleteGroup(ctx context.Context, req *productv1.DeleteGroupRequest) (*productv1.DeleteGroupResponse, error) {
|
||||
if req == nil {
|
||||
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||
}
|
||||
scope, err := requireStoreScope(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
groupID, err := normalizeCategoryID(req.GetGroupId(), "group_id")
|
||||
if 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")
|
||||
}
|
||||
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.group.delete", trace.WithAttributes(attribute.String("group.id", groupID)))
|
||||
defer dbSpan.End()
|
||||
result, err := s.repo.DeleteGroup(dbCtx, groupID, req.GetExpectedVersion(), scope)
|
||||
if err != nil {
|
||||
dbSpan.RecordError(err)
|
||||
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||
switch {
|
||||
case errors.Is(err, repository.ErrCategoryNodeNotFound), errors.Is(err, repository.ErrInvalidProductGroup):
|
||||
return nil, status.Error(codes.NotFound, "group not found")
|
||||
case errors.Is(err, repository.ErrCategoryVersionConflict):
|
||||
return nil, status.Error(codes.Aborted, "group version conflict")
|
||||
default:
|
||||
s.observer.Logger(ctx).Error("delete group failed", zap.String("group_id", groupID), zap.Error(err))
|
||||
return nil, status.Error(codes.Internal, "delete group")
|
||||
}
|
||||
}
|
||||
return &productv1.DeleteGroupResponse{
|
||||
DeletedGroupId: result.DeletedGroupID,
|
||||
UnboundProductCount: result.UnboundProductCount,
|
||||
UnboundBindingCount: result.UnboundBindingCount,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListGroups returns product groups.
|
||||
func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroupsRequest) (*productv1.ListGroupsResponse, error) {
|
||||
scope, err := requireStoreScope(req)
|
||||
@ -1731,6 +1811,78 @@ func groupFromCreateRequest(req *productv1.CreateGroupRequest) (repository.Categ
|
||||
}, nil
|
||||
}
|
||||
|
||||
func groupFieldUpdateFromRequest(req *productv1.UpdateGroupRequest) (*repository.CategoryFieldUpdate, error) {
|
||||
if req.GetUpdateMask() == nil || len(req.GetUpdateMask().GetPaths()) == 0 {
|
||||
return nil, errors.New("update_mask is required")
|
||||
}
|
||||
update := &repository.CategoryFieldUpdate{
|
||||
ID: strings.TrimSpace(req.GetGroupId()),
|
||||
ExpectedVersion: req.GetExpectedVersion(),
|
||||
}
|
||||
seen := make(map[string]struct{}, len(req.GetUpdateMask().GetPaths()))
|
||||
for _, path := range req.GetUpdateMask().GetPaths() {
|
||||
path = strings.TrimSpace(path)
|
||||
if path == "" {
|
||||
continue
|
||||
}
|
||||
if _, dup := seen[path]; dup {
|
||||
return nil, fmt.Errorf("duplicate update path %q", path)
|
||||
}
|
||||
seen[path] = struct{}{}
|
||||
switch path {
|
||||
case "name":
|
||||
if req.Name == nil {
|
||||
return nil, errors.New("name is required when present in update_mask")
|
||||
}
|
||||
value, err := normalizeNodeName(*req.Name, "name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
update.Name = &value
|
||||
case "image_json", "image_ids":
|
||||
raw := ""
|
||||
if req.ImageJson != nil {
|
||||
raw = *req.ImageJson
|
||||
}
|
||||
imageIDs, err := normalizeNodeImageIDs(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
update.ImageIDs = &imageIDs
|
||||
case "sort_num":
|
||||
if req.SortNum == nil {
|
||||
return nil, errors.New("sort_num is required when present in update_mask")
|
||||
}
|
||||
update.SortNum = req.SortNum
|
||||
case "status":
|
||||
if req.Status == nil {
|
||||
return nil, errors.New("status is required when present in update_mask")
|
||||
}
|
||||
if *req.Status != 0 && *req.Status != 1 {
|
||||
return nil, errors.New("status must be 0 or 1")
|
||||
}
|
||||
update.Status = req.Status
|
||||
case "campaign_id":
|
||||
value := ""
|
||||
if req.CampaignId != nil {
|
||||
value = strings.TrimSpace(*req.CampaignId)
|
||||
}
|
||||
if value != "" {
|
||||
if _, err := normalizeCategoryID(value, "campaign_id"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
update.CampaignID = &value
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported update path %q", path)
|
||||
}
|
||||
}
|
||||
if update.Name == nil && update.ImageIDs == nil && update.SortNum == nil && update.Status == nil && update.CampaignID == nil {
|
||||
return nil, errors.New("at least one mutable field is required")
|
||||
}
|
||||
return update, nil
|
||||
}
|
||||
|
||||
func normalizeNodeName(raw, field string) (string, error) {
|
||||
name := strings.Join(strings.Fields(raw), " ")
|
||||
if name == "" {
|
||||
@ -2554,6 +2706,7 @@ func toProtoGroupNode(group *repository.CategoryRecord) *productv1.GroupNode {
|
||||
Status: group.Status,
|
||||
ProductCount: group.ProductCount,
|
||||
CampaignId: group.CampaignID,
|
||||
Version: group.Version,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user