zhangqian
2023-11-01 530fed8ec225453572d57b15c200ab062c335457
service/client.go
@@ -4,6 +4,7 @@
   "aps_crm/model"
   "aps_crm/pkg/ecode"
   "aps_crm/pkg/mysqlx"
   "gorm.io/gorm"
)
type ClientService struct{}
@@ -43,7 +44,7 @@
   return ecode.OK
}
func (ClientService) UpdateClient(client *model.Client) int {
func (ClientService) UpdateClient(client *model.Client, conId int) int {
   // check client exist
   errCode := CheckClientExist(client.Id)
   if errCode != ecode.OK {
@@ -51,9 +52,44 @@
   }
   // update client
   err := model.NewClientSearch(nil).SetId(client.Id).Update(client)
   if err != nil {
      return ecode.ClientUpdateErr
   if len(client.Contacts) == 0 {
      err := model.NewClientSearch(nil).SetId(client.Id).Update(client)
      if err != nil {
         return ecode.ClientUpdateErr
      }
   } else {
      tx := mysqlx.GetDB().Begin()
      err := model.NewClientSearch(tx).SetId(client.Id).Update(client)
      if err != nil {
         tx.Rollback()
         return ecode.ClientUpdateErr
      }
      for _, contact := range client.Contacts {
         contact.ClientId = client.Id
         // check isFirst
         errCode = setFirstContact(tx, &contact)
         if errCode != ecode.OK {
            return errCode
         }
         if conId == 0 {
            err = model.NewContactSearch(tx).Create(&contact)
            if err != nil {
               tx.Rollback()
               return ecode.ClientUpdateErr
            }
         } else {
            contact.Id = conId
            err = model.NewContactSearch(tx).SetId(contact.Id).Update(&contact)
            if err != nil {
               tx.Rollback()
               return ecode.ClientUpdateErr
            }
         }
      }
      tx.Commit()
   }
   return ecode.OK
@@ -94,3 +130,13 @@
   }
   return ecode.OK
}
func (ClientService) CheckName(name string) int {
   // check client exist
   _, err := model.NewClientSearch(nil).SetName(name).First()
   if err != gorm.ErrRecordNotFound {
      return ecode.ClientExist
   }
   return ecode.OK
}