diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 0c688a5..e36ce03 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -124,6 +124,22 @@ type InventoryRecord struct { UpdatedAt time.Time } +// CartItemProductLookup identifies the SPU/SKU pair stored by one cart line. +// Line IDs are intentionally kept outside the repository because they belong to trade.cart_items. +type CartItemProductLookup struct { + ProductID string + SKUID string +} + +// CartItemProductRecord contains the current catalog facts for one cart lookup. +// A nil Product or SKU means the corresponding record is missing or soft deleted. +type CartItemProductRecord struct { + ProductID string + SKUID string + Product *ProductRecord + SKU *SKURecord +} + // SKUChangeMode selects how SKU input is applied during a product update. type SKUChangeMode int32 @@ -1240,6 +1256,66 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (* return product, skus[productID], nil } +// BatchGetCartItemProducts loads current catalog facts for cart lines in request order. +// It includes archived SKUs, but treats soft-deleted SPUs and SKUs as unavailable. +func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookups []CartItemProductLookup) ([]CartItemProductRecord, error) { + if len(lookups) == 0 { + return []CartItemProductRecord{}, nil + } + + productIDs := make([]string, 0, len(lookups)) + skuIDs := make([]string, 0, len(lookups)) + seenProductIDs := make(map[string]struct{}, len(lookups)) + seenSKUIDs := make(map[string]struct{}, len(lookups)) + for _, lookup := range lookups { + if _, err := parseID(lookup.ProductID, "product id"); err != nil { + return nil, err + } + if _, err := parseID(lookup.SKUID, "sku id"); err != nil { + return nil, err + } + if _, ok := seenProductIDs[lookup.ProductID]; !ok { + seenProductIDs[lookup.ProductID] = struct{}{} + productIDs = append(productIDs, lookup.ProductID) + } + if _, ok := seenSKUIDs[lookup.SKUID]; !ok { + seenSKUIDs[lookup.SKUID] = struct{}{} + skuIDs = append(skuIDs, lookup.SKUID) + } + } + + products, err := r.loadProductsByIDs(ctx, productIDs) + if err != nil { + return nil, err + } + skus, err := r.loadCartItemSKUsByIDs(ctx, skuIDs) + if err != nil { + return nil, err + } + + productsByID := make(map[string]*ProductRecord, len(products)) + for _, product := range products { + productsByID[product.ID] = product + } + skusByID := make(map[string]*SKURecord, len(skus)) + for index := range skus { + skusByID[skus[index].ID] = &skus[index] + } + + results := make([]CartItemProductRecord, 0, len(lookups)) + for _, lookup := range lookups { + result := CartItemProductRecord{ProductID: lookup.ProductID, SKUID: lookup.SKUID} + result.Product = productsByID[lookup.ProductID] + if result.Product != nil { + if sku := skusByID[lookup.SKUID]; sku != nil && sku.ProductID == lookup.ProductID { + result.SKU = sku + } + } + results = append(results, result) + } + return results, nil +} + // ListProducts loads paginated summaries for all non-deleted products. func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int32) ([]*CategoryProductRecord, int64, error) { if page < 1 { @@ -1881,6 +1957,74 @@ ORDER BY pi.created_at ASC return result, nil } +// loadCartItemSKUsByIDs loads current and archived SKU rows used by cart display. +// Soft-deleted rows remain excluded so they are represented as missing to callers. +func (r *ProductRepository) loadCartItemSKUsByIDs(ctx context.Context, skuIDs []string) ([]SKURecord, error) { + if len(skuIDs) == 0 { + return []SKURecord{}, nil + } + + placeholders := make([]string, len(skuIDs)) + args := make([]any, len(skuIDs)) + for i, id := range skuIDs { + parsed, err := parseID(id, "sku id") + if err != nil { + return nil, err + } + placeholders[i] = fmt.Sprintf("$%d", i+1) + args[i] = parsed + } + + query := fmt.Sprintf(` +SELECT pi.id, + pi.product_id, + pi.sku_no, + pi.name, + pi.price, + COALESCE(to_json(pi.image_ids)::text, '[]'), + pi.attributes, + pi.status, + pi.is_archived, + pi.archived_at, + pi.version, + pi.deleted_at, + pi.created_at, + pi.updated_at, + inv.id, + inv.sku_id, + inv.available_quantity, + inv.locked_quantity, + inv.sold_quantity, + inv.version, + inv.created_at, + inv.updated_at +FROM product.product_items pi +LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id +WHERE pi.id IN (%s) + AND pi.deleted_at IS NULL +ORDER BY pi.created_at ASC, pi.id ASC +`, strings.Join(placeholders, ", ")) + + rows, err := r.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, fmt.Errorf("query cart item skus: %w", err) + } + defer rows.Close() + + skus := make([]SKURecord, 0, len(skuIDs)) + for rows.Next() { + sku, err := scanSKU(rows) + if err != nil { + return nil, err + } + skus = append(skus, *sku) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate cart item skus: %w", err) + } + return skus, nil +} + type rowScanner interface { Scan(dest ...any) error } diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 800a1c8..97f6c5e 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -33,9 +33,10 @@ const ( categoryNodeType = int32(0) groupNodeType = int32(1) - defaultNodeStatus = int32(1) - maxNodeNameLength = 100 - maxProductsPerGroupRequest = 100 + defaultNodeStatus = int32(1) + maxNodeNameLength = 100 + maxProductsPerGroupRequest = 100 + maxCartItemProductBatchSize = 100 ) // ProductServer implements productv1.ProductServiceServer. @@ -149,6 +150,72 @@ func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProduc }, 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) { + 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) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("batch get cart item products failed", zap.Error(err)) + return nil, status.Errorf(codes.Internal, "batch get cart item products: %v", err) + } + if len(records) != len(req.GetItems()) { + err := fmt.Errorf("repository returned %d records for %d lookups", len(records), len(req.GetItems())) + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("batch get cart item products incomplete", zap.Error(err)) + return nil, status.Error(codes.Internal, "batch get cart item products returned incomplete data") + } + + items := make([]*productv1.CartItemProduct, 0, len(records)) + for index, record := range records { + items = append(items, toProtoCartItemProduct(req.GetItems()[index].GetLineId(), record)) + } + return &productv1.BatchGetCartItemProductResponse{Items: items}, nil +} + // UpdateProduct updates mutable SPU fields and optionally patches or replaces its SKU set. func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.UpdateProductRequest) (*productv1.UpdateProductResponse, error) { if req == nil || req.GetProductId() == "" { @@ -1277,6 +1344,35 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco } } +func toProtoCartItemProduct(lineID string, record repository.CartItemProductRecord) *productv1.CartItemProduct { + result := &productv1.CartItemProduct{ + LineId: lineID, + ProductId: record.ProductID, + SkuId: record.SKUID, + SpuStatus: productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED, + } + if record.Product == nil { + return result + } + + result.ProductName = record.Product.Title + result.ServiceGuarantees = record.Product.ServiceGuarantees + result.SpuImageIds = record.Product.ImageIDs + result.SpuStatus = record.Product.Status + if record.SKU == nil { + return result + } + + result.SkuName = record.SKU.Name + result.Price = record.SKU.Price + result.SkuImageIds = record.SKU.ImageIDs + result.SkuAvailableQuantity = record.SKU.AvailableQuantity + 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