cg_lepao.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. const axios = require('axios')
  2. const Redis = require('../../plugin/DataBase/Redis')
  3. const db = require('../../plugin/DataBase/db')
  4. const mq = require('../../plugin/mq')
  5. const Logger = require('../Logger')
  6. const path = require('path')
  7. const EmailTemplate = require('../../plugin/Email/emailTemplate')
  8. const { offsetGeoPoints, geoPointsToString, getCurrentTime } = require('./generatePath')
  9. const { sendStartLepao, sendStopLepao, lepaoUserInfo } = require('./lepaoAPI')
  10. class cgLepao {
  11. constructor() {
  12. this.logger = new Logger(path.join(__dirname, '../logs/cgLepao.log'), 'INFO')
  13. }
  14. // 获取跑步线路
  15. async getPath(account) {
  16. this.logger.info(`${account}开始获取路径`)
  17. const accountSql = 'SELECT area, sex FROM lepao_account WHERE student_num = ?'
  18. const rows = await db.query(accountSql, [account])
  19. if (!rows || rows.length === 0) {
  20. this.logger.error(`${account}无法获取账号数据`)
  21. throw new Error('无法获取账号数据')
  22. }
  23. const { area, sex } = rows[0]
  24. let max = 4.00
  25. let min = 2.00
  26. let speed = 9
  27. if (sex === 1) {
  28. max = 2.00
  29. min = 1.60
  30. speed = 11
  31. }
  32. this.logger.info(`${account}路径参数: area=${area ?? '随机'}`)
  33. let pathSql = 'SELECT id, time FROM path_data WHERE state = 1 AND distance < ? AND distance > ? AND speed <= ?'
  34. const pathParams = [max, min, speed]
  35. if (area) {
  36. pathSql += ' AND run_zone_name = ?'
  37. pathParams.push(area)
  38. }
  39. pathSql += ' ORDER BY count ASC LIMIT 1'
  40. const paths = await db.query(pathSql, pathParams)
  41. if (!paths || paths.length === 0) {
  42. this.logger.error(`${account}未找到符合条件的路线`)
  43. throw new Error('未找到符合条件的路线,请改变路径选择条件')
  44. }
  45. const randomPath = paths[0]
  46. const updateSql = 'UPDATE path_data SET count = count + 1 WHERE id = ?'
  47. await db.query(updateSql, [randomPath.id])
  48. this.logger.info(`${account}路径选中id=${randomPath.id},计数加1成功`)
  49. return { path_id: randomPath.id, path_time: randomPath.time, area }
  50. }
  51. async writeRedis(account) {
  52. try {
  53. // 计算至明日0时过期的秒数
  54. const now = new Date()
  55. const tomorrow = new Date().setHours(24, 0, 0, 0)
  56. const exp = Math.floor((tomorrow - now) / 1000)
  57. await Redis.set(`cgLepaoSuccess:${account}`, account, {
  58. EX: exp
  59. })
  60. } catch (error) {
  61. this.logger.error(`redis缓存乐跑记录失败: ${error.stack || '未知错误'}`)
  62. }
  63. }
  64. async lepaoFail(uuid) {
  65. try {
  66. this.logger.info(`返还用户 ${uuid} 乐跑次数`)
  67. let sql = 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid = ?'
  68. await db.query(sql, [uuid])
  69. this.logger.info(`返还用户 ${uuid} 乐跑次数成功`)
  70. } catch (error) {
  71. this.logger.error(`返还用户 ${uuid} 乐跑次数时出错: ${error.stack || error.message}`)
  72. }
  73. }
  74. async sendSuccessEmail(account, lepaoData, total_num) {
  75. try {
  76. this.logger.info(`${account}发送乐跑成功邮件`)
  77. const emailSql = 'SELECT name, email, target_count, auto_run FROM lepao_account WHERE student_num = ?'
  78. const rows = await db.query(emailSql, [account])
  79. if (!rows || rows.length === 0) {
  80. this.logger.error(`${account}查找用户邮箱失败`)
  81. throw new Error('查找用户邮箱失败')
  82. }
  83. const data = {
  84. ...lepaoData,
  85. term_num: rows[0].target_count,
  86. total_num,
  87. name: rows[0].name,
  88. account
  89. }
  90. await EmailTemplate.lepaoSuccess(rows[0].email, data)
  91. this.logger.info(`${account}乐跑成功邮件发送完成`)
  92. if (rows[0].target_count !== 0 && total_num >= rows[0].target_count && rows[0].auto_run === 1) {
  93. this.logger.info(`${account}乐跑目标完成,发送乐跑结束邮件并关闭自动乐跑`)
  94. await EmailTemplate.lepaoOver(rows[0].email, data)
  95. let overSql = 'UPDATE lepao_account SET auto_run = 0 WHERE student_num = ?'
  96. let overRows = await db.query(overSql, [account])
  97. if (!overRows || overRows.affectedRows !== 1)
  98. this.logger.warn(`${account}乐跑结束后关闭自动乐跑失败`)
  99. else
  100. this.logger.info(`${account}自动乐跑关闭成功`)
  101. }
  102. } catch (error) {
  103. this.logger.error(`发送成功邮件失败: ${error.stack || error.message}`)
  104. }
  105. }
  106. async sendFailEmail(account, reason) {
  107. try {
  108. this.logger.info(`${account}发送乐跑失败邮件,原因: ${reason}`)
  109. const emailSql = 'SELECT name, email FROM lepao_account WHERE student_num = ?'
  110. const rows = await db.query(emailSql, [account])
  111. if (!rows || rows.length == 0) {
  112. this.logger.error(`${account}查找用户邮箱失败`)
  113. throw new Error('查找用户邮箱失败')
  114. }
  115. const data = {
  116. name: rows[0].name,
  117. account,
  118. reason: reason || '系统繁忙,请联系客服或稍后再试'
  119. }
  120. await EmailTemplate.lepaoFail(rows[0].email, data)
  121. this.logger.info(`${account}乐跑失败邮件发送完成`)
  122. } catch (error) {
  123. this.logger.error(`发送失败邮件失败: ${error.stack || error.message}`)
  124. }
  125. }
  126. async beginLepao(uuid, account) {
  127. try {
  128. this.logger.info(`${account}开始执行乐跑流程`)
  129. // 检查redis是否存在当天乐跑成功记录
  130. // const isSuccess = await Redis.get(`cgLepaoSuccess:${account}`)
  131. // if (isSuccess)
  132. // throw new Error('该账号当天已存在成功乐跑记录')
  133. const isProgress = await Redis.get(`cgLepaoProgress:${account}`)
  134. if (isProgress)
  135. throw new Error('该账号已进入乐跑任务队列,请等待乐跑完成后再进行乐跑操作')
  136. //已开始乐跑,存入Redis
  137. await Redis.set(`cgLepaoProgress:${account}`, account)
  138. // 扣除乐跑次数
  139. this.logger.info(`${account}开始扣减乐跑次数`)
  140. const useLepaoCountSql = 'UPDATE users SET lepao_count = lepao_count - 1 WHERE uuid = ?'
  141. await db.query(useLepaoCountSql, [uuid])
  142. this.logger.info(`${account}扣减乐跑次数完成`)
  143. const userPermissionSql = 'SELECT lepao_count FROM users WHERE uuid = ?'
  144. const userPermissionData = await db.query(userPermissionSql, [uuid])
  145. if (!userPermissionData || userPermissionData.length !== 1) {
  146. this.logger.error(`${account}无法获取用户信息`)
  147. throw new Error('无法获取用户信息,请重试或联系哪吒乐跑客服')
  148. }
  149. if (userPermissionData[0].lepao_count < 1) {
  150. this.logger.warn(`${account}乐跑次数不足`)
  151. throw new Error('用户乐跑次数不足,请购买乐跑套餐!')
  152. }
  153. // 获取路径 ID
  154. const { path_id, path_time, area } = await this.getPath(account)
  155. // 提交乐跑请求
  156. const { task_id, startTime } = await sendStartLepao(account)
  157. let taskSql = 'INSERT INTO lepao_record (uuid, lepao_account, task_id, path_id, startTime, time, area) VALUES (?, ?, ?, ?, ?, ?, ?)'
  158. let taskRows = await db.query(taskSql, [uuid, account, task_id, path_id, startTime, path_time, area])
  159. if (!taskRows || taskRows.affectedRows === 0) {
  160. this.logger.error(`${account}乐跑任务入库失败`)
  161. throw new Error('乐跑任务发起失败,请联系客服或稍后再试')
  162. }
  163. let task = {
  164. uuid, account, task_id, path_id, path_time, startTime
  165. }
  166. let delayMs = path_time * 1000
  167. const ch = await mq.getChannel('cg_run_task')
  168. ch.sendToQueue(
  169. 'cg_run_delay_queue',
  170. Buffer.from(JSON.stringify(task)),
  171. {
  172. expiration: delayMs.toString(),
  173. persistent: true
  174. }
  175. )
  176. this.logger.info(`已投递跑步任务 user=${account} 延迟=${path_time}s`)
  177. } catch (error) {
  178. await this.lepaoFail(uuid)
  179. let failSql = 'UPDATE lepao_records SET state = 2 WHERE lepao_account = ? AND state = 0 ORDER BY id DESC LIMIT 1'
  180. await db.query(failSql, [account])
  181. await this.sendFailEmail(account, error.message)
  182. await Redis.del(`cgLepaoProgress:${account}`)
  183. this.logger.error(`乐跑流程失败: ${error.stack || '未知错误'}`)
  184. }
  185. }
  186. async lepaoFinish() {
  187. const ch = await mq.getChannel('cg_run_finish')
  188. ch.prefetch(1) // 控制并发
  189. await ch.consume('cg_run_finish_queue', async (msg) => {
  190. if (!msg) return
  191. const task = JSON.parse(msg.content.toString())
  192. this.logger.info(`开始处理乐跑结束任务 user=${task.account} task_id=${task.task_id}`)
  193. try {
  194. const currentTime = getCurrentTime()
  195. let pathSql = 'SELECT * FROM path_data WHERE id = ?'
  196. const pathRows = await db.query(pathSql, [task.path_id])
  197. if (!pathRows || pathRows.length === 0) {
  198. this.logger.error(`${task.account}乐跑路径数据获取失败 id=${task.path_id}`)
  199. throw new Error('乐跑路径数据获取失败,请联系客服或稍后再试')
  200. }
  201. let pathData = pathRows[0]
  202. let pathLine = offsetGeoPoints(pathData.data)
  203. let pathLineStr = geoPointsToString(pathLine)
  204. let lepaoData = {
  205. account: task.account,
  206. calorie: Number(pathData.calorie).toFixed(2),
  207. distance: Number(pathData.distance).toFixed(6),
  208. distribution: pathData.speed,
  209. duration: pathData.time,
  210. endTime: currentTime,
  211. id: task.task_id,
  212. maxDistribution: '0.00',
  213. pathLine: pathLineStr,
  214. startTime: task.startTime,
  215. }
  216. this.logger.info(`${task.account}乐跑数据构造结束:`)
  217. console.log(lepaoData)
  218. let lepaoResult = await sendStopLepao(lepaoData)
  219. if (lepaoResult.status !== 1) {
  220. this.logger.error(`${task.account}乐跑失败!`)
  221. let updateSql = 'UPDATE lepao_record SET startTime = ?, endTime = ?, frequency = ?, distance = ?, path_data = ?, state = 2 WHERE task_id = ?'
  222. await db.query(updateSql, [
  223. lepaoResult.startTime,
  224. lepaoResult.endTime,
  225. lepaoResult.frequency,
  226. pathData.distance,
  227. pathLine,
  228. task.task_id
  229. ])
  230. throw new Error('乐跑失败,请联系客服或稍后再试')
  231. }
  232. let updateSql = 'UPDATE lepao_record SET startTime = ?, endTime = ?, frequency = ?, distance = ?, path_data = ?, state = 1 WHERE task_id = ?'
  233. await db.query(updateSql, [
  234. lepaoResult.startTime,
  235. lepaoResult.endTime,
  236. lepaoResult.frequency,
  237. pathData.distance,
  238. pathLine,
  239. task.task_id
  240. ])
  241. this.logger.info(`${task.account}乐跑成功,获取账号信息`)
  242. let userInfo = await lepaoUserInfo(task.account)
  243. const { frequency } = userInfo
  244. lepaoResult.time = pathData.time
  245. lepaoResult.distance = Number(pathData.distance).toFixed(2)
  246. lepaoResult.area = pathData.run_zone_name
  247. await this.writeRedis(task.account)
  248. let updateAccountSql = 'UPDATE lepao_account SET total_num = ? WHERE student_num = ?'
  249. await db.query(updateAccountSql, [frequency, task.account])
  250. this.sendSuccessEmail(task.account, lepaoResult, frequency)
  251. } catch (error) {
  252. await this.lepaoFail(task.uuid)
  253. await this.sendFailEmail(task.account, error.message)
  254. this.logger.error(`乐跑结束处理失败: ${error.stack || '未知错误'}`)
  255. } finally {
  256. await Redis.del(`cgLepaoProgress:${task.account}`)
  257. ch.ack(msg)
  258. }
  259. })
  260. this.logger.info('乐跑任务结束消费者启动完成')
  261. }
  262. }
  263. const Lepao = new cgLepao()
  264. module.exports.Lepao = Lepao