mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
3287 lines
121 KiB
Go
3287 lines
121 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"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/structpb"
|
|
"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
|
|
maxStorefrontProductBatchSize = 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, productCreateError(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, productCreateError(codes.InvalidArgument, err.Error(), productCreateFieldFromMessage(err.Error()))
|
|
}
|
|
product.Scope = scope
|
|
if err := s.repo.ValidateProductMasterRefs(ctx, product.SupplierID, product.BrandID, scope); err != nil {
|
|
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, productCreateError(codes.InvalidArgument, "freight_template_id not found or disabled", "freight_template_id")
|
|
}
|
|
return nil, status.Errorf(codes.Internal, "validate freight template: %v", 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())
|
|
}
|
|
for range product.ProductCategoryIDs {
|
|
product.ProductCategoryBindingIDs = append(product.ProductCategoryBindingIDs, 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, productCreateError(codes.AlreadyExists, fmt.Sprintf("spu_no already exists: %s", product.SPUNo), "spu_no")
|
|
}
|
|
if errors.Is(err, repository.ErrInvalidLeafCategory) {
|
|
return nil, productCreateError(codes.InvalidArgument, err.Error(), "leaf_catalog_category_ids")
|
|
}
|
|
if errors.Is(err, repository.ErrInvalidProductGroup) {
|
|
return nil, productCreateError(codes.InvalidArgument, err.Error(), "group_ids")
|
|
}
|
|
if errors.Is(err, repository.ErrInvalidProductCategory) {
|
|
return nil, productCreateError(codes.InvalidArgument, err.Error(), "product_category_ids")
|
|
}
|
|
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)
|
|
}
|
|
totalSoldQuantity, err := s.repo.GetProductTotalSoldQuantity(dbCtx, req.GetProductId(), scope)
|
|
if err != nil {
|
|
dbSpan.RecordError(err)
|
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
|
s.observer.Logger(ctx).Error("get product total sold quantity failed", zap.String("product_id", req.GetProductId()), zap.Error(err))
|
|
return nil, status.Errorf(codes.Internal, "get product total sold quantity: %v", err)
|
|
}
|
|
|
|
return &productv1.GetProductResponse{
|
|
Product: toProtoProduct(product, skus),
|
|
TotalSoldQuantity: totalSoldQuantity,
|
|
}, 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
|
|
}
|
|
|
|
// BatchGetStorefrontProductSKUs returns the current sellable SKU prices needed
|
|
// to calculate product-card promotion display data in one downstream call.
|
|
func (s *ProductServer) BatchGetStorefrontProductSKUs(ctx context.Context, req *productv1.BatchGetStorefrontProductSKUsRequest) (*productv1.BatchGetStorefrontProductSKUsResponse, error) {
|
|
scope, err := requireStoreScope(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(req.GetProductIds()) == 0 {
|
|
return nil, status.Error(codes.InvalidArgument, "product_ids is required")
|
|
}
|
|
if len(req.GetProductIds()) > maxStorefrontProductBatchSize {
|
|
return nil, status.Errorf(codes.InvalidArgument, "product_ids must contain at most %d entries", maxStorefrontProductBatchSize)
|
|
}
|
|
|
|
productIDs := make([]string, 0, len(req.GetProductIds()))
|
|
seen := make(map[string]struct{}, len(req.GetProductIds()))
|
|
for index, productID := range req.GetProductIds() {
|
|
if err := validatePositiveID(productID, "product_id"); err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "product_ids[%d]: %v", index, err)
|
|
}
|
|
if _, exists := seen[productID]; exists {
|
|
continue
|
|
}
|
|
seen[productID] = struct{}{}
|
|
productIDs = append(productIDs, productID)
|
|
}
|
|
|
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.storefront_skus.batch_get", trace.WithAttributes(
|
|
attribute.Int("product.count", len(productIDs)),
|
|
))
|
|
defer dbSpan.End()
|
|
records, err := s.repo.BatchGetStorefrontProductSKUs(dbCtx, productIDs, scope)
|
|
if err != nil {
|
|
dbSpan.RecordError(err)
|
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
|
s.observer.Logger(ctx).Error("batch get storefront product skus failed", zap.Error(err))
|
|
return nil, status.Errorf(codes.Internal, "batch get storefront product skus: %v", err)
|
|
}
|
|
|
|
byProduct := make(map[string][]*productv1.StorefrontProductSKU, len(productIDs))
|
|
for _, record := range records {
|
|
byProduct[record.ProductID] = append(byProduct[record.ProductID], &productv1.StorefrontProductSKU{
|
|
SkuId: record.SKUID,
|
|
OriginalPrice: record.Price,
|
|
})
|
|
}
|
|
products := make([]*productv1.StorefrontProductSKUs, 0, len(byProduct))
|
|
for _, productID := range productIDs {
|
|
skus := byProduct[productID]
|
|
if len(skus) == 0 {
|
|
continue
|
|
}
|
|
products = append(products, &productv1.StorefrontProductSKUs{ProductId: productID, Skus: skus})
|
|
}
|
|
return &productv1.BatchGetStorefrontProductSKUsResponse{Products: products}, 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)
|
|
}
|
|
if merged.FreightChargeType == 2 {
|
|
if err := s.repo.FreightTemplateExists(ctx, merged.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, status.Errorf(codes.Internal, "validate freight template: %v", 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
|
|
var productCategoryIDs *[]string
|
|
var productCategoryBindingIDs []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())
|
|
}
|
|
}
|
|
if containsUpdatePath(req.GetUpdateMask().GetPaths(), "product_category_ids") {
|
|
productCategoryIDs = &merged.ProductCategoryIDs
|
|
if s.idgen == nil {
|
|
return nil, status.Error(codes.Internal, "id generator is not configured")
|
|
}
|
|
for range merged.ProductCategoryIDs {
|
|
productCategoryBindingIDs = append(productCategoryBindingIDs, 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,
|
|
ProductCategoryIDs: productCategoryIDs,
|
|
ProductCategoryBindingIDs: productCategoryBindingIDs,
|
|
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())
|
|
case errors.Is(err, repository.ErrInvalidProductCategory):
|
|
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
|
|
}
|
|
|
|
// UpdateProductFreightCharge updates only one product's freight configuration,
|
|
// locating it by the store-scoped SPU business number.
|
|
func (s *ProductServer) UpdateProductFreightCharge(ctx context.Context, req *productv1.UpdateProductFreightChargeRequest) (*productv1.UpdateProductFreightChargeResponse, error) {
|
|
if req == nil {
|
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
|
}
|
|
scope, err := requireStoreScope(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
spuNo, freightChargeType, freightFixedAmount, freightTemplateID, err := productFreightChargeFromUpdateRequest(req)
|
|
if err != nil {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
if freightChargeType == 2 {
|
|
if err := validatePositiveID(freightTemplateID, "freight_template_id"); err != nil {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
if err := s.repo.FreightTemplateExists(ctx, 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, status.Errorf(codes.Internal, "validate freight template: %v", err)
|
|
}
|
|
}
|
|
|
|
updated, err := s.repo.UpdateProductFreightChargeBySPUNo(ctx, spuNo, freightChargeType, freightFixedAmount, freightTemplateID, scope)
|
|
if errors.Is(err, repository.ErrProductNotFound) {
|
|
return nil, status.Error(codes.NotFound, "product not found")
|
|
}
|
|
if err != nil {
|
|
s.observer.Logger(ctx).Error("update product freight charge failed", zap.String("spu_no", spuNo), zap.Error(err))
|
|
return nil, status.Errorf(codes.Internal, "update product freight charge: %v", err)
|
|
}
|
|
return &productv1.UpdateProductFreightChargeResponse{
|
|
ProductId: updated.ProductID,
|
|
SpuNo: updated.SPUNo,
|
|
FreightChargeType: updated.FreightChargeType,
|
|
FreightFixedAmount: updated.FreightFixedAmount,
|
|
FreightTemplateId: updated.FreightTemplateID,
|
|
Version: updated.Version,
|
|
UpdatedAt: updated.UpdatedAt.UTC().Format(time.RFC3339Nano),
|
|
}, 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):
|
|
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) {
|
|
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)
|
|
}
|
|
}
|
|
if filter.ProductCategoryID != "" {
|
|
if err := s.repo.ValidateProductCategory(dbCtx, filter.ProductCategoryID, scope); err != nil {
|
|
dbSpan.RecordError(err)
|
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
|
if errors.Is(err, repository.ErrProductCategoryNotFound) {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
s.observer.Logger(ctx).Error("validate product category filter failed", zap.String("category_id", filter.ProductCategoryID), zap.Error(err))
|
|
return nil, status.Errorf(codes.Internal, "validate product category 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()),
|
|
ProductCategoryID: strings.TrimSpace(req.GetCategoryId()),
|
|
}
|
|
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 filter.ProductCategoryID != "" {
|
|
if err := validatePositiveID(filter.ProductCategoryID, "category_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.PresaleType != nil {
|
|
presaleType := req.GetPresaleType()
|
|
if presaleType < 0 || presaleType > 2 {
|
|
return repository.ProductListFilter{}, errors.New("presale_type must be 0, 1, or 2")
|
|
}
|
|
filter.PresaleType = &presaleType
|
|
}
|
|
if req.Status != nil {
|
|
statusValue := req.GetStatus()
|
|
if statusValue != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY &&
|
|
statusValue != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE &&
|
|
statusValue != productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT {
|
|
return repository.ProductListFilter{}, errors.New("status must be 1, 2, or 3")
|
|
}
|
|
filter.Status = &statusValue
|
|
}
|
|
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)")
|
|
}
|
|
if targetNodeType == 2 {
|
|
if err := s.repo.ValidateProductGroup(ctx, req.GetCategoryId(), scope); err != nil {
|
|
if errors.Is(err, repository.ErrInvalidProductGroup) {
|
|
return nil, status.Error(codes.NotFound, "leaf product group not found")
|
|
}
|
|
return nil, status.Errorf(codes.Internal, "validate product group: %v", err)
|
|
}
|
|
}
|
|
|
|
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())
|
|
if errors.Is(err, repository.ErrStorefrontCategoryNotFound) {
|
|
return nil, status.Error(codes.NotFound, "catalog category not found")
|
|
}
|
|
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()
|
|
|
|
categoryID := ""
|
|
maxDepth := int32(0)
|
|
if req != nil {
|
|
categoryID = strings.TrimSpace(req.GetCategoryId())
|
|
maxDepth = req.GetMaxDepth()
|
|
}
|
|
if maxDepth < 0 {
|
|
return nil, status.Error(codes.InvalidArgument, "max_depth must be non-negative")
|
|
}
|
|
if categoryID != "" {
|
|
if _, err := normalizeCategoryID(categoryID, "category_id"); err != nil {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
}
|
|
categories, err := s.repo.ListCategoryTreeNodes(dbCtx, onlyVisible, categoryID, maxDepth, 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 catalog-category subtree at any depth.
|
|
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())
|
|
}
|
|
assignCatalogCategoryIDs(&parent, s)
|
|
|
|
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, _, err := s.repo.CreateCatalogCategoryTree(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)
|
|
|
|
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, "", 0, 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 category subtree. 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 and optional child groups.
|
|
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, children, err := groupTreeFromCreateRequest(req)
|
|
if err != nil {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
group.ID = s.idgen.NextString()
|
|
for index := range children {
|
|
children[index].ID = s.idgen.NextString()
|
|
}
|
|
|
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create_group", trace.WithAttributes(
|
|
attribute.String("group.name", group.Name),
|
|
attribute.Int("group.child_count", len(children)),
|
|
))
|
|
defer dbSpan.End()
|
|
|
|
createdGroup, createdChildren, err := s.repo.CreateCategoryTree(dbCtx, group, children, 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)
|
|
}
|
|
|
|
protoGroup := toProtoGroupNode(createdGroup)
|
|
for _, child := range createdChildren {
|
|
protoGroup.Children = append(protoGroup.Children, toProtoGroupNode(child))
|
|
}
|
|
return &productv1.CreateGroupResponse{Group: protoGroup}, nil
|
|
}
|
|
|
|
// CreateGroupChildren batch-creates second-level groups under one first-level group.
|
|
func (s *ProductServer) CreateGroupChildren(ctx context.Context, req *productv1.CreateGroupChildrenRequest) (*productv1.CreateGroupChildrenResponse, error) {
|
|
if req == nil {
|
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
|
}
|
|
scope, err := requireStoreScope(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
parentID, err := normalizeCategoryID(req.GetGroupId(), "group_id")
|
|
if err != nil {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
children, err := groupChildrenFromProto(req.GetChildren())
|
|
if err != nil {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
if s.idgen == nil {
|
|
return nil, status.Error(codes.Internal, "id generator is not configured")
|
|
}
|
|
for index := range children {
|
|
children[index].ID = s.idgen.NextString()
|
|
}
|
|
created, err := s.repo.CreateGroupChildren(ctx, parentID, children, scope)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, repository.ErrGroupNameExists):
|
|
return nil, status.Error(codes.AlreadyExists, "group name already exists")
|
|
case errors.Is(err, repository.ErrInvalidProductGroup), errors.Is(err, repository.ErrCategoryNodeNotFound):
|
|
return nil, status.Error(codes.InvalidArgument, "group_id must identify a first-level group")
|
|
default:
|
|
return nil, status.Errorf(codes.Internal, "create group children: %v", err)
|
|
}
|
|
}
|
|
groups := make([]*productv1.GroupNode, 0, len(created))
|
|
for _, child := range created {
|
|
groups = append(groups, toProtoGroupNode(child))
|
|
}
|
|
return &productv1.CreateGroupChildrenResponse{Groups: groups}, nil
|
|
}
|
|
|
|
// UpdateGroup updates mutable fields on one product group.
|
|
func (s *ProductServer) UpdateGroup(ctx context.Context, req *productv1.UpdateGroupRequest) (*productv1.UpdateGroupResponse, error) {
|
|
if req == nil {
|
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
|
}
|
|
scope, err := requireStoreScope(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
groupID, err := normalizeCategoryID(req.GetGroupId(), "group_id")
|
|
if err != nil {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
if req.GetExpectedVersion() < 0 {
|
|
return nil, status.Error(codes.InvalidArgument, "expected_version must be non-negative")
|
|
}
|
|
update, err := groupFieldUpdateFromRequest(req)
|
|
if err != nil {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.group.update", trace.WithAttributes(attribute.String("group.id", groupID)))
|
|
defer dbSpan.End()
|
|
updated, err := s.repo.UpdateGroup(dbCtx, *update, scope)
|
|
if err != nil {
|
|
dbSpan.RecordError(err)
|
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
|
switch {
|
|
case errors.Is(err, repository.ErrCategoryNodeNotFound), errors.Is(err, repository.ErrInvalidProductGroup):
|
|
return nil, status.Error(codes.NotFound, "group not found")
|
|
case errors.Is(err, repository.ErrCategoryVersionConflict):
|
|
return nil, status.Error(codes.Aborted, "group version conflict")
|
|
case errors.Is(err, repository.ErrGroupNameExists):
|
|
return nil, status.Error(codes.AlreadyExists, "group name already exists")
|
|
default:
|
|
s.observer.Logger(ctx).Error("update group failed", zap.String("group_id", groupID), zap.Error(err))
|
|
return nil, status.Errorf(codes.Internal, "update group: %v", err)
|
|
}
|
|
}
|
|
return &productv1.UpdateGroupResponse{Group: toProtoGroupNode(updated)}, nil
|
|
}
|
|
|
|
// DeleteGroup hard-deletes one product group and its bindings.
|
|
func (s *ProductServer) DeleteGroup(ctx context.Context, req *productv1.DeleteGroupRequest) (*productv1.DeleteGroupResponse, error) {
|
|
if req == nil {
|
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
|
}
|
|
scope, err := requireStoreScope(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
groupID, err := normalizeCategoryID(req.GetGroupId(), "group_id")
|
|
if err != nil {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
if req.GetExpectedVersion() < 0 {
|
|
return nil, status.Error(codes.InvalidArgument, "expected_version must be non-negative")
|
|
}
|
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.group.delete", trace.WithAttributes(attribute.String("group.id", groupID)))
|
|
defer dbSpan.End()
|
|
result, err := s.repo.DeleteGroup(dbCtx, groupID, req.GetExpectedVersion(), scope)
|
|
if err != nil {
|
|
dbSpan.RecordError(err)
|
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
|
switch {
|
|
case errors.Is(err, repository.ErrCategoryNodeNotFound), errors.Is(err, repository.ErrInvalidProductGroup):
|
|
return nil, status.Error(codes.NotFound, "group not found")
|
|
case errors.Is(err, repository.ErrCategoryVersionConflict):
|
|
return nil, status.Error(codes.Aborted, "group version conflict")
|
|
default:
|
|
s.observer.Logger(ctx).Error("delete group failed", zap.String("group_id", groupID), zap.Error(err))
|
|
return nil, status.Error(codes.Internal, "delete group")
|
|
}
|
|
}
|
|
return &productv1.DeleteGroupResponse{
|
|
DeletedGroupId: result.DeletedGroupID,
|
|
UnboundProductCount: result.UnboundProductCount,
|
|
UnboundBindingCount: result.UnboundBindingCount,
|
|
}, nil
|
|
}
|
|
|
|
// ListGroups returns product groups.
|
|
func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroupsRequest) (*productv1.ListGroupsResponse, error) {
|
|
scope, err := requireStoreScope(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
onlyVisible := false
|
|
filter := repository.GroupListFilter{}
|
|
if req != nil {
|
|
onlyVisible = req.GetOnlyVisible()
|
|
filter.FirstLevelName = strings.TrimSpace(req.GetFirstLevelName())
|
|
filter.SecondLevelName = strings.TrimSpace(req.GetSecondLevelName())
|
|
filter.ExactMatch = req.GetExactMatch()
|
|
}
|
|
filter.OnlyVisible = onlyVisible
|
|
|
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_groups", trace.WithAttributes(
|
|
attribute.Bool("group.only_visible", onlyVisible),
|
|
))
|
|
defer dbSpan.End()
|
|
|
|
page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize())
|
|
groups, total, err := s.repo.ListGroupNodes(dbCtx, filter, page, pageSize, scope)
|
|
if err != nil {
|
|
dbSpan.RecordError(err)
|
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
|
fields := []zap.Field{
|
|
zap.Int64("tenant_id", scope.TenantID),
|
|
zap.Int64("store_id", scope.StoreID),
|
|
zap.Bool("only_visible", onlyVisible),
|
|
zap.String("first_level_name", filter.FirstLevelName),
|
|
zap.String("second_level_name", filter.SecondLevelName),
|
|
zap.Bool("exact_match", filter.ExactMatch),
|
|
zap.Int32("page", page),
|
|
zap.Int32("page_size", pageSize),
|
|
zap.Error(err),
|
|
}
|
|
var queryErr *repository.GroupListQueryError
|
|
if errors.As(err, &queryErr) {
|
|
fields = append(fields, zap.String("sql_query", queryErr.Query), zap.Any("sql_args", queryErr.Args))
|
|
}
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) {
|
|
fields = append(fields,
|
|
zap.String("sqlstate", pgErr.Code),
|
|
zap.Int32("sql_position", pgErr.Position),
|
|
zap.String("pg_detail", pgErr.Detail),
|
|
zap.String("pg_where", pgErr.Where),
|
|
zap.String("pg_internal_query", pgErr.InternalQuery),
|
|
zap.Int32("pg_internal_position", pgErr.InternalPosition),
|
|
)
|
|
}
|
|
s.observer.Logger(dbCtx).Error("list groups failed", fields...)
|
|
return nil, status.Errorf(codes.Internal, "list groups: %v", err)
|
|
}
|
|
dbSpan.SetAttributes(
|
|
attribute.Int("group.result_count", len(groups)),
|
|
attribute.Int64("group.total", total),
|
|
attribute.Int("page", int(page)),
|
|
attribute.Int("page_size", int(pageSize)),
|
|
)
|
|
|
|
protoGroups := make([]*productv1.GroupNode, 0, len(groups))
|
|
for _, group := range groups {
|
|
protoGroups = append(protoGroups, toProtoGroupNode(group))
|
|
}
|
|
|
|
return &productv1.ListGroupsResponse{
|
|
Groups: protoGroups,
|
|
Page: page,
|
|
PageSize: pageSize,
|
|
Total: total,
|
|
TotalPages: totalPages(total, pageSize),
|
|
}, 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.ErrProductSoldOut):
|
|
return nil, status.Error(codes.FailedPrecondition, "product is sold out")
|
|
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(),
|
|
}
|
|
if req.ParentId != nil {
|
|
parent.ParentID, err = normalizeCategoryID(req.GetParentId(), "parent_id")
|
|
if err != nil {
|
|
return repository.CategoryRecord{}, nil, err
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
grandchildren, err := categoryChildrenFromCreateRequest(child.GetChildren(), "children.children")
|
|
if err != nil {
|
|
return repository.CategoryRecord{}, nil, err
|
|
}
|
|
children = append(children, repository.CategoryRecord{NodeType: categoryNodeType, Name: childName, ImageIDs: childImageIDs, SortNum: child.GetSortNum(), Status: childStatus, CampaignID: child.GetCampaignId(), Children: grandchildren})
|
|
}
|
|
|
|
return parent, children, nil
|
|
}
|
|
|
|
func categoryChildrenFromCreateRequest(inputs []*productv1.CreateChildCategory, field string) ([]repository.CategoryRecord, error) {
|
|
children := make([]repository.CategoryRecord, 0, len(inputs))
|
|
seen := make(map[string]struct{}, len(inputs))
|
|
for _, child := range inputs {
|
|
if child == nil {
|
|
return nil, errors.New(field + " item is required")
|
|
}
|
|
name, err := normalizeNodeName(child.GetName(), field+".name")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if _, exists := seen[normalizedNodeNameKey(name)]; exists {
|
|
return nil, errors.New(field + ".name must be unique")
|
|
}
|
|
seen[normalizedNodeNameKey(name)] = struct{}{}
|
|
images, err := normalizeNodeImageIDs(child.GetImageJson())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
statusValue, err := normalizeNodeStatus(child.Status)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
grandchildren, err := categoryChildrenFromCreateRequest(child.GetChildren(), field+".children")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
children = append(children, repository.CategoryRecord{NodeType: categoryNodeType, Name: name, ImageIDs: images, SortNum: child.GetSortNum(), Status: statusValue, CampaignID: child.GetCampaignId(), Children: grandchildren})
|
|
}
|
|
return children, nil
|
|
}
|
|
|
|
func assignCatalogCategoryIDs(node *repository.CategoryRecord, s *ProductServer) {
|
|
if node == nil {
|
|
return
|
|
}
|
|
node.ID = s.idgen.NextString()
|
|
for index := range node.Children {
|
|
assignCatalogCategoryIDs(&node.Children[index], s)
|
|
}
|
|
}
|
|
|
|
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 groupTreeFromCreateRequest(req *productv1.CreateGroupRequest) (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: groupNodeType,
|
|
Name: name,
|
|
Level: 1,
|
|
ImageIDs: imageIDs,
|
|
SortNum: req.GetSortNum(),
|
|
Status: statusValue,
|
|
}
|
|
children, err := groupChildrenFromProto(req.GetChildren())
|
|
if err != nil {
|
|
return repository.CategoryRecord{}, nil, err
|
|
}
|
|
return parent, children, nil
|
|
}
|
|
|
|
func groupChildrenFromProto(items []*productv1.CreateChildGroup) ([]repository.CategoryRecord, error) {
|
|
if len(items) > 100 {
|
|
return nil, errors.New("children must contain at most 100 items")
|
|
}
|
|
children := make([]repository.CategoryRecord, 0, len(items))
|
|
names := make(map[string]struct{}, len(items))
|
|
for _, item := range items {
|
|
if item == nil {
|
|
return nil, errors.New("children item is required")
|
|
}
|
|
name, err := normalizeNodeName(item.GetName(), "children.name")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if _, exists := names[normalizedNodeNameKey(name)]; exists {
|
|
return nil, errors.New("children.name must be unique")
|
|
}
|
|
names[normalizedNodeNameKey(name)] = struct{}{}
|
|
imageIDs, err := normalizeNodeImageIDs(item.GetImageJson())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
statusValue, err := normalizeNodeStatus(item.Status)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
children = append(children, repository.CategoryRecord{NodeType: groupNodeType, Name: name, Level: 2, ImageIDs: imageIDs, SortNum: item.GetSortNum(), Status: statusValue})
|
|
}
|
|
return children, nil
|
|
}
|
|
|
|
func groupFieldUpdateFromRequest(req *productv1.UpdateGroupRequest) (*repository.CategoryFieldUpdate, error) {
|
|
if req.GetUpdateMask() == nil || len(req.GetUpdateMask().GetPaths()) == 0 {
|
|
return nil, errors.New("update_mask is required")
|
|
}
|
|
update := &repository.CategoryFieldUpdate{
|
|
ID: strings.TrimSpace(req.GetGroupId()),
|
|
ExpectedVersion: req.GetExpectedVersion(),
|
|
}
|
|
seen := make(map[string]struct{}, len(req.GetUpdateMask().GetPaths()))
|
|
for _, path := range req.GetUpdateMask().GetPaths() {
|
|
path = strings.TrimSpace(path)
|
|
if path == "" {
|
|
continue
|
|
}
|
|
if _, dup := seen[path]; dup {
|
|
return nil, fmt.Errorf("duplicate update path %q", path)
|
|
}
|
|
seen[path] = struct{}{}
|
|
switch path {
|
|
case "name":
|
|
if req.Name == nil {
|
|
return nil, errors.New("name is required when present in update_mask")
|
|
}
|
|
value, err := normalizeNodeName(*req.Name, "name")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
update.Name = &value
|
|
case "image_json", "image_ids":
|
|
raw := ""
|
|
if req.ImageJson != nil {
|
|
raw = *req.ImageJson
|
|
}
|
|
imageIDs, err := normalizeNodeImageIDs(raw)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
update.ImageIDs = &imageIDs
|
|
case "sort_num":
|
|
if req.SortNum == nil {
|
|
return nil, errors.New("sort_num is required when present in update_mask")
|
|
}
|
|
update.SortNum = req.SortNum
|
|
case "status":
|
|
if req.Status == nil {
|
|
return nil, errors.New("status is required when present in update_mask")
|
|
}
|
|
if *req.Status != 0 && *req.Status != 1 {
|
|
return nil, errors.New("status must be 0 or 1")
|
|
}
|
|
update.Status = req.Status
|
|
default:
|
|
return nil, fmt.Errorf("unsupported update path %q", path)
|
|
}
|
|
}
|
|
if update.Name == nil && update.ImageIDs == nil && update.SortNum == nil && update.Status == nil {
|
|
return nil, errors.New("at least one mutable field is required")
|
|
}
|
|
return update, nil
|
|
}
|
|
|
|
func normalizeNodeName(raw, field string) (string, error) {
|
|
name := strings.Join(strings.Fields(raw), " ")
|
|
if name == "" {
|
|
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())
|
|
|
|
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_SOLD_OUT {
|
|
return repository.ProductRecord{}, nil, errors.New("unsupported product status")
|
|
}
|
|
crossBorderJSON, err := crossBorderJSONFromProto(req.GetCrossBorderInfo())
|
|
if err != nil {
|
|
return repository.ProductRecord{}, nil, err
|
|
}
|
|
categoryPropertiesJSON, err := categoryPropertiesJSONFromProto(req.GetCategoryProperties())
|
|
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: "",
|
|
MemberDiscountEnabled: req.GetMemberDiscountEnabled(),
|
|
GoodsType: defaultInt32(req.GetGoodsType(), 1),
|
|
ServiceGuarantees: normalizeStringList(req.GetServiceGuarantees()),
|
|
Status: statusValue,
|
|
CrossBorderJSON: crossBorderJSON,
|
|
CategoryPropertiesJSON: categoryPropertiesJSON,
|
|
FreightChargeType: defaultInt32(req.GetFreightChargeType(), 1),
|
|
FreightFixedAmount: req.GetFreightFixedAmount(),
|
|
FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()),
|
|
SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1),
|
|
ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()),
|
|
PresaleType: req.GetPresaleType(),
|
|
DeliveryTimeType: req.GetDeliveryTimeType(),
|
|
DeliveryStartAt: timestampToTime(req.GetDeliveryStartAt()),
|
|
DeliveryAfterPaidDays: req.GetDeliveryAfterPaidDays(),
|
|
PurchaseLimitQuantity: req.GetPurchaseLimitQuantity(),
|
|
}
|
|
detailHTML, err := sanitizeDetailHTML(req.GetDetailHtml())
|
|
if err != nil {
|
|
return repository.ProductRecord{}, nil, err
|
|
}
|
|
record.DetailHTML = detailHTML
|
|
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
|
|
productCategoryIDs, err := normalizeProductCategoryIDs(req.GetProductCategoryIds())
|
|
if err != nil {
|
|
return repository.ProductRecord{}, nil, err
|
|
}
|
|
record.ProductCategoryIDs = productCategoryIDs
|
|
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")
|
|
}
|
|
if err := validateProductDeliveryConfiguration(&record); err != nil {
|
|
return repository.ProductRecord{}, nil, err
|
|
}
|
|
|
|
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":
|
|
sanitized, err := sanitizeDetailHTML(update.GetDetailHtml())
|
|
if err != nil {
|
|
return repository.ProductRecord{}, err
|
|
}
|
|
merged.DetailHTML = sanitized
|
|
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 "category_properties":
|
|
categoryPropertiesJSON, err := categoryPropertiesJSONFromProto(update.GetCategoryProperties())
|
|
if err != nil {
|
|
return repository.ProductRecord{}, err
|
|
}
|
|
merged.CategoryPropertiesJSON = categoryPropertiesJSON
|
|
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 "presale_type":
|
|
merged.PresaleType = update.GetPresaleType()
|
|
case "delivery_time_type":
|
|
merged.DeliveryTimeType = update.GetDeliveryTimeType()
|
|
case "delivery_start_at":
|
|
merged.DeliveryStartAt = timestampToTime(update.GetDeliveryStartAt())
|
|
case "delivery_after_paid_days":
|
|
merged.DeliveryAfterPaidDays = update.GetDeliveryAfterPaidDays()
|
|
case "purchase_limit_quantity":
|
|
merged.PurchaseLimitQuantity = update.GetPurchaseLimitQuantity()
|
|
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
|
|
case "product_category_ids":
|
|
productCategoryIDs, err := normalizeProductCategoryIDs(update.GetProductCategoryIds())
|
|
if err != nil {
|
|
return repository.ProductRecord{}, err
|
|
}
|
|
merged.ProductCategoryIDs = productCategoryIDs
|
|
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 productFreightChargeFromUpdateRequest(req *productv1.UpdateProductFreightChargeRequest) (spuNo string, freightChargeType int32, freightFixedAmount int64, freightTemplateID string, err error) {
|
|
spuNo = strings.TrimSpace(req.GetSpuNo())
|
|
if spuNo == "" {
|
|
return "", 0, 0, "", errors.New("spu_no is required")
|
|
}
|
|
if utf8.RuneCountInString(spuNo) > 100 {
|
|
return "", 0, 0, "", errors.New("spu_no must contain at most 100 characters")
|
|
}
|
|
freightChargeType = req.GetFreightChargeType()
|
|
switch freightChargeType {
|
|
case 1:
|
|
if req.FreightFixedAmount == nil {
|
|
return "", 0, 0, "", errors.New("freight_fixed_amount is required when freight_charge_type is 1")
|
|
}
|
|
if *req.FreightFixedAmount < 0 {
|
|
return "", 0, 0, "", errors.New("freight_fixed_amount must be greater than or equal to 0")
|
|
}
|
|
if req.FreightTemplateId != nil {
|
|
return "", 0, 0, "", errors.New("freight_template_id must be omitted when freight_charge_type is 1")
|
|
}
|
|
return spuNo, freightChargeType, *req.FreightFixedAmount, "", nil
|
|
case 2:
|
|
if req.FreightFixedAmount != nil {
|
|
return "", 0, 0, "", errors.New("freight_fixed_amount must be omitted when freight_charge_type is 2")
|
|
}
|
|
if req.FreightTemplateId == nil {
|
|
return "", 0, 0, "", errors.New("freight_template_id is required when freight_charge_type is 2")
|
|
}
|
|
freightTemplateID = strings.TrimSpace(*req.FreightTemplateId)
|
|
if freightTemplateID == "" {
|
|
return "", 0, 0, "", errors.New("freight_template_id is required when freight_charge_type is 2")
|
|
}
|
|
return spuNo, freightChargeType, 0, freightTemplateID, nil
|
|
default:
|
|
return "", 0, 0, "", errors.New("freight_charge_type must be 1 or 2")
|
|
}
|
|
}
|
|
|
|
func validateProductForUpdate(product *repository.ProductRecord) error {
|
|
if product == nil {
|
|
return errors.New("product is required")
|
|
}
|
|
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 validateProductDeliveryConfiguration(product)
|
|
}
|
|
|
|
func validateProductDeliveryConfiguration(product *repository.ProductRecord) error {
|
|
if product.PresaleType < 0 || product.PresaleType > 2 {
|
|
return errors.New("presale_type must be 0, 1, or 2")
|
|
}
|
|
if product.PurchaseLimitQuantity < 0 {
|
|
return errors.New("purchase_limit_quantity must be greater than or equal to 0")
|
|
}
|
|
switch product.DeliveryTimeType {
|
|
case 0:
|
|
product.DeliveryStartAt = nil
|
|
product.DeliveryAfterPaidDays = 0
|
|
case 1:
|
|
if product.DeliveryStartAt == nil {
|
|
return errors.New("delivery_start_at is required when delivery_time_type is 1")
|
|
}
|
|
product.DeliveryAfterPaidDays = 0
|
|
case 2:
|
|
if product.DeliveryAfterPaidDays <= 0 {
|
|
return errors.New("delivery_after_paid_days must be greater than 0 when delivery_time_type is 2")
|
|
}
|
|
product.DeliveryStartAt = nil
|
|
default:
|
|
return errors.New("delivery_time_type must be 0, 1, or 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 "weight_kg":
|
|
update.WeightKgSet = true
|
|
update.WeightKg = input.WeightKg
|
|
if update.WeightKg != nil && *update.WeightKg < 0 {
|
|
return repository.SKUUpdate{}, errors.New("weight_kg must be greater than or equal to 0")
|
|
}
|
|
case "barcode":
|
|
value := strings.TrimSpace(input.GetBarcode())
|
|
update.Barcode = &value
|
|
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.WeightKg != nil && *sku.WeightKg < 0 {
|
|
return repository.SKURecord{}, errors.New("weight_kg 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,
|
|
WeightKg: sku.WeightKg,
|
|
Barcode: strings.TrimSpace(sku.GetBarcode()),
|
|
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 categoryPropertiesJSONFromProto(properties *structpb.Struct) (string, error) {
|
|
if properties == nil {
|
|
return "{}", nil
|
|
}
|
|
raw, err := json.Marshal(properties.AsMap())
|
|
if err != nil {
|
|
return "", fmt.Errorf("marshal category_properties: %w", err)
|
|
}
|
|
return string(raw), nil
|
|
}
|
|
|
|
func categoryPropertiesProto(raw string) *structpb.Struct {
|
|
properties := make(map[string]any)
|
|
if strings.TrimSpace(raw) != "" {
|
|
if err := json.Unmarshal([]byte(raw), &properties); err != nil || properties == nil {
|
|
return &structpb.Struct{Fields: map[string]*structpb.Value{}}
|
|
}
|
|
}
|
|
result, err := structpb.NewStruct(properties)
|
|
if err != nil {
|
|
return &structpb.Struct{Fields: map[string]*structpb.Value{}}
|
|
}
|
|
return result
|
|
}
|
|
|
|
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 normalizeProductCategoryIDs(values []string) ([]string, error) {
|
|
if len(values) > 100 {
|
|
return nil, errors.New("product_category_ids must contain at most 100 items")
|
|
}
|
|
categoryIDs := 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("product_category_ids must not contain an empty id")
|
|
}
|
|
if _, err := normalizeCategoryID(categoryID, "product_category_ids"); err != nil {
|
|
return nil, err
|
|
}
|
|
if _, duplicate := seen[categoryID]; duplicate {
|
|
return nil, errors.New("product_category_ids must not contain duplicates")
|
|
}
|
|
seen[categoryID] = struct{}{}
|
|
categoryIDs = append(categoryIDs, categoryID)
|
|
}
|
|
return categoryIDs, 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 timePtrToTimestamp(value *time.Time) *timestamppb.Timestamp {
|
|
if value == nil {
|
|
return nil
|
|
}
|
|
return timestamppb.New(*value)
|
|
}
|
|
|
|
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,
|
|
WeightKg: sku.WeightKg,
|
|
Barcode: sku.Barcode,
|
|
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),
|
|
})
|
|
}
|
|
|
|
result := &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),
|
|
CategoryProperties: categoryPropertiesProto(product.CategoryPropertiesJSON),
|
|
FreightChargeType: product.FreightChargeType,
|
|
FreightFixedAmount: product.FreightFixedAmount,
|
|
FreightTemplateId: product.FreightTemplateID,
|
|
SaleTimeType: product.SaleTimeType,
|
|
ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime),
|
|
PresaleType: product.PresaleType,
|
|
DeliveryTimeType: product.DeliveryTimeType,
|
|
DeliveryStartAt: timePtrToTimestamp(product.DeliveryStartAt),
|
|
DeliveryAfterPaidDays: product.DeliveryAfterPaidDays,
|
|
PurchaseLimitQuantity: product.PurchaseLimitQuantity,
|
|
Version: product.Version,
|
|
DeletedAt: timePtrToMillisString(product.DeletedAt),
|
|
LeafCatalogCategoryIds: append([]string(nil), product.LeafCategoryIDs...),
|
|
GroupIds: append([]string(nil), product.GroupIDs...),
|
|
ProductCategoryIds: append([]string(nil), product.ProductCategoryIDs...),
|
|
}
|
|
for _, category := range product.ProductCategories {
|
|
item := &productv1.ProductCategorySummary{
|
|
ProductCategoryId: category.ID,
|
|
Name: category.Name,
|
|
Level: category.Level,
|
|
ParentCategoryId: category.ParentID,
|
|
ParentCategoryName: category.ParentName,
|
|
Path: make([]*productv1.ProductCategoryPathNode, 0, len(category.Path)),
|
|
}
|
|
for _, node := range category.Path {
|
|
item.Path = append(item.Path, &productv1.ProductCategoryPathNode{
|
|
ProductCategoryId: node.ID,
|
|
Name: node.Name,
|
|
Level: node.Level,
|
|
ParentCategoryId: node.ParentID,
|
|
})
|
|
}
|
|
result.ProductCategories = append(result.ProductCategories, item)
|
|
}
|
|
return result
|
|
}
|
|
|
|
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
|
|
result.PresaleType = record.Product.PresaleType
|
|
result.DeliveryTimeType = record.Product.DeliveryTimeType
|
|
result.DeliveryStartAt = timePtrToTimestamp(record.Product.DeliveryStartAt)
|
|
result.DeliveryAfterPaidDays = record.Product.DeliveryAfterPaidDays
|
|
result.PurchaseLimitQuantity = record.Product.PurchaseLimitQuantity
|
|
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
|
|
}
|
|
result := &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,
|
|
CategoryProperties: categoryPropertiesProto(product.CategoryPropertiesJSON),
|
|
PresaleType: product.PresaleType,
|
|
}
|
|
for _, category := range product.ProductCategories {
|
|
item := &productv1.ProductCategorySummary{
|
|
ProductCategoryId: category.ID,
|
|
Name: category.Name,
|
|
Level: category.Level,
|
|
ParentCategoryId: category.ParentID,
|
|
ParentCategoryName: category.ParentName,
|
|
Path: make([]*productv1.ProductCategoryPathNode, 0, len(category.Path)),
|
|
}
|
|
for _, node := range category.Path {
|
|
item.Path = append(item.Path, &productv1.ProductCategoryPathNode{
|
|
ProductCategoryId: node.ID,
|
|
Name: node.Name,
|
|
Level: node.Level,
|
|
ParentCategoryId: node.ParentID,
|
|
})
|
|
}
|
|
result.ProductCategories = append(result.ProductCategories, item)
|
|
}
|
|
for _, group := range product.Groups {
|
|
result.Groups = append(result.Groups, &productv1.ProductGroupSummary{GroupId: group.ID, Name: group.Name})
|
|
}
|
|
if product.Brand != nil {
|
|
result.Brand = &productv1.ProductBrandSummary{
|
|
BrandId: product.Brand.ID, Name: product.Brand.Name, Alias: product.Brand.Alias, BrandCode: product.Brand.BrandCode,
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
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
|
|
}
|
|
out := &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{},
|
|
}
|
|
for index := range category.Children {
|
|
out.Children = append(out.Children, toProtoCategoryNode(&category.Children[index]))
|
|
}
|
|
return out
|
|
}
|
|
|
|
func toProtoGroupNode(group *repository.CategoryRecord) *productv1.GroupNode {
|
|
if group == nil {
|
|
return nil
|
|
}
|
|
node := &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,
|
|
IsLeaf: group.IsLeaf,
|
|
Version: group.Version,
|
|
}
|
|
if group.IsLeaf {
|
|
node.Brands = make([]*productv1.GroupBrandProductSummary, 0, len(group.BrandProducts))
|
|
for _, brand := range group.BrandProducts {
|
|
node.Brands = append(node.Brands, &productv1.GroupBrandProductSummary{
|
|
BrandId: brand.BrandID,
|
|
BrandName: brand.BrandName,
|
|
})
|
|
protoBrand := node.Brands[len(node.Brands)-1]
|
|
protoBrand.Products = make([]*productv1.GroupBrandProduct, 0, len(brand.Products))
|
|
for _, product := range brand.Products {
|
|
protoBrand.Products = append(protoBrand.Products, &productv1.GroupBrandProduct{
|
|
ProductId: product.ProductID,
|
|
SpuNo: product.SPUNo,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
return node
|
|
}
|
|
|
|
func categoryImageIDsJSON(imageIDs []string) string {
|
|
encoded, err := json.Marshal(imageIDs)
|
|
if err != nil {
|
|
return "[]"
|
|
}
|
|
return string(encoded)
|
|
}
|