Refactor product model and update CreateProduct logic to use new fields. Enhance SKU handling with inventory management and update README for consistency in product attributes.

This commit is contained in:
robinj0726 2026-07-07 15:39:30 +08:00
parent 54bbf73f56
commit 62ec3c43c4
3 changed files with 172 additions and 111 deletions

View File

@ -91,7 +91,7 @@ grpcurl -plaintext -d '{"product_id":"<snowflake-id>"}' \
localhost:50052 ids.product.v1.ProductService/GetProduct localhost:50052 ids.product.v1.ProductService/GetProduct
# 创建商品 # 创建商品
grpcurl -plaintext -d '{"product":{"product_id":"<snowflake-id>","spu_code":"<spu-code>","name":"商品名称","description":"商品描述","status":"PRODUCT_STATUS_DRAFT","skus":[]}}' \ grpcurl -plaintext -d '{"product_id":"<snowflake-id>","spu_no":"<spu-no>","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_DRAFT","skus":[]}' \
localhost:50052 ids.product.v1.ProductService/CreateProduct localhost:50052 ids.product.v1.ProductService/CreateProduct
# 批量查询 # 批量查询
@ -109,8 +109,9 @@ grpcurl -plaintext -d '{"category_id":"<snowflake-category-id>","page":1,"page_s
| 表 | 职责 | | 表 | 职责 |
|---|---| |---|---|
| `product.products` | SPU 主表(名称、描述、状态、扩展属性) | | `product.products` | SPU 主表(标题、卖点、状态、扩展属性) |
| `product.product_items` | SKU 明细(规格、价格、库存) | | `product.product_items` | SKU 明细(规格、价格、属性) |
| `product.product_item_inventory` | SKU 库存销量(可售、锁定、已售) |
- 价格字段统一为 `BIGINT` / Go `int64`,单位:**分** - 价格字段统一为 `BIGINT` / Go `int64`,单位:**分**
- 禁止跨 Schema JOIN(`trade`、`customer` 等) - 禁止跨 Schema JOIN(`trade`、`customer` 等)

View File

