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

4419 lines
136 KiB
Go
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package repository
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"sort"
"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")
// ErrCategoryNodeNotFound is returned when a category or product group node does not exist.
var ErrCategoryNodeNotFound = errors.New("category or group node not found")
// ErrStorefrontCategoryNotFound deliberately also covers a hidden category or
// a category below a hidden/missing ancestor. Storefront callers must not be
// able to distinguish those states from a category that does not exist.
var ErrStorefrontCategoryNotFound = errors.New("storefront category not found")
var ErrCategoryVersionConflict = errors.New("category version conflict")
var ErrCategoryTreeConflict = errors.New("category tree conflict")
var ErrCategoryNameExists = errors.New("category name already exists")
var ErrGroupNameExists = errors.New("group name already exists")
var ErrInvalidLeafCategory = errors.New("category must be an existing second-level category")
// ErrInvalidProductGroup is returned when a requested node is not a group in
// the current store.
var ErrInvalidProductGroup = errors.New("group must be an existing product group")
// ErrSKUNotFound is returned when a SKU does not exist.
var ErrSKUNotFound = errors.New("sku not found")
// ErrInsufficientStock is returned when stock - locked is less than the requested quantity.
var ErrInsufficientStock = errors.New("insufficient stock")
// ErrInsufficientLockedStock is returned when locked stock is less than the requested quantity.
var ErrInsufficientLockedStock = errors.New("insufficient locked stock")
// ErrInventoryAdjustmentConflict is returned when an idempotent inventory adjustment is replayed with different data.
var ErrInventoryAdjustmentConflict = errors.New("inventory adjustment conflict")
// ErrProductNotOnSale is returned when a new inventory reservation targets a product that is not on sale.
var ErrProductNotOnSale = errors.New("product is not on sale")
// ErrDuplicateSPUNo is returned when a non-deleted product already uses the SPU number.
var ErrDuplicateSPUNo = errors.New("spu_no already exists")
// ErrProductVersionConflict indicates that a concurrent product change won the optimistic-lock race.
var ErrProductVersionConflict = errors.New("product version conflict")
// ErrSKUVersionConflict indicates that a concurrent SKU or inventory change won the optimistic-lock race.
var ErrSKUVersionConflict = errors.New("sku version conflict")
// ErrSKUArchived is returned when an operation attempts to modify an archived SKU.
var ErrSKUArchived = errors.New("sku is archived")
// ErrSKUReplacementRequiresNotOnSale is returned when replacing SKUs for an on-sale product.
var ErrSKUReplacementRequiresNotOnSale = errors.New("sku replacement requires inventory or off-sale product status")
// ErrSameStore is returned when a store transfer targets the product's current store.
var ErrSameStore = errors.New("target store is the current store")
// ErrDuplicateSKUNo is returned when the destination store already has an active SKU number.
var ErrDuplicateSKUNo = errors.New("sku_no already exists in target store")
// 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
LeafCategoryIDs []string
CategoryBindingIDs []string
GroupIDs []string
GroupBindingIDs []string
Version int32
DeletedAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
Scope StoreScope
}
// ProductCountRecord contains aggregate counts for product.products.
type ProductCountRecord struct {
Total int64
Active int64
Draft int64
OnSale int64
OffSale int64
Deleted int64
}
// SKURecord is the persistence model for product.product_items.
type SKURecord struct {
ID string
ProductID string
SKUNo string
Name string
Price int64
SupplyPrice *int64
WeightKg *float64
Barcode string
ImageIDs []string
StockQuantity int32
LockedQuantity int32
SoldQuantity int32
AttributesJSON string
K1 string
V1 string
K2 string
V2 string
K3 string
V3 string
Status int32
IsArchived bool
ArchivedAt *time.Time
Version int32
DeletedAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
Inventory *InventoryRecord
}
// ProductSKUStockRecord is the compact current-SKU projection used by SKU list queries.
type ProductSKUStockRecord struct {
ID string
Name string
StockQuantity int32
SupplyPrice *int64
}
// InventoryRecord is the persistence model for product.product_item_inventory.
type InventoryRecord struct {
ID string
SKUID string
StockQuantity int32
LockedQuantity int32
SoldQuantity int32
Version int32
CreatedAt time.Time
UpdatedAt time.Time
}
// InventoryAdjustment is one order item quantity to confirm or release.
type InventoryAdjustment struct {
SKUID string
Quantity int32
}
// CartItemProductLookup identifies the SPU/SKU pair stored by one cart line.
// Line IDs are intentionally kept outside the repository because they belong to trade.cart_items.
type CartItemProductLookup struct {
ProductID string
SKUID string
}
// CartItemProductRecord contains the current catalog facts for one cart lookup.
// A nil Product or SKU means the corresponding record is missing or soft deleted.
type CartItemProductRecord struct {
ProductID string
SKUID string
Product *ProductRecord
SKU *SKURecord
}
// SKUChangeMode selects how SKU input is applied during a product update.
type SKUChangeMode int32
const (
SKUChangeModePatchExisting SKUChangeMode = 1
SKUChangeModeReplaceAll SKUChangeMode = 2
)
// SKUUpdate contains mutable fields for one existing current SKU.
type SKUUpdate struct {
ID string
ExpectedSKUVersion int32
ExpectedInventoryVersion int32
Name *string
Price *int64
SupplyPrice *int64
SupplyPriceSet bool
WeightKg *float64
WeightKgSet bool
Barcode *string
StockQuantity *int32
Status *int32
ImageIDs *[]string
}
// SKUChange is the optional SKU operation embedded in a product update.
type SKUChange struct {
Mode SKUChangeMode
PatchItems []SKUUpdate
ReplaceItems []SKURecord
}
// ProductUpdateInput is the atomically persisted product update payload.
type ProductUpdateInput struct {
Product ProductRecord
ExpectedVersion int32
SKUChange *SKUChange
// LeafCategoryIDs is nil when category bindings must remain unchanged. A
// non-nil empty slice clears all leaf-category bindings.
LeafCategoryIDs *[]string
CategoryBindingIDs []string
// GroupIDs is nil when group bindings must remain unchanged. A non-nil
// empty slice clears all product-group bindings.
GroupIDs *[]string
GroupBindingIDs []string
Scope StoreScope
}
// CategoryDeleteResult summarizes a destructive category deletion.
type CategoryDeleteResult struct {
DeletedCategoryID string
DeletedLevel int32
DeletedCategoryCount int32
UnboundProductCount int64
UnboundBindingCount int64
}
// SKUChangeResult records the SKU IDs affected by a product update.
type SKUChangeResult struct {
Mode SKUChangeMode
CreatedSKUIds []string
ArchivedSKUIds []string
UpdatedSKUIds []string
}
// ProductStatusUpdate contains the resulting status projection.
type ProductStatusUpdate struct {
ProductID string
PreviousStatus productv1.ProductStatus
Status productv1.ProductStatus
Version int32
UpdatedAt time.Time
}
// CategoryProductRecord is the product summary returned by product list endpoints.
type CategoryProductRecord struct {
ID string
SPUNo string
Title string
Status productv1.ProductStatus
ImageIDs []string
Price int64
SoldQuantity int64
StockQuantity int64
LockedQuantity int64
CreatedAt time.Time
UpdatedAt time.Time
}
// ProductListFilter contains the optional constraints for an admin product list.
type ProductListFilter struct {
CreatedAtFrom *time.Time
CreatedAtTo *time.Time
TitleKeyword string
SPUNo string
GroupID string
// ProductCategoryID identifies the standard business taxonomy stored in
// product.product_category. It is intentionally separate from storefront
// catalog categories and product groups.
ProductCategoryID string
GoodsType *int32
SoldQuantityMin *int64
SoldQuantityMax *int64
PriceMin *int64
PriceMax *int64
}
// CategoryRecord is the persistence model for product.catalog_category.
type CategoryRecord struct {
ID string
NodeType int32
Name string
ParentID string
Level int32
ImageIDs []string
SortNum int32
Status int32
CampaignID string
Version int32
// ProductCount is populated when listing product groups.
ProductCount int64
}
// CategoryFieldUpdate selects mutable fields of one category node.
type CategoryFieldUpdate struct {
ID string
ExpectedVersion int32
Name *string
ImageIDs *[]string
SortNum *int32
Status *int32
CampaignID *string
}
// CategoryTreeUpdate groups an optional root update with direct-child updates.
type CategoryTreeUpdate struct {
CategoryID string
Category *CategoryFieldUpdate
Children []CategoryFieldUpdate
NewChildren []CategoryRecord
}
// 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 = `
DO $$
BEGIN
IF to_regclass('product.catalog_category') IS NULL
AND to_regclass('product.product_category') IS NOT NULL THEN
ALTER TABLE product.product_category RENAME TO catalog_category;
END IF;
IF to_regclass('product.product_catalog_bindings') IS NULL
AND to_regclass('product.product_category_bindings') IS NOT NULL THEN
ALTER TABLE product.product_category_bindings RENAME TO product_catalog_bindings;
END IF;
END $$;
ALTER TABLE product.products
ALTER COLUMN id DROP DEFAULT;
ALTER TABLE product.product_catalog_bindings
ALTER COLUMN id DROP DEFAULT;
ALTER TABLE product.catalog_category
ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[];
ALTER TABLE product.catalog_category
ADD COLUMN IF NOT EXISTS version INTEGER NOT NULL DEFAULT 0;
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'chk_product_category_version'
AND connamespace = 'product'::regnamespace
) THEN
ALTER TABLE product.catalog_category
ADD CONSTRAINT chk_product_category_version CHECK (version >= 0);
END IF;
END $$;
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_schema = 'product'
AND table_name = 'catalog_category'
AND column_name = 'image_json'
) THEN
EXECUTE $migration$
UPDATE product.catalog_category
SET image_ids = CASE
WHEN jsonb_typeof(image_json) = 'array' THEN COALESCE(
(SELECT array_agg(image_id)
FROM jsonb_array_elements_text(image_json) AS image_id),
'{}'::VARCHAR[]
)
ELSE '{}'::VARCHAR[]
END
WHERE image_json IS NOT NULL
$migration$;
END IF;
END $$;
ALTER TABLE product.catalog_category
DROP COLUMN IF EXISTS image_json;
CREATE TABLE IF NOT EXISTS product.product_category (
id BIGINT PRIMARY KEY,
parent_id BIGINT REFERENCES product.product_category(id) ON DELETE RESTRICT,
level SMALLINT NOT NULL CHECK (level >= 1),
name VARCHAR(100) NOT NULL,
priority INTEGER NOT NULL DEFAULT 0,
rule_id VARCHAR(64) NOT NULL,
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
category_type SMALLINT NOT NULL,
channel_list INTEGER[] NOT NULL DEFAULT '{}'::INTEGER[],
has_children BOOLEAN NOT NULL DEFAULT FALSE,
has_prop_required BOOLEAN NOT NULL DEFAULT FALSE,
extra TEXT NOT NULL DEFAULT '',
cert_status_code INTEGER NOT NULL,
cert_status_pass BOOLEAN NOT NULL DEFAULT FALSE,
cert_status_msg VARCHAR(500) NOT NULL DEFAULT '',
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
deleted_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_product_category_active_parent_name
ON product.product_category (COALESCE(parent_id, 0), lower(btrim(name))) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_product_category_active_parent_priority
ON product.product_category (parent_id, priority, id) WHERE deleted_at IS NULL;
CREATE TABLE IF NOT EXISTS product.product_category_bindings (
id BIGINT PRIMARY KEY,
tenant_id BIGINT NOT NULL,
store_id BIGINT NOT NULL,
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
product_category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE RESTRICT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
deleted_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_bindings_active
ON product.product_category_bindings (product_id, product_category_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category
ON product.product_category_bindings (store_id, product_category_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_product
ON product.product_category_bindings (store_id, product_id) WHERE deleted_at IS NULL;
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),
supply_price BIGINT CONSTRAINT chk_product_items_supply_price CHECK (supply_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)),
is_archived BOOLEAN NOT NULL DEFAULT FALSE,
archived_at TIMESTAMPTZ,
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(),
CONSTRAINT chk_product_items_archived
CHECK ((is_archived = FALSE AND archived_at IS NULL) OR (is_archived = TRUE AND archived_at IS NOT NULL))
);
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),
stock_quantity INTEGER NOT NULL DEFAULT 0 CHECK (stock_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 TABLE IF NOT EXISTS product.inventory_adjustments (
order_id BIGINT NOT NULL,
action VARCHAR(20) NOT NULL,
sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE,
quantity INTEGER NOT NULL CHECK (quantity > 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (order_id, action, sku_id),
CONSTRAINT chk_inventory_adjustments_action CHECK (action IN ('confirm', 'release'))
);
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[];
ALTER TABLE product.product_items
ADD COLUMN IF NOT EXISTS supply_price BIGINT;
ALTER TABLE product.product_items
ADD COLUMN IF NOT EXISTS is_archived BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE product.product_items
ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;
CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL AND is_archived = FALSE;
CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL AND is_archived = FALSE;
CREATE INDEX IF NOT EXISTS idx_products_active_created_id ON product.products(created_at DESC, id DESC) WHERE deleted_at IS NULL;
ALTER TABLE product.products ADD COLUMN IF NOT EXISTS tenant_id BIGINT;
ALTER TABLE product.products ADD COLUMN IF NOT EXISTS store_id BIGINT;
ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS tenant_id BIGINT;
ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS store_id BIGINT;
ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS campaign_id BIGINT;
ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS tenant_id BIGINT;
ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS store_id BIGINT;
ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS weight_kg DOUBLE PRECISION;
ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS barcode VARCHAR(64);
DROP INDEX IF EXISTS product.uq_products_spu_no;
CREATE UNIQUE INDEX IF NOT EXISTS uq_products_store_spu_no ON product.products (store_id, spu_no) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_products_store_id ON product.products (store_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_id ON product.catalog_category (store_id);
CREATE INDEX IF NOT EXISTS idx_product_category_campaign_id
ON product.catalog_category (campaign_id) WHERE campaign_id IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_group_normalized_name
ON product.catalog_category (
store_id,
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
)
WHERE node_type = 2;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_sibling_normalized_name
ON product.catalog_category (
store_id,
COALESCE(parent_id, 0),
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
)
WHERE node_type = 1;
DROP INDEX IF EXISTS product.uq_product_items_sku_no;
DROP INDEX IF EXISTS product.uq_product_items_sku_no_active;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_store_sku_no_active
ON product.product_items (store_id, sku_no)
WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE;
CREATE INDEX IF NOT EXISTS idx_product_items_store_id ON product.product_items (store_id) WHERE deleted_at IS NULL;
CREATE TABLE IF NOT EXISTS product.suppliers (
id BIGINT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
alias VARCHAR(100) NOT NULL DEFAULT '',
supplier_code VARCHAR(64) NOT NULL,
attachments JSONB NOT NULL DEFAULT '[]'::JSONB,
contact_name VARCHAR(100) NOT NULL DEFAULT '',
contact_phone VARCHAR(32) NOT NULL DEFAULT '',
remark VARCHAR(1000) NOT NULL DEFAULT '',
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
tenant_id BIGINT NOT NULL,
store_id BIGINT NOT NULL,
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
deleted_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_suppliers_store_code_active
ON product.suppliers (store_id, supplier_code) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_suppliers_store_list
ON product.suppliers (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL;
CREATE TABLE IF NOT EXISTS product.brands (
id BIGINT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
alias VARCHAR(100) NOT NULL DEFAULT '',
brand_code VARCHAR(64) NOT NULL,
supplier_id BIGINT NOT NULL,
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
tenant_id BIGINT NOT NULL,
store_id BIGINT NOT NULL,
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
deleted_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_brands_store_code_active
ON product.brands (store_id, brand_code) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_brands_store_list
ON product.brands (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_brands_supplier
ON product.brands (store_id, supplier_id) WHERE deleted_at IS NULL;
`
if _, err := r.db.ExecContext(ctx, ddl); err != nil {
return fmt.Errorf("ensure product tables: %w", err)
}
if err := r.ensureFreightTemplateSchema(ctx); err != nil {
return fmt.Errorf("ensure freight template schema: %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) {
if err := requireWriteScope(product.Scope); err != nil {
return nil, nil, err
}
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 len(product.LeafCategoryIDs) > 0 {
if err := replaceProductLeafCategoryBindings(ctx, tx, createdProduct.ID, product.LeafCategoryIDs, product.CategoryBindingIDs, product.Scope); err != nil {
return nil, nil, err
}
}
if len(product.GroupIDs) > 0 {
if err := replaceProductGroupBindings(ctx, tx, createdProduct.ID, product.GroupIDs, product.GroupBindingIDs, product.Scope); 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, scope StoreScope) (*CategoryRecord, []*CategoryRecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, nil, err
}
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, scope)
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, scope)
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, scope StoreScope) (*CategoryRecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
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, scope)
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
}
// UpdateCategoryTrees applies all requested root and direct-child patches in a
// single transaction. Callers must supply already-validated patch fields.
func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []CategoryTreeUpdate, scope StoreScope) error {
if err := requireWriteScope(scope); err != nil {
return err
}
if len(updates) == 0 {
return errors.New("category_trees is required")
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin update category trees: %w", err)
}
defer tx.Rollback()
for _, tree := range updates {
root, err := loadCategoryForUpdate(ctx, tx, tree.CategoryID, scope)
if err != nil {
return err
}
if root.NodeType != 1 || root.Level != 1 || root.ParentID != "" {
return ErrCategoryTreeConflict
}
if tree.Category != nil {
if tree.Category.ID != tree.CategoryID {
return ErrCategoryTreeConflict
}
if _, err := updateCategoryFields(ctx, tx, *tree.Category); err != nil {
return err
}
}
for _, child := range tree.Children {
current, err := loadCategoryForUpdate(ctx, tx, child.ID, scope)
if err != nil {
return err
}
if current.NodeType != 1 || current.Level != 2 || current.ParentID != tree.CategoryID {
return ErrCategoryTreeConflict
}
if _, err := updateCategoryFields(ctx, tx, child); err != nil {
return err
}
}
for _, child := range tree.NewChildren {
child.NodeType = 1
child.ParentID = tree.CategoryID
child.Level = 2
if _, err := insertCategoryNode(ctx, tx, child, scope); err != nil {
return err
}
}
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit update category trees: %w", err)
}
return nil
}
// DeleteCategory removes a leaf category or a complete top-level category tree
// and all affected product bindings in one transaction. Product rows and group
// bindings are deliberately retained.
func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID string, expectedVersion int32, scope StoreScope) (*CategoryDeleteResult, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
if expectedVersion < 0 {
return nil, errors.New("expected_version must be non-negative")
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin delete category: %w", err)
}
defer tx.Rollback()
target, err := loadCategoryForUpdate(ctx, tx, categoryID, scope)
if err != nil {
return nil, err
}
if target.NodeType != 1 || (target.Level != 1 && target.Level != 2) {
return nil, ErrCategoryTreeConflict
}
if target.Version != expectedVersion {
return nil, ErrCategoryVersionConflict
}
categoryIDs := []int64{}
targetID, err := parseID(target.ID, "category_id")
if err != nil {
return nil, err
}
if target.Level == 1 {
rows, err := tx.QueryContext(ctx, `
SELECT id, node_type, name, parent_id, level,
COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, campaign_id, version
FROM product.catalog_category
WHERE parent_id = $1 AND store_id = $2
FOR UPDATE
`, targetID, scope.StoreID)
if err != nil {
return nil, fmt.Errorf("load category children for delete: %w", err)
}
for rows.Next() {
child, err := scanCategory(rows)
if err != nil {
rows.Close()
return nil, err
}
if child.NodeType != 1 || child.Level != 2 || child.ParentID != target.ID {
rows.Close()
return nil, ErrCategoryTreeConflict
}
childID, err := parseID(child.ID, "category_id")
if err != nil {
rows.Close()
return nil, err
}
categoryIDs = append(categoryIDs, childID)
}
if err := rows.Err(); err != nil {
rows.Close()
return nil, fmt.Errorf("iterate category children for delete: %w", err)
}
if err := rows.Close(); err != nil {
return nil, fmt.Errorf("close category children for delete: %w", err)
}
}
categoryIDs = append(categoryIDs, targetID)
placeholders := make([]string, len(categoryIDs))
args := make([]any, len(categoryIDs))
for index, id := range categoryIDs {
placeholders[index] = fmt.Sprintf("$%d", index+1)
args[index] = id
}
whereIDs := strings.Join(placeholders, ", ")
result := &CategoryDeleteResult{
DeletedCategoryID: target.ID,
DeletedLevel: target.Level,
DeletedCategoryCount: int32(len(categoryIDs)),
}
if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
SELECT COUNT(DISTINCT product_id), COUNT(*)
FROM product.product_catalog_bindings
WHERE category_id IN (%s)
`, whereIDs), args...).Scan(&result.UnboundProductCount, &result.UnboundBindingCount); err != nil {
return nil, fmt.Errorf("count category bindings for delete: %w", err)
}
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`
DELETE FROM product.product_catalog_bindings
WHERE category_id IN (%s)
`, whereIDs), args...); err != nil {
return nil, fmt.Errorf("delete category bindings: %w", err)
}
if target.Level == 1 {
if _, err := tx.ExecContext(ctx, `DELETE FROM product.catalog_category WHERE parent_id = $1 AND store_id = $2`, targetID, scope.StoreID); err != nil {
return nil, fmt.Errorf("delete child categories: %w", err)
}
}
if _, err := tx.ExecContext(ctx, `DELETE FROM product.catalog_category WHERE id = $1 AND store_id = $2`, targetID, scope.StoreID); err != nil {
return nil, fmt.Errorf("delete category: %w", err)
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit delete category: %w", err)
}
return result, nil
}
// GroupDeleteResult summarizes a destructive product-group deletion.
type GroupDeleteResult struct {
DeletedGroupID string
UnboundProductCount int64
UnboundBindingCount int64
}
// UpdateGroup applies a field patch to one product group (node_type=2).
func (r *ProductRepository) UpdateGroup(ctx context.Context, update CategoryFieldUpdate, scope StoreScope) (*CategoryRecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
if update.ExpectedVersion < 0 {
return nil, errors.New("expected_version must be non-negative")
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin update group: %w", err)
}
defer tx.Rollback()
current, err := loadCategoryForUpdate(ctx, tx, update.ID, scope)
if err != nil {
return nil, err
}
if current.NodeType != 2 {
return nil, ErrInvalidProductGroup
}
if current.Version != update.ExpectedVersion {
return nil, ErrCategoryVersionConflict
}
updated, err := updateCategoryFields(ctx, tx, update)
if err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit update group: %w", err)
}
return updated, nil
}
// DeleteGroup hard-deletes one product group and its bindings. Products are retained.
func (r *ProductRepository) DeleteGroup(ctx context.Context, groupID string, expectedVersion int32, scope StoreScope) (*GroupDeleteResult, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
if expectedVersion < 0 {
return nil, errors.New("expected_version must be non-negative")
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin delete group: %w", err)
}
defer tx.Rollback()
target, err := loadCategoryForUpdate(ctx, tx, groupID, scope)
if err != nil {
return nil, err
}
if target.NodeType != 2 {
return nil, ErrInvalidProductGroup
}
if target.Version != expectedVersion {
return nil, ErrCategoryVersionConflict
}
targetID, err := parseID(target.ID, "group_id")
if err != nil {
return nil, err
}
result := &GroupDeleteResult{DeletedGroupID: target.ID}
if err := tx.QueryRowContext(ctx, `
SELECT COUNT(DISTINCT product_id), COUNT(*)
FROM product.product_catalog_bindings
WHERE category_id = $1
`, targetID).Scan(&result.UnboundProductCount, &result.UnboundBindingCount); err != nil {
return nil, fmt.Errorf("count group bindings for delete: %w", err)
}
if _, err := tx.ExecContext(ctx, `
DELETE FROM product.product_catalog_bindings
WHERE category_id = $1
`, targetID); err != nil {
return nil, fmt.Errorf("delete group bindings: %w", err)
}
if _, err := tx.ExecContext(ctx, `
DELETE FROM product.catalog_category
WHERE id = $1 AND store_id = $2 AND node_type = 2
`, targetID, scope.StoreID); err != nil {
return nil, fmt.Errorf("delete group: %w", err)
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit delete group: %w", err)
}
return result, nil
}
func loadCategoryForUpdate(ctx context.Context, tx *sql.Tx, categoryID string, scope StoreScope) (*CategoryRecord, error) {
id, err := parseID(categoryID, "category_id")
if err != nil {
return nil, err
}
if err := requireWriteScope(scope); err != nil {
return nil, err
}
row := tx.QueryRowContext(ctx, `
SELECT id, node_type, name, parent_id, level,
COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, campaign_id, version
FROM product.catalog_category
WHERE id = $1 AND store_id = $2
FOR UPDATE`, id, scope.StoreID)
category, err := scanCategory(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrCategoryNodeNotFound
}
if err != nil {
return nil, fmt.Errorf("load category for update: %w", err)
}
return category, nil
}
func updateCategoryFields(ctx context.Context, tx *sql.Tx, update CategoryFieldUpdate) (*CategoryRecord, error) {
if update.Name == nil && update.ImageIDs == nil && update.SortNum == nil && update.Status == nil && update.CampaignID == nil {
return nil, errors.New("category update has no fields")
}
id, err := parseID(update.ID, "category_id")
if err != nil {
return nil, err
}
campaignID, err := nullableCategoryCampaignID(update.CampaignID)
if err != nil {
return nil, err
}
row := tx.QueryRowContext(ctx, `
UPDATE product.catalog_category
SET name = CASE WHEN $3 THEN $4 ELSE name END,
image_ids = CASE WHEN $5 THEN $6 ELSE image_ids END,
sort_num = CASE WHEN $7 THEN $8 ELSE sort_num END,
status = CASE WHEN $9 THEN $10 ELSE status END,
campaign_id = CASE WHEN $11 THEN $12 ELSE campaign_id END,
version = version + 1
WHERE id = $1 AND version = $2
RETURNING id, node_type, name, parent_id, level,
COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, campaign_id, version`,
id, update.ExpectedVersion,
update.Name != nil, stringValue(update.Name),
update.ImageIDs != nil, stringSliceOrEmpty(pointerStringSlice(update.ImageIDs)),
update.SortNum != nil, int32Value(update.SortNum),
update.Status != nil, int32Value(update.Status),
update.CampaignID != nil, campaignID,
)
category, err := scanCategory(row)
if nameConflict := categoryNameConflictError(err); nameConflict != nil {
return nil, nameConflict
}
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrCategoryVersionConflict
}
if err != nil {
return nil, fmt.Errorf("update category fields: %w", err)
}
return category, nil
}
func nullableCategoryCampaignID(value *string) (sql.NullInt64, error) {
if value == nil || strings.TrimSpace(*value) == "" {
return sql.NullInt64{}, nil
}
id, err := parseID(strings.TrimSpace(*value), "campaign_id")
if err != nil {
return sql.NullInt64{}, err
}
return sql.NullInt64{Int64: id, Valid: true}, nil
}
func stringValue(value *string) string {
if value == nil {
return ""
}
return *value
}
func int32Value(value *int32) int32 {
if value == nil {
return 0
}
return *value
}
func pointerStringSlice(value *[]string) []string {
if value == nil {
return nil
}
return *value
}
// AddProductsToGroup binds every product to a product group in one transaction.
// Existing bindings are retained and duplicate bindings are ignored.
func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID string, bindingIDs, productIDs []string, scope StoreScope) error {
return r.addProductsToCategoryNode(ctx, groupID, bindingIDs, productIDs, 2, 0, "group", scope)
}
// AddProductsToCategory binds every product to a second-level category in one
// transaction. Existing bindings are retained and duplicate bindings are ignored.
func (r *ProductRepository) AddProductsToCategory(ctx context.Context, categoryID string, bindingIDs, productIDs []string, scope StoreScope) error {
return r.addProductsToCategoryNode(ctx, categoryID, bindingIDs, productIDs, 1, 2, "category", scope)
}
func (r *ProductRepository) addProductsToCategoryNode(ctx context.Context, nodeID string, bindingIDs, productIDs []string, nodeType, level int32, nodeLabel string, scope StoreScope) error {
if err := requireWriteScope(scope); err != nil {
return err
}
if len(productIDs) == 0 {
return errors.New("product_ids is required")
}
if len(bindingIDs) != len(productIDs) {
return errors.New("binding ids must match product ids")
}
parsedNodeID, err := parseID(nodeID, nodeLabel+"_id")
if err != nil {
return err
}
parsedProductIDs := make([]int64, len(productIDs))
parsedBindingIDs := make([]int64, len(bindingIDs))
for i := range productIDs {
parsedProductIDs[i], err = parseID(productIDs[i], "product_id")
if err != nil {
return err
}
parsedBindingIDs[i], err = parseID(bindingIDs[i], "category binding id")
if err != nil {
return err
}
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin add products to %s: %w", nodeLabel, err)
}
defer tx.Rollback()
err = tx.QueryRowContext(ctx, `
SELECT id
FROM product.catalog_category
WHERE id = $1
AND node_type = $2
AND store_id = $3
AND ($4 = 0 OR level = $4)
`, parsedNodeID, nodeType, scope.StoreID, level).Scan(&parsedNodeID)
if errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, nodeID)
}
if err != nil {
return fmt.Errorf("query %s node %s: %w", nodeLabel, nodeID, err)
}
productPlaceholders := make([]string, len(parsedProductIDs))
productArgs := make([]any, len(parsedProductIDs))
for i, productID := range parsedProductIDs {
productPlaceholders[i] = fmt.Sprintf("$%d", i+1)
productArgs[i] = productID
}
productArgs = append(productArgs, scope.StoreID)
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
SELECT id
FROM product.products
WHERE deleted_at IS NULL
AND store_id = $%d
AND id IN (%s)
`, len(productArgs), strings.Join(productPlaceholders, ", ")), productArgs...)
if err != nil {
return fmt.Errorf("query products for %s binding: %w", nodeLabel, err)
}
foundProducts := make(map[int64]struct{}, len(parsedProductIDs))
for rows.Next() {
var productID int64
if err := rows.Scan(&productID); err != nil {
return fmt.Errorf("scan product for %s binding: %w", nodeLabel, err)
}
foundProducts[productID] = struct{}{}
}
if err := rows.Err(); err != nil {
return fmt.Errorf("iterate products for %s binding: %w", nodeLabel, err)
}
if err := rows.Close(); err != nil {
return fmt.Errorf("close products for %s binding: %w", nodeLabel, err)
}
for i, productID := range parsedProductIDs {
if _, ok := foundProducts[productID]; !ok {
return fmt.Errorf("%w: %s", ErrProductNotFound, productIDs[i])
}
}
valuePlaceholders := make([]string, len(parsedProductIDs))
args := make([]any, 0, len(parsedProductIDs)*3)
for i, productID := range parsedProductIDs {
base := i * 3
valuePlaceholders[i] = fmt.Sprintf("($%d, $%d, $%d)", base+1, base+2, base+3)
args = append(args, parsedBindingIDs[i], productID, parsedNodeID)
}
_, err = tx.ExecContext(ctx, fmt.Sprintf(`
INSERT INTO product.product_catalog_bindings (id, product_id, category_id)
VALUES %s
ON CONFLICT (product_id, category_id) DO NOTHING
`, strings.Join(valuePlaceholders, ", ")), args...)
if err != nil {
return fmt.Errorf("insert product %s bindings: %w", nodeLabel, err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit add products to %s: %w", nodeLabel, err)
}
return nil
}
// RemoveProductsFromGroup removes product bindings from the requested category or product group in one transaction.
// Missing bindings are ignored so callers can safely retry the same request.
func (r *ProductRepository) RemoveProductsFromGroup(ctx context.Context, groupID string, productIDs []string, scope StoreScope) error {
if err := requireWriteScope(scope); err != nil {
return err
}
if len(productIDs) == 0 {
return errors.New("product_ids is required")
}
parsedGroupID, err := parseID(groupID, "group_id")
if err != nil {
return err
}
parsedProductIDs := make([]int64, len(productIDs))
for i := range productIDs {
parsedProductIDs[i], err = parseID(productIDs[i], "product_id")
if err != nil {
return err
}
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin remove products from group: %w", err)
}
defer tx.Rollback()
err = tx.QueryRowContext(ctx, `
SELECT id
FROM product.catalog_category
WHERE id = $1 AND node_type = 2 AND store_id = $2
`, parsedGroupID, scope.StoreID).Scan(&parsedGroupID)
if errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID)
}
if err != nil {
return fmt.Errorf("query category or group node %s: %w", groupID, err)
}
placeholders := make([]string, len(parsedProductIDs))
args := make([]any, 0, len(parsedProductIDs)+1)
args = append(args, parsedGroupID)
for i, productID := range parsedProductIDs {
placeholders[i] = fmt.Sprintf("$%d", i+2)
args = append(args, productID)
}
_, err = tx.ExecContext(ctx, fmt.Sprintf(`
DELETE FROM product.product_catalog_bindings
WHERE category_id = $1
AND product_id IN (%s)
`, strings.Join(placeholders, ", ")), args...)
if err != nil {
return fmt.Errorf("delete product category or group bindings: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit remove products from group: %w", 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("{}")
}
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
}
// UpdateProductWithSKUChange atomically persists a merged SPU update and an optional SKU operation.
func (r *ProductRepository) UpdateProductWithSKUChange(ctx context.Context, input ProductUpdateInput) (*SKUChangeResult, error) {
if err := requireWriteScope(input.Scope); err != nil {
return nil, err
}
if input.ExpectedVersion < 0 {
return nil, fmt.Errorf("expected product version must be non-negative")
}
productID, err := parseID(input.Product.ID, "product id")
if err != nil {
return nil, err
}
attrs, err := productCrossBorderJSON(input.Product)
if err != nil {
return nil, err
}
brandID, err := nullableID(input.Product.BrandID, "brand_id")
if err != nil {
return nil, err
}
supplierID, err := nullableID(input.Product.SupplierID, "supplier_id")
if err != nil {
return nil, err
}
freightTemplateID, err := nullableID(input.Product.FreightTemplateID, "freight_template_id")
if err != nil {
return nil, err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin update product: %w", err)
}
defer tx.Rollback()
var currentStatus int16
var currentVersion int32
err = tx.QueryRowContext(ctx, `
SELECT status, version
FROM product.products
WHERE id = $1 AND deleted_at IS NULL AND store_id = $2
FOR UPDATE
`, productID, input.Scope.StoreID).Scan(&currentStatus, &currentVersion)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrProductNotFound
}
if err != nil {
return nil, fmt.Errorf("lock product %s: %w", input.Product.ID, err)
}
if currentVersion != input.ExpectedVersion {
return nil, ErrProductVersionConflict
}
if input.LeafCategoryIDs != nil {
if err := replaceProductLeafCategoryBindings(ctx, tx, input.Product.ID, *input.LeafCategoryIDs, input.CategoryBindingIDs, input.Scope); err != nil {
return nil, err
}
}
if input.GroupIDs != nil {
if err := replaceProductGroupBindings(ctx, tx, input.Product.ID, *input.GroupIDs, input.GroupBindingIDs, input.Scope); err != nil {
return nil, err
}
}
if input.SKUChange != nil && input.SKUChange.Mode == SKUChangeModeReplaceAll && statusFromDB(currentStatus) == productv1.ProductStatus_PRODUCT_STATUS_ON_SALE {
return nil, ErrSKUReplacementRequiresNotOnSale
}
if _, err := tx.ExecContext(ctx, `
UPDATE product.products
SET title = $2,
selling_point = $3,
brand_id = $4,
supplier_id = $5,
image_ids = $6,
detail_html = $7,
member_discount_enabled = $8,
goods_type = $9,
service_guarantees = $10,
cross_border = $11::jsonb,
freight_charge_type = $12,
freight_fixed_amount = $13,
freight_template_id = $14,
sale_time_type = $15,
scheduled_sale_time = $16,
version = version + 1,
updated_at = NOW()
WHERE id = $1 AND version = $17 AND deleted_at IS NULL AND store_id = $18
`, productID, input.Product.Title, input.Product.SellingPoint, brandID, supplierID,
stringSliceOrEmpty(input.Product.ImageIDs), input.Product.DetailHTML, input.Product.MemberDiscountEnabled,
int16(input.Product.GoodsType), stringSliceOrEmpty(input.Product.ServiceGuarantees), attrs,
int16(input.Product.FreightChargeType), input.Product.FreightFixedAmount, freightTemplateID,
int16(input.Product.SaleTimeType), input.Product.ScheduledSaleTime, input.ExpectedVersion, input.Scope.StoreID); err != nil {
return nil, fmt.Errorf("update product %s: %w", input.Product.ID, err)
}
result := &SKUChangeResult{}
if input.SKUChange != nil {
result.Mode = input.SKUChange.Mode
switch input.SKUChange.Mode {
case SKUChangeModePatchExisting:
for _, item := range input.SKUChange.PatchItems {
if err := updateCurrentSKU(ctx, tx, productID, item); err != nil {
return nil, err
}
result.UpdatedSKUIds = append(result.UpdatedSKUIds, item.ID)
}
case SKUChangeModeReplaceAll:
if len(input.SKUChange.ReplaceItems) == 0 {
return nil, fmt.Errorf("replace_items must not be empty")
}
archivedIDs, err := archiveCurrentSKUs(ctx, tx, productID)
if err != nil {
return nil, err
}
result.ArchivedSKUIds = archivedIDs
for _, sku := range input.SKUChange.ReplaceItems {
createdSKU, err := insertSKU(ctx, tx, input.Product.ID, sku)
if err != nil {
return nil, err
}
result.CreatedSKUIds = append(result.CreatedSKUIds, createdSKU.ID)
}
default:
return nil, fmt.Errorf("unsupported sku change mode")
}
if err := autoOffSaleIfNoSellableSKU(ctx, tx, productID); err != nil {
return nil, err
}
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit update product: %w", err)
}
return result, nil
}
func replaceProductLeafCategoryBindings(ctx context.Context, tx *sql.Tx, productID string, leafCategoryIDs []string, bindingIDs []string, scope StoreScope) error {
if err := requireWriteScope(scope); err != nil {
return err
}
if len(leafCategoryIDs) != len(bindingIDs) {
return errors.New("leaf category ids and category binding ids must have the same length")
}
parsedProductID, err := parseID(productID, "product_id")
if err != nil {
return err
}
parsedLeafCategoryIDs := make([]int64, len(leafCategoryIDs))
seenCategoryIDs := make(map[int64]struct{}, len(leafCategoryIDs))
for index, categoryID := range leafCategoryIDs {
parsedLeafCategoryIDs[index], err = parseID(categoryID, "leaf_category_id")
if err != nil {
return err
}
if _, duplicate := seenCategoryIDs[parsedLeafCategoryIDs[index]]; duplicate {
return errors.New("leaf_catalog_category_ids must not contain duplicates")
}
seenCategoryIDs[parsedLeafCategoryIDs[index]] = struct{}{}
if _, err := parseID(bindingIDs[index], "category binding id"); err != nil {
return err
}
}
if len(parsedLeafCategoryIDs) > 0 {
placeholders := make([]string, len(parsedLeafCategoryIDs))
args := make([]any, len(parsedLeafCategoryIDs))
for index, categoryID := range parsedLeafCategoryIDs {
placeholders[index] = fmt.Sprintf("$%d", index+1)
args[index] = categoryID
}
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
SELECT id
FROM product.catalog_category
WHERE node_type = 1
AND level = 2
AND store_id = $%d
AND id IN (%s)
FOR KEY SHARE
`, len(args)+1, strings.Join(placeholders, ", ")), append(args, scope.StoreID)...)
if err != nil {
return fmt.Errorf("validate leaf categories: %w", err)
}
found := make(map[int64]struct{}, len(parsedLeafCategoryIDs))
for rows.Next() {
var categoryID int64
if err := rows.Scan(&categoryID); err != nil {
rows.Close()
return fmt.Errorf("scan leaf category: %w", err)
}
found[categoryID] = struct{}{}
}
if err := rows.Err(); err != nil {
rows.Close()
return fmt.Errorf("iterate leaf categories: %w", err)
}
if err := rows.Close(); err != nil {
return fmt.Errorf("close leaf categories: %w", err)
}
if len(found) != len(parsedLeafCategoryIDs) {
return ErrInvalidLeafCategory
}
}
if _, err := tx.ExecContext(ctx, `
DELETE FROM product.product_catalog_bindings AS b
USING product.catalog_category AS c
WHERE b.product_id = $1
AND b.category_id = c.id
AND c.node_type = 1
AND c.level = 2
AND c.store_id = $2
`, parsedProductID, scope.StoreID); err != nil {
return fmt.Errorf("delete product leaf category bindings: %w", err)
}
for index, categoryID := range leafCategoryIDs {
if err := insertCategoryBinding(ctx, tx, bindingIDs[index], productID, categoryID); err != nil {
return err
}
}
return nil
}
// replaceProductGroupBindings replaces only the product's group bindings. It
// deliberately leaves category bindings intact.
func replaceProductGroupBindings(ctx context.Context, tx *sql.Tx, productID string, groupIDs []string, bindingIDs []string, scope StoreScope) error {
if err := requireWriteScope(scope); err != nil {
return err
}
if len(groupIDs) != len(bindingIDs) {
return errors.New("group ids and group binding ids must have the same length")
}
parsedProductID, err := parseID(productID, "product_id")
if err != nil {
return err
}
parsedGroupIDs := make([]int64, len(groupIDs))
seenGroupIDs := make(map[int64]struct{}, len(groupIDs))
for index, groupID := range groupIDs {
parsedGroupIDs[index], err = parseID(groupID, "group_id")
if err != nil {
return err
}
if _, duplicate := seenGroupIDs[parsedGroupIDs[index]]; duplicate {
return errors.New("group_ids must not contain duplicates")
}
seenGroupIDs[parsedGroupIDs[index]] = struct{}{}
if _, err := parseID(bindingIDs[index], "group binding id"); err != nil {
return err
}
}
if len(parsedGroupIDs) > 0 {
placeholders := make([]string, len(parsedGroupIDs))
args := make([]any, len(parsedGroupIDs))
for index, groupID := range parsedGroupIDs {
placeholders[index] = fmt.Sprintf("$%d", index+1)
args[index] = groupID
}
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
SELECT id
FROM product.catalog_category
WHERE node_type = 2
AND store_id = $%d
AND id IN (%s)
FOR KEY SHARE
`, len(args)+1, strings.Join(placeholders, ", ")), append(args, scope.StoreID)...)
if err != nil {
return fmt.Errorf("validate product groups: %w", err)
}
found := make(map[int64]struct{}, len(parsedGroupIDs))
for rows.Next() {
var groupID int64
if err := rows.Scan(&groupID); err != nil {
rows.Close()
return fmt.Errorf("scan product group: %w", err)
}
found[groupID] = struct{}{}
}
if err := rows.Err(); err != nil {
rows.Close()
return fmt.Errorf("iterate product groups: %w", err)
}
if err := rows.Close(); err != nil {
return fmt.Errorf("close product groups: %w", err)
}
if len(found) != len(parsedGroupIDs) {
return ErrInvalidProductGroup
}
}
if _, err := tx.ExecContext(ctx, `
DELETE FROM product.product_catalog_bindings AS b
USING product.catalog_category AS c
WHERE b.product_id = $1
AND b.category_id = c.id
AND c.node_type = 2
AND c.store_id = $2
`, parsedProductID, scope.StoreID); err != nil {
return fmt.Errorf("delete product group bindings: %w", err)
}
for index, groupID := range groupIDs {
if err := insertCategoryBinding(ctx, tx, bindingIDs[index], productID, groupID); err != nil {
return err
}
}
return nil
}
// UpdateProductStatus changes the product lifecycle state using optimistic locking.
func (r *ProductRepository) UpdateProductStatus(ctx context.Context, productID string, next productv1.ProductStatus, expectedVersion int32, scope StoreScope) (*ProductStatusUpdate, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
if expectedVersion < 0 {
return nil, fmt.Errorf("expected product version must be non-negative")
}
if next != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY && next != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE && next != productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE {
return nil, fmt.Errorf("unsupported product status")
}
id, err := parseID(productID, "product id")
if err != nil {
return nil, err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin update product status: %w", err)
}
defer tx.Rollback()
var previousDBStatus int16
var currentVersion int32
err = tx.QueryRowContext(ctx, `
SELECT status, version
FROM product.products
WHERE id = $1 AND deleted_at IS NULL AND store_id = $2
FOR UPDATE
`, id, scope.StoreID).Scan(&previousDBStatus, &currentVersion)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrProductNotFound
}
if err != nil {
return nil, fmt.Errorf("lock product %s: %w", productID, err)
}
if currentVersion != expectedVersion {
return nil, ErrProductVersionConflict
}
if next == productv1.ProductStatus_PRODUCT_STATUS_ON_SALE {
sellable, err := hasSellableSKU(ctx, tx, id)
if err != nil {
return nil, err
}
if !sellable {
return nil, fmt.Errorf("cannot put product on sale without a sellable sku")
}
}
result := &ProductStatusUpdate{ProductID: productID, PreviousStatus: statusFromDB(previousDBStatus), Status: next}
if result.PreviousStatus == next {
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit unchanged product status: %w", err)
}
result.Version = currentVersion
return result, nil
}
if err := tx.QueryRowContext(ctx, `
UPDATE product.products
SET status = $2, version = version + 1, updated_at = NOW()
WHERE id = $1 AND version = $3 AND deleted_at IS NULL AND store_id = $4
RETURNING version, updated_at
`, id, statusToDB(next), expectedVersion, scope.StoreID).Scan(&result.Version, &result.UpdatedAt); err != nil {
return nil, fmt.Errorf("update product status %s: %w", productID, err)
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit update product status: %w", err)
}
return result, nil
}
// TransferProductStoreResult is the identity after a same-tenant store move.
type TransferProductStoreResult struct {
ProductID string
TenantID int64
StoreID int64
}
// TransferProductStore moves a product and its SKUs to another store. Tenant stays unchanged.
// Category bindings are dropped because categories are store-scoped.
func (r *ProductRepository) TransferProductStore(ctx context.Context, productID string, targetStoreID int64, scope StoreScope) (*TransferProductStoreResult, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
if targetStoreID <= 0 {
return nil, fmt.Errorf("target store id must be a positive snowflake id")
}
if targetStoreID == scope.StoreID {
return nil, ErrSameStore
}
id, err := parseID(productID, "product id")
if err != nil {
return nil, err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin transfer product store: %w", err)
}
defer tx.Rollback()
var tenantID int64
var spuNo string
err = tx.QueryRowContext(ctx, `
SELECT tenant_id, spu_no
FROM product.products
WHERE id = $1 AND deleted_at IS NULL AND store_id = $2 AND tenant_id = $3
FOR UPDATE
`, id, scope.StoreID, scope.TenantID).Scan(&tenantID, &spuNo)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrProductNotFound
}
if err != nil {
return nil, fmt.Errorf("lock product %s: %w", productID, err)
}
var taken int
if err := tx.QueryRowContext(ctx, `
SELECT 1
FROM product.products
WHERE store_id = $1 AND spu_no = $2 AND deleted_at IS NULL AND id <> $3
LIMIT 1
`, targetStoreID, spuNo, id).Scan(&taken); err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("check target spu_no: %w", err)
}
if taken == 1 {
return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, spuNo)
}
var conflictSKU string
if err := tx.QueryRowContext(ctx, `
SELECT pi.sku_no
FROM product.product_items pi
WHERE pi.product_id = $1
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
AND pi.sku_no IS NOT NULL
AND EXISTS (
SELECT 1
FROM product.product_items other
WHERE other.store_id = $2
AND other.sku_no = pi.sku_no
AND other.deleted_at IS NULL
AND other.is_archived = FALSE
AND other.product_id <> $1
)
LIMIT 1
`, id, targetStoreID).Scan(&conflictSKU); err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("check target sku_no: %w", err)
}
if conflictSKU != "" {
return nil, fmt.Errorf("%w: %s", ErrDuplicateSKUNo, conflictSKU)
}
if _, err := tx.ExecContext(ctx, `
UPDATE product.products
SET store_id = $2, version = version + 1, updated_at = NOW()
WHERE id = $1 AND store_id = $3 AND tenant_id = $4 AND deleted_at IS NULL
`, id, targetStoreID, scope.StoreID, tenantID); err != nil {
if isPostgresConstraintError(err, "23505", "uq_products_store_spu_no") {
return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, spuNo)
}
return nil, fmt.Errorf("update product store: %w", err)
}
if _, err := tx.ExecContext(ctx, `
UPDATE product.product_items
SET store_id = $2
WHERE product_id = $1 AND store_id = $3
`, id, targetStoreID, scope.StoreID); err != nil {
if isPostgresConstraintError(err, "23505", "uq_product_items_store_sku_no_active") {
return nil, ErrDuplicateSKUNo
}
return nil, fmt.Errorf("update sku store: %w", err)
}
if _, err := tx.ExecContext(ctx, `
DELETE FROM product.product_catalog_bindings
WHERE product_id = $1
`, id); err != nil {
return nil, fmt.Errorf("detach product categories: %w", err)
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit transfer product store: %w", err)
}
return &TransferProductStoreResult{ProductID: productID, TenantID: tenantID, StoreID: targetStoreID}, nil
}
func updateCurrentSKU(ctx context.Context, tx *sql.Tx, productID int64, input SKUUpdate) error {
if input.ExpectedSKUVersion < 0 || input.ExpectedInventoryVersion < 0 {
return fmt.Errorf("expected sku and inventory versions must be non-negative")
}
skuID, err := parseID(input.ID, "sku id")
if err != nil {
return err
}
var currentVersion int32
err = tx.QueryRowContext(ctx, `
SELECT version
FROM product.product_items
WHERE id = $1 AND product_id = $2 AND deleted_at IS NULL AND is_archived = FALSE
FOR UPDATE
`, skuID, productID).Scan(&currentVersion)
if errors.Is(err, sql.ErrNoRows) {
var archived bool
lookupErr := tx.QueryRowContext(ctx, `SELECT is_archived FROM product.product_items WHERE id = $1 AND product_id = $2`, skuID, productID).Scan(&archived)
if lookupErr == nil && archived {
return ErrSKUArchived
}
return ErrSKUNotFound
}
if err != nil {
return fmt.Errorf("lock sku %s: %w", input.ID, err)
}
if currentVersion != input.ExpectedSKUVersion {
return ErrSKUVersionConflict
}
if input.Name != nil || input.Price != nil || input.SupplyPriceSet || input.WeightKgSet || input.Barcode != nil || input.Status != nil || input.ImageIDs != nil {
sets := []string{"updated_at = NOW()", "version = version + 1"}
args := []any{skuID, productID}
argIndex := 3
if input.Name != nil {
if strings.TrimSpace(*input.Name) == "" {
return fmt.Errorf("sku name must not be empty")
}
sets = append(sets, fmt.Sprintf("name = $%d", argIndex))
args = append(args, strings.TrimSpace(*input.Name))
argIndex++
}
if input.Price != nil {
if *input.Price < 0 {
return fmt.Errorf("sku price must be greater than or equal to 0")
}
sets = append(sets, fmt.Sprintf("price = $%d", argIndex))
args = append(args, *input.Price)
argIndex++
}
if input.SupplyPriceSet {
if input.SupplyPrice != nil && *input.SupplyPrice < 0 {
return fmt.Errorf("sku supply_price must be greater than or equal to 0")
}
sets = append(sets, fmt.Sprintf("supply_price = $%d", argIndex))
args = append(args, nullableInt64(input.SupplyPrice))
argIndex++
}
if input.WeightKgSet {
if input.WeightKg != nil && *input.WeightKg < 0 {
return fmt.Errorf("sku weight_kg must be greater than or equal to 0")
}
sets = append(sets, fmt.Sprintf("weight_kg = $%d", argIndex))
args = append(args, nullableFloat64(input.WeightKg))
argIndex++
}
if input.Barcode != nil {
sets = append(sets, fmt.Sprintf("barcode = $%d", argIndex))
args = append(args, nullString(strings.TrimSpace(*input.Barcode)))
argIndex++
}
if input.Status != nil {
if *input.Status != 0 && *input.Status != 1 {
return fmt.Errorf("sku status must be 0 or 1")
}
sets = append(sets, fmt.Sprintf("status = $%d", argIndex))
args = append(args, *input.Status)
argIndex++
}
if input.ImageIDs != nil {
sets = append(sets, fmt.Sprintf("image_ids = $%d", argIndex))
args = append(args, stringSliceOrEmpty(*input.ImageIDs))
argIndex++
}
query := fmt.Sprintf(`UPDATE product.product_items SET %s WHERE id = $1 AND product_id = $2 AND version = $%d`, strings.Join(sets, ", "), argIndex)
args = append(args, input.ExpectedSKUVersion)
res, err := tx.ExecContext(ctx, query, args...)
if err != nil {
return fmt.Errorf("update sku %s: %w", input.ID, err)
}
affected, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("sku rows affected: %w", err)
}
if affected == 0 {
return ErrSKUVersionConflict
}
}
if input.StockQuantity != nil {
if *input.StockQuantity < 0 {
return fmt.Errorf("stock_quantity must be greater than or equal to 0")
}
var lockedQuantity int32
var inventoryVersion int32
err := tx.QueryRowContext(ctx, `
SELECT locked_quantity, version
FROM product.product_item_inventory
WHERE sku_id = $1
FOR UPDATE
`, skuID).Scan(&lockedQuantity, &inventoryVersion)
if errors.Is(err, sql.ErrNoRows) {
return ErrSKUNotFound
}
if err != nil {
return fmt.Errorf("lock sku inventory %s: %w", input.ID, err)
}
if inventoryVersion != input.ExpectedInventoryVersion {
return ErrSKUVersionConflict
}
if *input.StockQuantity < lockedQuantity {
return fmt.Errorf("stock_quantity cannot be less than locked_quantity")
}
if _, err := tx.ExecContext(ctx, `
UPDATE product.product_item_inventory
SET stock_quantity = $2, version = version + 1, updated_at = NOW()
WHERE sku_id = $1 AND version = $3
`, skuID, *input.StockQuantity, input.ExpectedInventoryVersion); err != nil {
return fmt.Errorf("update sku inventory %s: %w", input.ID, err)
}
}
return nil
}
func archiveCurrentSKUs(ctx context.Context, tx *sql.Tx, productID int64) ([]string, error) {
rows, err := tx.QueryContext(ctx, `
UPDATE product.product_items
SET status = 0, is_archived = TRUE, archived_at = NOW(), version = version + 1, updated_at = NOW()
WHERE product_id = $1 AND deleted_at IS NULL AND is_archived = FALSE
RETURNING id
`, productID)
if err != nil {
return nil, fmt.Errorf("archive current skus: %w", err)
}
defer rows.Close()
ids := make([]string, 0)
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, fmt.Errorf("scan archived sku id: %w", err)
}
ids = append(ids, formatID(id))
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate archived skus: %w", err)
}
return ids, nil
}
func hasSellableSKU(ctx context.Context, tx *sql.Tx, productID int64) (bool, error) {
var exists bool
err := tx.QueryRowContext(ctx, `
SELECT EXISTS(
SELECT 1
FROM product.product_items pi
JOIN product.product_item_inventory inv ON inv.sku_id = pi.id
WHERE pi.product_id = $1
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
AND pi.status = 1
AND inv.stock_quantity > inv.locked_quantity
)
`, productID).Scan(&exists)
if err != nil {
return false, fmt.Errorf("check sellable sku: %w", err)
}
return exists, nil
}
// autoOffSaleIfNoSellableSKU transitions an on-sale product to OFF_SALE only; it never auto-relists.
func autoOffSaleIfNoSellableSKU(ctx context.Context, tx *sql.Tx, productID int64) error {
_, err := tx.ExecContext(ctx, `
UPDATE product.products p
SET status = $2, version = version + 1, updated_at = NOW()
WHERE p.id = $1
AND p.deleted_at IS NULL
AND p.status = $3
AND NOT EXISTS (
SELECT 1
FROM product.product_items pi
JOIN product.product_item_inventory inv ON inv.sku_id = pi.id
WHERE pi.product_id = p.id
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
AND pi.status = 1
AND inv.stock_quantity > inv.locked_quantity
)
`, productID, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE))
if err != nil {
return fmt.Errorf("auto off-sale product %s: %w", formatID(productID), err)
}
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, supply_price, weight_kg, barcode, image_ids, attributes, status, tenant_id, store_id)
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb, $11, p.tenant_id, p.store_id
FROM product.products p
WHERE p.id = $2
RETURNING id
`, skuID, productID, nullString(sku.SKUNo), sku.Name, sku.Price, nullableInt64(sku.SupplyPrice), nullableFloat64(sku.WeightKg), nullString(sku.Barcode), 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.StockQuantity); 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, version = version + 1, updated_at = NOW()
WHERE id = $1 AND is_archived = FALSE
`, 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.StockQuantity); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit update sku: %w", err)
}
return nil
}
// LockInventory atomically reserves quantity when stock_quantity - locked_quantity >= quantity.
func (r *ProductRepository) LockInventory(ctx context.Context, skuID string, quantity int32, scope StoreScope) (*InventoryRecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
if quantity <= 0 {
return nil, fmt.Errorf("quantity must be positive")
}
id, err := parseID(skuID, "sku id")
if err != nil {
return nil, err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin lock inventory: %w", err)
}
defer tx.Rollback()
var productID int64
var productStatus int16
err = tx.QueryRowContext(ctx, `
SELECT pi.product_id, p.status
FROM product.product_items pi
JOIN product.products p ON p.id = pi.product_id
WHERE pi.id = $1
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
AND pi.status = 1
AND p.deleted_at IS NULL
AND p.store_id = $2
FOR UPDATE OF p
`, id, scope.StoreID).Scan(&productID, &productStatus)
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrSKUNotFound)
}
if err != nil {
return nil, fmt.Errorf("lock product for inventory %s: %w", skuID, err)
}
if statusFromDB(productStatus) != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE {
return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrProductNotOnSale)
}
row := tx.QueryRowContext(ctx, `
UPDATE product.product_item_inventory
SET locked_quantity = locked_quantity + $2,
version = version + 1,
updated_at = NOW()
WHERE sku_id = $1
AND EXISTS (
SELECT 1
FROM product.product_items pi
WHERE pi.id = product.product_item_inventory.sku_id
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
AND pi.status = 1
)
AND stock_quantity - locked_quantity >= $2
RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at
`, id, quantity)
inventory, err := scanInventory(row)
if errors.Is(err, sql.ErrNoRows) {
exists, existsErr := r.skuInventoryExists(ctx, id)
if existsErr != nil {
return nil, existsErr
}
if !exists {
return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrSKUNotFound)
}
return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrInsufficientStock)
}
if err != nil {
return nil, fmt.Errorf("lock inventory %s: %w", skuID, err)
}
if err := autoOffSaleIfNoSellableSKU(ctx, tx, productID); err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit lock inventory: %w", err)
}
return inventory, nil
}
// ConfirmInventory converts locked stock to sold stock after payment succeeds.
func (r *ProductRepository) ConfirmInventory(ctx context.Context, orderID string, items []InventoryAdjustment, scope StoreScope) ([]*InventoryRecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
return r.applyInventoryAdjustments(ctx, orderID, "confirm", items, scope)
}
// ReleaseInventory releases locked stock when a pending order is cancelled or expires.
func (r *ProductRepository) ReleaseInventory(ctx context.Context, orderID string, items []InventoryAdjustment, scope StoreScope) ([]*InventoryRecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
return r.applyInventoryAdjustments(ctx, orderID, "release", items, scope)
}
func (r *ProductRepository) applyInventoryAdjustments(ctx context.Context, orderID, action string, items []InventoryAdjustment, scope StoreScope) ([]*InventoryRecord, error) {
parsedOrderID, err := parseID(orderID, "order id")
if err != nil {
return nil, err
}
aggregated, err := aggregateInventoryAdjustments(items)
if err != nil {
return nil, err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin %s inventory: %w", action, err)
}
defer tx.Rollback()
inventories := make([]*InventoryRecord, 0, len(aggregated))
for _, item := range aggregated {
skuID, err := parseID(item.SKUID, "sku id")
if err != nil {
return nil, err
}
var owned int
err = tx.QueryRowContext(ctx, `
SELECT 1
FROM product.product_items pi
JOIN product.products p ON p.id = pi.product_id
WHERE pi.id = $1 AND p.store_id = $2 AND p.deleted_at IS NULL
`, skuID, scope.StoreID).Scan(&owned)
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("%s inventory %s: %w", action, formatID(skuID), ErrSKUNotFound)
}
if err != nil {
return nil, fmt.Errorf("verify %s inventory store %s: %w", action, formatID(skuID), err)
}
var inserted bool
err = tx.QueryRowContext(ctx, `
INSERT INTO product.inventory_adjustments (order_id, action, sku_id, quantity)
VALUES ($1, $2, $3, $4)
ON CONFLICT (order_id, action, sku_id) DO NOTHING
RETURNING TRUE
`, parsedOrderID, action, skuID, item.Quantity).Scan(&inserted)
if errors.Is(err, sql.ErrNoRows) {
recordedQuantity, err := loadInventoryAdjustmentQuantity(ctx, tx, parsedOrderID, action, skuID)
if err != nil {
return nil, err
}
if recordedQuantity != item.Quantity {
return nil, fmt.Errorf("%s inventory %s: %w: recorded quantity %d, requested quantity %d", action, formatID(skuID), ErrInventoryAdjustmentConflict, recordedQuantity, item.Quantity)
}
inventory, err := loadInventoryForUpdate(ctx, tx, skuID)
if err != nil {
return nil, err
}
inventories = append(inventories, inventory)
continue
}
if err != nil {
return nil, fmt.Errorf("record %s inventory adjustment: %w", action, err)
}
inventory, err := applyInventoryAdjustment(ctx, tx, action, skuID, item.Quantity)
if err != nil {
return nil, err
}
inventories = append(inventories, inventory)
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit %s inventory: %w", action, err)
}
return inventories, nil
}
func aggregateInventoryAdjustments(items []InventoryAdjustment) ([]InventoryAdjustment, error) {
if len(items) == 0 {
return nil, errors.New("items are required")
}
type aggregate struct {
skuID string
parsedID int64
quantity int32
}
quantities := make(map[string]int32, len(items))
parsedIDs := make(map[string]int64, len(items))
for i, item := range items {
if strings.TrimSpace(item.SKUID) == "" {
return nil, fmt.Errorf("items[%d].sku_id is required", i)
}
if item.Quantity <= 0 {
return nil, fmt.Errorf("items[%d].quantity must be positive", i)
}
skuID := strings.TrimSpace(item.SKUID)
parsedID, err := parseID(skuID, fmt.Sprintf("items[%d].sku_id", i))
if err != nil {
return nil, err
}
quantities[skuID] += item.Quantity
parsedIDs[skuID] = parsedID
}
aggregated := make([]aggregate, 0, len(quantities))
for skuID, quantity := range quantities {
aggregated = append(aggregated, aggregate{skuID: skuID, parsedID: parsedIDs[skuID], quantity: quantity})
}
sort.Slice(aggregated, func(i, j int) bool {
return aggregated[i].parsedID < aggregated[j].parsedID
})
out := make([]InventoryAdjustment, 0, len(aggregated))
for _, item := range aggregated {
out = append(out, InventoryAdjustment{SKUID: item.skuID, Quantity: item.quantity})
}
return out, nil
}
func applyInventoryAdjustment(ctx context.Context, tx *sql.Tx, action string, skuID int64, quantity int32) (*InventoryRecord, error) {
var query string
switch action {
case "confirm":
query = `
UPDATE product.product_item_inventory
SET stock_quantity = stock_quantity - $2,
locked_quantity = locked_quantity - $2,
sold_quantity = sold_quantity + $2,
version = version + 1,
updated_at = NOW()
WHERE sku_id = $1
AND locked_quantity >= $2
AND stock_quantity >= $2
RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at
`
case "release":
query = `
UPDATE product.product_item_inventory
SET locked_quantity = locked_quantity - $2,
version = version + 1,
updated_at = NOW()
WHERE sku_id = $1
AND locked_quantity >= $2
RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at
`
default:
return nil, fmt.Errorf("unsupported inventory action %q", action)
}
inventory, err := scanInventory(tx.QueryRowContext(ctx, query, skuID, quantity))
if errors.Is(err, sql.ErrNoRows) {
exists, existsErr := skuInventoryExistsInTx(ctx, tx, skuID)
if existsErr != nil {
return nil, existsErr
}
if !exists {
return nil, fmt.Errorf("%s inventory %s: %w", action, formatID(skuID), ErrSKUNotFound)
}
return nil, fmt.Errorf("%s inventory %s: %w", action, formatID(skuID), ErrInsufficientLockedStock)
}
if err != nil {
return nil, fmt.Errorf("%s inventory %s: %w", action, formatID(skuID), err)
}
return inventory, nil
}
func loadInventoryForUpdate(ctx context.Context, tx *sql.Tx, skuID int64) (*InventoryRecord, error) {
inventory, err := scanInventory(tx.QueryRowContext(ctx, `
SELECT id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at
FROM product.product_item_inventory
WHERE sku_id = $1
FOR UPDATE
`, skuID))
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("load inventory %s: %w", formatID(skuID), ErrSKUNotFound)
}
if err != nil {
return nil, fmt.Errorf("load inventory %s: %w", formatID(skuID), err)
}
return inventory, nil
}
func loadInventoryAdjustmentQuantity(ctx context.Context, tx *sql.Tx, orderID int64, action string, skuID int64) (int32, error) {
var quantity int32
err := tx.QueryRowContext(ctx, `
SELECT quantity
FROM product.inventory_adjustments
WHERE order_id = $1
AND action = $2
AND sku_id = $3
FOR UPDATE
`, orderID, action, skuID).Scan(&quantity)
if errors.Is(err, sql.ErrNoRows) {
return 0, fmt.Errorf("%s inventory %s: %w: missing recorded adjustment", action, formatID(skuID), ErrInventoryAdjustmentConflict)
}
if err != nil {
return 0, fmt.Errorf("load %s inventory adjustment %s: %w", action, formatID(skuID), err)
}
return quantity, nil
}
func (r *ProductRepository) skuInventoryExists(ctx context.Context, skuID int64) (bool, error) {
return skuInventoryExistsInTx(ctx, r.db, skuID)
}
type queryRower interface {
QueryRowContext(context.Context, string, ...any) *sql.Row
}
func skuInventoryExistsInTx(ctx context.Context, q queryRower, skuID int64) (bool, error) {
var exists bool
err := q.QueryRowContext(ctx, `
SELECT EXISTS(
SELECT 1
FROM product.product_item_inventory inv
JOIN product.product_items pi ON pi.id = inv.sku_id
WHERE inv.sku_id = $1
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
AND pi.status = 1
)
`, skuID).Scan(&exists)
if err != nil {
return false, fmt.Errorf("check inventory exists %s: %w", formatID(skuID), err)
}
return exists, 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, scope StoreScope) (*ProductRecord, []SKURecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, nil, err
}
product, err := r.loadProductByID(ctx, productID, scope)
if err != nil {
return nil, nil, err
}
skus, err := r.loadSKUsByProductIDs(ctx, []string{productID})
if err != nil {
return nil, nil, err
}
leafCategoryIDs, err := r.listProductLeafCategoryIDs(ctx, productID, scope)
if err != nil {
return nil, nil, err
}
product.LeafCategoryIDs = leafCategoryIDs
groupIDs, err := r.listProductGroupIDs(ctx, productID, scope)
if err != nil {
return nil, nil, err
}
product.GroupIDs = groupIDs
return product, skus[productID], nil
}
// ListProductSKUStocks loads every current SKU and its inventory pool quantity for one product.
// Archived and soft-deleted SKU rows are historical records and are deliberately excluded.
func (r *ProductRepository) ListProductSKUStocks(ctx context.Context, productID string, scope StoreScope) ([]ProductSKUStockRecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
parsedProductID, err := parseID(productID, "product_id")
if err != nil {
return nil, err
}
var exists bool
err = r.db.QueryRowContext(ctx, `
SELECT EXISTS(
SELECT 1
FROM product.products
WHERE id = $1
AND store_id = $2
AND deleted_at IS NULL
)
`, parsedProductID, scope.StoreID).Scan(&exists)
if err != nil {
return nil, fmt.Errorf("check product for sku list: %w", err)
}
if !exists {
return nil, ErrProductNotFound
}
rows, err := r.db.QueryContext(ctx, `
SELECT pi.id,
pi.name,
COALESCE(inv.stock_quantity, 0),
pi.supply_price
FROM product.product_items AS pi
LEFT JOIN product.product_item_inventory AS inv ON inv.sku_id = pi.id
WHERE pi.product_id = $1
AND pi.store_id = $2
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
ORDER BY pi.created_at ASC, pi.id ASC
`, parsedProductID, scope.StoreID)
if err != nil {
return nil, fmt.Errorf("query product sku stocks: %w", err)
}
defer rows.Close()
skus := make([]ProductSKUStockRecord, 0)
for rows.Next() {
var (
sku ProductSKUStockRecord
id int64
)
var supplyPrice sql.NullInt64
if err := rows.Scan(&id, &sku.Name, &sku.StockQuantity, &supplyPrice); err != nil {
return nil, fmt.Errorf("scan product sku stock: %w", err)
}
sku.ID = formatID(id)
if supplyPrice.Valid {
value := supplyPrice.Int64
sku.SupplyPrice = &value
}
skus = append(skus, sku)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate product sku stocks: %w", err)
}
return skus, nil
}
// GetProductBySKU loads the SPU that owns skuID (product_items.id is the SKU PK).
func (r *ProductRepository) GetProductBySKU(ctx context.Context, skuID string, scope StoreScope) (*ProductRecord, []SKURecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, nil, err
}
parsedSKU, err := parseID(skuID, "sku_id")
if err != nil {
return nil, nil, err
}
var productID int64
err = r.db.QueryRowContext(ctx, `
SELECT pi.product_id
FROM product.product_items pi
JOIN product.products p ON p.id = pi.product_id
WHERE pi.id = $1 AND pi.deleted_at IS NULL AND pi.is_archived = FALSE
AND p.deleted_at IS NULL AND p.store_id = $2
`, parsedSKU, scope.StoreID).Scan(&productID)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil, ErrSKUNotFound
}
if err != nil {
return nil, nil, fmt.Errorf("lookup product by sku: %w", err)
}
return r.GetProduct(ctx, formatID(productID), scope)
}
func (r *ProductRepository) listProductLeafCategoryIDs(ctx context.Context, productID string, scope StoreScope) ([]string, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
parsedProductID, err := parseID(productID, "product_id")
if err != nil {
return nil, err
}
rows, err := r.db.QueryContext(ctx, `
SELECT c.id
FROM product.product_catalog_bindings AS b
JOIN product.catalog_category AS c ON c.id = b.category_id
WHERE b.product_id = $1
AND c.node_type = 1
AND c.level = 2
AND c.store_id = $2
ORDER BY c.sort_num, c.id
`, parsedProductID, scope.StoreID)
if err != nil {
return nil, fmt.Errorf("list product leaf category ids: %w", err)
}
defer rows.Close()
leafCategoryIDs := make([]string, 0)
for rows.Next() {
var categoryID int64
if err := rows.Scan(&categoryID); err != nil {
return nil, fmt.Errorf("scan product leaf category id: %w", err)
}
leafCategoryIDs = append(leafCategoryIDs, formatID(categoryID))
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate product leaf category ids: %w", err)
}
return leafCategoryIDs, nil
}
func (r *ProductRepository) listProductGroupIDs(ctx context.Context, productID string, scope StoreScope) ([]string, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
parsedProductID, err := parseID(productID, "product_id")
if err != nil {
return nil, err
}
rows, err := r.db.QueryContext(ctx, `
SELECT c.id
FROM product.product_catalog_bindings AS b
JOIN product.catalog_category AS c ON c.id = b.category_id
WHERE b.product_id = $1
AND c.node_type = 2
AND c.store_id = $2
ORDER BY c.sort_num, c.id
`, parsedProductID, scope.StoreID)
if err != nil {
return nil, fmt.Errorf("list product group ids: %w", err)
}
defer rows.Close()
groupIDs := make([]string, 0)
for rows.Next() {
var groupID int64
if err := rows.Scan(&groupID); err != nil {
return nil, fmt.Errorf("scan product group id: %w", err)
}
groupIDs = append(groupIDs, formatID(groupID))
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate product group ids: %w", err)
}
return groupIDs, nil
}
// BatchGetCartItemProducts loads current catalog facts for cart lines in request order.
// It includes archived SKUs, but treats soft-deleted SPUs and SKUs as unavailable.
func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookups []CartItemProductLookup, scope StoreScope) ([]CartItemProductRecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
if len(lookups) == 0 {
return []CartItemProductRecord{}, nil
}
productIDs := make([]string, 0, len(lookups))
skuIDs := make([]string, 0, len(lookups))
seenProductIDs := make(map[string]struct{}, len(lookups))
seenSKUIDs := make(map[string]struct{}, len(lookups))
for _, lookup := range lookups {
if _, err := parseID(lookup.ProductID, "product id"); err != nil {
return nil, err
}
if _, err := parseID(lookup.SKUID, "sku id"); err != nil {
return nil, err
}
if _, ok := seenProductIDs[lookup.ProductID]; !ok {
seenProductIDs[lookup.ProductID] = struct{}{}
productIDs = append(productIDs, lookup.ProductID)
}
if _, ok := seenSKUIDs[lookup.SKUID]; !ok {
seenSKUIDs[lookup.SKUID] = struct{}{}
skuIDs = append(skuIDs, lookup.SKUID)
}
}
products, err := r.loadProductsByIDs(ctx, productIDs, scope)
if err != nil {
return nil, err
}
skus, err := r.loadCartItemSKUsByIDs(ctx, skuIDs)
if err != nil {
return nil, err
}
productsByID := make(map[string]*ProductRecord, len(products))
for _, product := range products {
productsByID[product.ID] = product
}
skusByID := make(map[string]*SKURecord, len(skus))
for index := range skus {
skusByID[skus[index].ID] = &skus[index]
}
results := make([]CartItemProductRecord, 0, len(lookups))
for _, lookup := range lookups {
result := CartItemProductRecord{ProductID: lookup.ProductID, SKUID: lookup.SKUID}
result.Product = productsByID[lookup.ProductID]
if result.Product != nil {
if sku := skusByID[lookup.SKUID]; sku != nil && sku.ProductID == lookup.ProductID {
result.SKU = sku
}
}
results = append(results, result)
}
return results, nil
}
// ValidateProductGroup verifies that a group belongs to the current store.
func (r *ProductRepository) ValidateProductGroup(ctx context.Context, groupID string, scope StoreScope) error {
if err := requireWriteScope(scope); err != nil {
return err
}
parsedGroupID, err := parseID(groupID, "group_id")
if err != nil {
return err
}
var found int64
err = r.db.QueryRowContext(ctx, `
SELECT id
FROM product.catalog_category
WHERE id = $1 AND node_type = 2 AND store_id = $2
`, parsedGroupID, scope.StoreID).Scan(&found)
if errors.Is(err, sql.ErrNoRows) {
return ErrInvalidProductGroup
}
if err != nil {
return fmt.Errorf("validate product group: %w", err)
}
return nil
}
// ListProducts loads paginated summaries for all non-deleted products.
func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int32, filter ProductListFilter, scope StoreScope) ([]*CategoryProductRecord, int64, error) {
if err := requireWriteScope(scope); err != nil {
return nil, 0, err
}
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 20
}
where, args := productListWhere(filter, scope)
metricJoin := `
LEFT JOIN LATERAL (
SELECT MIN(pi.price) AS price,
SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity,
SUM(COALESCE(inv.stock_quantity, 0)) AS stock_quantity,
SUM(COALESCE(inv.locked_quantity, 0)) AS locked_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
AND pi.is_archived = FALSE
) sku_summary ON TRUE`
var total int64
countQuery := "SELECT COUNT(*) FROM product.products p " + metricJoin + " WHERE " + where
if err := r.db.QueryRowContext(ctx, countQuery, args...).Scan(&total); err != nil {
return nil, 0, fmt.Errorf("count products: %w", err)
}
if total == 0 {
return []*CategoryProductRecord{}, 0, nil
}
offset := int64(page-1) * int64(pageSize)
queryArgs := append(append([]any{}, args...), pageSize, offset)
limitArg := len(args) + 1
offsetArg := len(args) + 2
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),
COALESCE(sku_summary.stock_quantity, 0),
COALESCE(sku_summary.locked_quantity, 0)
FROM product.products p `+metricJoin+`
WHERE `+where+`
ORDER BY p.created_at DESC, p.id DESC
LIMIT $`+strconv.Itoa(limitArg)+` OFFSET $`+strconv.Itoa(offsetArg), queryArgs...)
if err != nil {
return nil, 0, fmt.Errorf("query 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 products: %w", err)
}
return products, total, nil
}
func productListWhere(filter ProductListFilter, scope StoreScope) (string, []any) {
predicates := []string{"p.deleted_at IS NULL", "p.store_id = $1"}
args := []any{scope.StoreID}
add := func(predicate string, value any) {
args = append(args, value)
predicates = append(predicates, fmt.Sprintf(predicate, len(args)))
}
if filter.CreatedAtFrom != nil {
add("p.created_at >= $%d", *filter.CreatedAtFrom)
}
if filter.CreatedAtTo != nil {
add("p.created_at <= $%d", *filter.CreatedAtTo)
}
if filter.TitleKeyword != "" {
add(`p.title ILIKE $%d ESCAPE '\'`, "%"+escapeLikeLiteral(filter.TitleKeyword)+"%")
}
if filter.SPUNo != "" {
add("p.spu_no = $%d", filter.SPUNo)
}
if filter.GroupID != "" {
add(`EXISTS (
SELECT 1
FROM product.product_catalog_bindings pcb
JOIN product.catalog_category pc ON pc.id = pcb.category_id
WHERE pcb.product_id = p.id
AND pcb.category_id = $%d
AND pc.node_type = 2
AND pc.store_id = p.store_id
)`, filter.GroupID)
}
if filter.ProductCategoryID != "" {
args = append(args, filter.ProductCategoryID)
argPos := len(args)
predicates = append(predicates, fmt.Sprintf(`EXISTS (
WITH RECURSIVE category_descendants AS (
SELECT c.id
FROM product.product_category c
WHERE c.id = $%d
AND c.deleted_at IS NULL
UNION
SELECT child.id
FROM product.product_category child
JOIN category_descendants parent ON child.parent_id = parent.id
WHERE child.deleted_at IS NULL
)
SELECT 1
FROM product.product_category_bindings pcb
JOIN category_descendants descendant ON descendant.id = pcb.product_category_id
WHERE pcb.product_id = p.id
AND pcb.tenant_id = p.tenant_id
AND pcb.store_id = p.store_id
AND pcb.deleted_at IS NULL
)`, argPos))
}
if filter.GoodsType != nil {
add("p.goods_type = $%d", *filter.GoodsType)
}
if filter.SoldQuantityMin != nil {
add("COALESCE(sku_summary.sold_quantity, 0) >= $%d", *filter.SoldQuantityMin)
}
if filter.SoldQuantityMax != nil {
add("COALESCE(sku_summary.sold_quantity, 0) <= $%d", *filter.SoldQuantityMax)
}
if filter.PriceMin != nil {
add("COALESCE(sku_summary.price, 0) >= $%d", *filter.PriceMin)
}
if filter.PriceMax != nil {
add("COALESCE(sku_summary.price, 0) <= $%d", *filter.PriceMax)
}
return strings.Join(predicates, " AND "), args
}
// SearchProducts loads storefront-visible product summaries whose titles contain
// keyword. Callers cannot opt out of the visibility predicate: soft-deleted and
// inventory-only products must never be exposed by keyword search.
func (r *ProductRepository) SearchProducts(ctx context.Context, keyword string, page, pageSize int32, scope StoreScope) ([]*CategoryProductRecord, int64, error) {
if err := requireWriteScope(scope); err != nil {
return nil, 0, err
}
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 20
}
escapedKeyword := escapeLikeLiteral(keyword)
containsPattern := "%" + escapedKeyword + "%"
prefixPattern := escapedKeyword + "%"
onSaleStatus := statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE)
offSaleStatus := statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE)
var total int64
if err := r.db.QueryRowContext(ctx, `
SELECT COUNT(*)
FROM product.products p
WHERE p.deleted_at IS NULL
AND p.store_id = $4
AND p.status IN ($2, $3)
AND EXISTS (
SELECT 1
FROM product.product_items pi
WHERE pi.product_id = p.id
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
AND pi.status = 1
)
AND p.title ILIKE $1 ESCAPE '\'
`, containsPattern, onSaleStatus, offSaleStatus, scope.StoreID).Scan(&total); err != nil {
return nil, 0, fmt.Errorf("count searched 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),
COALESCE(sku_summary.stock_quantity, 0),
COALESCE(sku_summary.locked_quantity, 0)
FROM product.products p
LEFT JOIN LATERAL (
SELECT MIN(pi.price) AS price,
SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity,
SUM(COALESCE(inv.stock_quantity, 0)) AS stock_quantity,
SUM(COALESCE(inv.locked_quantity, 0)) AS locked_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
AND pi.is_archived = FALSE
AND pi.status = 1
) sku_summary ON TRUE
WHERE p.deleted_at IS NULL
AND p.store_id = $8
AND p.status IN ($2, $3)
AND EXISTS (
SELECT 1
FROM product.product_items pi
WHERE pi.product_id = p.id
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
AND pi.status = 1
)
AND p.title ILIKE $1 ESCAPE '\'
ORDER BY CASE
WHEN LOWER(p.title) = LOWER($4) THEN 0
WHEN p.title ILIKE $5 ESCAPE '\' THEN 1
ELSE 2
END,
p.updated_at DESC,
p.id DESC
LIMIT $6 OFFSET $7
`, containsPattern, onSaleStatus, offSaleStatus, keyword, prefixPattern, pageSize, offset, scope.StoreID)
if err != nil {
return nil, 0, fmt.Errorf("query searched 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 searched products: %w", err)
}
return products, total, nil
}
// CountProducts returns aggregate product counts grouped by lifecycle status.
func (r *ProductRepository) CountProducts(ctx context.Context, scope StoreScope) (*ProductCountRecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
var counts ProductCountRecord
if err := r.db.QueryRowContext(ctx, `
SELECT COUNT(*) AS total,
COUNT(*) FILTER (WHERE deleted_at IS NULL) AS active,
COUNT(*) FILTER (WHERE deleted_at IS NULL AND status = 0) AS draft,
COUNT(*) FILTER (WHERE deleted_at IS NULL AND status = 1) AS on_sale,
COUNT(*) FILTER (WHERE deleted_at IS NULL AND status = 3) AS off_sale,
COUNT(*) FILTER (WHERE deleted_at IS NOT NULL) AS deleted
FROM product.products
WHERE store_id = $1
`, scope.StoreID).Scan(
&counts.Total,
&counts.Active,
&counts.Draft,
&counts.OnSale,
&counts.OffSale,
&counts.Deleted,
); err != nil {
return nil, fmt.Errorf("count products: %w", err)
}
return &counts, nil
}
// ListCategoryProducts loads paginated product summaries for a category or group node.
func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32, onlyVisible bool, targetNodeType int32, scope StoreScope) ([]*CategoryProductRecord, []string, int64, error) {
if err := requireWriteScope(scope); err != nil {
return nil, nil, 0, err
}
parsedCategoryID, err := parseID(categoryID, "category id")
if err != nil {
return nil, nil, 0, err
}
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 20
}
if onlyVisible && targetNodeType == 1 {
visible, err := r.isStorefrontCategoryVisible(ctx, parsedCategoryID, scope)
if err != nil {
return nil, nil, 0, err
}
if !visible {
return nil, nil, 0, ErrStorefrontCategoryNotFound
}
}
var total int64
if err := r.db.QueryRowContext(ctx, `
SELECT COUNT(*)
FROM product.products p
JOIN product.product_catalog_bindings b ON b.product_id = p.id
JOIN product.catalog_category c ON c.id = b.category_id
WHERE b.category_id = $1
AND p.deleted_at IS NULL
AND p.store_id = $5
AND c.store_id = $5
AND c.node_type = $6
AND ($2 = FALSE OR p.status IN ($3, $4))
AND ($2 = FALSE OR EXISTS (
SELECT 1
FROM product.product_items pi
WHERE pi.product_id = p.id
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
AND pi.status = 1
))
`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), scope.StoreID, targetNodeType).Scan(&total); err != nil {
return nil, nil, 0, fmt.Errorf("count category products: %w", err)
}
if total == 0 {
return []*CategoryProductRecord{}, []string{}, 0, nil
}
idRows, err := r.db.QueryContext(ctx, `
SELECT p.id
FROM product.products p
JOIN product.product_catalog_bindings b ON b.product_id = p.id
JOIN product.catalog_category c ON c.id = b.category_id
WHERE b.category_id = $1
AND p.deleted_at IS NULL
AND p.store_id = $5
AND c.store_id = $5
AND c.node_type = $6
AND ($2 = FALSE OR p.status IN ($3, $4))
AND ($2 = FALSE OR EXISTS (
SELECT 1
FROM product.product_items pi
WHERE pi.product_id = p.id
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
AND pi.status = 1
))
ORDER BY p.created_at DESC, p.id DESC
`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), scope.StoreID, targetNodeType)
if err != nil {
return nil, nil, 0, fmt.Errorf("query category product ids: %w", err)
}
defer idRows.Close()
productIDs := make([]string, 0)
for idRows.Next() {
var productID int64
if err := idRows.Scan(&productID); err != nil {
return nil, nil, 0, fmt.Errorf("scan category product id: %w", err)
}
productIDs = append(productIDs, formatID(productID))
}
if err := idRows.Err(); err != nil {
return nil, nil, 0, fmt.Errorf("iterate category product ids: %w", err)
}
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),
COALESCE(sku_summary.stock_quantity, 0),
COALESCE(sku_summary.locked_quantity, 0)
FROM product.products p
JOIN product.product_catalog_bindings b ON b.product_id = p.id
JOIN product.catalog_category c ON c.id = b.category_id
LEFT JOIN LATERAL (
SELECT MIN(pi.price) AS price,
SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity,
SUM(COALESCE(inv.stock_quantity, 0)) AS stock_quantity,
SUM(COALESCE(inv.locked_quantity, 0)) AS locked_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
AND pi.is_archived = FALSE
AND ($2 = FALSE OR pi.status = 1)
) sku_summary ON TRUE
WHERE b.category_id = $1
AND p.deleted_at IS NULL
AND p.store_id = $7
AND c.store_id = $7
AND c.node_type = $8
AND ($2 = FALSE OR p.status IN ($5, $6))
AND ($2 = FALSE OR EXISTS (
SELECT 1
FROM product.product_items pi
WHERE pi.product_id = p.id
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
AND pi.status = 1
))
ORDER BY p.created_at DESC, p.id DESC
LIMIT $3 OFFSET $4
`, parsedCategoryID, onlyVisible, pageSize, offset, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), scope.StoreID, targetNodeType)
if err != nil {
return nil, 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, nil, 0, err
}
products = append(products, product)
}
if err := rows.Err(); err != nil {
return nil, nil, 0, fmt.Errorf("iterate category products: %w", err)
}
return products, productIDs, total, nil
}
// isStorefrontCategoryVisible verifies the requested category and every
// ancestor in one store. A broken parent link or cycle is not storefront
// visible: exposing it would either leak a hidden branch or promote a child to
// a false root in the miniapp category tree.
func (r *ProductRepository) isStorefrontCategoryVisible(ctx context.Context, categoryID int64, scope StoreScope) (bool, error) {
var visible bool
err := r.db.QueryRowContext(ctx, `
WITH RECURSIVE ancestry AS (
SELECT id, parent_id, status, ARRAY[id] AS path
FROM product.catalog_category
WHERE id = $1
AND store_id = $2
AND node_type = 1
UNION ALL
SELECT parent.id, parent.parent_id, parent.status, ancestry.path || parent.id
FROM product.catalog_category parent
JOIN ancestry ON ancestry.parent_id = parent.id
WHERE parent.store_id = $2
AND parent.node_type = 1
AND NOT parent.id = ANY(ancestry.path)
)
SELECT EXISTS (SELECT 1 FROM ancestry WHERE parent_id IS NULL)
AND NOT EXISTS (SELECT 1 FROM ancestry WHERE status <> 1)
AND NOT EXISTS (
SELECT 1
FROM ancestry child
WHERE child.parent_id IS NOT NULL
AND NOT EXISTS (
SELECT 1
FROM product.catalog_category parent
WHERE parent.id = child.parent_id
AND parent.store_id = $2
AND parent.node_type = 1
)
)
`, categoryID, scope.StoreID).Scan(&visible)
if err != nil {
return false, fmt.Errorf("check storefront category visibility: %w", err)
}
return visible, nil
}
// ListCategoryTreeNodes loads product category nodes for storefront category trees.
func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool, scope StoreScope) ([]*CategoryRecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
rows, err := r.db.QueryContext(ctx, `
SELECT id,
node_type,
name,
parent_id,
level,
COALESCE(to_json(image_ids)::text, '[]'),
sort_num,
status,
campaign_id,
version
FROM (
WITH RECURSIVE category_tree AS (
SELECT id, node_type, name, parent_id, level, image_ids, sort_num, status, campaign_id, version
FROM product.catalog_category
WHERE node_type = 1
AND store_id = $2
AND parent_id IS NULL
AND ($1 = FALSE OR status = 1)
UNION ALL
SELECT child.id, child.node_type, child.name, child.parent_id, child.level, child.image_ids, child.sort_num, child.status, child.campaign_id, child.version
FROM product.catalog_category child
JOIN category_tree parent ON child.parent_id = parent.id
WHERE child.node_type = 1
AND child.store_id = $2
AND ($1 = FALSE OR child.status = 1)
)
SELECT * FROM category_tree
) category_tree
ORDER BY level ASC, sort_num ASC, id ASC
`, onlyVisible, scope.StoreID)
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, scope StoreScope) ([]*CategoryRecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
rows, err := r.db.QueryContext(ctx, `
SELECT c.id,
c.node_type,
c.name,
c.parent_id,
c.level,
COALESCE(to_json(c.image_ids)::text, '[]'),
c.sort_num,
c.status,
c.campaign_id,
c.version,
COUNT(p.id) AS product_count
FROM product.catalog_category AS c
LEFT JOIN product.product_catalog_bindings AS b ON b.category_id = c.id
LEFT JOIN product.products AS p ON p.id = b.product_id
AND p.store_id = c.store_id
AND p.deleted_at IS NULL
WHERE c.node_type = 2
AND c.store_id = $2
AND ($1 = false OR c.status = 1)
GROUP BY c.id
ORDER BY c.sort_num ASC, c.id ASC
`, onlyVisible, scope.StoreID)
if err != nil {
return nil, fmt.Errorf("query group nodes: %w", err)
}
defer rows.Close()
groups := make([]*CategoryRecord, 0)
for rows.Next() {
group, err := scanGroup(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, scope StoreScope) (*ProductRecord, error) {
products, err := r.loadProductsByIDs(ctx, []string{productID}, scope)
if err != nil {
return nil, err
}
if len(products) == 0 {
return nil, ErrProductNotFound
}
product := products[0]
product.Scope = scope
return product, nil
}
func (r *ProductRepository) loadProductsByIDs(ctx context.Context, productIDs []string, scope StoreScope) ([]*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
}
storeFilter := ""
if scope.Valid() {
args = append(args, scope.StoreID)
storeFilter = fmt.Sprintf(" AND store_id = $%d", len(args))
}
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,
version,
deleted_at,
created_at,
updated_at
FROM product.products
WHERE id IN (%s)
AND deleted_at IS NULL%s
ORDER BY created_at ASC
`, strings.Join(placeholders, ", "), storeFilter)
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
}
if scope.Valid() {
product.Scope = scope
}
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) {
if err := requireWriteScope(product.Scope); err != nil {
return nil, err
}
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,
tenant_id,
store_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, $14, $15::jsonb, $16, $17, $18, $19, $20)
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,
version,
deleted_at,
created_at,
updated_at
`, id, product.Scope.TenantID, product.Scope.StoreID, 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_store_spu_no") || isPostgresConstraintError(err, "23505", "uq_products_spu_no") {
return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, product.SPUNo)
}
return nil, fmt.Errorf("insert product: %w", err)
}
createdProduct.Scope = product.Scope
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 categoryNameConflictError(err error) error {
switch {
case isPostgresConstraintError(err, "23505", "uq_product_category_group_normalized_name"):
return ErrGroupNameExists
case isPostgresConstraintError(err, "23505", "uq_product_category_sibling_normalized_name"):
return ErrCategoryNameExists
default:
return nil
}
}
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, supply_price, weight_kg, barcode, image_ids, attributes, status, tenant_id, store_id)
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb, $11, p.tenant_id, p.store_id
FROM product.products p
WHERE p.id = $2
RETURNING id,
product_id,
sku_no,
name,
price,
supply_price,
weight_kg,
barcode,
COALESCE(to_json(image_ids)::text, '[]'),
attributes,
status,
is_archived,
archived_at,
version,
deleted_at,
created_at,
updated_at,
NULL::bigint,
NULL::bigint,
NULL::integer,
NULL::integer,
NULL::integer,
NULL::integer,
NULL::timestamptz,
NULL::timestamptz
`, id, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, nullableInt64(sku.SupplyPrice), nullableFloat64(sku.WeightKg), nullString(sku.Barcode), 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.StockQuantity)
if err != nil {
return nil, err
}
createdSKU.Inventory = inventory
if inventory != nil {
createdSKU.StockQuantity = inventory.StockQuantity
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, stockQuantity int32) (*InventoryRecord, error) {
row := tx.QueryRowContext(ctx, `
INSERT INTO product.product_item_inventory (id, sku_id, spu_no, sku_no, stock_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, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at
`, inventoryID, skuID, stockQuantity)
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, stockQuantity int32) (*InventoryRecord, error) {
row := tx.QueryRowContext(ctx, `
UPDATE product.product_item_inventory
SET stock_quantity = $2,
version = version + 1,
updated_at = NOW()
WHERE sku_id = $1
RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at
`, skuID, stockQuantity)
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_catalog_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, scope StoreScope) (*CategoryRecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
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}
}
campaignID, err := nullableCategoryCampaignID(&category.CampaignID)
if err != nil {
return nil, err
}
row := tx.QueryRowContext(ctx, `
INSERT INTO product.catalog_category (
id,
tenant_id,
store_id,
node_type,
name,
parent_id,
level,
image_ids,
sort_num,
status,
campaign_id
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
RETURNING id,
node_type,
name,
parent_id,
level,
COALESCE(to_json(image_ids)::text, '[]'),
sort_num,
status,
campaign_id,
version
`, id, scope.TenantID, scope.StoreID, int16(category.NodeType), category.Name, parentID, int16(category.Level), stringSliceOrEmpty(category.ImageIDs), category.SortNum, int16(category.Status), campaignID)
createdCategory, err := scanCategory(row)
if nameConflict := categoryNameConflictError(err); nameConflict != nil {
return nil, nameConflict
}
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,
pi.supply_price,
pi.weight_kg,
pi.barcode,
COALESCE(to_json(pi.image_ids)::text, '[]'),
pi.attributes,
pi.status,
pi.is_archived,
pi.archived_at,
pi.version,
pi.deleted_at,
pi.created_at,
pi.updated_at,
inv.id,
inv.sku_id,
inv.stock_quantity,
inv.locked_quantity,
inv.sold_quantity,
inv.version,
inv.created_at,
inv.updated_at
FROM product.product_items pi
LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id
WHERE pi.product_id IN (%s)
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
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
}
// loadCartItemSKUsByIDs loads current and archived SKU rows used by cart display.
// Soft-deleted rows remain excluded so they are represented as missing to callers.
func (r *ProductRepository) loadCartItemSKUsByIDs(ctx context.Context, skuIDs []string) ([]SKURecord, error) {
if len(skuIDs) == 0 {
return []SKURecord{}, nil
}
placeholders := make([]string, len(skuIDs))
args := make([]any, len(skuIDs))
for i, id := range skuIDs {
parsed, err := parseID(id, "sku id")
if err != nil {
return nil, err
}
placeholders[i] = fmt.Sprintf("$%d", i+1)
args[i] = parsed
}
query := fmt.Sprintf(`
SELECT pi.id,
pi.product_id,
pi.sku_no,
pi.name,
pi.price,
pi.supply_price,
pi.weight_kg,
pi.barcode,
COALESCE(to_json(pi.image_ids)::text, '[]'),
pi.attributes,
pi.status,
pi.is_archived,
pi.archived_at,
pi.version,
pi.deleted_at,
pi.created_at,
pi.updated_at,
inv.id,
inv.sku_id,
inv.stock_quantity,
inv.locked_quantity,
inv.sold_quantity,
inv.version,
inv.created_at,
inv.updated_at
FROM product.product_items pi
LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id
WHERE pi.id IN (%s)
AND pi.deleted_at IS NULL
ORDER BY pi.created_at ASC, pi.id ASC
`, strings.Join(placeholders, ", "))
rows, err := r.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("query cart item skus: %w", err)
}
defer rows.Close()
skus := make([]SKURecord, 0, len(skuIDs))
for rows.Next() {
sku, err := scanSKU(rows)
if err != nil {
return nil, err
}
skus = append(skus, *sku)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate cart item skus: %w", err)
}
return skus, nil
}
type rowScanner interface {
Scan(dest ...any) error
}
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,
&rec.StockQuantity,
&rec.LockedQuantity,
); 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
version int32
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,
&version,
&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)
rec.Version = version
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
supplyPrice sql.NullInt64
weightKg sql.NullFloat64
barcode sql.NullString
imageIDsJSON string
attrsJSON []byte
status int16
isArchived bool
archivedAt sql.NullTime
version int32
deletedAt sql.NullTime
inventoryID sql.NullInt64
inventorySKUID sql.NullInt64
stockQuantity sql.NullInt32
lockedQuantity sql.NullInt32
soldQuantity sql.NullInt32
inventoryVersion sql.NullInt32
inventoryCreatedAt sql.NullTime
inventoryUpdatedAt sql.NullTime
)
if err := scanner.Scan(
&id,
&productID,
&skuNo,
&rec.Name,
&rec.Price,
&supplyPrice,
&weightKg,
&barcode,
&imageIDsJSON,
&attrsJSON,
&status,
&isArchived,
&archivedAt,
&version,
&deletedAt,
&rec.CreatedAt,
&rec.UpdatedAt,
&inventoryID,
&inventorySKUID,
&stockQuantity,
&lockedQuantity,
&soldQuantity,
&inventoryVersion,
&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
}
if supplyPrice.Valid {
value := supplyPrice.Int64
rec.SupplyPrice = &value
}
if weightKg.Valid {
value := weightKg.Float64
rec.WeightKg = &value
}
if barcode.Valid {
rec.Barcode = barcode.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)
rec.IsArchived = isArchived
rec.Version = version
if archivedAt.Valid {
rec.ArchivedAt = timePtr(archivedAt.Time)
}
if deletedAt.Valid {
rec.DeletedAt = timePtr(deletedAt.Time)
}
if inventoryID.Valid {
rec.Inventory = &InventoryRecord{
ID: formatID(inventoryID.Int64),
SKUID: formatID(inventorySKUID.Int64),
StockQuantity: nullInt32Value(stockQuantity),
LockedQuantity: nullInt32Value(lockedQuantity),
SoldQuantity: nullInt32Value(soldQuantity),
Version: nullInt32Value(inventoryVersion),
}
if inventoryCreatedAt.Valid {
rec.Inventory.CreatedAt = inventoryCreatedAt.Time
}
if inventoryUpdatedAt.Valid {
rec.Inventory.UpdatedAt = inventoryUpdatedAt.Time
}
rec.StockQuantity = rec.Inventory.StockQuantity
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.StockQuantity,
&rec.LockedQuantity,
&rec.SoldQuantity,
&rec.Version,
&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 scanGroup(scanner rowScanner) (*CategoryRecord, error) {
var (
rec CategoryRecord
id int64
parentID sql.NullInt64
imageIDsJSON []byte
nodeType int16
level int16
status int16
campaignID sql.NullInt64
)
if err := scanner.Scan(
&id, &nodeType, &rec.Name, &parentID, &level, &imageIDsJSON, &rec.SortNum, &status, &campaignID, &rec.Version, &rec.ProductCount,
); err != nil {
return nil, fmt.Errorf("scan group: %w", err)
}
rec.ID = formatID(id)
rec.NodeType = int32(nodeType)
if parentID.Valid {
rec.ParentID = formatID(parentID.Int64)
}
rec.Level = int32(level)
imageIDs, err := parseStringArrayJSON(string(imageIDsJSON))
if err != nil {
return nil, fmt.Errorf("unmarshal group image_ids: %w", err)
}
rec.ImageIDs = imageIDs
rec.Status = int32(status)
if campaignID.Valid {
rec.CampaignID = formatID(campaignID.Int64)
}
return &rec, nil
}
func scanCategory(scanner rowScanner) (*CategoryRecord, error) {
var (
rec CategoryRecord
id int64
parentID sql.NullInt64
imageIDsJSON []byte
nodeType int16
level int16
status int16
campaignID sql.NullInt64
)
if err := scanner.Scan(
&id, &nodeType, &rec.Name, &parentID, &level, &imageIDsJSON, &rec.SortNum, &status, &campaignID, &rec.Version,
); 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)
imageIDs, err := parseStringArrayJSON(string(imageIDsJSON))
if err != nil {
return nil, fmt.Errorf("unmarshal category image_ids: %w", err)
}
rec.ImageIDs = imageIDs
rec.Status = int32(status)
if campaignID.Valid {
rec.CampaignID = formatID(campaignID.Int64)
}
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 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}
}
// PromoteDueScheduledSales sets due scheduled products to ON_SALE (status=2).
func (r *ProductRepository) PromoteDueScheduledSales(ctx context.Context, now time.Time) (int64, error) {
res, err := r.db.ExecContext(ctx, `
UPDATE product.products
SET status = 2,
sale_time_type = 1,
scheduled_sale_time = NULL,
version = version + 1,
updated_at = NOW()
WHERE deleted_at IS NULL
AND sale_time_type = 2
AND scheduled_sale_time IS NOT NULL
AND scheduled_sale_time <= $1
AND status <> 2
`, now)
if err != nil {
return 0, fmt.Errorf("promote scheduled sales: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return 0, err
}
return n, nil
}
func nullableInt64(value *int64) any {
if value == nil {
return nil
}
return *value
}
func nullableFloat64(value *float64) any {
if value == nil {
return nil
}
return *value
}
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_INVENTORY:
return 1
case productv1.ProductStatus_PRODUCT_STATUS_ON_SALE:
return 2
case productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE:
return 3
default:
return 1
}
}
func statusFromDB(status int16) productv1.ProductStatus {
switch status {
case 1:
return productv1.ProductStatus_PRODUCT_STATUS_INVENTORY
case 2:
return productv1.ProductStatus_PRODUCT_STATUS_ON_SALE
case 3:
return productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE
default:
return productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED
}
}
// escapeLikeLiteral makes PostgreSQL LIKE metacharacters literal. The caller
// still passes the resulting value as a bound query parameter; this helper is
// about preserving search semantics rather than SQL injection prevention.
func escapeLikeLiteral(value string) string {
replacer := strings.NewReplacer(
`\`, `\\`,
`%`, `\%`,
`_`, `\_`,
)
return replacer.Replace(value)
}
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)
}