package server import ( "context" "encoding/json" "errors" "fmt" "math" "sort" "strconv" "strings" "time" "unicode/utf8" "go.opentelemetry.io/otel/attribute" otelcodes "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/types/known/fieldmaskpb" "google.golang.org/protobuf/types/known/timestamppb" productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/idgen" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/observability" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" ) const ( defaultPageSize = int32(20) maxPageSize = int32(100) categoryNodeType = int32(1) groupNodeType = int32(2) defaultNodeStatus = int32(1) maxNodeNameLength = 100 maxProductsPerGroupRequest = 100 maxCartItemProductBatchSize = 100 maxSearchKeywordLength = 50 maxProductTitleLength = 200 ) // ProductServer implements productv1.ProductServiceServer. type ProductServer struct { productv1.UnimplementedProductServiceServer productv1.UnimplementedProductCategoryServiceServer repo *repository.ProductRepository idgen *idgen.Generator logger *zap.Logger observer *observability.Observer } // NewProductServer constructs the gRPC product service handler. func NewProductServer(repo *repository.ProductRepository, idGenerator *idgen.Generator, logger *zap.Logger, observer *observability.Observer) *ProductServer { if logger == nil { logger = zap.NewNop() } if observer == nil { observer = observability.NewNoop(logger) } return &ProductServer{ repo: repo, idgen: idGenerator, logger: logger, observer: observer, } } // 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") } scope, err := requireStoreScope(req) if err != nil { return nil, err } product, skus, err := productFromCreateRequest(req) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } product.Scope = scope if err := s.repo.ValidateProductMasterRefs(ctx, product.SupplierID, product.BrandID, scope); err != nil { return nil, catalogGRPCError(err) } if s.idgen == nil { return nil, status.Error(codes.Internal, "id generator is not configured") } product.ID = s.idgen.NextString() for i := range skus { skus[i].ID = s.idgen.NextString() skus[i].Inventory = &repository.InventoryRecord{ID: s.idgen.NextString()} } for range product.LeafCategoryIDs { product.CategoryBindingIDs = append(product.CategoryBindingIDs, s.idgen.NextString()) } for range product.GroupIDs { product.GroupBindingIDs = append(product.GroupBindingIDs, s.idgen.NextString()) } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes( attribute.String("product.spu_no", product.SPUNo), attribute.Int("product.sku_count", len(skus)), )) defer dbSpan.End() createdProduct, _, err := s.repo.CreateProductWithSKUs(dbCtx, product, skus) if err != nil { dbSpan.RecordError(err) 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) } if errors.Is(err, repository.ErrInvalidLeafCategory) { return nil, status.Error(codes.InvalidArgument, err.Error()) } if errors.Is(err, repository.ErrInvalidProductGroup) { return nil, status.Error(codes.InvalidArgument, err.Error()) } return nil, status.Errorf(codes.Internal, "create product: %v", err) } observability.IncProductsCreated() itemID, err := strconv.ParseInt(createdProduct.ID, 10, 64) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("parse created product id failed", zap.String("product_id", createdProduct.ID), zap.Error(err)) return nil, status.Errorf(codes.Internal, "parse created product id: %v", err) } return &productv1.CreateProductResponse{ Data: &productv1.CreateProductData{ ItemId: itemID, Title: createdProduct.Title, }, Success: true, Code: 0, Message: "success", }, nil } // GetProduct returns a single SPU and its SKU list. func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProductRequest) (*productv1.GetProductResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } if req.GetProductId() == "" { return nil, status.Error(codes.InvalidArgument, "product_id is required") } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.load", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) defer dbSpan.End() product, skus, err := s.repo.GetProduct(dbCtx, req.GetProductId(), scope) if errors.Is(err, repository.ErrProductNotFound) { dbSpan.SetStatus(otelcodes.Error, "product not found") return nil, status.Error(codes.NotFound, "product not found") } if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("get product failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) return nil, status.Errorf(codes.Internal, "get product: %v", err) } return &productv1.GetProductResponse{ Product: toProtoProduct(product, skus), }, nil } // ListProductSKUs returns the compact current-SKU stock projection for one SPU. func (s *ProductServer) ListProductSKUs(ctx context.Context, req *productv1.ListProductSKUsRequest) (*productv1.ListProductSKUsResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } if err := validatePositiveID(req.GetProductId(), "product_id"); err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.sku.list", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) defer dbSpan.End() skus, err := s.repo.ListProductSKUStocks(dbCtx, req.GetProductId(), scope) if errors.Is(err, repository.ErrProductNotFound) { dbSpan.SetStatus(otelcodes.Error, "product not found") return nil, status.Error(codes.NotFound, "product not found") } if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("list product skus failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) return nil, status.Errorf(codes.Internal, "list product skus: %v", err) } result := make([]*productv1.ProductSKUStock, 0, len(skus)) for _, sku := range skus { result = append(result, &productv1.ProductSKUStock{ Id: sku.ID, Name: sku.Name, StockQuantity: sku.StockQuantity, SupplyPrice: sku.SupplyPrice, }) } return &productv1.ListProductSKUsResponse{ Skus: result, Total: int32(len(result)), }, nil } // GetProductBySku returns the SPU that owns the SKU. func (s *ProductServer) GetProductBySku(ctx context.Context, req *productv1.GetProductBySkuRequest) (*productv1.GetProductResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } if req.GetSkuId() == "" { return nil, status.Error(codes.InvalidArgument, "sku_id is required") } if err := validatePositiveID(req.GetSkuId(), "sku_id"); err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.load_by_sku", trace.WithAttributes(attribute.String("sku.id", req.GetSkuId()))) defer dbSpan.End() product, skus, err := s.repo.GetProductBySKU(dbCtx, req.GetSkuId(), scope) if errors.Is(err, repository.ErrSKUNotFound) { dbSpan.SetStatus(otelcodes.Error, "sku not found") return nil, status.Error(codes.NotFound, "sku not found") } if errors.Is(err, repository.ErrProductNotFound) { dbSpan.SetStatus(otelcodes.Error, "product not found") return nil, status.Error(codes.NotFound, "product not found") } if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("get product by sku failed", zap.String("sku_id", req.GetSkuId()), zap.Error(err)) return nil, status.Errorf(codes.Internal, "get product by sku: %v", err) } return &productv1.GetProductResponse{ Product: toProtoProduct(product, skus), }, nil } // BatchGetCartItemProduct returns current SPU/SKU facts for cart rows in request order. // Missing and soft-deleted records are represented by their default invalid state rather // than failing the whole batch; malformed requests still return InvalidArgument. func (s *ProductServer) BatchGetCartItemProduct(ctx context.Context, req *productv1.BatchGetCartItemProductRequest) (*productv1.BatchGetCartItemProductResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } if req == nil || len(req.GetItems()) == 0 { return nil, status.Error(codes.InvalidArgument, "items is required") } if len(req.GetItems()) > maxCartItemProductBatchSize { return nil, status.Errorf(codes.InvalidArgument, "items must contain at most %d entries", maxCartItemProductBatchSize) } lookups := make([]repository.CartItemProductLookup, 0, len(req.GetItems())) lineIDs := make(map[string]struct{}, len(req.GetItems())) for index, item := range req.GetItems() { if item == nil { return nil, status.Errorf(codes.InvalidArgument, "items[%d] is required", index) } if err := validatePositiveID(item.GetLineId(), "line_id"); err != nil { return nil, status.Errorf(codes.InvalidArgument, "items[%d]: %v", index, err) } if _, exists := lineIDs[item.GetLineId()]; exists { return nil, status.Errorf(codes.InvalidArgument, "items[%d]: duplicate line_id", index) } lineIDs[item.GetLineId()] = struct{}{} if err := validatePositiveID(item.GetProductId(), "product_id"); err != nil { return nil, status.Errorf(codes.InvalidArgument, "items[%d]: %v", index, err) } if err := validatePositiveID(item.GetSkuId(), "sku_id"); err != nil { return nil, status.Errorf(codes.InvalidArgument, "items[%d]: %v", index, err) } if item.GetQuantity() <= 0 { return nil, status.Errorf(codes.InvalidArgument, "items[%d]: quantity must be positive", index) } lookups = append(lookups, repository.CartItemProductLookup{ ProductID: item.GetProductId(), SKUID: item.GetSkuId(), }) } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.cart_item.batch_get", trace.WithAttributes( attribute.Int("product.cart_item_count", len(lookups)), )) defer dbSpan.End() records, err := s.repo.BatchGetCartItemProducts(dbCtx, lookups, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("batch get cart item products failed", zap.Error(err)) return nil, status.Errorf(codes.Internal, "batch get cart item products: %v", err) } if len(records) != len(req.GetItems()) { err := fmt.Errorf("repository returned %d records for %d lookups", len(records), len(req.GetItems())) dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("batch get cart item products incomplete", zap.Error(err)) return nil, status.Error(codes.Internal, "batch get cart item products returned incomplete data") } items := make([]*productv1.CartItemProduct, 0, len(records)) for index, record := range records { items = append(items, toProtoCartItemProduct(req.GetItems()[index].GetLineId(), record)) } return &productv1.BatchGetCartItemProductResponse{Items: items}, nil } // UpdateProduct updates mutable SPU fields and optionally patches or replaces its SKU set. func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.UpdateProductRequest) (*productv1.UpdateProductResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } if req.GetProductId() == "" { return nil, status.Error(codes.InvalidArgument, "product_id is required") } if req.GetExpectedVersion() < 0 { return nil, status.Error(codes.InvalidArgument, "expected_version must be non-negative") } current, _, err := s.repo.GetProduct(ctx, req.GetProductId(), scope) if errors.Is(err, repository.ErrProductNotFound) { return nil, status.Error(codes.NotFound, "product not found") } if err != nil { s.observer.Logger(ctx).Error("load product for update failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) return nil, status.Errorf(codes.Internal, "load product for update: %v", err) } merged, err := mergeProductUpdate(current, req.GetProduct(), req.GetUpdateMask().GetPaths()) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } skuChange, err := skuChangeFromProto(req.GetSkuChange(), 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") } if err := validateProductForUpdate(merged); err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } if err := s.repo.ValidateProductMasterRefs(ctx, merged.SupplierID, merged.BrandID, scope); err != nil { return nil, catalogGRPCError(err) } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.update", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) defer dbSpan.End() var leafCategoryIDs *[]string var categoryBindingIDs []string var groupIDs *[]string var groupBindingIDs []string if containsUpdatePath(req.GetUpdateMask().GetPaths(), "leaf_catalog_category_ids") { leafCategoryIDs = &merged.LeafCategoryIDs if s.idgen == nil { return nil, status.Error(codes.Internal, "id generator is not configured") } for range merged.LeafCategoryIDs { categoryBindingIDs = append(categoryBindingIDs, s.idgen.NextString()) } } if containsUpdatePath(req.GetUpdateMask().GetPaths(), "group_ids") { groupIDs = &merged.GroupIDs if s.idgen == nil { return nil, status.Error(codes.Internal, "id generator is not configured") } for range merged.GroupIDs { groupBindingIDs = append(groupBindingIDs, s.idgen.NextString()) } } result, err := s.repo.UpdateProductWithSKUChange(dbCtx, repository.ProductUpdateInput{ Product: merged, ExpectedVersion: req.GetExpectedVersion(), SKUChange: skuChange, LeafCategoryIDs: leafCategoryIDs, CategoryBindingIDs: categoryBindingIDs, GroupIDs: groupIDs, GroupBindingIDs: groupBindingIDs, Scope: scope, }) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) switch { case errors.Is(err, repository.ErrProductNotFound): return nil, status.Error(codes.NotFound, "product not found") case errors.Is(err, repository.ErrProductVersionConflict), errors.Is(err, repository.ErrSKUVersionConflict): return nil, status.Error(codes.Aborted, "product or sku version conflict") case errors.Is(err, repository.ErrSKUReplacementRequiresNotOnSale): 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.ErrInvalidLeafCategory): return nil, status.Error(codes.InvalidArgument, err.Error()) case errors.Is(err, repository.ErrInvalidProductGroup): return nil, status.Error(codes.InvalidArgument, err.Error()) default: s.observer.Logger(ctx).Error("update product failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) return nil, status.Errorf(codes.Internal, "update product: %v", err) } } updated, skus, err := s.repo.GetProduct(ctx, req.GetProductId(), scope) if err != nil { return nil, status.Errorf(codes.Internal, "load updated product: %v", err) } return &productv1.UpdateProductResponse{ Product: toProtoProduct(updated, skus), SkuChangeResult: toProtoSKUChangeResult(result), }, nil } // UpdateProductStatus changes the product lifecycle status. func (s *ProductServer) UpdateProductStatus(ctx context.Context, req *productv1.UpdateProductStatusRequest) (*productv1.UpdateProductStatusResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } if req.GetProductId() == "" { return nil, status.Error(codes.InvalidArgument, "product_id is required") } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.status.update", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) defer dbSpan.End() updated, err := s.repo.UpdateProductStatus(dbCtx, req.GetProductId(), req.GetStatus(), req.GetExpectedVersion(), scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) switch { case errors.Is(err, repository.ErrProductNotFound): return nil, status.Error(codes.NotFound, "product not found") case errors.Is(err, repository.ErrProductVersionConflict): return nil, status.Error(codes.Aborted, "product version conflict") default: return nil, status.Error(codes.InvalidArgument, err.Error()) } } return &productv1.UpdateProductStatusResponse{ ProductId: updated.ProductID, PreviousStatus: updated.PreviousStatus, Status: updated.Status, Version: updated.Version, UpdatedAt: timeToMillisString(updated.UpdatedAt), }, nil } // TransferProductStore moves a product to another store without changing tenant. func (s *ProductServer) TransferProductStore(ctx context.Context, req *productv1.TransferProductStoreRequest) (*productv1.TransferProductStoreResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } if req.GetProductId() == "" { return nil, status.Error(codes.InvalidArgument, "product_id is required") } targetStoreID, err := parsePositiveID(strings.TrimSpace(req.GetTargetStoreId()), "target_store_id") if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.store.transfer", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) defer dbSpan.End() updated, err := s.repo.TransferProductStore(dbCtx, req.GetProductId(), targetStoreID, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) switch { case errors.Is(err, repository.ErrProductNotFound): return nil, status.Error(codes.NotFound, "product not found") case errors.Is(err, repository.ErrSameStore): return nil, status.Error(codes.InvalidArgument, "target store is the current store") case errors.Is(err, repository.ErrDuplicateSPUNo), errors.Is(err, repository.ErrDuplicateSKUNo): return nil, status.Error(codes.AlreadyExists, err.Error()) default: s.observer.Logger(ctx).Error("transfer product store failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) return nil, status.Errorf(codes.Internal, "transfer product store: %v", err) } } return &productv1.TransferProductStoreResponse{ ProductId: updated.ProductID, TenantId: strconv.FormatInt(updated.TenantID, 10), StoreId: strconv.FormatInt(updated.StoreID, 10), }, nil } // CopyProductToStore creates a new target-store product instead of moving the // source record. Source product, SKU, inventory, and material records remain // untouched. Material IDs must already have been copied by ids-svc-storage. func (s *ProductServer) CopyProductToStore(ctx context.Context, req *productv1.CopyProductToStoreRequest) (*productv1.CopyProductToStoreResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } if err := validatePositiveID(req.GetSourceProductId(), "source_product_id"); err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } targetStoreID, err := parsePositiveID(strings.TrimSpace(req.GetTargetStoreId()), "target_store_id") if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } if targetStoreID == scope.StoreID { return nil, status.Error(codes.InvalidArgument, "target store is the current store") } if s.idgen == nil { return nil, status.Error(codes.Internal, "id generator is not configured") } source, sourceSKUs, err := s.repo.GetProduct(ctx, req.GetSourceProductId(), scope) if errors.Is(err, repository.ErrProductNotFound) { return nil, status.Error(codes.NotFound, "source product not found") } if err != nil { return nil, status.Errorf(codes.Internal, "load source product: %v", err) } mappings, err := productCopyMaterialMap(source, sourceSKUs, req.GetMaterialIdMappings()) if err != nil { return nil, status.Error(codes.FailedPrecondition, err.Error()) } targetScope := repository.StoreScope{TenantID: scope.TenantID, StoreID: targetStoreID} target := *source target.ID = s.idgen.NextString() target.Scope = targetScope target.Status = productv1.ProductStatus_PRODUCT_STATUS_INVENTORY target.BrandID = "" target.SupplierID = "" target.ImageIDs = remapProductCopyImageIDs(source.ImageIDs, mappings) target.LeafCategoryIDs = nil target.CategoryBindingIDs = nil target.GroupIDs = nil target.GroupBindingIDs = nil target.Version = 0 target.DeletedAt = nil target.CreatedAt = time.Time{} target.UpdatedAt = time.Time{} targetSKUs := make([]repository.SKURecord, 0, len(sourceSKUs)) for _, sourceSKU := range sourceSKUs { targetSKU := sourceSKU targetSKU.ID = s.idgen.NextString() targetSKU.ProductID = target.ID targetSKU.ImageIDs = remapProductCopyImageIDs(sourceSKU.ImageIDs, mappings) targetSKU.StockQuantity = 0 targetSKU.LockedQuantity = 0 targetSKU.SoldQuantity = 0 targetSKU.Version = 0 targetSKU.DeletedAt = nil targetSKU.IsArchived = false targetSKU.ArchivedAt = nil targetSKU.CreatedAt = time.Time{} targetSKU.UpdatedAt = time.Time{} targetSKU.Inventory = &repository.InventoryRecord{ID: s.idgen.NextString()} targetSKUs = append(targetSKUs, targetSKU) } created, _, err := s.repo.CreateProductWithSKUs(ctx, target, targetSKUs) if err != nil { if errors.Is(err, repository.ErrDuplicateSPUNo) || errors.Is(err, repository.ErrDuplicateSKUNo) { return nil, status.Error(codes.AlreadyExists, err.Error()) } return nil, status.Errorf(codes.Internal, "copy product to target store: %v", err) } return &productv1.CopyProductToStoreResponse{ SourceProductId: req.GetSourceProductId(), TargetProductId: created.ID, TenantId: strconv.FormatInt(scope.TenantID, 10), TargetStoreId: strconv.FormatInt(targetStoreID, 10), }, nil } func productCopyMaterialMap(product *repository.ProductRecord, skus []repository.SKURecord, mappings []*productv1.MaterialIDMapping) (map[string]string, error) { required := make(map[string]struct{}) if product != nil { for _, imageID := range product.ImageIDs { required[imageID] = struct{}{} } } for _, sku := range skus { for _, imageID := range sku.ImageIDs { required[imageID] = struct{}{} } } resolved := make(map[string]string, len(mappings)) for _, mapping := range mappings { if mapping == nil || strings.TrimSpace(mapping.GetSourceMaterialId()) == "" || strings.TrimSpace(mapping.GetTargetMaterialId()) == "" { return nil, fmt.Errorf("material_id_mappings must contain source and target IDs") } if _, err := parsePositiveID(mapping.GetSourceMaterialId(), "source_material_id"); err != nil { return nil, err } if _, err := parsePositiveID(mapping.GetTargetMaterialId(), "target_material_id"); err != nil { return nil, err } if _, exists := resolved[mapping.GetSourceMaterialId()]; exists { return nil, fmt.Errorf("material_id_mappings contains duplicate source_material_id") } resolved[mapping.GetSourceMaterialId()] = mapping.GetTargetMaterialId() } if len(required) != len(resolved) { return nil, fmt.Errorf("material_id_mappings must exactly cover source product images") } for sourceID := range required { if _, ok := resolved[sourceID]; !ok { return nil, fmt.Errorf("material_id_mappings is missing source material %s", sourceID) } } return resolved, nil } func remapProductCopyImageIDs(imageIDs []string, mappings map[string]string) []string { result := make([]string, 0, len(imageIDs)) for _, imageID := range imageIDs { result = append(result, mappings[imageID]) } return result } // ListProducts returns a paginated list of all non-deleted products. func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListProductsRequest) (*productv1.ListProductsResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize()) filter, err := productListFilterFromRequest(req) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list", trace.WithAttributes( attribute.Int("page", int(page)), attribute.Int("page_size", int(pageSize)), )) defer dbSpan.End() if filter.GroupID != "" { if err := s.repo.ValidateProductGroup(dbCtx, filter.GroupID, scope); err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) if errors.Is(err, repository.ErrInvalidProductGroup) { return nil, status.Error(codes.InvalidArgument, err.Error()) } s.observer.Logger(ctx).Error("validate product group filter failed", zap.String("group_id", filter.GroupID), zap.Error(err)) return nil, status.Errorf(codes.Internal, "validate product group filter: %v", err) } } products, total, err := s.repo.ListProducts(dbCtx, page, pageSize, filter, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("list products failed", zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err)) return nil, status.Errorf(codes.Internal, "list products: %v", err) } dbSpan.SetAttributes(attribute.Int64("product.total", total), attribute.Int("product.result_count", len(products))) observability.IncProductLists() protoProducts := make([]*productv1.CategoryProduct, 0, len(products)) for _, product := range products { protoProducts = append(protoProducts, toProtoCategoryProduct(product)) } return &productv1.ListProductsResponse{ Products: protoProducts, Page: page, PageSize: pageSize, Total: total, TotalPages: totalPages(total, pageSize), }, nil } func productListFilterFromRequest(req *productv1.ListProductsRequest) (repository.ProductListFilter, error) { if req == nil { return repository.ProductListFilter{}, errors.New("request is required") } filter := repository.ProductListFilter{ TitleKeyword: strings.TrimSpace(req.GetTitleKeyword()), SPUNo: strings.TrimSpace(req.GetSpuNo()), GroupID: strings.TrimSpace(req.GetGroupId()), } if utf8.RuneCountInString(filter.TitleKeyword) > maxProductTitleLength { return repository.ProductListFilter{}, fmt.Errorf("title_keyword must contain at most %d characters", maxProductTitleLength) } if utf8.RuneCountInString(filter.SPUNo) > 100 { return repository.ProductListFilter{}, errors.New("spu_no must contain at most 100 characters") } if filter.GroupID != "" { if err := validatePositiveID(filter.GroupID, "group_id"); err != nil { return repository.ProductListFilter{}, err } } if req.CreatedAtFrom != nil { value := req.GetCreatedAtFrom() if value < 0 { return repository.ProductListFilter{}, errors.New("created_at_from must be greater than or equal to 0") } createdAtFrom := time.UnixMilli(value) filter.CreatedAtFrom = &createdAtFrom } if req.CreatedAtTo != nil { value := req.GetCreatedAtTo() if value < 0 { return repository.ProductListFilter{}, errors.New("created_at_to must be greater than or equal to 0") } createdAtTo := time.UnixMilli(value) filter.CreatedAtTo = &createdAtTo } if filter.CreatedAtFrom != nil && filter.CreatedAtTo != nil && filter.CreatedAtFrom.After(*filter.CreatedAtTo) { return repository.ProductListFilter{}, errors.New("created_at_from must be less than or equal to created_at_to") } if req.GoodsType != nil { goodsType := req.GetGoodsType() if goodsType < 1 || goodsType > 4 { return repository.ProductListFilter{}, errors.New("goods_type must be between 1 and 4") } filter.GoodsType = &goodsType } if req.SoldQuantityMin != nil { value := req.GetSoldQuantityMin() if value < 0 { return repository.ProductListFilter{}, errors.New("sold_quantity_min must be greater than or equal to 0") } filter.SoldQuantityMin = &value } if req.SoldQuantityMax != nil { value := req.GetSoldQuantityMax() if value < 0 { return repository.ProductListFilter{}, errors.New("sold_quantity_max must be greater than or equal to 0") } filter.SoldQuantityMax = &value } if filter.SoldQuantityMin != nil && filter.SoldQuantityMax != nil && *filter.SoldQuantityMin > *filter.SoldQuantityMax { return repository.ProductListFilter{}, errors.New("sold_quantity_min must be less than or equal to sold_quantity_max") } if req.PriceMin != nil { value := req.GetPriceMin() if value < 0 { return repository.ProductListFilter{}, errors.New("price_min must be greater than or equal to 0") } filter.PriceMin = &value } if req.PriceMax != nil { value := req.GetPriceMax() if value < 0 { return repository.ProductListFilter{}, errors.New("price_max must be greater than or equal to 0") } filter.PriceMax = &value } if filter.PriceMin != nil && filter.PriceMax != nil && *filter.PriceMin > *filter.PriceMax { return repository.ProductListFilter{}, errors.New("price_min must be less than or equal to price_max") } return filter, nil } // SearchProducts returns storefront-visible products whose titles contain the // supplied keyword. Visibility is enforced inside the repository and cannot be // relaxed by callers. func (s *ProductServer) SearchProducts(ctx context.Context, req *productv1.SearchProductsRequest) (*productv1.ListCategoryProductsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } scope, err := requireStoreScope(req) if err != nil { return nil, err } keyword := strings.TrimSpace(req.GetKeyword()) keywordLength := utf8.RuneCountInString(keyword) if keyword == "" || keywordLength > maxSearchKeywordLength { return nil, status.Errorf(codes.InvalidArgument, "keyword must contain between 1 and %d characters", maxSearchKeywordLength) } page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize()) dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.search", trace.WithAttributes( attribute.Int("keyword.length", keywordLength), attribute.Int("page", int(page)), attribute.Int("page_size", int(pageSize)), )) defer dbSpan.End() products, total, err := s.repo.SearchProducts(dbCtx, keyword, page, pageSize, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("search products failed", zap.Int("keyword_length", keywordLength), zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err)) return nil, status.Errorf(codes.Internal, "search products: %v", err) } dbSpan.SetAttributes(attribute.Int64("product.total", total), attribute.Int("product.result_count", len(products))) observability.IncProductSearches() protoProducts := make([]*productv1.CategoryProduct, 0, len(products)) for _, product := range products { protoProducts = append(protoProducts, toProtoCategoryProduct(product)) } return &productv1.ListCategoryProductsResponse{ Products: protoProducts, Page: page, PageSize: pageSize, Total: total, TotalPages: totalPages(total, pageSize), }, nil } // ListCategoryProducts returns a paginated product list under a category. func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1.ListCategoryProductsRequest) (*productv1.ListCategoryProductsResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } if req.GetCategoryId() == "" { return nil, status.Error(codes.InvalidArgument, "category_id is required") } categoryID, err := strconv.ParseInt(req.GetCategoryId(), 10, 64) if err != nil || categoryID <= 0 { return nil, status.Error(codes.InvalidArgument, "category_id must be a positive snowflake id") } targetNodeType := req.GetTargetNodeType() if targetNodeType == 0 { targetNodeType = 1 } if targetNodeType != 1 && targetNodeType != 2 { return nil, status.Error(codes.InvalidArgument, "target_node_type must be category (1) or group (2)") } page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize()) dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_by_category", trace.WithAttributes( attribute.String("category.id", req.GetCategoryId()), attribute.Int("category.node_type", int(targetNodeType)), attribute.Int("page", int(page)), attribute.Int("page_size", int(pageSize)), )) defer dbSpan.End() products, productIDs, total, err := s.repo.ListCategoryProducts(dbCtx, req.GetCategoryId(), page, pageSize, req.GetOnlyVisible(), targetNodeType, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("list category products failed", zap.String("category_id", req.GetCategoryId()), zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err)) return nil, status.Errorf(codes.Internal, "list category products: %v", err) } dbSpan.SetAttributes(attribute.Int64("product.total", total), attribute.Int("product.result_count", len(products))) observability.IncCategoryProductLists() protoProducts := make([]*productv1.CategoryProduct, 0, len(products)) for _, product := range products { protoProducts = append(protoProducts, toProtoCategoryProduct(product)) } return &productv1.ListCategoryProductsResponse{ Products: protoProducts, Page: page, PageSize: pageSize, Total: total, TotalPages: totalPages(total, pageSize), ProductIds: productIDs, }, nil } func normalizedPage(page, pageSize int32) (int32, int32) { if page <= 0 { page = 1 } if pageSize <= 0 { pageSize = defaultPageSize } if pageSize > maxPageSize { pageSize = maxPageSize } return page, pageSize } // CountProducts returns product counts grouped by lifecycle status. func (s *ProductServer) CountProducts(ctx context.Context, req *productv1.CountProductsRequest) (*productv1.CountProductsResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.count") defer dbSpan.End() counts, err := s.repo.CountProducts(dbCtx, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("count products failed", zap.Error(err)) return nil, status.Errorf(codes.Internal, "count products: %v", err) } return &productv1.CountProductsResponse{ Total: counts.Total, Active: counts.Active, Draft: counts.Draft, OnSale: counts.OnSale, OffSale: counts.OffSale, Deleted: counts.Deleted, }, nil } // ListCategoryTree returns product category nodes as a parent-child hierarchy. func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.ListCategoryTreeRequest) (*productv1.ListCategoryTreeResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } onlyVisible := false if req != nil { onlyVisible = req.GetOnlyVisible() } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_category_tree", trace.WithAttributes( attribute.Bool("category.only_visible", onlyVisible), )) defer dbSpan.End() categories, err := s.repo.ListCategoryTreeNodes(dbCtx, onlyVisible, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("list category tree failed", zap.Bool("only_visible", onlyVisible), zap.Error(err)) return nil, status.Errorf(codes.Internal, "list category tree: %v", err) } dbSpan.SetAttributes(attribute.Int("category.result_count", len(categories))) observability.IncCategoryTreeLists() resp := &productv1.ListCategoryTreeResponse{ Categories: buildCategoryTree(categories), } if payload, marshalErr := (protojson.MarshalOptions{UseProtoNames: true, EmitUnpopulated: true}).Marshal(resp); marshalErr != nil { s.observer.Logger(ctx).Warn("marshal category tree response for logging failed", zap.Error(marshalErr)) } else { s.observer.Logger(ctx).Info("list category tree response", zap.ByteString("response", payload)) } return resp, nil } // CreateCategoryTree creates a top-level category and optional second-level categories. func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.CreateCategoryTreeRequest) (*productv1.CreateCategoryTreeResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } scope, err := requireStoreScope(req) if err != nil { return nil, err } if s.idgen == nil { return nil, status.Error(codes.Internal, "id generator is not configured") } parent, children, err := categoryTreeFromCreateRequest(req) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } parent.ID = s.idgen.NextString() for i := range children { children[i].ID = s.idgen.NextString() } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create_category_tree", trace.WithAttributes( attribute.String("category.name", parent.Name), attribute.Int("category.child_count", len(children)), )) defer dbSpan.End() createdParent, createdChildren, err := s.repo.CreateCategoryTree(dbCtx, parent, children, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) if errors.Is(err, repository.ErrCategoryNameExists) { return nil, status.Error(codes.AlreadyExists, "category name already exists") } s.observer.Logger(ctx).Error("create category tree failed", zap.String("category_name", parent.Name), zap.Error(err)) return nil, status.Errorf(codes.Internal, "create category tree: %v", err) } category := toProtoCategoryNode(createdParent) for _, child := range createdChildren { category.Children = append(category.Children, toProtoCategoryNode(child)) } return &productv1.CreateCategoryTreeResponse{ Category: category, }, nil } // UpdateCategoryTrees atomically updates one or more top-level category trees. func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1.UpdateCategoryTreesRequest) (*productv1.UpdateCategoryTreesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } scope, err := requireStoreScope(req) if err != nil { return nil, err } updates, rootIDs, err := categoryTreeUpdatesFromRequest(req) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } for updateIndex := range updates { for childIndex := range updates[updateIndex].NewChildren { if s.idgen == nil { return nil, status.Error(codes.Internal, "id generator is not configured") } updates[updateIndex].NewChildren[childIndex].ID = s.idgen.NextString() } } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category_trees.update", trace.WithAttributes(attribute.Int("category.tree_count", len(updates)))) defer dbSpan.End() if err := s.repo.UpdateCategoryTrees(dbCtx, updates, scope); err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) switch { case errors.Is(err, repository.ErrCategoryNodeNotFound): return nil, status.Error(codes.NotFound, "category not found") case errors.Is(err, repository.ErrCategoryNameExists): return nil, status.Error(codes.AlreadyExists, "category name already exists") case errors.Is(err, repository.ErrCategoryVersionConflict): return nil, status.Error(codes.Aborted, "category version conflict") case errors.Is(err, repository.ErrCategoryTreeConflict): return nil, status.Error(codes.FailedPrecondition, "child category does not belong to the specified top-level category") default: s.observer.Logger(ctx).Error("update category trees failed", zap.Error(err)) return nil, status.Error(codes.Internal, "update category trees") } } all, err := s.repo.ListCategoryTreeNodes(dbCtx, false, scope) if err != nil { return nil, status.Error(codes.Internal, "load updated category trees") } rootsByID := make(map[string]*productv1.CategoryNode) for _, root := range buildCategoryTree(all) { rootsByID[root.GetCategoryId()] = root } categories := make([]*productv1.CategoryNode, 0, len(rootIDs)) for _, rootID := range rootIDs { root := rootsByID[rootID] if root == nil { return nil, status.Error(codes.Internal, "updated category tree is missing") } categories = append(categories, root) } return &productv1.UpdateCategoryTreesResponse{Categories: categories}, nil } // DeleteCategory removes a single second-level category or a full top-level // category tree. It never deletes products themselves. func (s *ProductServer) DeleteCategory(ctx context.Context, req *productv1.DeleteCategoryRequest) (*productv1.DeleteCategoryResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } scope, err := requireStoreScope(req) if err != nil { return nil, err } categoryID, err := normalizeCategoryID(req.GetCategoryId(), "category_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.category.delete", trace.WithAttributes(attribute.String("category.id", categoryID))) defer dbSpan.End() result, err := s.repo.DeleteCategory(dbCtx, categoryID, req.GetExpectedVersion(), scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) switch { case errors.Is(err, repository.ErrCategoryNodeNotFound): return nil, status.Error(codes.NotFound, "category not found") case errors.Is(err, repository.ErrCategoryVersionConflict): return nil, status.Error(codes.Aborted, "category version conflict") case errors.Is(err, repository.ErrCategoryTreeConflict): return nil, status.Error(codes.FailedPrecondition, "target is not a deletable product category") default: s.observer.Logger(ctx).Error("delete category failed", zap.String("category_id", categoryID), zap.Error(err)) return nil, status.Error(codes.Internal, "delete category") } } return &productv1.DeleteCategoryResponse{ DeletedCategoryId: result.DeletedCategoryID, DeletedLevel: result.DeletedLevel, DeletedCategoryCount: result.DeletedCategoryCount, UnboundProductCount: result.UnboundProductCount, UnboundBindingCount: result.UnboundBindingCount, }, nil } // CreateGroup creates a top-level product group. func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGroupRequest) (*productv1.CreateGroupResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } scope, err := requireStoreScope(req) if err != nil { return nil, err } if s.idgen == nil { return nil, status.Error(codes.Internal, "id generator is not configured") } group, err := groupFromCreateRequest(req) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } group.ID = s.idgen.NextString() dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create_group", trace.WithAttributes( attribute.String("group.name", group.Name), )) defer dbSpan.End() createdGroup, err := s.repo.CreateCategoryNode(dbCtx, group, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) if errors.Is(err, repository.ErrGroupNameExists) { return nil, status.Error(codes.AlreadyExists, "group name already exists") } s.observer.Logger(ctx).Error("create group failed", zap.String("group_name", group.Name), zap.Error(err)) return nil, status.Errorf(codes.Internal, "create group: %v", err) } return &productv1.CreateGroupResponse{ Group: toProtoGroupNode(createdGroup), }, nil } // ListGroups returns product groups. func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroupsRequest) (*productv1.ListGroupsResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } onlyVisible := false if req != nil { onlyVisible = req.GetOnlyVisible() } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_groups", trace.WithAttributes( attribute.Bool("group.only_visible", onlyVisible), )) defer dbSpan.End() groups, err := s.repo.ListGroupNodes(dbCtx, onlyVisible, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("list groups failed", zap.Bool("only_visible", onlyVisible), zap.Error(err)) return nil, status.Errorf(codes.Internal, "list groups: %v", err) } dbSpan.SetAttributes(attribute.Int("group.result_count", len(groups))) protoGroups := make([]*productv1.GroupNode, 0, len(groups)) for _, group := range groups { protoGroups = append(protoGroups, toProtoGroupNode(group)) } return &productv1.ListGroupsResponse{ Groups: protoGroups, }, nil } // AddProductsToGroup adds one or more products to either a product group or a // second-level category. Exactly one target id is accepted. 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") } scope, err := requireStoreScope(req) if err != nil { return nil, err } if s.idgen == nil { return nil, status.Error(codes.Internal, "id generator is not configured") } groupID := strings.TrimSpace(req.GetGroupId()) categoryID := strings.TrimSpace(req.GetCategoryId()) if (groupID == "" && categoryID == "") || (groupID != "" && categoryID != "") { return nil, status.Error(codes.InvalidArgument, "exactly one of group_id or category_id is required") } targetType := "group" targetID := groupID targetField := "group_id" if categoryID != "" { targetType = "category" targetID = categoryID targetField = "category_id" } if err := validatePositiveSnowflakeID(targetID, targetField); 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.category_binding.add_products", trace.WithAttributes( attribute.String("binding.target_type", targetType), attribute.String("binding.target_id", targetID), attribute.Int("binding.product_count", len(productIDs)), )) defer dbSpan.End() if categoryID != "" { err = s.repo.AddProductsToCategory(dbCtx, targetID, bindingIDs, productIDs, scope) } else { err = s.repo.AddProductsToGroup(dbCtx, targetID, bindingIDs, productIDs, scope) } if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("add products to binding target failed", zap.String("target_type", targetType), zap.String("target_id", targetID), 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 %s: %v", targetType, 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") } scope, err := requireStoreScope(req) if err != nil { return nil, err } 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, scope); 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. func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockInventoryRequest) (*productv1.LockInventoryResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } if req.GetSkuId() == "" { return nil, status.Error(codes.InvalidArgument, "sku_id is required") } if req.GetQuantity() <= 0 { return nil, status.Error(codes.InvalidArgument, "quantity must be positive") } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.lock_inventory", trace.WithAttributes( attribute.String("sku.id", req.GetSkuId()), attribute.Int("inventory.quantity", int(req.GetQuantity())), attribute.String("order.id", req.GetOrderId()), )) defer dbSpan.End() inventory, err := s.repo.LockInventory(dbCtx, req.GetSkuId(), req.GetQuantity(), scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) switch { case errors.Is(err, repository.ErrSKUNotFound): return nil, status.Error(codes.NotFound, "sku inventory not found") case errors.Is(err, repository.ErrProductNotOnSale): return nil, status.Error(codes.FailedPrecondition, "product is not on sale") case errors.Is(err, repository.ErrInsufficientStock): return nil, status.Error(codes.FailedPrecondition, "insufficient stock") default: s.observer.Logger(ctx).Error("lock inventory failed", zap.String("sku_id", req.GetSkuId()), zap.Int32("quantity", req.GetQuantity()), zap.String("order_id", req.GetOrderId()), zap.Error(err), ) return nil, status.Errorf(codes.Internal, "lock inventory: %v", err) } } return &productv1.LockInventoryResponse{ Inventory: toProtoInventory(inventory), }, nil } // ConfirmInventory converts locked stock into sold stock for a paid order. func (s *ProductServer) ConfirmInventory(ctx context.Context, req *productv1.ConfirmInventoryRequest) (*productv1.ConfirmInventoryResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } if req.GetOrderId() == "" { return nil, status.Error(codes.InvalidArgument, "order_id is required") } items, err := toRepositoryInventoryAdjustments(req.GetItems()) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.confirm_inventory", trace.WithAttributes( attribute.String("order.id", req.GetOrderId()), attribute.Int("inventory.items", len(items)), )) defer dbSpan.End() inventories, err := s.repo.ConfirmInventory(dbCtx, req.GetOrderId(), items, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) return nil, mapInventoryAdjustmentError(ctx, s, "confirm", err) } return &productv1.ConfirmInventoryResponse{Inventories: toProtoInventories(inventories)}, nil } // ReleaseInventory releases locked stock for an unpaid closed order. func (s *ProductServer) ReleaseInventory(ctx context.Context, req *productv1.ReleaseInventoryRequest) (*productv1.ReleaseInventoryResponse, error) { scope, err := requireStoreScope(req) if err != nil { return nil, err } if req.GetOrderId() == "" { return nil, status.Error(codes.InvalidArgument, "order_id is required") } items, err := toRepositoryInventoryAdjustments(req.GetItems()) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.release_inventory", trace.WithAttributes( attribute.String("order.id", req.GetOrderId()), attribute.Int("inventory.items", len(items)), )) defer dbSpan.End() inventories, err := s.repo.ReleaseInventory(dbCtx, req.GetOrderId(), items, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) return nil, mapInventoryAdjustmentError(ctx, s, "release", err) } return &productv1.ReleaseInventoryResponse{Inventories: toProtoInventories(inventories)}, nil } func toRepositoryInventoryAdjustments(items []*productv1.InventoryAdjustmentItem) ([]repository.InventoryAdjustment, error) { if len(items) == 0 { return nil, errors.New("items are required") } out := make([]repository.InventoryAdjustment, 0, len(items)) for i, item := range items { if item == nil { return nil, fmt.Errorf("items[%d] is required", i) } if item.GetSkuId() == "" { return nil, fmt.Errorf("items[%d].sku_id is required", i) } if item.GetQuantity() <= 0 { return nil, fmt.Errorf("items[%d].quantity must be positive", i) } out = append(out, repository.InventoryAdjustment{ SKUID: item.GetSkuId(), Quantity: item.GetQuantity(), }) } return out, nil } func mapInventoryAdjustmentError(ctx context.Context, s *ProductServer, action string, err error) error { switch { case errors.Is(err, repository.ErrSKUNotFound): return status.Error(codes.NotFound, "sku inventory not found") case errors.Is(err, repository.ErrInsufficientLockedStock): return status.Error(codes.FailedPrecondition, "insufficient locked stock") case errors.Is(err, repository.ErrInventoryAdjustmentConflict): return status.Error(codes.FailedPrecondition, "inventory adjustment conflict") default: s.observer.Logger(ctx).Error(action+" inventory failed", zap.Error(err)) return status.Errorf(codes.Internal, "%s inventory: %v", action, err) } } func totalPages(total int64, pageSize int32) int32 { if total <= 0 || pageSize <= 0 { return 0 } pages := (total + int64(pageSize) - 1) / int64(pageSize) if pages > math.MaxInt32 { return math.MaxInt32 } return int32(pages) } func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (repository.CategoryRecord, []repository.CategoryRecord, error) { name, err := normalizeNodeName(req.GetName(), "name") if err != nil { return repository.CategoryRecord{}, nil, err } imageIDs, err := normalizeNodeImageIDs(req.GetImageJson()) if err != nil { return repository.CategoryRecord{}, nil, err } statusValue, err := normalizeNodeStatus(req.Status) if err != nil { return repository.CategoryRecord{}, nil, err } parent := repository.CategoryRecord{ NodeType: categoryNodeType, Name: name, Level: 1, ImageIDs: imageIDs, SortNum: req.GetSortNum(), Status: statusValue, CampaignID: req.GetCampaignId(), } children := make([]repository.CategoryRecord, 0, len(req.GetChildren())) childNames := make(map[string]struct{}, len(req.GetChildren())) for _, child := range req.GetChildren() { if child == nil { return repository.CategoryRecord{}, nil, errors.New("children item is required") } childName, err := normalizeNodeName(child.GetName(), "children.name") if err != nil { return repository.CategoryRecord{}, nil, err } if _, exists := childNames[normalizedNodeNameKey(childName)]; exists { return repository.CategoryRecord{}, nil, errors.New("children.name must be unique") } childNames[normalizedNodeNameKey(childName)] = struct{}{} childImageIDs, err := normalizeNodeImageIDs(child.GetImageJson()) if err != nil { return repository.CategoryRecord{}, nil, err } childStatus, err := normalizeNodeStatus(child.Status) if err != nil { return repository.CategoryRecord{}, nil, err } children = append(children, repository.CategoryRecord{ NodeType: categoryNodeType, Name: childName, Level: 2, ImageIDs: childImageIDs, SortNum: child.GetSortNum(), Status: childStatus, CampaignID: child.GetCampaignId(), }) } return parent, children, nil } func categoryTreeUpdatesFromRequest(req *productv1.UpdateCategoryTreesRequest) ([]repository.CategoryTreeUpdate, []string, error) { if len(req.GetCategoryTrees()) == 0 { return nil, nil, errors.New("category_trees is required") } updates := make([]repository.CategoryTreeUpdate, 0, len(req.GetCategoryTrees())) rootIDs := make([]string, 0, len(req.GetCategoryTrees())) seenRoots := make(map[string]struct{}, len(req.GetCategoryTrees())) seenChildren := make(map[string]struct{}) for _, tree := range req.GetCategoryTrees() { if tree == nil { return nil, nil, errors.New("category_trees item is required") } rootID, err := normalizeCategoryID(tree.GetCategoryId(), "category_trees.category_id") if err != nil { return nil, nil, err } if _, exists := seenRoots[rootID]; exists { return nil, nil, errors.New("category_trees.category_id must be unique") } seenRoots[rootID] = struct{}{} update := repository.CategoryTreeUpdate{CategoryID: rootID} if tree.GetCategory() != nil { patch, err := categoryFieldUpdateFromProto(rootID, tree.GetCategory(), "category") if err != nil { return nil, nil, err } update.Category = patch } for _, child := range tree.GetChildCategories() { if child == nil { return nil, nil, errors.New("child_categories item is required") } childID, err := normalizeCategoryID(child.GetCategoryId(), "child_categories.category_id") if err != nil { return nil, nil, err } if _, exists := seenChildren[childID]; exists { return nil, nil, errors.New("child category_id must not appear more than once") } seenChildren[childID] = struct{}{} patch, err := categoryFieldUpdateFromProto(childID, child.GetPatch(), "child_categories.patch") if err != nil { return nil, nil, err } update.Children = append(update.Children, *patch) } newChildNames := make(map[string]struct{}, len(tree.GetNewChildCategories())) for _, child := range tree.GetNewChildCategories() { if child == nil { return nil, nil, errors.New("new_child_categories item is required") } newChild, err := newChildCategoryFromProto(child) if err != nil { return nil, nil, err } if _, exists := newChildNames[normalizedNodeNameKey(newChild.Name)]; exists { return nil, nil, errors.New("new_child_categories.name must be unique") } newChildNames[normalizedNodeNameKey(newChild.Name)] = struct{}{} update.NewChildren = append(update.NewChildren, newChild) } if update.Category == nil && len(update.Children) == 0 && len(update.NewChildren) == 0 { return nil, nil, errors.New("category tree patch must update category or child_categories") } sort.Slice(update.Children, func(i, j int) bool { return update.Children[i].ID < update.Children[j].ID }) updates = append(updates, update) rootIDs = append(rootIDs, rootID) } // A stable lock order avoids deadlocks when two edits overlap roots. sort.Slice(updates, func(i, j int) bool { return updates[i].CategoryID < updates[j].CategoryID }) return updates, rootIDs, nil } func newChildCategoryFromProto(child *productv1.CreateChildCategory) (repository.CategoryRecord, error) { name, err := normalizeNodeName(child.GetName(), "new_child_categories.name") if err != nil { return repository.CategoryRecord{}, err } imageIDs, err := normalizeNodeImageIDs(child.GetImageJson()) if err != nil { return repository.CategoryRecord{}, err } statusValue, err := normalizeNodeStatus(child.Status) if err != nil { return repository.CategoryRecord{}, err } return repository.CategoryRecord{ NodeType: categoryNodeType, Name: name, ImageIDs: imageIDs, SortNum: child.GetSortNum(), Status: statusValue, CampaignID: child.GetCampaignId(), }, nil } func categoryFieldUpdateFromProto(id string, patch *productv1.CategoryFieldPatch, field string) (*repository.CategoryFieldUpdate, error) { if patch == nil { return nil, fmt.Errorf("%s is required", field) } paths, err := categoryUpdatePaths(patch.GetUpdateMask()) if err != nil { return nil, fmt.Errorf("%s: %w", field, err) } if patch.GetExpectedVersion() < 0 { return nil, fmt.Errorf("%s.expected_version must be non-negative", field) } update := &repository.CategoryFieldUpdate{ID: id, ExpectedVersion: patch.GetExpectedVersion()} for _, path := range paths { switch path { case "name": value, err := normalizeNodeName(patch.GetName(), field+".name") if err != nil { return nil, err } update.Name = &value case "image_ids": value := normalizeStringList(patch.GetImageIds()) update.ImageIDs = &value case "sort_num": value := patch.GetSortNum() update.SortNum = &value case "status": value := patch.GetStatus() if value != 0 && value != 1 { return nil, fmt.Errorf("%s.status must be 0 or 1", field) } update.Status = &value case "campaign_id": value := strings.TrimSpace(patch.GetCampaignId()) if value != "" { if _, err := normalizeCategoryID(value, field+".campaign_id"); err != nil { return nil, err } } update.CampaignID = &value } } return update, nil } func categoryUpdatePaths(mask *fieldmaskpb.FieldMask) ([]string, error) { if mask == nil || len(mask.GetPaths()) == 0 { return nil, errors.New("update_mask is required") } allowed := map[string]struct{}{"name": {}, "image_ids": {}, "sort_num": {}, "status": {}, "campaign_id": {}} paths := make([]string, 0, len(mask.GetPaths())) seen := make(map[string]struct{}, len(mask.GetPaths())) for _, path := range mask.GetPaths() { if _, ok := allowed[path]; !ok { return nil, fmt.Errorf("unsupported update path %q", path) } if _, duplicate := seen[path]; duplicate { return nil, fmt.Errorf("duplicate update path %q", path) } seen[path] = struct{}{} paths = append(paths, path) } return paths, nil } func normalizeCategoryID(value, field string) (string, error) { trimmed := strings.TrimSpace(value) id, err := strconv.ParseInt(trimmed, 10, 64) if err != nil || id <= 0 { return "", fmt.Errorf("%s must be a positive snowflake id", field) } return trimmed, nil } func groupFromCreateRequest(req *productv1.CreateGroupRequest) (repository.CategoryRecord, error) { name, err := normalizeNodeName(req.GetName(), "name") if err != nil { return repository.CategoryRecord{}, err } imageIDs, err := normalizeNodeImageIDs(req.GetImageJson()) if err != nil { return repository.CategoryRecord{}, err } statusValue, err := normalizeNodeStatus(req.Status) if err != nil { return repository.CategoryRecord{}, err } return repository.CategoryRecord{ NodeType: groupNodeType, Name: name, Level: 1, ImageIDs: imageIDs, SortNum: req.GetSortNum(), Status: statusValue, CampaignID: req.GetCampaignId(), }, nil } func normalizeNodeName(raw, field string) (string, error) { name := strings.Join(strings.Fields(raw), " ") if name == "" { return "", fmt.Errorf("%s is required", field) } if len([]rune(name)) > maxNodeNameLength { return "", fmt.Errorf("%s length must be <= %d", field, maxNodeNameLength) } return name, nil } func normalizedNodeNameKey(name string) string { return strings.ToLower(name) } func normalizeNodeImageIDs(raw string) ([]string, error) { raw = strings.TrimSpace(raw) if raw == "" { return []string{}, nil } var imageIDs []string if err := json.Unmarshal([]byte(raw), &imageIDs); err != nil { return nil, errors.New("image_json must be a json string array") } return normalizeStringList(imageIDs), nil } func normalizeNodeStatus(statusValue *int32) (int32, error) { if statusValue == nil { return defaultNodeStatus, nil } if *statusValue != 0 && *statusValue != 1 { return 0, errors.New("status must be 0 or 1") } return *statusValue, nil } func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.ProductRecord, []repository.SKURecord, error) { spuNo := strings.TrimSpace(req.GetSpuNo()) if spuNo == "" { return repository.ProductRecord{}, nil, errors.New("spu_no is required") } title := strings.TrimSpace(req.GetTitle()) if title == "" { return repository.ProductRecord{}, nil, errors.New("title is required") } statusValue := req.GetStatus() if statusValue == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED { statusValue = productv1.ProductStatus_PRODUCT_STATUS_INVENTORY } if statusValue != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY && statusValue != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE && statusValue != productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE { return repository.ProductRecord{}, nil, errors.New("unsupported product status") } crossBorderJSON, err := crossBorderJSONFromProto(req.GetCrossBorderInfo()) if err != nil { return repository.ProductRecord{}, nil, err } record := repository.ProductRecord{ SPUNo: spuNo, Title: title, SellingPoint: strings.TrimSpace(req.GetSellingPoint()), BrandID: strings.TrimSpace(req.GetBrandId()), SupplierID: strings.TrimSpace(req.GetSupplierId()), ImageIDs: normalizeStringList(req.GetImageIds()), DetailHTML: req.GetDetailHtml(), MemberDiscountEnabled: req.GetMemberDiscountEnabled(), GoodsType: defaultInt32(req.GetGoodsType(), 1), ServiceGuarantees: normalizeStringList(req.GetServiceGuarantees()), Status: statusValue, CrossBorderJSON: crossBorderJSON, FreightChargeType: defaultInt32(req.GetFreightChargeType(), 1), FreightFixedAmount: req.GetFreightFixedAmount(), FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()), SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1), ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()), } leafCategoryIDs, err := normalizeLeafCategoryIDs(req.GetLeafCatalogCategoryIds()) if err != nil { return repository.ProductRecord{}, nil, err } record.LeafCategoryIDs = leafCategoryIDs groupIDs, err := normalizeGroupIDs(req.GetGroupIds()) if err != nil { return repository.ProductRecord{}, nil, err } record.GroupIDs = groupIDs if record.FreightFixedAmount < 0 { return repository.ProductRecord{}, nil, errors.New("freight_fixed_amount must be greater than or equal to 0") } if record.GoodsType < 1 || record.GoodsType > 4 { return repository.ProductRecord{}, nil, errors.New("goods_type must be between 1 and 4") } if record.FreightChargeType < 1 || record.FreightChargeType > 2 { return repository.ProductRecord{}, nil, errors.New("freight_charge_type must be 1 or 2") } if record.FreightChargeType == 2 && record.FreightTemplateID == "" { return repository.ProductRecord{}, nil, errors.New("freight_template_id is required when freight_charge_type is 2") } if record.SaleTimeType < 1 || record.SaleTimeType > 2 { return repository.ProductRecord{}, nil, errors.New("sale_time_type must be 1 or 2") } if record.SaleTimeType == 2 && record.ScheduledSaleTime == nil { return repository.ProductRecord{}, nil, errors.New("scheduled_sale_time is required when sale_time_type is 2") } skus := make([]repository.SKURecord, 0, len(req.GetSkus())) for i, protoSKU := range req.GetSkus() { sku, err := skuFromCreateInput(protoSKU) if err != nil { return repository.ProductRecord{}, nil, errors.New("skus[" + strconv.Itoa(i) + "]: " + err.Error()) } skus = append(skus, sku) } if record.Status == productv1.ProductStatus_PRODUCT_STATUS_ON_SALE && !hasSellableSKURecord(skus) { return repository.ProductRecord{}, nil, errors.New("on-sale product requires at least one sellable sku") } return record, skus, nil } func mergeProductUpdate(current *repository.ProductRecord, update *productv1.ProductUpdate, paths []string) (repository.ProductRecord, error) { if current == nil { return repository.ProductRecord{}, errors.New("product is required") } merged := *current if len(paths) == 0 { return merged, nil } if update == nil { return repository.ProductRecord{}, errors.New("product update is required when update_mask is set") } for _, path := range paths { switch path { case "title": merged.Title = strings.TrimSpace(update.GetTitle()) case "selling_point": merged.SellingPoint = strings.TrimSpace(update.GetSellingPoint()) case "brand_id": merged.BrandID = strings.TrimSpace(update.GetBrandId()) case "supplier_id": merged.SupplierID = strings.TrimSpace(update.GetSupplierId()) case "image_ids": merged.ImageIDs = normalizeStringList(update.GetImageIds()) case "detail_html": merged.DetailHTML = update.GetDetailHtml() case "member_discount_enabled": merged.MemberDiscountEnabled = update.GetMemberDiscountEnabled() case "service_guarantees": merged.ServiceGuarantees = normalizeStringList(update.GetServiceGuarantees()) case "cross_border_info": crossBorderJSON, err := crossBorderJSONFromProto(update.GetCrossBorderInfo()) if err != nil { return repository.ProductRecord{}, err } merged.CrossBorderJSON = crossBorderJSON case "freight_charge_type": merged.FreightChargeType = update.GetFreightChargeType() case "freight_fixed_amount": merged.FreightFixedAmount = update.GetFreightFixedAmount() case "freight_template_id": merged.FreightTemplateID = strings.TrimSpace(update.GetFreightTemplateId()) case "sale_time_type": merged.SaleTimeType = update.GetSaleTimeType() case "scheduled_sale_time": merged.ScheduledSaleTime = timestampToTime(update.GetScheduledSaleTime()) case "goods_type": merged.GoodsType = update.GetGoodsType() case "leaf_catalog_category_ids": leafCategoryIDs, err := normalizeLeafCategoryIDs(update.GetLeafCatalogCategoryIds()) if err != nil { return repository.ProductRecord{}, err } merged.LeafCategoryIDs = leafCategoryIDs case "group_ids": groupIDs, err := normalizeGroupIDs(update.GetGroupIds()) if err != nil { return repository.ProductRecord{}, err } merged.GroupIDs = groupIDs default: return repository.ProductRecord{}, fmt.Errorf("unsupported update field %q", path) } } return merged, nil } func containsUpdatePath(paths []string, target string) bool { for _, path := range paths { if path == target { return true } } return false } func validateProductForUpdate(product repository.ProductRecord) error { if strings.TrimSpace(product.Title) == "" { return errors.New("title is required") } if product.FreightFixedAmount < 0 { return errors.New("freight_fixed_amount must be greater than or equal to 0") } if product.GoodsType < 1 || product.GoodsType > 4 { return errors.New("goods_type must be between 1 and 4") } if product.FreightChargeType < 1 || product.FreightChargeType > 2 { return errors.New("freight_charge_type must be 1 or 2") } if product.FreightChargeType == 2 && product.FreightTemplateID == "" { return errors.New("freight_template_id is required when freight_charge_type is 2") } if product.SaleTimeType < 1 || product.SaleTimeType > 2 { return errors.New("sale_time_type must be 1 or 2") } if product.SaleTimeType == 2 && product.ScheduledSaleTime == nil { return errors.New("scheduled_sale_time is required when sale_time_type is 2") } return nil } func skuChangeFromProto(input *productv1.SKUChange, idGenerator *idgen.Generator) (*repository.SKUChange, error) { if input == nil || input.GetMode() == productv1.SKUChangeMode_SKU_CHANGE_MODE_UNSPECIFIED { return nil, nil } change := &repository.SKUChange{} switch input.GetMode() { case productv1.SKUChangeMode_SKU_CHANGE_MODE_PATCH_EXISTING: if len(input.GetPatchItems()) == 0 || len(input.GetReplaceItems()) != 0 { return nil, errors.New("PATCH_EXISTING requires patch_items only") } change.Mode = repository.SKUChangeModePatchExisting change.PatchItems = make([]repository.SKUUpdate, 0, len(input.GetPatchItems())) for index, item := range input.GetPatchItems() { if item == nil || strings.TrimSpace(item.GetSkuId()) == "" { return nil, fmt.Errorf("patch_items[%d].sku_id is required", index) } update, err := skuUpdateFromProto(item) if err != nil { return nil, fmt.Errorf("patch_items[%d]: %w", index, err) } change.PatchItems = append(change.PatchItems, update) } case productv1.SKUChangeMode_SKU_CHANGE_MODE_REPLACE_ALL: if len(input.GetReplaceItems()) == 0 || len(input.GetPatchItems()) != 0 { return nil, errors.New("REPLACE_ALL requires replace_items only") } if idGenerator == nil { return nil, errors.New("id generator is not configured") } change.Mode = repository.SKUChangeModeReplaceAll change.ReplaceItems = make([]repository.SKURecord, 0, len(input.GetReplaceItems())) for index, item := range input.GetReplaceItems() { sku, err := skuFromCreateInput(item) if err != nil { return nil, fmt.Errorf("replace_items[%d]: %w", index, err) } sku.ID = idGenerator.NextString() sku.Inventory = &repository.InventoryRecord{ID: idGenerator.NextString()} change.ReplaceItems = append(change.ReplaceItems, sku) } default: return nil, errors.New("unsupported sku change mode") } return change, nil } func skuUpdateFromProto(input *productv1.PatchExistingSKU) (repository.SKUUpdate, error) { paths := input.GetUpdateMask().GetPaths() if len(paths) == 0 { return repository.SKUUpdate{}, errors.New("update_mask is required") } update := repository.SKUUpdate{ ID: strings.TrimSpace(input.GetSkuId()), ExpectedSKUVersion: input.GetExpectedSkuVersion(), ExpectedInventoryVersion: input.GetExpectedInventoryVersion(), } for _, path := range paths { switch path { case "name": value := input.GetName() update.Name = &value case "price": value := input.GetPrice() update.Price = &value case "supply_price": update.SupplyPriceSet = true update.SupplyPrice = input.SupplyPrice case "stock_quantity": value := input.GetStockQuantity() update.StockQuantity = &value case "status": value := input.GetStatus() update.Status = &value case "image_ids": value := normalizeStringList(input.GetImageIds()) update.ImageIDs = &value default: return repository.SKUUpdate{}, fmt.Errorf("unsupported sku update field %q", path) } } return update, nil } func toProtoSKUChangeResult(result *repository.SKUChangeResult) *productv1.SKUChangeResult { if result == nil { return nil } mode := productv1.SKUChangeMode_SKU_CHANGE_MODE_UNSPECIFIED switch result.Mode { case repository.SKUChangeModePatchExisting: mode = productv1.SKUChangeMode_SKU_CHANGE_MODE_PATCH_EXISTING case repository.SKUChangeModeReplaceAll: mode = productv1.SKUChangeMode_SKU_CHANGE_MODE_REPLACE_ALL } return &productv1.SKUChangeResult{ Mode: mode, CreatedSkuIds: result.CreatedSKUIds, ArchivedSkuIds: result.ArchivedSKUIds, UpdatedSkuIds: result.UpdatedSKUIds, } } func hasSellableSKURecord(skus []repository.SKURecord) bool { for _, sku := range skus { if sku.Status == 1 && sku.StockQuantity > sku.LockedQuantity { return true } } return false } func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord, error) { if sku == nil { return repository.SKURecord{}, errors.New("sku is required") } if sku.GetPrice() < 0 { return repository.SKURecord{}, errors.New("price must be greater than or equal to 0") } if sku.SupplyPrice != nil && *sku.SupplyPrice < 0 { return repository.SKURecord{}, errors.New("supply_price must be greater than or equal to 0") } if sku.GetStockQuantity() < 0 { return repository.SKURecord{}, errors.New("stock_quantity must be greater than or equal to 0") } attrs, derivedName, err := buildSKUAttributesAndName(sku) if err != nil { return repository.SKURecord{}, err } name := strings.TrimSpace(sku.GetName()) if name == "" { name = derivedName } statusValue := sku.GetStatus() if statusValue < 0 || statusValue > 1 { return repository.SKURecord{}, errors.New("status must be 0 or 1") } return repository.SKURecord{ SKUNo: strings.TrimSpace(sku.GetSkuNo()), Name: name, Price: sku.GetPrice(), SupplyPrice: sku.SupplyPrice, ImageIDs: normalizeStringList(sku.GetImageIds()), StockQuantity: sku.GetStockQuantity(), AttributesJSON: attrs, K1: strings.TrimSpace(sku.GetK1()), V1: strings.TrimSpace(sku.GetV1()), K2: strings.TrimSpace(sku.GetK2()), V2: strings.TrimSpace(sku.GetV2()), K3: strings.TrimSpace(sku.GetK3()), V3: strings.TrimSpace(sku.GetV3()), Status: statusValue, }, nil } func buildSKUAttributesAndName(sku *productv1.CreateProductSKU) (string, string, error) { specs := []struct { keyField string valueField string key string value string }{ {keyField: "k1", valueField: "v1", key: strings.TrimSpace(sku.GetK1()), value: strings.TrimSpace(sku.GetV1())}, {keyField: "k2", valueField: "v2", key: strings.TrimSpace(sku.GetK2()), value: strings.TrimSpace(sku.GetV2())}, {keyField: "k3", valueField: "v3", key: strings.TrimSpace(sku.GetK3()), value: strings.TrimSpace(sku.GetV3())}, } attrs := make([]map[string]string, 0, len(specs)) nameParts := make([]string, 0, len(specs)) foundEmpty := false for _, spec := range specs { if spec.key == "" && spec.value == "" { foundEmpty = true continue } if foundEmpty { return "", "", errors.New("sku specs must be filled in order from k1/v1 to k3/v3") } if spec.key == "" || spec.value == "" { return "", "", errors.New(spec.keyField + "/" + spec.valueField + " must be provided together") } attrs = append(attrs, map[string]string{ spec.keyField: spec.key, spec.valueField: spec.value, }) nameParts = append(nameParts, spec.value) } if len(attrs) == 0 { return "", "", errors.New("at least one sku spec k1/v1 is required") } attrsJSON, err := json.Marshal(attrs) if err != nil { return "", "", err } return string(attrsJSON), strings.Join(nameParts, " "), nil } func crossBorderJSONFromProto(info *productv1.CrossBorderInfo) (string, error) { if info == nil { return "{}", nil } if info.GetCustomsTaxRateBps() < 0 { return "", errors.New("cross_border_info.customs_tax_rate_bps must be greater than or equal to 0") } switch info.GetLogisticsMode() { case productv1.CrossBorderLogisticsMode_CROSS_BORDER_LOGISTICS_MODE_UNSPECIFIED, productv1.CrossBorderLogisticsMode_CROSS_BORDER_LOGISTICS_MODE_BONDED_IMPORT, productv1.CrossBorderLogisticsMode_CROSS_BORDER_LOGISTICS_MODE_OVERSEAS_DIRECT_MAIL: default: return "", errors.New("cross_border_info.logistics_mode is invalid") } marshalOptions := protojson.MarshalOptions{UseProtoNames: true, UseEnumNumbers: true, EmitUnpopulated: true} raw, err := marshalOptions.Marshal(info) if err != nil { return "", err } return string(raw), nil } func toProtoCrossBorderInfo(raw string) *productv1.CrossBorderInfo { if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "{}" { return nil } info := &productv1.CrossBorderInfo{} unmarshalOptions := protojson.UnmarshalOptions{DiscardUnknown: true} if err := unmarshalOptions.Unmarshal([]byte(raw), info); err != nil { return nil } return info } func normalizeStringList(values []string) []string { if len(values) == 0 { return []string{} } out := make([]string, 0, len(values)) seen := make(map[string]struct{}, len(values)) for _, value := range values { trimmed := strings.TrimSpace(value) if trimmed == "" { continue } if _, ok := seen[trimmed]; ok { continue } seen[trimmed] = struct{}{} out = append(out, trimmed) } return out } func normalizeLeafCategoryIDs(values []string) ([]string, error) { if len(values) > 100 { return nil, errors.New("leaf_catalog_category_ids must contain at most 100 items") } leafCategoryIDs := make([]string, 0, len(values)) seen := make(map[string]struct{}, len(values)) for _, value := range values { categoryID := strings.TrimSpace(value) if categoryID == "" { return nil, errors.New("leaf_catalog_category_ids must not contain an empty id") } if _, err := normalizeCategoryID(categoryID, "leaf_catalog_category_ids"); err != nil { return nil, err } if _, duplicate := seen[categoryID]; duplicate { return nil, errors.New("leaf_catalog_category_ids must not contain duplicates") } seen[categoryID] = struct{}{} leafCategoryIDs = append(leafCategoryIDs, categoryID) } return leafCategoryIDs, nil } func normalizeGroupIDs(values []string) ([]string, error) { if len(values) > 100 { return nil, errors.New("group_ids must contain at most 100 items") } groupIDs := make([]string, 0, len(values)) seen := make(map[string]struct{}, len(values)) for _, value := range values { groupID := strings.TrimSpace(value) if groupID == "" { return nil, errors.New("group_ids must not contain an empty id") } if _, err := normalizeCategoryID(groupID, "group_ids"); err != nil { return nil, err } if _, duplicate := seen[groupID]; duplicate { return nil, errors.New("group_ids must not contain duplicates") } seen[groupID] = struct{}{} groupIDs = append(groupIDs, groupID) } return groupIDs, nil } 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 { if value == 0 { return fallback } return value } func timestampToTime(value *timestamppb.Timestamp) *time.Time { if value == nil { return nil } t := value.AsTime() return &t } func timeToMillisString(value time.Time) string { return strconv.FormatInt(value.UnixMilli(), 10) } func timePtrToMillisString(value *time.Time) *string { if value == nil { return nil } millis := timeToMillisString(*value) return &millis } func validatePositiveID(raw, field string) error { if raw == "" { return errors.New(field + " is required") } id, err := strconv.ParseInt(raw, 10, 64) if err != nil || id <= 0 { return errors.New(field + " must be a positive snowflake id") } return nil } func toProtoProduct(product *repository.ProductRecord, skus []repository.SKURecord) *productv1.Product { if product == nil { return nil } protoSKUs := make([]*productv1.SKU, 0, len(skus)) for _, sku := range skus { protoSKUs = append(protoSKUs, &productv1.SKU{ SkuId: sku.ID, ProductId: sku.ProductID, SkuNo: sku.SKUNo, Name: sku.Name, Price: sku.Price, SupplyPrice: sku.SupplyPrice, StockQuantity: sku.StockQuantity, SoldQuantity: sku.SoldQuantity, AttributesJson: sku.AttributesJSON, Status: sku.Status, ImageIds: sku.ImageIDs, K1: sku.K1, V1: sku.V1, K2: sku.K2, V2: sku.V2, K3: sku.K3, V3: sku.V3, IsArchived: sku.IsArchived, ArchivedAt: timePtrToMillisString(sku.ArchivedAt), Version: sku.Version, DeletedAt: timePtrToMillisString(sku.DeletedAt), CreatedAt: timeToMillisString(sku.CreatedAt), UpdatedAt: timeToMillisString(sku.UpdatedAt), Inventory: toProtoInventory(sku.Inventory), }) } return &productv1.Product{ ProductId: product.ID, SpuNo: product.SPUNo, Title: product.Title, SellingPoint: product.SellingPoint, Status: product.Status, Skus: protoSKUs, CreatedAt: timeToMillisString(product.CreatedAt), UpdatedAt: timeToMillisString(product.UpdatedAt), ImageIds: product.ImageIDs, BrandId: product.BrandID, SupplierId: product.SupplierID, DetailHtml: product.DetailHTML, MemberDiscountEnabled: product.MemberDiscountEnabled, GoodsType: product.GoodsType, ServiceGuarantees: product.ServiceGuarantees, CrossBorderJson: product.CrossBorderJSON, CrossBorderInfo: toProtoCrossBorderInfo(product.CrossBorderJSON), FreightChargeType: product.FreightChargeType, FreightFixedAmount: product.FreightFixedAmount, FreightTemplateId: product.FreightTemplateID, SaleTimeType: product.SaleTimeType, ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime), Version: product.Version, DeletedAt: timePtrToMillisString(product.DeletedAt), LeafCatalogCategoryIds: append([]string(nil), product.LeafCategoryIDs...), GroupIds: append([]string(nil), product.GroupIDs...), } } func toProtoCartItemProduct(lineID string, record repository.CartItemProductRecord) *productv1.CartItemProduct { result := &productv1.CartItemProduct{ LineId: lineID, ProductId: record.ProductID, SkuId: record.SKUID, SpuStatus: productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED, } if record.Product == nil { return result } result.ProductName = record.Product.Title result.ServiceGuarantees = record.Product.ServiceGuarantees result.SpuImageIds = record.Product.ImageIDs result.SpuStatus = record.Product.Status if record.SKU == nil { return result } result.SkuName = record.SKU.Name result.Price = record.SKU.Price result.SkuImageIds = record.SKU.ImageIDs result.SkuStockQuantity = record.SKU.StockQuantity result.SkuLockedQuantity = record.SKU.LockedQuantity result.SkuStatus = record.SKU.Status result.SkuIsArchived = record.SKU.IsArchived return result } func toProtoCategoryProduct(product *repository.CategoryProductRecord) *productv1.CategoryProduct { if product == nil { return nil } return &productv1.CategoryProduct{ UpdatedAt: timeToMillisString(product.UpdatedAt), CreatedAt: timeToMillisString(product.CreatedAt), Title: product.Title, ProductId: product.ID, SpuNo: product.SPUNo, Status: product.Status, ImageIds: product.ImageIDs, Price: product.Price, SoldQuantity: product.SoldQuantity, StockQuantity: product.StockQuantity, LockedQuantity: product.LockedQuantity, } } func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductItemInventory { if inventory == nil { return nil } return &productv1.ProductItemInventory{ InventoryId: inventory.ID, SkuId: inventory.SKUID, StockQuantity: inventory.StockQuantity, LockedQuantity: inventory.LockedQuantity, SoldQuantity: inventory.SoldQuantity, Version: inventory.Version, CreatedAt: timeToMillisString(inventory.CreatedAt), UpdatedAt: timeToMillisString(inventory.UpdatedAt), } } func toProtoInventories(inventories []*repository.InventoryRecord) []*productv1.ProductItemInventory { out := make([]*productv1.ProductItemInventory, 0, len(inventories)) for _, inventory := range inventories { out = append(out, toProtoInventory(inventory)) } return out } func buildCategoryTree(categories []*repository.CategoryRecord) []*productv1.CategoryNode { nodes := make(map[string]*productv1.CategoryNode, len(categories)) records := make(map[string]*repository.CategoryRecord, len(categories)) orderedIDs := make([]string, 0, len(categories)) for _, category := range categories { if category == nil || category.ID == "" { continue } nodes[category.ID] = toProtoCategoryNode(category) records[category.ID] = category orderedIDs = append(orderedIDs, category.ID) } roots := make([]*productv1.CategoryNode, 0) for _, id := range orderedIDs { node := nodes[id] record := records[id] if node == nil || record == nil { continue } parentID := record.ParentID parent, parentExists := nodes[parentID] parentRecord := records[parentID] if parentID == "" || !parentExists || parentRecord == nil || parentID == id || parentRecord.Level >= record.Level { roots = append(roots, node) continue } parent.Children = append(parent.Children, node) } return roots } func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.CategoryNode { if category == nil { return nil } return &productv1.CategoryNode{ CategoryId: category.ID, NodeType: category.NodeType, Name: category.Name, ParentId: category.ParentID, Level: category.Level, ImageJson: categoryImageIDsJSON(category.ImageIDs), SortNum: category.SortNum, Status: category.Status, CampaignId: category.CampaignID, Version: category.Version, Children: []*productv1.CategoryNode{}, } } func toProtoGroupNode(group *repository.CategoryRecord) *productv1.GroupNode { if group == nil { return nil } return &productv1.GroupNode{ GroupId: group.ID, NodeType: group.NodeType, Name: group.Name, ParentId: group.ParentID, Level: group.Level, ImageJson: categoryImageIDsJSON(group.ImageIDs), SortNum: group.SortNum, Status: group.Status, ProductCount: group.ProductCount, CampaignId: group.CampaignID, } } func categoryImageIDsJSON(imageIDs []string) string { encoded, err := json.Marshal(imageIDs) if err != nil { return "[]" } return string(encoded) }