mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
440 lines
14 KiB
Go
440 lines
14 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"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/types/known/timestamppb"
|
|
|
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
|
|
|
"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)
|
|
)
|
|
|
|
// ProductServer implements productv1.ProductServiceServer.
|
|
type ProductServer struct {
|
|
productv1.UnimplementedProductServiceServer
|
|
|
|
repo *repository.ProductRepository
|
|
logger *zap.Logger
|
|
observer *observability.Observer
|
|
}
|
|
|
|
// NewProductServer constructs the gRPC product service handler.
|
|
func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger, observer *observability.Observer) *ProductServer {
|
|
if logger == nil {
|
|
logger = zap.NewNop()
|
|
}
|
|
if observer == nil {
|
|
observer = observability.NewNoop(logger)
|
|
}
|
|
return &ProductServer{
|
|
repo: repo,
|
|
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())
|
|
}
|
|
|
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes(
|
|
attribute.String("product.id", product.ID),
|
|
attribute.Int("product.sku_count", len(skus)),
|
|
))
|
|
defer dbSpan.End()
|
|
|
|
createdProduct, createdSKUs, 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("product_id", product.ID), zap.Error(err))
|
|
return nil, status.Errorf(codes.Internal, "create product: %v", err)
|
|
}
|
|
observability.IncProductsCreated()
|
|
|
|
return &productv1.CreateProductResponse{
|
|
Product: toProtoProduct(createdProduct, createdSKUs),
|
|
}, 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, skuMap, 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, skuMap[product.ID]))
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
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 productFromCreateRequest(req *productv1.CreateProductRequest) (repository.ProductRecord, []repository.SKURecord, error) {
|
|
productID := strings.TrimSpace(req.GetProductId())
|
|
if err := validatePositiveID(productID, "product_id"); err != nil {
|
|
return repository.ProductRecord{}, nil, err
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
record := repository.ProductRecord{
|
|
ID: productID,
|
|
SPUNo: spuNo,
|
|
Title: title,
|
|
SellingPoint: req.GetSellingPoint(),
|
|
Status: statusValue,
|
|
Attrs: map[string]any{},
|
|
}
|
|
|
|
skus := make([]repository.SKURecord, 0, len(req.GetSkus()))
|
|
for i, protoSKU := range req.GetSkus() {
|
|
sku, err := skuFromCreateInput(productID, 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(productID string, sku *productv1.CreateProductSKU) (repository.SKURecord, error) {
|
|
if sku == nil {
|
|
return repository.SKURecord{}, errors.New("sku is required")
|
|
}
|
|
|
|
skuID := strings.TrimSpace(sku.GetSkuId())
|
|
if err := validatePositiveID(skuID, "sku_id"); err != nil {
|
|
return repository.SKURecord{}, err
|
|
}
|
|
|
|
name := strings.TrimSpace(sku.GetName())
|
|
if name == "" {
|
|
return repository.SKURecord{}, errors.New("name 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 := strings.TrimSpace(sku.GetAttributesJson())
|
|
if attrs != "" && !json.Valid([]byte(attrs)) {
|
|
return repository.SKURecord{}, errors.New("attributes_json must be valid json")
|
|
}
|
|
|
|
return repository.SKURecord{
|
|
ID: skuID,
|
|
ProductID: productID,
|
|
Name: name,
|
|
Price: sku.GetPrice(),
|
|
AvailableQuantity: sku.GetAvailableQuantity(),
|
|
AttributesJSON: attrs,
|
|
}, nil
|
|
}
|
|
|
|
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,
|
|
DeletedAt: timestampOrNil(sku.DeletedAt),
|
|
CreatedAt: timestamppb.New(sku.CreatedAt),
|
|
UpdatedAt: timestamppb.New(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: timestamppb.New(product.CreatedAt),
|
|
UpdatedAt: timestamppb.New(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,
|
|
FreightChargeType: product.FreightChargeType,
|
|
FreightFixedAmount: product.FreightFixedAmount,
|
|
FreightTemplateId: product.FreightTemplateID,
|
|
SaleTimeType: product.SaleTimeType,
|
|
ScheduledSaleTime: timestampOrNil(product.ScheduledSaleTime),
|
|
DeletedAt: timestampOrNil(product.DeletedAt),
|
|
}
|
|
}
|
|
|
|
func toProtoCategoryProduct(product *repository.CategoryProductRecord, skus []repository.CategoryProductSKURecord) *productv1.CategoryProduct {
|
|
if product == nil {
|
|
return nil
|
|
}
|
|
protoSKUs := make([]*productv1.CategoryProductSKU, 0, len(skus))
|
|
for _, sku := range skus {
|
|
protoSKUs = append(protoSKUs, &productv1.CategoryProductSKU{
|
|
SkuId: sku.ID,
|
|
AvailableQuantity: sku.AvailableQuantity,
|
|
Price: sku.Price,
|
|
})
|
|
}
|
|
return &productv1.CategoryProduct{
|
|
UpdatedAt: timestamppb.New(product.UpdatedAt),
|
|
CreatedAt: timestamppb.New(product.CreatedAt),
|
|
Title: product.Title,
|
|
ProductId: product.ID,
|
|
SpuNo: product.SPUNo,
|
|
Status: product.Status,
|
|
ImageIds: product.ImageIDs,
|
|
Skus: protoSKUs,
|
|
}
|
|
}
|
|
|
|
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: timestamppb.New(inventory.CreatedAt),
|
|
UpdatedAt: timestamppb.New(inventory.UpdatedAt),
|
|
}
|
|
}
|
|
|
|
func timestampOrNil(value *time.Time) *timestamppb.Timestamp {
|
|
if value == nil {
|
|
return nil
|
|
}
|
|
return timestamppb.New(*value)
|
|
}
|
|
|
|
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: category.ImageJSON,
|
|
SortNum: category.SortNum,
|
|
Status: category.Status,
|
|
Children: []*productv1.CategoryNode{},
|
|
}
|
|
}
|