lotteryDrawTask.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. if vipStatus > 0 {
  139. obj, _ := (*res)["o_vipjy"].(map[string]interface{})
  140. if obj != nil {
  141. itmes, _ := obj["a_items"].([]interface{})
  142. for _, v := range itmes {
  143. item, _ := v.(map[string]interface{})
  144. keys, _ := item["a_key"].([]interface{})
  145. if len(keys) > 0 {
  146. hasKeys = true
  147. break
  148. }
  149. }
  150. }
  151. }
  152. if memberStatus > 0 && !hasKeys {
  153. obj, _ := (*res)["o_member_jy"].(map[string]interface{})
  154. if obj != nil {
  155. itmes, _ := obj["a_items"].([]interface{})
  156. for _, v := range itmes {
  157. item, _ := v.(map[string]interface{})
  158. keys, _ := item["a_key"].([]interface{})
  159. if len(keys) > 0 {
  160. hasKeys = true
  161. break
  162. }
  163. }
  164. }
  165. }
  166. } else {
  167. obj, _ := (*res)["o_jy"].(map[string]interface{})
  168. aKey, _ := obj["a_key"].([]interface{})
  169. if len(aKey) > 0 {
  170. hasKeys = true
  171. }
  172. }
  173. }
  174. //没有设置关键词
  175. if !hasKeys {
  176. logger.Info(fmt.Sprintf("当前用户:%s,手机号: %s 没有设置订阅词", msgBody.UserId, msgBody.Phone))
  177. return
  178. }
  179. case 3: //招标采购搜索任务
  180. case 4: //购买/续费/升级超级订阅会员
  181. cacheKey := fmt.Sprintf(model.PayCacheKey, msgBody.ActiveId, msgBody.UserId, "v", strconv.Itoa(msgBody.State))
  182. if cacheBool := redis.Put(PowerCacheDb, cacheKey, msgBody.Phone, int(emdTime.Unix()-time.Now().Unix())); !cacheBool {
  183. logger.Info(fmt.Sprintf("当前用户:%s,手机号: %s 超级订阅订单信息 %d redis存储失败,keys:%s", msgBody.UserId, msgBody.Phone, msgBody.State, cacheKey))
  184. }
  185. case 5: //购买/续费/升级大会员
  186. // TODO 完成任务 赠送两次 抽奖机会
  187. cacheKey := fmt.Sprintf(model.PayCacheKey, msgBody.ActiveId, msgBody.UserId, "m", strconv.Itoa(msgBody.State))
  188. if cacheBool := redis.Put(PowerCacheDb, cacheKey, msgBody.Phone, int(emdTime.Unix()-time.Now().Unix())); !cacheBool {
  189. logger.Info(fmt.Sprintf("当前用户:%s,手机号: %s 大会员订单信息 %d redis存储失败,keys:%s", msgBody.UserId, msgBody.Phone, msgBody.State, cacheKey))
  190. }
  191. case 6: //给朋友分享活动
  192. }
  193. insertMap := map[string]interface{}{
  194. "active_id": msgBody.ActiveId,
  195. "task_id": msgBody.TaskInfoId,
  196. "phone": msgBody.Phone,
  197. "user_id": msgBody.UserId,
  198. "position_id": msgBody.PositionId,
  199. "mgo_user_id": msgBody.MgoUserId,
  200. "order_code": msgBody.OrderCode,
  201. "state": 0,
  202. "end_date": timeRange.EndTime.Format(date.Date_Full_Layout),
  203. "update_date": time.Now().Format(date.Date_Full_Layout),
  204. "create_date": time.Now().Format(date.Date_Full_Layout),
  205. }
  206. var tf bool
  207. for i := 0; i < taskInfo.Qualification; i++ {
  208. if id := db.Mysql.Insert(tableTaskUser, insertMap); id < 0 {
  209. logger.Info(fmt.Sprintf("保存任务记录异常:%v", msgBody))
  210. // TODO 保存任务记录异常 告警
  211. if webhookURL := g.Cfg().MustGet(gctx.New(), "webhookURL").Strings(); len(webhookURL) > 0 {
  212. content := fmt.Sprintf(`保存任务记录异常:\n活动名称:%s \n手机号:%s \n职位id:%d \n任务id:%d \n任务名称:%s`,
  213. taskInfo.ActivityName, msgBody.Phone, msgBody.PositionId, msgBody.TaskInfoId, taskInfo.Name)
  214. util.SendMsgByWXURL(content, webhookURL)
  215. }
  216. } else {
  217. tf = true
  218. }
  219. }
  220. if tf {
  221. logger.Info(" sse 任务信息通知:", msg)
  222. var userName = msgBody.NickName
  223. if msgBody.Phone != "" {
  224. var PhoneReg = regexp.MustCompile(`^(100\d{8}|1[3-9]\d{9})$`)
  225. if PhoneReg.MatchString(msgBody.Phone) {
  226. phone := []rune(msgBody.Phone)
  227. userName = string(phone[0:3]) + "****" + string(phone[(len(phone)-4):])
  228. }
  229. }
  230. if sendData := util.GetSseRedisCache(msgBody.UserId); len(sendData) > 0 {
  231. for _, sv := range sendData {
  232. util.SendNotification(sv, model.SseMessage{
  233. //util.SendNotificationToAll(model.SseMessage{
  234. Name: taskInfo.Name,
  235. User: encrypt.SE.EncodeString(msgBody.UserId),
  236. State: model.TaskTarget,
  237. Time: time.Now().Format(date.Date_Full_Layout),
  238. Remark: fmt.Sprintf("%s 完成 %s 任务。", userName, taskInfo.Name),
  239. ActiveId: encrypt.SE.EncodeString(strconv.FormatInt(msgBody.ActiveId, 10)),
  240. })
  241. }
  242. }
  243. }
  244. }
  245. type lotteryBody struct {
  246. NickName string `json:"nick_name"`
  247. Phone string `json:"phone"`
  248. MgoUserId string `json:"mgo_user_id"`
  249. PositionId int64 `json:"position_id"`
  250. ActiveId int64 `json:"active_id"`
  251. ActiveName string `json:"active_name"`
  252. PrizeId int64 `json:"prize_id"`
  253. PrizeName string `json:"prize_name"`
  254. }
  255. // LotteryWinning 中奖信息
  256. func LotteryWinning(msg *model.Message) {
  257. //TODO sse 通知用户 中奖信息
  258. var lb lotteryBody
  259. if msg.E_body != nil {
  260. b, err := json.Marshal(msg.E_body)
  261. if err == nil {
  262. err = json.Unmarshal(b, &lb)
  263. }
  264. if err != nil {
  265. logger.Info(fmt.Sprintf("中奖参数信息有误:%s", msg.E_userId))
  266. return
  267. }
  268. }
  269. var userName = lb.NickName
  270. if lb.Phone != "" {
  271. var PhoneReg = regexp.MustCompile(`^(100\d{8}|1[3-9]\d{9})$`)
  272. if PhoneReg.MatchString(lb.Phone) {
  273. phone := []rune(lb.Phone)
  274. userName = string(phone[0:3]) + "****" + string(phone[(len(phone)-4):])
  275. }
  276. }
  277. logger.Info(" sse 中奖信息通知:", msg)
  278. util.SendNotificationToAll(model.SseMessage{
  279. Name: lb.PrizeName,
  280. User: userName,
  281. State: model.WinningTarget,
  282. Time: time.Now().Format(date.Date_Full_Layout),
  283. Remark: fmt.Sprintf("恭喜 %s 抽中 %s ", userName, lb.PrizeName),
  284. ActiveId: encrypt.SE.EncodeString(strconv.FormatInt(lb.ActiveId, 10)),
  285. })
  286. }