task.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package task
  2. import (
  3. "database/sql"
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "strconv"
  8. "time"
  9. "app.yhyue.com/moapp/MessageCenter/rpc/type/message"
  10. . "app.yhyue.com/moapp/jybase/api"
  11. qu "app.yhyue.com/moapp/jybase/common"
  12. "app.yhyue.com/moapp/jybase/date"
  13. "app.yhyue.com/moapp/jybase/go-xweb/xweb"
  14. "app.yhyue.com/moapp/message/config"
  15. "app.yhyue.com/moapp/message/db"
  16. "app.yhyue.com/moapp/message/handler/activity"
  17. "app.yhyue.com/moapp/message/model"
  18. . "app.yhyue.com/moapp/message/rpc"
  19. mrpc "app.yhyue.com/moapp/message/rpc"
  20. . "bp.jydev.jianyu360.cn/BaseService/pushpkg/p"
  21. "github.com/gogf/gf/v2/util/gconv"
  22. )
  23. type Task struct {
  24. *xweb.Action
  25. task xweb.Mapper `xweb:"/task"` //获取任务
  26. confirmChallenge xweb.Mapper `xweb:"/confirmChallenge"` //确认挑战
  27. }
  28. type TaskInfo struct {
  29. Name string `json:"name"`
  30. Desc string `json:"desc"`
  31. PcHref string `json:"pcHref"`
  32. AppHref string `json:"appHref"`
  33. WxHref string `json:"wxHref"`
  34. Point int `json:"point"`
  35. Icon string `json:"icon"`
  36. Type string `json:"type"`
  37. Status int `json:"status"`
  38. FinishTime string `json:"finishTime"`
  39. }
  40. //InitTask 初始化任务
  41. func (this *Task) InitTask(isNew bool) []*config.TaskStruct {
  42. if isNew {
  43. return config.TaskConf.NewTask
  44. }
  45. return config.TaskConf.OldTask
  46. }
  47. //Task 获取任务
  48. func (this *Task) Task() {
  49. sessVal := this.Session().GetMultiple()
  50. mgoUserId := gconv.String(sessVal["mgoUserId"])
  51. userId := gconv.String(sessVal["userId"])
  52. positionId := gconv.Int64(sessVal["positionId"])
  53. baseUserId := gconv.Int64(sessVal["base_user_id"])
  54. now := date.NowFormat(date.Date_Full_Layout)
  55. //
  56. rData, errMsg := func() (interface{}, error) {
  57. info := map[string]interface{}{}
  58. data := []*TaskInfo{}
  59. dataM := map[string]*TaskInfo{}
  60. //完成状态 0未开始/过期 1正在进行 2已完成
  61. status := 0
  62. //查询用户任务情况
  63. taskDetail := db.Tidb.SelectBySql(`select * from integral_task_detail where user_id =?`, baseUserId)
  64. if taskDetail != nil && len(*taskDetail) > 0 {
  65. for _, v := range *taskDetail {
  66. name := gconv.String(v["name"])
  67. desc := gconv.String(v["description"])
  68. pcHref := gconv.String(v["pc_href"])
  69. appHref := gconv.String(v["app_href"])
  70. wxHref := gconv.String(v["wx_href"])
  71. point := gconv.Int(v["point"])
  72. icon := gconv.String(v["icon"])
  73. types := gconv.String(v["type"])
  74. detailStatus := gconv.Int(v["status"])
  75. finishTime := gconv.String(v["finish_time"])
  76. tf := &TaskInfo{
  77. Name: name,
  78. Desc: desc,
  79. PcHref: pcHref,
  80. AppHref: appHref,
  81. WxHref: wxHref,
  82. Point: point,
  83. Icon: icon,
  84. Type: types,
  85. Status: detailStatus,
  86. FinishTime: finishTime,
  87. }
  88. dataM[types] = tf
  89. }
  90. }
  91. userMsg, ok := db.Mgo.FindById("user", mgoUserId, `{"s_m_openid":1,"l_registedate":1,"s_m_phone":1,"s_phone":1,"s_myemail":1,"s_nickname":1,"s_headimageurl":1,"s_password":1,"s_company":1,"s_unionid":1,"o_jy":1,"o_vipjy":1,"o_member_jy":1,"i_app_login_task":1}`)
  92. if userMsg == nil || len(*userMsg) == 0 || !ok {
  93. return nil, fmt.Errorf("未查询到用户")
  94. }
  95. //注册时间 判断是新手任务还是老用户限时任务
  96. l_registedate := gconv.Int64((*userMsg)["l_registedate"])
  97. isNew := l_registedate > config.TaskConf.TaskStartTime //是否注册时间处于新手任务开始时间
  98. ts := this.InitTask(isNew)
  99. //初始化任务
  100. for _, v := range ts {
  101. if dataM[v.Type] == nil {
  102. dataM[v.Type] = &TaskInfo{
  103. Name: v.Name,
  104. Desc: v.Desc,
  105. PcHref: v.PcHref,
  106. AppHref: v.AppHref,
  107. WxHref: v.WxHref,
  108. Point: v.Point,
  109. Icon: v.Icon,
  110. Type: v.Type,
  111. Status: 0,
  112. }
  113. }
  114. }
  115. mail := gconv.String((*userMsg)["s_myemail"])
  116. openid := gconv.String((*userMsg)["s_m_openid"])
  117. if !isNew {
  118. //邮箱是否绑定
  119. if mail != "" {
  120. dataM[model.BindMail].Status = 1
  121. dataM[model.BindMail].FinishTime = now
  122. activity.Task(&model.Message{
  123. E_code: "task",
  124. E_userId: userId,
  125. E_time: time.Now().Unix(),
  126. E_app: "jyweb_node2",
  127. E_body: map[string]interface{}{
  128. "code": 1009, //首次订阅
  129. "types": "bindMail",
  130. "baseUserId": baseUserId,
  131. "positionId": positionId,
  132. },
  133. })
  134. }
  135. } else {
  136. //openid是否绑定
  137. if openid != "" {
  138. dataM[model.FollowWx].Status = 1
  139. dataM[model.FollowWx].FinishTime = now
  140. activity.Task(&model.Message{
  141. E_code: "followWx",
  142. E_userId: userId,
  143. E_time: time.Now().Unix(),
  144. E_app: "jyweb_node2",
  145. E_body: map[string]interface{}{
  146. "code": 1008, //首次订阅
  147. "types": "followWx",
  148. "baseUserId": baseUserId,
  149. "positionId": positionId,
  150. },
  151. })
  152. }
  153. }
  154. //判断是否已经创建任务
  155. integralTaskData := db.Tidb.SelectBySql(`select * from integral_task where user_id =? limit 1`, baseUserId)
  156. if integralTaskData == nil || len(*integralTaskData) <= 0 {
  157. db.Tidb.ExecTx("创建任务", func(tx *sql.Tx) bool {
  158. taskId := db.Tidb.InsertByTx(tx, "integral_task", map[string]interface{}{
  159. "user_id": baseUserId,
  160. "position_id": positionId,
  161. "type": qu.If(isNew, 2, 1),
  162. "create_time": now,
  163. })
  164. fields := []string{"task_id", "user_id", "position_id", "name", "description", "icon", "point", "pc_href", "wx_href", "app_href", "status", "finish_time", "create_time", "type"}
  165. args := []interface{}{}
  166. //任务明细
  167. for _, v := range dataM {
  168. args = append(args, taskId, baseUserId, positionId, v.Name, v.Desc, v.Icon, v.Point, v.PcHref, v.WxHref, v.AppHref, v.Status, qu.If(v.FinishTime == "", nil, v.FinishTime), now, v.Type)
  169. }
  170. db.Tidb.InsertBatchByTx(tx, "integral_task_detail", fields, args)
  171. return true
  172. })
  173. } else {
  174. //部分初始化
  175. taskId := gconv.Int64((*integralTaskData)[0]["id"])
  176. fields := []string{"task_id", "user_id", "position_id", "name", "description", "icon", "point", "pc_href", "wx_href", "app_href", "status", "finish_time", "create_time", "type"}
  177. args := []interface{}{}
  178. for _, v := range dataM {
  179. if v.Status == 0 {
  180. if db.Tidb.CountBySql(`select count(1) from integral_task_detail where user_id =? and type =?`, baseUserId, v.Type) > 0 {
  181. continue
  182. }
  183. //任务明细
  184. args = append(args, taskId, baseUserId, positionId, v.Name, v.Desc, v.Icon, v.Point, v.PcHref, v.WxHref, v.AppHref, v.Status, qu.If(v.FinishTime == "", nil, v.FinishTime), now, v.Type)
  185. }
  186. }
  187. if len(args) > 0 {
  188. db.Tidb.InsertBatch("integral_task_detail", fields, args)
  189. }
  190. if (*integralTaskData)[0]["end_time"] != nil {
  191. et := gconv.String((*integralTaskData)[0]["end_time"])
  192. loc, _ := time.LoadLocation("Asia/Shanghai")
  193. endtime, _ := time.ParseInLocation(date.Date_Full_Layout, et, loc)
  194. if time.Now().Before(endtime) {
  195. //当前时间未超过结束时间
  196. status = 1
  197. } else {
  198. status = 3
  199. }
  200. info["endTime"] = endtime.Unix()
  201. }
  202. success_status := gconv.Int((*integralTaskData)[0]["success_status"])
  203. if success_status == 1 {
  204. //已完成挑战
  205. status = 2
  206. }
  207. }
  208. // for _, v := range dataM {
  209. for _, v := range ts {
  210. data = append(data, &TaskInfo{
  211. Name: dataM[v.Type].Name,
  212. Desc: dataM[v.Type].Desc,
  213. PcHref: dataM[v.Type].PcHref,
  214. AppHref: dataM[v.Type].AppHref,
  215. WxHref: dataM[v.Type].WxHref,
  216. Point: dataM[v.Type].Point,
  217. Icon: dataM[v.Type].Icon,
  218. Type: dataM[v.Type].Type,
  219. Status: dataM[v.Type].Status,
  220. FinishTime: dataM[v.Type].FinishTime,
  221. })
  222. }
  223. if isNew {
  224. info["newbieTask"] = data
  225. info["taskType"] = 2
  226. } else {
  227. info["limitedTask"] = data
  228. info["taskType"] = 1
  229. }
  230. //查询完成状态
  231. info["status"] = status
  232. return info, nil
  233. }()
  234. if errMsg != nil {
  235. log.Printf("%s Task %s异常:%s\n", userId, errMsg.Error())
  236. }
  237. this.ServeJson(NewResult(rData, errMsg))
  238. }
  239. //EntSubscribe 判断企业是否订阅
  240. func EntSubscribe(entUserId, entId int64) int {
  241. if entId > 0 {
  242. //企业
  243. data, ok := db.Mgo.FindOne("entniche_rule", map[string]interface{}{
  244. "i_entid": entId,
  245. "i_userid": entUserId,
  246. })
  247. if data == nil || len(*data) <= 0 || !ok {
  248. return 0
  249. }
  250. o_entniche := gconv.Map((*data)["o_entniche"])
  251. a_items := gconv.Maps(o_entniche["a_items"])
  252. for _, v := range a_items {
  253. a_key := gconv.Maps(v["a_key"])
  254. if len(a_key) > 0 {
  255. return 1
  256. }
  257. }
  258. }
  259. return 0
  260. }
  261. func (this *Task) ConfirmChallenge() {
  262. sessVal := this.Session().GetMultiple()
  263. baseUserId := gconv.Int64(sessVal["base_user_id"])
  264. userId := gconv.String(sessVal["mgoUserId"])
  265. rData, errMsg := func() (interface{}, error) {
  266. infoMap := map[string]interface{}{}
  267. if string(this.Body()) == "" {
  268. return map[string]interface{}{"status": -1}, fmt.Errorf(Error_msg_1001)
  269. }
  270. body := xweb.FilterXSS(string(this.Body()))
  271. //接收参数
  272. json.Unmarshal([]byte(body), &infoMap)
  273. if len(infoMap) == 0 {
  274. return map[string]interface{}{"status": -1}, fmt.Errorf(Error_msg_1002)
  275. }
  276. if gconv.Int(infoMap["challenge"]) == 1 {
  277. dayLater := time.Now().Add(time.Duration(config.TaskConf.TaskDayTime-1) * time.Hour * 24)
  278. endTime := time.Date(dayLater.Year(), dayLater.Month(), dayLater.Day(), 23, 59, 59, 0, time.Local)
  279. if db.Tidb.Update("integral_task", map[string]interface{}{
  280. "user_id": baseUserId,
  281. }, map[string]interface{}{
  282. "end_time": endTime.Format(date.Date_Full_Layout),
  283. }) {
  284. go func() {
  285. //用户点击“确认挑战”给用户发消息
  286. wxUrl := "/front/sess/" + Se.EncodeString(userId+",_id,identityKeep,") + "__" + Se.EncodeString(config.PushConfig.Messages.ConfirmChallenge.MobileUrl)
  287. appUrl := "/jyapp/free/sess/" + Se.EncodeString(userId+",id,"+strconv.Itoa(int(time.Now().Unix()))+",") + "__" + Se.EncodeString(config.PushConfig.Messages.ConfirmChallenge.MobileUrl)
  288. req := &message.MultipleSaveMsgReq{
  289. UserIds: userId,
  290. Title: config.PushConfig.Messages.ConfirmChallenge.Title,
  291. Content: config.PushConfig.Messages.ConfirmChallenge.Content,
  292. MsgType: config.PushConfig.Messages.ConfirmChallenge.MsgType,
  293. Link: config.PushConfig.Messages.ConfirmChallenge.PcUrl + "," + config.PushConfig.Messages.ConfirmChallenge.MobileUrl + "," + config.PushConfig.Messages.ConfirmChallenge.MobileUrl,
  294. Appid: config.PushConfig.Messages.ConfirmChallenge.Appid,
  295. AppPushUrl: appUrl,
  296. WxPushUrl: config.PushConfig.Webdomain + wxUrl,
  297. IosPushUrl: appUrl,
  298. }
  299. SendMsg("确认挑战", req)
  300. }()
  301. }
  302. //判断用户是否已经完成所有任务
  303. userMsg, ok := db.Mgo.FindById("user", userId, `{"l_registedate":1}`)
  304. if userMsg == nil || len(*userMsg) == 0 || !ok {
  305. return map[string]interface{}{"status": -1}, fmt.Errorf("未查询到用户")
  306. }
  307. //注册时间 判断是新手任务还是老用户限时任务
  308. l_registedate := gconv.Int64((*userMsg)["l_registedate"])
  309. isNew := l_registedate > config.TaskConf.TaskStartTime //是否注册时间处于新手任务开始时间
  310. ts := this.InitTask(isNew)
  311. taskDetailCount := db.Tidb.CountBySql(`select count(1) from integral_task_detail where user_id =? and stauts=1`, baseUserId)
  312. taskMsg := db.Tidb.SelectBySql(`select id from integral_task where user_id =? LIMIT 1`, baseUserId)
  313. if taskMsg == nil || len(*taskMsg) == 0 {
  314. return map[string]interface{}{"status": -1}, fmt.Errorf("任务创建失败")
  315. }
  316. taskId := gconv.Int64((*taskMsg)[0]["id"])
  317. if gconv.Int(taskDetailCount) == len(ts) {
  318. //任务完成 赠送超级订阅
  319. //判断是否完成所有任务且开启确认挑战
  320. if mrpc.SubVipHarvest(userId, 7, "") == nil {
  321. if db.Tidb.Update("integral_task", map[string]interface{}{"id": taskId}, map[string]interface{}{
  322. "success_status": 1,
  323. }) {
  324. go func() {
  325. wxUrl := "/front/sess/" + Se.EncodeString(userId+",_id,"+strconv.Itoa(int(time.Now().Unix()))+",") + "__" + Se.EncodeString(config.PushConfig.Messages.GetVip.MobileUrl)
  326. appUrl := "/jyapp/free/sess/" + Se.EncodeString(userId+",_id,"+strconv.Itoa(int(time.Now().Unix()))+",") + "__" + Se.EncodeString(config.PushConfig.Messages.GetVip.MobileUrl)
  327. SendMsg("获赠七天超级订阅服务", &message.MultipleSaveMsgReq{
  328. UserIds: userId,
  329. Title: config.PushConfig.Messages.GetVip.Title,
  330. Content: config.PushConfig.Messages.GetVip.Content,
  331. MsgType: config.PushConfig.Messages.GetVip.MsgType,
  332. Link: config.PushConfig.Messages.GetVip.PcUrl + "," + config.PushConfig.Messages.GetVip.MobileUrl + "," + config.PushConfig.Messages.GetVip.MobileUrl,
  333. Appid: config.PushConfig.Messages.GetVip.Appid,
  334. AppPushUrl: appUrl,
  335. WxPushUrl: config.PushConfig.Webdomain + wxUrl,
  336. IosPushUrl: appUrl,
  337. })
  338. }()
  339. }
  340. }
  341. }
  342. return map[string]interface{}{"status": 1}, nil
  343. }
  344. return map[string]interface{}{"status": 1}, nil
  345. }()
  346. if errMsg != nil {
  347. log.Printf("%s UserAccount ConfirmChallenge 异常:%s\n", baseUserId, errMsg.Error())
  348. }
  349. this.ServeJson(NewResult(rData, errMsg))
  350. }