sync_chatLog_discover.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package jobs
  2. import (
  3. "context"
  4. "errors"
  5. "gadmin/config"
  6. "gadmin/internal/gorm/model"
  7. "gadmin/internal/gorm/query"
  8. "github.com/sirupsen/logrus"
  9. "gorm.io/gen"
  10. "gorm.io/gorm"
  11. "os"
  12. )
  13. // 处理客服聊天记录中accId和name为空的数据
  14. var SyncChatLogDiscover = new(JobSyncChatLogDiscover)
  15. type JobSyncChatLogDiscover struct{}
  16. func (j *JobSyncChatLogDiscover) Run() {
  17. if os.Getenv("ADMIN_PLATFORM") != "wechat" {
  18. logrus.Warn("客服聊天记录目前只有微信平台")
  19. return
  20. }
  21. logrus.Info("处理客服聊天记录数据...")
  22. var (
  23. ctx = context.Background()
  24. chatLogQuery = query.Use(config.DB).CustomerServiceChatLog
  25. chatLogModel = chatLogQuery.WithContext(ctx)
  26. )
  27. //获取聊天记录
  28. count, err := chatLogModel.Distinct(chatLogQuery.OpenID).Where(chatLogQuery.PlayerName.Eq("")).Count()
  29. if err != nil {
  30. logrus.Errorf("JobSyncChatLogDiscover 统计mysql客服记录失败:%s", err.Error())
  31. }
  32. if count == 0 {
  33. logrus.Info("客服聊天记录数据无需处理...")
  34. return
  35. }
  36. //处理数据
  37. results := make([]*model.CustomerServiceChatLog, 0)
  38. err = chatLogModel.Where(chatLogQuery.AccID.Eq(0)).Or(chatLogQuery.PlayerName.Eq("")).Group(chatLogQuery.OpenID).FindInBatches(&results, 500, func(tx gen.Dao, batch int) error {
  39. //查询account
  40. for _, item := range results {
  41. var account model.UserAccount
  42. err = config.LDB.WithContext(ctx).Scopes(model.UserAccountTableByKey(&model.UserAccount{}, item.OpenID)).Where("openid = ?", item.OpenID).First(&account).Error
  43. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  44. return err
  45. }
  46. if account.ID == 0 {
  47. logrus.Infof("用户不存在,openId:%s", item.OpenID)
  48. continue
  49. }
  50. //更新数据
  51. updates, err := chatLogModel.Where(chatLogQuery.OpenID.Eq(item.OpenID)).Updates(model.CustomerServiceChatLog{AccID: account.AccID, PlayerName: account.Nickname})
  52. if err != nil {
  53. return err
  54. }
  55. if updates.Error != nil {
  56. return updates.Error
  57. }
  58. }
  59. return nil
  60. })
  61. if err != nil {
  62. logrus.Errorf("JobSyncChatLogDiscover 处理mysql客服记录失败:%s", err.Error())
  63. return
  64. }
  65. logrus.Info("处理客服聊天记录数据完成...")
  66. }