18 Commits

Author SHA1 Message Date
asif
7e0c9d251e fixed an error on redis js of undefined err 2025-08-09 20:51:07 +05:30
asif
6e8eccd767 returning a valid response after creating a beneficiary
also throw 409 status code if account already exists in beneficiaries table against that customer
2025-08-09 15:51:28 +05:30
asif
20af204304 changed the beneficiary routes to follow standards
/beneficiary send GET AND POST request for retrieving or adding beneficiaries
2025-08-09 15:50:16 +05:30
asif
9316a41646 made the function validateOutsideBank return beneficiary name rather than refNo
Also removed the now redundant checkBeneficiaryName controller and paths
2025-08-09 13:49:25 +05:30
2d39e1e66d added routes for validating beneficiary outside bank, checking beneficiary name after successful validation and getting beneficiary list of the customer 2025-08-08 20:46:32 +05:30
90cbddd248 added functions for validate outside bank, check beneficiary name and get beneficiary 2025-08-08 20:45:13 +05:30
29d0949039 modified handle NPCI success method to only put the beneficiary name in redis 2025-08-08 20:43:42 +05:30
c331ba5505 changed ifsc_code_bank table name to ifsc_details 2025-08-08 20:42:39 +05:30
123d5c9f1d added two methods to get registered beneficiaries for a customer 2025-08-08 20:40:10 +05:30
e75ff4d658 added authentication for all beneficiary routes
added npci routes for receiving responses from NPCI for beneficiary validation requests
2025-08-07 02:02:25 +05:30
ecb9b14629 implemented a controller for processing all the responses we will get from NPCI for beneficiary validation 2025-08-07 02:01:03 +05:30
35bd668116 implemented validator to validate beneficiary details 2025-08-07 01:59:27 +05:30
ae14968739 added service for sending beneficiary details to NPCI interface 2025-08-07 01:58:37 +05:30
6d675ad81c added controllers for beneficiary addition, checking and fetching ifsc details 2025-08-07 01:57:50 +05:30
df68fc4a29 added routes for beneficiary addition, checking and fetching ifsc details 2025-08-07 01:57:02 +05:30
e9a001ecf6 added redis configuration 2025-08-07 01:55:21 +05:30
9093da6bc9 changed port number for development 2025-08-04 15:11:07 +05:30
b88e00f758 added beneficiary routes, controllers and services 2025-07-31 12:28:26 +05:30
11 changed files with 385 additions and 11 deletions

3
.env
View File

@@ -1,3 +0,0 @@
PORT=8080
DATABASE_URL=postgresql://kmobile_app_rw:kmobile@localhost:5431/kmobile_banking
JWT_SECRET=supersecret

1
.gitignore vendored
View File

@@ -1 +1,2 @@
node_modules/
.env

94
package-lock.json generated
View File

