cg_lepao.js 13 KB

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