mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
431 lines
12 KiB
Go
431 lines
12 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
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")
|
|
|
|
// ProductRecord is the persistence model for product_schema.products (SPU).
|
|
type ProductRecord struct {
|
|
ID string
|
|
SPUCode string
|
|
Name string
|
|
Description string
|
|
Status productv1.ProductStatus
|
|
Attrs map[string]any
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
}
|
|
|
|
// SKURecord is the persistence model for product_schema.skus.
|
|
type SKURecord struct {
|
|
ID string
|
|
ProductID string
|
|
Name string
|
|
Price int64
|
|
Stock int32
|
|
AttributesJSONB string
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
}
|
|
|
|
// ProductRepository provides CRUD access to product_schema 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 product-domain columns and the skus table when missing.
|
|
func (r *ProductRepository) EnsureSchema(ctx context.Context) error {
|
|
const ddl = `
|
|
ALTER TABLE product_schema.products
|
|
ADD COLUMN IF NOT EXISTS description TEXT NOT NULL DEFAULT '';
|
|
ALTER TABLE product_schema.products
|
|
ADD COLUMN IF NOT EXISTS status VARCHAR(32) NOT NULL DEFAULT 'draft';
|
|
|
|
CREATE TABLE IF NOT EXISTS product_schema.skus (
|
|
id UUID PRIMARY KEY,
|
|
product_id UUID NOT NULL REFERENCES product_schema.products(id) ON DELETE CASCADE,
|
|
name VARCHAR(256) NOT NULL,
|
|
price BIGINT NOT NULL CHECK (price >= 0),
|
|
stock INTEGER NOT NULL DEFAULT 0 CHECK (stock >= 0),
|
|
attributes JSONB NOT NULL DEFAULT '{}',
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_skus_product_id ON product_schema.skus(product_id);
|
|
`
|
|
if _, err := r.db.ExecContext(ctx, ddl); err != nil {
|
|
return fmt.Errorf("ensure product_schema tables: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// 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("{}")
|
|
}
|
|
|
|
_, err = r.db.ExecContext(ctx, `
|
|
INSERT INTO product_schema.products (id, spu_code, title, description, status, attrs)
|
|
VALUES ($1, $2, $3, $4, $5, $6::jsonb)
|
|
`, product.ID, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs)
|
|
if err != nil {
|
|
return fmt.Errorf("insert product %s: %w", product.ID, err)
|
|
}
|
|
return 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("{}")
|
|
}
|
|
|
|
res, err := r.db.ExecContext(ctx, `
|
|
UPDATE product_schema.products
|
|
SET spu_code = $2, title = $3, description = $4, status = $5, attrs = $6::jsonb, updated_at = NOW()
|
|
WHERE id = $1
|
|
`, product.ID, product.SPUCode, product.Name, product.Description, 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 removes an SPU and its SKUs via ON DELETE CASCADE.
|
|
func (r *ProductRepository) DeleteProduct(ctx context.Context, productID string) error {
|
|
res, err := r.db.ExecContext(ctx, `DELETE FROM product_schema.products WHERE id = $1`, productID)
|
|
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
|
|
}
|
|
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.AttributesJSONB)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = r.db.ExecContext(ctx, `
|
|
INSERT INTO product_schema.skus (id, product_id, name, price, stock, attributes)
|
|
VALUES ($1, $2, $3, $4, $5, $6::jsonb)
|
|
`, sku.ID, sku.ProductID, sku.Name, sku.Price, sku.Stock, attrs)
|
|
if err != nil {
|
|
return fmt.Errorf("insert sku %s: %w", sku.ID, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UpdateSKU updates mutable SKU fields.
|
|
func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error {
|
|
attrs, err := normalizeAttributesJSON(sku.AttributesJSONB)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
res, err := r.db.ExecContext(ctx, `
|
|
UPDATE product_schema.skus
|
|
SET name = $2, price = $3, stock = $4, attributes = $5::jsonb, updated_at = NOW()
|
|
WHERE id = $1
|
|
`, sku.ID, sku.Name, sku.Price, sku.Stock, attrs)
|
|
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
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DeleteSKU removes a SKU row.
|
|
func (r *ProductRepository) DeleteSKU(ctx context.Context, skuID string) error {
|
|
res, err := r.db.ExecContext(ctx, `DELETE FROM product_schema.skus WHERE id = $1`, skuID)
|
|
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
|
|
}
|
|
|
|
// BatchGetProducts loads multiple SPUs and their SKU lists; missing IDs are skipped [ARC-PROD-003].
|
|
func (r *ProductRepository) BatchGetProducts(ctx context.Context, productIDs []string) ([]*ProductRecord, map[string][]SKURecord, error) {
|
|
uniqueIDs := dedupeProductIDs(productIDs)
|
|
if len(uniqueIDs) == 0 {
|
|
return nil, map[string][]SKURecord{}, nil
|
|
}
|
|
|
|
products, err := r.loadProductsByIDs(ctx, uniqueIDs)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
if len(products) == 0 {
|
|
return []*ProductRecord{}, map[string][]SKURecord{}, nil
|
|
}
|
|
|
|
foundIDs := make([]string, 0, len(products))
|
|
for _, product := range products {
|
|
foundIDs = append(foundIDs, product.ID)
|
|
}
|
|
|
|
skuMap, err := r.loadSKUsByProductIDs(ctx, foundIDs)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
return products, skuMap, 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 {
|
|
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
|
args[i] = id
|
|
}
|
|
|
|
query := fmt.Sprintf(`
|
|
SELECT id, spu_code, title, description, status, attrs, created_at, updated_at
|
|
FROM product_schema.products
|
|
WHERE id IN (%s)
|
|
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 (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 {
|
|
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
|
args[i] = id
|
|
}
|
|
|
|
query := fmt.Sprintf(`
|
|
SELECT id, product_id, name, price, stock, attributes, created_at, updated_at
|
|
FROM product_schema.skus
|
|
WHERE product_id IN (%s)
|
|
ORDER BY 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 scanProduct(scanner rowScanner) (*ProductRecord, error) {
|
|
var (
|
|
rec ProductRecord
|
|
status string
|
|
attrsJSON []byte
|
|
)
|
|
if err := scanner.Scan(
|
|
&rec.ID, &rec.SPUCode, &rec.Name, &rec.Description, &status, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt,
|
|
); err != nil {
|
|
return nil, fmt.Errorf("scan product: %w", err)
|
|
}
|
|
|
|
rec.Status = statusFromDB(status)
|
|
if len(attrsJSON) > 0 {
|
|
if err := json.Unmarshal(attrsJSON, &rec.Attrs); err != nil {
|
|
return nil, fmt.Errorf("unmarshal product attrs: %w", err)
|
|
}
|
|
}
|
|
return &rec, nil
|
|
}
|
|
|
|
func scanSKU(scanner rowScanner) (*SKURecord, error) {
|
|
var (
|
|
rec SKURecord
|
|
attrsJSON []byte
|
|
)
|
|
if err := scanner.Scan(
|
|
&rec.ID, &rec.ProductID, &rec.Name, &rec.Price, &rec.Stock, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt,
|
|
); err != nil {
|
|
return nil, fmt.Errorf("scan sku: %w", err)
|
|
}
|
|
|
|
rec.AttributesJSONB = string(attrsJSON)
|
|
if rec.AttributesJSONB == "" {
|
|
rec.AttributesJSONB = "{}"
|
|
}
|
|
return &rec, nil
|
|
}
|
|
|
|
func dedupeProductIDs(ids []string) []string {
|
|
seen := make(map[string]struct{}, len(ids))
|
|
out := make([]string, 0, len(ids))
|
|
for _, id := range ids {
|
|
if id == "" {
|
|
continue
|
|
}
|
|
if _, ok := seen[id]; ok {
|
|
continue
|
|
}
|
|
seen[id] = struct{}{}
|
|
out = append(out, id)
|
|
}
|
|
return out
|
|
}
|
|
|
|
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 statusToDB(status productv1.ProductStatus) string {
|
|
switch status {
|
|
case productv1.ProductStatus_PRODUCT_STATUS_DRAFT:
|
|
return "draft"
|
|
case productv1.ProductStatus_PRODUCT_STATUS_ON_SALE:
|
|
return "on_sale"
|
|
case productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE:
|
|
return "off_sale"
|
|
default:
|
|
return "unspecified"
|
|
}
|
|
}
|
|
|
|
func statusFromDB(status string) productv1.ProductStatus {
|
|
switch status {
|
|
case "draft":
|
|
return productv1.ProductStatus_PRODUCT_STATUS_DRAFT
|
|
case "on_sale":
|
|
return productv1.ProductStatus_PRODUCT_STATUS_ON_SALE
|
|
case "off_sale":
|
|
return productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE
|
|
default:
|
|
return productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED
|
|
}
|
|
}
|