Transaction.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. g.group_name
  44. FROM transactions t
  45. LEFT JOIN users u ON t.operator_id = u.id
  46. LEFT JOIN groups g ON t.group_id = g.group_id
  47. WHERE 1=1
  48. `;
  49. const params = [];
  50. if (query.groupId) {
  51. sql += ' AND t.group_id = ?';
  52. params.push(query.groupId);
  53. }
  54. if (query.type) {
  55. sql += ' AND t.type = ?';
  56. params.push(query.type);
  57. }
  58. if (query.startDate) {
  59. sql += ' AND DATE(t.time) >= ?';
  60. params.push(query.startDate);
  61. }
  62. if (query.endDate) {
  63. sql += ' AND DATE(t.time) <= ?';
  64. params.push(query.endDate);
  65. }
  66. // 获取总记录数
  67. const [countResult] = await pool.query(
  68. sql.replace('t.*,', 'COUNT(*) as total,'),
  69. params
  70. );
  71. const total = countResult[0].total;
  72. // 添加排序和分页
  73. sql += ' ORDER BY t.time DESC LIMIT ? OFFSET ?';
  74. params.push(limit, offset);
  75. const [rows] = await pool.query(sql, params);
  76. return {
  77. transactions: rows,
  78. total,
  79. page: parseInt(page),
  80. pages: Math.ceil(total / limit)
  81. };
  82. } catch (error) {
  83. console.error('查询交易列表失败:', error);
  84. throw error;
  85. }
  86. },
  87. // 创建交易
  88. create: async (transactionData) => {
  89. try {
  90. // 获取群组的默认费率和汇率
  91. const [groupInfo] = await pool.query(
  92. 'SELECT in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate FROM groups WHERE group_id = ?',
  93. [transactionData.groupId]
  94. );
  95. if (!groupInfo || groupInfo.length === 0) {
  96. throw new Error('群组不存在');
  97. }
  98. // 根据交易类型选择对应的费率和汇率
  99. const defaultFeeRate = transactionData.type === 'deposit' ?
  100. groupInfo[0].in_fee_rate : groupInfo[0].out_fee_rate;
  101. const defaultExchangeRate = transactionData.type === 'deposit' ?
  102. groupInfo[0].in_exchange_rate : groupInfo[0].out_exchange_rate;
  103. // 使用指定的费率和汇率,如果没有指定则使用默认值
  104. const feeRate = transactionData.feeRate || defaultFeeRate;
  105. const exchangeRate = transactionData.exchangeRate || defaultExchangeRate;
  106. // 使用群内操作人的ID作为operator_id
  107. const operatorId = transactionData.operatorId || 1;
  108. const [result] = await pool.query(
  109. 'INSERT INTO transactions (group_id, group_name, type, amount, remark, operator_id, fee_rate, exchange_rate) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
  110. [
  111. transactionData.groupId,
  112. transactionData.groupName,
  113. transactionData.type,
  114. transactionData.amount,
  115. transactionData.remark || null,
  116. operatorId, // 使用群内操作人的ID
  117. feeRate,
  118. exchangeRate
  119. ]
  120. );
  121. return result.insertId;
  122. } catch (error) {
  123. console.error('创建交易记录失败:', error);
  124. throw error;
  125. }
  126. },
  127. // 删除交易
  128. delete: async (id) => {
  129. await pool.query('DELETE FROM transactions WHERE id = ?', [id]);
  130. },
  131. // 获取仪表板数据
  132. getDashboardData: async () => {
  133. try {
  134. // 获取总群组数
  135. const [groupResult] = await pool.query('SELECT COUNT(*) as total FROM groups WHERE is_active = true');
  136. const totalGroups = groupResult[0].total;
  137. // 获取总交易数
  138. const [transactionResult] = await pool.query('SELECT COUNT(*) as total FROM transactions');
  139. const totalTransactions = transactionResult[0].total;
  140. // 获取总金额
  141. const [amountResult] = await pool.query(`
  142. SELECT
  143. SUM(CASE WHEN type = 'deposit' THEN amount ELSE -amount END) as total
  144. FROM transactions
  145. `);
  146. const totalAmount = amountResult[0].total || 0;
  147. // 获取今日交易数
  148. const [todayResult] = await pool.query(`
  149. SELECT COUNT(*) as total
  150. FROM transactions
  151. WHERE DATE(time) = CURDATE()
  152. `);
  153. const todayTransactions = todayResult[0].total;
  154. // 获取最近交易
  155. const [recentTransactions] = await pool.query(`
  156. SELECT
  157. t.*,
  158. u.username as operator_name
  159. FROM transactions t
  160. LEFT JOIN users u ON t.operator_id = u.id
  161. ORDER BY t.time DESC
  162. LIMIT 5
  163. `);
  164. // 获取活跃群组
  165. const [activeGroups] = await pool.query(`
  166. SELECT
  167. g.*,
  168. COUNT(t.id) as transaction_count,
  169. SUM(CASE WHEN t.type = 'deposit' THEN t.amount ELSE 0 END) as total_deposit,
  170. SUM(CASE WHEN t.type = 'withdrawal' THEN t.amount ELSE 0 END) as total_withdrawal
  171. FROM groups g
  172. LEFT JOIN transactions t ON g.group_id = t.group_id
  173. WHERE g.is_active = true
  174. GROUP BY g.id
  175. ORDER BY transaction_count DESC
  176. LIMIT 5
  177. `);
  178. return {
  179. totalGroups,
  180. totalTransactions,
  181. totalAmount,
  182. todayTransactions,
  183. recentTransactions,
  184. activeGroups
  185. };
  186. } catch (error) {
  187. console.error('获取仪表板数据失败:', error);
  188. throw error;
  189. }
  190. },
  191. // 入款方法
  192. deposit: async (transactionData) => {
  193. try {
  194. const id = await Transaction.create({
  195. groupId: transactionData.groupId,
  196. groupName: transactionData.groupName,
  197. type: 'deposit',
  198. amount: parseFloat(transactionData.amount),
  199. operatorId: transactionData.operatorId || 1, // 添加默认操作者ID
  200. feeRate: transactionData.feeRate,
  201. exchangeRate: transactionData.exchangeRate
  202. });
  203. const transaction = await Transaction.findById(id);
  204. if (transaction) {
  205. return {
  206. success: true,
  207. transaction,
  208. message: '入款记录创建成功'
  209. };
  210. } else {
  211. return {
  212. success: false,
  213. message: '入款记录创建失败'
  214. };
  215. }
  216. } catch (error) {
  217. console.error('入款记录创建失败:', error);
  218. return {
  219. success: false,
  220. message: '入款记录创建失败,请稍后重试'
  221. };
  222. }
  223. },
  224. // 出款方法
  225. withdrawal: async (transactionData) => {
  226. try {
  227. const id = await Transaction.create({
  228. groupId: transactionData.groupId,
  229. groupName: transactionData.groupName,
  230. type: 'withdrawal',
  231. amount: parseFloat(transactionData.amount),
  232. operatorId: transactionData.operatorId || 1, // 添加默认操作者ID
  233. feeRate: transactionData.feeRate,
  234. exchangeRate: transactionData.exchangeRate
  235. });
  236. const transaction = await Transaction.findById(id);
  237. if (transaction) {
  238. return {
  239. success: true,
  240. transaction,
  241. message: '出款记录创建成功'
  242. };
  243. } else {
  244. return {
  245. success: false,
  246. message: '出款记录创建失败'
  247. };
  248. }
  249. } catch (error) {
  250. console.error('出款记录创建失败:', error);
  251. return {
  252. success: false,
  253. message: '出款记录创建失败,请稍后重试'
  254. };
  255. }
  256. },
  257. // 查询群组账单
  258. getGroupTransactions: async (groupId, options = {}) => {
  259. const {
  260. startDate,
  261. endDate,
  262. type,
  263. page = 1,
  264. limit = 10
  265. } = options;
  266. let sql = `
  267. SELECT
  268. t.*,
  269. u.username as operator_name,
  270. DATE_FORMAT(t.time, '%Y-%m-%d %H:%i:%s') as formatted_time
  271. FROM transactions t
  272. LEFT JOIN users u ON t.operator_id = u.id
  273. WHERE t.group_id = ?
  274. `;
  275. const params = [groupId];
  276. if (startDate) {
  277. sql += ' AND t.time >= ?';
  278. params.push(startDate);
  279. }
  280. if (endDate) {
  281. sql += ' AND t.time <= ?';
  282. params.push(endDate);
  283. }
  284. if (type) {
  285. sql += ' AND t.type = ?';
  286. params.push(type);
  287. }
  288. // 获取总数
  289. const countSql = `
  290. SELECT COUNT(*) as total
  291. FROM transactions t
  292. WHERE 1=1
  293. ${startDate ? 'AND t.time >= ?' : ''}
  294. ${endDate ? 'AND t.time <= ?' : ''}
  295. ${type ? 'AND t.type = ?' : ''}
  296. ${groupId ? 'AND t.group_id = ?' : ''}
  297. `;
  298. const [countResult] = await pool.query(countSql, params);
  299. const total = countResult[0].total;
  300. // 获取分页数据
  301. sql += ' ORDER BY t.time DESC LIMIT ? OFFSET ?';
  302. params.push(limit, (page - 1) * limit);
  303. const [rows] = await pool.query(sql, params);
  304. // 计算总入款和总出款
  305. const [summary] = await pool.query(`
  306. SELECT
  307. SUM(CASE WHEN type = 'deposit' THEN amount ELSE 0 END) as total_deposit,
  308. SUM(CASE WHEN type = 'withdrawal' THEN amount ELSE 0 END) as total_withdrawal
  309. FROM transactions
  310. WHERE group_id = ?
  311. ${startDate ? 'AND time >= ?' : ''}
  312. ${endDate ? 'AND time <= ?' : ''}
  313. `, [groupId, ...(startDate ? [startDate] : []), ...(endDate ? [endDate] : [])]);
  314. return {
  315. transactions: rows,
  316. total,
  317. page: parseInt(page),
  318. pages: Math.ceil(total / limit),
  319. summary: {
  320. totalDeposit: summary[0].total_deposit || 0,
  321. totalWithdrawal: summary[0].total_withdrawal || 0,
  322. balance: (summary[0].total_deposit || 0) - (summary[0].total_withdrawal || 0)
  323. }
  324. };
  325. },
  326. // 根据ID查找交易记录
  327. findById: async (id) => {
  328. try {
  329. const [rows] = await pool.query(`
  330. SELECT
  331. t.*,
  332. u.username as operator_name
  333. FROM transactions t
  334. LEFT JOIN users u ON t.operator_id = u.id
  335. WHERE t.id = ?
  336. `, [id]);
  337. return rows[0] || null;
  338. } catch (error) {
  339. console.error('查询交易记录失败:', error);
  340. return null;
  341. }
  342. }
  343. };
  344. module.exports = Transaction;