diff --git a/CHANGELOG-server.md b/CHANGELOG-server.md index 3139d3c..300788f 100644 --- a/CHANGELOG-server.md +++ b/CHANGELOG-server.md @@ -5,6 +5,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.0.68] - 2026-06-21 + +### 修复 +- 根治商品编码可能重复的问题:自动编码改为按现有最大序号递增生成(不再复用已删除商品占用过的编号、并发下也不会撞号),并在数据库层为「同门店 + 编码」加唯一约束,从此重复编码无法静默产生 + ## [1.0.67] - 2026-06-20 ### 修复 diff --git a/backend/internal/handler/product.go b/backend/internal/handler/product.go index 4d86474..9f18ecc 100644 --- a/backend/internal/handler/product.go +++ b/backend/internal/handler/product.go @@ -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) diff --git a/backend/internal/handler/product_test.go b/backend/internal/handler/product_test.go index ea2704b..4e04df4 100644 --- a/backend/internal/handler/product_test.go +++ b/backend/internal/handler/product_test.go @@ -2,13 +2,16 @@ package handler import ( "encoding/json" + "errors" "fmt" "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gorm.io/gorm" + "github.com/wangjia/jiu/backend/internal/model" "github.com/wangjia/jiu/backend/testutil" ) @@ -199,3 +202,67 @@ func TestProductHandler_Create_ShopIDFromToken(t *testing.T) { dataBytes, _ := json.Marshal(data) _ = dataBytes } + +// 自动编码按最大序号递增:P001 → P002 → P003。 +func TestProductHandler_AutoCode_Increment(t *testing.T) { + db := testutil.SetupTestDB() + shop := testutil.CreateTestShop(db, "AC001") + user := testutil.CreateTestUser(db, shop.ID, "admin", "pass", "admin") + token := getAuthToken(user.ID, shop.ID, "admin") + r := setupProtectedRouter(db) + + var codes []string + for i := 0; i < 3; i++ { + w := makeRequest(r, "POST", "/api/v1/products", token, map[string]interface{}{ + "name": fmt.Sprintf("AutoP %d", i), "unit": "个", + }) + require.Equal(t, http.StatusCreated, w.Code) + data := parseResponse(w)["data"].(map[string]interface{}) + codes = append(codes, data["code"].(string)) + } + assert.Equal(t, []string{"P001", "P002", "P003"}, codes) +} + +// 软删商品后,新建不复用被删的号(旧 count+1 逻辑会复用 → 重复,此为根因修复回归测试)。 +func TestProductHandler_AutoCode_NoReuseAfterSoftDelete(t *testing.T) { + db := testutil.SetupTestDB() + shop := testutil.CreateTestShop(db, "AC002") + user := testutil.CreateTestUser(db, shop.ID, "admin", "pass", "admin") + token := getAuthToken(user.ID, shop.ID, "admin") + r := setupProtectedRouter(db) + + var lastID uint64 + for i := 0; i < 3; i++ { // P001 P002 P003 + w := makeRequest(r, "POST", "/api/v1/products", token, map[string]interface{}{ + "name": fmt.Sprintf("NR %d", i), "unit": "个", + }) + require.Equal(t, http.StatusCreated, w.Code) + lastID = extractID(w) + } + // 软删 P003 + w := makeRequest(r, "DELETE", fmt.Sprintf("/api/v1/products/%d", lastID), token, nil) + require.Equal(t, http.StatusOK, w.Code) + + // 再建 → 必须是 P004,不能复用已软删的 P003 + w = makeRequest(r, "POST", "/api/v1/products", token, map[string]interface{}{ + "name": "NR new", "unit": "个", + }) + require.Equal(t, http.StatusCreated, w.Code) + data := parseResponse(w)["data"].(map[string]interface{}) + assert.Equal(t, "P004", data["code"]) +} + +// (shop_id, code) 唯一约束生效,且重复被翻译成 gorm.ErrDuplicatedKey(Create/FindOrCreate 重试的前提)。 +func TestProductHandler_UniqueShopCode(t *testing.T) { + db := testutil.SetupTestDB() + shop := testutil.CreateTestShop(db, "UQ001") + require.NoError(t, db.Exec("CREATE UNIQUE INDEX uk_shop_code ON products(shop_id, code)").Error) + + p1 := model.Product{TenantBase: model.TenantBase{ShopID: shop.ID}, Name: "A", Code: "P001"} + require.NoError(t, db.Create(&p1).Error) + + p2 := model.Product{TenantBase: model.TenantBase{ShopID: shop.ID}, Name: "B", Code: "P001"} + err := db.Create(&p2).Error + require.Error(t, err) + assert.True(t, errors.Is(err, gorm.ErrDuplicatedKey)) +} diff --git a/backend/internal/model/product.go b/backend/internal/model/product.go index 7599695..cbf4a26 100644 --- a/backend/internal/model/product.go +++ b/backend/internal/model/product.go @@ -10,6 +10,8 @@ type ProductCategory struct { type Product struct { TenantBase PublicID string `gorm:"size:36;uniqueIndex" json:"public_id"` + // Code 商品编码:同店内唯一。(shop_id, code) 联合唯一索引 uk_shop_code 由 autoMigrate 显式建(见 main.go), + // 不在此用 tag 声明——ShopID 在共用 TenantBase 上,tag 只能建单列索引会破坏多租户隔离。 Code string `gorm:"size:50" json:"code"` Barcode string `gorm:"size:100" json:"barcode"` Name string `gorm:"size:200;not null" json:"name"` diff --git a/backend/main.go b/backend/main.go index 8b29f51..04f52fb 100644 --- a/backend/main.go +++ b/backend/main.go @@ -87,7 +87,8 @@ func initDB() *gorm.DB { } db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ - Logger: logger.Default.LogMode(logLevel), + Logger: logger.Default.LogMode(logLevel), + TranslateError: true, // 把 MySQL 1062 翻译成 gorm.ErrDuplicatedKey,供编码撞唯一约束时重试 }) if err != nil { log.Fatalf("failed to connect database: %v", err) @@ -136,5 +137,12 @@ func autoMigrate(db *gorm.DB) { if err != nil { log.Fatalf("auto migrate failed: %v", err) } + // products(shop_id, code) 联合唯一索引:ShopID 在共用 TenantBase 上无法用 struct tag 表达, + // 故在此幂等显式建(保证同店内商品编码唯一,DB 层兜底防止重复编码静默落库)。 + if !db.Migrator().HasIndex(&model.Product{}, "uk_shop_code") { + if err := db.Exec("CREATE UNIQUE INDEX uk_shop_code ON products (shop_id, code)").Error; err != nil { + log.Fatalf("create unique index uk_shop_code failed: %v", err) + } + } log.Println("AutoMigrate completed") } diff --git a/backend/testutil/setup.go b/backend/testutil/setup.go index 9aceae5..abd562e 100644 --- a/backend/testutil/setup.go +++ b/backend/testutil/setup.go @@ -46,7 +46,8 @@ func SetupTestDB() *gorm.DB { InitConfig() db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{ - Logger: logger.Default.LogMode(logger.Silent), + Logger: logger.Default.LogMode(logger.Silent), + TranslateError: true, }) if err != nil { panic(fmt.Sprintf("failed to open sqlite: %v", err))