WorkOrderMcp.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. const db = require('../../plugin/DataBase/db')
  2. const path = require('path')
  3. const Logger = require('../Logger')
  4. const mq = require('../../plugin/mq')
  5. const { mq: mqName } = require('../../plugin/mq/mqPrefix')
  6. const Redis = require('../../plugin/DataBase/Redis')
  7. const EmailTemplate = require('../../plugin/Email/emailTemplate')
  8. const { insertBindAudit, BindAuditAction, BindAuditSource } = require('./BindAudit')
  9. class WorkOrderMcp {
  10. constructor() {
  11. this.logger = new Logger(path.join(__dirname, '../logs/MCP.log'), 'INFO')
  12. this.messageQueue = mqName('runforge_message_queue')
  13. this.auto_day = [
  14. { label: '周一', value: 1 },
  15. { label: '周二', value: 2 },
  16. { label: '周三', value: 3 },
  17. { label: '周四', value: 4 },
  18. { label: '周五', value: 5 },
  19. { label: '周六', value: 6 },
  20. { label: '周日', value: 0 }
  21. ]
  22. this.area = ["兰花湖校区跑区", "主校区北跑区", "主校区南跑区", "重庆工商大学茶园校区", "随机分配"]
  23. this.auto_time = [
  24. { label: '随机分配', value: -1 },
  25. ...Array.from({ length: 17 }, (_, i) => {
  26. const hour = i + 7
  27. return { label: `${hour} ~ ${hour + 1}时`, value: hour }
  28. })
  29. ]
  30. this.autoTimeLabel = (record) => {
  31. if (record.auto_time === -1) {
  32. if (record.today_auto_time)
  33. return `随机-今日${record.today_auto_time}时`
  34. return '随机-待分配'
  35. }
  36. const match = this.auto_time.find(item => item.value === record.auto_time)
  37. return match ? match.label : '-'
  38. }
  39. this.emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  40. this.banEmailList = ['icloud.com']
  41. this.dailyUnbindLimit = 10
  42. }
  43. async get_account_info({ sender, student_num }) {
  44. try {
  45. if ([sender, student_num].some(value => value === '' || value === null || value === undefined))
  46. return '缺少参数'
  47. this.logger.info(`MCP接收获取账号信息请求:${sender},student_num:${student_num}`)
  48. let sql = `
  49. SELECT
  50. l.name,
  51. l.student_num,
  52. l.state,
  53. l.area,
  54. l.auto_time,
  55. l.total_num,
  56. l.term_num,
  57. l.academy_name,
  58. l.sex,
  59. l.grade_id,
  60. l.email,
  61. l.auto_run,
  62. l.today_auto_time,
  63. l.target_count,
  64. l.auto_day,
  65. l.notice_type
  66. FROM
  67. lepao_account l
  68. WHERE
  69. l.student_num = ? AND l.create_user = ?
  70. `
  71. const rows = await db.query(sql, [student_num, sender])
  72. if (!rows || rows.length == 0) return '该账号未被您绑定,无法查看'
  73. let data = rows[0]
  74. let returnMsg = `
  75. 姓名:${data.name ?? '未更新,请使用乐跑登录器更新账号信息'};学号:${data.student_num};账号状态:${data.state === 1 ? '正常' : '需使用乐跑登录器更新账号信息'};乐跑跑区:${data.area == '' ? "随机分配" : data.area};自动乐跑状态:${data.auto_run === 1 ? '开启' : '关闭'}
  76. `
  77. if (data.auto_run === 1) {
  78. returnMsg += `自动乐跑时间:${this.autoTimeLabel(data)};`
  79. returnMsg += `自动乐跑星期:${data.auto_day.slice().sort((a, b) => {
  80. if (a === 0) return 1; if (b === 0) return -1; return a - b;
  81. }).map(day => this.auto_day.find(item => item.value === day)?.label).join(',')};`
  82. }
  83. if (data.sex) returnMsg += `性别:${data.sex === 1 ? '男' : '女'};`
  84. if (data.email) returnMsg += `邮箱:${data.email};`
  85. if (data.grade) returnMsg += `邮箱:${data.grade};`
  86. if (data.academy_name) returnMsg += `学院:${data.academy_name};`
  87. if (data.grade_id) returnMsg += `年级:${data.grade_id}级;`
  88. if (data.target_count) returnMsg += `目标乐跑次数:${data.target_count};`
  89. if (data.total_num) returnMsg += `累计乐跑次数:${data.total_num};`
  90. if (data.notice_type) returnMsg += `通知方式:${data.notice_type};`
  91. return returnMsg
  92. } catch (error) {
  93. this.logger.error(`MCP查询账号信息出错:${error.stack}`)
  94. return '系统出错,请稍后再试'
  95. }
  96. }
  97. getDailyUnbindRedisKey(sender) {
  98. const now = new Date()
  99. const year = now.getFullYear()
  100. const month = `${now.getMonth() + 1}`.padStart(2, '0')
  101. const day = `${now.getDate()}`.padStart(2, '0')
  102. return `mcp:unbind:daily:${sender}:${year}${month}${day}`
  103. }
  104. getSecondsToDayEnd() {
  105. const now = new Date()
  106. const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0, 0)
  107. return Math.max(1, Math.floor((tomorrow.getTime() - now.getTime()) / 1000))
  108. }
  109. async unbind_account({ sender, student_num }) {
  110. try {
  111. if ([sender, student_num].some(value => value === '' || value === null || value === undefined))
  112. return '缺少参数'
  113. this.logger.info(`工单MCP接收解绑账号请求:${sender}`)
  114. const dailyUnbindKey = this.getDailyUnbindRedisKey(sender)
  115. const dailyUnbindCount = Number(await Redis.get(dailyUnbindKey) || 0)
  116. if (dailyUnbindCount >= this.dailyUnbindLimit) return '今日通过MCP解绑次数已超过限制,只能人工处理'
  117. let selectSql = `SELECT create_user, auto_run FROM lepao_account WHERE student_num = ? AND create_user IS NOT NULL`
  118. let selectRows = await db.query(selectSql, [student_num])
  119. if (!selectRows || selectRows.length === 0 || !selectRows[0]?.create_user) return '该账号未绑定,无需解绑'
  120. if (selectRows[0].auto_run === 1) return '该账号已开启自动乐跑,请用原绑定账号关闭自动乐跑后再解绑或联系人工客服处理'
  121. let updateSql = `UPDATE lepao_account SET create_user = NULL, auto_run = 0, update_time = ? WHERE student_num = ?`
  122. let updateRows = await db.query(updateSql, [Date.now(), student_num])
  123. if (!updateRows || updateRows.affectedRows !== 1)
  124. return '系统出错,请稍后再试'
  125. const auditOk = await insertBindAudit({
  126. studentNum: student_num,
  127. ownerUuid: selectRows[0].create_user || null,
  128. action: BindAuditAction.PLATFORM_UNBIND,
  129. source: BindAuditSource.MCP_WORK_ORDER,
  130. operatorUuid: sender || null,
  131. detail: { sender },
  132. createdAt: Date.now()
  133. })
  134. if (!auditOk) {
  135. this.logger.warn(`工单解绑审计写入失败 student_num=${student_num}`)
  136. }
  137. const latestUnbindCount = await Redis.incr(dailyUnbindKey)
  138. if (latestUnbindCount === 1) {
  139. await Redis.expire(dailyUnbindKey, this.getSecondsToDayEnd())
  140. }
  141. return `解绑成功,您现在可绑定该账号`
  142. } catch (error) {
  143. this.logger.error(`工单MCP解绑账号出错:${error.stack}`)
  144. return '系统出错,请稍后再试'
  145. }
  146. }
  147. async need_manual({ sender, order_id }) {
  148. try {
  149. if ([sender, order_id].some(value => value === '' || value === null || value === undefined))
  150. return '缺少参数'
  151. this.logger.info(`MCP接收转人工服务请求:${order_id}`)
  152. const selectSql = 'SELECT msg, state, email, need_manual FROM work_order WHERE id = ? AND create_user = ?'
  153. const selectRows = await db.query(selectSql, [order_id, sender])
  154. if (!selectRows || selectRows.length !== 1)
  155. return '未找到你创建的工单,请核对工单ID'
  156. if (selectRows[0].state === 2) return '工单已关闭,无法提交转人工服务,请提交新工单'
  157. if (selectRows[0].need_manual === 1) return '该工单已提交转人工服务,无需重复提交'
  158. let msg = selectRows[0].msg
  159. msg.push({
  160. time: Date.now(),
  161. content: '人工处理请求已提交,请耐心等待人工客服处理',
  162. uuid: 'e4fe0277-0b1a-41a1-b25f-8b6e4cec3281',
  163. type: 'system'
  164. })
  165. let updateSql = `UPDATE work_order SET msg = ?, need_manual = 1, update_time = ? WHERE id = ? AND create_user = ?`
  166. let updateRows = await db.query(updateSql, [msg, Date.now(), order_id, sender])
  167. if (!updateRows || updateRows.affectedRows !== 1) return '系统出错,请稍后再试'
  168. return `转人工服务请求已提交,后续消息AI助理小妍将不再回复`
  169. } catch (error) {
  170. this.logger.error(`MCP转人工服务出错:${error.stack}`)
  171. return '系统出错,请稍后再试'
  172. }
  173. }
  174. }
  175. const WORKORDERMCP = new WorkOrderMcp()
  176. module.exports.WORKORDERMCP = WORKORDERMCP