24 Commits

Author SHA1 Message Date
3da77cf97a feat: added account balance in statement 2025-09-08 20:32:19 +05:30
f675f1561a feat: added transactions record keeping feature 2025-09-08 20:04:55 +05:30
05068634fe added empty string as default narration value in transfer 2025-09-08 16:33:03 +05:30
50753295b4 changed the directory of log directory 2025-08-29 15:49:35 +05:30
454553adbb added log files in .gitignore 2025-08-29 15:40:36 +05:30
077d48c7f0 added logger for logging all kinds of requests with headers, body, ip and other data 2025-08-29 15:40:11 +05:30
c8efe8d75a fix: check if password is not null on login req 2025-08-29 13:40:57 +05:30
484a0dd51a added beneficiary deletion feature 2025-08-27 12:32:25 +05:30
780eb39c18 fixed a bug where data and pin validations were not called 2025-08-26 19:24:37 +05:30
asif
3cfcb8e5bc formatted auth route 2025-08-26 19:21:48 +05:30
0d2cea8902 added imps transactions payment feature 2025-08-22 15:31:13 +05:30
1e32b4a5a6 fixed typo in rtgs.route.js 2025-08-20 12:14:40 +05:30
4ff437319e fixed typo in beneficiary.service 2025-08-11 00:04:36 +05:30
d6a750092c fixed typo in neft.route 2025-08-10 23:29:17 +05:30
de90be86a7 return random names instead of John Doe in beneficiary validation 2025-08-10 23:28:48 +05:30
asif
cbfd1d6d09 integrated acct statement with date range filter 2025-08-10 18:14:46 +05:30
asif
98ab9954bf code formatting in auth.service 2025-08-10 15:38:38 +05:30
asif
2000ec3e4e implemented RTGS payment feature 2025-08-10 15:29:09 +05:30
asif
bfd062be80 removed logger from neft controller 2025-08-10 15:28:37 +05:30
asif
33ef65de32 implemented neft transaction feature 2025-08-10 15:17:44 +05:30
asif
6f07e9beb9 extracted payment password validator from transfer route to its own validator 2025-08-10 15:16:26 +05:30
asif
dbdc1c7829 removed unnecessary async keyword from validators 2025-08-09 21:43:59 +05:30
asif
1bd618b4fd implemented neft.validator.js 2025-08-09 21:41:29 +05:30
asif
6b6b5679bf reformatted transfer.validator.js 2025-08-09 21:41:04 +05:30
27 changed files with 708 additions and 47 deletions

1
.gitignore vendored
View File

@@ -1,2 +1,3 @@
node_modules/ node_modules/
.env .env
logs/requests.log

View File

