Compare commits
30 Commits
feat-daily
...
admin_feat
| Author | SHA1 | Date | |
|---|---|---|---|
| c481e4f139 | |||
| 12750e833c | |||
| 7e162e741d | |||
| b0c9cb8038 | |||
| a8a576f5c1 | |||
| 759869b0e3 | |||
| 3262ff53bf | |||
| 739f2737ba | |||
| 6b80ef83b4 | |||
| a28c08f8b2 | |||
| 1ebe666bb3 | |||
| f922179765 | |||
| b9c9d35f74 | |||
| c39492edde | |||
| 3f86697f6b | |||
| c021d6033c | |||
| 55c822487b | |||
| 0164aad402 | |||
| f7bc0f6785 | |||
| 95fc26ef6b | |||
| caef3bd690 | |||
| 689b00aec7 | |||
| 56c69e54de | |||
| 2c210f07c7 | |||
| ea1d7dae85 | |||
| a53bca4a34 | |||
| 43cce9f04a | |||
| 05db88f409 | |||
| 2cc1f3fcad | |||
| f807f62660 |
2
.vscode/settings.json
vendored
2
.vscode/settings.json
vendored
@@ -1,8 +1,10 @@
|
||||
{
|
||||
"cSpell.words": [
|
||||
"emandate",
|
||||
"MPIN",
|
||||
"occured",
|
||||
"otpgenerator",
|
||||
"TLIMIT",
|
||||
"tpassword",
|
||||
"tpin",
|
||||
"TPWORD"
|
||||
|
||||
@@ -6,5 +6,6 @@ dotenv.config({ path: path.resolve(__dirname, '../../.env') });
|
||||
module.exports = {
|
||||
port: process.env.PORT || 8080,
|
||||
dbUrl: process.env.DATABASE_URL,
|
||||
redisUrl: process.env.REDIS_URL,
|
||||
jwtSecret: process.env.JWT_SECRET,
|
||||
};
|
||||
|
||||
@@ -62,6 +62,7 @@ async function getUserDetails(req, res) {
|
||||
res.status(500).json({ error: 'invalid CIF number' });
|
||||
}
|
||||
}
|
||||
|
||||
async function getUserRights(req, res) {
|
||||
const { CIF } = req.query;
|
||||
if (!CIF) {
|
||||
@@ -71,13 +72,13 @@ async function getUserRights(req, res) {
|
||||
}
|
||||
const userDetails = await adminAuthService.getCustomerDetailsFromDB(CIF);
|
||||
if (!userDetails)
|
||||
return res.status(401).json({ error: 'invalid CIF number or No rights is present for the user.' });
|
||||
return res.status(404).json({ error: 'invalid CIF number or No rights is present for the user.' });
|
||||
return res.json(userDetails);
|
||||
}
|
||||
|
||||
async function UserRights(req, res) {
|
||||
try {
|
||||
const { CIF, ib_access_level, mb_access_level } = req.body;
|
||||
const { CIF, ib_access_level, mb_access_level, ib_limit, mb_limit } = req.body;
|
||||
|
||||
if (!CIF) {
|
||||
return res.status(400).json({ error: 'CIF number is required' });
|
||||
@@ -93,23 +94,26 @@ async function UserRights(req, res) {
|
||||
if (FirstTimeLogin && dayjs(currentTime).diff(dayjs(user.created_at), 'day') > 8) {
|
||||
// Password expired, resend
|
||||
await db.query(
|
||||
'UPDATE users SET password_hash=$2, updated_at=$5, ib_access_level=$3, mb_access_level=$4 WHERE customer_no=$1',
|
||||
[CIF, password, ib_access_level, mb_access_level, currentTime]
|
||||
'UPDATE users SET password_hash=$2, updated_at=$5, ib_access_level=$3, mb_access_level=$4 ,inb_limit_amount=$6,mobile_limit_amount=$7 WHERE customer_no=$1',
|
||||
[CIF, password, ib_access_level, mb_access_level, currentTime, ib_limit, mb_limit]
|
||||
);
|
||||
logger.info("Admin sended the OTP");
|
||||
return res.json({ otp: first_time_pass });
|
||||
}
|
||||
// Just update access levels and timestamp
|
||||
await db.query(
|
||||
'UPDATE users SET updated_at=$4, ib_access_level=$2, mb_access_level=$3 WHERE customer_no=$1',
|
||||
[CIF, ib_access_level, mb_access_level, currentTime]
|
||||
'UPDATE users SET updated_at=$4, ib_access_level=$2, mb_access_level=$3 ,inb_limit_amount=$5,mobile_limit_amount=$6 WHERE customer_no=$1',
|
||||
[CIF, ib_access_level, mb_access_level, currentTime, ib_limit, mb_limit]
|
||||
);
|
||||
logger.info("Admin Updated the user.");
|
||||
return res.json({ message: "User updated successfully." });
|
||||
} else {
|
||||
// User does not exist, insert
|
||||
await db.query(
|
||||
'INSERT INTO users (customer_no, password_hash, ib_access_level, mb_access_level) VALUES ($1, $2, $3, $4)',
|
||||
[CIF, password, ib_access_level, mb_access_level]
|
||||
'INSERT INTO users (customer_no, password_hash, ib_access_level, mb_access_level ,inb_limit_amount,mobile_limit_amount) VALUES ($1, $2, $3, $4 ,$5 ,$6)',
|
||||
[CIF, password, ib_access_level, mb_access_level, ib_limit, mb_limit]
|
||||
);
|
||||
logger.info("New user enroll by admin.");
|
||||
return res.json({ otp: first_time_pass });
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -119,4 +123,30 @@ async function UserRights(req, res) {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { login, fetchAdminDetails, getUserDetails, UserRights, getUserRights };
|
||||
async function handleUnlockUser(req, res) {
|
||||
try {
|
||||
const { user, action } = req.body;
|
||||
const adminUserName = req.admin;
|
||||
if (!user) {
|
||||
return res.status(400).json({ error: "CIF or username is required" });
|
||||
}
|
||||
const userDetails = await adminAuthService.getCustomerDetailsFromDB(user);
|
||||
if (!userDetails) {
|
||||
return res
|
||||
.status(404)
|
||||
.json({ error: "Invalid CIF number or username" });
|
||||
}
|
||||
await adminAuthService.updateUserLockStatus(user, action,adminUserName);
|
||||
const statusText = action ? "locked" : "unlocked";
|
||||
logger.info(`User ${user} has been successfully ${statusText}.`);
|
||||
|
||||
return res.json({
|
||||
message: `User ${user} has been successfully ${statusText}.`,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Unlock user error:", error);
|
||||
return res.status(500).json({ error: "Internal server error" });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { login, fetchAdminDetails, getUserDetails, UserRights, getUserRights, handleUnlockUser };
|
||||
|
||||
@@ -7,13 +7,14 @@ const { comparePassword } = require('../util/hash');
|
||||
const customerController = require('../controllers/customer_details.controller.js');
|
||||
const { setJson, getJson } = require('../config/redis');
|
||||
|
||||
|
||||
async function login(req, res) {
|
||||
let { customerNo, userName, password, otp } = req.body;
|
||||
const loginType = req.headers['x-login-type'] || 'standard';
|
||||
|
||||
if ((!customerNo && !userName) || !password) {
|
||||
return res.status(400).json({ error: 'customerNo and password are required' });
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: 'customerNo and password are required' });
|
||||
}
|
||||
const currentTime = new Date().toISOString();
|
||||
const MAX_ATTEMPTS = 3; // Max invalid attempts before lock
|
||||
@@ -23,24 +24,30 @@ async function login(req, res) {
|
||||
const blockedKey = `login:blocked:${customerNo}`;
|
||||
const attemptsKey = `login:attempts:${customerNo}`;
|
||||
if (!customerNo && userName) {
|
||||
const result = await db.query('SELECT * FROM users WHERE preferred_name = $1', [
|
||||
userName,
|
||||
]);
|
||||
const result = await db.query(
|
||||
'SELECT * FROM users WHERE preferred_name = $1',
|
||||
[userName]
|
||||
);
|
||||
if (result.rows.length === 0) {
|
||||
logger.error("Customer not found with this user name.");
|
||||
return res.status(404).json({ error: 'No user found with this username.' });
|
||||
logger.error('Customer not found with this user name.');
|
||||
return res
|
||||
.status(404)
|
||||
.json({ error: 'No user found with this username.' });
|
||||
}
|
||||
logger.info("Customer found with user name.");
|
||||
logger.info('Customer found with user name.');
|
||||
customerNo = result.rows[0].customer_no;
|
||||
}
|
||||
|
||||
const userCheck = await authService.findUserByCustomerNo(customerNo);
|
||||
if (!userCheck) {
|
||||
return res.status(404).json({ error: 'customer not found' });
|
||||
}
|
||||
|
||||
if (loginType.toUpperCase() === 'IB') {
|
||||
// check DB locked flag
|
||||
if (userCheck && userCheck.locked) {
|
||||
await setJson(blockedKey, true, BLOCK_DURATION);
|
||||
logger.error("USER Account Locked");
|
||||
logger.error('USER Account Locked');
|
||||
return res.status(423).json({
|
||||
error: 'Your account is locked. Please contact the administrator.',
|
||||
});
|
||||
@@ -48,9 +55,13 @@ async function login(req, res) {
|
||||
}
|
||||
|
||||
// --- Step 2: Check migration status
|
||||
const isMigratedUser = await authService.isMigratedUser(customerNo);
|
||||
if (isMigratedUser)
|
||||
const migratedPassword = `${userCheck.customer_no}@KCCB`;
|
||||
const isMigratedUser = userCheck.password_hash === migratedPassword;
|
||||
if (isMigratedUser) {
|
||||
if (password !== migratedPassword)
|
||||
return res.status(401).json({ error: 'Invalid credentials.' });
|
||||
return res.status(401).json({ error: 'MIGRATED_USER_HAS_NO_PASSWORD' });
|
||||
}
|
||||
|
||||
// --- Step 3: Validate credentials ---
|
||||
const user = await authService.validateUser(customerNo, password);
|
||||
@@ -61,12 +72,16 @@ async function login(req, res) {
|
||||
attempts += 1;
|
||||
|
||||
if (attempts >= MAX_ATTEMPTS) {
|
||||
await db.query('UPDATE users SET locked = true WHERE customer_no = $1', [customerNo]);
|
||||
await db.query(
|
||||
'UPDATE users SET locked = true WHERE customer_no = $1',
|
||||
[customerNo]
|
||||
);
|
||||
await setJson(blockedKey, true, BLOCK_DURATION);
|
||||
await setJson(attemptsKey, 0);
|
||||
|
||||
return res.status(423).json({
|
||||
error: 'Your account has been locked due to multiple failed login attempts. Please contact the administrator.',
|
||||
error:
|
||||
'Your account has been locked due to multiple failed login attempts. Please contact the administrator.',
|
||||
});
|
||||
} else {
|
||||
await setJson(attemptsKey, attempts, BLOCK_DURATION);
|
||||
@@ -107,6 +122,8 @@ async function login(req, res) {
|
||||
// --- Step 7: Generate token and update last login ---
|
||||
const token = generateToken(user.customer_no);
|
||||
const loginPswExpiry = user.password_hash_expiry;
|
||||
const mobileTncAccepted = user.tnc_mobile;
|
||||
const tnc = { mobile: mobileTncAccepted };
|
||||
const rights = {
|
||||
ibAccess: user.ib_access_level,
|
||||
mbAccess: user.mb_access_level,
|
||||
@@ -116,7 +133,7 @@ async function login(req, res) {
|
||||
customerNo,
|
||||
]);
|
||||
logger.info(`Login successful | Type: ${loginType}`);
|
||||
return res.json({ token, FirstTimeLogin, loginPswExpiry, rights });
|
||||
return res.json({ token, FirstTimeLogin, loginPswExpiry, rights, tnc });
|
||||
} catch (err) {
|
||||
logger.error(err, `login failed | Type: ${loginType}`);
|
||||
return res.status(500).json({ error: 'something went wrong' });
|
||||
@@ -161,7 +178,28 @@ async function setTpin(req, res) {
|
||||
const { tpin } = req.body;
|
||||
if (!/^\d{6}$/.test(tpin))
|
||||
return res.status(400).json({ error: 'INVALID_TPIN_FORMAT' });
|
||||
authService.setTpin(customerNo, tpin);
|
||||
await authService.setTpin(customerNo, tpin);
|
||||
return res.json({ message: 'TPIN_SET' });
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return res.status(500).json({ error: 'SOMETHING_WENT_WRONG' });
|
||||
}
|
||||
}
|
||||
|
||||
async function changeTpin(req, res) {
|
||||
const customerNo = req.user;
|
||||
try {
|
||||
const user = await authService.findUserByCustomerNo(customerNo);
|
||||
if (!user) return res.status(404).json({ error: 'USER_NOT_FOUND' });
|
||||
if (!user.tpin)
|
||||
return res.status(400).json({ error: 'USER_DOESNT_HAVE_A_TPIN' });
|
||||
const { oldTpin, newTpin } = req.body;
|
||||
const isMatch = await comparePassword(oldTpin, user.tpin);
|
||||
if (!isMatch) return res.status(400).json({ error: 'TPIN_DOESNT_MATCH' });
|
||||
|
||||
if (!/^\d{6}$/.test(newTpin))
|
||||
return res.status(400).json({ error: 'INVALID_TPIN_FORMAT' });
|
||||
await authService.setTpin(customerNo, newTpin);
|
||||
return res.json({ message: 'TPIN_SET' });
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
@@ -298,18 +336,25 @@ async function setUserName(req, res) {
|
||||
return res.json({ message: 'All set! Your username has been saved.' });
|
||||
}
|
||||
if (userNameIsExits) {
|
||||
const historyRes = await db.query('SELECT preferred_name FROM preferred_name_history WHERE customer_no = $1 ORDER BY changed_at DESC LIMIT 5',
|
||||
const historyRes = await db.query(
|
||||
'SELECT preferred_name FROM preferred_name_history WHERE customer_no = $1 ORDER BY changed_at DESC LIMIT 5',
|
||||
[customerNo]
|
||||
);
|
||||
// maximum 5 times can changed username
|
||||
const history = historyRes.rows.map((r) => r.preferred_name.toLowerCase());
|
||||
const history = historyRes.rows.map((r) =>
|
||||
r.preferred_name.toLowerCase()
|
||||
);
|
||||
if (history.length >= 5) {
|
||||
return res.status(429).json({ error: "Preferred name change limit reached -5 times" });
|
||||
return res
|
||||
.status(429)
|
||||
.json({ error: 'Preferred name change limit reached -5 times' });
|
||||
}
|
||||
// Cannot match last 2
|
||||
const lastTwo = history.slice(0, 2);
|
||||
if (lastTwo.includes(user_name.toLowerCase())) {
|
||||
return res.status(409).json({ error: "Preferred name cannot match last 2 preferred names" });
|
||||
return res.status(409).json({
|
||||
error: 'Preferred name cannot match last 2 preferred names',
|
||||
});
|
||||
}
|
||||
await authService.setUserName(customerNo, user_name);
|
||||
logger.info('User name has been updated.');
|
||||
@@ -321,10 +366,34 @@ async function setUserName(req, res) {
|
||||
}
|
||||
}
|
||||
|
||||
async function getTncAcceptanceFlag(req, res) {
|
||||
try {
|
||||
const flag = await authService.getTncFlag(req.user, req.client);
|
||||
res.json({ tnc_accepted: flag });
|
||||
} catch (error) {
|
||||
logger.error(error, 'error occured while getting tnc flag');
|
||||
res.status(500).json({ error: 'INTERNAL SERVER ERROR' });
|
||||
}
|
||||
}
|
||||
|
||||
async function setTncAcceptanceFlag(req, res) {
|
||||
try {
|
||||
const { flag } = req.body;
|
||||
if (flag !== 'Y' && flag !== 'N')
|
||||
res.status(400).json({ error: 'invalid value for flag' });
|
||||
await authService.setTncFlag(req.user, req.client, flag);
|
||||
return res.json({ message: 'SUCCESS' });
|
||||
} catch (error) {
|
||||
logger.error(error, 'error occured while updating tnc flag');
|
||||
res.status(500).json({ error: 'INTERNAL SERVER ERROR' });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
login,
|
||||
tpin,
|
||||
setTpin,
|
||||
changeTpin,
|
||||
setLoginPassword,
|
||||
setTransactionPassword,
|
||||
fetchUserDetails,
|
||||
@@ -332,4 +401,6 @@ module.exports = {
|
||||
changeTransPassword,
|
||||
isUserNameExits,
|
||||
setUserName,
|
||||
getTncAcceptanceFlag,
|
||||
setTncAcceptanceFlag,
|
||||
};
|
||||
|
||||
@@ -4,11 +4,11 @@ const { logger } = require('../util/logger');
|
||||
|
||||
async function npciResponse(req, res) {
|
||||
const { resp } = req.body;
|
||||
logger.info(resp, 'received from NPCI');
|
||||
if (resp.status === 'Success') {
|
||||
await handleNPCISuccess(resp);
|
||||
logger.info(req.body, 'received response from NPCI');
|
||||
if (resp === 'SUCCESS') {
|
||||
await handleNPCISuccess(req.body);
|
||||
} else {
|
||||
await handleNPCIFailure(resp);
|
||||
await handleNPCIFailure(req.body);
|
||||
}
|
||||
res.send('ok');
|
||||
}
|
||||
|
||||
@@ -107,10 +107,19 @@ async function SendOtp(req, res) {
|
||||
case 'USERNAME_SAVED':
|
||||
message = templates.USERNAME_SAVED(PreferName);
|
||||
break;
|
||||
case 'TLIMIT':
|
||||
otp = generateOTP(6);
|
||||
message = templates.TLIMIT(otp);
|
||||
break;
|
||||
case 'TLIMIT_SET':
|
||||
message = templates.TLIMIT_SET(amount);
|
||||
break;
|
||||
default:
|
||||
return res.status(400).json({ error: 'Invalid OTP type' });
|
||||
}
|
||||
|
||||
if (message.includes('OTP')) {
|
||||
await setJson(`otp:${mobileNumber}`, otp, 300);
|
||||
}
|
||||
// Call SMS API
|
||||
const response = await axios.post(
|
||||
'http://localhost:9999/api/SendtoMessage',
|
||||
@@ -119,12 +128,8 @@ async function SendOtp(req, res) {
|
||||
stMessage: message,
|
||||
}
|
||||
);
|
||||
|
||||
if (response.data) {
|
||||
// Save OTP only if it's OTP based (skip notifications without OTP)
|
||||
if (message.includes('OTP')) {
|
||||
await setJson(`otp:${mobileNumber}`, otp, 300);
|
||||
}
|
||||
logger.info(`Sent OTP [${otp}] for type [${type}] to ${mobileNumber}`);
|
||||
}
|
||||
return res.status(200).json({ message: 'Message sent successfully' });
|
||||
@@ -145,15 +150,18 @@ async function VerifyOtp(req, res) {
|
||||
|
||||
try {
|
||||
const storedOtp = await getJson(`otp:${mobileNumber}`);
|
||||
logger.info("OTP is stored");
|
||||
|
||||
if (!storedOtp) {
|
||||
logger.error("OTP expired or not found");
|
||||
return res.status(400).json({ error: 'OTP expired or not found' });
|
||||
}
|
||||
|
||||
if (parseInt(otp, 10) !== parseInt(storedOtp, 10)) {
|
||||
logger.error("Invalid OTP");
|
||||
return res.status(400).json({ error: 'Invalid OTP' });
|
||||
}
|
||||
|
||||
logger.info(`OTP verified with mobile number -${mobileNumber}`);
|
||||
return res.status(200).json({ message: 'OTP verified successfully' });
|
||||
} catch (err) {
|
||||
logger.error(err, 'Error verifying OTP');
|
||||
|
||||
178
src/controllers/report.controller.js
Normal file
178
src/controllers/report.controller.js
Normal file
@@ -0,0 +1,178 @@
|
||||
|
||||
const reportService = require('../services/report.service');
|
||||
const { logger } = require('../util/logger');
|
||||
|
||||
async function active_users(req, res) {
|
||||
const { from_date, to_date } = req.body;
|
||||
if (!from_date || !to_date) {
|
||||
return res.status(400).json({ error: 'from_date and to_date are required' });
|
||||
}
|
||||
try {
|
||||
const users = await reportService.total_users(from_date, to_date);
|
||||
const activeUsers = users.filter(u => u.is_first_login === false);
|
||||
const inactiveUsers = users.filter(u => u.is_first_login === true);
|
||||
const active_user_list = activeUsers.map(u => ({
|
||||
customer_no: u.customer_no,
|
||||
user_name: u.preferred_name,
|
||||
created_at: u.created_at,
|
||||
last_login: u.last_login,
|
||||
status: "active"
|
||||
}));
|
||||
logger.info(`fetch total number of users and active users from date ${from_date} to ${to_date}`);
|
||||
res.json({
|
||||
total_users: users.length,
|
||||
active_users: activeUsers.length,
|
||||
inactive_users: inactiveUsers.length,
|
||||
active_user_list: active_user_list
|
||||
});
|
||||
} catch (err) {
|
||||
logger.error(err, 'failed to fetch data');
|
||||
res.status(500).json({ error: 'something went wrong' });
|
||||
}
|
||||
}
|
||||
|
||||
async function inactive_users(req, res) {
|
||||
const { from_date, to_date } = req.body;
|
||||
if (!from_date || !to_date) {
|
||||
return res.status(400).json({ error: 'from_date and to_date are required' });
|
||||
}
|
||||
try {
|
||||
const users = await reportService.total_users(from_date, to_date);
|
||||
const activeUsers = users.filter(u => u.is_first_login === false);
|
||||
const inactiveUsers = users.filter(u => u.is_first_login === true);
|
||||
const inactive_user_list = inactiveUsers.map(u => ({
|
||||
customer_no: u.customer_no,
|
||||
user_name: u.preferred_name,
|
||||
created_at: u.created_at,
|
||||
last_login: u.last_login,
|
||||
status: "in-active"
|
||||
}));
|
||||
logger.info(`fetch total number of users and inactive users from date ${from_date} to ${to_date}`);
|
||||
res.json({
|
||||
total_users: users.length,
|
||||
active_users: activeUsers.length,
|
||||
inactive_users: inactiveUsers.length,
|
||||
inactive_user_list: inactive_user_list
|
||||
});
|
||||
} catch (err) {
|
||||
logger.error(err, 'failed to fetch data');
|
||||
res.status(500).json({ error: 'something went wrong' });
|
||||
}
|
||||
}
|
||||
|
||||
async function getTransactions(req, res) {
|
||||
const {
|
||||
trx_type,
|
||||
from_date,
|
||||
to_date,
|
||||
client,
|
||||
amount_min,
|
||||
amount_max,
|
||||
customer_no
|
||||
} = req.body;
|
||||
|
||||
if (!trx_type || !from_date || !to_date) {
|
||||
return res.status(400).json({ error: 'trx_type, from_date and to_date are required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const filters = {
|
||||
trx_type,
|
||||
from_date,
|
||||
to_date,
|
||||
client,
|
||||
amount_min,
|
||||
amount_max,
|
||||
customer_no
|
||||
};
|
||||
|
||||
const transactions = await reportService.getTransactions(filters);
|
||||
const transactions_list = transactions.map(u => ({
|
||||
|
||||
customer_no: u.customer_no,
|
||||
from_account: u.from_account,
|
||||
to_account: u.to_account,
|
||||
ifsc_code: u.ifsc_code,
|
||||
amount: u.amount,
|
||||
created_at: u.created_at,
|
||||
trx_type: u.trx_type,
|
||||
status: u.status,
|
||||
}));
|
||||
|
||||
res.json({ count: transactions.length, transactions_list });
|
||||
|
||||
} catch (err) {
|
||||
logger.error(err, 'failed to fetch transactions');
|
||||
res.status(500).json({ error: 'something went wrong' });
|
||||
}
|
||||
}
|
||||
|
||||
async function getFailedTransactions(req, res) {
|
||||
const {
|
||||
from_date,
|
||||
to_date,
|
||||
customer_no
|
||||
} = req.body;
|
||||
|
||||
if (!from_date || !to_date) {
|
||||
return res.status(400).json({ error: 'from_date and to_date are required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const filters = {
|
||||
from_date,
|
||||
to_date,
|
||||
customer_no
|
||||
};
|
||||
|
||||
const transactions = await reportService.getFailedTransactions(filters);
|
||||
const transactions_list = transactions.map(u => ({
|
||||
|
||||
customer_no: u.customer_no,
|
||||
from_account: u.from_account,
|
||||
to_account: u.to_account,
|
||||
ifsc_code: u.ifsc_code,
|
||||
amount: u.amount,
|
||||
created_at: u.created_at,
|
||||
trx_type: u.trx_type,
|
||||
status: u.status,
|
||||
}));
|
||||
|
||||
res.json({ count: transactions.length, transactions_list });
|
||||
|
||||
} catch (err) {
|
||||
logger.error(err, 'failed to fetch transactions');
|
||||
res.status(500).json({ error: 'something went wrong' });
|
||||
}
|
||||
}
|
||||
|
||||
async function getDetailsOfNotLoginWithinDuration(req, res) {
|
||||
const {
|
||||
duration
|
||||
} = req.body;
|
||||
|
||||
if (!duration) {
|
||||
return res.status(400).json({ error: 'Duration are required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const users = await reportService.getNotLogin(duration);
|
||||
const user_list = users.map(u => ({
|
||||
|
||||
customer_no: u.customer_no,
|
||||
user_name: u.preferred_name,
|
||||
last_login: u.last_login,
|
||||
created_at: u.created_at,
|
||||
locked: u.locked,
|
||||
status: u.status,
|
||||
}));
|
||||
|
||||
res.json({ count: users.length, user_list });
|
||||
|
||||
} catch (err) {
|
||||
logger.error(err, 'failed to fetch not logged in user details');
|
||||
res.status(500).json({ error: 'something went wrong' });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { active_users, inactive_users, getTransactions, getFailedTransactions, getDetailsOfNotLoginWithinDuration };
|
||||
@@ -13,7 +13,6 @@ function checkAdmin (req,res,next){
|
||||
const token = authHeader.split(' ')[1];
|
||||
try {
|
||||
const payload = verifyToken(token);
|
||||
// console.log("hi",payload);
|
||||
if(payload.customerNo && payload.role === 'admin'){
|
||||
req.admin = payload.customerNo;
|
||||
next();
|
||||
|
||||
@@ -3,7 +3,7 @@ const { logger } = require('../util/logger');
|
||||
function verifyClient(req, res, next) {
|
||||
const clientHeader = req.headers['x-login-type'];
|
||||
|
||||
if (!clientHeader || (clientHeader !== 'MB' && clientHeader !== 'IB')) {
|
||||
if (!clientHeader || (clientHeader !== 'MB' && clientHeader !== 'IB' && clientHeader !== 'eMandate' && clientHeader !=='Admin')) {
|
||||
logger.error(
|
||||
`Invalid or missing client header. Expected 'MB' or 'IB'. Found ${clientHeader}`
|
||||
);
|
||||
|
||||
29
src/middlewares/cooldown.middleware.js
Normal file
29
src/middlewares/cooldown.middleware.js
Normal file
@@ -0,0 +1,29 @@
|
||||
const { logger } = require('../util/logger');
|
||||
const { getSingleBeneficiary } = require('../services/beneficiary.service');
|
||||
|
||||
async function checkBeneficiaryCooldown(req, res, next) {
|
||||
const cooldownTime = parseInt(
|
||||
process.env.BENEFICIARY_COOLDOWN_TIME || '60',
|
||||
10
|
||||
);
|
||||
const customerNo = req.user;
|
||||
const { toAccount } = req.body;
|
||||
const beneficiary = await getSingleBeneficiary(customerNo, toAccount);
|
||||
|
||||
if (beneficiary) {
|
||||
const now = new Date();
|
||||
const cooldownPeriod = new Date(now.getTime() - cooldownTime * 60 * 1000);
|
||||
const createdAt = new Date(beneficiary['created_at']);
|
||||
if (createdAt > cooldownPeriod) {
|
||||
const remaining = (now - createdAt) / (60 * 1000);
|
||||
logger.warn('TRANSACTION_FAILED BENEFICIARY_COOLDOWN_ACTIVE');
|
||||
return res.status(403).json({
|
||||
remaining,
|
||||
error: 'beneficiary cooldown period active',
|
||||
});
|
||||
}
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = { checkBeneficiaryCooldown };
|
||||
@@ -9,4 +9,5 @@ router.get('/admin_details', adminAuthenticate, adminAuthController.fetchAdminDe
|
||||
router.get('/fetch/customer_details',adminAuthenticate,adminAuthController.getUserDetails);
|
||||
router.post('/user/rights',adminAuthenticate,adminAuthController.UserRights);
|
||||
router.get('/user/rights',adminAuthenticate,adminAuthController.getUserRights);
|
||||
router.post('/user/unlock',adminAuthenticate,adminAuthController.handleUnlockUser);
|
||||
module.exports = router;
|
||||
|
||||
19
src/routes/atm.route.js
Normal file
19
src/routes/atm.route.js
Normal file
@@ -0,0 +1,19 @@
|
||||
const express = require('express');
|
||||
const { logger } = require('../util/logger');
|
||||
const db = require('../config/db');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const atmRoute = async (req, res) => {
|
||||
try {
|
||||
const query_str = 'SELECT * FROM atm';
|
||||
const result = await db.query(query_str);
|
||||
return res.json(result.rows);
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
res.status(500).json({ error: 'INTERNAL SERVER ERROR' });
|
||||
}
|
||||
};
|
||||
router.get('/', atmRoute);
|
||||
|
||||
module.exports = router;
|
||||
@@ -8,12 +8,27 @@ router.post('/login', authController.login);
|
||||
router.get('/user_details', authenticate, authController.fetchUserDetails);
|
||||
router.get('/tpin', authenticate, authController.tpin);
|
||||
router.post('/tpin', authenticate, authController.setTpin);
|
||||
router.post('/change/tpin', authenticate, authController.changeTpin);
|
||||
router.post('/login_password', authenticate, authController.setLoginPassword);
|
||||
router.post('/transaction_password',authenticate,authController.setTransactionPassword);
|
||||
router.post('/change/login_password',authenticate,authController.changeLoginPassword);
|
||||
router.post('/change/transaction_password',authenticate,authController.changeTransPassword);
|
||||
router.post(
|
||||
'/transaction_password',
|
||||
authenticate,
|
||||
authController.setTransactionPassword
|
||||
);
|
||||
router.post(
|
||||
'/change/login_password',
|
||||
authenticate,
|
||||
authController.changeLoginPassword
|
||||
);
|
||||
router.post(
|
||||
'/change/transaction_password',
|
||||
authenticate,
|
||||
authController.changeTransPassword
|
||||
);
|
||||
router.get('/user_name', authenticate, authController.isUserNameExits);
|
||||
router.post('/user_name', authenticate, authController.setUserName);
|
||||
|
||||
router.get('/tnc', authenticate, authController.getTncAcceptanceFlag);
|
||||
router.post('/tnc', authenticate, authController.setTncAcceptanceFlag);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
19
src/routes/branch.route.js
Normal file
19
src/routes/branch.route.js
Normal file
@@ -0,0 +1,19 @@
|
||||
const express = require('express');
|
||||
const { logger } = require('../util/logger');
|
||||
const db = require('../config/db');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const branchRoute = async (req, res) => {
|
||||
try {
|
||||
const query_str = 'SELECT * FROM branches';
|
||||
const result = await db.query(query_str);
|
||||
return res.json(result.rows);
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
res.status(500).json({ error: 'INTERNAL SERVER ERROR' });
|
||||
}
|
||||
};
|
||||
router.get('/', branchRoute);
|
||||
|
||||
module.exports = router;
|
||||
24
src/routes/emandate.route.js
Normal file
24
src/routes/emandate.route.js
Normal file
@@ -0,0 +1,24 @@
|
||||
const express = require('express');
|
||||
const axios = require('axios');
|
||||
const { logger } = require('../util/logger');
|
||||
const router = express.Router();
|
||||
const emandateData = async (req, res) => {
|
||||
const { data, mandateRequest, mandateType } = req.body;
|
||||
if (!data || !mandateRequest | !mandateType)
|
||||
return res.status(404).json({ error: 'DATA NOT FOUND FROM CLIENT' })
|
||||
try {
|
||||
const reqData = { data, mandateRequest, mandateType };
|
||||
const response = await axios.post('http://192.168.1.166:9992/kccb/validation', reqData,
|
||||
{
|
||||
headers: { 'Content-Type': 'application/json', },
|
||||
}
|
||||
);
|
||||
logger.info("Data validate");
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
logger.error(error, 'error occured while E-Mandate validation');
|
||||
return res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
|
||||
}
|
||||
};
|
||||
router.post('/validation', emandateData);
|
||||
module.exports = router;
|
||||
@@ -4,9 +4,17 @@ const { logger } = require('../util/logger');
|
||||
const impsValidator = require('../validators/imps.validator');
|
||||
const paymentSecretValidator = require('../validators/payment.secret.validator');
|
||||
const { checkLimit } = require('../middlewares/limitCheck.middleware');
|
||||
const {
|
||||
checkBeneficiaryCooldown,
|
||||
} = require('../middlewares/cooldown.middleware');
|
||||
|
||||
const router = express.Router();
|
||||
router.use(impsValidator, paymentSecretValidator, checkLimit);
|
||||
router.use(
|
||||
impsValidator,
|
||||
paymentSecretValidator,
|
||||
checkLimit,
|
||||
checkBeneficiaryCooldown
|
||||
);
|
||||
|
||||
const impsRoute = async (req, res) => {
|
||||
const { fromAccount, toAccount, ifscCode, amount, beneficiaryName, remarks } =
|
||||
|
||||
@@ -4,14 +4,22 @@ const adminAuthRoute = require('./admin_auth.route');
|
||||
const detailsRoute = require('./customer_details.route');
|
||||
const transactionRoute = require('./transactions.route');
|
||||
const authenticate = require('../middlewares/auth.middleware');
|
||||
const adminAuthenticate = require('../middlewares/admin.middleware');
|
||||
const transferRoute = require('./transfer.route');
|
||||
const beneficiaryRoute = require('./beneficiary.route');
|
||||
const neftRoute = require('./neft.route');
|
||||
const rtgsRoute = require('./rtgs.route');
|
||||
const impsRoute = require('./imps.route');
|
||||
const branchRoute = require('./branch.route');
|
||||
const atmRoute = require('./atm.route');
|
||||
const { npciResponse } = require('../controllers/npci.controller');
|
||||
const otp = require('./otp.route');
|
||||
<<<<<<< HEAD
|
||||
const reports =require('./report.route');
|
||||
|
||||
=======
|
||||
const eMandate = require('./emandate.route');
|
||||
>>>>>>> 7e162e741d4d126fd029b1875bd5e4e0d3c460cf
|
||||
const router = express.Router();
|
||||
|
||||
router.use('/auth', authRoute);
|
||||
@@ -24,6 +32,10 @@ router.use('/payment/rtgs', authenticate, rtgsRoute);
|
||||
router.use('/payment/imps', authenticate, impsRoute);
|
||||
router.use('/beneficiary', authenticate, beneficiaryRoute);
|
||||
router.use('/npci/beneficiary-response', npciResponse);
|
||||
router.use('/report',adminAuthenticate,reports);
|
||||
router.use('/otp', otp);
|
||||
router.use('/e-mandate', authenticate, eMandate);
|
||||
router.use('/branch', authenticate, branchRoute);
|
||||
router.use('/atm', authenticate, atmRoute);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -4,9 +4,17 @@ const { logger } = require('../util/logger');
|
||||
const neftValidator = require('../validators/neft.validator.js');
|
||||
const paymentSecretValidator = require('../validators/payment.secret.validator');
|
||||
const { checkLimit } = require('../middlewares/limitCheck.middleware');
|
||||
const {
|
||||
checkBeneficiaryCooldown,
|
||||
} = require('../middlewares/cooldown.middleware');
|
||||
|
||||
const router = express.Router();
|
||||
router.use(neftValidator, paymentSecretValidator, checkLimit);
|
||||
router.use(
|
||||
neftValidator,
|
||||
paymentSecretValidator,
|
||||
checkLimit,
|
||||
checkBeneficiaryCooldown
|
||||
);
|
||||
|
||||
const neftRoute = async (req, res) => {
|
||||
const {
|
||||
|
||||
12
src/routes/report.route.js
Normal file
12
src/routes/report.route.js
Normal file
@@ -0,0 +1,12 @@
|
||||
const reportController = require('../controllers/report.controller');
|
||||
const express = require('express');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.post('/active_users', reportController.active_users);
|
||||
router.post('/in-active_users', reportController.inactive_users);
|
||||
router.post('/transaction_report', reportController.getTransactions);
|
||||
router.post('/failed_transaction_report', reportController.getFailedTransactions);
|
||||
router.post('/not_logged_in', reportController.getDetailsOfNotLoginWithinDuration);
|
||||
|
||||
module.exports = router;
|
||||
@@ -4,9 +4,17 @@ const { logger } = require('../util/logger');
|
||||
const rtgsValidator = require('../validators/rtgs.validator.js');
|
||||
const paymentSecretValidator = require('../validators/payment.secret.validator');
|
||||
const { checkLimit } = require('../middlewares/limitCheck.middleware');
|
||||
const {
|
||||
checkBeneficiaryCooldown,
|
||||
} = require('../middlewares/cooldown.middleware');
|
||||
|
||||
const router = express.Router();
|
||||
router.use(rtgsValidator, paymentSecretValidator, checkLimit);
|
||||
router.use(
|
||||
rtgsValidator,
|
||||
paymentSecretValidator,
|
||||
checkLimit,
|
||||
checkBeneficiaryCooldown
|
||||
);
|
||||
|
||||
const rtgsRoute = async (req, res) => {
|
||||
const {
|
||||
|
||||
@@ -4,9 +4,17 @@ const express = require('express');
|
||||
const transferValidator = require('../validators/transfer.validator');
|
||||
const passwordValidator = require('../validators/payment.secret.validator.js');
|
||||
const { checkLimit } = require('../middlewares/limitCheck.middleware');
|
||||
const {
|
||||
checkBeneficiaryCooldown,
|
||||
} = require('../middlewares/cooldown.middleware');
|
||||
|
||||
const router = express.Router();
|
||||
router.use(passwordValidator, transferValidator, checkLimit);
|
||||
router.use(
|
||||
passwordValidator,
|
||||
transferValidator,
|
||||
checkLimit,
|
||||
checkBeneficiaryCooldown
|
||||
);
|
||||
|
||||
const transferRoute = async (req, res) => {
|
||||
const { fromAccount, toAccount, toAccountType, amount, remarks } = req.body;
|
||||
|
||||
@@ -38,10 +38,19 @@ async function getCustomerDetails(customerNo) {
|
||||
}
|
||||
|
||||
async function getCustomerDetailsFromDB(customerNo) {
|
||||
const result = await db.query('SELECT customer_no,created_at,last_login,is_first_login,ib_access_level,mb_access_level FROM users WHERE customer_no = $1', [
|
||||
const result = await db.query(
|
||||
'SELECT customer_no,created_at,last_login,is_first_login,ib_access_level,mb_access_level,inb_limit_amount,mobile_limit_amount,locked FROM users WHERE customer_no = $1 or preferred_name= $1', [
|
||||
customerNo,
|
||||
]);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
module.exports = { validateAdmin, findAdminByUserName, getCustomerDetails,getCustomerDetailsFromDB };
|
||||
async function updateUserLockStatus(customerNo ,locked ,adminUserName) {
|
||||
const result = await db.query(
|
||||
'Update users set locked =$2 ,unlocked_by=$3 WHERE customer_no = $1 or preferred_name= $1', [
|
||||
customerNo, locked ,adminUserName
|
||||
]);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
module.exports = { validateAdmin, findAdminByUserName, getCustomerDetails, getCustomerDetailsFromDB ,updateUserLockStatus };
|
||||
|
||||
@@ -127,16 +127,16 @@ async function changeTransPassword(customerNo, trans_psw) {
|
||||
|
||||
async function CheckUserName(customerNo) {
|
||||
try {
|
||||
const result = await db.query('SELECT preferred_name from users WHERE customer_no = $1',
|
||||
const result = await db.query(
|
||||
'SELECT preferred_name from users WHERE customer_no = $1',
|
||||
[customerNo]
|
||||
);
|
||||
if (result.rows.length > 0) {
|
||||
return result.rows[0].preferred_name;;
|
||||
return result.rows[0].preferred_name;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`error occurred while fetch the preferred name ${error.message}`
|
||||
);
|
||||
@@ -150,12 +150,12 @@ async function setUserName(customerNo, username) {
|
||||
'UPDATE users SET preferred_name = $1 ,updated_at = $2 WHERE customer_no = $3',
|
||||
[username, currentTime, customerNo]
|
||||
);
|
||||
logger.info("user table updated");
|
||||
logger.info('user table updated');
|
||||
await db.query(
|
||||
"INSERT INTO preferred_name_history (customer_no, preferred_name) VALUES ($1, $2)",
|
||||
'INSERT INTO preferred_name_history (customer_no, preferred_name) VALUES ($1, $2)',
|
||||
[customerNo, username]
|
||||
);
|
||||
logger.info("preferred_name_history table updated");
|
||||
logger.info('preferred_name_history table updated');
|
||||
} catch (error) {
|
||||
if (error.code === '23505') {
|
||||
throw new Error('PREFERRED_NAME_ALREADY_EXISTS');
|
||||
@@ -166,6 +166,32 @@ async function setUserName(customerNo, username) {
|
||||
}
|
||||
}
|
||||
|
||||
async function getTncFlag(customerNo, clientType) {
|
||||
let query = '';
|
||||
if (clientType === 'MB') {
|
||||
query = 'SELECT tnc_mobile AS tnc_flag FROM users WHERE customer_no = $1';
|
||||
} else if (clientType === 'IB') {
|
||||
query = 'SELECT tnc_inb AS tnc_flag FROM users WHERE customer_no = $1';
|
||||
} else {
|
||||
throw new Error('UNKNOWN_CLIENT_TYPE. ONLY IB AND MB ALLOWED');
|
||||
}
|
||||
|
||||
const result = await db.query(query, [customerNo]);
|
||||
return result.rows[0]['tnc_flag'];
|
||||
}
|
||||
|
||||
async function setTncFlag(customerNo, clientType, flag) {
|
||||
let query = '';
|
||||
if (clientType === 'MB') {
|
||||
query = 'UPDATE users SET tnc_mobile = $1 WHERE customer_no = $2';
|
||||
} else if (clientType === 'IB') {
|
||||
query = 'UPDATE users SET tnc_inb = $1 WHERE customer_no = $2';
|
||||
} else {
|
||||
throw new Error('UNKNOWN_CLIENT_TYPE. ONLY IB AND MB ALLOWED');
|
||||
}
|
||||
await db.query(query, [flag, customerNo]);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
validateUser,
|
||||
findUserByCustomerNo,
|
||||
@@ -180,5 +206,6 @@ module.exports = {
|
||||
isMigratedUser,
|
||||
CheckUserName,
|
||||
setUserName,
|
||||
|
||||
getTncFlag,
|
||||
setTncFlag,
|
||||
};
|
||||
|
||||
@@ -36,7 +36,7 @@ async function validateOutsideBank(accountNo, ifscCode, name) {
|
||||
|
||||
async function getSingleBeneficiary(customerNo, accountNo) {
|
||||
const queryStr =
|
||||
'SELECT b.account_no, b.name, b.account_type, b.ifsc_code, i.bank_name, i.branch_name FROM beneficiaries b JOIN ifsc_details i ON b.ifsc_code = i.ifsc_code WHERE customer_no = $1 AND account_no = $2';
|
||||
'SELECT b.account_no, b.name, b.account_type, b.ifsc_code, b.created_at, i.bank_name, i.branch_name FROM beneficiaries b JOIN ifsc_details i ON b.ifsc_code = i.ifsc_code WHERE customer_no = $1 AND account_no = $2';
|
||||
const result = await db.query(queryStr, [customerNo, accountNo]);
|
||||
return result.rows[0];
|
||||
}
|
||||
@@ -53,13 +53,14 @@ async function deleteBeneficiary(customerNo, beneficiaryAccountNo) {
|
||||
|
||||
async function getAllBeneficiaries(customerNo) {
|
||||
const queryStr =
|
||||
'SELECT b.account_no, b.name, b.account_type, b.ifsc_code, i.bank_name, i.branch_name FROM beneficiaries b JOIN LATERAL( SELECT * FROM ifsc_details i WHERE i.ifsc_code = b.ifsc_code LIMIT 1 ) i ON true WHERE customer_no = $1';
|
||||
'SELECT b.account_no, b.name, b.account_type, b.ifsc_code, b.created_at, i.bank_name, i.branch_name FROM beneficiaries b JOIN LATERAL( SELECT * FROM ifsc_details i WHERE i.ifsc_code = b.ifsc_code LIMIT 1 ) i ON true WHERE customer_no = $1';
|
||||
const result = await db.query(queryStr, [customerNo]);
|
||||
const list = result.rows.map((row) => {
|
||||
const details = {
|
||||
accountNo: row['account_no'],
|
||||
name: row['name'],
|
||||
accountType: row['account_type'],
|
||||
createdAt: row['created_at'],
|
||||
};
|
||||
if (row['ifsc_code'] === '_') {
|
||||
details['bankName'] = 'THE KANGRA CENTRAL COOPERATIVE BANK LIMITED';
|
||||
|
||||
106
src/services/report.service.js
Normal file
106
src/services/report.service.js
Normal file
@@ -0,0 +1,106 @@
|
||||
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 };
|
||||
@@ -52,7 +52,13 @@ const templates = {
|
||||
`Dear Customer, Your OTP for updating your Preferred Name is ${otp}. It is valid for 1 minute. Do not share this OTP with anyone. -KCCB`,
|
||||
|
||||
USERNAME_SAVED: (PreferName) =>
|
||||
`Dear Customer, Your Preferred Name -${PreferName} has been updated successfully. If this change was not made by you, please contact our support team immediately.`
|
||||
`Dear Customer, Your Preferred Name -${PreferName} has been updated successfully. If this change was not made by you, please contact our support team immediately.`,
|
||||
|
||||
TLIMIT :(otp) =>
|
||||
`Dear Customer,Please complete the transaction limit set with OTP -${otp}. -KCCB`,
|
||||
|
||||
TLIMIT_SET :(amount) =>
|
||||
`Dear Customer,Your transaction limit for Internet Banking is set to Rs ${amount}. -KCCB`,
|
||||
};
|
||||
|
||||
module.exports = templates;
|
||||
Reference in New Issue
Block a user