@@ -17,7 +17,9 @@
"jsonwebtoken": "^9.0.2",
"pg": "^8.16.0",
"pino": "^9.7.0",
"pino-http": "^10.4.0"
"pino-http": "^10.4.0",
"redis": "^5.7.0",
"uuid": "^11.1.0"
},
"devDependencies": {
"@eslint/js": "^9.28.0",
@@ -265,6 +267,61 @@
"url": "https://opencollective.com/pkgr"
}
},
"node_modules/@redis/bloom": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-5.7.0.tgz",
"integrity": "sha512-KtBHDH2Aw1BxYDQd87PJsdEmZcpMbD4oPzdBwB4IvSRmMovukO2NNGi5vpCHhCoicS83zu7cjX1fw79uFBZFJA==",
"engines": {
"node": ">= 18"
},
"peerDependencies": {
"@redis/client": "^5.7.0"
}
},
"node_modules/@redis/client": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/@redis/client/-/client-5.7.0.tgz",
"integrity": "sha512-YV3Knspdj9k6H6s4v8QRcj1WBxHt40vtPmszLKGwRUOUpUOLWSlI9oCUjprMDcQNzgSCXGXYdL/Aj6nT2+Ub0w==",
"dependencies": {
"cluster-key-slot": "1.1.2"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/@redis/json": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/@redis/json/-/json-5.7.0.tgz",
"integrity": "sha512-VP3wtse1PSB/UjZAV1lWyDrWrrZcwi/cjb3L0lIarcIJ+EbHliB2QPml0Bvjz8F8F0eDJRtChJVXFc+jhGxCtA==",
"engines": {
"node": ">= 18"
},
"peerDependencies": {
"@redis/client": "^5.7.0"
}
},
"node_modules/@redis/search": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/@redis/search/-/search-5.7.0.tgz",
"integrity": "sha512-dDZIq8pZJnT+kZ9xRlLLi2Rvkd792z9eh31QRIwPr5wXjAXeaQ+Nf65em6dLpsxZ60MmhwDwLrBPJpYVjKPBPQ==",
"engines": {
"node": ">= 18"
},
"peerDependencies": {
"@redis/client": "^5.7.0"
}
},
"node_modules/@redis/time-series": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-5.7.0.tgz",
"integrity": "sha512-AJTF9sz3y1MJAukgQW4Jw8zt8qGOE3+1d87pufOP35zsFBlHipGscpctoXiNMebfy0114y/FjSprr65LjbJQSQ==",
"engines": {
"node": ">= 18"
},
"peerDependencies": {
"@redis/client": "^5.7.0"
}
},
"node_modules/@types/estree": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz",
@@ -644,6 +701,14 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/cluster-key-slot": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz",
"integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -2894,6 +2959,21 @@
"node": ">= 12.13.0"
}
},
"node_modules/redis": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/redis/-/redis-5.7.0.tgz",
"integrity": "sha512-ZRbiWYBUYdDTopodRjCVwwCLThrkciPW3bOrkdMCW3nYEelBwUGN6SovmACDsiLUB7mnU3mXnaI5f0W7bDcwng==",
"dependencies": {
"@redis/bloom": "5.7.0",
"@redis/client": "5.7.0",
"@redis/json": "5.7.0",
"@redis/search": "5.7.0",
"@redis/time-series": "5.7.0"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/resolve-from": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
@@ -3399,6 +3479,18 @@
"punycode": "^2.1.0"
}
},
"node_modules/uuid": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",
"integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"bin": {
"uuid": "dist/esm/bin/uuid"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",

View File

