handle duplicate company name

main
alex 2024-03-05 21:35:35 +01:00
parent ffbbd9e953
commit 553192f767
2 changed files with 38 additions and 3 deletions

View File

@ -17,7 +17,7 @@ type CrmCustomer struct {
LastContact time.Time
CreatedBy string
Notes string
Company string
Company string `gorm:"unique"`
ZipCode string
Address string
City string

View File

@ -10,8 +10,10 @@ import (
"git.ex.umbach.dev/Alex/roese-utils/rslogger"
"git.ex.umbach.dev/Alex/roese-utils/rspagination"
"github.com/go-sql-driver/mysql"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"gorm.io/gorm"
)
func GetCrmTypeCustomers(c *fiber.Ctx) error {
@ -169,6 +171,8 @@ func UpdateCrmCustomer(c *fiber.Ctx) error {
// description: No permissions
// '404':
// description: Crm customer not found
// '409':
// description: Crm customer with the company name already exists
// '500':
// description: Failed to update crm customer
@ -196,11 +200,15 @@ func UpdateCrmCustomer(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusBadRequest)
}
database.DB.Model(&structs.CrmCustomer{}).
result := database.DB.Model(&structs.CrmCustomer{}).
Where("id = ?", params.Id).
Select("*"). // update all fields (even if they are empty)
Updates(crmCustomer)
if err := handleError(result, c); err != nil {
return err
}
crmCustomer["Id"] = params.Id
socketclients.BroadcastMessageToTopicStartsWith(utils.SubscribedTopicCrm, structs.SendSocketMessage{
@ -234,6 +242,8 @@ func CreateCrmCustomer(c *fiber.Ctx) error {
// description: Invalid request query
// '401':
// description: No permissions
// '409':
// description: Crm customer with the company name already exists
// '500':
// description: Failed to create crm customer
@ -257,7 +267,11 @@ func CreateCrmCustomer(c *fiber.Ctx) error {
crmCustomer["DealPhase"] = 1
}
database.DB.Model(&structs.CrmCustomer{}).Create(&crmCustomer)
result := database.DB.Model(&structs.CrmCustomer{}).Create(&crmCustomer)
if err := handleError(result, c); err != nil {
return err
}
socketclients.BroadcastMessageToTopicStartsWith(utils.SubscribedTopicCrm,
structs.SendSocketMessage{
@ -269,3 +283,24 @@ func CreateCrmCustomer(c *fiber.Ctx) error {
return c.JSON(crmCustomer)
}
func handleError(result *gorm.DB, c *fiber.Ctx) error {
if result.Error != nil {
if mysqlErr, ok := result.Error.(*mysql.MySQLError); ok {
switch mysqlErr.Number {
case 1062:
logger.AddCrmLog(rslogger.LogTypeError, "Failed to create crm customer as company name already exists: %v", result.Error.Error())
return c.SendStatus(fiber.StatusConflict)
default:
logger.AddCrmLog(rslogger.LogTypeError, "Failed to create crm customer: %v", result.Error.Error())
return c.SendStatus(fiber.StatusInternalServerError)
}
}
logger.AddCrmLog(rslogger.LogTypeError, "Failed to create crm customer: %v", result.Error.Error())
return c.SendStatus(fiber.StatusInternalServerError)
}
return nil
}