Transaction.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 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. 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, totalDeposit, totalWithdrawal,
  144. depositFee, withdrawalFee, totalUDeposit, totalUWithdrawal
  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. deposit: async (transactionData) => {
  175. try {
  176. const id = await Transaction.create({
  177. groupId: transactionData.groupId,
  178. groupName: transactionData.groupName,
  179. type: 'deposit',
  180. amount: parseFloat(transactionData.amount),
  181. operatorId: transactionData.operatorId || 1, // 添加默认操作者ID
  182. feeRate: transactionData.feeRate,
  183. exchangeRate: transactionData.exchangeRate
  184. });
  185. const transaction = await Transaction.findById(id);
  186. if (transaction) {
  187. return {
  188. success: true,
  189. transaction,
  190. message: '入款记录创建成功'
  191. };
  192. } else {
  193. return {
  194. success: false,
  195. message: '入款记录创建失败'
  196. };
  197. }
  198. } catch (error) {
  199. console.error('入款记录创建失败:', error);
  200. return {
  201. success: false,
  202. message: '入款记录创建失败,请稍后重试'
  203. };
  204. }
  205. },
  206. // 出款方法
  207. withdrawal: async (transactionData) => {
  208. try {
  209. const id = await Transaction.create({
  210. groupId: transactionData.groupId,
  211. groupName: transactionData.groupName,
  212. type: 'withdrawal',
  213. amount: parseFloat(transactionData.amount),
  214. operatorId: transactionData.operatorId || 1, // 添加默认操作者ID
  215. feeRate: transactionData.feeRate,
  216. exchangeRate: transactionData.exchangeRate
  217. });
  218. const transaction = await Transaction.findById(id);
  219. if (transaction) {
  220. return {
  221. success: true,
  222. transaction,
  223. message: '出款记录创建成功'
  224. };
  225. } else {
  226. return {
  227. success: false,
  228. message: '出款记录创建失败'
  229. };
  230. }
  231. } catch (error) {
  232. console.error('出款记录创建失败:', error);
  233. return {
  234. success: false,
  235. message: '出款记录创建失败,请稍后重试'
  236. };
  237. }
  238. },
  239. // 查询群组账单
  240. getGroupTransactions: async (groupId, options = {}) => {
  241. const {
  242. startDate,
  243. endDate,
  244. type,
  245. page = 1,
  246. limit = 10
  247. } = options;
  248. let sql = `
  249. SELECT
  250. t.*,
  251. u.username as operator_name,
  252. u.uid as uid,
  253. DATE_FORMAT(t.time, '%Y-%m-%d %H:%i:%s') as formatted_time
  254. FROM transactions t
  255. LEFT JOIN users u ON t.operator_id = u.id
  256. WHERE t.group_id = ?
  257. `;
  258. const params = [groupId];
  259. if (startDate) {
  260. sql += ' AND t.time >= ?';
  261. params.push(startDate);
  262. }
  263. if (endDate) {
  264. sql += ' AND t.time <= ?';
  265. params.push(endDate);
  266. }
  267. if (type) {
  268. sql += ' AND t.type = ?';
  269. params.push(type);
  270. }
  271. // 获取总数
  272. const countSql = `
  273. SELECT COUNT(*) as total
  274. FROM transactions t
  275. WHERE 1=1
  276. ${startDate ? 'AND t.time >= ?' : ''}
  277. ${endDate ? 'AND t.time <= ?' : ''}
  278. ${type ? 'AND t.type = ?' : ''}
  279. ${groupId ? 'AND t.group_id = ?' : ''}
  280. `;
  281. const [countResult] = await pool.query(countSql, params);
  282. const total = countResult[0].total;
  283. // 获取分页数据
  284. sql += ' ORDER BY t.time DESC LIMIT ? OFFSET ?';
  285. params.push(limit, (page - 1) * limit);
  286. const [rows] = await pool.query(sql, params);
  287. // 计算总入款和总出款
  288. const [summary] = await pool.query(`
  289. SELECT
  290. SUM(CASE WHEN type = 'deposit' THEN amount ELSE 0 END) as total_deposit,
  291. SUM(CASE WHEN type = 'withdrawal' THEN amount ELSE 0 END) as total_withdrawal
  292. FROM transactions
  293. WHERE group_id = ?
  294. ${startDate ? 'AND time >= ?' : ''}
  295. ${endDate ? 'AND time <= ?' : ''}
  296. `, [groupId, ...(startDate ? [startDate] : []), ...(endDate ? [endDate] : [])]);
  297. return {
  298. transactions: rows,
  299. total,
  300. page: parseInt(page),
  301. pages: Math.ceil(total / limit),
  302. summary: {
  303. totalDeposit: summary[0].total_deposit || 0,
  304. totalWithdrawal: summary[0].total_withdrawal || 0,
  305. balance: (summary[0].total_deposit || 0) - (summary[0].total_withdrawal || 0)
  306. }
  307. };
  308. },
  309. // 根据ID查找交易记录
  310. findById: async (id) => {
  311. try {
  312. const [rows] = await pool.query(`
  313. SELECT
  314. t.*,
  315. u.username as operator_name
  316. FROM transactions t
  317. LEFT JOIN users u ON t.operator_id = u.id
  318. WHERE t.id = ?
  319. `, [id]);
  320. return rows[0] || null;
  321. } catch (error) {
  322. console.error('查询交易记录失败:', error);
  323. return null;
  324. }
  325. }
  326. };
  327. module.exports = Transaction;