@@ -1,6 +1,6 @@
const express = require('express'); const express = require('express');
const cors = require('cors'); const cors = require('cors');
const { logger } = require('./util/logger'); const { logger, requestLogger } = require('./util/logger');
const routes = require('./routes'); const routes = require('./routes');
const app = express(); const app = express();
@@ -9,6 +9,26 @@ app.use(cors());
app.use(express.json()); app.use(express.json());
app.use(express.urlencoded({ extended: true })); app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
requestLogger.info(
{
ip: req.ip || req.connection.remoteAddress,
method: req.method,
url: req.originalUrl,
headers: req.headers,
body: req.body,
status: res.statusCode,
responseTime: `${Date.now() - start}ms`,
},
'Incoming request'
);
});
next();
});
app.use('/api', routes); app.use('/api', routes);
app.get('/health', (_, res) => res.send('server is healthy')); app.get('/health', (_, res) => res.send('server is healthy'));
app.use((err, _req, res, _next) => { app.use((err, _req, res, _next) => {

View File

@@ -14,7 +14,8 @@ async function login(req, res) {
const currentTime = new Date().toISOString(); const currentTime = new Date().toISOString();
try { try {
const user = await authService.validateUser(customerNo, password); const user = await authService.validateUser(customerNo, password);
if (!user) return res.status(401).json({ error: 'invalid credentials' }); if (!user || !password)
return res.status(401).json({ error: 'invalid credentials' });
const token = generateToken(user.customer_no, '1d'); const token = generateToken(user.customer_no, '1d');
const FirstTimeLogin = await authService.CheckFirstTimeLogin(customerNo); const FirstTimeLogin = await authService.CheckFirstTimeLogin(customerNo);
await db.query('UPDATE users SET last_login = $1 WHERE customer_no = $2', [ await db.query('UPDATE users SET last_login = $1 WHERE customer_no = $2', [
@@ -34,7 +35,6 @@ async function fetchUserDetails(req, res) {
const user = await authService.findUserByCustomerNo(customerNo); const user = await authService.findUserByCustomerNo(customerNo);
if (!user) return res.status(404).json({ message: 'USER_NOT_FOUND' }); if (!user) return res.status(404).json({ message: 'USER_NOT_FOUND' });
return res.json(user); return res.json(user);
} catch (err) { } catch (err) {
logger.error(err, 'error occured while fetching user details'); logger.error(err, 'error occured while fetching user details');
res.status(500).json({ error: 'something went wrong' }); res.status(500).json({ error: 'something went wrong' });
@@ -102,4 +102,11 @@ async function setTransactionPassword(req, res) {
} }
} }
module.exports = { login, tpin, setTpin, setLoginPassword, setTransactionPassword,fetchUserDetails }; module.exports = {
login,
tpin,
setTpin,
setLoginPassword,
setTransactionPassword,
fetchUserDetails,
};

View File

@@ -1,6 +1,7 @@
const { logger } = require('../util/logger'); const { logger } = require('../util/logger');
const beneficiaryService = require('../services/beneficiary.service'); const beneficiaryService = require('../services/beneficiary.service');
const db = require('../config/db'); const db = require('../config/db');
const randomName = require('../util/name.generator');
async function validateWithinBank(req, res) { async function validateWithinBank(req, res) {
const { accountNumber } = req.query; const { accountNumber } = req.query;
@@ -40,7 +41,8 @@ async function validateOutsideBank(req, res) {
return res.status(401).json({ error: 'invalid account number' }); return res.status(401).json({ error: 'invalid account number' });
//**IN PRODUCTION** poll the redis server continuously giving the refNo since the response from NPCI will be stored there //**IN PRODUCTION** poll the redis server continuously giving the refNo since the response from NPCI will be stored there
await delay(3000); await delay(3000);
return res.json({ name: 'John Doe' }); const name = randomName();
return res.json({ name });
} catch (err) { } catch (err) {
logger.error(err, 'beneficiary validation within bank failed'); logger.error(err, 'beneficiary validation within bank failed');
res.status(500).json({ error: 'invalid account number' }); res.status(500).json({ error: 'invalid account number' });
@@ -93,6 +95,24 @@ async function getBeneficiary(req, res) {
} }
} }
async function deleteBeneficiary(req, res) {
const { beneficiaryAccountNo } = req.params;
try {
await beneficiaryService.deleteBeneficiary(req.user, beneficiaryAccountNo);
res.status(204).send();
} catch (error) {
if (error.message === 'ACCOUNT_NOT_FOUND') {
logger.warn(
`beneficiary ${beneficiaryAccountNo} does not exist for the customer ${req.user}`
);
return res.status(400).json({ error: 'INVALID_BENEFICIARY_ACCOUNT_NO' });
} else {
logger.error(error, 'error deleting beneficiary');
return res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
}
}
async function getIfscDetails(req, res) { async function getIfscDetails(req, res) {
const { ifscCode } = req.query; const { ifscCode } = req.query;
if (!ifscCode) { if (!ifscCode) {
@@ -125,4 +145,5 @@ module.exports = {
addBeneficiary, addBeneficiary,
getIfscDetails, getIfscDetails,
getBeneficiary, getBeneficiary,
deleteBeneficiary,
}; };

View File

@@ -0,0 +1,56 @@
const axios = require('axios');
const { logger } = require('../util/logger');
const {
recordInterBankTransaction,
} = require('../services/recordkeeping.service');
async function send(
customerNo,
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
beneficiaryAcctType = 'SAVING',
remarks = ''
) {
try {
const reqData = {
stBenAccNo: toAccount,
stBeneName: beneficiaryName,
stBenAccType: beneficiaryAcctType,
stBenIFSC: ifscCode,
stFromAccDetails: fromAccount,
stTransferAmount: amount,
stRemarks: remarks,
};
const response = await axios.post(
'http://localhost:6768/kccb/api/IMPS/Producer',
reqData,
{
headers: {
'Content-Type': 'application/json',
},
}
);
await recordInterBankTransaction(
customerNo,
'imps',
fromAccount,
toAccount,
ifscCode,
amount,
'',
'',
response.data
);
return response.data;
} catch (error) {
logger.error(error, 'error from IMPS');
throw new Error(
'API call failed: ' + (error.response?.data?.message || error.message)
);
}
}
module.exports = { send };

View File

@@ -0,0 +1,52 @@
const axios = require('axios');
const {
recordInterBankTransaction,
} = require('../services/recordkeeping.service');
async function send(
customerNo,
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
remitterName
) {
const commission = 0;
try {
const response = await axios.post(
'http://localhost:8690/kccb/Neftfundtransfer',
{
stFromAcc: fromAccount,
stToAcc: toAccount,
stTranAmt: amount,
stCommission: commission,
stIfscCode: ifscCode,
stFullName: remitterName,
stBeneName: beneficiaryName,
stAddress1: '',
stAddress2: '',
stAddress3: '',
}
);
await recordInterBankTransaction(
customerNo,
'neft',
fromAccount,
toAccount,
ifscCode,
amount,
commission,
beneficiaryName,
remitterName,
response.data.status
);
return response.data;
} catch (error) {
throw new Error(
'API call failed: ' + (error.response?.data?.message || error.message)
);
}
}
module.exports = { send };

View File

@@ -0,0 +1,53 @@
const axios = require('axios');
const {
recordInterBankTransaction,
} = require('../services/recordkeeping.service');
async function send(
customerNo,
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
remitterName
) {
const commission = 0;
try {
const response = await axios.post(
'http://localhost:8690/kccb/Rtgsfundtransfer',
{
stFromAcc: fromAccount,
stToAcc: toAccount,
stTranAmt: amount,
stCommission: commission,
stIfscCode: ifscCode,
stFullName: remitterName,
stBeneName: beneficiaryName,
stAddress1: '',
stAddress2: '',
stAddress3: '',
}
);
await recordInterBankTransaction(
customerNo,
'rtgs',
fromAccount,
toAccount,
ifscCode,
amount,
commission,
beneficiaryName,
remitterName,
response.data.status
);
return response.data;
} catch (error) {
throw new Error(
'API call to CBS failed' +
(error.response?.data?.message || error.message)
);
}
}
module.exports = { send };

View File

@@ -13,6 +13,8 @@ async function getLastTen(accountNumber) {
date: tx.stTransactionDate, date: tx.stTransactionDate,
amount: tx.stTransactionAmount.slice(0, -3), amount: tx.stTransactionAmount.slice(0, -3),
type: tx.stTransactionAmount.slice(-2), type: tx.stTransactionAmount.slice(-2),
balance: tx.stAccountBalance.slice(0, -3),
balanceType: tx.stAccountBalance.slice(-2),
})); }));
return processedTransactions; return processedTransactions;
} catch (error) { } catch (error) {
@@ -21,5 +23,29 @@ async function getLastTen(accountNumber) {
); );
} }
} }
async function getFiltered(accountNumber, fromDate, toDate) {
module.exports = { getLastTen }; try {
const response = await axios.get(
`http://localhost:8688/kccb/cbs/montlyacctstmt/details`,
{
params: { stacctno: accountNumber, fromdate: fromDate, todate: toDate },
}
);
const transactions = response.data;
const processedTransactions = transactions.map((tx) => ({
id: tx.stTransactionNumber,
name: tx.stTransactionDesc,
date: tx.stTransactionDate,
amount: tx.stTransactionAmount.slice(0, -3),
type: tx.stTransactionAmount.slice(-2),
balance: tx.stAccountBalance.slice(0, -3),
balanceType: tx.stAccountBalance.slice(-2),
}));
return processedTransactions;
} catch (error) {
throw new Error(
'API call failde: ' + (error.response?.data?.message || error.message)
);
}
}
module.exports = { getLastTen, getFiltered };

View File

@@ -1,12 +1,15 @@
const axios = require('axios'); const axios = require('axios');
const {
recordIntraBankTransaction,
} = require('../services/recordkeeping.service');
async function transfer( async function transfer(
fromAccountNo, fromAccountNo,
toAccountNo, toAccountNo,
toAccountType, toAccountType,
amount, amount,
// narration = 'transfer from mobile' customerNo,
narration narration = ''
) { ) {
try { try {
const response = await axios.post( const response = await axios.post(
@@ -19,6 +22,14 @@ async function transfer(
narration, narration,
} }
); );
await recordIntraBankTransaction(
customerNo,
fromAccountNo,
toAccountNo,
toAccountType,
amount,
response.data.status
);
return response.data; return response.data;
} catch (error) { } catch (error) {
throw new Error( throw new Error(

View File

@@ -9,6 +9,10 @@ router.get('/user_details', authenticate, authController.fetchUserDetails);
router.get('/tpin', authenticate, authController.tpin); router.get('/tpin', authenticate, authController.tpin);
router.post('/tpin', authenticate, authController.setTpin); router.post('/tpin', authenticate, authController.setTpin);
router.post('/login_password', authenticate, authController.setLoginPassword); router.post('/login_password', authenticate, authController.setLoginPassword);
router.post('/transaction_password', authenticate, authController.setTransactionPassword); router.post(
'/transaction_password',
authenticate,
authController.setTransactionPassword
);
module.exports = router; module.exports = router;

View File

@@ -9,5 +9,9 @@ router.get('/validate/outside-bank', beneficiaryController.validateOutsideBank);
router.get('/ifsc-details', beneficiaryController.getIfscDetails); router.get('/ifsc-details', beneficiaryController.getIfscDetails);
router.get('/', beneficiaryController.getBeneficiary); router.get('/', beneficiaryController.getBeneficiary);
router.post('/', newBeneficiaryValidator, beneficiaryController.addBeneficiary); router.post('/', newBeneficiaryValidator, beneficiaryController.addBeneficiary);
router.delete(
'/:beneficiaryAccountNo',
beneficiaryController.deleteBeneficiary
);
module.exports = router; module.exports = router;

38
src/routes/imps.route.js Normal file
View File

@@ -0,0 +1,38 @@
const express = require('express');
const impsController = require('../controllers/imps.controller');
const { logger } = require('../util/logger');
const impsValidator = require('../validators/imps.validator');
const paymentSecretValidator = require('../validators/payment.secret.validator');
const router = express.Router();
router.use(impsValidator, paymentSecretValidator);
const impsRoute = async (req, res) => {
const { fromAccount, toAccount, ifscCode, amount, beneficiaryName } =
req.body;
try {
const result = await impsController.send(
req.user,
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
'SAVING',
'check'
);
if (result.startsWith('Message produced successfully')) {
return res.json({ message: 'SUCCESS' });
} else {
return res.json({ error: 'INVALID_REQUEST' });
}
} catch (error) {
logger.error(error, 'error occured while doing IMPS');
return res.json({ error: 'INTERVAL_SERVER_ERROR' });
}
};
router.post('/', impsRoute);
module.exports = router;

View File

@@ -5,6 +5,9 @@ const transactionRoute = require('./transactions.route');
const authenticate = require('../middlewares/auth.middleware'); const authenticate = require('../middlewares/auth.middleware');
const transferRoute = require('./transfer.route'); const transferRoute = require('./transfer.route');
const beneficiaryRoute = require('./beneficiary.route'); const beneficiaryRoute = require('./beneficiary.route');
const neftRoute = require('./neft.route');
const rtgsRoute = require('./rtgs.route');
const impsRoute = require('./imps.route');
const { npciResponse } = require('../controllers/npci.controller'); const { npciResponse } = require('../controllers/npci.controller');
const router = express.Router(); const router = express.Router();
@@ -13,6 +16,9 @@ router.use('/auth', authRoute);
router.use('/customer', authenticate, detailsRoute); router.use('/customer', authenticate, detailsRoute);
router.use('/transactions/account/:accountNo', authenticate, transactionRoute); router.use('/transactions/account/:accountNo', authenticate, transactionRoute);
router.use('/payment/transfer', authenticate, transferRoute); router.use('/payment/transfer', authenticate, transferRoute);
router.use('/payment/neft', authenticate, neftRoute);
router.use('/payment/rtgs', authenticate, rtgsRoute);
router.use('/payment/imps', authenticate, impsRoute);
router.use('/beneficiary', authenticate, beneficiaryRoute); router.use('/beneficiary', authenticate, beneficiaryRoute);
router.use('/npci/beneficiary-response', npciResponse); router.use('/npci/beneficiary-response', npciResponse);

50
src/routes/neft.route.js Normal file
View File

@@ -0,0 +1,50 @@
const express = require('express');
const neftController = require('../controllers/neft.controller');
const { logger } = require('../util/logger');
const neftValidator = require('../validators/neft.validator.js');
const paymentSecretValidator = require('../validators/payment.secret.validator');
const router = express.Router();
router.use(neftValidator, paymentSecretValidator);
const neftRoute = async (req, res) => {
const {
fromAccount,
toAccount,
ifscCode,
amount,
beneficiaryName,
remitterName,
} = req.body;
try {
const result = await neftController.send(
req.user,
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
remitterName
);
logger.info(result);
if (result.status.startsWith('O.K.')) {
const utr = result.status.slice(9, 25);
return res.json({ message: 'SUCCESS', utr });
} else if (result.status.includes('INSUFFICIENT FUNDS')) {
return res.status(422).json({ error: 'INSUFFICIENT_FUNDS' });
} else if (result.status.includes('INVALID CHECK DIGIT')) {
return res.status(400).json({ error: 'INVALID_ACCOUNT_NUMBER' });
} else {
return res.status(400).json({ error: 'PROBLEM_TRANSFERRING_FUNDS' });
}
} catch (error) {
logger.error(error, 'error occured while doing NEFT transaction');
return res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
};
router.post('/', neftRoute);
module.exports = router;

49
src/routes/rtgs.route.js Normal file
View File

@@ -0,0 +1,49 @@
const express = require('express');
const rtgsController = require('../controllers/rtgs.controller');
const { logger } = require('../util/logger');
const rtgsValidator = require('../validators/rtgs.validator.js');
const paymentSecretValidator = require('../validators/payment.secret.validator');
const router = express.Router();
router.use(rtgsValidator, paymentSecretValidator);
const rtgsRoute = async (req, res) => {
const {
fromAccount,
toAccount,
ifscCode,
amount,
beneficiaryName,
remitterName,
} = req.body;
try {
const result = await rtgsController.send(
req.user,
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
remitterName
);
if (result.status.startsWith('O.K.')) {
const utr = result.status.slice(9, 25);
return res.json({ message: 'SUCCESS', utr });
} else if (result.status.includes('INSUFFICIENT FUNDS')) {
return res.status(422).json({ error: 'INSUFFICIENT_FUNDS' });
} else if (result.status.includes('INVALID CHECK DIGIT')) {
return res.status(400).json({ error: 'INVALID_ACCOUNT_NUMBER' });
} else {
return res.status(400).json({ error: 'PROBLEM_TRANSFERRING_FUNDS' });
}
} catch (error) {
logger.error(error, 'error occured while doing NEFT transaction');
return res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
};
router.post('/', rtgsRoute);
module.exports = router;

View File

@@ -3,15 +3,44 @@ const { logger } = require('../util/logger');
const transactionsRoute = async (req, res) => { const transactionsRoute = async (req, res) => {
const accountNo = req.params.accountNo; const accountNo = req.params.accountNo;
const { fromDate, toDate } = req.query;
let data;
try { try {
const data = await transactionsController.getLastTen(accountNo); if (fromDate && toDate) {
if (!isValidDDMMYYYY(fromDate) || !isValidDDMMYYYY(toDate)) {
return res.status(400).json({ error: 'INVALID_DATE_FORMAT' });
}
data = await transactionsController.getFiltered(
accountNo,
fromDate,
toDate
);
} else {
data = await transactionsController.getLastTen(accountNo);
}
return res.json(data); return res.json(data);
} catch (error) { } catch (error) {
logger.error('error retriving last 10 txns', error); logger.error('error retriving transaction history', error);
return res return res
.status(500) .status(500)
.json({ message: 'error occured while fetching transactions' }); .json({ message: 'error occured while fetching transactions' });
} }
}; };
function isValidDDMMYYYY(dateStr) {
if (!/^\d{8}$/.test(dateStr)) return false;
const day = parseInt(dateStr.slice(0, 2), 10);
const month = parseInt(dateStr.slice(2, 4), 10);
const year = parseInt(dateStr.slice(4), 10);
const date = new Date(year, month - 1, day);
return (
date.getFullYear() === year &&
date.getMonth() === month - 1 &&
date.getDate() === day
);
}
module.exports = transactionsRoute; module.exports = transactionsRoute;

View File

@@ -1,24 +1,10 @@
const transferController = require('../controllers/transfer.controller'); const transferController = require('../controllers/transfer.controller');
const { logger } = require('../util/logger'); const { logger } = require('../util/logger');
const express = require('express'); const express = require('express');
const tpinValidator = require('../validators/tpin.validator');
const tpasswordValidator = require('../validators/tpassword.validator');
const transferValidator = require('../validators/transfer.validator'); const transferValidator = require('../validators/transfer.validator');
const passwordValidator = require('../validators/payment.secret.validator.js');
const router = express.Router(); const router = express.Router();
// Added for tpassword
const passwordValidator=async(req,res,next)=>{
const{tpin,tpassword} =req.body;
if(tpin){
return tpinValidator(req,res,next);
}
else if(tpassword){
return tpasswordValidator(req,res,next);
}
else{
return res.status(400).json({error:"tpin or tpassword is required"})
}
}
router.use(passwordValidator, transferValidator); router.use(passwordValidator, transferValidator);
const transferRoute = async (req, res) => { const transferRoute = async (req, res) => {
@@ -28,7 +14,8 @@ const transferRoute = async (req, res) => {
fromAccount, fromAccount,
toAccount, toAccount,
toAccountType, toAccountType,
amount amount,
req.user
); );
if (result.status === 'O.K.') { if (result.status === 'O.K.') {

View File

@@ -48,10 +48,10 @@ async function setTpin(customerNo, tpin) {
async function setLoginPassword(customerNo, login_psw) { async function setLoginPassword(customerNo, login_psw) {
const hashedLoginPassword = await hashPassword(login_psw); const hashedLoginPassword = await hashPassword(login_psw);
try { try {
await db.query('UPDATE users SET password_hash = $1 ,is_first_login = false WHERE customer_no = $2', [ await db.query(
hashedLoginPassword, 'UPDATE users SET password_hash = $1 ,is_first_login = false WHERE customer_no = $2',
customerNo, [hashedLoginPassword, customerNo]
]); );
} catch (error) { } catch (error) {
throw new Error( throw new Error(
`error occured while while setting new Login Password ${error.message}` `error occured while while setting new Login Password ${error.message}`
@@ -62,7 +62,7 @@ async function setLoginPassword(customerNo, login_psw) {
async function validateTransactionPassword(customerNo, tpassword) { async function validateTransactionPassword(customerNo, tpassword) {
const user = await findUserByCustomerNo(customerNo); const user = await findUserByCustomerNo(customerNo);
if (!user?.transaction_password) return null; if (!user?.transaction_password) return null;
const isMatch = await comparePassword(tpassword, user.transaction_password ); const isMatch = await comparePassword(tpassword, user.transaction_password);
return isMatch; return isMatch;
} }
@@ -70,10 +70,10 @@ async function validateTransactionPassword(customerNo, tpassword) {
async function setTransactionPassword(customerNo, trans_psw) { async function setTransactionPassword(customerNo, trans_psw) {
const hashedTransPassword = await hashPassword(trans_psw); const hashedTransPassword = await hashPassword(trans_psw);
try { try {
await db.query('UPDATE users SET transaction_password = $1 WHERE customer_no = $2', [ await db.query(
hashedTransPassword, 'UPDATE users SET transaction_password = $1 WHERE customer_no = $2',
customerNo, [hashedTransPassword, customerNo]
]); );
} catch (error) { } catch (error) {
throw new Error( throw new Error(
`error occured while while setting new Transaction Password ${error.message}` `error occured while while setting new Transaction Password ${error.message}`
@@ -81,5 +81,13 @@ async function setTransactionPassword(customerNo, trans_psw) {
} }
} }
module.exports = { validateUser, findUserByCustomerNo, setTpin, validateTpin, module.exports = {
CheckFirstTimeLogin, setLoginPassword, validateTransactionPassword,setTransactionPassword }; validateUser,
findUserByCustomerNo,
setTpin,
validateTpin,
CheckFirstTimeLogin,
setLoginPassword,
validateTransactionPassword,
setTransactionPassword,
};

View File

@@ -44,6 +44,16 @@ async function getSingleBeneficiary(customerNo, accountNo) {
return result.rows[0]; return result.rows[0];
} }
async function deleteBeneficiary(customerNo, beneficiaryAccountNo) {
const queryStr =
'DELETE FROM beneficiaries WHERE customer_no = $1 AND account_no = $2';
const result = await db.query(queryStr, [customerNo, beneficiaryAccountNo]);
if (result.rowCount == 0) {
throw new Error('ACCOUNT_NOT_FOUND');
}
return;
}
async function getAllBeneficiaries(customerNo) { async function getAllBeneficiaries(customerNo) {
const queryStr = 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'; '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';
@@ -53,10 +63,10 @@ async function getAllBeneficiaries(customerNo) {
accountNo: row['account_no'], accountNo: row['account_no'],
name: row['name'], name: row['name'],
accountType: row['account_type'], accountType: row['account_type'],
ifscCdoe: row['ifsc_code'], ifscCode: row['ifsc_code'],
bankName: row['bank_name'], bankName: row['bank_name'],
branchName: row['branch_name'], branchName: row['branch_name'],
} };
}); });
return list; return list;
@@ -66,4 +76,5 @@ module.exports = {
validateOutsideBank, validateOutsideBank,
getAllBeneficiaries, getAllBeneficiaries,
getSingleBeneficiary, getSingleBeneficiary,
deleteBeneficiary,
}; };

View File

@@ -0,0 +1,52 @@
const db = require('../config/db');
const recordIntraBankTransaction = async (
customerNo,
fromAccount,
toAccount,
accountType,
amount,
status
) => {
const trxType = 'TRF';
const query =
'INSERT INTO transactions (customer_no, trx_type, from_account, to_account, to_account_type, amount, status) VALUES ($1, $2, $3, $4, $5, $6, $7)';
await db.query(query, [
customerNo,
trxType,
fromAccount,
toAccount,
accountType,
amount,
status,
]);
};
const recordInterBankTransaction = async (
customerNo,
trxType,
fromAccount,
toAccount,
ifscCode,
amount,
commission,
beneficiaryName,
remitterName,
status
) => {
const query =
'INSERT INTO transactions (customer_no, trx_type, from_account, to_account, ifsc_code, amount, commission, beneficiary_name, remitter_name, status) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)';
await db.query(query, [
customerNo,
trxType,
fromAccount,
toAccount,
ifscCode,
amount,
commission,
beneficiaryName,
remitterName,
status,
]);
};
module.exports = { recordIntraBankTransaction, recordInterBankTransaction };

View File

@@ -1,6 +1,19 @@
const pino = require('pino'); const pino = require('pino');
const fs = require('fs');
const path = require('path');
const isDev = process.env.NODE_ENV !== 'production'; const isDev = process.env.NODE_ENV !== 'production';
const logDir = path.join(__dirname, '../..', 'logs');
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
const requestLoggerStream = pino.destination({
dest: path.join(logDir, 'requests.log'),
sync: false,
});
const logger = pino({ const logger = pino({
transport: isDev transport: isDev
? { ? {
@@ -15,8 +28,12 @@ const logger = pino({
level: isDev ? 'debug' : 'info', level: isDev ? 'debug' : 'info',
}); });
const requestLogger = (req, _res, next) => { const requestLogger = pino(
logger.info(`${req.method} ${req.url}`); {
next(); level: 'info',
}; base: null,
},
requestLoggerStream
);
module.exports = { logger, requestLogger }; module.exports = { logger, requestLogger };

View File

@@ -0,0 +1,36 @@
const indianFirstNames = [
'Aarav',
'Vivaan',
'Aditya',
'Vihaan',
'Krishna',
'Ishaan',
'Rohan',
'Ananya',
'Diya',
'Aisha',
'Priya',
'Sneha',
];
const indianLastNames = [
'Sharma',
'Verma',
'Iyer',
'Reddy',
'Patel',
'Mehta',
'Choudhary',
'Kumar',
'Das',
'Rao',
];
function getRandomIndianName() {
const firstName =
indianFirstNames[Math.floor(Math.random() * indianFirstNames.length)];
const lastName =
indianLastNames[Math.floor(Math.random() * indianLastNames.length)];
return `${firstName} ${lastName}`;
}
module.exports = getRandomIndianName;

View File

@@ -0,0 +1,36 @@
const impsValidator = (req, res, next) => {
const {
fromAccount,
toAccount,
amount,
remitterName,
beneficiaryName,
ifscCode,
} = req.body;
if (!isAccountNumbersValid(fromAccount, toAccount)) {
return res.status(400).json({ error: 'INVALID_ACCOUNT_NUMBER_FORMAT' });
}
if (amount < 1) {
return res.status(400).json({ error: 'INVALID_AMOUNT' });
}
if (!remitterName || !beneficiaryName) {
return res
.status(400)
.json({ error: 'REMITTER_NAME AND BENEFICIARY_NAME REQUIRED' });
}
if (!ifscCode || !/^[A-Z]{4}0[0-9]{6}$/.test(ifscCode)) {
return res.status(400).json({ error: 'INVALID_IFSC_CODE' });
}
next();
};
const isAccountNumbersValid = (fromAcct, toAcct) => {
return !(!fromAcct || !toAcct || fromAcct.length != 11 || toAcct.length < 7);
};
module.exports = impsValidator;

View File

@@ -0,0 +1,36 @@
const neftValidator = (req, res, next) => {
const {
fromAccount,
toAccount,
amount,
remitterName,
beneficiaryName,
ifscCode,
} = req.body;
if (!isAccountNumbersValid(fromAccount, toAccount)) {
return res.status(400).json({ error: 'INVALID_ACCOUNT_NUMBER_FORMAT' });
}
if (amount < 1) {
return res.status(400).json({ error: 'INVALID_AMOUNT' });
}
if (!remitterName || !beneficiaryName) {
return res
.status(400)
.json({ error: 'REMITTER_NAME AND BENEFICIARY_NAME REQUIRED' });
}
if (!ifscCode || !/^[A-Z]{4}0[0-9]{6}$/.test(ifscCode)) {
return res.status(400).json({ error: 'INVALID_IFSC_CODE' });
}
next();
};
const isAccountNumbersValid = (fromAcct, toAcct) => {
return !(!fromAcct || !toAcct || fromAcct.length != 11 || toAcct.length < 7);
};
module.exports = neftValidator;

View File

@@ -0,0 +1,15 @@
const tpasswordValidator = require('./tpassword.validator.js');
const tpinValidator = require('./tpin.validator.js');
const paymentSecretValidator = async (req, res, next) => {
const { tpin, tpassword } = req.body;
if (tpin) {
return tpinValidator(req, res, next);
} else if (tpassword) {
return tpasswordValidator(req, res, next);
} else {
return res.status(400).json({ error: 'tpin or tpassword is required' });
}
};
module.exports = paymentSecretValidator;

View File

@@ -0,0 +1,36 @@
const rtgsValidator = (req, res, next) => {
const {
fromAccount,
toAccount,
amount,
remitterName,
beneficiaryName,
ifscCode,
} = req.body;
if (!isAccountNumbersValid(fromAccount, toAccount)) {
return res.status(400).json({ error: 'INVALID_ACCOUNT_NUMBER_FORMAT' });
}
if (amount < 200000) {
return res.status(400).json({ error: 'AMOUNT_SHOULD_BE_MORE_THAN_200000' });
}
if (!remitterName || !beneficiaryName) {
return res
.status(400)
.json({ error: 'REMITTER_NAME AND BENEFICIARY_NAME REQUIRED' });
}
if (!ifscCode || !/^[A-Z]{4}0[0-9]{6}$/.test(ifscCode)) {
return res.status(400).json({ error: 'INVALID_IFSC_CODE' });
}
next();
};
const isAccountNumbersValid = (fromAcct, toAcct) => {
return !(!fromAcct || !toAcct || fromAcct.length != 11 || toAcct.length < 7);
};
module.exports = rtgsValidator;

View File

@@ -1,7 +1,7 @@
const transferValidator = async (req, res, next) => { const transferValidator = (req, res, next) => {
const { fromAccount, toAccount, toAccountType, amount } = req.body; const { fromAccount, toAccount, toAccountType, amount } = req.body;
const accountTypes = ['SB', 'LN','Savings','Current']; const accountTypes = ['SB', 'LN', 'Savings', 'Current'];
if (!fromAccount || fromAccount.length != 11) { if (!fromAccount || fromAccount.length != 11) {
return res.status(400).json({ error: 'INVALID_ACCOUNT_NUMBER_FORMAT' }); return res.status(400).json({ error: 'INVALID_ACCOUNT_NUMBER_FORMAT' });
} }