This commit is contained in:
2025-08-08 13:15:04 +05:30
9 changed files with 345 additions and 24 deletions

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', () => 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,8 @@
const { logger } = require('../util/logger');
const { setJson, getJson } = require('../config/redis');
const beneficiaryService = require('../services/beneficiary.service');
const db = require('../config/db');
const axios = require('axios');
async function validateWithinBank(req, res) {
const { accountNumber } = req.query;
@@ -22,29 +25,89 @@ async function validateWithinBank(req, res) {
}
}
async function validateOutsideBank(req, res) {
res.status(400).send('WIP. Try after sometime');
}
async function addBeneficiary(req, res) {
try {
const { accountNo, ifscCode, accountType, name } = req.body;
const customerNo = req.user;
console.log(`Customer Number: ${customerNo}`);
const uuid = await beneficiaryService.validateOutsideBank(
accountNo,
ifscCode,
name
);
await setJson(
uuid,
{ customerNo, accountNo, ifscCode, accountType, name },
300
);
async function npciResponse(req, res) {
const { resp } = req.body;
console.log(req.body);
if (resp === 'Success') {
await handleNPCISuccess(resp);
} else {
await handleNPCIFailure(resp);
//-------------------------------------------------------------------------
//*REMOVE IN PRODUCTION* firing this from here since no NPCI in test region
const r = await axios.post(
'http://localhost:8081/api/npci/beneficiary-response',
{
resp: { status: 'Success', txnid: uuid, benename: name },
}
);
console.log(r.data);
//-------------------------------------------------------------------------
res.json({ message: 'SENT_FOR_VALIDATION' });
} catch (error) {
logger.error(error, 'Error adding beneficiary');
res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
res.send('ok');
}
async function handleNPCISuccess(response) {
const { txnid, benename } = response;
console.log(txnid);
console.log(benename);
async function checkBeneficiary(req, res) {
await delay(5000);
const { accountNo } = req.query;
const customerNo = req.user;
if (!accountNo) {
res.status(403).json({ error: 'BAS_REQUEST' });
return;
}
console.log(customerNo, accountNo);
const query =
'SELECT EXISTS(SELECT 1 FROM beneficiaries WHERE customer_no = $1 AND account_no = $2)';
const result = await db.query(query, [customerNo, accountNo]);
const exists = result.rows[0].exists;
if (!exists) {
res.status(404).json({ error: 'NOT_FOUND' });
return;
}
res.json({ message: 'FOUND' });
}
async function handleNPCIFailure(response) {
console.log(response);
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_code_bank 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' });
}
}
module.exports = { validateWithinBank, npciResponse, validateOutsideBank };
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
module.exports = {
validateWithinBank,
addBeneficiary,
checkBeneficiary,
getIfscDetails,
};

View File

@@ -0,0 +1,45 @@
const db = require('../config/db');
const { getJson } = 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 {
const beneficiaryDetails = await getJson(txnid);
if (!beneficiaryDetails) {
logger.warn('no txnid in redis');
return false;
}
const { customerNo, accountNo, ifscCode, accountType } = beneficiaryDetails;
const query =
'INSERT INTO beneficiaries (customer_no, account_no, name, account_type, ifsc_code) VALUES ($1, $2, $3, $4, $5)';
const result = await db.query(query, [
customerNo,
accountNo,
benename,
accountType,
ifscCode,
]);
logger.info(result);
return true;
} catch (error) {
logger.error(error, 'error processing npci response');
return false;
}
}
async function handleNPCIFailure(response) {
console.log(response);
}
module.exports = { npciResponse };

View File

@@ -1,10 +1,16 @@
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.post('/validate/npci-response', beneficiaryController.npciResponse);
router.get('/check', beneficiaryController.checkBeneficiary);
router.get('/ifsc-details', beneficiaryController.getIfscDetails);
router.post(
'/add',
newBeneficiaryValidator,
beneficiaryController.addBeneficiary
);
module.exports = router;

View File

@@ -6,6 +6,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();
@@ -14,7 +15,8 @@ router.use('/auth/admin',adminAuthRoute);
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,5 +1,6 @@
const axios = require('axios');
const { logger } = require('../util/logger');
const { v4: uuidv4 } = require('uuid');
async function validateWithinBank(accountNo) {
const url = 'http://localhost:8687/kccb/cbs/acctInfo/details';
@@ -16,4 +17,23 @@ 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');
}
}
module.exports = { validateWithinBank, validateOutsideBank };

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