const { sequelize,Test,CreditGeneralInformation,SizeAndGeographicalResearch,CreditProfile,ProductAndProcess,PortFolioHealth,TotalOverallDebit,OverallPlanOfAction,ValidationPoint, CreditLoanDetail,CreditFinalRemarks,CreditGeneralBusinessInformation,CreditKeyProductBusinessContribution,EmployeeStrength,CreditBusinessAndPersonalBankingDetails,CreditFinancialInformation, SupplierDetail ,ClientDetail,CreditFuturePlans,CreditExistingLoanObligation,FamilyMemberInvolvedInBusiness,CreditManager,CreditBorrowerAndGuarantorDetails,CreditFinancialAnalysis,CreditAddressDetail, CreditKeyShareholder,Covid19Questions,StockDetail,BusinessAsset,CreditFilterTable,Photograph } = require('../models') const { logMsg } = require('../services/logger.js'); const Credit_PdHelper = require('../services/CreditPdHelper.js'); const request = require('request'); const moment = require('moment'); const { json } = require('body-parser'); const path = require('path'); const {Storage} = require('@google-cloud/storage'); const fs = require('fs'); const https = require('https'); // var global = require('global'); // global.arr = [ CreditAddressDetail , CreditBorrowerAndGuarantorDetails , CreditBusinessAndPersonalBankingDetails, BusinessAsset , ClientDetail , Covid19Questions , EmployeeStrength , CreditExistingLoanObligation , FamilyMemberInvolvedInBusiness , CreditFinalRemarks , CreditFinancialAnalysis , CreditFinancialInformation , CreditFuturePlans , CreditGeneralBusinessInformation , CreditGeneralInformation , CreditKeyProductBusinessContribution , CreditKeyShareholder , CreditLoanDetail , OverallPlanOfAction , PortFolioHealth , ProductAndProcess , CreditProfile , SizeAndGeographicalResearch , StockDetail , SupplierDetail , TotalOverallDebit , ValidationPoint , CreditManager , Photograph ] // PullCreditPdData exports.PullCreditPdData = async (req, res) => { try { CreditGeneralInformationDataExist = await CreditGeneralInformation.findOne({ where : { ref_no : req.body.pdid ,product:req.body.product,case_no :req.body.caseno, is_active : 1 }}); if(CreditGeneralInformationDataExist) { res.send({'status':200, 'message': "data already exist." ,'data': "No data" }); logMsg.info("CreditGeneralInformation data already exist.,PdId(ref_no)= "+req.body.pdid); } else { const arr = [ CreditAddressDetail , CreditBorrowerAndGuarantorDetails , CreditBusinessAndPersonalBankingDetails, BusinessAsset , ClientDetail , Covid19Questions , EmployeeStrength , CreditExistingLoanObligation , FamilyMemberInvolvedInBusiness , CreditFinalRemarks , CreditFinancialAnalysis , CreditFinancialInformation , CreditFuturePlans , CreditGeneralBusinessInformation , CreditGeneralInformation , CreditKeyProductBusinessContribution , CreditKeyShareholder , CreditLoanDetail , OverallPlanOfAction , PortFolioHealth , ProductAndProcess , CreditProfile , SizeAndGeographicalResearch , StockDetail , SupplierDetail , TotalOverallDebit , ValidationPoint , CreditManager , Photograph ] ; const tempData = JSON.parse(JSON.stringify(req.body)); PDID = []; obj = {}; GenInfoObj = {}; temp_array = []; if(req.body.completed_date === null){ completed_date = req.body.completed_date }else{ originalDate = req.body.completed_date; parts = originalDate.split(/[/ :]/); day = parts[0]; month = parts[1]; year = parts[2]; completed_date = `${year}-${month}-${day}`; } console.log(completed_date); // create creditGeneralInormationData Object.assign(obj, { ref_no: tempData.pdid ,name:tempData.name, product : tempData.product , case_no : tempData.caseno , credit_pd_type : req.body.credit_pd_type , completed_date : completed_date , applicant_id :req.body.lender_applicant_id , location : req.body.start_location}); await CreditGeneralInformation.create(obj) .then((successData)=>{logMsg.info("GeneralInformation insert success ,PdId= "+successData.dataValues.pd_id);}) .catch((err)=>{ logMsg.info("GeneralInformation insert failed ,PdId(ref_no)= "+req.body.pdid+ " ERR =" + err); }); PDID = await CreditGeneralInformation.findOne({ where : { ref_no : req.body.pdid ,case_no :req.body.caseno, is_active : 1 }}); length = []; for (var [OverallKey, OverallValue] of Object.entries(tempData.data)) { length.push(OverallKey); if(OverallKey != "Officer Details" || OverallKey != "last_index"){ table_name = await CreditFilterTable.findAll({ raw: true, attributes: [ 'table_name'], where : { section : OverallKey , is_active : 1 } , group: ['table_name']}); } obj = { }; temp_array.length = 0 ; for (var [ObjectKey, ObjectValue] of Object.entries(OverallValue)) { if (Array.isArray(OverallValue[ObjectKey]) == true && OverallValue[ObjectKey].length != 0) { temp_array = await Credit_PdHelper.ARRAY( OverallValue[ObjectKey] , GenInfoObj , OverallKey ) } else if (typeof OverallValue[ObjectKey] === "object" && ( OverallValue[ObjectKey] !== null )) { delete OverallValue[ObjectKey].display_data; delete OverallValue.display_data; obj = await Credit_PdHelper.OBJECT( OverallValue, ObjectKey , OverallValue[ObjectKey] ) } else if (moment(OverallValue[ObjectKey], "DD-MM-YYYY", true).isValid() == true || moment(OverallValue[ObjectKey], "DD/MM/YYYY hh:mm:ss A", true).isValid() == true ) { date = await Credit_PdHelper.DATE( OverallValue[ObjectKey] ); Object.assign(obj, { [ObjectKey]: date }); if (OverallKey == "Officer Details") { Object.assign(GenInfoObj,{[ObjectKey] : date}) }; } else { if(ObjectValue == "" && OverallKey == "Financial Information"){ delete OverallValue[ObjectKey]; } else { Object.assign(obj, { [ObjectKey]: ObjectValue }); if (OverallKey == "Borrower & Guarantor Details" && ObjectKey == "common_remarks") { Object.assign(GenInfoObj,{remarks : ObjectValue}) }; if (OverallKey == "Loan details" && ObjectKey == "loan_amount") { Object.assign(GenInfoObj,{loan_amount : ObjectValue}) }; if (OverallKey == "Officer Details") { Object.assign(GenInfoObj,{[ObjectKey] : ObjectValue}) };} } } // DB Insertion if (Object.entries(tempData.data).length == length.length) { await CreditGeneralInformation.update(GenInfoObj , { where : { pd_id : PDID.dataValues.pd_id , is_active : 1}}); logMsg.info("CreditGeneralInformation update success ,PdId= "+PDID.dataValues.pd_id); } if (temp_array.length > 0) { temp_array.forEach(async(element,i) => { if (OverallKey == "Borrower & Guarantor Details" && element.entity_type.toLowerCase() != "individual") { console.log(element.borrower_type.toLowerCase()); Object.assign(element,{borrower_age : element.numbers_of_years_business_running}); delete element.numbers_of_years_business_running; } await Object.assign(element , {pd_id : PDID.dataValues.pd_id , ref_no : req.body.pdid , display_order : i+1} ); await Object.assign(element ,obj ); var index = table_name[0].table_name; var tableName = arr[index]; console.log(tableName); await tableName.create(element) .then((successData)=>{logMsg.info(tableName+" insert success ,PdId= "+successData.dataValues.pd_id);}) .catch((err)=>{ logMsg.info(tableName+" insert failed ,PdId = "+PDID.dataValues.pd_id+ " ERR =" + err ); }); }); } else { if(OverallKey != "Officer Details") { Object.assign(obj , {pd_id : PDID.dataValues.pd_id} ); var index = table_name[0].table_name; var tableName = arr[index]; console.log(tableName); await tableName.create(obj) .then((successData)=>{logMsg.info(tableName+" insert success ,PdId= "+successData.dataValues.pd_id);}) .catch((err)=>{ logMsg.info(tableName+" insert failed ,PdId= "+PDID.dataValues.pd_id+ " ERR =" + err); }); } } } res.send({'status':200,'message':"success"}); }//end of else condition } catch (err) { res.send({ 'status': 404, message: err.message || "Some error occurred while retrieving data.", 'data': "No data" }); } //end of try catch } exports.PullCreditPdPhotographsData = async (req, res) => { try { // fetch SMC PdId from DB GeneralSectionData = await CreditGeneralInformation.findOne({ where : { ref_no : req.body.pdid ,case_no :req.body.caseno, is_active : 1 }}); PdId = GeneralSectionData.dataValues.pd_id; // convert image file to base64 code // path = "storage/uploads/" // file = path+img_name; // base64_data = "data:image/png;base64," + fs.readFileSync(file, 'base64'); // insert photograph data here await Photograph.create({pd_id: PdId , ref_no :req.body.pdid , img_name :req.body.img_name , img : img_name}) .then((successData)=>{ logMsg.info("Photograph insert success ,PdId= "+PdId); res.send({'status':200,'message':"success",'data': "no data"}); //,"+base64_data+" }) .catch((err)=>{ logMsg.info("Photograph insert failed ,PdId= "+PdId+" ERROR : "+err); res.send({'status':404,message: err.message || "Some error occurred while retrieving data." ,'data': "No data" }); }); // responce to FE } catch(err) { res.send({'status':404,message: err.message || "Some error occurred while retrieving data." ,'data': "No data" }); } //end of try catch }; // MWISE00840 exports.imageView = async (req, res) => { try { const filePath = "storage/uploads/"+req.query.img_name; const { dirname } = require('path'); const appDir = dirname(require.main.filename); res.sendFile(filePath , { root: appDir }); } catch(err) { res.send({'status':404,message: err.message || "Some error occurred while retrieving data." ,'data': "No data" }) ; } //end of try catch }; exports.DownloadPdReport = async (req, res) => { try { // pd_id = req.query.ref_no; // DownloadPdReportUrl = process.env.PD_REPORT_URL; // url = DownloadPdReportUrl+"getCreditPDReportforCETApp?credit_pd_id="+pd_id; // request({ // url: url, // method: "GET" // }, function (error, response, body) { console.log(body); // if (body != undefined) { // data = JSON.parse(body); // if ( data.status == 200) { // link = data.records; // res.send({'status':200,'message':"success",'data':link}); // }else{ // res.send({'status':404,'message':"failed",'data':"No data"}); // } // } // }); const storage = new Storage({ keyFilename : path.join(__dirname, "../../googleCloud.json") }); const bucketName = process.env.GCP_BUCKET_NAME; const fileName = 'credit-pd/pd'+req.query.ref_no+'/'+req.query.ref_no+'.pdf'; const options = {version: 'v2', action: 'read',expires: Date.now() + 1000 * 60 * 60, }; const [url] = await storage.bucket(bucketName).file(fileName).getSignedUrl(options); res.send({'status':200,'message':"success",'data':url}); } catch(err) { res.send({'status':404,message: err.message || "Some error occurred while retrieving data." ,'data': "No data" }); } //end of try catch }; exports.GetCreditPdData = async (req, res) => { try { // applicantDetails = await Credit_PdHelper.MainApplicantDetails(req.query.losid); // MainApplicantDetails = JSON.parse(applicantDetails); // if(MainApplicantDetails.status == 200) // { CreditGeneralInformation.findAll({ where : { applicant_id : req.query.losid,is_active : 1}, include : [ {model: CreditAddressDetail }, {model : CreditBorrowerAndGuarantorDetails ,separate: true, order: [['display_order', 'ASC']] }, {model: CreditKeyShareholder ,separate: true, order: [['display_order', 'ASC']] }, {model: FamilyMemberInvolvedInBusiness }, {model: CreditGeneralBusinessInformation }, {model: EmployeeStrength }, {model: CreditFinancialInformation ,separate: true, order: [['display_order', 'ASC']] }, {model: SupplierDetail }, {model: ClientDetail }, {model: StockDetail ,separate: true, order: [['display_order', 'ASC']]}, {model: CreditFuturePlans }, {model: CreditBusinessAndPersonalBankingDetails,separate: true, order: [['display_order', 'ASC']] }, {model: CreditExistingLoanObligation ,separate: true, order: [['display_order', 'ASC']] }, {model : CreditManager }, {model: CreditFinalRemarks }, {model: BusinessAsset ,separate: true, order: [['display_order', 'ASC']] }, {model: CreditKeyProductBusinessContribution ,separate: true, order: [['display_order', 'ASC']] }, {model: Photograph }, {model: CreditLoanDetail }, ] }) .then(async(data)=>{ if (data.length > 0) { if(Array.isArray(data[0].dataValues.Photographs) == true && data[0].dataValues.Photographs.length > 0) { ImageData = []; const storage = new Storage({ keyFilename : path.join(__dirname, "../../googleCloud.json") }); const bucketName = process.env.GCP_BUCKET_NAME; const bucketFolderName = process.env.GCP_BUCKET_FOLDER_NAME; for(const PhotographsValue of data[0].dataValues.Photographs) { const fileName = bucketFolderName+'/pd'+PhotographsValue.ref_no+'/images/'+PhotographsValue.img; const options = {version: 'v2', action: 'read',expires: Date.now() + 1000 * 60 * 60, }; const [url] = await storage.bucket(bucketName).file(fileName).getSignedUrl(options); await ImageData.push( Object.assign(PhotographsValue.dataValues, { url: url })); } Object.assign(data[0], {Photographs:ImageData}) } res.send({'status':200,'message':"success",'data':data}); } else { res.send({'status':404,'message':"failed",'data':"No data"}); } }) // } // else // { // res.send({'status':404,'message':"failed",'data':"No data"}); // } } catch(err) { res.status(500).send({'status':404, message: err.message || "Some error occurred while inserting statements." ,'data': "No data" }); } }; exports.ReInsertImageData = async (req, res) => { try { CreditGeneralInformationData = await CreditGeneralInformation.findOne({ where : { ref_no : req.body.pdid ,product:req.body.product,case_no :req.body.caseno, is_active : 1 }}); if(CreditGeneralInformationData) { var salesPD = new Promise(async(resolve, reject) => { const reqData =JSON.parse(JSON.stringify(req.body.data)); key = 'Photograph Details'; if (Array.isArray(reqData[key].photo) == true ) { Photograph.destroy({ where: { pd_id: CreditGeneralInformationData.pd_id , ref_no :req.body.pdid} }).then(function(result) { logMsg.info("Photos count for pd_id (ref_no) = "+reqData[key].photo); reqData[key].photo.forEach(async(values,index,array) => { Object.assign(values, { pd_id: CreditGeneralInformationData.pd_id,ref_no:req.body.pdid }); await Photograph.create( values).then((successData)=>{logMsg.info("Photograph insert success name = "+values.img+", PdId = "+CreditGeneralInformationData.pd_id);}).catch((err)=>{ logMsg.info("Photograph insert failed name = "+values.img+", PdId = "+CreditGeneralInformationData.pd_id+" Error = "+err);}); if(array.length == index+1){resolve(true);} }); }).catch(err=>{}); } else {resolve(false); } }); // end of promise salesPD.then(async(result) => { setTimeout(() => { if(result == false) { res.send({'status':404,'message':"failed",'data':"No Data"}); }else{ res.send({'status':200,'message':"success",'data':"No Data"}); } }, 1000); }); } else { res.send({'status':404,'message':"PD not exist",'data':"No Data"}); } } catch(err) { res.send({'status':404,message: err.message || "Some error occurred while retrieving data." ,'data': "No data" }); } //end of try catch }; // exports.GetCreditPdData__1 = async (req, res) => // { // try // { // // // applicantDetails = await Credit_PdHelper.MainApplicantDetails(req.query.losid); // // // MainApplicantDetails = JSON.parse(applicantDetails); // // // if(MainApplicantDetails.status == 200) // // // { // CreditGeneralInformation.findAll({ where : { pd_id :432,is_active : 1}, // include : [ // {model: CreditAddressDetail }, // {model: CreditFuturePlans }, // {model : CreditBorrowerAndGuarantorDetails }, // {model: CreditBusinessAndPersonalBankingDetails }, {model: BusinessAsset }, // {model: CreditFinancialInformation }, {model: CreditKeyShareholder }, // {model: CreditKeyProductBusinessContribution }, {model: EmployeeStrength }, // {model: ClientDetail }, {model: StockDetail }, // {model: CreditExistingLoanObligation }, // {model: FamilyMemberInvolvedInBusiness }, // {model : CreditManager }, // {model: Photograph }, // {model: CreditFinalRemarks }, {model: CreditLoanDetail }, // {model: CreditGeneralBusinessInformation }, // {model: SupplierDetail } // ] // }) // .then((data)=>{ // if (data.length > 0) // { // res.send({'status':200,'message':"success",'data':data}); // } // else // { // res.send({'status':404,'message':"failed",'data':"No data"}); // } // }) // // // } // // // else // // // { // // // res.send({'status':404,'message':"failed",'data':"No data"}); // // // } // } catch(err) { // res.status(500).send({'status':404, // message: err.message || "Some error occurred while inserting statements." ,'data': "No data" // }); // } // }; exports.readLogFileName = async (req , res) => { try { folderName = req; const logFilePath = 'storage/log'; const fileNames = fs.readdirSync(logFilePath); // Remove the first element (0th index) const [, ...data] = fileNames; return data; } catch(err) { res.status(500).send({'status':404, message: err.message || "Some error occurred while inserting statements." ,'data': "No data" }); } //end of try catch }; exports.readLogFile = async (req , res) => { try { folderName = req.body.folder; fileName = req.body.file; const logFilePath = 'storage/log/'+fileName; fs.readFile(logFilePath, 'utf8', (err, data) => { if (err) { console.error(err); res.status(500).send({'status':404,'message': err.message || "Error reading log file." ,'data': "No data"}); } res.send({'status':200 , message:"Success." ,'data': data}); }); } catch(err) { res.status(500).send({'status':404, message: err.message || "Some error occurred while inserting statements." ,'data': "No data" }); } //end of try catch }; exports.viewLandingPage = async (req , res) => { try { moduleName = [ { "module":"CREDIT PD","folder":"smc_cet_creditpd_backend"} ]; img = [] for(const [index,val] of moduleName.entries()) { fileName = await this.readLogFileName(val.folder); for (let i = 0; i < fileName.length; i++) { filePath = 'storage/log/'+fileName[i]; const logData = fs.readFileSync(filePath); // Convert the file content to Base64 const base64Data = logData.toString('base64'); // Create Base64 URL from Base64 data const base64Url = `data:application/octet-stream;base64,${encodeURIComponent(base64Data)}`; img.push(base64Url) } moduleName[index] = await Object.assign(val,{'file':fileName , 'img':img}); }; res.render( 'module' , { 'data' : moduleName } ,function (err, html ) { res.send(html) }) } catch(err) { res.status(500).send({'status':404, message: err.message || "Some error occurred while inserting statements." ,'data': "No data" }); } //end of try catch }; exports.deleteLogFile = async (req , res) => { try { folderName = req.body.folder; fileName = req.body.file; // folderName = 'smc_cet_creditpd_backend'; // fileName = 'msg.log.2023-07-10'; const logFilePath = 'storage/log/'+fileName; fs.unlink(logFilePath, (err) => { if (err) { console.error(`Error deleting file: ${err}`); return; } console.log('File deleted successfully.'); res.send({'status':200 , message:"Success." ,'data': 'No data'}); }); } catch(err) { res.status(500).send({'status':404, message: err.message || "Some error occurred while inserting statements." ,'data': "No data" }); } //end of try catch }; exports.callSineedgeApi = (req, res) => { try { request('http://www.google.com', function (error, response, body) { res = this.PullSalesPdData(body); if(res.status == 200){ res.send({'status':200 , message:"Success." ,'data': Msg}); } else{ res.send({'status':404 , message:"Failed." ,'data': "No data"}); } }); } catch(err) { res.status(500).send({'status':404, message: err.message || "Some error occurred while inserting statements." ,'data': "No data" }); } //end of try catch };