Transaction.js 13 KB

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