sms_service.go 9.4KB

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