const { sequelize, Entities , Financials , Statementsmaster , Sectionsmaster , Subsectionsmaster , Itemsmaster , Brokenperiods , Entityfinyear} = require('../models') const { logMsg } = require('../services/logger.js'); const financialControllerHelper = require('../services/financial.controller.helper.js'); const camundaHelper = require('../services/camunda.helper.js'); const ApiCallHelper = require('../services/financials.apicall.helper.js'); const Probe42DataMappingHelper = require('../services/probe42lineitem.mapping.helper.js'); const Sync = require('sync'); const { Op } = require("sequelize"); // all master data list for dropdown exports.MasterDatas = async (req, res) => { await Statementsmaster.findAll({ where :{is_active : 1} , attributes: ['id', 'statement', 'is_active'], include :[{ association: 'sectionsmasterData' , where :{is_active : 1} , attributes: ['id', 'section', 'is_active'], include :[{ association: 'subsectionsmasterData' , where :{is_active : 1} , attributes: ['id', 'subsection', 'is_active'], required :false }], required :false }], required :false }) .then(data => { res.send({'status':200,'message':"success",'statementsmasterrData':data}); logMsg.info("Master Data List api call Success"); }) .catch(err => { res.status(404).send({'status':404, message: err.message || "Some error occurred while retrieving statements." ,'data': "No data" }); }); }; exports.MenuList = async (req, res) => { Sync(function() { try { const losid = req.query.losid; var EntityInsert = new Promise((resolve, reject) => { //Redirection api call with losid redirectionApi = ApiCallHelper.redirectionApiCall(losid); redirectionApi.then(function(redirectionApiData){ if(redirectionApiData == false) { resolve(); } else { // insert pro42data into entities table using using foreach redirectionApiData.forEach((Pro42Datavalue, key,array)=>{ let cin_number = Pro42Datavalue.ciN_LLPIN.toUpperCase(); // check if the Pro42Data (entity) already inserted Entities.findOne({ where: { losid : Pro42Datavalue.loginNo , pan : Pro42Datavalue.pan , cin : cin_number } }).then(Entity => { if(Entity) { // skip inserting if (key === array.length -1) {resolve();} } else { Entities.create({ "losid":Pro42Datavalue.loginNo,"pan":Pro42Datavalue.pan,"cin":cin_number,"bizname":Pro42Datavalue.entityName,"entity_type":Pro42Datavalue.entityType,"probe42_data_status":1,"is_verified":0,"createdby":Pro42Datavalue.createdby}) .then(Entitydata => { const cin = Entitydata.dataValues.cin; if(cin != "") { //process instance Id update const entityid = Entitydata.dataValues.id; const user = "SMC"; processInstanceId = camundaHelper.startFinancialsProcessInstance(Entitydata.dataValues.losid,Entitydata.dataValues.pan,user); processInstanceId.then(function(InstanceId){ Entities.update({ "process_instance_id":InstanceId },{ where: { id: entityid }}).then(processInstanceIdData =>{ // resolve here if (key === array.length -1) { resolve(); } }).catch(err=>{ logMsg.info("camunda process_instance_id creation for entity_id= "+entityid); }); }); // call and get financial year wise data for entity (probe42 api call) financials_data_api_response = ApiCallHelper.probe42ApiCall(cin); financials_data_api_response.then(function(result){ if(result == false) { // create skeleton here financialControllerHelper.createSkeleton(losid,entityid); } else { //filter lineitems from api responce and construct to needed format lineItem_data = Probe42DataMappingHelper.lineItemFetching(result); lineItem_data.then(function(lineItem_result){ //create financial table and entityfinyear table record here lineItem_result.forEach((value, key)=>{ Entityfinyear.create({ "losid":Entitydata.dataValues.losid,"entityid":Entitydata.dataValues.id,"FY":value.year,"st_type": 1 }) .then(Entityfinyearsdata => { // create skeletion with itemmaster data (itemmaster(id) == financial(itemid)) Itemsmaster.findAll({ where :{is_active : 1},attributes: ['id'] , order: [['id', 'ASC']] }) .then(ItemsmasterData => { //construct lineitem array for bulk insert using itemmaster primarykey (id) var SkeletonInsert = new Promise((resolve, reject) => { let fin_data_array = []; ItemsmasterData.forEach( (itemvalue , index , itemvaluearray) => { fin_data_obj = { "entity_id":Entityfinyearsdata.dataValues.entityid,"st_type":Entityfinyearsdata.dataValues.st_type,"itemid":itemvalue.dataValues.id,"fy":Entityfinyearsdata.dataValues.FY,"value":0,"is_active":1,"createdby":4} fin_data_array.push(fin_data_obj); if (index === itemvaluearray.length -1) { resolve(fin_data_array); } }) }); SkeletonInsert.then((Query_data)=>{ Financials.bulkCreate(Query_data).then(data=>{ //line item data update // mapping of probe42 api lineItem with itemMaster primary key final_array = Probe42DataMappingHelper.lineItemMapping(value,entityid); final_array.then(function(update_array_data){ // update mapped lineitem value here Probe42DataMappingHelper.lineItemUpdate(update_array_data); });//end of lineItemUpdate helper call }).catch(err=>(console.log(err))); //skeleton bulk create query }); }).catch(err=>(console.log(err))); //itemmaster query }).catch(err => { res.status(404).send({'status':404, message: err.message || "Some error occurred while insertinging statements." ,'data': "No data" }); }); // end of entity fin year table data insert });//end of line item foreach });//end of lineItem filter from api response helper call } // end of probe42 api responce success else condition });//end of probe42 api call } else { // resolve here if (key === array.length -1) { resolve(); } } }).catch(err => { res.status(404).send({'status':404, message: err.message || "Some error occurred while insertinging statements." ,'data': "No data" }); }); // end of entity insert } //end of else condition }); // end of (losid,pan,cin) combination checking entity data exist or not }); // end of Redirection api data foreach } // end of redirectionApiData else condition }) // end of Redirection api call }); // end of promise EntityInsert.then(async() => { Statementsmaster.findAll({ where :{is_active : 1} , include: { all: true, nested: true , where :{is_active : 1} , required:false}}) .then(MasterData => { Entities.findAll({where : { losid } , attributes: [ 'id', 'losid' , 'pan' , 'cin' , 'bizname' , 'entity_type' , 'activity_group' , 'biz_act_desc' , 'process_instance_id' , 'probe42_data_status' ,'is_verified' ], order: [['id', 'ASC']] }) .then(async(EntitiesData) => { let Time = 2000; let data = []; //EntitiesData.forEach((value, key)=>{ // Time = Time + 500; // instancesid = value.dataValues.process_instance_id; // taskid = camundaHelper.financialsListOfProcessInstances(instancesid); // taskid.then(function(result){ // Time = Time + 500; // formVariable = camundaHelper.financialsFormVariables(result); // formVariable.then(function(form_result){ // formVariableResult = JSON.parse(form_result); // if(formVariableResult.type){ camunda_status = {"process_status":"NULL"}; } else { camunda_status =JSON.parse(form_result); } // obj_data = { ...value.dataValues ,status:camunda_status , statementsmasterrData:MasterData } // data.push(obj_data); // }); // }); //}); // end of EntitiesData foreach for(const value of EntitiesData) { Time = Time + 500; instancesid = value.dataValues.process_instance_id; taskid = await camundaHelper.financialsListOfProcessInstances(instancesid); Time = Time + 500; formVariable = await camundaHelper.financialsFormVariables(taskid); formVariableResult = JSON.parse(formVariable); if(formVariableResult.type){ camunda_status = {"process_status":"NULL"}; } else { camunda_status =JSON.parse(formVariable); } obj_data = { ...value.dataValues ,status:camunda_status , statementsmasterrData:MasterData } data.push(obj_data); } // end of for loop setTimeout(()=>{ if(data.length > 1) { // below code for overall sum object push process sum_data = { ...{'losid':losid,'bizname':"Consolidated Financials Summary",'is_consolidated_api_call':1} , statementsmasterrData:MasterData }; data.push(sum_data); // send respose to FE res.send({'status':200,'message':"success",'data':data}); } else if(data.length == 1) { // send respose to FE res.send({'status':200,'message':"success",'data':data}); } else { res.send({'status':404,'message':"failed",'data':"data not found"}); } },Time) }); // end of findall EntitiesData }); // end of findall masters datas }); } catch(err) { res.status(500).send({'status':404, message: err.message || "Some error occurred while inserting statements." ,'data': "No data" }); } // end of try catch }); // end of sync function }; // FinantialsSummary exports.FinantialsSummary = async (req, res) => { try { const id = req.query.entityid Entities.findOne({where : { id } , attributes: [ 'id','losid','process_instance_id' , 'entity_type' ] }) .then(EntitiesData => { const instancesid = EntitiesData.dataValues.process_instance_id; sequelize.query("select a.losid,a.entityid,a.FY,a.st_type as st_type_id, b.statement_name as st_type_name,a.additional_year_type FROM entity_fin_year a LEFT JOIN (SELECT id,statement_name FROM statement_type) b ON a.st_type = b.id WHERE entityid ="+id+" order by a.fy desc") .then(EntityfinyearData => { if(EntityfinyearData[0].length != 0) { const data = EntityfinyearData[0]; const year_1 = EntityfinyearData[0][0].FY; const additional_year_type = EntityfinyearData[0][0].additional_year_type; if(EntitiesData.dataValues.entity_type == "COMPANY"){entity_type_key = "pvtltd"} else if(EntitiesData.dataValues.entity_type == "INDIVIDUAL"){entity_type_key = "llp"} else {entity_type_key = "others"} const years = {losid:EntitiesData.dataValues.losid,entityid:EntitiesData.dataValues.id,entity_type_key:entity_type_key,additional_year_type:additional_year_type}; // below function call is for calculation of additional new year flag generation add_new_FY_flag = financialControllerHelper.addNewFyFlag(year_1); // below code for constructing query for dynamic financial years var select_items = ""; var sub_query = ""; data.forEach((value, key)=>{ const words = ['','one','two','three','four', 'five','six','seven','eight','nine','ten']; // years object construction year_count = key + 1; years["Y"+year_count] = value.FY; years["Y"+year_count+"_st_type_id"] = value.st_type_id; years["Y"+year_count+"_st_type_name"] = value.st_type_name; // fin_query construction if(key != 0) { key_addition = key + 1; alisename = words[key_addition]; select_items += ","+alisename+".st_type as Y"+key_addition+"_st_type,"+alisename+".fy as Y"+key_addition+","+alisename+".id Y"+key_addition+"_id ,"+alisename+".is_editable as Y"+key_addition+"_is_editable ,"+alisename+".value Y"+key_addition+"_value"; sub_query += "LEFT JOIN ( SELECT id,entity_id, itemid, value,fy,is_active,st_type,is_editable FROM financials WHERE fy = '"+value.FY+"' and entity_id = "+id+" and is_active = 1) "+alisename+" ON a.entity_id = "+alisename+".entity_id and a.itemid = "+alisename+".itemid "; } }); // end of foreach var query = "Select a.entity_id,x.id as statement_id,x.statement as statement,y.id as section_id,y.section as section,w.subsection as subsection_id,z.subsection as subsection , z.itemtext as subsection_itemtext ,a.itemid,w.itemtext as items,w.formula,w.is_calculated,w.is_summary,w.pvtltd,w.llp,w.others,a.st_type as Y1_st_type,a.fy as Y1,a.id as Y1_id ,a.is_editable as Y1_is_editable,a.value as Y1_value "+ select_items +",v.remarks , v.id as remarks_id FROM financials a LEFT JOIN ( SELECT id,entity_id,itemid,remarks FROM fin_remarks WHERE is_active = 1) v ON a.entity_id = v.entity_id and a.itemid = v.itemid JOIN ( SELECT id,itemtext,statement,section,subsection,formula,is_calculated,is_summary,pvtltd,llp,others FROM itemsmaster ) w ON a.itemid = w.id JOIN ( SELECT id, statement FROM statementsmaster ) x ON w.statement = x.id JOIN ( SELECT id, section FROM sectionsmaster ) y ON w.section = y.id LEFT JOIN ( SELECT id, subsection , itemtext FROM subsectionsmaster ) z ON w.subsection = z.id "+ sub_query +"WHERE a.fy = '"+year_1+"' and a.entity_id = "+id+" and a.is_active = 1 order by w.statement asc , w.section asc , w.subsection asc"; setTimeout(function(){ sequelize.query(query).then(summary => { // is_summary filter from fin_summary data let is_summary_item_array = []; const fin_summary = summary[0]; fin_summary.forEach((value, key)=>{ if(value.is_summary == 1) { obj_data = value; is_summary_item_array.push(obj_data); } }); // get camunda status taskid = camundaHelper.financialsListOfProcessInstances(instancesid); taskid.then(function(result){ formVariable = camundaHelper.financialsFormVariables(result); formVariable.then(function(form_result){ formVariableResult = JSON.parse(form_result); if(formVariableResult.type){ camunda_status = {"process_status":"NULL"}; } else { camunda_status =JSON.parse(form_result); } setTimeout(function() { res.send({'status':200,'message':"success",'data':{"years" : years ,"add_new_finyear_flag" : add_new_FY_flag , status:camunda_status,"summary" : is_summary_item_array , "fin_summary" : summary } }); }, 3000); }); // enf of formVariable api call }); // enf of taskid api call }).catch(err => { res.status(500).send({'status':404, message: err.message || "Some error occurred while retrieving tutorials." ,'data': "No data" }); }); }, 2000);// end of set time out } else { res.status(404).send({'status':404,message: "Financials data not found." ,'data': "No data" });} }) // end of EntityfinyearData query }) // end of EntitiesData query } catch(err) { res.status(500).send({'status':404, message: err.message || "Some error occurred while inserting statements." ,'data': "No data" }); } }; //ConsolidatedSummary exports.ConsolidatedSummary = async (req, res) => { try { const losid = req.query.losid Entityfinyear.findAll({where : { losid } , attributes: [ [sequelize.fn('DISTINCT', sequelize.col('FY')), 'FY'] ] , order: [['FY', 'DESC']] }) .then(EntityfinyearData => { const year_1 = EntityfinyearData[0].FY; var select_items = ""; var sub_query = ""; var group = ""; EntityfinyearData.forEach((value,key)=>{ const words = ['','one','two','three','four', 'five','six','seven','eight','nine','ten']; if(key != 0) { key_addition = key + 1; alisename = words[key_addition]; select_items += ","+alisename+".fy as Y"+key_addition+" ,SUM("+alisename+".value) as Y"+key_addition+"_value", sub_query += " JOIN(SELECT entity_id,itemid,fy,value FROM financials WHERE fy = '"+value.FY+"' and is_active = 1 GROUP BY itemid,fy,is_active,value,entity_id) "+alisename+ " ON z.id = " + alisename + ".entity_id and a.itemid = "+ alisename +".itemid " group += ","+alisename+".fy"; } }); // end of foreach var query = "Select x.id as statement_id,x.statement as statement,y.id as section_id,y.section as section,e.subsection as subsection_id,g.subsection as subsection , g.itemtext as subsection_itemtext, a.itemid,e.itemtext as items,e.is_summary,a.fy as Y1 , SUM(a.value) as Y1_value"+ select_items +" from entities z JOIN(SELECT entity_id,itemid,fy,value FROM financials WHERE fy = '"+year_1+"'and is_active = 1 GROUP BY itemid,fy,is_active,value,entity_id) a ON z.id = a.entity_id" + sub_query + " JOIN ( SELECT id,itemtext,statement,section,subsection,formula,is_calculated,is_summary FROM itemsmaster ) e ON a.itemid = e.id JOIN ( SELECT id, statement FROM statementsmaster ) x ON e.statement = x.id JOIN ( SELECT id, section FROM sectionsmaster ) y ON e.section = y.id LEFT JOIN ( SELECT id, subsection , itemtext FROM subsectionsmaster ) g ON e.subsection = g.id where losid = '"+losid+"' GROUP BY a.itemid,x.id,x.statement,y.id,y.section,e.subsection,g.subsection,g.itemtext,e.itemtext,e.statement,e.section,e.id,a.fy,e.is_summary " + group + " ORDER BY e.statement asc , e.section asc , e.id asc" setTimeout(function(){ sequelize.query(query) .then(summary => { let is_summary_item_array = []; const summary_data = summary[0]; summary_data.forEach((value, key)=>{ if(value.is_summary == 1) { obj_data = value; is_summary_item_array.push(obj_data); } }); setTimeout(function(){ res.send({'status':200,'message':"success","data":{"summary": is_summary_item_array,'consolidated_summary' : summary }} ); }, 2000);// end of set time out }).catch(err => { res.status(500).send({'status':404, message: err.message || "Some error occurred while retrieving tutorials." ,'data': "No data" }); }); }, 2000);// end of set time out //}); }); } catch(err) { res.status(500).send({'status':404, message: err.message || "Some error occurred while inserting statements." ,'data': "No data" }); } }; // Broken period list api exports.BrokenPeriodsList = (req, res) => { const entityid = req.query.entityid try { Brokenperiods.findOne({where : { entity_id : entityid } }) .then(data => { if(data) {res.send({'status':200,'message':"success",'data':data});} else{res.send({'status':404,'message':"failed",'data':"nodata"});} }) }catch(err) { res.status(500).send({'status':404, message: err.message || "Some error occurred while inserting statements." ,'data': "No data" }); } }; // Broken period Insert OR Update exports.BrokenPeriods = (req, res) => { const obj = req.body if (obj.hasOwnProperty("id")) { // update broken periods const Id = req.body.id Brokenperiods.update( { entity_id: req.body.entity_id, from: req.body.from, to: req.body.to, months: req.body.months, cy: req.body.cy, py: req.body.py, variation: req.body.variation, updatedby: req.body.updatedby, } , { where: { id: Id } }) .then(data => { res.send({'status':200,'message':"success",'data':data}); }) .catch(err => { res.status(404).send({'status':404, message: err.message || "Some error occurred while insertinging statements." ,'data': "No data" }); }); } else { // create broken period Brokenperiods.create({ entity_id: req.body.entity_id, from: req.body.from, to: req.body.to, months: req.body.months, cy: req.body.cy, py: req.body.py, variation: req.body.variation, createdby: req.body.createdby, }) .then(data => { res.send({'status':200,'message':"success",'data':data}); }) .catch(err => { res.status(404).send({'status':404, message: err.message || "Some error occurred while insertinging statements." ,'data': "No data" }); }); } }; exports.createFinancials = (req, res) => { const req_array_data = req.body; try { req_array_data.forEach((value, key)=>{ Financials.findOne({ where: { id : value.id } }).then(function(result) { if(result.value == value.value) { logMsg.info("Value not updated for - EntityId : "+value.entity_id+" , FY : "+value.fy+",ItemId : "+value.itemid+",primary key :"+value.id); } else { Financials.update({ is_active : 0 },{ where: { id: value.id }}); logMsg.info("updated is_active = 0 for primary key : "+value.id); Financials.create({ "entity_id":value.entity_id,"st_type":value.st_type,"itemid":value.itemid,"fy":value.fy,"value":value.value,"is_active":value.is_active,"createdby":value.createdby }) logMsg.info("Created new financials data - EntityId : "+value.entity_id+" , FY : "+value.fy+",ItemId : "+value.itemid); } }) }); 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" }); } }; // this api not in use exports.updateFinancials = (req, res) => { const req_array_data = req.body; try { req_array_data.forEach((value, key)=>{ const id = value.id; Financials.update({ "entity_id":value.entity_id,"st_type":value.sy_type,"itemid":value.itemid,"fy":value.fy,"value":value.value,"is_active":value.is_active,"updatedby":value.updatedby },{ where: { id:id }}) }); res.send({'status':200,'message':"success",'data':"No data"}); logMsg.info("multiple financials update Success"); }catch(err) { res.send({'status':404, message: err.message || "Some error occurred while inserting statements." ,'data': "No data" }); } }; // create financial skeletion for given year exports.createFinancialYear = async (req, res) => { losid = req.body.losid; entityid = req.body.entityid; Entityfinyear.findOne({ where: { losid : losid , entityid : entityid } }) .then(Entityfinyearsdata => { const fy = req.body.fy; const st_type = req.body.st_type; const additional_year_type = req.body.additional_year_type; if(req.body.fy != 0) { Entityfinyear.create({ losid:Entityfinyearsdata.dataValues.losid,entityid:Entityfinyearsdata.dataValues.entityid,FY:fy,st_type:st_type,additional_year_type:additional_year_type }) .then(Entityfinyearsdata => { // generate new financials data array for given FY with entity_id Itemsmaster.findAll({ where :{is_active : 1},attributes: ['id'] , order: [['id', 'ASC']] }) .then(ItemsmasterData => { //construct lineitem array for bulk insert using itemmaster primarykey (id) var SkeletonInsert = new Promise((resolve, reject) => { let fin_data_array = []; ItemsmasterData.forEach( (itemvalue , index , itemvaluearray) => { fin_data_obj = { "entity_id":Entityfinyearsdata.dataValues.entityid,"st_type":Entityfinyearsdata.dataValues.st_type,"itemid":itemvalue.dataValues.id,"fy":Entityfinyearsdata.dataValues.FY,"value":0,"is_active":1,"createdby":4} fin_data_array.push(fin_data_obj); if (index === itemvaluearray.length -1) { resolve(fin_data_array); } }) }); SkeletonInsert.then((Query_data)=>{ Financials.bulkCreate(Query_data).then(data=>{ logMsg.info("Skeleton created for LosId ="+losid+" - EntityId = "+entityid); //response res.status(200).send({'status':200,'message':"success",'data':"No data"}); }).catch(err=>(console.log(err))); //skeleton bulk create query }); }).catch(err=>(console.log(err))); //itemmaster query }).catch(err => { res.status(404).send({'status':404, message: err.message || "Some error occurred while insertinging statements." ,'data': "No data" }); }); // end of update Entityfinyears } else { res.status(405).send({'status':405, 'message': "The year creation not allowed" ,'data': "No data" }); } // end of else part }).catch(err => { res.status(404).send({'status':404, message: err.message || "Some error occurred while insertinging statements." ,'data': "No data" }); }); // end of findOne Entityfinyears }; exports.refreshApi = (req, res) => { try { const cin = req.body.cin; const losid = req.body.losid; const entityid = req.body.entityid; // call and get financial year wise data for entity (probe42 api call) financials_data_api_response = ApiCallHelper.probe42ApiCall(cin); financials_data_api_response.then(function(result){ // check if(result == false) { res.send({'status':404,message: "Failed" ,'data': "No data for this cin number from probe42" }); } else { //filter lineitems from api responce and construct to needed format lineItem_data = Probe42DataMappingHelper.lineItemFetching(result); lineItem_data.then(function(lineItem_result){ var SkeletonUpdate = new Promise((resolve, reject) => { //create financial table and entityfinyear table record here lineItem_result.forEach((value, index , lineItem_result_array)=>{ Entityfinyear.findOne({raw : true , where:{losid : losid , entityid : entityid , FY : value.year}}) .then((data)=>{ if(data) { console.log(value.year + "exist"); // mapping of probe42 api lineItem with itemMaster primary key final_array = Probe42DataMappingHelper.lineItemMapping(value,entityid); final_array.then(function(update_array_data){ // update mapped lineitem value here Probe42DataMappingHelper.lineItemUpdate(update_array_data); // promise resolve check if (index === lineItem_result_array.length -1) { resolve(); } });//end of lineItemUpdate helper call } else { console.log(value.year + " not exist"); // create skeleton for missing year and update financials values Entityfinyear.create({ "losid":losid,"entityid":entityid,"FY":value.year,"st_type": 1 }) .then(Entityfinyearsdata => { // create skeletion with itemmaster data (itemmaster(id) == financial(itemid)) Itemsmaster.findAll({ where :{is_active : 1},attributes: ['id'] , order: [['id', 'ASC']] }) .then(ItemsmasterData => { //construct lineitem array for bulk insert using itemmaster primarykey (id) var SkeletonInsert = new Promise((resolve, reject) => { let fin_data_array = []; ItemsmasterData.forEach( (itemvalue , index , itemvaluearray) => { fin_data_obj = { "entity_id":Entityfinyearsdata.dataValues.entityid,"st_type":Entityfinyearsdata.dataValues.st_type,"itemid":itemvalue.dataValues.id,"fy":Entityfinyearsdata.dataValues.FY,"value":0,"is_active":1,"createdby":4} fin_data_array.push(fin_data_obj); if (index === itemvaluearray.length -1) { resolve(fin_data_array); } }) }); SkeletonInsert.then((Query_data)=>{ Financials.bulkCreate(Query_data).then(data=>{ logMsg.info("Skeleton created successfully for entityid : "+ entityid +" year : " +value.year); // mapping of probe42 api lineItem with itemMaster primary key final_array = Probe42DataMappingHelper.lineItemMapping(value,entityid); final_array.then(function(update_array_data){ // update mapped lineitem value here Probe42DataMappingHelper.lineItemUpdate(update_array_data); // promise resolve check if (index === lineItem_result_array.length -1) { resolve(); } });//end of lineItemUpdate helper call }).catch(err=>(console.log(err))); //skeleton bulk create query }); }).catch(err=>(console.log(err))); //itemmaster query }).catch(err => { res.status(404).send({'status':404, message: err.message || "Some error occurred while insertinging statements." ,'data': "No data" }); }); // end of entity fin year table data insert } }); });//end of line item foreach }); SkeletonUpdate.then((Query_data)=>{ setTimeout(() => { res.status(200).send({'status':200,message: "success" ,'data': "No data" }); }, 2000); }); });//end of lineItem filter from api response helper call } // end of probe42 api responce success else condition });//end of probe42 api call }catch(err) { res.send({'status':404,message: err.message || "Some error occurred while inserting statements." ,'data': "No data"}); } }; //MW83031480 // exports.queryConstruct = async (req, res) => { // try // { // data = [{"ID": "float"}, {"ApplicationRefno": "float"}, {"ReportIssuesCode": "NoneType"}, {"ReportIssuesMsg": "NoneType"}, {"ReportIssuesDescription": "NoneType"}, {"ReportHeaderDaysPasswrdToExpire": "NoneType"}, {"ReportHeaderReportOrderNo": "str"}, {"ReportHeaderReportOrderDate": "datetime"}, {"ReportHeaderReportOrderedBy": "str"}, {"ReportHeaderMemberDetails": "str"}, {"ReportHeaderApplicationRefNo": "float"}, {"ReportHeaderMemberRefNo": "NoneType"}, {"ReportHeaderInquiryPurpose": "str"}, {"EnqInfoBorrowerName": "str"}, {"EnqInfoDateOfReg": "datetime"}, {"EnqInfoPan": "str"}, {"EnqInfoCin": "str"}, {"EnqInfoTin": "NoneType"}, {"EnqInfoCrn": "NoneType"}, {"EnqInfoAddressCount": "float"}, {"EnqInfoAddressAddressLine0": "str"}, {"EnqInfoAddressAddressLine1": "NoneType"}, {"EnqInfoAddressAddressLine2": "NoneType"}, {"BorrowerProfileBDName": "str"}, {"BorrowerProfileBDBLC": "str"}, {"BorrowerProfileBDClassOfActivity0": "str"}, {"BorrowerProfileBDClassOfActivity1": "str"}, {"BorrowerProfileBDClassOfActivity2": "str"}, {"BorrowerProfileBDBusinessCatg": "str"}, {"BorrowerProfileBDBusinessIndustryType": "str"}, {"BorrowerProfileBDSalesFigure": "NoneType"}, {"BorrowerProfileBDNoOfEmp": "NoneType"}, {"BorrowerProfileBDDOI": "datetime"}, {"BorrowerProfileBDYear": "NoneType"}, {"BorrowerProfileBACDRegaddress": "str"}, {"BorrowerProfileBACDTelephoneNo": "float"}, {"BorrowerProfileBACDfaxNo": "NoneType"}, {"BorrowerProfileBACDMobileNo": "str"}, {"BorrowerProfileBDRInstCurrent": "str"}, {"BorrowerProfileBDRInstLst24Mnths": "str"}, {"BorrowerProfileBDROutCurrent": "str"}, {"BorrowerProfileBDROutLst24Mnths": "str"}, {"RankName": "str"}, {"RankValue": "str"}, {"RankExclusionReason": "str"}, {"RankMessage": "NoneType"}, {"CPSInstMsg": "str"}, {"CPSInstTotalLenders": "float"}, {"CPSInsttotalCFBorrower": "float"}, {"CPSInsttotalCFGuarantor": "float"}, {"CPSInsttotalCFBP": "NoneType"}, {"CPSInstTotalCFGP": "NoneType"}, {"CPSInstOpenCF": "float"}, {"CPSInsTotalOutstandingBorrower": "float"}, {"CPSInsTotalOutstandingGuarantor": "float"}, {"CPSInsTotalOutstandingBP": "float"}, {"CPSInsTotalOutstandingGP": "float"}, {"CPSInsLtstCFOpndDate": "NoneType"}, {"CPSInsDCFBorrower": "float"}, {"CPSInsDCFGuarantor": "float"}, {"CPSInsDCFBP": "NoneType"}, {"CPSInsDCFGP": "NoneType"}, {"CPSInsDOSBorrower": "float"}, {"CPSInsDOSGuarantor": "float"}, {"CPSInsDOSBP": "float"}, {"CPSInsDOSGP": "float"}, {"CPSOutMsg": "NoneType"}, {"CPSOutOPSBMsg": "NoneType"}, {"CPSOutOPSBTotalLenders": "float"}, {"CPSOutOPSBTotalCFBorrower": "float"}, {"CPSOutOPSBTotalCFGuarantor": "float"}, {"CPSOutOPSBTotalCFBP": "NoneType"}, {"CPSOutOPSBTotalCFGP": "float"}, {"CPSOutOPSBOpenCF": "float"}, {"CPSOutOPSBTOBorrower": "float"}, {"CPSOutOPSBTOGuarantor": "float"}, {"CPSOutOPSBTOBP": "NoneType"}, {"CPSOutOPSBTOGP": "NoneType"}, {"CPSOutOPSBLtstCFOpndDate": "datetime"}, {"CPSOutOPSBDCFBorrower": "float"}, {"CPSOutOPSBDCFGuarantor": "float"}, {"CPSOutOPSBDCFBP": "NoneType"}, {"CPSOutOPSBDCFGP": "float"}, {"CPSOutOPSBDOSBorrower": "float"}, {"CPSOutOPSBDOSGuarantor": "float"}, {"CPSOutOPSBDOSBP": "NoneType"}, {"CPSOutOPSBDOSGP": "NoneType"}, {"CPSOutOPFBMsg": "NoneType"}, {"CPSOutOPFBTotalLenders": "float"}, {"CPSOutOPFBTCFBorrower": "float"}, {"CPSOutOPFBTCFGuarantor": "float"}, {"CPSOutOPFBTCFBP": "NoneType"}, {"CPSOutOPFBTCFGP": "NoneType"}, {"CPSOutOPFBOpenCF": "float"}, {"CPSOutOPFBTOSBorrower": "float"}, {"CPSOutOPFBTOSGuarantor": "float"}, {"CPSOutOPFBTOSBP": "NoneType"}, {"CPSOutOPFBTOSGP": "NoneType"}, {"CPSOutOPFBLtstCFOpndDate": "datetime"}, {"CPSOutOPFBDCFBorrower": "float"}, {"CPSOutOPFBDCFGuarantor": "float"}, {"CPSOutOPFBDCFBP": "NoneType"}, {"CPSOutOPFBDCFGP": "NoneType"}, {"CPSOutOPFBDOSBorrower": "float"}, {"CPSOutOPFBDOSGuarantor": "float"}, {"CPSOutOPFBDOSBP": "NoneType"}, {"CPSOutOPFBDOSGP": "NoneType"}, {"CPSOutNBFCMsg": "NoneType"}, {"CPSOutNBFCTotalLenders": "float"}, {"CPSOutNBFCTCFBorrower": "float"}, {"CPSOutNBFCTCFGuarantor": "float"}, {"CPSOutNBFCTCFBP": "NoneType"}, {"CPSOutNBFCTCFGP": "NoneType"}, {"CPSOutNBFCOpenCF": "float"}, {"CPSOutNBFCTOSBorrower": "float"}, {"CPSOutNBFCTOSGuarantor": "float"}, {"CPSOutNBFCTOSBP": "NoneType"}, {"CPSOutNBFCTOSGP": "NoneType"}, {"CPSOutNBFCLtstCFOpndDate": "NoneType"}, {"CPSOutNBFCDCFBorrower": "float"}, {"CPSOutNBFCDCFGuarantor": "float"}, {"CPSOutNBFCDCFBP": "NoneType"}, {"CPSOutNBFCDCFGP": "NoneType"}, {"CPSOutNBFCDOSBorrower": "float"}, {"CPSOutNBFCDOSGuarantor": "float"}, {"CPSOutNBFCDOSBP": "NoneType"}, {"CPSOutNBFCDOSGP": "NoneType"}, {"CPSOutOutsideTotalMsg": "NoneType"}, {"CPSOutOutsideTotalTotalLenders": "float"}, {"CPSOutOutsideTotalTCFBorrower": "float"}, {"CPSOutOutsideTotalTCFGuarantor": "float"}, {"CPSOutOutsideTotalTCFBP": "NoneType"}, {"CPSOutOutsideTotalTCFGP": "NoneType"}, {"CPSOutOutsideTotalOpenCF": "float"}, {"CPSOutOutsideTotalTOSBorrower": "float"}, {"CPSOutOutsideTotalTOSGuarantor": "float"}, {"CPSOutOutsideTotalTOSBP": "float"}, {"CPSOutOutsideTotalTOSGP": "float"}, {"CPSOutOutsideTotalLtstCFOpndDate": "str"}, {"CPSOutOutsideTotalDCFBorrower": "float"}, {"CPSOutOutsideTotalDCFGuarantor": "float"}, {"CPSOutOutsideTotalDCFBP": "NoneType"}, {"CPSOutOutsideTotalDCFGP": "NoneType"}, {"CPSOutOutsideTotalDOSBorrower": "float"}, {"CPSOutOutsideTotalDOSGuarantor": "float"}, {"CPSOutOutsideTotalDOSBP": "float"}, {"CPSOutOutsideTotalDOSGP": "float"}, {"CPSTotalTotalLenders": "float"}, {"CPSTotalTotalCF": "float"}, {"CPSTotalOpenCF": "float"}, {"CPSTotalTotalOutstanding": "float"}, {"CPSTotalLtstCFOpndDate": "str"}, {"CPSTotalDCF": "float"}, {"CPSTotalDOS": "float"}, {"EnqSSMsg": "NoneType"}, {"EnqSSInstNOEMnths1": "float"}, {"EnqSSInstNOEMnths2to3": "float"}, {"EnqSSInstNOEMnths4to6": "float"}, {"EnqSSInstNOEMnths7to12": "float"}, {"EnqSSInstNOEMnths12to24": "float"}, {"EnqSSInstNOEGrtrThan24Mnths": "float"}, {"EnqSSInstNOETotal": "float"}, {"EnqSSInstNOEMstRecentDate": "NoneType"}, {"EnqSSOutNOEMnths1": "float"}, {"EnqSSOutNOEMnths2to3": "float"}, {"EnqSSOutNOEMnths4to6": "float"}, {"EnqSSOutNOEMnths7to12": "float"}, {"EnqSSOutNOEMnthsGrtrThan24Mnths": "float"}, {"EnqSSOutNOETotal": "float"}, {"EnqSSOutNOEMstRecentDate": "datetime"}, {"EnqSSETMnths1": "float"}, {"EnqSSETMnths2to3": "float"}, {"EnqSSETMnths4to6": "float"}, {"EnqSSETMnths7to12": "float"}, {"EnqSSETMnths12to24": "float"}, {"EnqSSETGrtrThan24Mnths": "float"}, {"EnqSSETTotal": "float"}, {"EnqSSETMstRecentDate": "NoneType"}, {"DISMsg": "NoneType"}, {"DISMsgOfBorrower": "NoneType"}, {"DISMsgOfBorrowerInst": "str"}, {"DISMsgOfBorrowerOut": "NoneType"}, {"DISMsgOfRelatedPartie": "str"}, {"DISMsgOfRelatedPartiesInst": "NoneType"}, {"DISMsgOfRelatedPartiesOut": "NoneType"}, {"DISMsgOfGuarantedParties": "str"}, {"DISDIBInstWilfulDefault": "float"}, {"DISDIBInstSFNOS": "float"}, {"DISDIBInstSFAmt": "float"}, {"DISDIBInstWOffNOS": "float"}, {"DISDIBInstWOffAmt": "float"}, {"DISDIBInstSettledNOS": "float"}, {"DISDIBInstSettledAmt": "float"}, {"DISDIBInstInvokedNOS": "float"}, {"DISDIBInstInvokedAmt": "float"}, {"DISDIBInstOverdueCFNOS": "float"}, {"DISDIBInstOverdueCFAmt": "float"}, {"DISDIBInstDishonoredCheque": "float"}, {"DISDIBOutWilfulDefault": "float"}, {"DISDIBOutSFNOS": "float"}, {"DISDIBOutSFAmt": "float"}, {"DISDIBOutWOffNOS": "float"}, {"DISDIBOutWOffAmt": "float"}, {"DISDIBOutSettledNOS": "float"}, {"DISDIBOutSettledAmt": "float"}, {"DISDIBOutInvokedNOS": "float"}, {"DISDIBOutInvokedAmt": "float"}, {"DISDIBOutOverdueCFNOS": "float"}, {"DISDIBOutOverdueCFAmt": "float"}, {"DISDIBOutDishonoredCheque": "float"}, {"DISDIBTotalWilfulDefault": "float"}, {"DISDIBTotalSFNOS": "float"}, {"DISDIBTotalSFAmt": "float"}, {"DISDIBTotalWOffNOS": "float"}, {"DISDIBTotalWOffAmt": "float"}, {"DISDIBTotalSettledNOS": "float"}, {"DISDIBTotalSettledAmt": "float"}, {"DISDIBTotalInvokedNOS": "float"}, {"DISDIBTotalInvokedAmt": "float"}, {"DISDIBTotalOverdueCFNOS": "float"}, {"DISDIBTotalOverdueCFAmt": "float"}, {"DISDIBTotalDishonoredCheque": "float"}, {"DISGOBInstWilfulDefault": "float"}, {"DISGOBInstSFNOS": "float"}, {"DISGOBInstSFAmt": "float"}, {"DISGOBInstWOffNOS": "float"}, {"DISGOBInstWOffAmt": "float"}, {"DISGOBInstSettledNOS": "float"}, {"DISGOBInstSettledAmt": "float"}, {"DISGOBInstInvokedNOS": "float"}, {"DISGOBInstInvokedAmt": "float"}, {"DISGOBInstOverdueCFNOS": "float"}, {"DISGOBInstOverdueCFAmt": "float"}, {"DISGOBInstDishonoredCheque": "float"}, {"DISGOBOutWilfulDefault": "float"}, {"DISGOBOutSFNOS": "float"}, {"DISGOBOutSFAmt": "float"}, {"DISGOBOutWOffNOS": "float"}, {"DISGOBOutWOffAmt": "float"}, {"DISGOBOutSettledNOS": "float"}, {"DISGOBOutSettledAmt": "float"}, {"DISGOBOutInvokedNOS": "float"}, {"DISGOBOutInvokedAmt": "float"}, {"DISGOBOutOverdueCFNOS": "float"}, {"DISGOBOutOverdueCFAmt": "float"}, {"DISGOBOutDishonoredCheque": "float"}, {"DISGOBTotalWilfulDefault": "float"}, {"DISGOBTotalSFNOS": "float"}, {"DISGOBTotalSFAmt": "float"}, {"DISGOBTotalWOffNOS": "float"}, {"DISGOBTotalWOffAmt": "float"}, {"DISGOBTotalSettledNOS": "float"}, {"DISGOBTotalSettledAmt": "float"}, {"DISGOBTotalInvokedNOS": "float"}, {"DISGOBTotalInvokedAmt": "float"}, {"DISGOBTotalOverdueCFNOS": "float"}]; // let Queryvalues = "CREATE TABLE commercial_borrower_profile "; // data.forEach((result, index, array) => { // Object.keys(result).forEach((key) => { // if(index == 0) // { // if(result[key] == 'float') // { Datatype = "real NULL"; Queryvalues += "("+key +" "+Datatype+","; } // else if(result[key] == 'NoneType') // { Datatype = "nvarchar(255) NULL"; Queryvalues += "("+key +" "+Datatype+","; } // else if(result[key] == 'str') // { Datatype = "nvarchar(255) NULL"; Queryvalues += "("+key +" "+Datatype+","; } // else if(result[key] == 'datetime') // { Datatype = "datetime NULL"; Queryvalues += "("+key +" "+Datatype+","; } // else if(result[key] == 'int') // { Datatype = "int NULL"; Queryvalues += "("+key +" "+Datatype+","; } // } // else if (array.length == index + 1 ) // { // if(result[key] == 'float') // { Datatype = "real NULL"; Queryvalues += key +" "+Datatype+")";} // else if(result[key] == 'NoneType') // { Datatype = "nvarchar(255) NULL"; Queryvalues += key +" "+Datatype+")";} // else if(result[key] == 'str') // { Datatype = "nvarchar(255) NULL"; Queryvalues += key +" "+Datatype+")"; } // else if(result[key] == 'datetime') // { Datatype = "datetime NULL"; Queryvalues += key +" "+Datatype+")"; } // else if(result[key] == 'int') // { Datatype = "int NULL"; Queryvalues += key +" "+Datatype+")"; } // } // else // { // if(result[key] == 'float') // { Datatype = "real NULL"; Queryvalues += key +" "+Datatype+","; } // else if(result[key] == 'NoneType') // { Datatype = "nvarchar(255) NULL"; Queryvalues += key +" "+Datatype+","; } // else if(result[key] == 'str') // { Datatype = "nvarchar(255) NULL"; Queryvalues += key +" "+Datatype+","; } // else if(result[key] == 'datetime') // { Datatype = "datetime NULL"; Queryvalues += key +" "+Datatype+","; } // else if(result[key] == 'int') // { Datatype = "int NULL"; Queryvalues += key +" "+Datatype+","; } // } // }) // }) // setTimeout(() => { // console.log(Queryvalues); // }, 7000); // }catch(err) { // res.send({'status':404,message: err.message || "Some error occurred while inserting statements." ,'data': "No data"}); // } // }; exports.demo = async (req, res) => { try { start_date = "'2019-08-12'"; let starting_date = new Date(start_date); end_date = "'2021-05-12'"; let date = new Date(end_date); years_skeleton = []; for(let i=0;i<12;i++) { //store on fly month number month_count = date.getMonth() + 1; //create on fly month data new_date = date.toLocaleString('default', { month: 'short' })+"-"+date.getFullYear(); //create on fly period data new_period = date.getFullYear()+"-"+month_count+"-01"; obj = {month:new_date,period:new_period}; // push skeleton object years_skeleton.push(obj); //Reset date here date.setMonth(date.getMonth() - 1); //check if loop meets starting date or not if(starting_date.getFullYear() == date.getFullYear() && starting_date.getMonth() + 1 == month_count) { break; } } console.log(years_skeleton); // Statementsmaster.findAll({ where :{is_active : 1} , include: { all: true, nested: true , where :{is_active : 1} , required:false}}) // .then(MasterData => { // Entities.findAll({where : { losid } , attributes: [ 'id', 'losid' , 'pan' , 'cin' , 'bizname' , 'entity_type' , 'activity_group' , 'biz_act_desc' , 'process_instance_id' , 'probe42_data_status' ,'is_verified' ] }) // .then(EntitiesData => { // let data = []; // var getCamundaStatus = new Promise(async (resolve, reject) => { // await EntitiesData.forEach(async (value, key , array)=>{ // instancesid = value.dataValues.process_instance_id; // taskid = await camundaHelper.financialsListOfProcessInstances(instancesid); // formVariable = await camundaHelper.financialsFormVariables(taskid); // formVariableResult = await JSON.parse(formVariable); // if(formVariableResult.type){ camunda_status = {"process_status":"NULL"}; } else { camunda_status = formVariableResult; } // obj_data = { ...value.dataValues ,status:camunda_status , statementsmasterrData:MasterData } // data.push(obj_data); // if (key === array.length -1) { resolve(); } // }); // end of EntitiesData foreach // }); // getCamundaStatus.then(()=>{ // // below code for overall sum object push process // sum_data = { ...{'losid':losid,'bizname':"Consolidated Financials Summary",'is_consolidated_api_call':1} , statementsmasterrData:MasterData }; // data.push(sum_data); // // send respose to FE // res.send({'status':200,'message':"success",'data':data}); // }); // }); // end of findall EntitiesData // }); // end of findall masters datas // redirectionApi = ApiCallHelper.redirectionApiCall(losid); // redirectionApi.then(function(redirectionApiData){ // cin = redirectionApiData[0].ciN_LLPIN; // cin_no = cin.toUpperCase(); // console.log(cin_no) // financials_data_api_response = ApiCallHelper.probe42ApiCall(cin_no); // financials_data_api_response.then(function(result){ console.log(result) // //filter lineitems from api responce and construct to needed format // lineItem_data = Probe42DataMappingHelper.lineItemFetching(result); // lineItem_data.then(function(lineItem_result){ // lineItem_result.forEach((value,index,array) => { // // mapping of probe42 api lineItem with itemMaster primary key // entityid = 00000; // final_array = Probe42DataMappingHelper.lineItemMapping(value,entityid); // final_array.then(function(update_array_data){ // console.log(update_array_data) // console.log(update_array_data.length) // // update mapped lineitem value here // //Probe42DataMappingHelper.lineItemUpdate(update_array_data); // });//end of lineItemUpdate helper call // });//end of lineItem mapping with itemMaster primary key helper call // });//end of lineItem filter from api response helper call // });//end of probe42 api call // }); }catch(err) { res.send({'status':404,message: err.message || "Some error occurred while inserting statements." ,'data': "No data"}); } }; // exports.demoone = (req, res) => { // Sync(function() // { // try // { // cin = "L74120MH1985PLC035308"; // // //probe42 api call // financials_data_api_response = ApiCallHelper.probe42ApiCall(cin); // financials_data_api_response.then(function(result){ // //filter lineitems from api responce and construct to needed format // lineItem_data = Probe42DataMappingHelper.lineItemFetching(result); // lineItem_data.then(function(lineItem_result){ console.log(lineItem_result); // lineItem_result.forEach((value,index,array) => { // // mapping of probe42 api lineItem with itemMaster primary key // final_array = Probe42DataMappingHelper.lineItemMapping(value,entityid); // final_array.then(function(update_array_data){ console.log(update_array_data) // console.log(update_array_data.length) // // update mapped lineitem value here // //Probe42DataMappingHelper.lineItemUpdate(update_array_data); // });//end of lineItemUpdate helper call // });//end of lineItem mapping with itemMaster primary key helper call // });//end of lineItem filter from api response helper call // });//end of probe42 api call // } catch(err) { // res.status(500).send({'status':404, // message: err.message || "Some error occurred while inserting statements." ,'data': "No data" // }); } // end of try catch // }); // end of sync function // };