@ -21,26 +21,26 @@ var ErrSKUNotFound = errors.New("sku not found")
// ProductRecord is the persistence model for product.products (SPU). // ProductRecord is the persistence model for product.products (SPU).
type ProductRecord struct { type ProductRecord struct {
ID string ID string
SPUCode string SPUNo string
Name string Title string
Description string SellingPoint string
Status productv1.ProductStatus Status productv1.ProductStatus
Attrs map[string]any Attrs map[string]any
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
} }
// SKURecord is the persistence model for product.product_items. // SKURecord is the persistence model for product.product_items.
type SKURecord struct { type SKURecord struct {
ID string ID string
ProductID string ProductID string
Name string Name string
Price int64 Price int64
Stock int32 AvailableQuantity int32
AttributesJSONB string AttributesJSON string
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
} }
// ProductRepository provides CRUD access to product tables only [ARC-PROD-001]. // ProductRepository provides CRUD access to product tables only [ARC-PROD-001].
@ -59,23 +59,30 @@ func (r *ProductRepository) EnsureSchema(ctx context.Context) error {
CREATE TABLE IF NOT EXISTS product.product_items ( CREATE TABLE IF NOT EXISTS product.product_items (
id BIGINT PRIMARY KEY, id BIGINT PRIMARY KEY,
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
sku_no VARCHAR(100) UNIQUE, sku_no VARCHAR(100),
name VARCHAR(256) NOT NULL, name VARCHAR(256) NOT NULL,
price BIGINT NOT NULL CHECK (price >= 0), price BIGINT NOT NULL CHECK (price >= 0),
stock INTEGER NOT NULL DEFAULT 0 CHECK (stock >= 0),
attributes JSONB NOT NULL DEFAULT '{}', 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), version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
deleted_at TIMESTAMPTZ, deleted_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
); );
ALTER TABLE product.product_items CREATE TABLE IF NOT EXISTS product.product_item_inventory (
ADD COLUMN IF NOT EXISTS sku_no VARCHAR(100), id BIGINT PRIMARY KEY,
ADD COLUMN IF NOT EXISTS version INTEGER NOT NULL DEFAULT 0, sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE,
ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ; 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)
);
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_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 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; 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 { if _, err := r.db.ExecContext(ctx, ddl); err != nil {
return fmt.Errorf("ensure product tables: %w", err) return fmt.Errorf("ensure product tables: %w", err)
@ -101,7 +108,7 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe
_, err = r.db.ExecContext(ctx, ` _, err = r.db.ExecContext(ctx, `
INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border) INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border)
VALUES ($1, $2, $3, $4, $5, $6::jsonb) VALUES ($1, $2, $3, $4, $5, $6::jsonb)
`, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) `, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs)
if err != nil { if err != nil {
return fmt.Errorf("insert product %s: %w", product.ID, err) return fmt.Errorf("insert product %s: %w", product.ID, err)
} }
@ -169,7 +176,7 @@ func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRe
UPDATE product.products UPDATE product.products
SET spu_no = $2, title = $3, selling_point = $4, status = $5, cross_border = $6::jsonb, updated_at = NOW() SET spu_no = $2, title = $3, selling_point = $4, status = $5, cross_border = $6::jsonb, updated_at = NOW()
WHERE id = $1 WHERE id = $1
`, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) `, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs)
if err != nil { if err != nil {
return fmt.Errorf("update product %s: %w", product.ID, err) return fmt.Errorf("update product %s: %w", product.ID, err)
} }
@ -219,7 +226,7 @@ WHERE product_id = $1 AND deleted_at IS NULL
// CreateSKU inserts a SKU row under an existing SPU. // CreateSKU inserts a SKU row under an existing SPU.
func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error { func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error {
attrs, err := normalizeAttributesJSON(sku.AttributesJSONB) attrs, err := normalizeAttributesJSON(sku.AttributesJSON)
if err != nil { if err != nil {
return err return err
} }
@ -233,19 +240,33 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error
return err return err
} }
_, err = r.db.ExecContext(ctx, ` tx, err := r.db.BeginTx(ctx, nil)
INSERT INTO product.product_items (id, product_id, name, price, stock, attributes) if err != nil {
VALUES ($1, $2, $3, $4, $5, $6::jsonb) return fmt.Errorf("begin create sku: %w", err)
`, id, productID, sku.Name, sku.Price, sku.Stock, attrs) }
defer tx.Rollback()
_, err = tx.ExecContext(ctx, `
INSERT INTO product.product_items (id, product_id, name, price, attributes)
VALUES ($1, $2, $3, $4, $5::jsonb)
`, id, productID, sku.Name, sku.Price, attrs)
if err != nil { if err != nil {
return fmt.Errorf("insert sku %s: %w", sku.ID, err) return fmt.Errorf("insert sku %s: %w", sku.ID, err)
} }
if err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit create sku: %w", err)
}
return nil return nil
} }
// UpdateSKU updates mutable SKU fields. // UpdateSKU updates mutable SKU fields.
func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error { func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error {
attrs, err := normalizeAttributesJSON(sku.AttributesJSONB) attrs, err := normalizeAttributesJSON(sku.AttributesJSON)
if err != nil { if err != nil {
return err return err
} }
@ -254,11 +275,17 @@ func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error
if err != nil { if err != nil {
return err return err
} }
res, err := r.db.ExecContext(ctx, ` 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 UPDATE product.product_items
SET name = $2, price = $3, stock = $4, attributes = $5::jsonb, updated_at = NOW() SET name = $2, price = $3, attributes = $4::jsonb, updated_at = NOW()
WHERE id = $1 WHERE id = $1
`, id, sku.Name, sku.Price, sku.Stock, attrs) `, id, sku.Name, sku.Price, attrs)
if err != nil { if err != nil {
return fmt.Errorf("update sku %s: %w", sku.ID, err) return fmt.Errorf("update sku %s: %w", sku.ID, err)
} }
@ -270,6 +297,14 @@ WHERE id = $1
if affected == 0 { if affected == 0 {
return ErrSKUNotFound return ErrSKUNotFound
} }
if err := upsertSKUInventory(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 return nil
} }
@ -358,9 +393,10 @@ func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID
var total int64 var total int64
if err := r.db.QueryRowContext(ctx, ` if err := r.db.QueryRowContext(ctx, `
SELECT COUNT(*) SELECT COUNT(*)
FROM product.products FROM product.products p
WHERE category_ids @> ARRAY[$1]::BIGINT[] JOIN product.product_category_bindings b ON b.product_id = p.id
AND deleted_at IS NULL WHERE b.category_id = $1
AND p.deleted_at IS NULL
`, parsedCategoryID).Scan(&total); err != nil { `, parsedCategoryID).Scan(&total); err != nil {
return nil, nil, 0, fmt.Errorf("count category products: %w", err) return nil, nil, 0, fmt.Errorf("count category products: %w", err)
} }
@ -370,11 +406,12 @@ WHERE category_ids @> ARRAY[$1]::BIGINT[]
offset := int64(page-1) * int64(pageSize) offset := int64(page-1) * int64(pageSize)
rows, err := r.db.QueryContext(ctx, ` rows, err := r.db.QueryContext(ctx, `
SELECT id, spu_no, title, COALESCE(selling_point, ''), status, cross_border, created_at, updated_at SELECT p.id, p.spu_no, p.title, COALESCE(p.selling_point, ''), p.status, p.cross_border, p.created_at, p.updated_at
FROM product.products FROM product.products p
WHERE category_ids @> ARRAY[$1]::BIGINT[] JOIN product.product_category_bindings b ON b.product_id = p.id
AND deleted_at IS NULL WHERE b.category_id = $1
ORDER BY created_at DESC, id DESC AND p.deleted_at IS NULL
ORDER BY p.created_at DESC, p.id DESC
LIMIT $2 OFFSET $3 LIMIT $2 OFFSET $3
`, parsedCategoryID, pageSize, offset) `, parsedCategoryID, pageSize, offset)
if err != nil { if err != nil {
@ -467,7 +504,7 @@ func insertProduct(ctx context.Context, tx *sql.Tx, id int64, product ProductRec
INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border) INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border)
VALUES ($1, $2, $3, $4, $5, $6::jsonb) VALUES ($1, $2, $3, $4, $5, $6::jsonb)
RETURNING id, spu_no, title, COALESCE(selling_point, ''), status, cross_border, created_at, updated_at RETURNING id, spu_no, title, COALESCE(selling_point, ''), status, cross_border, created_at, updated_at
`, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) `, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs)
createdProduct, err := scanProduct(row) createdProduct, err := scanProduct(row)
if err != nil { if err != nil {
@ -477,7 +514,7 @@ RETURNING id, spu_no, title, COALESCE(selling_point, ''), status, cross_border,
} }
func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) (*SKURecord, error) { func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) (*SKURecord, error) {
attrs, err := normalizeAttributesJSON(sku.AttributesJSONB) attrs, err := normalizeAttributesJSON(sku.AttributesJSON)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -492,18 +529,37 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord)
} }
row := tx.QueryRowContext(ctx, ` row := tx.QueryRowContext(ctx, `
INSERT INTO product.product_items (id, product_id, name, price, stock, attributes) INSERT INTO product.product_items (id, product_id, name, price, attributes)
VALUES ($1, $2, $3, $4, $5, $6::jsonb) VALUES ($1, $2, $3, $4, $5::jsonb)
RETURNING id, product_id, name, price, stock, attributes, created_at, updated_at RETURNING id, product_id, name, price, 0, attributes, created_at, updated_at
`, id, parsedProductID, sku.Name, sku.Price, sku.Stock, attrs) `, id, parsedProductID, sku.Name, sku.Price, attrs)
createdSKU, err := scanSKU(row) createdSKU, err := scanSKU(row)
if err != nil { if err != nil {
return nil, fmt.Errorf("insert sku %s: %w", sku.ID, err) return nil, fmt.Errorf("insert sku %s: %w", sku.ID, err)
} }
if err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil {
return nil, err
}
createdSKU.AvailableQuantity = sku.AvailableQuantity
return createdSKU, nil return createdSKU, nil
} }
func upsertSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, availableQuantity int32) error {
_, err := tx.ExecContext(ctx, `
INSERT INTO product.product_item_inventory (id, sku_id, available_quantity)
VALUES ($1, $1, $2)
ON CONFLICT (sku_id) DO UPDATE
SET available_quantity = EXCLUDED.available_quantity,
updated_at = NOW()
`, skuID, availableQuantity)
if err != nil {
return fmt.Errorf("upsert sku inventory %s: %w", formatID(skuID), err)
}
return nil
}
func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs []string) (map[string][]SKURecord, error) { func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs []string) (map[string][]SKURecord, error) {
result := make(map[string][]SKURecord, len(productIDs)) result := make(map[string][]SKURecord, len(productIDs))
if len(productIDs) == 0 { if len(productIDs) == 0 {
@ -522,11 +578,19 @@ func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs
} }
query := fmt.Sprintf(` query := fmt.Sprintf(`
SELECT id, product_id, name, price, stock, attributes, created_at, updated_at SELECT pi.id,
FROM product.product_items pi.product_id,
WHERE product_id IN (%s) pi.name,
AND deleted_at IS NULL pi.price,
ORDER BY created_at ASC COALESCE(inv.available_quantity, 0),
pi.attributes,
pi.created_at,
pi.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, ", ")) `, strings.Join(placeholders, ", "))
rows, err := r.db.QueryContext(ctx, query, args...) rows, err := r.db.QueryContext(ctx, query, args...)
@ -561,7 +625,7 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) {
attrsJSON []byte attrsJSON []byte
) )
if err := scanner.Scan( if err := scanner.Scan(
&id, &rec.SPUCode, &rec.Name, &rec.Description, &status, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, &id, &rec.SPUNo, &rec.Title, &rec.SellingPoint, &status, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt,
); err != nil { ); err != nil {
return nil, fmt.Errorf("scan product: %w", err) return nil, fmt.Errorf("scan product: %w", err)
} }
@ -584,16 +648,16 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) {
attrsJSON []byte attrsJSON []byte
) )
if err := scanner.Scan( if err := scanner.Scan(
&id, &productID, &rec.Name, &rec.Price, &rec.Stock, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, &id, &productID, &rec.Name, &rec.Price, &rec.AvailableQuantity, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt,
); err != nil { ); err != nil {
return nil, fmt.Errorf("scan sku: %w", err) return nil, fmt.Errorf("scan sku: %w", err)
} }
rec.ID = formatID(id) rec.ID = formatID(id)
rec.ProductID = formatID(productID) rec.ProductID = formatID(productID)
rec.AttributesJSONB = string(attrsJSON) rec.AttributesJSON = string(attrsJSON)
if rec.AttributesJSONB == "" { if rec.AttributesJSON == "" {
rec.AttributesJSONB = "{}" rec.AttributesJSON = "{}"
} }
return &rec, nil return &rec, nil
} }

