lotteryDrawTask.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. package activity
  2. import (
  3. "app.yhyue.com/moapp/jybase/common"
  4. "app.yhyue.com/moapp/jybase/date"
  5. "app.yhyue.com/moapp/jybase/encrypt"
  6. "app.yhyue.com/moapp/jybase/go-logger/logger"
  7. "app.yhyue.com/moapp/jybase/redis"
  8. "app.yhyue.com/moapp/message/db"
  9. "app.yhyue.com/moapp/message/model"
  10. "app.yhyue.com/moapp/message/util"
  11. "encoding/json"
  12. "fmt"
  13. "github.com/gogf/gf/v2/frame/g"
  14. "github.com/gogf/gf/v2/os/gctx"
  15. "regexp"
  16. "strconv"
  17. "time"
  18. )
  19. const (
  20. //表
  21. tableTaskInfo = "jyactivities.lottery_task_info"
  22. tableTaskUser = "jyactivities.lottery_task_user"
  23. tableActivityInfo = "jyactivities.activity_info"
  24. )
  25. // 任务信息
  26. type TaskInfo struct {
  27. Id int64 `json:"id"`
  28. Name string `json:"name"`
  29. ActiveId int64 `json:"active_id"` //活动id
  30. Qualification int `json:"qualification"` //获取抽奖资格次数;
  31. CycleNum int `json:"cycle_num"` //任务周期(每天/每周/每月/活动周期) 可执行任务次数:n次;-1:不限制
  32. CycleUnit int `json:"cycle_unit"` //默认0:当天;;1:当周;2:当月;3:活动周期
  33. ActivityStartTime string `json:"start_time"` //活动开始时间
  34. ActivityEndTime string `json:"end_time"` //活动结束时间
  35. ActivityName string `json:"activity_name"` //活动名称
  36. }
  37. // 信息主题
  38. type MsgBody struct {
  39. Phone string `json:"phone"`
  40. UserId string `json:"userId"`
  41. MgoUserId string `json:"mgoUserId"`
  42. PositionId int64 `json:"positionId"`
  43. ActiveId int64 `json:"activeId"`
  44. TaskInfoId int64 `json:"taskInfoId"`
  45. OrderCode string `json:"orderCode"`
  46. NickName string `json:"nickName"`
  47. State int `json:"state"` //购买超级订阅和大会员 0:购买;1:续费;2:升级
  48. }
  49. // LotteryDrawTask 抽奖任务
  50. func LotteryDrawTask(msg *model.Message) {
  51. var msgBody MsgBody
  52. if msg.E_body != nil {
  53. b, err := json.Marshal(msg.E_body)
  54. if err == nil {
  55. err = json.Unmarshal(b, &msgBody)
  56. }
  57. if err != nil {
  58. logger.Info(fmt.Sprintf("任务完成参数信息有误:%s,err:%s", msg.E_userId, err.Error()))
  59. return
  60. }
  61. }
  62. if msgBody.MgoUserId == "" {
  63. logger.Info(fmt.Sprintf("用户mgo user id 参数信息有误:%v ,userId:%s", msgBody, msg.E_userId))
  64. return
  65. }
  66. //判断用户是否存在
  67. data, ok := db.Mgo.FindById("user", msgBody.MgoUserId, `{"l_registedate":1,"s_phone":1,"s_m_phone":1}`)
  68. if data == nil || len(*data) == 0 || !ok {
  69. logger.Info(fmt.Sprintf("未找到用户:%s, 任务id:%d。", msg.E_userId, msgBody.TaskInfoId))
  70. return
  71. }
  72. //任务信息
  73. taskInfos := db.Mysql.SelectBySql(fmt.Sprintf("SELECT lti.*,ai.start_time,ai.end_time,ai.name AS activity_name FROM %s lti LEFT JOIN %s ai ON lti.active_id = ai.id WHERE lti.active_id = ? AND lti.id = ? AND ai.start_time < NOW() AND ai.end_time >= NOW() ORDER BY lti.create_date DESC", tableTaskInfo, tableActivityInfo), msgBody.ActiveId, msgBody.TaskInfoId)
  74. if taskInfos == nil || len(*taskInfos) == 0 {
  75. logger.Info(fmt.Sprintf("没有当前需要完成的任务信息:%v", msgBody))
  76. return
  77. }
  78. //任务信息
  79. var taskInfo TaskInfo
  80. b, err := json.Marshal((*taskInfos)[0])
  81. if err == nil {
  82. err = json.Unmarshal(b, &taskInfo)
  83. }
  84. if err != nil {
  85. logger.Info(fmt.Sprintf("任务信息异常:%v,err:%s", msgBody, err.Error()))
  86. return
  87. }
  88. var (
  89. now = time.Now()
  90. timeRange = util.TimeRange{}
  91. emdTime, _ = time.ParseInLocation(date.Date_Full_Layout, taskInfo.ActivityEndTime, time.Local)
  92. )
  93. //判断任务有效期内,此次任务是否已完成
  94. switch taskInfo.CycleUnit {
  95. case 1: //当周
  96. timeRange = util.GetWeekRange(now)
  97. case 2: //当月
  98. timeRange = util.GetMonthRange(now)
  99. case 3: //活动周期
  100. startTime, _ := time.ParseInLocation(date.Date_Full_Layout, taskInfo.ActivityStartTime, time.Local)
  101. timeRange = util.TimeRange{
  102. StartTime: startTime,
  103. EndTime: emdTime,
  104. StartUnix: startTime.Unix(),
  105. EndUnix: emdTime.Unix(),
  106. }
  107. default: //当天
  108. timeRange = util.GetDayRange(now)
  109. }
  110. //当前周期内 是否已完成任务
  111. if taskInfo.CycleNum > 0 {
  112. tasks := db.Mysql.SelectBySql(fmt.Sprintf(`SELECT ltu.create_date FROM %s ltu WHERE ltu.active_id = ? AND ltu.task_id = ? AND ltu.position_id = ? AND ltu.create_date < ? AND ltu.create_date > ? `, tableTaskUser), msgBody.ActiveId, taskInfo.Id, msgBody.PositionId, timeRange.EndTime.Format(date.Date_Full_Layout), timeRange.StartTime.Format(date.Date_Full_Layout))
  113. if tasks != nil && taskInfo.CycleNum <= len(*tasks) {
  114. createDate := common.InterfaceToStr((*tasks)[0]["create_date"])
  115. logger.Info(fmt.Sprintf("用户:%s ,此任务:%s ,在 %s 已完成", msgBody.Phone, taskInfo.Name, createDate))
  116. return
  117. }
  118. } else if msgBody.OrderCode != "" {
  119. tasks := db.Mysql.SelectBySql(fmt.Sprintf(`SELECT ltu.create_date FROM %s ltu WHERE ltu.active_id = ? AND ltu.position_id = ? AND ltu.order_code = ?`, tableTaskUser), taskInfo.ActiveId, msgBody.PositionId, msgBody.OrderCode)
  120. //TODO 判重 担心订单有更新
  121. if tasks != nil && len(*tasks) > 0 {
  122. createDate := common.InterfaceToStr((*tasks)[0]["create_date"])
  123. logger.Info(fmt.Sprintf("用户:%s ,此订单:%s ,在 %s 已新增抽奖机会", msgBody.Phone, msgBody.OrderCode, createDate))
  124. return
  125. }
  126. }
  127. //二次验证
  128. switch taskInfo.Id {
  129. case 1: //签到赠送剑鱼币任务
  130. case 2: //设置关键词任务
  131. var hasKeys bool
  132. //查看当前用户是否有订阅词
  133. res := db.Compatible.Select(msgBody.UserId, `{"o_vipjy":1,"i_vip_status":1,"o_member_jy":1,"i_member_status":1,"o_jy":"1"}`)
  134. if res != nil && len(*res) > 0 {
  135. vipStatus := common.IntAll((*res)["i_vip_status"])
  136. memberStatus := common.IntAll((*res)["i_member_status"])
  137. if vipStatus > 0 || memberStatus > 0 {
  138. obj, _ := (*res)["o_vipjy"].(map[string]interface{})
  139. if obj != nil {
  140. itmes, _ := obj["a_items"].([]interface{})
  141. for _, v := range itmes {
  142. item, _ := v.(map[string]interface{})
  143. keys, _ := item["a_key"].([]interface{})
  144. if len(keys) > 0 {
  145. hasKeys = true
  146. break
  147. }
  148. }
  149. }
  150. if !hasKeys {
  151. obj, _ = (*res)["o_member_jy"].(map[string]interface{})
  152. }
  153. if obj != nil {
  154. itmes, _ := obj["a_items"].([]interface{})
  155. for _, v := range itmes {
  156. item, _ := v.(map[string]interface{})
  157. keys, _ := item["a_key"].([]interface{})
  158. if len(keys) > 0 {
  159. hasKeys = true
  160. break
  161. }
  162. }
  163. }
  164. } else {
  165. obj, _ := (*res)["o_jy"].(map[string]interface{})
  166. aKey, _ := obj["a_key"].([]interface{})
  167. if len(aKey) > 0 {
  168. hasKeys = true
  169. }
  170. }
  171. }
  172. //没有设置关键词
  173. if !hasKeys {
  174. logger.Info(fmt.Sprintf("当前用户:%s,手机号: %s 没有设置订阅词", msgBody.UserId, msgBody.Phone))
  175. return
  176. }
  177. case 3: //招标采购搜索任务
  178. case 4: //购买/续费/升级超级订阅会员
  179. cacheKey := fmt.Sprintf(model.PayCacheKey, msgBody.ActiveId, msgBody.UserId, "v", strconv.Itoa(msgBody.State))
  180. if cacheBool := redis.Put(PowerCacheDb, cacheKey, msgBody.Phone, int(emdTime.Unix()-time.Now().Unix())); !cacheBool {
  181. logger.Info(fmt.Sprintf("当前用户:%s,手机号: %s 超级订阅订单信息 %d redis存储失败,keys:%s", msgBody.UserId, msgBody.Phone, msgBody.State, cacheKey))
  182. }
  183. case 5: //购买/续费/升级大会员
  184. // TODO 完成任务 赠送两次 抽奖机会
  185. cacheKey := fmt.Sprintf(model.PayCacheKey, msgBody.ActiveId, msgBody.UserId, "m", strconv.Itoa(msgBody.State))
  186. if cacheBool := redis.Put(PowerCacheDb, cacheKey, msgBody.Phone, int(emdTime.Unix()-time.Now().Unix())); !cacheBool {
  187. logger.Info(fmt.Sprintf("当前用户:%s,手机号: %s 大会员订单信息 %d redis存储失败,keys:%s", msgBody.UserId, msgBody.Phone, msgBody.State, cacheKey))
  188. }
  189. case 6: //给朋友分享活动
  190. }
  191. insertMap := map[string]interface{}{
  192. "active_id": msgBody.ActiveId,
  193. "task_id": msgBody.TaskInfoId,
  194. "phone": msgBody.Phone,
  195. "user_id": msgBody.UserId,
  196. "position_id": msgBody.PositionId,
  197. "mgo_user_id": msgBody.MgoUserId,
  198. "order_code": msgBody.OrderCode,
  199. "state": 0,
  200. "end_date": timeRange.EndTime.Format(date.Date_Full_Layout),
  201. "update_date": time.Now().Format(date.Date_Full_Layout),
  202. "create_date": time.Now().Format(date.Date_Full_Layout),
  203. }
  204. var tf bool
  205. for i := 0; i < taskInfo.Qualification; i++ {
  206. if id := db.Mysql.Insert(tableTaskUser, insertMap); id < 0 {
  207. logger.Info(fmt.Sprintf("保存任务记录异常:%v", msgBody))
  208. // TODO 保存任务记录异常 告警
  209. if webhookURL := g.Cfg().MustGet(gctx.New(), "webhookURL").Strings(); len(webhookURL) > 0 {
  210. content := fmt.Sprintf(`保存任务记录异常:\n活动名称:%s \n手机号:%s \n职位id:%d \n任务id:%d \n任务名称:%s`,
  211. taskInfo.ActivityName, msgBody.Phone, msgBody.PositionId, msgBody.TaskInfoId, taskInfo.Name)
  212. util.SendMsgByWXURL(content, webhookURL)
  213. }
  214. } else {
  215. tf = true
  216. }
  217. }
  218. if tf {
  219. logger.Info(" sse 任务信息通知:", msg)
  220. var userName = msgBody.NickName
  221. if msgBody.Phone != "" {
  222. var PhoneReg = regexp.MustCompile(`^(100\d{8}|1[3-9]\d{9})$`)
  223. if PhoneReg.MatchString(msgBody.Phone) {
  224. phone := []rune(msgBody.Phone)
  225. userName = string(phone[0:3]) + "****" + string(phone[(len(phone)-4):])
  226. }
  227. }
  228. if sendData := util.GetSseRedisCache(msgBody.UserId); len(sendData) > 0 {
  229. for _, sv := range sendData {
  230. util.SendNotification(sv, model.SseMessage{
  231. //util.SendNotificationToAll(model.SseMessage{
  232. Name: taskInfo.Name,
  233. User: encrypt.SE.EncodeString(msgBody.UserId),
  234. State: model.TaskTarget,
  235. Time: time.Now().Format(date.Date_Full_Layout),
  236. Remark: fmt.Sprintf("%s 完成 %s 任务。", userName, taskInfo.Name),
  237. ActiveId: encrypt.SE.EncodeString(strconv.FormatInt(msgBody.ActiveId, 10)),
  238. })
  239. }
  240. }
  241. }
  242. }
  243. type lotteryBody struct {
  244. NickName string `json:"nick_name"`
  245. Phone string `json:"phone"`
  246. MgoUserId string `json:"mgo_user_id"`
  247. PositionId int64 `json:"position_id"`
  248. ActiveId int64 `json:"active_id"`
  249. ActiveName string `json:"active_name"`
  250. PrizeId int64 `json:"prize_id"`
  251. PrizeName string `json:"prize_name"`
  252. }
  253. // LotteryWinning 中奖信息
  254. func LotteryWinning(msg *model.Message) {
  255. //TODO sse 通知用户 中奖信息
  256. var lb lotteryBody
  257. if msg.E_body != nil {
  258. b, err := json.Marshal(msg.E_body)
  259. if err == nil {
  260. err = json.Unmarshal(b, &lb)
  261. }
  262. if err != nil {
  263. logger.Info(fmt.Sprintf("中奖参数信息有误:%s", msg.E_userId))
  264. return
  265. }
  266. }
  267. var userName = lb.NickName
  268. if lb.Phone != "" {
  269. var PhoneReg = regexp.MustCompile(`^(100\d{8}|1[3-9]\d{9})$`)
  270. if PhoneReg.MatchString(lb.Phone) {
  271. phone := []rune(lb.Phone)
  272. userName = string(phone[0:3]) + "****" + string(phone[(len(phone)-4):])
  273. }
  274. }
  275. logger.Info(" sse 中奖信息通知:", msg)
  276. util.SendNotificationToAll(model.SseMessage{
  277. Name: lb.PrizeName,
  278. User: userName,
  279. State: model.WinningTarget,
  280. Time: time.Now().Format(date.Date_Full_Layout),
  281. Remark: fmt.Sprintf("恭喜 %s 抽中 %s ", userName, lb.PrizeName),
  282. ActiveId: encrypt.SE.EncodeString(strconv.FormatInt(lb.ActiveId, 10)),
  283. })
  284. }