43 Commits

Author SHA1 Message Date
asif
2516ff5f4c added helmet for security 2025-09-09 02:11:43 +05:30
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
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
33 changed files with 1092 additions and 55 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

2
.gitignore vendored
View File

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

94
package-lock.json generated
View File

@@ -17,7 +17,9 @@
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"pg": "^8.16.0", "pg": "^8.16.0",
"pino": "^9.7.0", "pino": "^9.7.0",
"pino-http": "^10.4.0" "pino-http": "^10.4.0",
"redis": "^5.7.0",
"uuid": "^11.1.0"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.28.0", "@eslint/js": "^9.28.0",
@@ -265,6 +267,61 @@
"url": "https://opencollective.com/pkgr" "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": { "node_modules/@types/estree": {
"version": "1.0.7", "version": "1.0.7",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz",
@@ -644,6 +701,14 @@
"url": "https://github.com/sponsors/sindresorhus" "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": { "node_modules/color-convert": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -2894,6 +2959,21 @@
"node": ">= 12.13.0" "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": { "node_modules/resolve-from": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
@@ -3399,6 +3479,18 @@
"punycode": "^2.1.0" "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": { "node_modules/vary": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",

View File

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

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) => {

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

@@ -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,5 +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 randomName = require('../util/name.generator');
async function validateWithinBank(req, res) { async function validateWithinBank(req, res) {
const { accountNumber } = req.query; const { accountNumber } = req.query;
@@ -22,4 +24,126 @@ 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);
const name = randomName();
return res.json({ name });
} 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 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) {
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,
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,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

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

@@ -1,8 +1,17 @@
const express = require('express'); const express = require('express');
const beneficiaryController = require('../controllers/beneficiary.controller'); const beneficiaryController = require('../controllers/beneficiary.controller');
const newBeneficiaryValidator = require('../validators/beneficiary.validator');
const router = express.Router(); const router = express.Router();
router.get('/validate/within-bank', beneficiaryController.validateWithinBank); 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);
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,10 @@ 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 router = express.Router(); const router = express.Router();
@@ -12,6 +16,10 @@ 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('/beneficiary', beneficiaryRoute); 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('/npci/beneficiary-response', npciResponse);
module.exports = router; module.exports = router;

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

@@ -1,10 +1,15 @@
const axios = require('axios');
const { logger } = require('../util/logger'); const { logger } = require('../util/logger');
const { v4: uuidv4 } = require('uuid');
const db = require('../config/db');
async function validateWithinBank(accountNo) { 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 { try {
const response = await fetch(url); const response = await axios.get(url, {
const data = await response.json(); params: { stacctno: accountNo },
});
const data = response.data;
const customerName = data.customername; const customerName = data.customername;
return customerName; return customerName;
} catch (error) { } catch (error) {
@@ -13,4 +18,63 @@ 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 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) {
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'],
ifscCode: row['ifsc_code'],
bankName: row['bank_name'],
branchName: row['branch_name'],
};
});
return list;
}
module.exports = {
validateWithinBank,
validateOutsideBank,
getAllBeneficiaries,
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,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;

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