Mhamdans17 commited on
Commit
59cc420
·
1 Parent(s): aff35bf

fix: normalize empty string SKU to nil/NULL to prevent unique key constraint violations on duplicate empty SKUs

Browse files
Files changed (1) hide show
  1. controllers/product_controller.go +19 -7
controllers/product_controller.go CHANGED
@@ -374,6 +374,10 @@ func CreateProduct(c *gin.Context) {
374
  return
375
  }
376
 
 
 
 
 
377
  // Verifikasi SKU jika diisi
378
  if req.SKU != nil && *req.SKU != "" {
379
  var count int64
@@ -424,6 +428,10 @@ func UpdateProduct(c *gin.Context) {
424
  return
425
  }
426
 
 
 
 
 
427
  var product models.Product
428
  if err := config.DB.Where("id = ? AND company_id = ?", productID, *user.CompanyID).First(&product).Error; err != nil {
429
  c.JSON(http.StatusNotFound, gin.H{"detail": "Produk tidak ditemukan"})
@@ -431,14 +439,18 @@ func UpdateProduct(c *gin.Context) {
431
  }
432
 
433
  // Verifikasi SKU jika berubah
434
- if req.SKU != nil && *req.SKU != "" && (product.SKU == nil || *product.SKU != *req.SKU) {
435
- var count int64
436
- config.DB.Model(&models.Product{}).Where("sku = ? AND id != ?", *req.SKU, productID).Count(&count)
437
- if count > 0 {
438
- c.JSON(http.StatusBadRequest, gin.H{"detail": fmt.Sprintf("Produk dengan SKU '%s' sudah ada", *req.SKU)})
439
- return
 
 
 
440
  }
441
- product.SKU = req.SKU
 
442
  }
443
 
444
  product.Name = req.Name
 
374
  return
375
  }
376
 
377
+ if req.SKU != nil && *req.SKU == "" {
378
+ req.SKU = nil
379
+ }
380
+
381
  // Verifikasi SKU jika diisi
382
  if req.SKU != nil && *req.SKU != "" {
383
  var count int64
 
428
  return
429
  }
430
 
431
+ if req.SKU != nil && *req.SKU == "" {
432
+ req.SKU = nil
433
+ }
434
+
435
  var product models.Product
436
  if err := config.DB.Where("id = ? AND company_id = ?", productID, *user.CompanyID).First(&product).Error; err != nil {
437
  c.JSON(http.StatusNotFound, gin.H{"detail": "Produk tidak ditemukan"})
 
439
  }
440
 
441
  // Verifikasi SKU jika berubah
442
+ if req.SKU != nil && *req.SKU != "" {
443
+ if product.SKU == nil || *product.SKU != *req.SKU {
444
+ var count int64
445
+ config.DB.Model(&models.Product{}).Where("sku = ? AND id != ?", *req.SKU, productID).Count(&count)
446
+ if count > 0 {
447
+ c.JSON(http.StatusBadRequest, gin.H{"detail": fmt.Sprintf("Produk dengan SKU '%s' sudah ada", *req.SKU)})
448
+ return
449
+ }
450
+ product.SKU = req.SKU
451
  }
452
+ } else {
453
+ product.SKU = nil
454
  }
455
 
456
  product.Name = req.Name