const db = require('../config/db'); const { logger } = require('../util/logger'); async function total_users(from_date, to_date) { try { const result = await db.query( `SELECT * FROM users WHERE created_at BETWEEN $1 AND $2`, [from_date, to_date] ); logger.info("data fetch for users"); return result.rows; } catch (err) { logger.error(err, 'failed to fetch data'); res.status(500).json({ error: 'something went wrong' }); } } async function getTransactions(filters) { try { const { trx_type, from_date, to_date, client, amount_min, amount_max, customer_no } = filters; let query = `SELECT * FROM transactions WHERE trx_type = $1 AND created_at >= $2 AND created_at < $3`; const params = [trx_type, from_date, to_date]; let paramIndex = 4; if (client) { query += ` AND client = $${paramIndex++}`; params.push(client); } if (amount_min && amount_max) { query += ` AND amount BETWEEN $${paramIndex++} AND $${paramIndex++}`; params.push(amount_min, amount_max); } else if (amount_min) { query += ` AND amount >= $${paramIndex++}`; params.push(amount_min); } else if (amount_max) { query += ` AND amount <= $${paramIndex++}`; params.push(amount_max); } if (customer_no) { query += ` AND customer_no = $${paramIndex++}`; params.push(customer_no); } query += ` ORDER BY created_at DESC`; const result = await db.query(query, params); logger.info(`Fetched ${result.rows.length} transactions`); return result.rows; } catch (err) { logger.error(err, 'failed to fetch transactions'); throw err; } } async function getFailedTransactions(filters) { try { const { from_date, to_date, customer_no } = filters; let query = ` SELECT * FROM transactions WHERE created_at >= $1 AND created_at < $2 AND status LIKE 'FAILURE%'`; // params should match $1, $2, etc. const params = [from_date, to_date]; let paramIndex = params.length + 1; // start from 3 if (customer_no) { query += ` AND customer_no = $${paramIndex}`; params.push(customer_no); } query += ` ORDER BY created_at DESC`; console.log(query); const result = await db.query(query, params); logger.info(`Fetched ${result.rows.length} failed transactions`); return result.rows; } catch (err) { logger.error(err, 'Failed to fetch failed transactions'); throw err; } } async function getNotLogin(duration) { try { const result = await db.query( `SELECT * FROM users WHERE last_login <= NOW() - ($1 || ' month')::interval`, [duration] ); logger.info("data fetch for users who have not logged-in in mentioned duration"); return result.rows; } catch (err) { logger.error(err, 'failed to fetch not logged-in users data'); res.status(500).json({ error: 'something went wrong' }); } } module.exports = { total_users, getTransactions, getFailedTransactions, getNotLogin };