feat: Limit of trasnaction

This commit is contained in:
2025-11-04 11:12:55 +05:30
18 changed files with 204 additions and 32 deletions

View File

@@ -3,6 +3,7 @@
"MPIN", "MPIN",
"occured", "occured",
"otpgenerator", "otpgenerator",
"TLIMIT",
"tpassword", "tpassword",
"tpin", "tpin",
"TPWORD" "TPWORD"

View File

@@ -3,6 +3,7 @@ const cors = require('cors');
const { logger } = require('./util/logger'); const { logger } = require('./util/logger');
const routes = require('./routes'); const routes = require('./routes');
const helmet = require('helmet'); const helmet = require('helmet');
const { verifyClient } = require('./middlewares/clientVerifier.middleware');
const app = express(); const app = express();
@@ -11,7 +12,7 @@ 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('/api', routes); app.use('/api', verifyClient, 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) => {
logger.error(err, 'uncaught error'); logger.error(err, 'uncaught error');

View File

@@ -12,7 +12,8 @@ async function send(
ifscCode, ifscCode,
beneficiaryName, beneficiaryName,
beneficiaryAcctType = 'SAVINGS', beneficiaryAcctType = 'SAVINGS',
remarks = '' remarks = '',
client
) { ) {
try { try {
const reqData = { const reqData = {
@@ -42,7 +43,8 @@ async function send(
amount, amount,
'', '',
'', '',
response.data response.data,
client
); );
return response.data; return response.data;
} catch (error) { } catch (error) {

View File

@@ -11,7 +11,8 @@ async function send(
ifscCode, ifscCode,
beneficiaryName, beneficiaryName,
remitterName, remitterName,
remarks remarks,
client
) { ) {
const commission = 0; const commission = 0;
try { try {
@@ -28,7 +29,7 @@ async function send(
stAddress1: '', stAddress1: '',
stAddress2: '', stAddress2: '',
stAddress3: '', stAddress3: '',
narration: remarks narration: remarks,
} }
); );
await recordInterBankTransaction( await recordInterBankTransaction(
@@ -41,7 +42,8 @@ async function send(
commission, commission,
beneficiaryName, beneficiaryName,
remitterName, remitterName,
response.data.status response.data.status,
client
); );
return response.data; return response.data;
} catch (error) { } catch (error) {
@@ -49,8 +51,6 @@ async function send(
'API call failed: ' + (error.response?.data?.message || error.message) 'API call failed: ' + (error.response?.data?.message || error.message)
); );
} }
} }
module.exports = { send }; module.exports = { send };

View File

@@ -107,6 +107,13 @@ async function SendOtp(req, res) {
case 'USERNAME_SAVED': case 'USERNAME_SAVED':
message = templates.USERNAME_SAVED(PreferName); message = templates.USERNAME_SAVED(PreferName);
break; break;
case 'TLIMIT':
otp = generateOTP(6);
message = templates.TLIMIT(otp);
break;
case 'TLIMIT_SET':
message = templates.TLIMIT_SET(amount);
break;
default: default:
return res.status(400).json({ error: 'Invalid OTP type' }); return res.status(400).json({ error: 'Invalid OTP type' });
} }

View File

