SendCount.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. const API = require("../../lib/API")
  2. const db = require("../../plugin/DataBase/db")
  3. const AccessControl = require("../../lib/AccessControl")
  4. const { BaseStdResponse } = require("../../BaseStdResponse")
  5. const EmailTemplate = require("../../plugin/Email/emailTemplate")
  6. const { insertLedgerRecord } = require("../../lib/Lepao/CountLedger")
  7. class SendCount extends API {
  8. constructor() {
  9. super()
  10. this.setPath("/Goods/SendCount")
  11. this.setMethod("POST")
  12. }
  13. async onRequest(req, res) {
  14. let { uuid, session, username, count } = req.body
  15. username = typeof username === "string" ? username.trim() : username
  16. count = Number(count)
  17. if ([uuid, session, username, count].some(v => v == null || v === "" || Number.isNaN(count)))
  18. return res.json({ ...BaseStdResponse.MISSING_PARAMETER })
  19. if (!Number.isInteger(count) || count < 1 || count > 9999)
  20. return res.json({ ...BaseStdResponse.ERR, msg: "超出赠送的次数范围,请重新选择赠送次数" })
  21. if (!(await AccessControl.checkSession(uuid, session)))
  22. return res.status(401).json({ ...BaseStdResponse.ACCESS_DENIED })
  23. const conn = await db.connect() // 这里直接拿 connection
  24. try {
  25. await conn.beginTransaction()
  26. const [senderRows] = await conn.execute(
  27. "SELECT id, username, lepao_count FROM users WHERE uuid = ?",
  28. [uuid]
  29. )
  30. if (!senderRows || senderRows.length !== 1) {
  31. await conn.rollback()
  32. return res.json({ ...BaseStdResponse.MISSING_FILE, msg: "获取用户信息失败!" })
  33. }
  34. const [targetRows] = await conn.execute(
  35. "SELECT id, uuid FROM users WHERE username = ?",
  36. [username]
  37. )
  38. if (!targetRows || targetRows.length !== 1) {
  39. await conn.rollback()
  40. return res.json({ ...BaseStdResponse.ERR, msg: "未找到接收用户,请检查用户名是否正确!" })
  41. }
  42. if (targetRows[0].uuid === uuid) {
  43. await conn.rollback()
  44. return res.json({ ...BaseStdResponse.ERR, msg: "不能给自己赠送次数!" })
  45. }
  46. const [decResult] = await conn.execute(
  47. "UPDATE users SET lepao_count = lepao_count - ? WHERE uuid = ? AND lepao_count >= ?",
  48. [count, uuid, count]
  49. )
  50. if (decResult.affectedRows !== 1) {
  51. await conn.rollback()
  52. return res.json({ ...BaseStdResponse.ERR, msg: "剩余乐跑次数不足,请购买后再赠送!" })
  53. }
  54. const [insertResult] = await conn.execute(
  55. `INSERT INTO lepao_send_count_request
  56. (sender_uuid, receiver_user_id, count, status, created_at)
  57. VALUES (?, ?, ?, 'pending', NOW())`,
  58. [uuid, targetRows[0].id, count]
  59. )
  60. if (!insertResult || insertResult.affectedRows !== 1) {
  61. await conn.rollback()
  62. return res.json({ ...BaseStdResponse.ERR, msg: "提交赠送审核失败,请稍后再试!" })
  63. }
  64. const requestId = insertResult.insertId
  65. await insertLedgerRecord({
  66. executor: conn,
  67. userUuid: uuid,
  68. delta: -count,
  69. balanceBefore: Number(senderRows[0].lepao_count || 0),
  70. balanceAfter: Number(senderRows[0].lepao_count || 0) - count,
  71. bizType: 'gift_send_lock',
  72. bizId: `send_request:${requestId}`,
  73. remark: `向用户${username}赠送${count}次`
  74. })
  75. await conn.commit()
  76. const createTime = new Date().getTime()
  77. // 非阻塞通知管理员,不影响主业务流程
  78. Promise.resolve().then(async () => {
  79. try {
  80. const adminSql = `
  81. SELECT email
  82. FROM users
  83. WHERE email IS NOT NULL
  84. AND email <> ''
  85. AND (JSON_CONTAINS(permission, '"admin"') OR JSON_CONTAINS(permission, '"service"'))
  86. `
  87. const adminRows = await db.query(adminSql)
  88. if (!adminRows || adminRows.length === 0) {
  89. this.logger.warn(`[SendCountNotify][submit][requestId=${requestId}] 未找到可通知的管理员邮箱`)
  90. return
  91. }
  92. const emails = [...new Set(adminRows.map(row => row.email).filter(Boolean))]
  93. for (const email of emails) {
  94. await EmailTemplate.sendCountRequestNotifyAdmins(email, {
  95. requestId,
  96. senderUsername: senderRows[0].username,
  97. receiverUsername: username,
  98. count,
  99. createTime
  100. })
  101. }
  102. } catch (mailErr) {
  103. this.logger.error(`[SendCountNotify][submit][requestId=${requestId}] 管理员通知发送失败:${mailErr.message || "未知错误"}`)
  104. }
  105. })
  106. return res.json({ ...BaseStdResponse.OK, msg: "已提交审核,审核通过后接收方将到账" })
  107. } catch (err) {
  108. try { await conn.rollback() } catch (_) { }
  109. this.logger.error(`赠送乐跑次数失败!${err.message || "未知错误"}`)
  110. return res.json({
  111. ...BaseStdResponse.ERR,
  112. msg: `赠送次数失败,请稍后再试!`
  113. })
  114. } finally {
  115. if (conn?.connection && typeof conn.connection.release === 'function' && typeof conn?.release === 'function') {
  116. conn.release()
  117. }
  118. }
  119. }
  120. }
  121. module.exports.SendCount = SendCount