flexbiz-server
Version:
Flexible Server
39 lines (37 loc) • 13.5 kB
JavaScript
const fs=require("fs"),moment=require("moment"),numeral=require("numeral"),_=require("lodash"),path=require("path"),permission=require("../libs/permission"),htmlReport=require("../libs/htmlReport"),textReport=require("../libs/textReport"),excelReport=require("excel-report"),{JSONParser,evalute,prepareParameters,getParameterData}=require("../libs/utils"),{getCacheReport}=require("../libs/redis-cache"),utils=require("../libs/utils"),{createTmpFile,generateDefaultExcel}=require("../libs/excelHelper"),
rptExcelHandler=async($ctrl$$,$req$$,$callback$$)=>{const $rptId$$=$ctrl$$.module,$module$$=$ctrl$$.module,$options$$=$ctrl$$.options;let $notNeedRight$$=await $ctrl$$.notNeedRight($req$$.user);delete $req$$.query.rpt;let $body$$={};_.isObject($req$$.body)&&($body$$=$req$$.body);$req$$.query={...$req$$.query,...$body$$};try{for(let $q$$ in $req$$.query)if(!$req$$.query[$q$$])delete $req$$.query[$q$$];else if(_.isString($req$$.query[$q$$])&&($req$$.query[$q$$].indexOf("[")>=0||$req$$.query[$q$$].indexOf("{")>=
0))try{$req$$.query[$q$$]=JSONParser($req$$.query[$q$$])}catch($e$$){Logger.error("can't parse json",$req$$.query[$q$$],$rptId$$,"...")}delete $req$$.query.t;$req$$.query.tu_ngay&&($req$$.query.tu_ngay=moment(new Date($req$$.query.tu_ngay)).startOf("date").toDate());$req$$.query.den_ngay&&($req$$.query.den_ngay=moment(new Date($req$$.query.den_ngay)).endOf("date").toDate());$req$$.query.tu_ngay_kt&&($req$$.query.tu_ngay_kt=moment(new Date($req$$.query.tu_ngay_kt)).startOf("date").toDate());$req$$.query.den_ngay_kt&&
($req$$.query.den_ngay_kt=moment(new Date($req$$.query.den_ngay_kt)).endOf("date").toDate());$options$$.onExport||($options$$.onExport=function($app$$,$next$$){$next$$()});let $getData$$,$_new_query$$={...$req$$.query};delete $_new_query$$.id_rpt;delete $_new_query$$.jsonstream;delete $_new_query$$.cType;delete $_new_query$$.refresh_required;delete $_new_query$$.isDrilldown;let $cacheData$$=await getCacheReport($req$$.user.email,$req$$.user.current_id_app,$rptId$$,$req$$.query.id_session,null,null,
JSON.stringify($_new_query$$));$getData$$=$cacheData$$?$cacheData$$.data?function($req$$,$callback$$){$callback$$(null,$cacheData$$.data)}:$ctrl$$.getData:$ctrl$$.getData;let $streamData$$=async function($app$$){await $getData$$($req$$,async function($e$$,$data_report$$){if($e$$)return Logger.error("report getData",$e$$),$e$$.error?$callback$$($e$$):$callback$$({error:$e$$.message||$e$$});global.getModel("log").create({id_app:$req$$.user.current_id_app,id_func:$rptId$$,action:"EXCELRPT",data:{condition:JSON.stringify($req$$.query)}},
$req$$.user.email,$req$$.user_agent,$req$$);let $data$$=$data_report$$;_.isArray($data_report$$)||($data$$=$data_report$$.data||$data_report$$.rows||[$data_report$$]);if($req$$.query.type_data=="json_file"){var {template:$rs$jscomp$1_template$$}=$req$$.body;try{var $fileName_func_string_v$$=await createTmpFile(`${$rs$jscomp$1_template$$?.title||$ctrl$$.name}.json`,JSON.stringify($data$$,null,2));const $downloadUrl$$=$req$$.host?.startsWith("http")?`${$req$$.host}/downloads/temp/${$fileName_func_string_v$$}`:
`https://${$req$$.host}/downloads/temp/${$fileName_func_string_v$$}`;return $callback$$(null,{type:"json",data:{url:$downloadUrl$$}})}catch($e$$){return $callback$$($e$$)}}delete $app$$.participants;delete $app$$.expire_date;delete $app$$.sale_online;delete $app$$.viettel_user;delete $app$$.viettel_password;delete $app$$.viettel_url_service;delete $app$$.vnpt_user;delete $app$$.vnpt_password;delete $app$$.vnpt_url_service;delete $app$$.easy_user;delete $app$$.easy_password;delete $app$$.easy_url_service;
delete $app$$.zalo_app_id;delete $app$$.zalo_secret_key;delete $app$$.zalo_code;delete $app$$.zalo_oa_id;delete $app$$.zalo_code_verifier;delete $app$$.zalo_code_challenge;delete $app$$.zalo_access_token;delete $app$$.zalo_refresh_token;delete $app$$.google_credentials;delete $app$$.sip_uri;delete $app$$.sip_password;delete $app$$.sip_websocket;delete $app$$.voiip_access_token;delete $app$$.voiip_webhook;delete $app$$.wallet_address;delete $app$$.wallet_token;delete $app$$.owner;delete $app$$.default_password;
delete $app$$.email_host;delete $app$$.email_port;delete $app$$.email_secure;delete $app$$.email_authMethod;delete $app$$.email_user;delete $app$$.email_pass;delete $app$$.email_name;delete $app$$.ssl_key;delete $app$$.ssl_cert;delete $app$$.ssl_ca;$app$$.company=$app$$.appInfo={...$app$$};_.extend($app$$,$req$$.query);delete $app$$.access_token;for(let $key$$ in $app$$)$fileName_func_string_v$$=$app$$[$key$$],_.isDate($fileName_func_string_v$$)&&($app$$[$key$$+"_string"]=moment($fileName_func_string_v$$).format("DD/MM/YYYY"));
$app$$.detail=$app$$.details=$data$$;$app$$.datasource={...$app$$};if($rptConfig$$&&$rptConfig$$.handle_data_expression){if($rptConfig$$.handle_data_expression.indexOf("async ")>=0)return $callback$$({error:"async function is not allow"});$fileName_func_string_v$$=`return (async ()=>{
try{
${$rptConfig$$.handle_data_expression}
}catch(e){
return {error:e}
}
})`;try{var $func_string$$=await evalute($fileName_func_string_v$$,{data:$app$$,moment,user:$req$$.user,utils,numeral,getData:getParameterData})();if($func_string$$){if($func_string$$.error)return $callback$$($func_string$$.error);$app$$=$func_string$$}}catch($e$$){return Logger.error("via app: handle data before export",$e$$,$fileName_func_string_v$$),$e$$.error?$callback$$($e$$):$callback$$({error:$e$$.message||$e$$})}}if(($func_string$$=await global.getModel("reportinfo").findOne({code:($req$$.query.report_info_code||
$rptId$$).toLowerCase()}).lean())&&$func_string$$.handle_data_expression){if($func_string$$.handle_data_expression.indexOf("async ")>=0)return $callback$$({error:"async function is not allow"});$func_string$$=`return (async ()=>{
try{
${$func_string$$.handle_data_expression}
}catch(e){
return {error:e}
}
})`;try{if($rs$jscomp$1_template$$=await evalute($func_string$$,{data:$data$$,moment,user:$req$$.user,utils,numeral,getData:getParameterData})()){if($rs$jscomp$1_template$$.error)return Logger.error("global: handle data before export",$rs$jscomp$1_template$$.error,$func_string$$),$callback$$({error:$rs$jscomp$1_template$$.error.message||$rs$jscomp$1_template$$.error});$app$$.detail=$app$$.details=$rs$jscomp$1_template$$}}catch($e$$){return Logger.error("global: handle data before export",
$e$$,$func_string$$),$callback$$({error:$e$$.message||$e$$})}}else $app$$.detail.forEach($r$$=>{for(let $_key$$ in $r$$){let $_v$$=$r$$[$_key$$];if($_v$$&&($_key$$.indexOf("ngay")>=0||$_key$$.indexOf("date")>=0))try{let $d$$=moment($_v$$);$d$$.isValid()&&($r$$[`${$_key$$}`]=$d$$.toDate(),$r$$[`${$_key$$}_string`]=$d$$.format("DD/MM/YYYY"))}catch($e$$){Logger.error("Error convert to date",$_v$$,$e$$)}}});$rptConfig$$&&$rptConfig$$.parameters&&await prepareParameters($rptConfig$$.parameters,$app$$,
$app$$);if($req$$.query.json||$req$$.query.type_data=="json")$callback$$(null,{type:"json",data:$app$$});else $options$$.onExport($app$$,function(){setImmediate(async()=>{if($req$$.query.print||$send_to$$)htmlReport($html_template$$,$app$$).then($rs$$=>{$send_to$$&&global.getModel("app").emitEvent($req$$.user.current_id_app,"report",{id_app:$req$$.user.current_id_app,title:$title_template$$,body:$title_template$$,email_content:$rs$$,allow_unsubcribe:!1},null,$send_to$$.split(","),!0,!0);return $callback$$(null,
{type:"html",data:$rs$$})},$error$$=>{$callback$$({error:$error$$.message||$error$$.error||$error$$})});else{if($templatePath$$=="auto"){const {template:$template$$}=$req$$.body;try{const $fileName$$=await generateDefaultExcel({title:$template$$.title,data:$data$$,columns:$template$$.columns,filterFields:$template$$.filterFields,condition:$template$$.condition||$req$$.query||{}}),$downloadUrl$$=$req$$.host?.startsWith("http")?`${$req$$.host}/downloads/temp/${$fileName$$}`:`https://${$req$$.host}/downloads/temp/${$fileName$$}`;
return $callback$$(null,{type:"json",data:{url:$downloadUrl$$}})}catch($e$$){return $callback$$($e$$)}}let $ext$$=$templatePath$$.split(".").pop();Logger.warn("[rptExcelHandler] t\u1ea1o d\u1eef li\u1ec7u excel...",$req$$.query.return_type,$ext$$);$ext$$==="xlsx"?excelReport($templatePath$$,$app$$,async function($error$jscomp$3_template$$,$result$$){if($error$jscomp$3_template$$)return Logger.error("[rptExcelHandler] Error export to excel",$error$jscomp$3_template$$),$callback$$({error:$error$jscomp$3_template$$.message||
$error$jscomp$3_template$$.error||$error$jscomp$3_template$$});if($req$$.query.return_type=="url"){({template:$error$jscomp$3_template$$}=$req$$.body);try{const $fileName$$=await createTmpFile(`${$error$jscomp$3_template$$?.title||$ctrl$$.name}.xlsx`,$result$$),$downloadUrl$$=$req$$.host?.startsWith("http")?`${$req$$.host}/downloads/temp/${$fileName$$}`:`https://${$req$$.host}/downloads/temp/${$fileName$$}`;Logger.warn("[rptExcelHandler] t\u1ea1o excel tmp file export...",{fileName:$fileName$$,downloadUrl:$downloadUrl$$});
return $callback$$(null,{type:"json",data:{url:$downloadUrl$$}})}catch($e$$){return $callback$$($e$$)}}else $callback$$(null,{type:"xlsx",data:$result$$})},{timezone:configs.timezone||"Asia/Ho_Chi_Minh"}):textReport($templatePath$$,$app$$,async function($error$jscomp$4_template$$,$result$$){if($error$jscomp$4_template$$)return Logger.error("[rptExcelHandler] Error export to text",$error$jscomp$4_template$$),$callback$$({error:$error$jscomp$4_template$$.message||$error$jscomp$4_template$$.error||$error$jscomp$4_template$$});
if($req$$.query.return_type=="url"){Logger.warn("[rptExcelHandler] t\u1ea1o tmp file export...");({template:$error$jscomp$4_template$$}=$req$$.body);try{let $fileName$$=await createTmpFile(`${$error$jscomp$4_template$$?.title||$ctrl$$.name}.${$ext$$}`,$result$$);const $downloadUrl$$=$req$$.host?.startsWith("http")?`${$req$$.host}/downloads/temp/${$fileName$$}`:`https://${$req$$.host}/downloads/temp/${$fileName$$}`;return $callback$$(null,{type:"json",data:{url:$downloadUrl$$}})}catch($e$$){return $callback$$($e$$)}}else if($ext$$===
"docx")$callback$$(null,{type:"docx",data:$result$$});else return $callback$$(null,{type:$ext$$,data:$result$$})})}})})})},$id_rpt$$=$req$$.query.id_rpt,$dir_root_templates$$=configs.paths.templates||__dirname,$templatePath$$,$rptConfig$$,$html_template$$,$title_template$$,$send_to$$;(new Promise(($resolve$$,$reject$$)=>{$rptConfig$$=$templatePath$$=void 0;if($id_rpt$$=="default"&&$req$$.body?.template&&$req$$.body?.template.columns)return $templatePath$$="auto",$resolve$$($templatePath$$);if($id_rpt$$&&
global.mongoose.Types.ObjectId.isValid($id_rpt$$))global.getModel("rpt").findOne({_id:$id_rpt$$}).lean().then(async function($r$$){if(!$r$$)return Logger.error("Not found excel template",$id_rpt$$),$reject$$("Kh\u00f4ng t\u00ecm th\u1ea5y m\u1eabu");$send_to$$=$req$$.query.send_to||$r$$.send_to;if($req$$.query.print||$send_to$$)$html_template$$=$r$$.html_template,$title_template$$=$r$$.ten_mau_in;else{if($r$$.file_mau_in.indexOf("/file/download")>0){let $id_file$$=$r$$.file_mau_in.split("/").pop();
const $file$$=global.getModel("file");try{const $_fileMauIn$$=await $file$$.findOne({_id:$id_file$$}).lean();if(!$_fileMauIn$$)return $reject$$("Kh\u00f4ng t\u00ecm th\u1ea5y m\u1eabu");let $file_name$$=$_fileMauIn$$.file.name,$root$$=configs.paths.uploads;$root$$||($root$$=__dirname,$root$$=path.dirname($root$$),$root$$=path.join($root$$,"uploads"));$templatePath$$=path.join($root$$,$file_name$$)}catch($e$$){return $reject$$($e$$.message||"Kh\u00f4ng t\u00ecm th\u1ea5y m\u1eabu")}}else $templatePath$$=
path.dirname($dir_root_templates$$)+$r$$.file_mau_in;fs.existsSync($templatePath$$)||(Logger.error("[rptExcelHandler] file template not found",$templatePath$$),$templatePath$$=`${path.dirname($dir_root_templates$$)}/templates/excels/reports/${$module$$}.xlsx`,Logger.info("[rptExcelHandler] using default template",$templatePath$$));fs.existsSync($templatePath$$)||($templatePath$$=`${path.dirname(__dirname)}/templates/excels/reports/${$module$$}.xlsx`,Logger.info("[rptExcelHandler] using default template",
$templatePath$$));if(!fs.existsSync($templatePath$$))return $reject$$("M\u1eabu kh\u00f4ng t\u1ed3n t\u1ea1i")}$rptConfig$$=$r$$;return $resolve$$($templatePath$$,$html_template$$)}).catch($error$$=>{Logger.error("Not found excel template",$error$$);return $reject$$($error$$)});else return $templatePath$$=`${path.dirname($dir_root_templates$$)}/templates/excels/reports/${$module$$}.xlsx`,fs.existsSync($templatePath$$)||($templatePath$$=`${path.dirname(__dirname)}/templates/excels/reports/${$module$$}.xlsx`),
fs.existsSync($templatePath$$)?$resolve$$($templatePath$$):$reject$$("M\u1eabu file xu\u1ea5t kh\u00f4ng h\u1ee3p l\u1ec7 ho\u1eb7c kh\u00f4ng t\u1ed3n t\u1ea1i")})).then(async()=>{$options$$.require_id_app===!1?$streamData$$({}):permission.hasRight($req$$.params.id_app,$req$$.user.email,$module$$,"view",function($error$$,$hr$$,$app$$){$hr$$?$streamData$$({...$app$$}):$callback$$({error:"B\u1ea1n kh\u00f4ng c\u00f3 quy\u1ec1n xu\u1ea5t excel b\u00e1o c\u00e1o n\u00e0y"})},{notNeedRight:$notNeedRight$$})}).catch($e$$=>
{Logger.error($e$$);return $e$$.error?$callback$$($e$$):$callback$$({error:$e$$.message||$e$$})})}catch($e$$){return $e$$.error?$callback$$($e$$):$callback$$({error:$e$$.message||$e$$})}};module.exports=rptExcelHandler;