Transaction.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 : 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 total_deposit, total_withdrawal, total_u_deposit, total_u_withdrawal 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].total_deposit) || 0;
  122. totalWithdrawal = parseFloat(lastRecord[0].total_withdrawal) || 0;
  123. totalUDeposit = parseFloat(lastRecord[0].total_u_deposit) || 0;
  124. totalUWithdrawal = parseFloat(lastRecord[0].total_u_withdrawal) || 0;
  125. }
  126. // 计算本条交易的手续费
  127. const currentFee = Math.abs(transactionData.amount) * (feeRate / 100);
  128. // 计算本条交易的实际金额(减去手续费)
  129. const actualAmount = Math.abs(transactionData.amount) - currentFee;
  130. // 计算本条交易的U币金额
  131. const uAmount = actualAmount / exchangeRate;
  132. // 根据交易类型更新总金额
  133. if (transactionData.type === 'deposit') {
  134. totalDeposit += transactionData.amount;
  135. totalUDeposit += uAmount;
  136. } else {
  137. totalWithdrawal += transactionData.amount;
  138. totalUWithdrawal += uAmount;
  139. }
  140. const [result] = await pool.query(
  141. `INSERT INTO transactions (
  142. group_id, group_name, type, amount, remark, operator_id,
  143. fee_rate, exchange_rate, total_deposit, total_withdrawal,
  144. deposit_fee, withdrawal_fee, total_u_deposit, total_u_withdrawal
  145. ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
  146. [
  147. transactionData.groupId,
  148. transactionData.groupName,
  149. transactionData.type,
  150. transactionData.amount,
  151. transactionData.remark || null,
  152. operatorId,
  153. feeRate,
  154. exchangeRate,
  155. totalDeposit,
  156. totalWithdrawal,
  157. transactionData.type === 'deposit' ? currentFee : 0,
  158. transactionData.type === 'withdrawal' ? currentFee : 0,
  159. totalUDeposit,
  160. totalUWithdrawal
  161. ]
  162. );
  163. return result.insertId;
  164. } catch (error) {
  165. console.error('创建交易记录失败:', error);
  166. throw error;
  167. }
  168. },
  169. // 删除交易
  170. delete: async (id) => {
  171. await pool.query('DELETE FROM transactions WHERE id = ?', [id]);
  172. },
  173. // 获取仪表板数据
  174. getDashboardData: async () => {
  175. try {
  176. // 获取总群组数
  177. const [groupResult] = await pool.query('SELECT COUNT(*) as total FROM groups WHERE is_active = true');
  178. const totalGroups = groupResult[0].total;
  179. // 获取总交易数
  180. const [transactionResult] = await pool.query('SELECT COUNT(*) as total FROM transactions');
  181. const totalTransactions = transactionResult[0].total;
  182. // 获取总金额
  183. const [amountResult] = await pool.query(`
  184. SELECT
  185. SUM(CASE WHEN type = 'deposit' THEN amount ELSE -amount END) as total
  186. FROM transactions
  187. `);
  188. const totalAmount = amountResult[0].total || 0;
  189. // 获取今日交易数
  190. const [todayResult] = await pool.query(`
  191. SELECT COUNT(*) as total
  192. FROM transactions
  193. WHERE DATE(time) = CURDATE()
  194. `);
  195. const todayTransactions = todayResult[0].total;
  196. // 获取最近交易
  197. const [recentTransactions] = await pool.query(`
  198. SELECT
  199. t.*,
  200. u.username as operator_name
  201. FROM transactions t
  202. LEFT JOIN users u ON t.operator_id = u.id
  203. ORDER BY t.time DESC
  204. LIMIT 5
  205. `);
  206. // 获取活跃群组
  207. const [activeGroups] = await pool.query(`
  208. SELECT
  209. g.*,
  210. COUNT(t.id) as transaction_count,
  211. SUM(CASE WHEN t.type = 'deposit' THEN t.amount ELSE 0 END) as total_deposit,
  212. SUM(CASE WHEN t.type = 'withdrawal' THEN t.amount ELSE 0 END) as total_withdrawal
  213. FROM groups g
  214. LEFT JOIN transactions t ON g.group_id = t.group_id
  215. WHERE g.is_active = true
  216. GROUP BY g.id
  217. ORDER BY transaction_count DESC
  218. LIMIT 5
  219. `);
  220. return {
  221. totalGroups,
  222. totalTransactions,
  223. totalAmount,
  224. todayTransactions,
  225. recentTransactions,
  226. activeGroups
  227. };
  228. } catch (error) {
  229. console.error('获取仪表板数据失败:', error);
  230. throw error;
  231. }
  232. },
  233. // 入款方法
  234. deposit: async (transactionData) => {
  235. try {
  236. const id = await Transaction.create({
  237. groupId: transactionData.groupId,
  238. groupName: transactionData.groupName,
  239. type: 'deposit',
  240. amount: parseFloat(transactionData.amount),
  241. operatorId: transactionData.operatorId || 1, // 添加默认操作者ID
  242. feeRate: transactionData.feeRate,
  243. exchangeRate: transactionData.exchangeRate
  244. });
  245. const transaction = await Transaction.findById(id);
  246. if (transaction) {
  247. return {
  248. success: true,
  249. transaction,
  250. message: '入款记录创建成功'
  251. };
  252. } else {
  253. return {
  254. success: false,
  255. message: '入款记录创建失败'
  256. };
  257. }
  258. } catch (error) {
  259. console.error('入款记录创建失败:', error);
  260. return {
  261. success: false,
  262. message: '入款记录创建失败,请稍后重试'
  263. };
  264. }
  265. },
  266. // 出款方法
  267. withdrawal: async (transactionData) => {
  268. try {
  269. const id = await Transaction.create({
  270. groupId: transactionData.groupId,
  271. groupName: transactionData.groupName,
  272. type: 'withdrawal',
  273. amount: parseFloat(transactionData.amount),
  274. operatorId: transactionData.operatorId || 1, // 添加默认操作者ID
  275. feeRate: transactionData.feeRate,
  276. exchangeRate: transactionData.exchangeRate
  277. });
  278. const transaction = await Transaction.findById(id);
  279. if (transaction) {
  280. return {
  281. success: true,
  282. transaction,
  283. message: '出款记录创建成功'
  284. };
  285. } else {
  286. return {
  287. success: false,
  288. message: '出款记录创建失败'
  289. };
  290. }
  291. } catch (error) {
  292. console.error('出款记录创建失败:', error);
  293. return {
  294. success: false,
  295. message: '出款记录创建失败,请稍后重试'
  296. };
  297. }
  298. },
  299. // 查询群组账单
  300. getGroupTransactions: async (groupId, options = {}) => {
  301. const {
  302. startDate,
  303. endDate,
  304. type,
  305. page = 1,
  306. limit = 10
  307. } = options;
  308. let sql = `
  309. SELECT
  310. t.*,
  311. u.username as operator_name,
  312. u.uid as uid,
  313. DATE_FORMAT(t.time, '%Y-%m-%d %H:%i:%s') as formatted_time
  314. FROM transactions t
  315. LEFT JOIN users u ON t.operator_id = u.id
  316. WHERE t.group_id = ?
  317. `;
  318. const params = [groupId];
  319. if (startDate) {
  320. sql += ' AND t.time >= ?';
  321. params.push(startDate);
  322. }
  323. if (endDate) {
  324. sql += ' AND t.time <= ?';
  325. params.push(endDate);
  326. }
  327. if (type) {
  328. sql += ' AND t.type = ?';
  329. params.push(type);
  330. }
  331. // 获取总数
  332. const countSql = `
  333. SELECT COUNT(*) as total
  334. FROM transactions t
  335. WHERE 1=1
  336. ${startDate ? 'AND t.time >= ?' : ''}
  337. ${endDate ? 'AND t.time <= ?' : ''}
  338. ${type ? 'AND t.type = ?' : ''}
  339. ${groupId ? 'AND t.group_id = ?' : ''}
  340. `;
  341. const [countResult] = await pool.query(countSql, params);
  342. const total = countResult[0].total;
  343. // 获取分页数据
  344. sql += ' ORDER BY t.time DESC LIMIT ? OFFSET ?';
  345. params.push(limit, (page - 1) * limit);
  346. const [rows] = await pool.query(sql, params);
  347. // 计算总入款和总出款
  348. const [summary] = await pool.query(`
  349. SELECT
  350. SUM(CASE WHEN type = 'deposit' THEN amount ELSE 0 END) as total_deposit,
  351. SUM(CASE WHEN type = 'withdrawal' THEN amount ELSE 0 END) as total_withdrawal
  352. FROM transactions
  353. WHERE group_id = ?
  354. ${startDate ? 'AND time >= ?' : ''}
  355. ${endDate ? 'AND time <= ?' : ''}
  356. `, [groupId, ...(startDate ? [startDate] : []), ...(endDate ? [endDate] : [])]);
  357. return {
  358. transactions: rows,
  359. total,
  360. page: parseInt(page),
  361. pages: Math.ceil(total / limit),
  362. summary: {
  363. totalDeposit: summary[0].total_deposit || 0,
  364. totalWithdrawal: summary[0].total_withdrawal || 0,
  365. balance: (summary[0].total_deposit || 0) - (summary[0].total_withdrawal || 0)
  366. }
  367. };
  368. },
  369. // 根据ID查找交易记录
  370. findById: async (id) => {
  371. try {
  372. const [rows] = await pool.query(`
  373. SELECT
  374. t.*,
  375. u.username as operator_name
  376. FROM transactions t
  377. LEFT JOIN users u ON t.operator_id = u.id
  378. WHERE t.id = ?
  379. `, [id]);
  380. return rows[0] || null;
  381. } catch (error) {
  382. console.error('查询交易记录失败:', error);
  383. return null;
  384. }
  385. }
  386. };
  387. module.exports = Transaction;