View File

@ -44,11 +44,11 @@ func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger) *P
// CreateProduct creates a product SPU and optional SKU list. // CreateProduct creates a product SPU and optional SKU list.
func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.CreateProductRequest) (*productv1.CreateProductResponse, error) { func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.CreateProductRequest) (*productv1.CreateProductResponse, error) {
if req == nil || req.GetProduct() == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "product is required") return nil, status.Error(codes.InvalidArgument, "request is required")
} }
product, skus, err := productFromProto(req.GetProduct()) product, skus, err := productFromCreateRequest(req)
if err != nil { if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error()) return nil, status.Error(codes.InvalidArgument, err.Error())
} }
@ -159,39 +159,39 @@ func totalPages(total int64, pageSize int32) int32 {
return int32(pages) return int32(pages)
} }
func productFromProto(product *productv1.Product) (repository.ProductRecord, []repository.SKURecord, error) { func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.ProductRecord, []repository.SKURecord, error) {
productID := strings.TrimSpace(product.GetProductId()) productID := strings.TrimSpace(req.GetProductId())
if err := validatePositiveID(productID, "product_id"); err != nil { if err := validatePositiveID(productID, "product_id"); err != nil {
return repository.ProductRecord{}, nil, err return repository.ProductRecord{}, nil, err
} }
spuCode := strings.TrimSpace(product.GetSpuCode()) spuNo := strings.TrimSpace(req.GetSpuNo())
if spuCode == "" { if spuNo == "" {
return repository.ProductRecord{}, nil, errors.New("spu_code is required") return repository.ProductRecord{}, nil, errors.New("spu_no is required")
} }
name := strings.TrimSpace(product.GetName()) title := strings.TrimSpace(req.GetTitle())
if name == "" { if title == "" {
return repository.ProductRecord{}, nil, errors.New("name is required") return repository.ProductRecord{}, nil, errors.New("title is required")
} }
statusValue := product.GetStatus() statusValue := req.GetStatus()
if statusValue == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED { if statusValue == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED {
statusValue = productv1.ProductStatus_PRODUCT_STATUS_DRAFT statusValue = productv1.ProductStatus_PRODUCT_STATUS_DRAFT
} }
record := repository.ProductRecord{ record := repository.ProductRecord{
ID: productID, ID: productID,
SPUCode: spuCode, SPUNo: spuNo,
Name: name, Title: title,
Description: product.GetDescription(), SellingPoint: req.GetSellingPoint(),
Status: statusValue, Status: statusValue,
Attrs: map[string]any{}, Attrs: map[string]any{},
} }
skus := make([]repository.SKURecord, 0, len(product.GetSkus())) skus := make([]repository.SKURecord, 0, len(req.GetSkus()))
for i, protoSKU := range product.GetSkus() { for i, protoSKU := range req.GetSkus() {
sku, err := skuFromProto(productID, protoSKU) sku, err := skuFromCreateInput(productID, protoSKU)
if err != nil { if err != nil {
return repository.ProductRecord{}, nil, errors.New("skus[" + strconv.Itoa(i) + "]: " + err.Error()) return repository.ProductRecord{}, nil, errors.New("skus[" + strconv.Itoa(i) + "]: " + err.Error())
} }
@ -201,7 +201,7 @@ func productFromProto(product *productv1.Product) (repository.ProductRecord, []r
return record, skus, nil return record, skus, nil
} }
func skuFromProto(productID string, sku *productv1.SKU) (repository.SKURecord, error) { func skuFromCreateInput(productID string, sku *productv1.CreateProductSKU) (repository.SKURecord, error) {
if sku == nil { if sku == nil {
return repository.SKURecord{}, errors.New("sku is required") return repository.SKURecord{}, errors.New("sku is required")
} }
@ -211,10 +211,6 @@ func skuFromProto(productID string, sku *productv1.SKU) (repository.SKURecord, e
return repository.SKURecord{}, err return repository.SKURecord{}, err
} }
if sku.GetProductId() != "" && sku.GetProductId() != productID {
return repository.SKURecord{}, errors.New("product_id must match product.product_id")
}
name := strings.TrimSpace(sku.GetName()) name := strings.TrimSpace(sku.GetName())
if name == "" { if name == "" {
return repository.SKURecord{}, errors.New("name is required") return repository.SKURecord{}, errors.New("name is required")
@ -222,22 +218,22 @@ func skuFromProto(productID string, sku *productv1.SKU) (repository.SKURecord, e
if sku.GetPrice() < 0 { if sku.GetPrice() < 0 {
return repository.SKURecord{}, errors.New("price must be greater than or equal to 0") return repository.SKURecord{}, errors.New("price must be greater than or equal to 0")
} }
if sku.GetStock() < 0 { if sku.GetAvailableQuantity() < 0 {
return repository.SKURecord{}, errors.New("stock must be greater than or equal to 0") return repository.SKURecord{}, errors.New("available_quantity must be greater than or equal to 0")
} }
attrs := strings.TrimSpace(sku.GetAttributesJsonb()) attrs := strings.TrimSpace(sku.GetAttributesJson())
if attrs != "" && !json.Valid([]byte(attrs)) { if attrs != "" && !json.Valid([]byte(attrs)) {
return repository.SKURecord{}, errors.New("attributes_jsonb must be valid json") return repository.SKURecord{}, errors.New("attributes_json must be valid json")
} }
return repository.SKURecord{ return repository.SKURecord{
ID: skuID, ID: skuID,
ProductID: productID, ProductID: productID,
Name: name, Name: name,
Price: sku.GetPrice(), Price: sku.GetPrice(),
Stock: sku.GetStock(), AvailableQuantity: sku.GetAvailableQuantity(),
AttributesJSONB: attrs, AttributesJSON: attrs,
}, nil }, nil
} }
@ -260,23 +256,23 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
protoSKUs := make([]*productv1.SKU, 0, len(skus)) protoSKUs := make([]*productv1.SKU, 0, len(skus))
for _, sku := range skus { for _, sku := range skus {
protoSKUs = append(protoSKUs, &productv1.SKU{ protoSKUs = append(protoSKUs, &productv1.SKU{
SkuId: sku.ID, SkuId: sku.ID,
ProductId: sku.ProductID, ProductId: sku.ProductID,
Name: sku.Name, Name: sku.Name,
Price: sku.Price, Price: sku.Price,
Stock: sku.Stock, AvailableQuantity: sku.AvailableQuantity,
AttributesJsonb: sku.AttributesJSONB, AttributesJson: sku.AttributesJSON,
}) })
} }
return &productv1.Product{ return &productv1.Product{
ProductId: product.ID, ProductId: product.ID,
SpuCode: product.SPUCode, SpuNo: product.SPUNo,
Name: product.Name, Title: product.Title,
Description: product.Description, SellingPoint: product.SellingPoint,
Status: product.Status, Status: product.Status,
Skus: protoSKUs, Skus: protoSKUs,
CreatedAt: timestamppb.New(product.CreatedAt), CreatedAt: timestamppb.New(product.CreatedAt),
UpdatedAt: timestamppb.New(product.UpdatedAt), UpdatedAt: timestamppb.New(product.UpdatedAt),
} }
} }