SendCount.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. })
  74. await conn.commit()
  75. const createTime = new Date().getTime()
  76. // 非阻塞通知管理员,不影响主业务流程
  77. Promise.resolve().then(async () => {
  78. try {
  79. const adminSql = `
  80. SELECT email
  81. FROM users
  82. WHERE email IS NOT NULL
  83. AND email <> ''
  84. AND (JSON_CONTAINS(permission, '"admin"') OR JSON_CONTAINS(permission, '"service"'))
  85. `
  86. const adminRows = await db.query(adminSql)
  87. if (!adminRows || adminRows.length === 0) {
  88. this.logger.warn(`[SendCountNotify][submit][requestId=${requestId}] 未找到可通知的管理员邮箱`)
  89. return
  90. }
  91. const emails = [...new Set(adminRows.map(row => row.email).filter(Boolean))]
  92. for (const email of emails) {
  93. await EmailTemplate.sendCountRequestNotifyAdmins(email, {
  94. requestId,
  95. senderUsername: senderRows[0].username,
  96. receiverUsername: username,
  97. count,
  98. createTime
  99. })
  100. }
  101. } catch (mailErr) {
  102. this.logger.error(`[SendCountNotify][submit][requestId=${requestId}] 管理员通知发送失败:${mailErr.message || "未知错误"}`)
  103. }
  104. })
  105. return res.json({ ...BaseStdResponse.OK, msg: "已提交审核,审核通过后接收方将到账" })
  106. } catch (err) {
  107. try { await conn.rollback() } catch (_) { }
  108. this.logger.error(`赠送乐跑次数失败!${err.message || "未知错误"}`)
  109. return res.json({
  110. ...BaseStdResponse.ERR,
  111. msg: `赠送次数失败,请稍后再试!`
  112. })
  113. } finally {
  114. conn.release()
  115. }
  116. }
  117. }
  118. module.exports.SendCount = SendCount