mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
调整创建商品字段、SKU规格整理和入库逻辑
This commit is contained in:
parent
5e74ff2816
commit
42419db604
19
README.md
19
README.md
@ -28,24 +28,9 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
||||
|
||||
### `CreateProduct`
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `product_id` | `string` | 是 | 商品 SPU ID,由调用方生成 |
|
||||
| `spu_no` | `string` | 是 | SPU 编码,未删除商品内唯一 |
|
||||
| `title` | `string` | 是 | 商品标题 |
|
||||
| `selling_point` | `string` | 否 | 商品卖点 |
|
||||
| `status` | `ProductStatus` | 是 | 商品状态:`DRAFT` / `ON_SALE` / `OFF_SALE` |
|
||||
| `skus` | `CreateProductSKU[]` | 否 | 创建时附带的 SKU 列表 |
|
||||
创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。
|
||||
|
||||
`CreateProductSKU` 字段:
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `sku_id` | `string` | 是 | SKU ID,由调用方生成 |
|
||||
| `name` | `string` | 是 | SKU 名称 |
|
||||
| `price` | `int64` | 是 | 售价,单位:分 |
|
||||
| `available_quantity` | `int32` | 是 | 初始可售库存 |
|
||||
| `attributes_json` | `string` | 否 | 规格属性 JSON 字符串 |
|
||||
当前创建接口不再接收 `product_id`、`sku_id` 和 SKU `name`:`product_id`、`sku_id` 由数据库生成,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。
|
||||
|
||||
### `GetProduct`
|
||||
|
||||
|
||||
@ -40,6 +40,7 @@ type ProductRecord struct {
|
||||
FreightTemplateID string
|
||||
SaleTimeType int32
|
||||
ScheduledSaleTime *time.Time
|
||||
LeafCategoryID string
|
||||
DeletedAt *time.Time
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
@ -52,10 +53,17 @@ type SKURecord struct {
|
||||
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
|
||||
@ -118,12 +126,26 @@ func NewProductRepository(db *sql.DB) *ProductRepository {
|
||||
// EnsureSchema adds the SKU table when missing; products is provisioned by infra init-scripts.
|
||||
func (r *ProductRepository) EnsureSchema(ctx context.Context) error {
|
||||
const ddl = `
|
||||
CREATE SEQUENCE IF NOT EXISTS product.products_id_seq;
|
||||
CREATE SEQUENCE IF NOT EXISTS product.product_items_id_seq;
|
||||
CREATE SEQUENCE IF NOT EXISTS product.product_category_bindings_id_seq;
|
||||
|
||||
ALTER TABLE product.products
|
||||
ALTER COLUMN id SET DEFAULT nextval('product.products_id_seq');
|
||||
|
||||
ALTER TABLE product.product_category_bindings
|
||||
ALTER COLUMN id SET DEFAULT nextval('product.product_category_bindings_id_seq');
|
||||
|
||||
SELECT setval('product.products_id_seq', COALESCE((SELECT MAX(id) FROM product.products), 0) + 1, false);
|
||||
SELECT setval('product.product_category_bindings_id_seq', COALESCE((SELECT MAX(id) FROM product.product_category_bindings), 0) + 1, false);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS product.product_items (
|
||||
id BIGINT PRIMARY KEY,
|
||||
id BIGINT PRIMARY KEY DEFAULT nextval('product.product_items_id_seq'),
|
||||
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),
|
||||
@ -142,6 +164,11 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory (
|
||||
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 SET DEFAULT nextval('product.product_items_id_seq');
|
||||
ALTER TABLE product.product_items
|
||||
ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[];
|
||||
SELECT setval('product.product_items_id_seq', COALESCE((SELECT MAX(id) FROM product.product_items), 0) + 1, false);
|
||||
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;
|
||||
@ -154,40 +181,29 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_ite
|
||||
|
||||
// CreateProduct inserts a new SPU row.
|
||||
func (r *ProductRepository) CreateProduct(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")
|
||||
attrs, err := productCrossBorderJSON(product)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = r.db.ExecContext(ctx, `
|
||||
INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border)
|
||||
VALUES ($1, $2, $3, $4, $5, $6::jsonb)
|
||||
`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs)
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert product %s: %w", product.ID, err)
|
||||
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 := json.Marshal(product.Attrs)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("marshal product attrs: %w", err)
|
||||
}
|
||||
if product.Attrs == nil {
|
||||
attrs = []byte("{}")
|
||||
}
|
||||
|
||||
id, err := parseID(product.ID, "product id")
|
||||
attrs, err := productCrossBorderJSON(product)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@ -198,20 +214,26 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
createdProduct, err := insertProduct(ctx, tx, id, product, attrs)
|
||||
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, product.ID, sku)
|
||||
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, 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)
|
||||
}
|
||||
@ -293,10 +315,6 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error
|
||||
return err
|
||||
}
|
||||
|
||||
id, err := parseID(sku.ID, "sku id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
productID, err := parseID(sku.ProductID, "product id")
|
||||
if err != nil {
|
||||
return err
|
||||
@ -308,12 +326,14 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error
|
||||
}
|
||||
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)
|
||||
var id int64
|
||||
err = tx.QueryRowContext(ctx, `
|
||||
INSERT INTO product.product_items (product_id, sku_no, name, price, image_ids, attributes, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7)
|
||||
RETURNING id
|
||||
`, productID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert sku %s: %w", sku.ID, err)
|
||||
return fmt.Errorf("insert sku: %w", err)
|
||||
}
|
||||
|
||||
if _, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil {
|
||||
@ -345,9 +365,9 @@ func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error
|
||||
|
||||
res, err := tx.ExecContext(ctx, `
|
||||
UPDATE product.product_items
|
||||
SET name = $2, price = $3, attributes = $4::jsonb, updated_at = NOW()
|
||||
SET sku_no = $2, name = $3, price = $4, image_ids = $5, attributes = $6::jsonb, status = $7, updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`, id, sku.Name, sku.Price, attrs)
|
||||
`, 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)
|
||||
}
|
||||
@ -595,10 +615,40 @@ ORDER BY created_at ASC
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func insertProduct(ctx context.Context, tx *sql.Tx, id int64, product ProductRecord, attrs []byte) (*ProductRecord, error) {
|
||||
func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs []byte) (*ProductRecord, error) {
|
||||
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, status, cross_border)
|
||||
VALUES ($1, $2, $3, $4, $5, $6::jsonb)
|
||||
INSERT INTO product.products (
|
||||
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::jsonb, $13, $14, $15, $16, $17)
|
||||
RETURNING id,
|
||||
spu_no,
|
||||
title,
|
||||
@ -620,11 +670,14 @@ RETURNING id,
|
||||
deleted_at,
|
||||
created_at,
|
||||
updated_at
|
||||
`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs)
|
||||
`, 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 {
|
||||
return nil, fmt.Errorf("insert product %s: %w", product.ID, err)
|
||||
return nil, fmt.Errorf("insert product: %w", err)
|
||||
}
|
||||
return createdProduct, nil
|
||||
}
|
||||
@ -635,23 +688,20 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord)
|
||||
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, name, price, attributes)
|
||||
VALUES ($1, $2, $3, $4, $5::jsonb)
|
||||
INSERT INTO product.product_items (product_id, sku_no, name, price, image_ids, attributes, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7)
|
||||
RETURNING id,
|
||||
product_id,
|
||||
sku_no,
|
||||
name,
|
||||
price,
|
||||
COALESCE(to_json(image_ids)::text, '[]'),
|
||||
attributes,
|
||||
status,
|
||||
deleted_at,
|
||||
@ -664,14 +714,18 @@ RETURNING id,
|
||||
NULL::integer,
|
||||
NULL::timestamptz,
|
||||
NULL::timestamptz
|
||||
`, id, parsedProductID, sku.Name, sku.Price, attrs)
|
||||
`, 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 %s: %w", sku.ID, err)
|
||||
return nil, fmt.Errorf("insert sku: %w", err)
|
||||
}
|
||||
|
||||
inventory, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity)
|
||||
createdSKUID, err := parseID(createdSKU.ID, "sku id")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
inventory, err := upsertSKUInventory(ctx, tx, createdSKUID, sku.AvailableQuantity)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -700,6 +754,27 @@ RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, create
|
||||
return inventory, nil
|
||||
}
|
||||
|
||||
func insertCategoryBinding(ctx context.Context, tx *sql.Tx, productID, categoryID string) error {
|
||||
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 (product_id, category_id)
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT (product_id, category_id) DO NOTHING
|
||||
`, parsedProductID, parsedCategoryID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert category binding: %w", err)
|
||||
}
|
||||
return 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 {
|
||||
@ -723,6 +798,7 @@ SELECT pi.id,
|
||||
pi.sku_no,
|
||||
pi.name,
|
||||
pi.price,
|
||||
COALESCE(to_json(pi.image_ids)::text, '[]'),
|
||||
pi.attributes,
|
||||
pi.status,
|
||||
pi.deleted_at,
|
||||
@ -955,6 +1031,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) {
|
||||
id int64
|
||||
productID int64
|
||||
skuNo sql.NullString
|
||||
imageIDsJSON string
|
||||
attrsJSON []byte
|
||||
status int16
|
||||
deletedAt sql.NullTime
|
||||
@ -972,6 +1049,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) {
|
||||
&skuNo,
|
||||
&rec.Name,
|
||||
&rec.Price,
|
||||
&imageIDsJSON,
|
||||
&attrsJSON,
|
||||
&status,
|
||||
&deletedAt,
|
||||
@ -993,9 +1071,17 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) {
|
||||
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 = "{}"
|
||||
rec.AttributesJSON = "[]"
|
||||
}
|
||||
if err := applySKUAttributes(&rec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rec.Status = int32(status)
|
||||
if deletedAt.Valid {
|
||||
@ -1076,7 +1162,7 @@ func scanCategory(scanner rowScanner) (*CategoryRecord, error) {
|
||||
|
||||
func normalizeAttributesJSON(raw string) ([]byte, error) {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return []byte("{}"), nil
|
||||
return []byte("[]"), nil
|
||||
}
|
||||
if !json.Valid([]byte(raw)) {
|
||||
return nil, fmt.Errorf("invalid attributes json: %s", raw)
|
||||
@ -1084,6 +1170,58 @@ func normalizeAttributesJSON(raw string) ([]byte, error) {
|
||||
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 || strings.TrimSpace(rec.AttributesJSON) == "" {
|
||||
return nil
|
||||
}
|
||||
if strings.TrimSpace(rec.AttributesJSON) == "{}" {
|
||||
return nil
|
||||
}
|
||||
var attrs []map[string]string
|
||||
if err := json.Unmarshal([]byte(rec.AttributesJSON), &attrs); err != nil {
|
||||
return fmt.Errorf("unmarshal sku attributes: %w", 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 parseStringArrayJSON(raw string) ([]string, error) {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return []string{}, nil
|
||||
@ -1095,6 +1233,32 @@ func parseStringArrayJSON(raw string) ([]string, error) {
|
||||
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
|
||||
|
||||
@ -15,6 +15,7 @@ import (
|
||||
"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"
|
||||
@ -64,7 +65,7 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create
|
||||
}
|
||||
|
||||
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes(
|
||||
attribute.String("product.id", product.ID),
|
||||
attribute.String("product.spu_no", product.SPUNo),
|
||||
attribute.Int("product.sku_count", len(skus)),
|
||||
))
|
||||
defer dbSpan.End()
|
||||
@ -73,7 +74,7 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create
|
||||
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))
|
||||
s.observer.Logger(ctx).Error("create product failed", zap.String("spu_no", product.SPUNo), zap.Error(err))
|
||||
return nil, status.Errorf(codes.Internal, "create product: %v", err)
|
||||
}
|
||||
observability.IncProductsCreated()
|
||||
@ -201,11 +202,6 @@ func totalPages(total int64, pageSize int32) int32 {
|
||||
}
|
||||
|
||||
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")
|
||||
@ -220,19 +216,53 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P
|
||||
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{
|
||||
ID: productID,
|
||||
SPUNo: spuNo,
|
||||
Title: title,
|
||||
SellingPoint: req.GetSellingPoint(),
|
||||
Status: statusValue,
|
||||
Attrs: map[string]any{},
|
||||
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(productID, protoSKU)
|
||||
sku, err := skuFromCreateInput(protoSKU)
|
||||
if err != nil {
|
||||
return repository.ProductRecord{}, nil, errors.New("skus[" + strconv.Itoa(i) + "]: " + err.Error())
|
||||
}
|
||||
@ -242,20 +272,11 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P
|
||||
return record, skus, nil
|
||||
}
|
||||
|
||||
func skuFromCreateInput(productID string, sku *productv1.CreateProductSKU) (repository.SKURecord, error) {
|
||||
func skuFromCreateInput(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")
|
||||
}
|
||||
@ -263,21 +284,142 @@ func skuFromCreateInput(productID string, sku *productv1.CreateProductSKU) (repo
|
||||
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")
|
||||
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{
|
||||
ID: skuID,
|
||||
ProductID: productID,
|
||||
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 validatePositiveID(raw, field string) error {
|
||||
if raw == "" {
|
||||
return errors.New(field + " is required")
|
||||
@ -306,6 +448,13 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
|
||||
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: timestampOrNil(sku.DeletedAt),
|
||||
CreatedAt: timestamppb.New(sku.CreatedAt),
|
||||
UpdatedAt: timestamppb.New(sku.UpdatedAt),
|
||||
@ -330,6 +479,7 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
|
||||
GoodsType: product.GoodsType,
|
||||
ServiceGuarantees: product.ServiceGuarantees,
|
||||
CrossBorderJson: product.CrossBorderJSON,
|
||||
CrossBorderInfo: toProtoCrossBorderInfo(product.CrossBorderJSON),
|
||||
FreightChargeType: product.FreightChargeType,
|
||||
FreightFixedAmount: product.FreightFixedAmount,
|
||||
FreightTemplateId: product.FreightTemplateID,
|
||||
|
||||
@ -27,6 +27,10 @@ CREATE EXTENSION IF NOT EXISTS "pg_trgm";
|
||||
|
||||
CREATE SCHEMA IF NOT EXISTS product;
|
||||
|
||||
CREATE SEQUENCE IF NOT EXISTS product.products_id_seq;
|
||||
CREATE SEQUENCE IF NOT EXISTS product.product_items_id_seq;
|
||||
CREATE SEQUENCE IF NOT EXISTS product.product_category_bindings_id_seq;
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.set_updated_at()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
@ -36,7 +40,7 @@ END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS product.products (
|
||||
id BIGINT PRIMARY KEY,
|
||||
id BIGINT PRIMARY KEY DEFAULT nextval('product.products_id_seq'),
|
||||
spu_no VARCHAR(100) NOT NULL,
|
||||
title VARCHAR(200) NOT NULL,
|
||||
selling_point VARCHAR(300),
|
||||
@ -105,6 +109,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no
|
||||
ON product.products (spu_no)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
SELECT setval('product.products_id_seq', COALESCE((SELECT MAX(id) FROM product.products), 0) + 1, false);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS product.product_category (
|
||||
id BIGINT PRIMARY KEY,
|
||||
node_type SMALLINT NOT NULL DEFAULT 0,
|
||||
@ -139,7 +145,7 @@ CREATE INDEX IF NOT EXISTS idx_product_category_node_status_sort
|
||||
ON product.product_category (node_type, status, sort_num);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS product.product_category_bindings (
|
||||
id BIGINT PRIMARY KEY,
|
||||
id BIGINT PRIMARY KEY DEFAULT nextval('product.product_category_bindings_id_seq'),
|
||||
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
|
||||
category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE CASCADE,
|
||||
CONSTRAINT uq_product_category_bindings_product_category UNIQUE (product_id, category_id)
|
||||
@ -153,12 +159,15 @@ COMMENT ON COLUMN product.product_category_bindings.category_id IS '绑定分类
|
||||
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_id
|
||||
ON product.product_category_bindings (category_id);
|
||||
|
||||
SELECT setval('product.product_category_bindings_id_seq', COALESCE((SELECT MAX(id) FROM product.product_category_bindings), 0) + 1, false);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS product.product_items (
|
||||
id BIGINT PRIMARY KEY,
|
||||
id BIGINT PRIMARY KEY DEFAULT nextval('product.product_items_id_seq'),
|
||||
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),
|
||||
@ -169,6 +178,7 @@ CREATE TABLE IF NOT EXISTS product.product_items (
|
||||
|
||||
COMMENT ON TABLE product.product_items IS '商品 SKU 明细表:存储具体可售规格、价格和规格属性;库存统一存储在 product.product_item_inventory';
|
||||
COMMENT ON COLUMN product.product_items.price IS 'SKU 售价,单位:分';
|
||||
COMMENT ON COLUMN product.product_items.image_ids IS 'SKU 图片 ID 列表';
|
||||
COMMENT ON COLUMN product.product_items.attributes IS 'SKU 规格属性 JSONB,如颜色、尺寸等';
|
||||
COMMENT ON COLUMN product.product_items.status IS 'SKU 状态:0 停用,1 启用';
|
||||
COMMENT ON COLUMN product.product_items.version IS 'SKU 乐观锁版本号';
|
||||
@ -186,6 +196,8 @@ 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;
|
||||
|
||||
SELECT setval('product.product_items_id_seq', COALESCE((SELECT MAX(id) FROM product.product_items), 0) + 1, false);
|
||||
|
||||
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,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user