9 Commits

17 changed files with 214 additions and 15 deletions

1
.gitignore vendored
View File

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

View File

@@ -1,14 +1,36 @@
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 helmet = require('helmet');
const app = express(); const app = express();
app.use(cors()); app.use(cors());
app.use(helmet());
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

@@ -95,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) {
@@ -127,4 +145,5 @@ module.exports = {
addBeneficiary, addBeneficiary,
getIfscDetails, getIfscDetails,
getBeneficiary, getBeneficiary,
deleteBeneficiary,
}; };

View File

@@ -1,7 +1,11 @@
const axios = require('axios'); const axios = require('axios');
const { logger } = require('../util/logger'); const { logger } = require('../util/logger');
const {
recordInterBankTransaction,
} = require('../services/recordkeeping.service');
async function send( async function send(
customerNo,
fromAccount, fromAccount,
toAccount, toAccount,
amount, amount,
@@ -20,7 +24,6 @@ async function send(
stTransferAmount: amount, stTransferAmount: amount,
stRemarks: remarks, stRemarks: remarks,
}; };
logger.info(reqData, 'request data to be sent to IMPS server');
const response = await axios.post( const response = await axios.post(
'http://localhost:6768/kccb/api/IMPS/Producer', 'http://localhost:6768/kccb/api/IMPS/Producer',
reqData, reqData,
@@ -30,7 +33,17 @@ async function send(
}, },
} }
); );
logger.info(response, 'response from IMPS'); await recordInterBankTransaction(
customerNo,
'imps',
fromAccount,
toAccount,
ifscCode,
amount,
'',
'',
response.data
);
return response.data; return response.data;
} catch (error) { } catch (error) {
logger.error(error, 'error from IMPS'); logger.error(error, 'error from IMPS');

View File

@@ -1,6 +1,10 @@
const axios = require('axios'); const axios = require('axios');
const {
recordInterBankTransaction,
} = require('../services/recordkeeping.service');
async function send( async function send(
customerNo,
fromAccount, fromAccount,
toAccount, toAccount,
amount, amount,
@@ -8,6 +12,7 @@ async function send(
beneficiaryName, beneficiaryName,
remitterName remitterName
) { ) {
const commission = 0;
try { try {
const response = await axios.post( const response = await axios.post(
'http://localhost:8690/kccb/Neftfundtransfer', 'http://localhost:8690/kccb/Neftfundtransfer',
@@ -15,7 +20,7 @@ async function send(
stFromAcc: fromAccount, stFromAcc: fromAccount,
stToAcc: toAccount, stToAcc: toAccount,
stTranAmt: amount, stTranAmt: amount,
stCommission: 0, stCommission: commission,
stIfscCode: ifscCode, stIfscCode: ifscCode,
stFullName: remitterName, stFullName: remitterName,
stBeneName: beneficiaryName, stBeneName: beneficiaryName,
@@ -24,6 +29,18 @@ async function send(
stAddress3: '', stAddress3: '',
} }
); );
await recordInterBankTransaction(
customerNo,
'neft',
fromAccount,
toAccount,
ifscCode,
amount,
commission,
beneficiaryName,
remitterName,
response.data.status
);
return response.data; return response.data;
} catch (error) { } catch (error) {
throw new Error( throw new Error(

View File

@@ -1,6 +1,10 @@
const axios = require('axios'); const axios = require('axios');
const {
recordInterBankTransaction,
} = require('../services/recordkeeping.service');
async function send( async function send(
customerNo,
fromAccount, fromAccount,
toAccount, toAccount,
amount, amount,
@@ -8,6 +12,7 @@ async function send(
beneficiaryName, beneficiaryName,
remitterName remitterName
) { ) {
const commission = 0;
try { try {
const response = await axios.post( const response = await axios.post(
'http://localhost:8690/kccb/Rtgsfundtransfer', 'http://localhost:8690/kccb/Rtgsfundtransfer',
@@ -15,7 +20,7 @@ async function send(
stFromAcc: fromAccount, stFromAcc: fromAccount,
stToAcc: toAccount, stToAcc: toAccount,
stTranAmt: amount, stTranAmt: amount,
stCommission: 0, stCommission: commission,
stIfscCode: ifscCode, stIfscCode: ifscCode,
stFullName: remitterName, stFullName: remitterName,
stBeneName: beneficiaryName, stBeneName: beneficiaryName,
@@ -24,6 +29,18 @@ async function send(
stAddress3: '', stAddress3: '',
} }
); );
await recordInterBankTransaction(
customerNo,
'rtgs',
fromAccount,
toAccount,
ifscCode,
amount,
commission,
beneficiaryName,
remitterName,
response.data.status
);
return response.data; return response.data;
} catch (error) { } catch (error) {
throw new Error( throw new Error(

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) {
@@ -36,6 +38,8 @@ async function getFiltered(accountNumber, fromDate, toDate) {
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) {

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,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;

View File

@@ -13,6 +13,7 @@ const impsRoute = async (req, res) => {
try { try {
const result = await impsController.send( const result = await impsController.send(
req.user,
fromAccount, fromAccount,
toAccount, toAccount,
amount, amount,

View File

@@ -19,6 +19,7 @@ const neftRoute = async (req, res) => {
try { try {
const result = await neftController.send( const result = await neftController.send(
req.user,
fromAccount, fromAccount,
toAccount, toAccount,
amount, amount,

View File

@@ -19,6 +19,7 @@ const rtgsRoute = async (req, res) => {
try { try {
const result = await rtgsController.send( const result = await rtgsController.send(
req.user,
fromAccount, fromAccount,
toAccount, toAccount,
amount, amount,

View File

@@ -14,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

@@ -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';
@@ -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 };