mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
feat: enhance product creation error handling and validation for brand and supplier references
This commit is contained in:
parent
47539d663d
commit
0a58b5e332
@ -23,6 +23,10 @@ var (
|
||||
ErrSupplierHasActiveBrands = errors.New("supplier has active brands")
|
||||
ErrBrandInUse = errors.New("brand is referenced by products")
|
||||
ErrSupplierInactive = errors.New("supplier must be enabled")
|
||||
// Keep the historical client-visible message for an inactive brand while
|
||||
// retaining a distinct sentinel so the Admin API can point at brand_id.
|
||||
ErrBrandInactive = errors.New("supplier must be enabled")
|
||||
ErrBrandSupplierMismatch = errors.New("brand does not belong to supplier")
|
||||
)
|
||||
|
||||
type SupplierAttachmentRecord struct {
|
||||
@ -442,13 +446,13 @@ func (r *ProductRepository) ValidateProductMasterRefs(ctx context.Context, suppl
|
||||
return err
|
||||
}
|
||||
if brandStatus != 1 {
|
||||
return ErrSupplierInactive
|
||||
return ErrBrandInactive
|
||||
}
|
||||
if err := r.ensureEnabledSupplier(ctx, brandSupplierID, scope); err != nil {
|
||||
return err
|
||||
}
|
||||
if supplierID != "" && supplierID != brandSupplierID {
|
||||
return errors.New("brand does not belong to supplier")
|
||||
return ErrBrandSupplierMismatch
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -491,7 +491,7 @@ func catalogGRPCError(err error) error {
|
||||
return status.Error(codes.Aborted, err.Error())
|
||||
case errors.Is(err, repository.ErrDuplicateSupplierCode), errors.Is(err, repository.ErrDuplicateBrandCode):
|
||||
return status.Error(codes.AlreadyExists, err.Error())
|
||||
case errors.Is(err, repository.ErrSupplierHasBrands), errors.Is(err, repository.ErrSupplierHasActiveBrands), errors.Is(err, repository.ErrBrandInUse), errors.Is(err, repository.ErrSupplierInactive):
|
||||
case errors.Is(err, repository.ErrSupplierHasBrands), errors.Is(err, repository.ErrSupplierHasActiveBrands), errors.Is(err, repository.ErrBrandInUse), errors.Is(err, repository.ErrSupplierInactive), errors.Is(err, repository.ErrBrandInactive), errors.Is(err, repository.ErrBrandSupplierMismatch):
|
||||
return status.Error(codes.FailedPrecondition, err.Error())
|
||||
case errors.Is(err, repository.ErrStoreScopeRequired):
|
||||
return status.Error(codes.InvalidArgument, err.Error())
|
||||
|
||||
82
internal/server/product_create_errors.go
Normal file
82
internal/server/product_create_errors.go
Normal file
@ -0,0 +1,82 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||
)
|
||||
|
||||
// productCreateError preserves the existing gRPC code and message, while
|
||||
// attaching the field that failed validation for callers that understand the
|
||||
// standard google.rpc.BadRequest detail.
|
||||
func productCreateError(code codes.Code, message, field string) error {
|
||||
if field == "" {
|
||||
return status.Error(code, message)
|
||||
}
|
||||
grpcStatus := status.New(code, message)
|
||||
withDetails, err := grpcStatus.WithDetails(&errdetails.BadRequest{
|
||||
FieldViolations: []*errdetails.BadRequest_FieldViolation{{
|
||||
Field: field,
|
||||
Description: message,
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
return grpcStatus.Err()
|
||||
}
|
||||
return withDetails.Err()
|
||||
}
|
||||
|
||||
func productMasterReferenceField(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, repository.ErrBrandNotFound),
|
||||
errors.Is(err, repository.ErrBrandInactive),
|
||||
errors.Is(err, repository.ErrBrandSupplierMismatch):
|
||||
return "brand_id"
|
||||
case errors.Is(err, repository.ErrSupplierNotFound),
|
||||
errors.Is(err, repository.ErrSupplierInactive):
|
||||
return "supplier_id"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func productCreateFieldFromMessage(message string) string {
|
||||
if strings.HasPrefix(message, "skus[") {
|
||||
separator := strings.Index(message, ":")
|
||||
if separator > 0 {
|
||||
prefix := message[:separator]
|
||||
detail := strings.TrimSpace(message[separator+1:])
|
||||
for _, field := range []string{"supply_price", "weight_kg", "stock_quantity", "price", "status", "k1", "v1", "k2", "v2", "k3", "v3"} {
|
||||
if strings.HasPrefix(detail, field) || strings.Contains(detail, field+"/") {
|
||||
return prefix + "." + field
|
||||
}
|
||||
}
|
||||
return prefix
|
||||
}
|
||||
}
|
||||
if message == "request is required" {
|
||||
return "$"
|
||||
}
|
||||
if message == "unsupported product status" {
|
||||
return "status"
|
||||
}
|
||||
if strings.HasPrefix(message, "on-sale product") {
|
||||
return "skus"
|
||||
}
|
||||
for _, field := range []string{
|
||||
"title", "detail_html", "leaf_catalog_category_ids", "group_ids", "product_category_ids",
|
||||
"freight_fixed_amount", "goods_type", "freight_charge_type", "freight_template_id",
|
||||
"sale_time_type", "scheduled_sale_time", "presale_type", "purchase_limit_quantity",
|
||||
"delivery_time_type", "delivery_start_at", "delivery_after_paid_days", "cross_border_info",
|
||||
} {
|
||||
if strings.HasPrefix(message, field) {
|
||||
return field
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
43
internal/server/product_create_errors_test.go
Normal file
43
internal/server/product_create_errors_test.go
Normal file
@ -0,0 +1,43 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestProductCreateErrorIncludesFieldViolation(t *testing.T) {
|
||||
err := productCreateError(codes.InvalidArgument, "price must be greater than or equal to 0", "skus[0].price")
|
||||
grpcStatus := status.Convert(err)
|
||||
if grpcStatus.Code() != codes.InvalidArgument || grpcStatus.Message() != "price must be greater than or equal to 0" {
|
||||
t.Fatalf("status = (%s, %q)", grpcStatus.Code(), grpcStatus.Message())
|
||||
}
|
||||
details := grpcStatus.Details()
|
||||
if len(details) != 1 {
|
||||
t.Fatalf("details count = %d, want 1", len(details))
|
||||
}
|
||||
badRequest, ok := details[0].(*errdetails.BadRequest)
|
||||
if !ok || len(badRequest.GetFieldViolations()) != 1 {
|
||||
t.Fatalf("details = %#v", details)
|
||||
}
|
||||
violation := badRequest.GetFieldViolations()[0]
|
||||
if violation.GetField() != "skus[0].price" || violation.GetDescription() != grpcStatus.Message() {
|
||||
t.Fatalf("violation = %#v", violation)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProductCreateFieldFromMessage(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"title is required": "title",
|
||||
"skus[2]: price must be greater than or equal to 0": "skus[2].price",
|
||||
"cross_border_info.logistics_mode is invalid": "cross_border_info",
|
||||
"delivery_start_at is required when delivery_time_type is 1": "delivery_start_at",
|
||||
}
|
||||
for message, want := range tests {
|
||||
if got := productCreateFieldFromMessage(message); got != want {
|
||||
t.Errorf("productCreateFieldFromMessage(%q) = %q, want %q", message, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -76,7 +76,7 @@ func NewProductServer(repo *repository.ProductRepository, idGenerator *idgen.Gen
|
||||
// CreateProduct creates a product SPU and optional SKU list.
|
||||
func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.CreateProductRequest) (*productv1.CreateProductResponse, error) {
|
||||
if req == nil {
|
||||
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||
return nil, productCreateError(codes.InvalidArgument, "request is required", "$")
|
||||
}
|
||||
scope, err := requireStoreScope(req)
|
||||
if err != nil {
|
||||
@ -85,16 +85,17 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create
|
||||
|
||||
product, skus, err := productFromCreateRequest(req)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
return nil, productCreateError(codes.InvalidArgument, err.Error(), productCreateFieldFromMessage(err.Error()))
|
||||
}
|
||||
product.Scope = scope
|
||||
if err := s.repo.ValidateProductMasterRefs(ctx, product.SupplierID, product.BrandID, scope); err != nil {
|
||||
return nil, catalogGRPCError(err)
|
||||
catalogErr := catalogGRPCError(err)
|
||||
return nil, productCreateError(status.Code(catalogErr), status.Convert(catalogErr).Message(), productMasterReferenceField(err))
|
||||
}
|
||||
if product.FreightChargeType == 2 {
|
||||
if err := s.repo.FreightTemplateExists(ctx, product.FreightTemplateID, scope); err != nil {
|
||||
if errors.Is(err, repository.ErrFreightTemplateNotFound) {
|
||||
return nil, status.Error(codes.InvalidArgument, "freight_template_id not found or disabled")
|
||||
return nil, productCreateError(codes.InvalidArgument, "freight_template_id not found or disabled", "freight_template_id")
|
||||
}
|
||||
return nil, status.Errorf(codes.Internal, "validate freight template: %v", err)
|
||||
}
|
||||
@ -129,16 +130,16 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create
|
||||
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||
s.observer.Logger(ctx).Error("create product failed", zap.String("spu_no", product.SPUNo), zap.Error(err))
|
||||
if errors.Is(err, repository.ErrDuplicateSPUNo) {
|
||||
return nil, status.Errorf(codes.AlreadyExists, "spu_no already exists: %s", product.SPUNo)
|
||||
return nil, productCreateError(codes.AlreadyExists, fmt.Sprintf("spu_no already exists: %s", product.SPUNo), "spu_no")
|
||||
}
|
||||
if errors.Is(err, repository.ErrInvalidLeafCategory) {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
return nil, productCreateError(codes.InvalidArgument, err.Error(), "leaf_catalog_category_ids")
|
||||
}
|
||||
if errors.Is(err, repository.ErrInvalidProductGroup) {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
return nil, productCreateError(codes.InvalidArgument, err.Error(), "group_ids")
|
||||
}
|
||||
if errors.Is(err, repository.ErrInvalidProductCategory) {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
return nil, productCreateError(codes.InvalidArgument, err.Error(), "product_category_ids")
|
||||
}
|
||||
return nil, status.Errorf(codes.Internal, "create product: %v", err)
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user