@@ -21,7 +21,9 @@
"jsonwebtoken": "^9.0.2",
"pg": "^8.16.0",
"pino": "^9.7.0",
"pino-http": "^10.4.0"
"pino-http": "^10.4.0",
"redis": "^5.7.0",
"uuid": "^11.1.0"
},
"devDependencies": {
"@eslint/js": "^9.28.0",

58
src/config/redis.js Normal file
View File

@@ -0,0 +1,58 @@
const { createClient } = require('redis');
const { redisUrl } = require('./config');
const { logger } = require('../util/logger');
const client = createClient({
url: redisUrl,
socket: {
reconnectStrategy: (retries) => {
const delay = Math.min(retries * 100, 5000);
logger.info(`Redis reconnecting attempt ${retries}, delay ${delay}ms`);
return delay;
},
},
});
client.on('connect', () => logger.info('Connected to redis'));
client.on('error', (err) => logger.error(err, 'Redis error'));
client.on('ready', () => logger.info('Redis client ready'));
client.on('end', () => logger.info('Redis connection closed'));
client
.connect()
.catch((err) => logger.error(err, 'Failed to connect to Redis'));
// Helper functions
async function setJson(key, value, ttl = null) {
try {
const jsonValue = JSON.stringify(value);
if (ttl) {
return await client.set(key, jsonValue, { EX: ttl });
}
return await client.set(key, jsonValue);
} catch (err) {
logger.error(err, 'Redis setJson error');
throw err;
}
}
async function getJson(key) {
try {
const value = await client.get(key);
return value ? JSON.parse(value) : null;
} catch (err) {
logger.error(err, 'Redis getJson error');
throw err;
}
}
process.on('SIGTERM', async () => {
logger.info('SIGTERM received - closing Redis connection');
await client.quit();
});
module.exports = {
client,
getJson,
setJson,
};

View File

@@ -1,5 +1,6 @@
const { logger } = require('../util/logger');
const beneficiaryService = require('../services/beneficiary.service');
const db = require('../config/db');
async function validateWithinBank(req, res) {
const { accountNumber } = req.query;
@@ -22,4 +23,106 @@ async function validateWithinBank(req, res) {
}
}
module.exports = { validateWithinBank };
async function validateOutsideBank(req, res) {
const { accountNo, ifscCode, remitterName } = req.query;
if (!accountNo || !ifscCode || !remitterName) {
res.status(401).json({ error: 'BAD_REQUEST' });
return;
}
try {
const refNo = await beneficiaryService.validateOutsideBank(
accountNo,
ifscCode,
remitterName
);
if (!refNo)
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
await delay(3000);
return res.json({ name: 'John Doe' });
} catch (err) {
logger.error(err, 'beneficiary validation within bank failed');
res.status(500).json({ error: 'invalid account number' });
}
}
async function addBeneficiary(req, res) {
try {
const { accountNo, ifscCode, accountType, name } = req.body;
const customerNo = req.user;
const query =
'INSERT INTO beneficiaries (customer_no, account_no, account_type, ifsc_code, name) VALUES ($1, $2, $3, $4, $5)';
await db.query(query, [customerNo, accountNo, accountType, ifscCode, name]);
res.json({ message: 'SUCCESS' });
} catch (error) {
logger.error(error, 'Error adding beneficiary');
if (
error.message ==
'duplicate key value violates unique constraint "beneficiaries_pkey"'
) {
res.status(409).json({ error: 'BENEFICIARY_ALREADY_EXITS' });
}
res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
}
async function getBeneficiary(req, res) {
const { accountNo } = req.query;
let beneficiaryDetails;
try {
if (accountNo) {
beneficiaryDetails = await beneficiaryService.getSingleBeneficiary(
req.user,
accountNo
);
} else {
beneficiaryDetails = await beneficiaryService.getAllBeneficiaries(
req.user
);
}
if (!beneficiaryDetails) {
res.status(404).json({ error: 'NO_BENEFICIARY_FOUND' });
return;
}
res.json(beneficiaryDetails);
} catch (error) {
logger.error(error, 'error fetching beneficiaries');
res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
}
async function getIfscDetails(req, res) {
const { ifscCode } = req.query;
if (!ifscCode) {
res.status(403).json({ error: 'BAD_REQUEST' });
return;
}
console.log(ifscCode);
try {
const query = 'SELECT * FROM ifsc_details WHERE ifsc_code = $1';
const result = await db.query(query, [ifscCode]);
console.log(result.rows);
if (!result.rows) {
res.status(404).json({ error: 'NOT_FOUND' });
return;
}
res.json(result.rows[0]);
} catch (error) {
logger.error(error, 'error fetching ifsc code');
res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
module.exports = {
validateWithinBank,
validateOutsideBank,
addBeneficiary,
getIfscDetails,
getBeneficiary,
};

View File

@@ -0,0 +1,28 @@
const db = require('../config/db');
const { getJson, setJson } = require('../config/redis');
const { logger } = require('../util/logger');
async function npciResponse(req, res) {
const { resp } = req.body;
if (resp.status === 'Success') {
await handleNPCISuccess(resp);
} else {
await handleNPCIFailure(resp);
}
res.send('ok');
}
async function handleNPCISuccess(response) {
const { txnid, benename } = response;
try {
await setJson(txnid, benename);
} catch (error) {
logger.error(error, 'error processing npci response');
}
}
async function handleNPCIFailure(response) {
console.log(response);
}
module.exports = { npciResponse };

View File

@@ -1,8 +1,13 @@
const express = require('express');
const beneficiaryController = require('../controllers/beneficiary.controller');
const newBeneficiaryValidator = require('../validators/beneficiary.validator');
const router = express.Router();
router.get('/validate/within-bank', beneficiaryController.validateWithinBank);
router.get('/validate/outside-bank', beneficiaryController.validateOutsideBank);
router.get('/ifsc-details', beneficiaryController.getIfscDetails);
router.get('/', beneficiaryController.getBeneficiary);
router.post('/', newBeneficiaryValidator, beneficiaryController.addBeneficiary);
module.exports = router;

View File

@@ -5,6 +5,7 @@ const transactionRoute = require('./transactions.route');
const authenticate = require('../middlewares/auth.middleware');
const transferRoute = require('./transfer.route');
const beneficiaryRoute = require('./beneficiary.route');
const { npciResponse } = require('../controllers/npci.controller');
const router = express.Router();
@@ -12,6 +13,7 @@ router.use('/auth', authRoute);
router.use('/customer', authenticate, detailsRoute);
router.use('/transactions/account/:accountNo', authenticate, transactionRoute);
router.use('/payment/transfer', authenticate, transferRoute);
router.use('/beneficiary', beneficiaryRoute);
router.use('/beneficiary', authenticate, beneficiaryRoute);
router.use('/npci/beneficiary-response', npciResponse);
module.exports = router;

View File

@@ -1,10 +1,15 @@
const axios = require('axios');
const { logger } = require('../util/logger');
const { v4: uuidv4 } = require('uuid');
const db = require('../config/db');
async function validateWithinBank(accountNo) {
const url = `http://localhost:8687/kccb/cbs/acctInfo/details?stacctno=${accountNo}`;
const url = 'http://localhost:8687/kccb/cbs/acctInfo/details';
try {
const response = await fetch(url);
const data = await response.json();
const response = await axios.get(url, {
params: { stacctno: accountNo },
});
const data = response.data;
const customerName = data.customername;
return customerName;
} catch (error) {
@@ -13,4 +18,52 @@ async function validateWithinBank(accountNo) {
}
}
module.exports = { validateWithinBank };
async function validateOutsideBank(accountNo, ifscCode, name) {
const uuid = `KCC${uuidv4().replace(/-/g, '')}`;
const url = `http://localhost:9091/kccb/benenamelookup/ReqBeneDetails/${uuid}`;
try {
const response = await axios.post(url, {
acctNo: accountNo,
ifsccode: ifscCode,
remittername: name,
});
if (response.data) {
console.log(response.data);
return uuid;
}
} catch (error) {
logger.error(error, 'error while validating customer from NPCI');
throw new Error('error in beneficiary validation');
}
}
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';
const result = await db.query(queryStr, [customerNo, accountNo]);
return result.rows[0];
}
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 ifsc_details i ON b.ifsc_code = i.ifsc_code WHERE customer_no = $1';
const result = await db.query(queryStr, [customerNo]);
const list = result.rows.map((row) => {
return {
accountNo: row['account_no'],
name: row['name'],
accountType: row['account_type'],
ifscCdoe: row['ifsc_code'],
bankName: row['bank_name'],
branchName: row['branch_name'],
}
});
return list;
}
module.exports = {
validateWithinBank,
validateOutsideBank,
getAllBeneficiaries,
getSingleBeneficiary,
};

View File

@@ -0,0 +1,33 @@
const db = require('../config/db');
const newBeneficiaryValidator = async (req, res, next) => {
const { accountNo, name, ifscCode, accountType } = req.body;
if (!accountNo || !/^[0-9]{7,20}$/.test(accountNo)) {
res.status(400).json({ error: 'INVALID_ACCOUNT_NO' });
return;
}
if (!name || !accountType) {
res.status(400).json({ error: 'BAD_REQUEST' });
return;
}
if (!ifscCode || !/^[A-Z]{4}0[0-9]{6}$/.test(ifscCode)) {
res.status(400).json({ error: 'INVALID_IFSC' });
return;
}
const query_str =
'SELECT EXISTS(SELECT 1 FROM ifsc_details WHERE ifsc_code = $1)';
const result = await db.query(query_str, [ifscCode]);
const exists = result.rows[0].exists;
if (!exists) {
res.status(400).json({ error: 'INVALID_IFSC_CODE' });
return;
}
// if everthing is ok then move forward
next();
};
module.exports = newBeneficiaryValidator;