ids-svc-product/internal/repository/product_repository.go

1473 lines
39 KiB
Go

package repository
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v5/pgconn"
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
)
// ErrProductNotFound is returned when a product does not exist.
var ErrProductNotFound = errors.New("product not found")
// ErrSKUNotFound is returned when a SKU does not exist.
var ErrSKUNotFound = errors.New("sku not found")
// ErrDuplicateSPUNo is returned when a non-deleted product already uses the SPU number.
var ErrDuplicateSPUNo = errors.New("spu_no already exists")
// ProductRecord is the persistence model for product.products (SPU).
type ProductRecord struct {
ID string
SPUNo string
Title string
SellingPoint string
BrandID string
SupplierID string
ImageIDs []string
DetailHTML string
MemberDiscountEnabled bool
GoodsType int32
ServiceGuarantees []string
Status productv1.ProductStatus
Attrs map[string]any
CrossBorderJSON string
FreightChargeType int32
FreightFixedAmount int64
FreightTemplateID string
SaleTimeType int32
ScheduledSaleTime *time.Time
LeafCategoryID string
CategoryBindingID string
DeletedAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
// SKURecord is the persistence model for product.product_items.
type SKURecord struct {
ID string
ProductID string
SKUNo string
Name string
Price int64
ImageIDs []string
AvailableQuantity int32
LockedQuantity int32
SoldQuantity int32
AttributesJSON string
K1 string
V1 string
K2 string
V2 string
K3 string
V3 string
Status int32
DeletedAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
Inventory *InventoryRecord
}
// InventoryRecord is the persistence model for product.product_item_inventory.
type InventoryRecord struct {
ID string
SKUID string
AvailableQuantity int32
LockedQuantity int32
SoldQuantity int32
CreatedAt time.Time
UpdatedAt time.Time
}
// CategoryProductRecord is the product summary returned by category product lists.
type CategoryProductRecord struct {
ID string
SPUNo string
Title string
Status productv1.ProductStatus
ImageIDs []string
Price int64
SoldQuantity int64
CreatedAt time.Time
UpdatedAt time.Time
}
// CategoryRecord is the persistence model for product.product_category.
type CategoryRecord struct {
ID string
NodeType int32
Name string
ParentID string
Level int32
ImageJSON string
SortNum int32
Status int32
}
// ProductRepository provides CRUD access to product tables only [ARC-PROD-001].
type ProductRepository struct {
db *sql.DB
}
// NewProductRepository creates a repository backed by the given database pool.
func NewProductRepository(db *sql.DB) *ProductRepository {
return &ProductRepository{db: db}
}
// EnsureSchema adds the SKU table when missing; products is provisioned by infra init-scripts.
func (r *ProductRepository) EnsureSchema(ctx context.Context) error {
const ddl = `
ALTER TABLE product.products
ALTER COLUMN id DROP DEFAULT;
ALTER TABLE product.product_category_bindings
ALTER COLUMN id DROP DEFAULT;
CREATE TABLE IF NOT EXISTS product.product_items (
id BIGINT PRIMARY KEY,
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
sku_no VARCHAR(100),
name VARCHAR(256) NOT NULL,
price BIGINT NOT NULL CHECK (price >= 0),
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
attributes JSONB NOT NULL DEFAULT '{}',
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
deleted_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS product.product_item_inventory (
id BIGINT PRIMARY KEY,
sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE,
spu_no VARCHAR(100),
sku_no VARCHAR(100),
available_quantity INTEGER NOT NULL DEFAULT 0 CHECK (available_quantity >= 0),
locked_quantity INTEGER NOT NULL DEFAULT 0 CHECK (locked_quantity >= 0),
sold_quantity INTEGER NOT NULL DEFAULT 0 CHECK (sold_quantity >= 0),
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id)
);
ALTER TABLE product.product_items
ALTER COLUMN id DROP DEFAULT;
ALTER TABLE product.product_items
ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[];
CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL;
`
if _, err := r.db.ExecContext(ctx, ddl); err != nil {
return fmt.Errorf("ensure product tables: %w", err)
}
return nil
}
// CreateProduct inserts a new SPU row.
func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRecord) error {
attrs, err := productCrossBorderJSON(product)
if err != nil {
return err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin create product: %w", err)
}
defer tx.Rollback()
if _, err := insertProduct(ctx, tx, product, attrs); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit create product: %w", err)
}
return nil
}
// CreateProductWithSKUs inserts an SPU and its optional SKU list in one transaction.
func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product ProductRecord, skus []SKURecord) (*ProductRecord, []SKURecord, error) {
attrs, err := productCrossBorderJSON(product)
if err != nil {
return nil, nil, err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, nil, fmt.Errorf("begin create product: %w", err)
}
defer tx.Rollback()
createdProduct, err := insertProduct(ctx, tx, product, attrs)
if err != nil {
return nil, nil, err
}
createdSKUs := make([]SKURecord, 0, len(skus))
for _, sku := range skus {
createdSKU, err := insertSKU(ctx, tx, createdProduct.ID, sku)
if err != nil {
return nil, nil, err
}
createdSKUs = append(createdSKUs, *createdSKU)
}
if product.LeafCategoryID != "" {
if err := insertCategoryBinding(ctx, tx, product.CategoryBindingID, createdProduct.ID, product.LeafCategoryID); err != nil {
return nil, nil, err
}
}
if err := tx.Commit(); err != nil {
return nil, nil, fmt.Errorf("commit create product: %w", err)
}
return createdProduct, createdSKUs, nil
}
// CreateCategoryTree inserts a top-level category and its optional child categories in one transaction.
func (r *ProductRepository) CreateCategoryTree(ctx context.Context, parent CategoryRecord, children []CategoryRecord) (*CategoryRecord, []*CategoryRecord, error) {
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, nil, fmt.Errorf("begin create category tree: %w", err)
}
defer tx.Rollback()
createdParent, err := insertCategoryNode(ctx, tx, parent)
if err != nil {
return nil, nil, err
}
createdChildren := make([]*CategoryRecord, 0, len(children))
for _, child := range children {
child.NodeType = createdParent.NodeType
child.ParentID = createdParent.ID
child.Level = createdParent.Level + 1
createdChild, err := insertCategoryNode(ctx, tx, child)
if err != nil {
return nil, nil, err
}
createdChildren = append(createdChildren, createdChild)
}
if err := tx.Commit(); err != nil {
return nil, nil, fmt.Errorf("commit create category tree: %w", err)
}
return createdParent, createdChildren, nil
}
// CreateCategoryNode inserts a single product category/group node.
func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category CategoryRecord) (*CategoryRecord, error) {
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin create category node: %w", err)
}
defer tx.Rollback()
createdCategory, err := insertCategoryNode(ctx, tx, category)
if err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit create category node: %w", err)
}
return createdCategory, nil
}
// UpdateProduct updates mutable SPU fields.
func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRecord) error {
attrs, err := json.Marshal(product.Attrs)
if err != nil {
return fmt.Errorf("marshal product attrs: %w", err)
}
if product.Attrs == nil {
attrs = []byte("{}")
}
id, err := parseID(product.ID, "product id")
if err != nil {
return err
}
res, err := r.db.ExecContext(ctx, `
UPDATE product.products
SET spu_no = $2, title = $3, selling_point = $4, status = $5, cross_border = $6::jsonb, updated_at = NOW()
WHERE id = $1
`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs)
if err != nil {
return fmt.Errorf("update product %s: %w", product.ID, err)
}
affected, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("rows affected: %w", err)
}
if affected == 0 {
return ErrProductNotFound
}
return nil
}
// DeleteProduct soft-deletes an SPU and its SKUs.
func (r *ProductRepository) DeleteProduct(ctx context.Context, productID string) error {
id, err := parseID(productID, "product id")
if err != nil {
return err
}
res, err := r.db.ExecContext(ctx, `
UPDATE product.products
SET deleted_at = COALESCE(deleted_at, NOW()), updated_at = NOW()
WHERE id = $1 AND deleted_at IS NULL
`, id)
if err != nil {
return fmt.Errorf("delete product %s: %w", productID, err)
}
affected, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("rows affected: %w", err)
}
if affected == 0 {
return ErrProductNotFound
}
if _, err := r.db.ExecContext(ctx, `
UPDATE product.product_items
SET deleted_at = COALESCE(deleted_at, NOW()), updated_at = NOW()
WHERE product_id = $1 AND deleted_at IS NULL
`, id); err != nil {
return fmt.Errorf("delete product skus %s: %w", productID, err)
}
return nil
}
// CreateSKU inserts a SKU row under an existing SPU.
func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error {
attrs, err := normalizeAttributesJSON(sku.AttributesJSON)
if err != nil {
return err
}
productID, err := parseID(sku.ProductID, "product id")
if err != nil {
return err
}
skuID, err := parseID(sku.ID, "sku id")
if err != nil {
return err
}
inventoryID, err := inventoryIDFromSKU(sku)
if err != nil {
return err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin create sku: %w", err)
}
defer tx.Rollback()
err = tx.QueryRowContext(ctx, `
INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status)
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8)
RETURNING id
`, skuID, productID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&skuID)
if err != nil {
return fmt.Errorf("insert sku: %w", err)
}
if _, err := insertSKUInventory(ctx, tx, inventoryID, skuID, sku.AvailableQuantity); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit create sku: %w", err)
}
return nil
}
// UpdateSKU updates mutable SKU fields.
func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error {
attrs, err := normalizeAttributesJSON(sku.AttributesJSON)
if err != nil {
return err
}
id, err := parseID(sku.ID, "sku id")
if err != nil {
return err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin update sku: %w", err)
}
defer tx.Rollback()
res, err := tx.ExecContext(ctx, `
UPDATE product.product_items
SET sku_no = $2, name = $3, price = $4, image_ids = $5, attributes = $6::jsonb, status = $7, updated_at = NOW()
WHERE id = $1
`, id, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status))
if err != nil {
return fmt.Errorf("update sku %s: %w", sku.ID, err)
}
affected, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("rows affected: %w", err)
}
if affected == 0 {
return ErrSKUNotFound
}
if _, err := updateSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit update sku: %w", err)
}
return nil
}
// DeleteSKU soft-deletes a SKU row.
func (r *ProductRepository) DeleteSKU(ctx context.Context, skuID string) error {
id, err := parseID(skuID, "sku id")
if err != nil {
return err
}
res, err := r.db.ExecContext(ctx, `
UPDATE product.product_items
SET deleted_at = COALESCE(deleted_at, NOW()), updated_at = NOW()
WHERE id = $1 AND deleted_at IS NULL
`, id)
if err != nil {
return fmt.Errorf("delete sku %s: %w", skuID, err)
}
affected, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("rows affected: %w", err)
}
if affected == 0 {
return ErrSKUNotFound
}
return nil
}
// GetProduct loads an SPU and its SKU list by product ID.
func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (*ProductRecord, []SKURecord, error) {
product, err := r.loadProductByID(ctx, productID)
if err != nil {
return nil, nil, err
}
skus, err := r.loadSKUsByProductIDs(ctx, []string{productID})
if err != nil {
return nil, nil, err
}
return product, skus[productID], nil
}
// ListCategoryProducts loads paginated product summaries for a category ID.
func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32) ([]*CategoryProductRecord, int64, error) {
parsedCategoryID, err := parseID(categoryID, "category id")
if err != nil {
return nil, 0, err
}
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 20
}
var total int64
if err := r.db.QueryRowContext(ctx, `
SELECT COUNT(*)
FROM product.products p
JOIN product.product_category_bindings b ON b.product_id = p.id
WHERE b.category_id = $1
AND p.deleted_at IS NULL
`, parsedCategoryID).Scan(&total); err != nil {
return nil, 0, fmt.Errorf("count category products: %w", err)
}
if total == 0 {
return []*CategoryProductRecord{}, 0, nil
}
offset := int64(page-1) * int64(pageSize)
rows, err := r.db.QueryContext(ctx, `
SELECT p.updated_at,
p.created_at,
p.title,
p.id,
p.spu_no,
p.status,
COALESCE(to_json(p.image_ids)::text, '[]'),
COALESCE(sku_summary.price, 0),
COALESCE(sku_summary.sold_quantity, 0)
FROM product.products p
JOIN product.product_category_bindings b ON b.product_id = p.id
LEFT JOIN LATERAL (
SELECT MIN(pi.price) AS price,
SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity
FROM product.product_items pi
LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id
WHERE pi.product_id = p.id
AND pi.deleted_at IS NULL
) sku_summary ON TRUE
WHERE b.category_id = $1
AND p.deleted_at IS NULL
ORDER BY p.created_at DESC, p.id DESC
LIMIT $2 OFFSET $3
`, parsedCategoryID, pageSize, offset)
if err != nil {
return nil, 0, fmt.Errorf("query category products: %w", err)
}
defer rows.Close()
products := make([]*CategoryProductRecord, 0, pageSize)
for rows.Next() {
product, err := scanCategoryProduct(rows)
if err != nil {
return nil, 0, err
}
products = append(products, product)
}
if err := rows.Err(); err != nil {
return nil, 0, fmt.Errorf("iterate category products: %w", err)
}
return products, total, nil
}
// ListCategoryTreeNodes loads product category nodes for storefront category trees.
func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool) ([]*CategoryRecord, error) {
rows, err := r.db.QueryContext(ctx, `
SELECT id,
node_type,
name,
parent_id,
level,
image_json,
sort_num,
status
FROM product.product_category
WHERE node_type = 0
AND ($1 = false OR status = 1)
ORDER BY level ASC, sort_num ASC, id ASC
`, onlyVisible)
if err != nil {
return nil, fmt.Errorf("query category tree nodes: %w", err)
}
defer rows.Close()
categories := make([]*CategoryRecord, 0)
for rows.Next() {
category, err := scanCategory(rows)
if err != nil {
return nil, err
}
categories = append(categories, category)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate category tree nodes: %w", err)
}
return categories, nil
}
// ListGroupNodes loads product group nodes.
func (r *ProductRepository) ListGroupNodes(ctx context.Context, onlyVisible bool) ([]*CategoryRecord, error) {
rows, err := r.db.QueryContext(ctx, `
SELECT id,
node_type,
name,
parent_id,
level,
image_json,
sort_num,
status
FROM product.product_category
WHERE node_type = 1
AND ($1 = false OR status = 1)
ORDER BY sort_num ASC, id ASC
`, onlyVisible)
if err != nil {
return nil, fmt.Errorf("query group nodes: %w", err)
}
defer rows.Close()
groups := make([]*CategoryRecord, 0)
for rows.Next() {
group, err := scanCategory(rows)
if err != nil {
return nil, err
}
groups = append(groups, group)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate group nodes: %w", err)
}
return groups, nil
}
func (r *ProductRepository) loadProductByID(ctx context.Context, productID string) (*ProductRecord, error) {
products, err := r.loadProductsByIDs(ctx, []string{productID})
if err != nil {
return nil, err
}
if len(products) == 0 {
return nil, ErrProductNotFound
}
return products[0], nil
}
func (r *ProductRepository) loadProductsByIDs(ctx context.Context, productIDs []string) ([]*ProductRecord, error) {
placeholders := make([]string, len(productIDs))
args := make([]any, len(productIDs))
for i, id := range productIDs {
parsed, err := parseID(id, "product id")
if err != nil {
return nil, err
}
placeholders[i] = fmt.Sprintf("$%d", i+1)
args[i] = parsed
}
query := fmt.Sprintf(`
SELECT id,
spu_no,
title,
COALESCE(selling_point, ''),
brand_id,
supplier_id,
COALESCE(to_json(image_ids)::text, '[]'),
COALESCE(detail_html, ''),
member_discount_enabled,
goods_type,
COALESCE(to_json(service_guarantees)::text, '[]'),
status,
cross_border,
freight_charge_type,
freight_fixed_amount,
freight_template_id,
sale_time_type,
scheduled_sale_time,
deleted_at,
created_at,
updated_at
FROM product.products
WHERE id IN (%s)
AND deleted_at IS NULL
ORDER BY created_at ASC
`, strings.Join(placeholders, ", "))
rows, err := r.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("query products: %w", err)
}
defer rows.Close()
var products []*ProductRecord
for rows.Next() {
product, err := scanProduct(rows)
if err != nil {
return nil, err
}
products = append(products, product)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate products: %w", err)
}
return products, nil
}
func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs []byte) (*ProductRecord, error) {
id, err := parseID(product.ID, "product id")
if err != nil {
return nil, err
}
brandID, err := nullableID(product.BrandID, "brand_id")
if err != nil {
return nil, err
}
supplierID, err := nullableID(product.SupplierID, "supplier_id")
if err != nil {
return nil, err
}
freightTemplateID, err := nullableID(product.FreightTemplateID, "freight_template_id")
if err != nil {
return nil, err
}
row := tx.QueryRowContext(ctx, `
INSERT INTO product.products (
id,
spu_no,
title,
selling_point,
brand_id,
supplier_id,
image_ids,
detail_html,
member_discount_enabled,
goods_type,
service_guarantees,
status,
cross_border,
freight_charge_type,
freight_fixed_amount,
freight_template_id,
sale_time_type,
scheduled_sale_time
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13::jsonb, $14, $15, $16, $17, $18)
RETURNING id,
spu_no,
title,
COALESCE(selling_point, ''),
brand_id,
supplier_id,
COALESCE(to_json(image_ids)::text, '[]'),
COALESCE(detail_html, ''),
member_discount_enabled,
goods_type,
COALESCE(to_json(service_guarantees)::text, '[]'),
status,
cross_border,
freight_charge_type,
freight_fixed_amount,
freight_template_id,
sale_time_type,
scheduled_sale_time,
deleted_at,
created_at,
updated_at
`, id, product.SPUNo, product.Title, product.SellingPoint, brandID, supplierID, stringSliceOrEmpty(product.ImageIDs),
product.DetailHTML, product.MemberDiscountEnabled, int16(product.GoodsType), stringSliceOrEmpty(product.ServiceGuarantees),
statusToDB(product.Status), attrs, int16(product.FreightChargeType), product.FreightFixedAmount, freightTemplateID,
int16(product.SaleTimeType), product.ScheduledSaleTime)
createdProduct, err := scanProduct(row)
if err != nil {
if isPostgresConstraintError(err, "23505", "uq_products_spu_no") {
return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, product.SPUNo)
}
return nil, fmt.Errorf("insert product: %w", err)
}
return createdProduct, nil
}
func isPostgresConstraintError(err error, code, constraint string) bool {
var pgErr *pgconn.PgError
if !errors.As(err, &pgErr) {
return false
}
return pgErr.Code == code && pgErr.ConstraintName == constraint
}
func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) (*SKURecord, error) {
attrs, err := normalizeAttributesJSON(sku.AttributesJSON)
if err != nil {
return nil, err
}
id, err := parseID(sku.ID, "sku id")
if err != nil {
return nil, err
}
parsedProductID, err := parseID(productID, "product id")
if err != nil {
return nil, err
}
row := tx.QueryRowContext(ctx, `
INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status)
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8)
RETURNING id,
product_id,
sku_no,
name,
price,
COALESCE(to_json(image_ids)::text, '[]'),
attributes,
status,
deleted_at,
created_at,
updated_at,
NULL::bigint,
NULL::bigint,
NULL::integer,
NULL::integer,
NULL::integer,
NULL::timestamptz,
NULL::timestamptz
`, id, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status))
createdSKU, err := scanSKU(row)
if err != nil {
return nil, fmt.Errorf("insert sku: %w", err)
}
createdSKUID, err := parseID(createdSKU.ID, "sku id")
if err != nil {
return nil, err
}
inventoryID, err := inventoryIDFromSKU(sku)
if err != nil {
return nil, err
}
inventory, err := insertSKUInventory(ctx, tx, inventoryID, createdSKUID, sku.AvailableQuantity)
if err != nil {
return nil, err
}
createdSKU.Inventory = inventory
if inventory != nil {
createdSKU.AvailableQuantity = inventory.AvailableQuantity
createdSKU.LockedQuantity = inventory.LockedQuantity
createdSKU.SoldQuantity = inventory.SoldQuantity
}
return createdSKU, nil
}
func inventoryIDFromSKU(sku SKURecord) (int64, error) {
if sku.Inventory == nil {
return 0, errors.New("inventory id is required")
}
return parseID(sku.Inventory.ID, "inventory id")
}
func insertSKUInventory(ctx context.Context, tx *sql.Tx, inventoryID, skuID int64, availableQuantity int32) (*InventoryRecord, error) {
row := tx.QueryRowContext(ctx, `
INSERT INTO product.product_item_inventory (id, sku_id, spu_no, sku_no, available_quantity)
SELECT $1, pi.id, p.spu_no, pi.sku_no, $3
FROM product.product_items pi
JOIN product.products p ON p.id = pi.product_id
WHERE pi.id = $2
RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, created_at, updated_at
`, inventoryID, skuID, availableQuantity)
inventory, err := scanInventory(row)
if err != nil {
return nil, fmt.Errorf("insert sku inventory %s: %w", formatID(skuID), err)
}
return inventory, nil
}
func updateSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, availableQuantity int32) (*InventoryRecord, error) {
row := tx.QueryRowContext(ctx, `
UPDATE product.product_item_inventory
SET available_quantity = $2,
updated_at = NOW()
WHERE sku_id = $1
RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, created_at, updated_at
`, skuID, availableQuantity)
inventory, err := scanInventory(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("update sku inventory %s: %w", formatID(skuID), ErrSKUNotFound)
}
if err != nil {
return nil, fmt.Errorf("update sku inventory %s: %w", formatID(skuID), err)
}
return inventory, nil
}
func insertCategoryBinding(ctx context.Context, tx *sql.Tx, bindingID, productID, categoryID string) error {
parsedBindingID, err := parseID(bindingID, "category binding id")
if err != nil {
return err
}
parsedProductID, err := parseID(productID, "product id")
if err != nil {
return err
}
parsedCategoryID, err := parseID(categoryID, "leaf_category_id")
if err != nil {
return err
}
_, err = tx.ExecContext(ctx, `
INSERT INTO product.product_category_bindings (id, product_id, category_id)
VALUES ($1, $2, $3)
ON CONFLICT (product_id, category_id) DO NOTHING
`, parsedBindingID, parsedProductID, parsedCategoryID)
if err != nil {
return fmt.Errorf("insert category binding: %w", err)
}
return nil
}
func insertCategoryNode(ctx context.Context, tx *sql.Tx, category CategoryRecord) (*CategoryRecord, error) {
id, err := parseID(category.ID, "category id")
if err != nil {
return nil, err
}
parentID := sql.NullInt64{}
if strings.TrimSpace(category.ParentID) != "" {
parsedParentID, err := parseID(category.ParentID, "parent_id")
if err != nil {
return nil, err
}
parentID = sql.NullInt64{Int64: parsedParentID, Valid: true}
}
imageJSON, err := normalizeCategoryImageJSON(category.ImageJSON)
if err != nil {
return nil, err
}
row := tx.QueryRowContext(ctx, `
INSERT INTO product.product_category (
id,
node_type,
name,
parent_id,
level,
image_json,
sort_num,
status
)
VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8)
RETURNING id,
node_type,
name,
parent_id,
level,
image_json,
sort_num,
status
`, id, int16(category.NodeType), category.Name, parentID, int16(category.Level), imageJSON, category.SortNum, int16(category.Status))
createdCategory, err := scanCategory(row)
if err != nil {
return nil, fmt.Errorf("insert category node: %w", err)
}
return createdCategory, nil
}
func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs []string) (map[string][]SKURecord, error) {
result := make(map[string][]SKURecord, len(productIDs))
if len(productIDs) == 0 {
return result, nil
}
placeholders := make([]string, len(productIDs))
args := make([]any, len(productIDs))
for i, id := range productIDs {
parsed, err := parseID(id, "product 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.deleted_at,
pi.created_at,
pi.updated_at,
inv.id,
inv.sku_id,
inv.available_quantity,
inv.locked_quantity,
inv.sold_quantity,
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.product_id IN (%s)
AND pi.deleted_at IS NULL
ORDER BY pi.created_at ASC
`, strings.Join(placeholders, ", "))
rows, err := r.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("query skus: %w", err)
}
defer rows.Close()
for rows.Next() {
sku, err := scanSKU(rows)
if err != nil {
return nil, err
}
result[sku.ProductID] = append(result[sku.ProductID], *sku)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate skus: %w", err)
}
return result, nil
}
type rowScanner interface {
Scan(dest ...any) error
}
func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) {
var (
rec CategoryProductRecord
id int64
status int16
imageIDsJSON string
)
if err := scanner.Scan(
&rec.UpdatedAt,
&rec.CreatedAt,
&rec.Title,
&id,
&rec.SPUNo,
&status,
&imageIDsJSON,
&rec.Price,
&rec.SoldQuantity,
); err != nil {
return nil, fmt.Errorf("scan category product: %w", err)
}
rec.ID = formatID(id)
rec.Status = statusFromDB(status)
imageIDs, err := parseStringArrayJSON(imageIDsJSON)
if err != nil {
return nil, fmt.Errorf("unmarshal category product image_ids: %w", err)
}
rec.ImageIDs = imageIDs
return &rec, nil
}
func scanProduct(scanner rowScanner) (*ProductRecord, error) {
var (
rec ProductRecord
id int64
brandID sql.NullInt64
supplierID sql.NullInt64
imageIDsJSON string
serviceGuaranteesJSON string
goodsType int16
status int16
attrsJSON []byte
freightChargeType int16
freightTemplateID sql.NullInt64
saleTimeType int16
scheduledSaleTime sql.NullTime
deletedAt sql.NullTime
)
if err := scanner.Scan(
&id,
&rec.SPUNo,
&rec.Title,
&rec.SellingPoint,
&brandID,
&supplierID,
&imageIDsJSON,
&rec.DetailHTML,
&rec.MemberDiscountEnabled,
&goodsType,
&serviceGuaranteesJSON,
&status,
&attrsJSON,
&freightChargeType,
&rec.FreightFixedAmount,
&freightTemplateID,
&saleTimeType,
&scheduledSaleTime,
&deletedAt,
&rec.CreatedAt,
&rec.UpdatedAt,
); err != nil {
return nil, fmt.Errorf("scan product: %w", err)
}
rec.ID = formatID(id)
if brandID.Valid {
rec.BrandID = formatID(brandID.Int64)
}
if supplierID.Valid {
rec.SupplierID = formatID(supplierID.Int64)
}
rec.GoodsType = int32(goodsType)
imageIDs, err := parseStringArrayJSON(imageIDsJSON)
if err != nil {
return nil, fmt.Errorf("unmarshal product image_ids: %w", err)
}
rec.ImageIDs = imageIDs
serviceGuarantees, err := parseStringArrayJSON(serviceGuaranteesJSON)
if err != nil {
return nil, fmt.Errorf("unmarshal product service_guarantees: %w", err)
}
rec.ServiceGuarantees = serviceGuarantees
rec.Status = statusFromDB(status)
rec.CrossBorderJSON = string(attrsJSON)
if rec.CrossBorderJSON == "" {
rec.CrossBorderJSON = "{}"
}
if len(attrsJSON) > 0 {
if err := json.Unmarshal(attrsJSON, &rec.Attrs); err != nil {
return nil, fmt.Errorf("unmarshal product attrs: %w", err)
}
}
if freightTemplateID.Valid {
rec.FreightTemplateID = formatID(freightTemplateID.Int64)
}
rec.FreightChargeType = int32(freightChargeType)
rec.SaleTimeType = int32(saleTimeType)
if scheduledSaleTime.Valid {
rec.ScheduledSaleTime = timePtr(scheduledSaleTime.Time)
}
if deletedAt.Valid {
rec.DeletedAt = timePtr(deletedAt.Time)
}
return &rec, nil
}
func scanSKU(scanner rowScanner) (*SKURecord, error) {
var (
rec SKURecord
id int64
productID int64
skuNo sql.NullString
imageIDsJSON string
attrsJSON []byte
status int16
deletedAt sql.NullTime
inventoryID sql.NullInt64
inventorySKUID sql.NullInt64
availableQuantity sql.NullInt32
lockedQuantity sql.NullInt32
soldQuantity sql.NullInt32
inventoryCreatedAt sql.NullTime
inventoryUpdatedAt sql.NullTime
)
if err := scanner.Scan(
&id,
&productID,
&skuNo,
&rec.Name,
&rec.Price,
&imageIDsJSON,
&attrsJSON,
&status,
&deletedAt,
&rec.CreatedAt,
&rec.UpdatedAt,
&inventoryID,
&inventorySKUID,
&availableQuantity,
&lockedQuantity,
&soldQuantity,
&inventoryCreatedAt,
&inventoryUpdatedAt,
); err != nil {
return nil, fmt.Errorf("scan sku: %w", err)
}
rec.ID = formatID(id)
rec.ProductID = formatID(productID)
if skuNo.Valid {
rec.SKUNo = skuNo.String
}
imageIDs, err := parseStringArrayJSON(imageIDsJSON)
if err != nil {
return nil, fmt.Errorf("unmarshal sku image_ids: %w", err)
}
rec.ImageIDs = imageIDs
rec.AttributesJSON = string(attrsJSON)
if rec.AttributesJSON == "" {
rec.AttributesJSON = "[]"
}
if err := applySKUAttributes(&rec); err != nil {
return nil, err
}
rec.Status = int32(status)
if deletedAt.Valid {
rec.DeletedAt = timePtr(deletedAt.Time)
}
if inventoryID.Valid {
rec.Inventory = &InventoryRecord{
ID: formatID(inventoryID.Int64),
SKUID: formatID(inventorySKUID.Int64),
AvailableQuantity: nullInt32Value(availableQuantity),
LockedQuantity: nullInt32Value(lockedQuantity),
SoldQuantity: nullInt32Value(soldQuantity),
}
if inventoryCreatedAt.Valid {
rec.Inventory.CreatedAt = inventoryCreatedAt.Time
}
if inventoryUpdatedAt.Valid {
rec.Inventory.UpdatedAt = inventoryUpdatedAt.Time
}
rec.AvailableQuantity = rec.Inventory.AvailableQuantity
rec.LockedQuantity = rec.Inventory.LockedQuantity
rec.SoldQuantity = rec.Inventory.SoldQuantity
}
return &rec, nil
}
func scanInventory(scanner rowScanner) (*InventoryRecord, error) {
var (
rec InventoryRecord
id int64
skuID int64
)
if err := scanner.Scan(
&id,
&skuID,
&rec.AvailableQuantity,
&rec.LockedQuantity,
&rec.SoldQuantity,
&rec.CreatedAt,
&rec.UpdatedAt,
); err != nil {
return nil, fmt.Errorf("scan inventory: %w", err)
}
rec.ID = formatID(id)
rec.SKUID = formatID(skuID)
return &rec, nil
}
func scanCategory(scanner rowScanner) (*CategoryRecord, error) {
var (
rec CategoryRecord
id int64
parentID sql.NullInt64
imageJSON []byte
nodeType int16
level int16
status int16
)
if err := scanner.Scan(
&id, &nodeType, &rec.Name, &parentID, &level, &imageJSON, &rec.SortNum, &status,
); err != nil {
return nil, fmt.Errorf("scan category: %w", err)
}
rec.ID = formatID(id)
rec.NodeType = int32(nodeType)
if parentID.Valid {
rec.ParentID = formatID(parentID.Int64)
}
rec.Level = int32(level)
rec.ImageJSON = string(imageJSON)
if rec.ImageJSON == "" {
rec.ImageJSON = "[]"
}
rec.Status = int32(status)
return &rec, nil
}
func normalizeAttributesJSON(raw string) ([]byte, error) {
if strings.TrimSpace(raw) == "" {
return []byte("[]"), nil
}
if !json.Valid([]byte(raw)) {
return nil, fmt.Errorf("invalid attributes json: %s", raw)
}
return []byte(raw), nil
}
func normalizeCategoryImageJSON(raw string) ([]byte, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return []byte("[]"), nil
}
if !json.Valid([]byte(raw)) {
return nil, fmt.Errorf("invalid image_json")
}
return []byte(raw), nil
}
func productCrossBorderJSON(product ProductRecord) ([]byte, error) {
if strings.TrimSpace(product.CrossBorderJSON) != "" {
attrs := []byte(product.CrossBorderJSON)
if !json.Valid(attrs) {
return nil, fmt.Errorf("invalid cross_border_json")
}
return attrs, nil
}
attrs, err := json.Marshal(product.Attrs)
if err != nil {
return nil, fmt.Errorf("marshal product attrs: %w", err)
}
if product.Attrs == nil {
attrs = []byte("{}")
}
return attrs, nil
}
func applySKUAttributes(rec *SKURecord) error {
if rec == nil {
return nil
}
attrs, err := parseSKUAttributes(rec.AttributesJSON)
if err != nil {
return err
}
for _, item := range attrs {
if value := item["k1"]; value != "" {
rec.K1 = value
}
if value := item["v1"]; value != "" {
rec.V1 = value
}
if value := item["k2"]; value != "" {
rec.K2 = value
}
if value := item["v2"]; value != "" {
rec.V2 = value
}
if value := item["k3"]; value != "" {
rec.K3 = value
}
if value := item["v3"]; value != "" {
rec.V3 = value
}
}
return nil
}
func parseSKUAttributes(raw string) ([]map[string]string, error) {
raw = strings.TrimSpace(raw)
if raw == "" || raw == "{}" || raw == "null" {
return nil, nil
}
var attrs []map[string]string
if err := json.Unmarshal([]byte(raw), &attrs); err == nil {
return attrs, nil
}
var attr map[string]any
if err := json.Unmarshal([]byte(raw), &attr); err != nil {
return nil, fmt.Errorf("unmarshal sku attributes: %w", err)
}
if isEmptySKUAttributeObject(attr) {
return nil, nil
}
return nil, fmt.Errorf("unmarshal sku attributes: expected array, got object")
}
func isEmptySKUAttributeObject(attr map[string]any) bool {
if len(attr) == 0 {
return true
}
for _, value := range attr {
if value == nil {
continue
}
if s, ok := value.(string); ok && strings.TrimSpace(s) == "" {
continue
}
return false
}
return true
}
func parseStringArrayJSON(raw string) ([]string, error) {
if strings.TrimSpace(raw) == "" {
return []string{}, nil
}
var values []string
if err := json.Unmarshal([]byte(raw), &values); err != nil {
return nil, err
}
return values, nil
}
func nullableID(raw, field string) (sql.NullInt64, error) {
if strings.TrimSpace(raw) == "" {
return sql.NullInt64{}, nil
}
id, err := parseID(raw, field)
if err != nil {
return sql.NullInt64{}, err
}
return sql.NullInt64{Int64: id, Valid: true}, nil
}
func nullString(raw string) sql.NullString {
value := strings.TrimSpace(raw)
if value == "" {
return sql.NullString{}
}
return sql.NullString{String: value, Valid: true}
}
func stringSliceOrEmpty(values []string) []string {
if values == nil {
return []string{}
}
return values
}
func nullInt32Value(value sql.NullInt32) int32 {
if value.Valid {
return value.Int32
}
return 0
}
func timePtr(value time.Time) *time.Time {
return &value
}
func statusToDB(status productv1.ProductStatus) int16 {
switch status {
case productv1.ProductStatus_PRODUCT_STATUS_DRAFT:
return 0
case productv1.ProductStatus_PRODUCT_STATUS_ON_SALE:
return 1
case productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE:
return 3
default:
return 0
}
}
func statusFromDB(status int16) productv1.ProductStatus {
switch status {
case 0:
return productv1.ProductStatus_PRODUCT_STATUS_DRAFT
case 1:
return productv1.ProductStatus_PRODUCT_STATUS_ON_SALE
case 3:
return productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE
default:
return productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED
}
}
func parseID(raw, field string) (int64, error) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, fmt.Errorf("%s must be a positive snowflake id", field)
}
return id, nil
}
func formatID(id int64) string {
return strconv.FormatInt(id, 10)
}