@@ -11,7 +11,8 @@ async function send(
ifscCode, ifscCode,
beneficiaryName, beneficiaryName,
remitterName, remitterName,
remarks remarks,
client
) { ) {
const commission = 0; const commission = 0;
try { try {
@@ -28,7 +29,8 @@ async function send(
stAddress1: '', stAddress1: '',
stAddress2: '', stAddress2: '',
stAddress3: '', stAddress3: '',
narration: remarks narration: remarks,
client,
} }
); );
await recordInterBankTransaction( await recordInterBankTransaction(
@@ -41,7 +43,8 @@ async function send(
commission, commission,
beneficiaryName, beneficiaryName,
remitterName, remitterName,
response.data.status response.data.status,
client
); );
return response.data; return response.data;
} catch (error) { } catch (error) {

View File

@@ -9,7 +9,8 @@ async function transfer(
toAccountType, toAccountType,
amount, amount,
customerNo, customerNo,
narration = '' narration = '',
client
) { ) {
try { try {
const response = await axios.post( const response = await axios.post(
@@ -28,7 +29,8 @@ async function transfer(
toAccountNo, toAccountNo,
toAccountType, toAccountType,
amount, amount,
response.data.status response.data.status,
client
); );
return response.data; return response.data;
} catch (error) { } catch (error) {

View File

@@ -0,0 +1,20 @@
const { logger } = require('../util/logger');
function verifyClient(req, res, next) {
const clientHeader = req.headers['x-login-type'];
if (!clientHeader || (clientHeader !== 'MB' && clientHeader !== 'IB' && clientHeader !== 'eMandate' && clientHeader !=='Admin')) {
logger.error(
`Invalid or missing client header. Expected 'MB' or 'IB'. Found ${clientHeader}`
);
return res
.status(401)
.json({ error: 'MISSING OR INVALID CLIENT TYPE HEADER' });
}
req.client = clientHeader;
next();
}
module.exports = { verifyClient };

View File

@@ -0,0 +1,28 @@
const { logger } = require('../util/logger');
const {
getDailyLimit,
getUsedLimit,
} = require('../services/paymentLimit.service');
async function checkLimit(req, res, next) {
const { amount } = req.body;
const { user, client } = req;
const dailyLimit = await getDailyLimit(user, client);
if (!dailyLimit) {
logger.info('NO LIMIT SET FOR CUSTOMER. ALLOWING TRANSACTIONS');
next();
}
const usedLimit = await getUsedLimit(user, client);
const remainingLimit = dailyLimit - usedLimit;
if (amount > remainingLimit) {
const midnight = new Date();
midnight.setHours(24, 0, 0, 0);
res.set('Retry-After', midnight.toUTCString());
return res.status(403).json({ error: 'Daily limit exhausted' });
}
next();
}
module.exports = { checkLimit };

View File

@@ -1,5 +1,13 @@
const customerController = require('../controllers/customer_details.controller'); const customerController = require('../controllers/customer_details.controller');
const {
getDailyLimit,
getUsedLimit,
setDailyLimit,
} = require('../services/paymentLimit.service');
const { logger } = require('../util/logger'); const { logger } = require('../util/logger');
const express = require('express');
const router = express.Router();
const customerRoute = async (req, res) => { const customerRoute = async (req, res) => {
const customerNo = req.user; const customerNo = req.user;
@@ -12,4 +20,45 @@ const customerRoute = async (req, res) => {
} }
}; };
module.exports = customerRoute; const limitRoute = async (req, res) => {
const customerNo = req.user;
const client = req.client;
try {
const dailyLimit = await getDailyLimit(customerNo, client);
if (!dailyLimit) {
return res.status(400).json({ error: 'NO DAILY LIMIT SET FOR USER' });
}
const usedLimit = await getUsedLimit(customerNo, client);
res.json({ dailyLimit: dailyLimit, usedLimit: usedLimit });
} catch (err) {
logger.error(err, 'Unknown error encountered while checking daily limit');
res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
};
const limitChangeRoute = async (req, res) => {
const customerNo = req.user;
const client = req.client;
const { amount } = req.body;
const numericLimit = Number(amount);
if (!Number.isFinite(numericLimit)) {
logger.error(`Invalid new Limit, found: ${newLimit}`);
return res
.status(400)
.json({ error: 'NEW LIMIT AMOUNT IS REQUIRED WHEN SETTING LIMIT' });
}
try {
await setDailyLimit(customerNo, client, numericLimit);
return res.status(200).json({ message: 'LIMIT SET' });
} catch (err) {
logger.error(err, 'Unexpected error while setting limit amount');
res.status(500).json({ error: 'INTERNAL SERVER ERROR' });
}
};
router.get('/', customerRoute);
router.get('/daily-limit', limitRoute);
router.post('/daily-limit', limitChangeRoute);
module.exports = router;

View File

@@ -3,13 +3,15 @@ const impsController = require('../controllers/imps.controller');
const { logger } = require('../util/logger'); const { logger } = require('../util/logger');
const impsValidator = require('../validators/imps.validator'); const impsValidator = require('../validators/imps.validator');
const paymentSecretValidator = require('../validators/payment.secret.validator'); const paymentSecretValidator = require('../validators/payment.secret.validator');
const { checkLimit } = require('../middlewares/limitCheck.middleware');
const router = express.Router(); const router = express.Router();
router.use(impsValidator, paymentSecretValidator); router.use(impsValidator, paymentSecretValidator, checkLimit);
const impsRoute = async (req, res) => { const impsRoute = async (req, res) => {
const { fromAccount, toAccount, ifscCode, amount, beneficiaryName, remarks } = const { fromAccount, toAccount, ifscCode, amount, beneficiaryName, remarks } =
req.body; req.body;
const client = req.client;
try { try {
const result = await impsController.send( const result = await impsController.send(
@@ -20,7 +22,8 @@ const impsRoute = async (req, res) => {
ifscCode, ifscCode,
beneficiaryName, beneficiaryName,
'SAVINGS', 'SAVINGS',
remarks remarks,
client
); );
if (result.startsWith('Message produced successfully')) { if (result.startsWith('Message produced successfully')) {

View File

@@ -26,5 +26,4 @@ router.use('/beneficiary', authenticate, beneficiaryRoute);
router.use('/npci/beneficiary-response', npciResponse); router.use('/npci/beneficiary-response', npciResponse);
router.use('/otp', otp); router.use('/otp', otp);
module.exports = router; module.exports = router;

View File

@@ -3,9 +3,10 @@ const neftController = require('../controllers/neft.controller');
const { logger } = require('../util/logger'); const { logger } = require('../util/logger');
const neftValidator = require('../validators/neft.validator.js'); const neftValidator = require('../validators/neft.validator.js');
const paymentSecretValidator = require('../validators/payment.secret.validator'); const paymentSecretValidator = require('../validators/payment.secret.validator');
const { checkLimit } = require('../middlewares/limitCheck.middleware');
const router = express.Router(); const router = express.Router();
router.use(neftValidator, paymentSecretValidator); router.use(neftValidator, paymentSecretValidator, checkLimit);
const neftRoute = async (req, res) => { const neftRoute = async (req, res) => {
const { const {
@@ -15,8 +16,9 @@ const neftRoute = async (req, res) => {
amount, amount,
beneficiaryName, beneficiaryName,
remitterName, remitterName,
remarks remarks,
} = req.body; } = req.body;
const client = req.client;
try { try {
const result = await neftController.send( const result = await neftController.send(
@@ -27,7 +29,8 @@ const neftRoute = async (req, res) => {
ifscCode, ifscCode,
beneficiaryName, beneficiaryName,
remitterName, remitterName,
remarks remarks,
client
); );
logger.info(result); logger.info(result);

View File

@@ -3,9 +3,10 @@ const rtgsController = require('../controllers/rtgs.controller');
const { logger } = require('../util/logger'); const { logger } = require('../util/logger');
const rtgsValidator = require('../validators/rtgs.validator.js'); const rtgsValidator = require('../validators/rtgs.validator.js');
const paymentSecretValidator = require('../validators/payment.secret.validator'); const paymentSecretValidator = require('../validators/payment.secret.validator');
const { checkLimit } = require('../middlewares/limitCheck.middleware');
const router = express.Router(); const router = express.Router();
router.use(rtgsValidator, paymentSecretValidator); router.use(rtgsValidator, paymentSecretValidator, checkLimit);
const rtgsRoute = async (req, res) => { const rtgsRoute = async (req, res) => {
const { const {
@@ -15,8 +16,9 @@ const rtgsRoute = async (req, res) => {
amount, amount,
beneficiaryName, beneficiaryName,
remitterName, remitterName,
remarks remarks,
} = req.body; } = req.body;
const client = req.client;
try { try {
const result = await rtgsController.send( const result = await rtgsController.send(
@@ -27,7 +29,8 @@ const rtgsRoute = async (req, res) => {
ifscCode, ifscCode,
beneficiaryName, beneficiaryName,
remitterName, remitterName,
remarks remarks,
client
); );
if (result.status.startsWith('O.K.')) { if (result.status.startsWith('O.K.')) {

View File

@@ -3,12 +3,14 @@ const { logger } = require('../util/logger');
const express = require('express'); const express = require('express');
const transferValidator = require('../validators/transfer.validator'); const transferValidator = require('../validators/transfer.validator');
const passwordValidator = require('../validators/payment.secret.validator.js'); const passwordValidator = require('../validators/payment.secret.validator.js');
const { checkLimit } = require('../middlewares/limitCheck.middleware');
const router = express.Router(); const router = express.Router();
router.use(passwordValidator, transferValidator); router.use(passwordValidator, transferValidator, checkLimit);
const transferRoute = async (req, res) => { const transferRoute = async (req, res) => {
const { fromAccount, toAccount, toAccountType, amount, remarks } = req.body; const { fromAccount, toAccount, toAccountType, amount, remarks } = req.body;
const client = req.client;
try { try {
const result = await transferController.transfer( const result = await transferController.transfer(
fromAccount, fromAccount,
@@ -16,7 +18,8 @@ const transferRoute = async (req, res) => {
toAccountType, toAccountType,
amount, amount,
req.user, req.user,
remarks remarks,
client
); );
if (result.status === 'O.K.') { if (result.status === 'O.K.') {

View File

@@ -0,0 +1,38 @@
const db = require('../config/db');
const { logger } = require('../util/logger');
async function getDailyLimit(customerNo, clientType) {
let query = '';
if (clientType === 'IB') {
query = `SELECT inb_limit_amount AS daily_limit FROM users WHERE customer_no = $1`;
} else {
query = `SELECT mobile_limit_amount AS daily_limit FROM users WHERE customer_no = $1`;
}
const result = await db.query(query, [customerNo]);
return result.rows[0].daily_limit;
}
async function getUsedLimit(customerNo, clientType) {
let query = `SELECT SUM(amount::numeric) AS used_limit FROM transactions WHERE created_at BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '1 day') AND customer_no = $1 AND client = $2`;
const result = await db.query(query, [customerNo, clientType]);
const usedLimit = result.rows[0].used_limit;
return Number(usedLimit);
}
async function setDailyLimit(customerNo, clientType, amount) {
let query = '';
if (clientType === 'IB') {
query = `UPDATE users SET inb_limit_amount = $1 WHERE customer_no = $2`;
} else {
query = `UPDATE users SET mobile_limit_amount = $1 WHERE customer_no = $2`;
}
const result = await db.query(query, [amount, customerNo]);
if (result.rowCount === 0) {
throw new Error('No rows affected');
}
logger.info(`set new limit: ${result.rowCount} rows affected`);
}
module.exports = { getDailyLimit, getUsedLimit, setDailyLimit };

View File

@@ -6,11 +6,12 @@ const recordIntraBankTransaction = async (
toAccount, toAccount,
accountType, accountType,
amount, amount,
status status,
clientType
) => { ) => {
const trxType = 'TRF'; const trxType = 'TRF';
const query = 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)'; 'INSERT INTO transactions (customer_no, trx_type, from_account, to_account, to_account_type, amount, status, client) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)';
await db.query(query, [ await db.query(query, [
customerNo, customerNo,
trxType, trxType,
@@ -19,6 +20,7 @@ const recordIntraBankTransaction = async (
accountType, accountType,
amount, amount,
status, status,
clientType,
]); ]);
}; };
const recordInterBankTransaction = async ( const recordInterBankTransaction = async (
@@ -31,10 +33,11 @@ const recordInterBankTransaction = async (
commission, commission,
beneficiaryName, beneficiaryName,
remitterName, remitterName,
status status,
clientType
) => { ) => {
const query = 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)'; 'INSERT INTO transactions (customer_no, trx_type, from_account, to_account, ifsc_code, amount, commission, beneficiary_name, remitter_name, status, client) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)';
await db.query(query, [ await db.query(query, [
customerNo, customerNo,
trxType, trxType,
@@ -46,6 +49,7 @@ const recordInterBankTransaction = async (
beneficiaryName, beneficiaryName,
remitterName, remitterName,
status, status,
clientType,
]); ]);
}; };

View File

@@ -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`, `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) => 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}. -KCCB`,
TLIMIT_SET :(amount) =>
`Dear Customer,Your transaction limit for Internet Banking is set to Rs ${amount}. -KCCB`,
}; };
module.exports = templates; module.exports = templates;