mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
873 lines
28 KiB
Go
873 lines
28 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"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/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(0)
|
|
groupNodeType = int32(1)
|
|
|
|
defaultNodeStatus = int32(1)
|
|
maxNodeNameLength = 100
|
|
)
|
|
|
|
// ProductServer implements productv1.ProductServiceServer.
|
|
type ProductServer struct {
|
|
productv1.UnimplementedProductServiceServer
|
|
|
|
repo *repository.ProductRepository
|
|
idgen *idgen.Generator
|
|
logger *zap.Logger
|
|
observer *observability.Observer
|
|
}
|
|
|
|
// NewProductServer constructs the gRPC product service handler.
|
|
func NewProductServer(repo *repository.ProductRepository, idGenerator *idgen.Generator, logger *zap.Logger, observer *observability.Observer) *ProductServer {
|
|
if logger == nil {
|
|
logger = zap.NewNop()
|
|
}
|
|
if observer == nil {
|
|
observer = observability.NewNoop(logger)
|
|
}
|
|
return &ProductServer{
|
|
repo: repo,
|
|
idgen: idGenerator,
|
|
logger: logger,
|
|
observer: observer,
|
|
}
|
|
}
|
|
|
|
// CreateProduct creates a product SPU and optional SKU list.
|
|
func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.CreateProductRequest) (*productv1.CreateProductResponse, error) {
|
|
if req == nil {
|
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
|
}
|
|
|
|
product, skus, err := productFromCreateRequest(req)
|
|
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")
|
|
}
|
|
product.ID = s.idgen.NextString()
|
|
for i := range skus {
|
|
skus[i].ID = s.idgen.NextString()
|
|
skus[i].Inventory = &repository.InventoryRecord{ID: s.idgen.NextString()}
|
|
}
|
|
if product.LeafCategoryID != "" {
|
|
product.CategoryBindingID = s.idgen.NextString()
|
|
}
|
|
|
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes(
|
|
attribute.String("product.spu_no", product.SPUNo),
|
|
attribute.Int("product.sku_count", len(skus)),
|
|
))
|
|
defer dbSpan.End()
|
|
|
|
createdProduct, _, err := s.repo.CreateProductWithSKUs(dbCtx, product, skus)
|
|
if err != nil {
|
|
dbSpan.RecordError(err)
|
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
|
s.observer.Logger(ctx).Error("create product failed", zap.String("spu_no", product.SPUNo), zap.Error(err))
|
|
if errors.Is(err, repository.ErrDuplicateSPUNo) {
|
|
return nil, status.Errorf(codes.AlreadyExists, "spu_no already exists: %s", product.SPUNo)
|
|
}
|
|
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) {
|
|
if req == nil || 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())
|
|
if errors.Is(err, repository.ErrProductNotFound) {
|
|
dbSpan.SetStatus(otelcodes.Error, "product not found")
|
|
return nil, status.Error(codes.NotFound, "product not found")
|
|
}
|
|
if err != nil {
|
|
dbSpan.RecordError(err)
|
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
|
s.observer.Logger(ctx).Error("get product failed", zap.String("product_id", req.GetProductId()), zap.Error(err))
|
|
return nil, status.Errorf(codes.Internal, "get product: %v", err)
|
|
}
|
|
|
|
return &productv1.GetProductResponse{
|
|
Product: toProtoProduct(product, skus),
|
|
}, nil
|
|
}
|
|
|
|
// ListCategoryProducts returns a paginated product list under a category.
|
|
func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1.ListCategoryProductsRequest) (*productv1.ListCategoryProductsResponse, error) {
|
|
if req == nil || 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")
|
|
}
|
|
|
|
page := req.GetPage()
|
|
if page <= 0 {
|
|
page = 1
|
|
}
|
|
pageSize := req.GetPageSize()
|
|
if pageSize <= 0 {
|
|
pageSize = defaultPageSize
|
|
}
|
|
if pageSize > maxPageSize {
|
|
pageSize = maxPageSize
|
|
}
|
|
|
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_by_category", trace.WithAttributes(
|
|
attribute.String("category.id", req.GetCategoryId()),
|
|
attribute.Int("page", int(page)),
|
|
attribute.Int("page_size", int(pageSize)),
|
|
))
|
|
defer dbSpan.End()
|
|
|
|
products, total, err := s.repo.ListCategoryProducts(dbCtx, req.GetCategoryId(), page, pageSize)
|
|
if err != nil {
|
|
dbSpan.RecordError(err)
|
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
|
s.observer.Logger(ctx).Error("list category products failed", zap.String("category_id", req.GetCategoryId()), zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err))
|
|
return nil, status.Errorf(codes.Internal, "list category products: %v", err)
|
|
}
|
|
dbSpan.SetAttributes(attribute.Int64("product.total", total), attribute.Int("product.result_count", len(products)))
|
|
observability.IncCategoryProductLists()
|
|
|
|
protoProducts := make([]*productv1.CategoryProduct, 0, len(products))
|
|
for _, product := range products {
|
|
protoProducts = append(protoProducts, toProtoCategoryProduct(product))
|
|
}
|
|
|
|
return &productv1.ListCategoryProductsResponse{
|
|
Products: protoProducts,
|
|
Page: page,
|
|
PageSize: pageSize,
|
|
Total: total,
|
|
TotalPages: totalPages(total, pageSize),
|
|
}, nil
|
|
}
|
|
|
|
// ListCategoryTree returns product category nodes as a parent-child hierarchy.
|
|
func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.ListCategoryTreeRequest) (*productv1.ListCategoryTreeResponse, error) {
|
|
onlyVisible := false
|
|
if req != nil {
|
|
onlyVisible = req.GetOnlyVisible()
|
|
}
|
|
|
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_category_tree", trace.WithAttributes(
|
|
attribute.Bool("category.only_visible", onlyVisible),
|
|
))
|
|
defer dbSpan.End()
|
|
|
|
categories, err := s.repo.ListCategoryTreeNodes(dbCtx, onlyVisible)
|
|
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()
|
|
|
|
return &productv1.ListCategoryTreeResponse{
|
|
Categories: buildCategoryTree(categories),
|
|
}, nil
|
|
}
|
|
|
|
// CreateCategoryTree creates a top-level category and optional second-level categories.
|
|
func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.CreateCategoryTreeRequest) (*productv1.CreateCategoryTreeResponse, error) {
|
|
if req == nil {
|
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
|
}
|
|
if s.idgen == nil {
|
|
return nil, status.Error(codes.Internal, "id generator is not configured")
|
|
}
|
|
|
|
parent, children, err := categoryTreeFromCreateRequest(req)
|
|
if err != nil {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
parent.ID = s.idgen.NextString()
|
|
for i := range children {
|
|
children[i].ID = s.idgen.NextString()
|
|
}
|
|
|
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create_category_tree", trace.WithAttributes(
|
|
attribute.String("category.name", parent.Name),
|
|
attribute.Int("category.child_count", len(children)),
|
|
))
|
|
defer dbSpan.End()
|
|
|
|
createdParent, createdChildren, err := s.repo.CreateCategoryTree(dbCtx, parent, children)
|
|
if err != nil {
|
|
dbSpan.RecordError(err)
|
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
|
s.observer.Logger(ctx).Error("create category tree failed", zap.String("category_name", parent.Name), zap.Error(err))
|
|
return nil, status.Errorf(codes.Internal, "create category tree: %v", err)
|
|
}
|
|
|
|
category := toProtoCategoryNode(createdParent)
|
|
for _, child := range createdChildren {
|
|
category.Children = append(category.Children, toProtoCategoryNode(child))
|
|
}
|
|
|
|
return &productv1.CreateCategoryTreeResponse{
|
|
Category: category,
|
|
}, nil
|
|
}
|
|
|
|
// CreateGroup creates a top-level product group.
|
|
func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGroupRequest) (*productv1.CreateGroupResponse, error) {
|
|
if req == nil {
|
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
|
}
|
|
if s.idgen == nil {
|
|
return nil, status.Error(codes.Internal, "id generator is not configured")
|
|
}
|
|
|
|
group, err := groupFromCreateRequest(req)
|
|
if err != nil {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
group.ID = s.idgen.NextString()
|
|
|
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create_group", trace.WithAttributes(
|
|
attribute.String("group.name", group.Name),
|
|
))
|
|
defer dbSpan.End()
|
|
|
|
createdGroup, err := s.repo.CreateCategoryNode(dbCtx, group)
|
|
if err != nil {
|
|
dbSpan.RecordError(err)
|
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
|
s.observer.Logger(ctx).Error("create group failed", zap.String("group_name", group.Name), zap.Error(err))
|
|
return nil, status.Errorf(codes.Internal, "create group: %v", err)
|
|
}
|
|
|
|
return &productv1.CreateGroupResponse{
|
|
Group: toProtoGroupNode(createdGroup),
|
|
}, nil
|
|
}
|
|
|
|
// ListGroups returns product groups.
|
|
func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroupsRequest) (*productv1.ListGroupsResponse, error) {
|
|
onlyVisible := false
|
|
if req != nil {
|
|
onlyVisible = req.GetOnlyVisible()
|
|
}
|
|
|
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_groups", trace.WithAttributes(
|
|
attribute.Bool("group.only_visible", onlyVisible),
|
|
))
|
|
defer dbSpan.End()
|
|
|
|
groups, err := s.repo.ListGroupNodes(dbCtx, onlyVisible)
|
|
if err != nil {
|
|
dbSpan.RecordError(err)
|
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
|
s.observer.Logger(ctx).Error("list groups failed", zap.Bool("only_visible", onlyVisible), zap.Error(err))
|
|
return nil, status.Errorf(codes.Internal, "list groups: %v", err)
|
|
}
|
|
dbSpan.SetAttributes(attribute.Int("group.result_count", len(groups)))
|
|
|
|
protoGroups := make([]*productv1.GroupNode, 0, len(groups))
|
|
for _, group := range groups {
|
|
protoGroups = append(protoGroups, toProtoGroupNode(group))
|
|
}
|
|
|
|
return &productv1.ListGroupsResponse{
|
|
Groups: protoGroups,
|
|
}, nil
|
|
}
|
|
|
|
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,
|
|
}
|
|
|
|
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[childName]; exists {
|
|
return repository.CategoryRecord{}, nil, errors.New("children.name must be unique")
|
|
}
|
|
childNames[childName] = struct{}{}
|
|
|
|
childImageIDs, err := normalizeNodeImageIDs(child.GetImageJson())
|
|
if err != nil {
|
|
return repository.CategoryRecord{}, nil, err
|
|
}
|
|
childStatus, err := normalizeNodeStatus(child.Status)
|
|
if err != nil {
|
|
return repository.CategoryRecord{}, nil, err
|
|
}
|
|
|
|
children = append(children, repository.CategoryRecord{
|
|
NodeType: categoryNodeType,
|
|
Name: childName,
|
|
Level: 2,
|
|
ImageIDs: childImageIDs,
|
|
SortNum: child.GetSortNum(),
|
|
Status: childStatus,
|
|
})
|
|
}
|
|
|
|
return parent, children, nil
|
|
}
|
|
|
|
func groupFromCreateRequest(req *productv1.CreateGroupRequest) (repository.CategoryRecord, error) {
|
|
name, err := normalizeNodeName(req.GetName(), "name")
|
|
if err != nil {
|
|
return repository.CategoryRecord{}, err
|
|
}
|
|
imageIDs, err := normalizeNodeImageIDs(req.GetImageJson())
|
|
if err != nil {
|
|
return repository.CategoryRecord{}, err
|
|
}
|
|
statusValue, err := normalizeNodeStatus(req.Status)
|
|
if err != nil {
|
|
return repository.CategoryRecord{}, err
|
|
}
|
|
|
|
return repository.CategoryRecord{
|
|
NodeType: groupNodeType,
|
|
Name: name,
|
|
Level: 1,
|
|
ImageIDs: imageIDs,
|
|
SortNum: req.GetSortNum(),
|
|
Status: statusValue,
|
|
}, nil
|
|
}
|
|
|
|
func normalizeNodeName(raw, field string) (string, error) {
|
|
name := strings.TrimSpace(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 normalizeNodeImageIDs(raw string) ([]string, error) {
|
|
raw = strings.TrimSpace(raw)
|
|
if raw == "" {
|
|
return []string{}, nil
|
|
}
|
|
var imageIDs []string
|
|
if err := json.Unmarshal([]byte(raw), &imageIDs); err != nil {
|
|
return nil, errors.New("image_json must be a json string array")
|
|
}
|
|
return normalizeStringList(imageIDs), nil
|
|
}
|
|
|
|
func normalizeNodeStatus(statusValue *int32) (int32, error) {
|
|
if statusValue == nil {
|
|
return defaultNodeStatus, nil
|
|
}
|
|
if *statusValue != 0 && *statusValue != 1 {
|
|
return 0, errors.New("status must be 0 or 1")
|
|
}
|
|
return *statusValue, nil
|
|
}
|
|
|
|
func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.ProductRecord, []repository.SKURecord, error) {
|
|
spuNo := strings.TrimSpace(req.GetSpuNo())
|
|
if spuNo == "" {
|
|
return repository.ProductRecord{}, nil, errors.New("spu_no is required")
|
|
}
|
|
|
|
title := strings.TrimSpace(req.GetTitle())
|
|
if title == "" {
|
|
return repository.ProductRecord{}, nil, errors.New("title is required")
|
|
}
|
|
|
|
statusValue := req.GetStatus()
|
|
if statusValue == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED {
|
|
statusValue = productv1.ProductStatus_PRODUCT_STATUS_DRAFT
|
|
}
|
|
crossBorderJSON, err := crossBorderJSONFromProto(req.GetCrossBorderInfo())
|
|
if err != nil {
|
|
return repository.ProductRecord{}, nil, err
|
|
}
|
|
|
|
record := repository.ProductRecord{
|
|
SPUNo: spuNo,
|
|
Title: title,
|
|
SellingPoint: strings.TrimSpace(req.GetSellingPoint()),
|
|
BrandID: strings.TrimSpace(req.GetBrandId()),
|
|
SupplierID: strings.TrimSpace(req.GetSupplierId()),
|
|
ImageIDs: normalizeStringList(req.GetImageIds()),
|
|
DetailHTML: req.GetDetailHtml(),
|
|
MemberDiscountEnabled: req.GetMemberDiscountEnabled(),
|
|
GoodsType: defaultInt32(req.GetGoodsType(), 1),
|
|
ServiceGuarantees: normalizeStringList(req.GetServiceGuarantees()),
|
|
Status: statusValue,
|
|
CrossBorderJSON: crossBorderJSON,
|
|
FreightChargeType: defaultInt32(req.GetFreightChargeType(), 1),
|
|
FreightFixedAmount: req.GetFreightFixedAmount(),
|
|
FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()),
|
|
SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1),
|
|
ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()),
|
|
LeafCategoryID: strings.TrimSpace(req.GetLeafCategoryId()),
|
|
}
|
|
if record.FreightFixedAmount < 0 {
|
|
return repository.ProductRecord{}, nil, errors.New("freight_fixed_amount must be greater than or equal to 0")
|
|
}
|
|
if record.GoodsType < 1 || record.GoodsType > 4 {
|
|
return repository.ProductRecord{}, nil, errors.New("goods_type must be between 1 and 4")
|
|
}
|
|
if record.FreightChargeType < 1 || record.FreightChargeType > 2 {
|
|
return repository.ProductRecord{}, nil, errors.New("freight_charge_type must be 1 or 2")
|
|
}
|
|
if record.FreightChargeType == 2 && record.FreightTemplateID == "" {
|
|
return repository.ProductRecord{}, nil, errors.New("freight_template_id is required when freight_charge_type is 2")
|
|
}
|
|
if record.SaleTimeType < 1 || record.SaleTimeType > 2 {
|
|
return repository.ProductRecord{}, nil, errors.New("sale_time_type must be 1 or 2")
|
|
}
|
|
if record.SaleTimeType == 2 && record.ScheduledSaleTime == nil {
|
|
return repository.ProductRecord{}, nil, errors.New("scheduled_sale_time is required when sale_time_type is 2")
|
|
}
|
|
|
|
skus := make([]repository.SKURecord, 0, len(req.GetSkus()))
|
|
for i, protoSKU := range req.GetSkus() {
|
|
sku, err := skuFromCreateInput(protoSKU)
|
|
if err != nil {
|
|
return repository.ProductRecord{}, nil, errors.New("skus[" + strconv.Itoa(i) + "]: " + err.Error())
|
|
}
|
|
skus = append(skus, sku)
|
|
}
|
|
|
|
return record, skus, nil
|
|
}
|
|
|
|
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.GetAvailableQuantity() < 0 {
|
|
return repository.SKURecord{}, errors.New("available_quantity must be greater than or equal to 0")
|
|
}
|
|
|
|
attrs, name, err := buildSKUAttributesAndName(sku)
|
|
if err != nil {
|
|
return repository.SKURecord{}, err
|
|
}
|
|
statusValue := sku.GetStatus()
|
|
if statusValue == 0 {
|
|
statusValue = 1
|
|
}
|
|
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(),
|
|
ImageIDs: normalizeStringList(sku.GetImageIds()),
|
|
AvailableQuantity: sku.GetAvailableQuantity(),
|
|
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, EmitUnpopulated: true}
|
|
raw, err := marshalOptions.Marshal(info)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(raw), nil
|
|
}
|
|
|
|
func toProtoCrossBorderInfo(raw string) *productv1.CrossBorderInfo {
|
|
if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "{}" {
|
|
return nil
|
|
}
|
|
info := &productv1.CrossBorderInfo{}
|
|
unmarshalOptions := protojson.UnmarshalOptions{DiscardUnknown: true}
|
|
if err := unmarshalOptions.Unmarshal([]byte(raw), info); err != nil {
|
|
return nil
|
|
}
|
|
return info
|
|
}
|
|
|
|
func normalizeStringList(values []string) []string {
|
|
if len(values) == 0 {
|
|
return []string{}
|
|
}
|
|
out := make([]string, 0, len(values))
|
|
for _, value := range values {
|
|
trimmed := strings.TrimSpace(value)
|
|
if trimmed != "" {
|
|
out = append(out, trimmed)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
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 {
|
|
millis := ""
|
|
if value != nil {
|
|
millis = timeToMillisString(*value)
|
|
}
|
|
return &millis
|
|
}
|
|
|
|
func validatePositiveID(raw, field string) error {
|
|
if raw == "" {
|
|
return errors.New(field + " is required")
|
|
}
|
|
id, err := strconv.ParseInt(raw, 10, 64)
|
|
if err != nil || id <= 0 {
|
|
return errors.New(field + " must be a positive snowflake id")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func toProtoProduct(product *repository.ProductRecord, skus []repository.SKURecord) *productv1.Product {
|
|
if product == nil {
|
|
return nil
|
|
}
|
|
|
|
protoSKUs := make([]*productv1.SKU, 0, len(skus))
|
|
for _, sku := range skus {
|
|
protoSKUs = append(protoSKUs, &productv1.SKU{
|
|
SkuId: sku.ID,
|
|
ProductId: sku.ProductID,
|
|
SkuNo: sku.SKUNo,
|
|
Name: sku.Name,
|
|
Price: sku.Price,
|
|
AvailableQuantity: sku.AvailableQuantity,
|
|
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,
|
|
DeletedAt: timePtrToMillisString(sku.DeletedAt),
|
|
CreatedAt: timeToMillisString(sku.CreatedAt),
|
|
UpdatedAt: timeToMillisString(sku.UpdatedAt),
|
|
Inventory: toProtoInventory(sku.Inventory),
|
|
})
|
|
}
|
|
|
|
return &productv1.Product{
|
|
ProductId: product.ID,
|
|
SpuNo: product.SPUNo,
|
|
Title: product.Title,
|
|
SellingPoint: product.SellingPoint,
|
|
Status: product.Status,
|
|
Skus: protoSKUs,
|
|
CreatedAt: timeToMillisString(product.CreatedAt),
|
|
UpdatedAt: timeToMillisString(product.UpdatedAt),
|
|
ImageIds: product.ImageIDs,
|
|
BrandId: product.BrandID,
|
|
SupplierId: product.SupplierID,
|
|
DetailHtml: product.DetailHTML,
|
|
MemberDiscountEnabled: product.MemberDiscountEnabled,
|
|
GoodsType: product.GoodsType,
|
|
ServiceGuarantees: product.ServiceGuarantees,
|
|
CrossBorderJson: product.CrossBorderJSON,
|
|
CrossBorderInfo: toProtoCrossBorderInfo(product.CrossBorderJSON),
|
|
FreightChargeType: product.FreightChargeType,
|
|
FreightFixedAmount: product.FreightFixedAmount,
|
|
FreightTemplateId: product.FreightTemplateID,
|
|
SaleTimeType: product.SaleTimeType,
|
|
ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime),
|
|
DeletedAt: timePtrToMillisString(product.DeletedAt),
|
|
}
|
|
}
|
|
|
|
func toProtoCategoryProduct(product *repository.CategoryProductRecord) *productv1.CategoryProduct {
|
|
if product == nil {
|
|
return nil
|
|
}
|
|
return &productv1.CategoryProduct{
|
|
UpdatedAt: timeToMillisString(product.UpdatedAt),
|
|
CreatedAt: timeToMillisString(product.CreatedAt),
|
|
Title: product.Title,
|
|
ProductId: product.ID,
|
|
SpuNo: product.SPUNo,
|
|
Status: product.Status,
|
|
ImageIds: product.ImageIDs,
|
|
Price: product.Price,
|
|
SoldQuantity: product.SoldQuantity,
|
|
}
|
|
}
|
|
|
|
func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductItemInventory {
|
|
if inventory == nil {
|
|
return nil
|
|
}
|
|
return &productv1.ProductItemInventory{
|
|
InventoryId: inventory.ID,
|
|
SkuId: inventory.SKUID,
|
|
AvailableQuantity: inventory.AvailableQuantity,
|
|
LockedQuantity: inventory.LockedQuantity,
|
|
SoldQuantity: inventory.SoldQuantity,
|
|
CreatedAt: timeToMillisString(inventory.CreatedAt),
|
|
UpdatedAt: timeToMillisString(inventory.UpdatedAt),
|
|
}
|
|
}
|
|
|
|
func buildCategoryTree(categories []*repository.CategoryRecord) []*productv1.CategoryNode {
|
|
nodes := make(map[string]*productv1.CategoryNode, len(categories))
|
|
records := make(map[string]*repository.CategoryRecord, len(categories))
|
|
orderedIDs := make([]string, 0, len(categories))
|
|
|
|
for _, category := range categories {
|
|
if category == nil || category.ID == "" {
|
|
continue
|
|
}
|
|
nodes[category.ID] = toProtoCategoryNode(category)
|
|
records[category.ID] = category
|
|
orderedIDs = append(orderedIDs, category.ID)
|
|
}
|
|
|
|
roots := make([]*productv1.CategoryNode, 0)
|
|
for _, id := range orderedIDs {
|
|
node := nodes[id]
|
|
record := records[id]
|
|
if node == nil || record == nil {
|
|
continue
|
|
}
|
|
|
|
parentID := record.ParentID
|
|
parent, parentExists := nodes[parentID]
|
|
parentRecord := records[parentID]
|
|
if parentID == "" || !parentExists || parentRecord == nil || parentID == id || parentRecord.Level >= record.Level {
|
|
roots = append(roots, node)
|
|
continue
|
|
}
|
|
|
|
parent.Children = append(parent.Children, node)
|
|
}
|
|
|
|
return roots
|
|
}
|
|
|
|
func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.CategoryNode {
|
|
if category == nil {
|
|
return nil
|
|
}
|
|
return &productv1.CategoryNode{
|
|
CategoryId: category.ID,
|
|
NodeType: category.NodeType,
|
|
Name: category.Name,
|
|
ParentId: category.ParentID,
|
|
Level: category.Level,
|
|
ImageJson: categoryImageIDsJSON(category.ImageIDs),
|
|
SortNum: category.SortNum,
|
|
Status: category.Status,
|
|
Children: []*productv1.CategoryNode{},
|
|
}
|
|
}
|
|
|
|
func toProtoGroupNode(group *repository.CategoryRecord) *productv1.GroupNode {
|
|
if group == nil {
|
|
return nil
|
|
}
|
|
return &productv1.GroupNode{
|
|
GroupId: group.ID,
|
|
NodeType: group.NodeType,
|
|
Name: group.Name,
|
|
ParentId: group.ParentID,
|
|
Level: group.Level,
|
|
ImageJson: categoryImageIDsJSON(group.ImageIDs),
|
|
SortNum: group.SortNum,
|
|
Status: group.Status,
|
|
}
|
|
}
|
|
|
|
func categoryImageIDsJSON(imageIDs []string) string {
|
|
encoded, err := json.Marshal(imageIDs)
|
|
if err != nil {
|
|
return "[]"
|
|
}
|
|
return string(encoded)
|
|
}
|