sms_service.go 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. package sms_service
  2. import (
  3. "SCRM/models"
  4. base "SCRM/service"
  5. "SCRM/utils"
  6. "errors"
  7. "fmt"
  8. "math"
  9. "strings"
  10. "time"
  11. "github.com/astaxie/beego"
  12. "github.com/jinzhu/gorm"
  13. )
  14. // 发送验证码短信
  15. func SMSSendVerificationCode(mobile string) (string, error) {
  16. if len(mobile) == 0 {
  17. return "", errors.New("手机号为空")
  18. }
  19. code_str := utils.RandomNumberString(6)
  20. templateID, _ := beego.AppConfig.Int("sms_verification_code_templateid")
  21. _, _, _, err := singleSendMessageUseUCPaas(templateID, []string{code_str}, mobile)
  22. return code_str, err
  23. }
  24. // 成为机构管理员的邀请短信
  25. func SMSSendInviteMobileToJoinOrgAdmin(name string, mobile string, password string) error {
  26. if len(mobile) == 0 {
  27. return errors.New("手机号为空")
  28. }
  29. if len(password) == 0 {
  30. _, _, _, err := singleSendMessageUseUCPaas(332784, []string{name, mobile}, mobile)
  31. return err
  32. } else {
  33. _, _, _, err := singleSendMessageUseUCPaas(332783, []string{name, mobile, password}, mobile)
  34. return err
  35. }
  36. }
  37. var (
  38. SMSErrorFreeLimitInsufficient = errors.New("短信额度不足")
  39. )
  40. // 发送自定义内容短信,content 不需要包括签名及“退订请回复TD”字样
  41. /* 流程说明:
  42. 检查额度 -> 创建短信平台模板 -> 创建数据库短信模板(待审核状态) -> 创建发送批次(待审核状态) -> 扣除额度 -> finish
  43. */
  44. func SMSOrgSendWithCustomContent(orgID int64, originContent string, mobiles []string) error {
  45. if len(mobiles) == 0 {
  46. return nil
  47. }
  48. autograph := "酷医聚客"
  49. content := fmt.Sprintf("%v退订请回复TD", originContent)
  50. fullContent := fmt.Sprintf("【%v】%v", autograph, content)
  51. if len(fullContent) > 500 {
  52. return errors.New("短信太长")
  53. }
  54. willConsumeLimit := GetWillConsumeLimit(fullContent, len(mobiles))
  55. freeLimit, getFreeLimitErr := GetUserSMSFreeLimit(orgID, time.Now())
  56. if getFreeLimitErr != nil {
  57. return getFreeLimitErr
  58. }
  59. if willConsumeLimit+freeLimit.UsedCount > freeLimit.TotalCount {
  60. return SMSErrorFreeLimitInsufficient
  61. }
  62. smsTplID, createSMSTplErr := createTemplate2UCPaas(autograph, content, 5)
  63. if createSMSTplErr != nil {
  64. return createSMSTplErr
  65. }
  66. template := models.SMSTemplate{
  67. TemplateType: 2,
  68. TemplateID: int64(smsTplID),
  69. MessageType: 2,
  70. Content: content,
  71. Autograph: autograph,
  72. OrgID: orgID,
  73. Status: 2,
  74. CreateTime: time.Now().Unix(),
  75. ModifyTime: time.Now().Unix(),
  76. }
  77. tx := base.PatientWriteDB().Begin()
  78. if createTplErr := tx.Save(&template).Error; createTplErr != nil {
  79. tx.Rollback()
  80. return createTplErr
  81. }
  82. sendTime := time.Now()
  83. batch := &models.SMSBatch{
  84. OrgID: orgID,
  85. Autograph: autograph,
  86. FullContent: fullContent,
  87. Mobiles: strings.Join(mobiles, ","),
  88. TemplateID: int64(smsTplID),
  89. SendTime: sendTime.Unix(),
  90. Status: models.SMSBatchStatusInReview,
  91. CreateTime: time.Now().Unix(),
  92. ModifyTime: time.Now().Unix(),
  93. }
  94. if createBatchErr := tx.Save(batch).Error; createBatchErr != nil {
  95. tx.Rollback()
  96. return createBatchErr
  97. }
  98. freeLimit.UsedCount += willConsumeLimit
  99. freeLimit.ModifyTime = time.Now().Unix()
  100. updateLimitErr := tx.Save(freeLimit).Error
  101. if updateLimitErr != nil {
  102. tx.Rollback()
  103. return updateLimitErr
  104. }
  105. tx.Commit()
  106. return nil
  107. }
  108. // 计算即将消耗的额度 (smsFullContent 包含签名在内)
  109. func GetWillConsumeLimit(smsFullContent string, mobileCount int) int {
  110. limitEachMessage := math.Ceil(float64(len(smsFullContent)) / 67.0)
  111. return int(limitEachMessage) * mobileCount
  112. }
  113. // 短信平台模板审核成功
  114. /* 流程说明
  115. 更新数据库模板状态(有效) -> 更新对应发送批次状态(待发送) -> finish
  116. */
  117. func SMSUCPaasTemplateApproved(templateID int64) error {
  118. tx := base.PatientWriteDB().Begin()
  119. updateTplErr := tx.Model(&models.SMSTemplate{}).Where("template_id = ?", templateID).Updates(map[string]interface{}{
  120. "status": 1,
  121. "mtime": time.Now().Unix(),
  122. }).Error
  123. if updateTplErr != nil {
  124. tx.Rollback()
  125. return updateTplErr
  126. }
  127. updateBatchErr := tx.Model(&models.SMSBatch{}).Where("sms_template_id = ?", templateID).Updates(map[string]interface{}{
  128. "status": models.SMSBatchStatusUnsend,
  129. "mtime": time.Now().Unix(),
  130. }).Error
  131. if updateBatchErr != nil {
  132. tx.Rollback()
  133. return updateBatchErr
  134. }
  135. tx.Commit()
  136. return nil
  137. }
  138. // 短信平台模板审核失败
  139. /* 流程说明
  140. 更新数据库模板状态(无效) -> 更新对应发送批次状态(审核未通过) -> 返回发送当月的额度 -> finish
  141. */
  142. func SMSUCPaasTemplateUnapproved(templateID int64) error {
  143. var batch models.SMSBatch
  144. getBatchErr := base.PatientReadDB().Model(&models.SMSBatch{}).Where("sms_template_id = ?", templateID).First(&batch).Error
  145. if getBatchErr != nil {
  146. if getBatchErr != gorm.ErrRecordNotFound {
  147. return getBatchErr
  148. }
  149. }
  150. tx := base.PatientWriteDB().Begin()
  151. updateTplErr := tx.Model(&models.SMSTemplate{}).Where("template_id = ?", templateID).Updates(map[string]interface{}{
  152. "status": 0,
  153. "mtime": time.Now().Unix(),
  154. }).Error
  155. if updateTplErr != nil {
  156. tx.Rollback()
  157. return updateTplErr
  158. }
  159. if batch.ID > 0 {
  160. batch.Status = models.SMSBatchStatusUnapproved
  161. batch.ModifyTime = time.Now().Unix()
  162. updateBatchErr := tx.Save(&batch).Error
  163. if updateBatchErr != nil {
  164. tx.Rollback()
  165. return updateBatchErr
  166. }
  167. freeLimit, getFreeLimitErr := GetUserSMSFreeLimit(batch.OrgID, time.Unix(batch.SendTime, 0))
  168. if getFreeLimitErr != nil {
  169. tx.Rollback()
  170. return getFreeLimitErr
  171. }
  172. mobiles := strings.Split(batch.Mobiles, ",")
  173. consumedLimit := GetWillConsumeLimit(batch.FullContent, len(mobiles))
  174. freeLimit.UsedCount -= consumedLimit
  175. freeLimit.ModifyTime = time.Now().Unix()
  176. updateFreeLimitErr := tx.Save(freeLimit).Error
  177. if updateFreeLimitErr != nil {
  178. tx.Rollback()
  179. return updateFreeLimitErr
  180. }
  181. }
  182. tx.Commit()
  183. return nil
  184. }
  185. // 发送“未发送”批次的短信
  186. // 备注:因短信平台每次群发限制 100 个号码,所以同一个批次可能需要分成多次发送
  187. func SMSSendUnsendBatchRealTime() {
  188. batchs, getBatchErr := GetUnsendSMSBatch()
  189. if getBatchErr != nil {
  190. return
  191. }
  192. for _, batch := range batchs {
  193. tx := base.PatientWriteDB().Begin()
  194. isSendSuccess := false
  195. failMobileCount := 0
  196. reports := []interface{}{}
  197. mobiles := strings.Split(batch.Mobiles, ",")
  198. subbatchCount := int(math.Ceil(float64(len(mobiles)) / 100.0))
  199. for index := 0; index < subbatchCount; index++ {
  200. var subMobiles []string
  201. if len(mobiles)-index*100 >= 100 {
  202. subMobiles = mobiles[index*100 : 100]
  203. } else {
  204. subMobiles = mobiles[index*100:]
  205. }
  206. sendCount, report, sendErr := batchSendMessageUseUCPaas(int(batch.TemplateID), nil, subMobiles)
  207. if sendErr != nil {
  208. utils.ErrorLog("%v", sendErr)
  209. failMobileCount += len(subMobiles)
  210. } else {
  211. isSendSuccess = true // 只要子批次有一次发送成功,就认为这个批次发送成功
  212. reports = append(reports, report)
  213. failMobileCount += len(subMobiles) - sendCount
  214. }
  215. }
  216. if isSendSuccess {
  217. batch.Status = models.SMSBatchStatusDidSend
  218. batch.ModifyTime = time.Now().Unix()
  219. updateBatchErr := tx.Save(batch).Error
  220. if updateBatchErr != nil {
  221. utils.ErrorLog("群发短信成功后 更新批次状态失败:%v", updateBatchErr)
  222. tx.Rollback()
  223. continue
  224. }
  225. valueStrs := make([]string, 0, len(reports))
  226. values := make([]interface{}, 0, len(reports))
  227. for _, item := range reports {
  228. json := item.(map[string]interface{})
  229. valueStrs = append(valueStrs, "(?, ?, ?, ?, ?, ?, ?)")
  230. values = append(values, batch.ID)
  231. values = append(values, json["mobile"])
  232. if json["code"].(string) == "000000" {
  233. values = append(values, 1)
  234. } else {
  235. values = append(values, 0)
  236. }
  237. values = append(values, json["code"])
  238. values = append(values, json["msg"])
  239. values = append(values, time.Now().Unix())
  240. values = append(values, time.Now().Unix())
  241. }
  242. sql := fmt.Sprintf("INSERT INTO sgj_patient_sms_send_status (batch_id, mobile, status, code, msg, ctime, mtime) VALUES %v;", strings.Join(valueStrs, ", "))
  243. if insertReportErr := tx.Exec(sql, values...).Error; insertReportErr != nil {
  244. utils.ErrorLog("群发短信成功后 插入短信发送状态失败: %v", insertReportErr)
  245. tx.Rollback()
  246. continue
  247. }
  248. if failMobileCount > 0 {
  249. freeLimit, getFreeLimitErr := GetUserSMSFreeLimit(batch.OrgID, time.Unix(batch.SendTime, 0))
  250. if getFreeLimitErr == nil {
  251. freeLimit.UsedCount -= GetWillConsumeLimit(batch.FullContent, failMobileCount)
  252. freeLimit.ModifyTime = time.Now().Unix()
  253. updateLimitErr := tx.Save(freeLimit).Error
  254. if updateLimitErr != nil {
  255. utils.ErrorLog("群发短信成功后 返回额度失败: %v", updateLimitErr)
  256. tx.Rollback()
  257. continue
  258. }
  259. }
  260. }
  261. tx.Commit()
  262. } else {
  263. batch.Status = models.SMSBatchStatusSendFailed
  264. batch.ModifyTime = time.Now().Unix()
  265. updateBatchErr := tx.Save(batch).Error
  266. if updateBatchErr != nil {
  267. utils.ErrorLog("群发短信成功后 更新批次状态失败:%v", updateBatchErr)
  268. tx.Rollback()
  269. continue
  270. }
  271. freeLimit, getFreeLimitErr := GetUserSMSFreeLimit(batch.OrgID, time.Unix(batch.SendTime, 0))
  272. if getFreeLimitErr == nil {
  273. freeLimit.UsedCount -= GetWillConsumeLimit(batch.FullContent, len(mobiles))
  274. freeLimit.ModifyTime = time.Now().Unix()
  275. updateLimitErr := tx.Save(freeLimit).Error
  276. if updateLimitErr != nil {
  277. utils.ErrorLog("群发短信成功后 返回额度失败: %v", updateLimitErr)
  278. tx.Rollback()
  279. continue
  280. }
  281. }
  282. tx.Commit()
  283. }
  284. }
  285. }