From f28df52a12956d01b16665e0fad882926e4b3fc0 Mon Sep 17 00:00:00 2001
From: robinj0726 <88188467+robinj0726@users.noreply.github.com>
Date: Fri, 2 Oct 2026 00:59:46 +0800
Subject: [PATCH] feat: implement freight template management and scheduled
sales promotion
---
cmd/main.go | 1 +
.../repository/freight_template_repository.go | 308 ++++++++++++++++++
internal/repository/product_repository.go | 87 ++++-
internal/server/freight_template_server.go | 267 +++++++++++++++
internal/server/html_sanitize.go | 42 +++
internal/server/product_server.go | 46 ++-
internal/server/scheduled_sale_worker.go | 43 +++
7 files changed, 784 insertions(+), 10 deletions(-)
create mode 100644 internal/repository/freight_template_repository.go
create mode 100644 internal/server/freight_template_server.go
create mode 100644 internal/server/html_sanitize.go
create mode 100644 internal/server/scheduled_sale_worker.go
diff --git a/cmd/main.go b/cmd/main.go
index 9a6913a..f484455 100644
--- a/cmd/main.go
+++ b/cmd/main.go
@@ -87,6 +87,7 @@ func main() {
}()
productServer := server.NewProductServer(repo, idGenerator, logger, observer)
+ server.StartScheduledSaleWorker(ctx, repo, logger, time.Minute)
grpcServer := grpc.NewServer(
grpc.StatsHandler(otelgrpc.NewServerHandler()),
diff --git a/internal/repository/freight_template_repository.go b/internal/repository/freight_template_repository.go
new file mode 100644
index 0000000..b106cf7
--- /dev/null
+++ b/internal/repository/freight_template_repository.go
@@ -0,0 +1,308 @@
+package repository
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+)
+
+var (
+ ErrFreightTemplateNotFound = errors.New("freight template not found")
+ ErrFreightTemplateVersionConflict = errors.New("freight template version conflict")
+ ErrFreightTemplateInUse = errors.New("freight template is referenced by products")
+)
+
+// FreightTemplateRecord is product.freight_templates.
+type FreightTemplateRecord struct {
+ ID string
+ Name string
+ PricingMode int32
+ DefaultFee *int64
+ RulesJSON []byte
+ Status int32
+ Version int32
+ Scope StoreScope
+ CreatedAt time.Time
+ UpdatedAt time.Time
+ DeletedAt *time.Time
+}
+
+// FreightTemplateListFilter pages store-scoped templates.
+type FreightTemplateListFilter struct {
+ Keyword string
+ Status *int32
+ Page, PageSize int32
+}
+
+// FreightTemplatePatch is an optimistic update.
+type FreightTemplatePatch struct {
+ ExpectedVersion int32
+ Name *string
+ PricingMode *int32
+ DefaultFee *int64
+ DefaultFeeSet bool
+ RulesJSON *[]byte
+ Status *int32
+}
+
+func (r *ProductRepository) ensureFreightTemplateSchema(ctx context.Context) error {
+ _, err := r.db.ExecContext(ctx, `
+CREATE TABLE IF NOT EXISTS product.freight_templates (
+ id BIGINT PRIMARY KEY,
+ tenant_id BIGINT NOT NULL,
+ store_id BIGINT NOT NULL,
+ name VARCHAR(64) NOT NULL,
+ pricing_mode SMALLINT NOT NULL DEFAULT 1 CHECK (pricing_mode IN (1, 2)),
+ default_fee BIGINT CHECK (default_fee IS NULL OR default_fee >= 0),
+ rules_json JSONB NOT NULL DEFAULT '{}'::jsonb,
+ status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
+ 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_freight_templates_store
+ ON product.freight_templates (store_id) WHERE deleted_at IS NULL;
+`)
+ return err
+}
+
+// CreateFreightTemplate inserts one template.
+func (r *ProductRepository) CreateFreightTemplate(ctx context.Context, rec FreightTemplateRecord) (*FreightTemplateRecord, error) {
+ if err := requireWriteScope(rec.Scope); err != nil {
+ return nil, err
+ }
+ id, err := parseID(rec.ID, "template_id")
+ if err != nil {
+ return nil, err
+ }
+ rules := rec.RulesJSON
+ if len(rules) == 0 {
+ rules = []byte("{}")
+ }
+ row := r.db.QueryRowContext(ctx, `
+INSERT INTO product.freight_templates (id, tenant_id, store_id, name, pricing_mode, default_fee, rules_json, status)
+VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8)
+RETURNING id::text, name, pricing_mode, default_fee, rules_json, status, version, created_at, updated_at, deleted_at
+`, id, rec.Scope.TenantID, rec.Scope.StoreID, rec.Name, rec.PricingMode, nullableInt64(rec.DefaultFee), rules, rec.Status)
+ return scanFreightTemplate(row, rec.Scope)
+}
+
+// GetFreightTemplate loads one non-deleted template.
+func (r *ProductRepository) GetFreightTemplate(ctx context.Context, templateID string, scope StoreScope) (*FreightTemplateRecord, error) {
+ if err := requireWriteScope(scope); err != nil {
+ return nil, err
+ }
+ id, err := parseID(templateID, "template_id")
+ if err != nil {
+ return nil, err
+ }
+ row := r.db.QueryRowContext(ctx, `
+SELECT id::text, name, pricing_mode, default_fee, rules_json, status, version, created_at, updated_at, deleted_at
+FROM product.freight_templates
+WHERE id = $1 AND store_id = $2 AND deleted_at IS NULL
+`, id, scope.StoreID)
+ rec, err := scanFreightTemplate(row, scope)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, ErrFreightTemplateNotFound
+ }
+ return rec, err
+}
+
+// ListFreightTemplates pages templates.
+func (r *ProductRepository) ListFreightTemplates(ctx context.Context, filter FreightTemplateListFilter, scope StoreScope) ([]FreightTemplateRecord, int64, error) {
+ if err := requireWriteScope(scope); err != nil {
+ return nil, 0, err
+ }
+ page, pageSize := filter.Page, filter.PageSize
+ if page < 1 {
+ page = 1
+ }
+ if pageSize < 1 {
+ pageSize = 20
+ }
+ if pageSize > 100 {
+ pageSize = 100
+ }
+ args := []any{scope.StoreID}
+ where := []string{"store_id = $1", "deleted_at IS NULL"}
+ if kw := strings.TrimSpace(filter.Keyword); kw != "" {
+ args = append(args, "%"+kw+"%")
+ where = append(where, fmt.Sprintf("name ILIKE $%d", len(args)))
+ }
+ if filter.Status != nil {
+ args = append(args, *filter.Status)
+ where = append(where, fmt.Sprintf("status = $%d", len(args)))
+ }
+ whereSQL := strings.Join(where, " AND ")
+ var total int64
+ if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.freight_templates WHERE `+whereSQL, args...).Scan(&total); err != nil {
+ return nil, 0, fmt.Errorf("count freight templates: %w", err)
+ }
+ args = append(args, pageSize, (page-1)*pageSize)
+ rows, err := r.db.QueryContext(ctx, fmt.Sprintf(`
+SELECT id::text, name, pricing_mode, default_fee, rules_json, status, version, created_at, updated_at, deleted_at
+FROM product.freight_templates
+WHERE %s
+ORDER BY updated_at DESC, id DESC
+LIMIT $%d OFFSET $%d
+`, whereSQL, len(args)-1, len(args)), args...)
+ if err != nil {
+ return nil, 0, fmt.Errorf("list freight templates: %w", err)
+ }
+ defer rows.Close()
+ out := make([]FreightTemplateRecord, 0)
+ for rows.Next() {
+ rec, err := scanFreightTemplate(rows, scope)
+ if err != nil {
+ return nil, 0, err
+ }
+ out = append(out, *rec)
+ }
+ return out, total, rows.Err()
+}
+
+// UpdateFreightTemplate applies a patch.
+func (r *ProductRepository) UpdateFreightTemplate(ctx context.Context, templateID string, patch FreightTemplatePatch, scope StoreScope) (*FreightTemplateRecord, error) {
+ current, err := r.GetFreightTemplate(ctx, templateID, scope)
+ if err != nil {
+ return nil, err
+ }
+ if current.Version != patch.ExpectedVersion {
+ return nil, ErrFreightTemplateVersionConflict
+ }
+ id, err := parseID(templateID, "template_id")
+ if err != nil {
+ return nil, err
+ }
+ name := current.Name
+ if patch.Name != nil {
+ name = strings.TrimSpace(*patch.Name)
+ }
+ mode := current.PricingMode
+ if patch.PricingMode != nil {
+ mode = *patch.PricingMode
+ }
+ fee := current.DefaultFee
+ if patch.DefaultFeeSet {
+ fee = patch.DefaultFee
+ }
+ rules := current.RulesJSON
+ if patch.RulesJSON != nil {
+ rules = *patch.RulesJSON
+ }
+ if len(rules) == 0 {
+ rules = []byte("{}")
+ }
+ st := current.Status
+ if patch.Status != nil {
+ st = *patch.Status
+ }
+ res, err := r.db.ExecContext(ctx, `
+UPDATE product.freight_templates
+SET name = $1, pricing_mode = $2, default_fee = $3, rules_json = $4::jsonb, status = $5,
+ version = version + 1, updated_at = NOW()
+WHERE id = $6 AND store_id = $7 AND version = $8 AND deleted_at IS NULL
+`, name, mode, nullableInt64(fee), rules, st, id, scope.StoreID, patch.ExpectedVersion)
+ if err != nil {
+ return nil, fmt.Errorf("update freight template: %w", err)
+ }
+ n, _ := res.RowsAffected()
+ if n == 0 {
+ return nil, ErrFreightTemplateVersionConflict
+ }
+ return r.GetFreightTemplate(ctx, templateID, scope)
+}
+
+// DeleteFreightTemplate soft-deletes when unused.
+func (r *ProductRepository) DeleteFreightTemplate(ctx context.Context, templateID string, expectedVersion int32, scope StoreScope) (*FreightTemplateRecord, error) {
+ current, err := r.GetFreightTemplate(ctx, templateID, scope)
+ if err != nil {
+ return nil, err
+ }
+ if current.Version != expectedVersion {
+ return nil, ErrFreightTemplateVersionConflict
+ }
+ id, err := parseID(templateID, "template_id")
+ if err != nil {
+ return nil, err
+ }
+ var used bool
+ if err := r.db.QueryRowContext(ctx, `
+SELECT EXISTS(
+ SELECT 1 FROM product.products
+ WHERE store_id = $1 AND freight_template_id = $2 AND deleted_at IS NULL
+)`, scope.StoreID, id).Scan(&used); err != nil {
+ return nil, fmt.Errorf("check freight template usage: %w", err)
+ }
+ if used {
+ return nil, ErrFreightTemplateInUse
+ }
+ res, err := r.db.ExecContext(ctx, `
+UPDATE product.freight_templates
+SET deleted_at = NOW(), updated_at = NOW(), version = version + 1
+WHERE id = $1 AND store_id = $2 AND version = $3 AND deleted_at IS NULL
+`, id, scope.StoreID, expectedVersion)
+ if err != nil {
+ return nil, fmt.Errorf("delete freight template: %w", err)
+ }
+ n, _ := res.RowsAffected()
+ if n == 0 {
+ return nil, ErrFreightTemplateVersionConflict
+ }
+ now := time.Now().UTC()
+ current.DeletedAt = &now
+ current.Version++
+ return current, nil
+}
+
+// FreightTemplateExists reports whether an enabled/non-deleted template exists in the store.
+func (r *ProductRepository) FreightTemplateExists(ctx context.Context, templateID string, scope StoreScope) error {
+ if err := requireWriteScope(scope); err != nil {
+ return err
+ }
+ id, err := parseID(templateID, "freight_template_id")
+ if err != nil {
+ return err
+ }
+ var ok bool
+ if err := r.db.QueryRowContext(ctx, `
+SELECT EXISTS(
+ SELECT 1 FROM product.freight_templates
+ WHERE id = $1 AND store_id = $2 AND deleted_at IS NULL AND status = 1
+)`, id, scope.StoreID).Scan(&ok); err != nil {
+ return fmt.Errorf("validate freight template: %w", err)
+ }
+ if !ok {
+ return ErrFreightTemplateNotFound
+ }
+ return nil
+}
+
+type freightScanner interface {
+ Scan(dest ...any) error
+}
+
+func scanFreightTemplate(row freightScanner, scope StoreScope) (*FreightTemplateRecord, error) {
+ var rec FreightTemplateRecord
+ var fee sql.NullInt64
+ var deleted sql.NullTime
+ var rules []byte
+ if err := row.Scan(&rec.ID, &rec.Name, &rec.PricingMode, &fee, &rules, &rec.Status, &rec.Version, &rec.CreatedAt, &rec.UpdatedAt, &deleted); err != nil {
+ return nil, err
+ }
+ if fee.Valid {
+ v := fee.Int64
+ rec.DefaultFee = &v
+ }
+ rec.RulesJSON = rules
+ if deleted.Valid {
+ t := deleted.Time
+ rec.DeletedAt = &t
+ }
+ rec.Scope = scope
+ return &rec, nil
+}
diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go
index a30d1bb..ea9619f 100644
--- a/internal/repository/product_repository.go
+++ b/internal/repository/product_repository.go
@@ -122,6 +122,8 @@ type SKURecord struct {
Name string
Price int64
SupplyPrice *int64
+ WeightKg *float64
+ Barcode string
ImageIDs []string
StockQuantity int32
LockedQuantity int32
@@ -202,6 +204,9 @@ type SKUUpdate struct {
Price *int64
SupplyPrice *int64
SupplyPriceSet bool
+ WeightKg *float64
+ WeightKgSet bool
+ Barcode *string
StockQuantity *int32
Status *int32
ImageIDs *[]string
@@ -499,6 +504,8 @@ 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;
@@ -569,6 +576,9 @@ CREATE INDEX IF NOT EXISTS idx_brands_supplier
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
}
@@ -1704,7 +1714,7 @@ FOR UPDATE
return ErrSKUVersionConflict
}
- if input.Name != nil || input.Price != nil || input.SupplyPriceSet || input.Status != nil || input.ImageIDs != nil {
+ 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
@@ -1732,6 +1742,19 @@ FOR UPDATE
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")
@@ -1925,12 +1948,12 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error
defer tx.Rollback()
err = tx.QueryRowContext(ctx, `
-INSERT INTO product.product_items (id, product_id, sku_no, name, price, supply_price, image_ids, attributes, status, tenant_id, store_id)
-SELECT $1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9, p.tenant_id, p.store_id
+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), stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&skuID)
+`, 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)
}
@@ -3393,8 +3416,8 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord)
}
row := tx.QueryRowContext(ctx, `
-INSERT INTO product.product_items (id, product_id, sku_no, name, price, supply_price, image_ids, attributes, status, tenant_id, store_id)
-SELECT $1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9, p.tenant_id, p.store_id
+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,
@@ -3403,6 +3426,8 @@ RETURNING id,
name,
price,
supply_price,
+ weight_kg,
+ barcode,
COALESCE(to_json(image_ids)::text, '[]'),
attributes,
status,
@@ -3420,7 +3445,7 @@ RETURNING id,
NULL::integer,
NULL::timestamptz,
NULL::timestamptz
-`, id, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, nullableInt64(sku.SupplyPrice), stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status))
+`, 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 {
@@ -3598,6 +3623,8 @@ SELECT pi.id,
pi.name,
pi.price,
pi.supply_price,
+ pi.weight_kg,
+ pi.barcode,
COALESCE(to_json(pi.image_ids)::text, '[]'),
pi.attributes,
pi.status,
@@ -3668,6 +3695,8 @@ SELECT pi.id,
pi.name,
pi.price,
pi.supply_price,
+ pi.weight_kg,
+ pi.barcode,
COALESCE(to_json(pi.image_ids)::text, '[]'),
pi.attributes,
pi.status,
@@ -3844,6 +3873,8 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) {
productID int64
skuNo sql.NullString
supplyPrice sql.NullInt64
+ weightKg sql.NullFloat64
+ barcode sql.NullString
imageIDsJSON string
attrsJSON []byte
status int16
@@ -3867,6 +3898,8 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) {
&rec.Name,
&rec.Price,
&supplyPrice,
+ &weightKg,
+ &barcode,
&imageIDsJSON,
&attrsJSON,
&status,
@@ -3897,6 +3930,13 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) {
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)
@@ -4158,6 +4198,32 @@ func nullString(raw string) 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
@@ -4165,6 +4231,13 @@ func nullableInt64(value *int64) any {
return *value
}
+func nullableFloat64(value *float64) any {
+ if value == nil {
+ return nil
+ }
+ return *value
+}
+
func stringSliceOrEmpty(values []string) []string {
if values == nil {
return []string{}
diff --git a/internal/server/freight_template_server.go b/internal/server/freight_template_server.go
new file mode 100644
index 0000000..7c71364
--- /dev/null
+++ b/internal/server/freight_template_server.go
@@ -0,0 +1,267 @@
+package server
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "unicode/utf8"
+
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+
+ productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
+ "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
+)
+
+const maxFreightTemplateNameLength = 64
+
+func (s *ProductServer) CreateFreightTemplate(ctx context.Context, req *productv1.CreateFreightTemplateRequest) (*productv1.CreateFreightTemplateResponse, error) {
+ if req == nil {
+ return nil, status.Error(codes.InvalidArgument, "request is required")
+ }
+ scope, err := requireStoreScope(req)
+ if err != nil {
+ return nil, err
+ }
+ rec, err := freightTemplateFromCreate(req)
+ if err != nil {
+ return nil, status.Error(codes.InvalidArgument, err.Error())
+ }
+ if s.idgen == nil {
+ return nil, status.Error(codes.Internal, "id generator is not configured")
+ }
+ rec.ID = s.idgen.NextString()
+ rec.Scope = scope
+ created, err := s.repo.CreateFreightTemplate(ctx, rec)
+ if err != nil {
+ return nil, freightTemplateGRPCError(err)
+ }
+ return &productv1.CreateFreightTemplateResponse{Template: toProtoFreightTemplate(created)}, nil
+}
+
+func (s *ProductServer) GetFreightTemplate(ctx context.Context, req *productv1.GetFreightTemplateRequest) (*productv1.GetFreightTemplateResponse, error) {
+ if req == nil {
+ return nil, status.Error(codes.InvalidArgument, "request is required")
+ }
+ scope, err := requireStoreScope(req)
+ if err != nil {
+ return nil, err
+ }
+ if err := validatePositiveID(req.GetTemplateId(), "template_id"); err != nil {
+ return nil, status.Error(codes.InvalidArgument, err.Error())
+ }
+ value, err := s.repo.GetFreightTemplate(ctx, req.GetTemplateId(), scope)
+ if err != nil {
+ return nil, freightTemplateGRPCError(err)
+ }
+ return &productv1.GetFreightTemplateResponse{Template: toProtoFreightTemplate(value)}, nil
+}
+
+func (s *ProductServer) ListFreightTemplates(ctx context.Context, req *productv1.ListFreightTemplatesRequest) (*productv1.ListFreightTemplatesResponse, error) {
+ if req == nil {
+ return nil, status.Error(codes.InvalidArgument, "request is required")
+ }
+ scope, err := requireStoreScope(req)
+ if err != nil {
+ return nil, err
+ }
+ page, size, err := catalogPagination(req.GetPage(), req.GetPageSize())
+ if err != nil {
+ return nil, status.Error(codes.InvalidArgument, err.Error())
+ }
+ var statusValue *int32
+ if req.Status != nil {
+ if *req.Status != 0 && *req.Status != 1 {
+ return nil, status.Error(codes.InvalidArgument, "status must be 0 or 1")
+ }
+ statusValue = req.Status
+ }
+ values, total, err := s.repo.ListFreightTemplates(ctx, repository.FreightTemplateListFilter{
+ Keyword: strings.TrimSpace(req.GetKeyword()), Status: statusValue, Page: page, PageSize: size,
+ }, scope)
+ if err != nil {
+ return nil, freightTemplateGRPCError(err)
+ }
+ out := make([]*productv1.FreightTemplate, 0, len(values))
+ for i := range values {
+ out = append(out, toProtoFreightTemplate(&values[i]))
+ }
+ return &productv1.ListFreightTemplatesResponse{
+ Templates: out, Page: page, PageSize: size, Total: total, TotalPages: catalogTotalPages(total, size),
+ }, nil
+}
+
+func (s *ProductServer) UpdateFreightTemplate(ctx context.Context, req *productv1.UpdateFreightTemplateRequest) (*productv1.UpdateFreightTemplateResponse, error) {
+ if req == nil {
+ return nil, status.Error(codes.InvalidArgument, "request is required")
+ }
+ scope, err := requireStoreScope(req)
+ if err != nil {
+ return nil, err
+ }
+ if err := validatePositiveID(req.GetTemplateId(), "template_id"); err != nil {
+ return nil, status.Error(codes.InvalidArgument, err.Error())
+ }
+ patch, err := freightTemplatePatch(req)
+ if err != nil {
+ return nil, status.Error(codes.InvalidArgument, err.Error())
+ }
+ updated, err := s.repo.UpdateFreightTemplate(ctx, req.GetTemplateId(), patch, scope)
+ if err != nil {
+ return nil, freightTemplateGRPCError(err)
+ }
+ return &productv1.UpdateFreightTemplateResponse{Template: toProtoFreightTemplate(updated)}, nil
+}
+
+func (s *ProductServer) DeleteFreightTemplate(ctx context.Context, req *productv1.DeleteFreightTemplateRequest) (*productv1.DeleteFreightTemplateResponse, error) {
+ if req == nil {
+ return nil, status.Error(codes.InvalidArgument, "request is required")
+ }
+ scope, err := requireStoreScope(req)
+ if err != nil {
+ return nil, err
+ }
+ if err := validatePositiveID(req.GetTemplateId(), "template_id"); err != nil {
+ return nil, status.Error(codes.InvalidArgument, err.Error())
+ }
+ deleted, err := s.repo.DeleteFreightTemplate(ctx, req.GetTemplateId(), req.GetExpectedVersion(), scope)
+ if err != nil {
+ return nil, freightTemplateGRPCError(err)
+ }
+ deletedAt := ""
+ if deleted.DeletedAt != nil {
+ deletedAt = timeToMillisString(*deleted.DeletedAt)
+ }
+ return &productv1.DeleteFreightTemplateResponse{TemplateId: deleted.ID, DeletedAt: deletedAt}, nil
+}
+
+func freightTemplateFromCreate(req *productv1.CreateFreightTemplateRequest) (repository.FreightTemplateRecord, error) {
+ name := strings.TrimSpace(req.GetName())
+ if name == "" {
+ return repository.FreightTemplateRecord{}, errors.New("name is required")
+ }
+ if utf8.RuneCountInString(name) > maxFreightTemplateNameLength {
+ return repository.FreightTemplateRecord{}, errors.New("name is too long")
+ }
+ mode := req.GetPricingMode()
+ if mode == 0 {
+ mode = 1
+ }
+ if mode != 1 && mode != 2 {
+ return repository.FreightTemplateRecord{}, errors.New("pricing_mode must be 1 or 2")
+ }
+ var fee *int64
+ if req.DefaultFee != nil {
+ if *req.DefaultFee < 0 {
+ return repository.FreightTemplateRecord{}, errors.New("default_fee must be >= 0")
+ }
+ fee = req.DefaultFee
+ }
+ if mode == 1 && fee == nil {
+ return repository.FreightTemplateRecord{}, errors.New("default_fee is required when pricing_mode is 1")
+ }
+ if mode == 2 && len(req.GetRulesJson()) == 0 {
+ return repository.FreightTemplateRecord{}, errors.New("rules_json is required when pricing_mode is 2")
+ }
+ st := int32(1)
+ if req.Status != nil {
+ if *req.Status != 0 && *req.Status != 1 {
+ return repository.FreightTemplateRecord{}, errors.New("status must be 0 or 1")
+ }
+ st = *req.Status
+ }
+ return repository.FreightTemplateRecord{
+ Name: name, PricingMode: mode, DefaultFee: fee, RulesJSON: append([]byte(nil), req.GetRulesJson()...), Status: st,
+ }, nil
+}
+
+func freightTemplatePatch(req *productv1.UpdateFreightTemplateRequest) (repository.FreightTemplatePatch, error) {
+ paths := make(map[string]struct{})
+ if req.GetUpdateMask() != nil {
+ for _, p := range req.GetUpdateMask().GetPaths() {
+ paths[strings.TrimSpace(p)] = struct{}{}
+ }
+ }
+ has := func(name string) bool {
+ if len(paths) == 0 {
+ return true
+ }
+ _, ok := paths[name]
+ return ok
+ }
+ patch := repository.FreightTemplatePatch{ExpectedVersion: req.GetExpectedVersion()}
+ if has("name") && req.Name != nil {
+ name := strings.TrimSpace(*req.Name)
+ if name == "" {
+ return patch, errors.New("name is required")
+ }
+ if utf8.RuneCountInString(name) > maxFreightTemplateNameLength {
+ return patch, errors.New("name is too long")
+ }
+ patch.Name = &name
+ }
+ if has("pricing_mode") && req.PricingMode != nil {
+ if *req.PricingMode != 1 && *req.PricingMode != 2 {
+ return patch, errors.New("pricing_mode must be 1 or 2")
+ }
+ patch.PricingMode = req.PricingMode
+ }
+ if has("default_fee") {
+ patch.DefaultFeeSet = true
+ if req.DefaultFee != nil {
+ if *req.DefaultFee < 0 {
+ return patch, errors.New("default_fee must be >= 0")
+ }
+ patch.DefaultFee = req.DefaultFee
+ }
+ }
+ if has("rules_json") && req.RulesJson != nil {
+ b := append([]byte(nil), req.GetRulesJson()...)
+ patch.RulesJSON = &b
+ }
+ if has("status") && req.Status != nil {
+ if *req.Status != 0 && *req.Status != 1 {
+ return patch, errors.New("status must be 0 or 1")
+ }
+ patch.Status = req.Status
+ }
+ return patch, nil
+}
+
+func toProtoFreightTemplate(rec *repository.FreightTemplateRecord) *productv1.FreightTemplate {
+ if rec == nil {
+ return nil
+ }
+ out := &productv1.FreightTemplate{
+ TemplateId: rec.ID,
+ Name: rec.Name,
+ PricingMode: rec.PricingMode,
+ DefaultFee: rec.DefaultFee,
+ RulesJson: append([]byte(nil), rec.RulesJSON...),
+ Status: rec.Status,
+ TenantId: fmt.Sprint(rec.Scope.TenantID),
+ StoreId: fmt.Sprint(rec.Scope.StoreID),
+ CreatedAt: timeToMillisString(rec.CreatedAt),
+ UpdatedAt: timeToMillisString(rec.UpdatedAt),
+ Version: rec.Version,
+ }
+ if rec.DeletedAt != nil {
+ v := timeToMillisString(*rec.DeletedAt)
+ out.DeletedAt = &v
+ }
+ return out
+}
+
+func freightTemplateGRPCError(err error) error {
+ switch {
+ case errors.Is(err, repository.ErrFreightTemplateNotFound):
+ return status.Error(codes.NotFound, err.Error())
+ case errors.Is(err, repository.ErrFreightTemplateVersionConflict):
+ return status.Error(codes.Aborted, err.Error())
+ case errors.Is(err, repository.ErrFreightTemplateInUse):
+ return status.Error(codes.FailedPrecondition, err.Error())
+ default:
+ return status.Errorf(codes.Internal, "%v", err)
+ }
+}
diff --git a/internal/server/html_sanitize.go b/internal/server/html_sanitize.go
new file mode 100644
index 0000000..2d6ccc0
--- /dev/null
+++ b/internal/server/html_sanitize.go
@@ -0,0 +1,42 @@
+package server
+
+import (
+ "regexp"
+ "strings"
+)
+
+var (
+ reScriptTag = regexp.MustCompile(`(?is)`)
+ reIFrameTag = regexp.MustCompile(`(?is)`)
+ reObjectTag = regexp.MustCompile(`(?is)`)
+ reEmbedTag = regexp.MustCompile(`(?is)`)
+ reEventAttr = regexp.MustCompile(`(?i)\s+on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)`)
+ reJSURL = regexp.MustCompile(`(?i)(href|src)\s*=\s*("|')\s*javascript:[^"']*("|')`)
+ reDataJSURL = regexp.MustCompile(`(?i)(href|src)\s*=\s*("|')\s*data:text/html[^"']*("|')`)
+)
+
+const maxDetailHTMLBytes = 512 * 1024
+
+func sanitizeDetailHTML(raw string) (string, error) {
+ if raw == "" {
+ return "", nil
+ }
+ if len(raw) > maxDetailHTMLBytes {
+ return "", errDetailHTMLTooLarge
+ }
+ out := raw
+ out = reScriptTag.ReplaceAllString(out, "")
+ out = reIFrameTag.ReplaceAllString(out, "")
+ out = reObjectTag.ReplaceAllString(out, "")
+ out = reEmbedTag.ReplaceAllString(out, "")
+ out = reEventAttr.ReplaceAllString(out, "")
+ out = reJSURL.ReplaceAllString(out, `$1=""`)
+ out = reDataJSURL.ReplaceAllString(out, `$1=""`)
+ return strings.TrimSpace(out), nil
+}
+
+type detailHTMLError string
+
+func (e detailHTMLError) Error() string { return string(e) }
+
+const errDetailHTMLTooLarge = detailHTMLError("detail_html exceeds maximum size")
diff --git a/internal/server/product_server.go b/internal/server/product_server.go
index 657e516..ad94f61 100644
--- a/internal/server/product_server.go
+++ b/internal/server/product_server.go
@@ -89,6 +89,14 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create
if err := s.repo.ValidateProductMasterRefs(ctx, product.SupplierID, product.BrandID, scope); err != nil {
return nil, catalogGRPCError(err)
}
+ if product.FreightChargeType == 2 {
+ if err := s.repo.FreightTemplateExists(ctx, product.FreightTemplateID, scope); err != nil {
+ if errors.Is(err, repository.ErrFreightTemplateNotFound) {
+ return nil, status.Error(codes.InvalidArgument, "freight_template_id not found or disabled")
+ }
+ return nil, status.Errorf(codes.Internal, "validate freight template: %v", err)
+ }
+ }
if s.idgen == nil {
return nil, status.Error(codes.Internal, "id generator is not configured")
}
@@ -363,7 +371,14 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update
if err := s.repo.ValidateProductMasterRefs(ctx, merged.SupplierID, merged.BrandID, scope); err != nil {
return nil, catalogGRPCError(err)
}
-
+ if merged.FreightChargeType == 2 {
+ if err := s.repo.FreightTemplateExists(ctx, merged.FreightTemplateID, scope); err != nil {
+ if errors.Is(err, repository.ErrFreightTemplateNotFound) {
+ return nil, status.Error(codes.InvalidArgument, "freight_template_id not found or disabled")
+ }
+ return nil, status.Errorf(codes.Internal, "validate freight template: %v", err)
+ }
+ }
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.update", trace.WithAttributes(attribute.String("product.id", req.GetProductId())))
defer dbSpan.End()
var leafCategoryIDs *[]string
@@ -1785,7 +1800,7 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P
BrandID: strings.TrimSpace(req.GetBrandId()),
SupplierID: strings.TrimSpace(req.GetSupplierId()),
ImageIDs: normalizeStringList(req.GetImageIds()),
- DetailHTML: req.GetDetailHtml(),
+ DetailHTML: "",
MemberDiscountEnabled: req.GetMemberDiscountEnabled(),
GoodsType: defaultInt32(req.GetGoodsType(), 1),
ServiceGuarantees: normalizeStringList(req.GetServiceGuarantees()),
@@ -1797,6 +1812,11 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P
SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1),
ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()),
}
+ detailHTML, err := sanitizeDetailHTML(req.GetDetailHtml())
+ if err != nil {
+ return repository.ProductRecord{}, nil, err
+ }
+ record.DetailHTML = detailHTML
leafCategoryIDs, err := normalizeLeafCategoryIDs(req.GetLeafCatalogCategoryIds())
if err != nil {
return repository.ProductRecord{}, nil, err
@@ -1865,7 +1885,11 @@ func mergeProductUpdate(current *repository.ProductRecord, update *productv1.Pro
case "image_ids":
merged.ImageIDs = normalizeStringList(update.GetImageIds())
case "detail_html":
- merged.DetailHTML = update.GetDetailHtml()
+ sanitized, err := sanitizeDetailHTML(update.GetDetailHtml())
+ if err != nil {
+ return repository.ProductRecord{}, err
+ }
+ merged.DetailHTML = sanitized
case "member_discount_enabled":
merged.MemberDiscountEnabled = update.GetMemberDiscountEnabled()
case "service_guarantees":
@@ -2008,6 +2032,15 @@ func skuUpdateFromProto(input *productv1.PatchExistingSKU) (repository.SKUUpdate
case "supply_price":
update.SupplyPriceSet = true
update.SupplyPrice = input.SupplyPrice
+ case "weight_kg":
+ update.WeightKgSet = true
+ update.WeightKg = input.WeightKg
+ if update.WeightKg != nil && *update.WeightKg < 0 {
+ return repository.SKUUpdate{}, errors.New("weight_kg must be greater than or equal to 0")
+ }
+ case "barcode":
+ value := strings.TrimSpace(input.GetBarcode())
+ update.Barcode = &value
case "stock_quantity":
value := input.GetStockQuantity()
update.StockQuantity = &value
@@ -2063,6 +2096,9 @@ func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord,
if sku.SupplyPrice != nil && *sku.SupplyPrice < 0 {
return repository.SKURecord{}, errors.New("supply_price must be greater than or equal to 0")
}
+ if sku.WeightKg != nil && *sku.WeightKg < 0 {
+ return repository.SKURecord{}, errors.New("weight_kg must be greater than or equal to 0")
+ }
if sku.GetStockQuantity() < 0 {
return repository.SKURecord{}, errors.New("stock_quantity must be greater than or equal to 0")
}
@@ -2085,6 +2121,8 @@ func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord,
Name: name,
Price: sku.GetPrice(),
SupplyPrice: sku.SupplyPrice,
+ WeightKg: sku.WeightKg,
+ Barcode: strings.TrimSpace(sku.GetBarcode()),
ImageIDs: normalizeStringList(sku.GetImageIds()),
StockQuantity: sku.GetStockQuantity(),
AttributesJSON: attrs,
@@ -2321,6 +2359,8 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
Name: sku.Name,
Price: sku.Price,
SupplyPrice: sku.SupplyPrice,
+ WeightKg: sku.WeightKg,
+ Barcode: sku.Barcode,
StockQuantity: sku.StockQuantity,
SoldQuantity: sku.SoldQuantity,
AttributesJson: sku.AttributesJSON,
diff --git a/internal/server/scheduled_sale_worker.go b/internal/server/scheduled_sale_worker.go
new file mode 100644
index 0000000..88aeb98
--- /dev/null
+++ b/internal/server/scheduled_sale_worker.go
@@ -0,0 +1,43 @@
+package server
+
+import (
+ "context"
+ "time"
+
+ "go.uber.org/zap"
+
+ "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
+)
+
+// StartScheduledSaleWorker periodically promotes due scheduled products to ON_SALE.
+func StartScheduledSaleWorker(ctx context.Context, repo *repository.ProductRepository, logger *zap.Logger, interval time.Duration) {
+ if interval <= 0 {
+ interval = time.Minute
+ }
+ if logger == nil {
+ logger = zap.NewNop()
+ }
+ go func() {
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ run := func() {
+ n, err := repo.PromoteDueScheduledSales(ctx, time.Now().UTC())
+ if err != nil {
+ logger.Error("promote scheduled sales failed", zap.Error(err))
+ return
+ }
+ if n > 0 {
+ logger.Info("promoted scheduled sales", zap.Int64("count", n))
+ }
+ }
+ run()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ run()
+ }
+ }
+ }()
+}