Transaction.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. const { pool } = require('../config/database');
  2. // 创建交易表
  3. const createTransactionTable = async () => {
  4. try {
  5. // 先检查表是否存在
  6. const [tables] = await pool.query('SHOW TABLES LIKE "transactions"');
  7. if (tables.length === 0) {
  8. // 如果表不存在,创建新表
  9. await pool.query(`
  10. CREATE TABLE transactions (
  11. id INT AUTO_INCREMENT PRIMARY KEY,
  12. group_id VARCHAR(50) NOT NULL,
  13. group_name VARCHAR(100) NOT NULL,
  14. type ENUM('deposit', 'withdrawal') NOT NULL COMMENT 'deposit:入款,withdrawal:出款',
  15. amount DECIMAL(10,2) NOT NULL,
  16. time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  17. remark VARCHAR(255) DEFAULT NULL COMMENT '备注',
  18. operator_id VARCHAR(50) NOT NULL COMMENT '操作人ID',
  19. fee_rate DECIMAL(5,2) DEFAULT NULL COMMENT '费率',
  20. exchange_rate DECIMAL(10,4) DEFAULT NULL COMMENT '汇率',
  21. INDEX idx_group_time (group_id, time),
  22. FOREIGN KEY (operator_id) REFERENCES users(id)
  23. )
  24. `);
  25. console.log('交易表创建成功');
  26. }
  27. } catch (error) {
  28. console.error('创建交易表失败:', error);
  29. throw error;
  30. }
  31. };
  32. // 初始化表
  33. createTransactionTable();
  34. const Transaction = {
  35. // 获取交易列表
  36. findAll: async (query = {}, page = 1, limit = 10) => {
  37. try {
  38. const offset = (page - 1) * limit;
  39. let sql = `
  40. SELECT
  41. t.*,
  42. u.username as operator_name,
  43. u.uid as uid,
  44. g.group_name
  45. FROM transactions t
  46. LEFT JOIN users u ON t.operator_id = u.id
  47. LEFT JOIN groups g ON t.group_id = g.group_id
  48. WHERE 1=1
  49. `;
  50. const params = [];
  51. if (query.groupId) {
  52. sql += ' AND t.group_id = ?';
  53. params.push(query.groupId);
  54. }
  55. if (query.type) {
  56. sql += ' AND t.type = ?';
  57. params.push(query.type);
  58. }
  59. if (query.startDate) {
  60. sql += ' AND DATE(t.time) >= ?';
  61. params.push(query.startDate);
  62. }
  63. if (query.endDate) {
  64. sql += ' AND DATE(t.time) <= ?';
  65. params.push(query.endDate);
  66. }
  67. // 获取总记录数
  68. const [countResult] = await pool.query(
  69. sql.replace('t.*,', 'COUNT(*) as total,'),
  70. params
  71. );
  72. const total = countResult[0].total;
  73. // 添加排序和分页
  74. sql += ' ORDER BY t.time DESC LIMIT ? OFFSET ?';
  75. params.push(limit, offset);
  76. const [rows] = await pool.query(sql, params);
  77. return {
  78. transactions: rows,
  79. total,
  80. page: parseInt(page),
  81. pages: Math.ceil(total / limit)
  82. };
  83. } catch (error) {
  84. console.error('查询交易列表失败:', error);
  85. throw error;
  86. }
  87. },
  88. // 创建交易
  89. create: async (transactionData) => {
  90. try {
  91. // 获取群组的默认费率和汇率
  92. const [groupInfo] = await pool.query(
  93. 'SELECT in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate FROM groups WHERE group_id = ?',
  94. [transactionData.groupId]
  95. );
  96. if (!groupInfo || groupInfo.length === 0) {
  97. throw new Error('群组不存在');
  98. }
  99. // 根据交易类型选择对应的费率和汇率
  100. const defaultFeeRate = transactionData.type === 'deposit' ?
  101. groupInfo[0].in_fee_rate : parseFloat(groupInfo[0].out_fee_rate);
  102. const defaultExchangeRate = transactionData.type === 'deposit' ?
  103. groupInfo[0].in_exchange_rate : groupInfo[0].out_exchange_rate;
  104. // 使用指定的费率和汇率,如果没有指定则使用默认值
  105. const feeRate = transactionData.feeRate || defaultFeeRate;
  106. const exchangeRate = transactionData.exchangeRate || defaultExchangeRate;
  107. // 使用群内操作人的ID作为operator_id
  108. const operatorId = transactionData.operatorId || 1;
  109. // 获取上一条记录的总金额数据
  110. const [lastRecord] = await pool.query(
  111. 'SELECT totalDeposit, totalWithdrawal, totalUDeposit, totalUWithdrawal FROM transactions WHERE group_id = ? ORDER BY time DESC LIMIT 1',
  112. [transactionData.groupId]
  113. );
  114. // 初始化总金额数据
  115. let totalDeposit = 0;
  116. let totalWithdrawal = 0;
  117. let totalUDeposit = 0;
  118. let totalUWithdrawal = 0;
  119. // 如果有上一条记录,使用其数据
  120. if (lastRecord && lastRecord.length > 0) {
  121. totalDeposit = parseFloat(lastRecord[0].totalDeposit) || 0;
  122. totalWithdrawal = parseFloat(lastRecord[0].totalWithdrawal) || 0;
  123. totalUDeposit = parseFloat(lastRecord[0].totalUDeposit) || 0;
  124. totalUWithdrawal = parseFloat(lastRecord[0].totalUWithdrawal) || 0;
  125. }
  126. // 计算本条交易的手续费和实际金额
  127. let currentFee = 0;
  128. let actualAmount = 0;
  129. if (transactionData.type === 'deposit') {
  130. // 入款:手续费 = 金额 * 费率
  131. currentFee = Math.abs(transactionData.amount) * (feeRate / 100);
  132. actualAmount = Math.abs(transactionData.amount) - currentFee;
  133. } else {
  134. // 出款:实际金额 = 金额 * (1 + 费率)
  135. actualAmount = Math.abs(transactionData.amount) * (1 + feeRate / 100);
  136. currentFee = actualAmount - Math.abs(transactionData.amount);
  137. }
  138. // 计算本条交易的U币金额(保持与金额相同的正负号)
  139. const uAmount = (actualAmount / exchangeRate) * (transactionData.amount < 0 ? -1 : 1);
  140. // 根据交易类型更新总金额
  141. if (transactionData.type === 'deposit') {
  142. totalDeposit += transactionData.amount;
  143. totalUDeposit += uAmount;
  144. } else {
  145. totalWithdrawal += transactionData.amount;
  146. totalUWithdrawal += uAmount;
  147. }
  148. const [result] = await pool.query(
  149. `INSERT INTO transactions (
  150. group_id, group_name, type, amount, remark, operator_id,
  151. fee_rate, exchange_rate, totalDeposit, totalWithdrawal,
  152. depositFee, withdrawalFee, totalUDeposit, totalUWithdrawal
  153. ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
  154. [
  155. transactionData.groupId,
  156. transactionData.groupName,
  157. transactionData.type,
  158. transactionData.amount,
  159. transactionData.remark || null,
  160. operatorId,
  161. feeRate,
  162. exchangeRate,
  163. totalDeposit,
  164. totalWithdrawal,
  165. transactionData.type === 'deposit' ? currentFee : 0,
  166. transactionData.type === 'withdrawal' ? currentFee : 0,
  167. totalUDeposit,
  168. totalUWithdrawal
  169. ]
  170. );
  171. return result.insertId;
  172. } catch (error) {
  173. console.error('创建交易记录失败:', error);
  174. throw error;
  175. }
  176. },
  177. // 删除交易
  178. delete: async (id) => {
  179. await pool.query('DELETE FROM transactions WHERE id = ?', [id]);
  180. },
  181. // 入款方法
  182. deposit: async (transactionData) => {
  183. try {
  184. const id = await Transaction.create({
  185. groupId: transactionData.groupId,
  186. groupName: transactionData.groupName,
  187. type: 'deposit',
  188. amount: parseFloat(transactionData.amount),
  189. operatorId: transactionData.operatorId || 1, // 添加默认操作者ID
  190. feeRate: transactionData.feeRate,
  191. exchangeRate: transactionData.exchangeRate
  192. });
  193. const transaction = await Transaction.findById(id);
  194. if (transaction) {
  195. return {
  196. success: true,
  197. transaction,
  198. message: '入款记录创建成功'
  199. };
  200. } else {
  201. return {
  202. success: false,
  203. message: '入款记录创建失败'
  204. };
  205. }
  206. } catch (error) {
  207. console.error('入款记录创建失败:', error);
  208. return {
  209. success: false,
  210. message: '入款记录创建失败,请稍后重试'
  211. };
  212. }
  213. },
  214. // 出款方法
  215. withdrawal: async (transactionData) => {
  216. try {
  217. const id = await Transaction.create({
  218. groupId: transactionData.groupId,
  219. groupName: transactionData.groupName,
  220. type: 'withdrawal',
  221. amount: parseFloat(transactionData.amount),
  222. operatorId: transactionData.operatorId || 1, // 添加默认操作者ID
  223. feeRate: transactionData.feeRate,
  224. exchangeRate: transactionData.exchangeRate
  225. });
  226. const transaction = await Transaction.findById(id);
  227. if (transaction) {
  228. return {
  229. success: true,
  230. transaction,
  231. message: '出款记录创建成功'
  232. };
  233. } else {
  234. return {
  235. success: false,
  236. message: '出款记录创建失败'
  237. };
  238. }
  239. } catch (error) {
  240. console.error('出款记录创建失败:', error);
  241. return {
  242. success: false,
  243. message: '出款记录创建失败,请稍后重试'
  244. };
  245. }
  246. },
  247. // 下发方法
  248. distribute: async (transactionData) => {
  249. try {
  250. // 获取上一条记录的总金额数据
  251. const [lastRecord] = await pool.query(
  252. 'SELECT totalDeposit, totalWithdrawal, totalUDeposit, totalUWithdrawal FROM transactions WHERE group_id = ? ORDER BY time DESC LIMIT 1',
  253. [transactionData.groupId]
  254. );
  255. // 初始化总金额数据
  256. let totalDeposit = 0;
  257. let totalWithdrawal = 0;
  258. let totalUDeposit = 0;
  259. let totalUWithdrawal = 0;
  260. // 如果有上一条记录,使用其数据
  261. if (lastRecord && lastRecord.length > 0) {
  262. totalDeposit = parseFloat(lastRecord[0].totalDeposit) || 0;
  263. totalWithdrawal = parseFloat(lastRecord[0].totalWithdrawal) || 0;
  264. totalUDeposit = parseFloat(lastRecord[0].totalUDeposit) || 0;
  265. totalUWithdrawal = parseFloat(lastRecord[0].totalUWithdrawal) || 0;
  266. }
  267. // 下发金额直接使用输入的U币金额
  268. const uAmount = parseFloat(transactionData.amount);
  269. // 更新总金额
  270. totalUWithdrawal += uAmount; // 累加下发金额
  271. const [result] = await pool.query(
  272. `INSERT INTO transactions (
  273. group_id, group_name, type, amount, remark, operator_id,
  274. fee_rate, exchange_rate, totalDeposit, totalWithdrawal,
  275. depositFee, withdrawalFee, totalUDeposit, totalUWithdrawal
  276. ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
  277. [
  278. transactionData.groupId,
  279. transactionData.groupName,
  280. 'distribute', // 使用withdrawal类型,因为distribute类型还未添加
  281. uAmount,
  282. transactionData.remark || null,
  283. transactionData.operatorId || 1,
  284. 0, // fee_rate
  285. 1, // exchange_rate
  286. totalDeposit,
  287. totalWithdrawal,
  288. 0, // depositFee
  289. 0, // withdrawalFee
  290. totalUDeposit,
  291. totalUWithdrawal
  292. ]
  293. );
  294. const transaction = await Transaction.findById(result.insertId);
  295. if (transaction) {
  296. return {
  297. success: true,
  298. transaction,
  299. message: '下发记录创建成功'
  300. };
  301. } else {
  302. return {
  303. success: false,
  304. message: '下发记录创建失败'
  305. };
  306. }
  307. } catch (error) {
  308. console.error('下发记录创建失败:', error);
  309. return {
  310. success: false,
  311. message: '下发记录创建失败,请稍后重试'
  312. };
  313. }
  314. },
  315. // 查询群组账单
  316. getGroupTransactions: async (groupId, options = {}) => {
  317. const {
  318. startDate,
  319. endDate,
  320. type,
  321. page = 1,
  322. limit = 10
  323. } = options;
  324. let sql = `
  325. SELECT
  326. t.*,
  327. u.username as operator_name,
  328. u.uid as uid,
  329. DATE_FORMAT(t.time, '%Y-%m-%d %H:%i:%s') as formatted_time
  330. FROM transactions t
  331. LEFT JOIN users u ON t.operator_id = u.id
  332. WHERE t.group_id = ?
  333. `;
  334. const params = [groupId];
  335. if (startDate) {
  336. sql += ' AND t.time >= ?';
  337. params.push(startDate);
  338. }
  339. if (endDate) {
  340. sql += ' AND t.time <= ?';
  341. params.push(endDate);
  342. }
  343. if (type) {
  344. sql += ' AND t.type = ?';
  345. params.push(type);
  346. }
  347. // 获取总数
  348. const countSql = `
  349. SELECT COUNT(*) as total
  350. FROM transactions t
  351. WHERE 1=1
  352. ${startDate ? 'AND t.time >= ?' : ''}
  353. ${endDate ? 'AND t.time <= ?' : ''}
  354. ${type ? 'AND t.type = ?' : ''}
  355. ${groupId ? 'AND t.group_id = ?' : ''}
  356. `;
  357. const [countResult] = await pool.query(countSql, params);
  358. const total = countResult[0].total;
  359. // 获取分页数据
  360. sql += ' ORDER BY t.time DESC LIMIT ? OFFSET ?';
  361. params.push(limit, (page - 1) * limit);
  362. const [rows] = await pool.query(sql, params);
  363. // 计算总入款和总出款
  364. const [summary] = await pool.query(`
  365. SELECT
  366. SUM(CASE WHEN type = 'deposit' THEN amount ELSE 0 END) as total_deposit,
  367. SUM(CASE WHEN type = 'withdrawal' THEN amount ELSE 0 END) as total_withdrawal
  368. FROM transactions
  369. WHERE group_id = ?
  370. ${startDate ? 'AND time >= ?' : ''}
  371. ${endDate ? 'AND time <= ?' : ''}
  372. `, [groupId, ...(startDate ? [startDate] : []), ...(endDate ? [endDate] : [])]);
  373. return {
  374. transactions: rows,
  375. total,
  376. page: parseInt(page),
  377. pages: Math.ceil(total / limit),
  378. summary: {
  379. totalDeposit: summary[0].total_deposit || 0,
  380. totalWithdrawal: summary[0].total_withdrawal || 0,
  381. balance: (summary[0].total_deposit || 0) - (summary[0].total_withdrawal || 0)
  382. }
  383. };
  384. },
  385. // 根据ID查找交易记录
  386. findById: async (id) => {
  387. try {
  388. const [rows] = await pool.query(`
  389. SELECT
  390. t.*,
  391. u.username as operator_name
  392. FROM transactions t
  393. LEFT JOIN users u ON t.operator_id = u.id
  394. WHERE t.id = ?
  395. `, [id]);
  396. return rows[0] || null;
  397. } catch (error) {
  398. console.error('查询交易记录失败:', error);
  399. return null;
  400. }
  401. }
  402. };
  403. module.exports = Transaction;