fix(backend): 商品编码改用最大序号生成不复用软删号 + 加 (shop_id,code) 唯一约束,根治重复编码
Deploy Server / release-deploy-server (push) Successful in 53s
Deploy Server / release-deploy-server (push) Successful in 53s
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YZ4DskSRKsSiheQonFtQvx
This commit is contained in:
@@ -62,6 +62,29 @@ func (h *ProductHandler) List(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// nextProductCode 生成该门店下一个自动商品编码(P001、P002…)。
|
||||
// 取现有 P 开头编码的最大数字序号 +1,**含软删行**(deleted_at 非空也计入,不复用已删商品占用过的号)。
|
||||
// 不加行锁——并发下两请求可能算出同号,由 uk_shop_code 唯一约束 + 调用方 ErrDuplicatedKey 重试兜底。
|
||||
// 用 GORM 表达式(非 MySQL 方言 SQL),sqlite 单测也能跑。
|
||||
func nextProductCode(tx *gorm.DB, shopID uint64) (string, error) {
|
||||
var codes []string
|
||||
if err := tx.Model(&model.Product{}).
|
||||
Where("shop_id = ? AND code LIKE 'P%'", shopID).
|
||||
Pluck("code", &codes).Error; err != nil {
|
||||
return "", err
|
||||
}
|
||||
maxN := 0
|
||||
for _, c := range codes {
|
||||
if len(c) < 2 {
|
||||
continue
|
||||
}
|
||||
if n, err := strconv.Atoi(c[1:]); err == nil && n > maxN {
|
||||
maxN = n
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("P%03d", maxN+1), nil
|
||||
}
|
||||
|
||||
// Create POST /api/v1/products
|
||||
func (h *ProductHandler) Create(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
@@ -74,31 +97,24 @@ func (h *ProductHandler) Create(c *gin.Context) {
|
||||
product.PublicID = uuid.New().String()
|
||||
product.NamePinyin, product.NameInitials = util.ToPinyin(product.Name)
|
||||
|
||||
// Auto-generate product code if not provided (e.g. P001, P002)
|
||||
// Retry up to 5 times on duplicate key to handle concurrent creates
|
||||
if product.Code == "" {
|
||||
var count int64
|
||||
h.db.Model(&model.Product{}).
|
||||
Where("shop_id = ? AND deleted_at IS NULL", shopID).
|
||||
Count(&count)
|
||||
product.Code = fmt.Sprintf("P%03d", count+1)
|
||||
}
|
||||
|
||||
// 未显式指定编码时自动生成(事务内 max+1);撞 uk_shop_code 唯一约束则重算下一号重试(应对并发)。
|
||||
autoCode := product.Code == ""
|
||||
var createErr error
|
||||
for attempt := 0; attempt < 5; attempt++ {
|
||||
if createErr = h.db.Create(&product).Error; createErr == nil {
|
||||
createErr = h.db.Transaction(func(tx *gorm.DB) error {
|
||||
if autoCode {
|
||||
code, err := nextProductCode(tx, shopID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
product.Code = code
|
||||
}
|
||||
product.ID = 0
|
||||
return tx.Create(&product).Error
|
||||
})
|
||||
if createErr == nil || !autoCode || !errors.Is(createErr, gorm.ErrDuplicatedKey) {
|
||||
break
|
||||
}
|
||||
if !errors.Is(createErr, gorm.ErrDuplicatedKey) {
|
||||
break
|
||||
}
|
||||
// Duplicate code: try next slot
|
||||
var count int64
|
||||
h.db.Model(&model.Product{}).
|
||||
Where("shop_id = ? AND deleted_at IS NULL", shopID).
|
||||
Count(&count)
|
||||
product.ID = 0
|
||||
product.Code = fmt.Sprintf("P%03d", count+int64(attempt)+2)
|
||||
}
|
||||
if createErr != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": createErr.Error()})
|
||||
@@ -256,25 +272,37 @@ func (h *ProductHandler) FindOrCreate(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var count int64
|
||||
h.db.Model(&model.Product{}).Where("shop_id = ? AND deleted_at IS NULL", shopID).Count(&count)
|
||||
namePinyin, nameInitials := util.ToPinyin(req.Name)
|
||||
product = model.Product{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
PublicID: uuid.New().String(),
|
||||
Name: req.Name,
|
||||
Series: req.Series,
|
||||
Spec: req.Spec,
|
||||
Code: fmt.Sprintf("P%03d", count+1),
|
||||
NamePinyin: namePinyin,
|
||||
NameInitials: nameInitials,
|
||||
OriginID: req.OriginID,
|
||||
ShelfLifeID: req.ShelfLifeID,
|
||||
StorageID: req.StorageID,
|
||||
DescriptionDocID: req.DescriptionDocID,
|
||||
// 事务内 max+1 生成编码;撞 uk_shop_code 唯一约束则重算下一号重试(应对并发)。
|
||||
var createErr error
|
||||
for attempt := 0; attempt < 5; attempt++ {
|
||||
createErr = h.db.Transaction(func(tx *gorm.DB) error {
|
||||
code, err := nextProductCode(tx, shopID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
product = model.Product{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
PublicID: uuid.New().String(),
|
||||
Name: req.Name,
|
||||
Series: req.Series,
|
||||
Spec: req.Spec,
|
||||
Code: code,
|
||||
NamePinyin: namePinyin,
|
||||
NameInitials: nameInitials,
|
||||
OriginID: req.OriginID,
|
||||
ShelfLifeID: req.ShelfLifeID,
|
||||
StorageID: req.StorageID,
|
||||
DescriptionDocID: req.DescriptionDocID,
|
||||
}
|
||||
return tx.Create(&product).Error
|
||||
})
|
||||
if createErr == nil || !errors.Is(createErr, gorm.ErrDuplicatedKey) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if createErr := h.db.Create(&product).Error; createErr != nil {
|
||||
// Race condition: try to find the record created by another request
|
||||
if createErr != nil {
|
||||
// Race condition: 并发可能已按同 name/series/spec 建好,回查返回既有
|
||||
if h.db.Where("shop_id = ? AND name = ? AND series = ? AND spec = ? AND deleted_at IS NULL",
|
||||
shopID, req.Name, req.Series, req.Spec).First(&product).Error == nil {
|
||||
util.RespondSuccess(c, product)
|
||||
|
||||
Reference in New Issue
Block a user