diff --git a/Dockerfile b/Dockerfile index f61f766..227c022 100644 --- a/Dockerfile +++ b/Dockerfile @@ -25,6 +25,7 @@ RUN apk add --no-cache ca-certificates tzdata \ && adduser -D -H -u 10001 appuser COPY --from=builder /out/ids-svc-product /usr/local/bin/ids-svc-product +COPY --from=builder /src/ids-svc-product/scripts/sql/008_product_presale_delivery_purchase_limit.sql /app/migrations/008_product_presale_delivery_purchase_limit.sql USER appuser diff --git a/README.md b/README.md index e31a1ed..6e1abea 100644 --- a/README.md +++ b/README.md @@ -276,7 +276,7 @@ go build ./... go run ./cmd ``` -启动时会执行 `db.PingContext()` 校验数据库连通性,并通过 `EnsureSchema` 补齐 `skus` 表及 `products` 扩展列。 +启动时会执行 `db.PingContext()` 校验数据库连通性;随后执行 `scripts/sql/008_product_presale_delivery_purchase_limit.sql`(生产镜像内路径为 `/app/migrations/`)并通过 `EnsureSchema` 补齐 `skus` 表及其他 `products` 扩展列。该预售迁移使用 PostgreSQL advisory lock 串行化多副本启动,SQL 本身可重复执行;迁移失败时服务不会开始监听端口。 ### 本地联调(grpcurl) diff --git a/cmd/main.go b/cmd/main.go index f484455..91dbfe8 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -73,6 +73,9 @@ func main() { } repo := repository.NewProductRepository(db) + if err := repository.ApplyProductPresaleMigration(ctx, db); err != nil { + logger.Fatal("apply product presale migration failed", zap.Error(err)) + } if err := repo.EnsureSchema(ctx); err != nil { logger.Fatal("ensure product schema failed", zap.Error(err)) } diff --git a/internal/repository/product_presale_migration.go b/internal/repository/product_presale_migration.go new file mode 100644 index 0000000..35e51bd --- /dev/null +++ b/internal/repository/product_presale_migration.go @@ -0,0 +1,60 @@ +package repository + +import ( + "context" + "database/sql" + "fmt" + "os" +) + +const ( + productPresaleMigrationFile = "008_product_presale_delivery_purchase_limit.sql" + productPresaleMigrationLockID = 904_120_008 +) + +// ApplyProductPresaleMigration executes the release SQL before the product +// service begins serving traffic. The migration itself is idempotent; the +// advisory lock only serializes concurrent replicas during deployment. +func ApplyProductPresaleMigration(ctx context.Context, db *sql.DB) error { + if db == nil { + return fmt.Errorf("database is required") + } + + ddl, err := readProductPresaleMigration() + if err != nil { + return err + } + + conn, err := db.Conn(ctx) + if err != nil { + return fmt.Errorf("acquire product presale migration connection: %w", err) + } + defer conn.Close() + if _, err := conn.ExecContext(ctx, "SELECT pg_advisory_lock($1)", productPresaleMigrationLockID); err != nil { + return fmt.Errorf("lock product presale migration: %w", err) + } + defer func() { + _, _ = conn.ExecContext(context.Background(), "SELECT pg_advisory_unlock($1)", productPresaleMigrationLockID) + }() + + if _, err := conn.ExecContext(ctx, string(ddl)); err != nil { + return fmt.Errorf("apply product presale migration: %w", err) + } + return nil +} + +func readProductPresaleMigration() ([]byte, error) { + paths := []string{ + "scripts/sql/" + productPresaleMigrationFile, + "/app/migrations/" + productPresaleMigrationFile, + } + var lastErr error + for _, path := range paths { + contents, err := os.ReadFile(path) + if err == nil { + return contents, nil + } + lastErr = err + } + return nil, fmt.Errorf("read product presale migration: %w", lastErr) +} diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 4704074..abe5742 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -95,6 +95,11 @@ type ProductRecord struct { FreightTemplateID string SaleTimeType int32 ScheduledSaleTime *time.Time + PresaleType int32 + DeliveryTimeType int32 + DeliveryStartAt *time.Time + DeliveryAfterPaidDays int32 + PurchaseLimitQuantity int32 LeafCategoryIDs []string CategoryBindingIDs []string GroupIDs []string @@ -281,6 +286,7 @@ type CategoryProductRecord struct { StockQuantity int64 LockedQuantity int64 CategoryPropertiesJSON string + PresaleType int32 CreatedAt time.Time UpdatedAt time.Time } @@ -301,6 +307,7 @@ type ProductListFilter struct { SoldQuantityMax *int64 PriceMin *int64 PriceMax *int64 + PresaleType *int32 } // CategoryRecord is the persistence model for product.catalog_category. @@ -597,6 +604,21 @@ CREATE INDEX IF NOT EXISTS idx_products_active_created_id ON product.products(cr 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.products ADD COLUMN IF NOT EXISTS category_properties JSONB NOT NULL DEFAULT '{}'::JSONB; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS presale_type SMALLINT NOT NULL DEFAULT 0; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS delivery_time_type SMALLINT NOT NULL DEFAULT 0; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS delivery_start_at TIMESTAMPTZ; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS delivery_after_paid_days INTEGER; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS purchase_limit_quantity INTEGER NOT NULL DEFAULT 0; +ALTER TABLE product.products DROP CONSTRAINT IF EXISTS chk_products_presale_configuration; +ALTER TABLE product.products ADD CONSTRAINT chk_products_presale_configuration CHECK ( + presale_type IN (0, 1, 2) + AND purchase_limit_quantity >= 0 + AND ( + (delivery_time_type = 0 AND delivery_start_at IS NULL AND delivery_after_paid_days IS NULL) + OR (delivery_time_type = 1 AND delivery_start_at IS NOT NULL AND delivery_after_paid_days IS NULL) + OR (delivery_time_type = 2 AND delivery_start_at IS NULL AND delivery_after_paid_days > 0) + ) +); 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; @@ -610,6 +632,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_products_store_spu_no ON product.products (store_id, spu_no) WHERE deleted_at IS NULL AND spu_no <> ''; 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_products_store_presale_created_id + ON product.products (store_id, presale_type, created_at DESC, id DESC) 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_catalog_category_store_type_parent_status_sort ON product.catalog_category (store_id, node_type, parent_id, status, sort_num, id); @@ -1507,9 +1531,20 @@ func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRe 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() +SET spu_no = $2, + title = $3, + selling_point = $4, + status = $5, + cross_border = $6::jsonb, + presale_type = $7, + delivery_time_type = $8, + delivery_start_at = $9, + delivery_after_paid_days = $10, + purchase_limit_quantity = $11, + updated_at = NOW() WHERE id = $1 -`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs) +`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs, + int16(product.PresaleType), int16(product.DeliveryTimeType), deliveryStartAtArgument(product), deliveryAfterPaidDaysArgument(product), product.PurchaseLimitQuantity) if err != nil { return fmt.Errorf("update product %s: %w", product.ID, err) } @@ -1618,14 +1653,21 @@ SET title = $2, freight_template_id = $15, sale_time_type = $16, scheduled_sale_time = $17, + presale_type = $18, + delivery_time_type = $19, + delivery_start_at = $20, + delivery_after_paid_days = $21, + purchase_limit_quantity = $22, version = version + 1, updated_at = NOW() -WHERE id = $1 AND version = $18 AND deleted_at IS NULL AND store_id = $19 +WHERE id = $1 AND version = $23 AND deleted_at IS NULL AND store_id = $24 `, 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, categoryProperties, int16(input.Product.FreightChargeType), input.Product.FreightFixedAmount, freightTemplateID, - int16(input.Product.SaleTimeType), input.Product.ScheduledSaleTime, input.ExpectedVersion, input.Scope.StoreID); err != nil { + int16(input.Product.SaleTimeType), input.Product.ScheduledSaleTime, + int16(input.Product.PresaleType), int16(input.Product.DeliveryTimeType), deliveryStartAtArgument(input.Product), deliveryAfterPaidDaysArgument(input.Product), input.Product.PurchaseLimitQuantity, + input.ExpectedVersion, input.Scope.StoreID); err != nil { return nil, fmt.Errorf("update product %s: %w", input.Product.ID, err) } @@ -3232,8 +3274,9 @@ SELECT p.updated_at, p.id, p.spu_no, p.status, - COALESCE(to_json(p.image_ids)::text, '[]'), + COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(p.category_properties, '{}'::jsonb)::text, + p.presale_type, COALESCE(sku_summary.price, 0), COALESCE(sku_summary.sold_quantity, 0), COALESCE(sku_summary.stock_quantity, 0), @@ -3330,6 +3373,9 @@ func productListWhere(filter ProductListFilter, scope StoreScope) (string, []any if filter.PriceMax != nil { add("COALESCE(sku_summary.price, 0) <= $%d", *filter.PriceMax) } + if filter.PresaleType != nil { + add("p.presale_type = $%d", *filter.PresaleType) + } return strings.Join(predicates, " AND "), args } @@ -3384,8 +3430,9 @@ SELECT p.updated_at, p.id, p.spu_no, p.status, - COALESCE(to_json(p.image_ids)::text, '[]'), + COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(p.category_properties, '{}'::jsonb)::text, + p.presale_type, COALESCE(sku_summary.price, 0), COALESCE(sku_summary.sold_quantity, 0), COALESCE(sku_summary.stock_quantity, 0), @@ -3584,8 +3631,9 @@ SELECT DISTINCT p.updated_at, p.id, p.spu_no, p.status, - COALESCE(to_json(p.image_ids)::text, '[]'), + COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(p.category_properties, '{}'::jsonb)::text, + p.presale_type, COALESCE(sku_summary.price, 0), COALESCE(sku_summary.sold_quantity, 0), COALESCE(sku_summary.stock_quantity, 0), @@ -3885,6 +3933,11 @@ SELECT id, freight_template_id, sale_time_type, scheduled_sale_time, + presale_type, + delivery_time_type, + delivery_start_at, + COALESCE(delivery_after_paid_days, 0), + purchase_limit_quantity, version, deleted_at, created_at, @@ -3961,9 +4014,14 @@ INSERT INTO product.products ( freight_fixed_amount, freight_template_id, sale_time_type, - scheduled_sale_time + scheduled_sale_time, + presale_type, + delivery_time_type, + delivery_start_at, + delivery_after_paid_days, + purchase_limit_quantity ) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15::jsonb, $16::jsonb, $17, $18, $19, $20, $21) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15::jsonb, $16::jsonb, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26) RETURNING id, spu_no, title, @@ -3983,6 +4041,11 @@ RETURNING id, freight_template_id, sale_time_type, scheduled_sale_time, + presale_type, + delivery_time_type, + delivery_start_at, + COALESCE(delivery_after_paid_days, 0), + purchase_limit_quantity, version, deleted_at, created_at, @@ -3990,7 +4053,8 @@ RETURNING id, `, 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, categoryProperties, int16(product.FreightChargeType), product.FreightFixedAmount, freightTemplateID, - int16(product.SaleTimeType), product.ScheduledSaleTime) + int16(product.SaleTimeType), product.ScheduledSaleTime, + int16(product.PresaleType), int16(product.DeliveryTimeType), deliveryStartAtArgument(product), deliveryAfterPaidDaysArgument(product), product.PurchaseLimitQuantity) createdProduct, err := scanProduct(row) if err != nil { @@ -4384,6 +4448,7 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { &status, &imageIDsJSON, &categoryPropertiesJSON, + &rec.PresaleType, &rec.Price, &rec.SoldQuantity, &rec.StockQuantity, @@ -4422,6 +4487,9 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) { freightTemplateID sql.NullInt64 saleTimeType int16 scheduledSaleTime sql.NullTime + presaleType int16 + deliveryTimeType int16 + deliveryStartAt sql.NullTime version int32 deletedAt sql.NullTime ) @@ -4445,6 +4513,11 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) { &freightTemplateID, &saleTimeType, &scheduledSaleTime, + &presaleType, + &deliveryTimeType, + &deliveryStartAt, + &rec.DeliveryAfterPaidDays, + &rec.PurchaseLimitQuantity, &version, &deletedAt, &rec.CreatedAt, @@ -4491,15 +4564,36 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) { } rec.FreightChargeType = int32(freightChargeType) rec.SaleTimeType = int32(saleTimeType) + rec.PresaleType = int32(presaleType) + rec.DeliveryTimeType = int32(deliveryTimeType) if scheduledSaleTime.Valid { rec.ScheduledSaleTime = timePtr(scheduledSaleTime.Time) } + if deliveryStartAt.Valid { + rec.DeliveryStartAt = timePtr(deliveryStartAt.Time) + } if deletedAt.Valid { rec.DeletedAt = timePtr(deletedAt.Time) } return &rec, nil } +// deliveryStartAtArgument and deliveryAfterPaidDaysArgument preserve the +// database invariant that non-applicable delivery promise values are NULL. +func deliveryStartAtArgument(product ProductRecord) any { + if product.DeliveryTimeType != 1 { + return nil + } + return product.DeliveryStartAt +} + +func deliveryAfterPaidDaysArgument(product ProductRecord) any { + if product.DeliveryTimeType != 2 { + return nil + } + return product.DeliveryAfterPaidDays +} + func scanSKU(scanner rowScanner) (*SKURecord, error) { var ( rec SKURecord diff --git a/internal/server/product_presale_configuration_test.go b/internal/server/product_presale_configuration_test.go new file mode 100644 index 0000000..0936d53 --- /dev/null +++ b/internal/server/product_presale_configuration_test.go @@ -0,0 +1,83 @@ +package server + +import ( + "testing" + "time" + + "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" +) + +func TestValidateProductDeliveryConfiguration(t *testing.T) { + scheduled := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + tests := []struct { + name string + product repository.ProductRecord + wantErr bool + }{ + { + name: "specified delivery time", + product: repository.ProductRecord{ + PresaleType: 1, + DeliveryTimeType: 1, + DeliveryStartAt: &scheduled, + PurchaseLimitQuantity: 2, + }, + }, + { + name: "after paid days", + product: repository.ProductRecord{ + PresaleType: 2, + DeliveryTimeType: 2, + DeliveryAfterPaidDays: 7, + PurchaseLimitQuantity: 0, + }, + }, + { + name: "specified delivery time requires date", + product: repository.ProductRecord{ + DeliveryTimeType: 1, + }, + wantErr: true, + }, + { + name: "after paid days must be positive", + product: repository.ProductRecord{ + DeliveryTimeType: 2, + DeliveryAfterPaidDays: 0, + }, + wantErr: true, + }, + { + name: "purchase limit cannot be negative", + product: repository.ProductRecord{ + PurchaseLimitQuantity: -1, + }, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + product := tt.product + err := validateProductDeliveryConfiguration(&product) + if (err != nil) != tt.wantErr { + t.Fatalf("validateProductDeliveryConfiguration() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestValidateProductDeliveryConfigurationClearsInapplicableValues(t *testing.T) { + scheduled := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + product := repository.ProductRecord{ + DeliveryTimeType: 0, + DeliveryStartAt: &scheduled, + DeliveryAfterPaidDays: 5, + } + if err := validateProductDeliveryConfiguration(&product); err != nil { + t.Fatalf("validateProductDeliveryConfiguration() error = %v", err) + } + if product.DeliveryStartAt != nil || product.DeliveryAfterPaidDays != 0 { + t.Fatalf("inapplicable delivery values were not cleared: %#v", product) + } +} diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 0a6b4b1..f1148d5 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -380,7 +380,7 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update if len(req.GetUpdateMask().GetPaths()) == 0 && skuChange == nil { return nil, status.Error(codes.InvalidArgument, "at least one product field or sku_change is required") } - if err := validateProductForUpdate(merged); err != nil { + if err := validateProductForUpdate(&merged); err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } if err := s.repo.ValidateProductMasterRefs(ctx, merged.SupplierID, merged.BrandID, scope); err != nil { @@ -795,6 +795,13 @@ func productListFilterFromRequest(req *productv1.ListProductsRequest) (repositor } filter.GoodsType = &goodsType } + if req.PresaleType != nil { + presaleType := req.GetPresaleType() + if presaleType < 0 || presaleType > 2 { + return repository.ProductListFilter{}, errors.New("presale_type must be 0, 1, or 2") + } + filter.PresaleType = &presaleType + } if req.SoldQuantityMin != nil { value := req.GetSoldQuantityMin() if value < 0 { @@ -2121,6 +2128,11 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()), SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1), ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()), + PresaleType: req.GetPresaleType(), + DeliveryTimeType: req.GetDeliveryTimeType(), + DeliveryStartAt: timestampToTime(req.GetDeliveryStartAt()), + DeliveryAfterPaidDays: req.GetDeliveryAfterPaidDays(), + PurchaseLimitQuantity: req.GetPurchaseLimitQuantity(), } detailHTML, err := sanitizeDetailHTML(req.GetDetailHtml()) if err != nil { @@ -2160,6 +2172,9 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P if record.SaleTimeType == 2 && record.ScheduledSaleTime == nil { return repository.ProductRecord{}, nil, errors.New("scheduled_sale_time is required when sale_time_type is 2") } + if err := validateProductDeliveryConfiguration(&record); err != nil { + return repository.ProductRecord{}, nil, err + } skus := make([]repository.SKURecord, 0, len(req.GetSkus())) for i, protoSKU := range req.GetSkus() { @@ -2233,6 +2248,16 @@ func mergeProductUpdate(current *repository.ProductRecord, update *productv1.Pro merged.ScheduledSaleTime = timestampToTime(update.GetScheduledSaleTime()) case "goods_type": merged.GoodsType = update.GetGoodsType() + case "presale_type": + merged.PresaleType = update.GetPresaleType() + case "delivery_time_type": + merged.DeliveryTimeType = update.GetDeliveryTimeType() + case "delivery_start_at": + merged.DeliveryStartAt = timestampToTime(update.GetDeliveryStartAt()) + case "delivery_after_paid_days": + merged.DeliveryAfterPaidDays = update.GetDeliveryAfterPaidDays() + case "purchase_limit_quantity": + merged.PurchaseLimitQuantity = update.GetPurchaseLimitQuantity() case "leaf_catalog_category_ids": leafCategoryIDs, err := normalizeLeafCategoryIDs(update.GetLeafCatalogCategoryIds()) if err != nil { @@ -2267,7 +2292,10 @@ func containsUpdatePath(paths []string, target string) bool { return false } -func validateProductForUpdate(product repository.ProductRecord) error { +func validateProductForUpdate(product *repository.ProductRecord) error { + if product == nil { + return errors.New("product is required") + } if strings.TrimSpace(product.Title) == "" { return errors.New("title is required") } @@ -2289,6 +2317,33 @@ func validateProductForUpdate(product repository.ProductRecord) error { if product.SaleTimeType == 2 && product.ScheduledSaleTime == nil { return errors.New("scheduled_sale_time is required when sale_time_type is 2") } + return validateProductDeliveryConfiguration(product) +} + +func validateProductDeliveryConfiguration(product *repository.ProductRecord) error { + if product.PresaleType < 0 || product.PresaleType > 2 { + return errors.New("presale_type must be 0, 1, or 2") + } + if product.PurchaseLimitQuantity < 0 { + return errors.New("purchase_limit_quantity must be greater than or equal to 0") + } + switch product.DeliveryTimeType { + case 0: + product.DeliveryStartAt = nil + product.DeliveryAfterPaidDays = 0 + case 1: + if product.DeliveryStartAt == nil { + return errors.New("delivery_start_at is required when delivery_time_type is 1") + } + product.DeliveryAfterPaidDays = 0 + case 2: + if product.DeliveryAfterPaidDays <= 0 { + return errors.New("delivery_after_paid_days must be greater than 0 when delivery_time_type is 2") + } + product.DeliveryStartAt = nil + default: + return errors.New("delivery_time_type must be 0, 1, or 2") + } return nil } @@ -2709,6 +2764,13 @@ func timePtrToMillisString(value *time.Time) *string { return &millis } +func timePtrToTimestamp(value *time.Time) *timestamppb.Timestamp { + if value == nil { + return nil + } + return timestamppb.New(*value) +} + func validatePositiveID(raw, field string) error { if raw == "" { return errors.New(field + " is required") @@ -2781,6 +2843,11 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco FreightTemplateId: product.FreightTemplateID, SaleTimeType: product.SaleTimeType, ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime), + PresaleType: product.PresaleType, + DeliveryTimeType: product.DeliveryTimeType, + DeliveryStartAt: timePtrToTimestamp(product.DeliveryStartAt), + DeliveryAfterPaidDays: product.DeliveryAfterPaidDays, + PurchaseLimitQuantity: product.PurchaseLimitQuantity, Version: product.Version, DeletedAt: timePtrToMillisString(product.DeletedAt), LeafCatalogCategoryIds: append([]string(nil), product.LeafCategoryIDs...), @@ -2804,6 +2871,11 @@ func toProtoCartItemProduct(lineID string, record repository.CartItemProductReco result.ServiceGuarantees = record.Product.ServiceGuarantees result.SpuImageIds = record.Product.ImageIDs result.SpuStatus = record.Product.Status + result.PresaleType = record.Product.PresaleType + result.DeliveryTimeType = record.Product.DeliveryTimeType + result.DeliveryStartAt = timePtrToTimestamp(record.Product.DeliveryStartAt) + result.DeliveryAfterPaidDays = record.Product.DeliveryAfterPaidDays + result.PurchaseLimitQuantity = record.Product.PurchaseLimitQuantity if record.SKU == nil { return result } @@ -2835,6 +2907,7 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord) *productv StockQuantity: product.StockQuantity, LockedQuantity: product.LockedQuantity, CategoryProperties: categoryPropertiesProto(product.CategoryPropertiesJSON), + PresaleType: product.PresaleType, } } diff --git a/scripts/sql/008_product_presale_delivery_purchase_limit.sql b/scripts/sql/008_product_presale_delivery_purchase_limit.sql new file mode 100644 index 0000000..af8e529 --- /dev/null +++ b/scripts/sql/008_product_presale_delivery_purchase_limit.sql @@ -0,0 +1,23 @@ +-- Product presale labels, delivery promises and per-customer purchase limits. +-- This migration is intentionally idempotent and matches EnsureSchema. + +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS presale_type SMALLINT NOT NULL DEFAULT 0; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS delivery_time_type SMALLINT NOT NULL DEFAULT 0; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS delivery_start_at TIMESTAMPTZ; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS delivery_after_paid_days INTEGER; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS purchase_limit_quantity INTEGER NOT NULL DEFAULT 0; + +ALTER TABLE product.products DROP CONSTRAINT IF EXISTS chk_products_presale_configuration; +ALTER TABLE product.products ADD CONSTRAINT chk_products_presale_configuration CHECK ( + presale_type IN (0, 1, 2) + AND purchase_limit_quantity >= 0 + AND ( + (delivery_time_type = 0 AND delivery_start_at IS NULL AND delivery_after_paid_days IS NULL) + OR (delivery_time_type = 1 AND delivery_start_at IS NOT NULL AND delivery_after_paid_days IS NULL) + OR (delivery_time_type = 2 AND delivery_start_at IS NULL AND delivery_after_paid_days > 0) + ) +); + +CREATE INDEX IF NOT EXISTS idx_products_store_presale_created_id + ON product.products (store_id, presale_type, created_at DESC, id DESC) + WHERE deleted_at IS NULL; diff --git a/scripts/sql/02-product-schema.sql b/scripts/sql/02-product-schema.sql index e56f025..ceb6b43 100644 --- a/scripts/sql/02-product-schema.sql +++ b/scripts/sql/02-product-schema.sql @@ -35,6 +35,11 @@ CREATE TABLE IF NOT EXISTS product.products ( freight_template_id BIGINT, sale_time_type SMALLINT NOT NULL DEFAULT 1, scheduled_sale_time TIMESTAMPTZ, + presale_type SMALLINT NOT NULL DEFAULT 0, + delivery_time_type SMALLINT NOT NULL DEFAULT 0, + delivery_start_at TIMESTAMPTZ, + delivery_after_paid_days INTEGER, + purchase_limit_quantity INTEGER NOT NULL DEFAULT 0, version INTEGER NOT NULL DEFAULT 0, tenant_id BIGINT, store_id BIGINT, @@ -55,6 +60,16 @@ CREATE TABLE IF NOT EXISTS product.products ( CHECK (sale_time_type IN (1, 2)), CONSTRAINT chk_products_scheduled_sale_time_required CHECK (sale_time_type <> 2 OR scheduled_sale_time IS NOT NULL), + CONSTRAINT chk_products_presale_configuration + CHECK ( + presale_type IN (0, 1, 2) + AND purchase_limit_quantity >= 0 + AND ( + (delivery_time_type = 0 AND delivery_start_at IS NULL AND delivery_after_paid_days IS NULL) + OR (delivery_time_type = 1 AND delivery_start_at IS NOT NULL AND delivery_after_paid_days IS NULL) + OR (delivery_time_type = 2 AND delivery_start_at IS NULL AND delivery_after_paid_days > 0) + ) + ), CONSTRAINT chk_products_version CHECK (version >= 0) ); diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 142d9a8..71b78c7 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -58,6 +58,11 @@ CREATE TABLE IF NOT EXISTS product.products ( freight_template_id BIGINT, sale_time_type SMALLINT NOT NULL DEFAULT 1, scheduled_sale_time TIMESTAMPTZ, + presale_type SMALLINT NOT NULL DEFAULT 0, + delivery_time_type SMALLINT NOT NULL DEFAULT 0, + delivery_start_at TIMESTAMPTZ, + delivery_after_paid_days INTEGER, + purchase_limit_quantity INTEGER NOT NULL DEFAULT 0, version INTEGER NOT NULL DEFAULT 0, deleted_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), @@ -76,6 +81,16 @@ CREATE TABLE IF NOT EXISTS product.products ( CHECK (sale_time_type IN (1, 2)), CONSTRAINT chk_products_scheduled_sale_time_required CHECK (sale_time_type <> 2 OR scheduled_sale_time IS NOT NULL), + CONSTRAINT chk_products_presale_configuration + CHECK ( + presale_type IN (0, 1, 2) + AND purchase_limit_quantity >= 0 + AND ( + (delivery_time_type = 0 AND delivery_start_at IS NULL AND delivery_after_paid_days IS NULL) + OR (delivery_time_type = 1 AND delivery_start_at IS NOT NULL AND delivery_after_paid_days IS NULL) + OR (delivery_time_type = 2 AND delivery_start_at IS NULL AND delivery_after_paid_days > 0) + ) + ), CONSTRAINT chk_products_version CHECK (version >= 0) );