UNPKG

flexbiz-server

Version:

Flexible Server

33 lines (31 loc) 10.9 kB
'use strict';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"),cache_time=5,rptExcelHandler=async($ctrl$$,$req$$,$callback$jscomp$0$$)=> {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$$])&&(0<=$req$$.query[$q$$].indexOf("[")||0<=$req$$.query[$q$$].indexOf("{")))try{$req$$.query[$q$$]=JSONParser($req$$.query[$q$$])}catch($e$$){console.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$$,$_new_query$$,$options$$.cache_time||cache_time);if($options$$.stream&&!$cacheData$$)return $callback$jscomp$0$$({error:"B\u1ea1n ph\u1ea3i ch\u1ea1y b\u00e1o c\u00e1o tr\u01b0\u1edbc khi xu\u1ea5t d\u1eef li\u1ec7u ra excel"}); if($cacheData$$)if($cacheData$$.data)$getData$$=function($req$$,$callback$$){$callback$$(null,$cacheData$$.data)};else{if($options$$.stream)return console.info("D\u1eef li\u1ec7u \u0111\u00e3 cache kh\u00f4ng ph\u00f9 h\u1ee3p v\u1edbi \u0111i\u1ec1u ki\u1ec7n l\u1ecdc m\u1edbi",$cacheData$$.query,$_new_query$$),$callback$jscomp$0$$({error:"B\u1ea1n ph\u1ea3i ch\u1ea1y b\u00e1o c\u00e1o tr\u01b0\u1edbc khi xu\u1ea5t d\u1eef li\u1ec7u ra excel"});$getData$$=$ctrl$$.getDataFunc()}else{if($options$$.stream)return console.info("D\u1eef li\u1ec7u \u0111\u00e3 cache h\u1ebft hi\u1ec7u l\u1ef1c."), $callback$jscomp$0$$({error:"B\u1ea1n ph\u1ea3i ch\u1ea1y b\u00e1o c\u00e1o tr\u01b0\u1edbc khi xu\u1ea5t d\u1eef li\u1ec7u ra excel"});$getData$$=$ctrl$$.getDataFunc()}let $streamData$$=function($app$$){$getData$$($req$$,async function($data_e$$,$data_report_v$$){if($data_e$$)return console.error("report getData",$data_e$$),$data_e$$.error?$callback$jscomp$0$$($data_e$$):$callback$jscomp$0$$({error:$data_e$$.message||$data_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$$);$data_e$$=$data_report_v$$;_.isArray($data_report_v$$)||($data_e$$=$data_report_v$$.data||$data_report_v$$.rows||[$data_report_v$$]);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$$.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$$};_.extend($app$$,$req$$.query);delete $app$$.access_token;for(var $func_string_key$$ in $app$$)$data_report_v$$= $app$$[$func_string_key$$],_.isDate($data_report_v$$)&&($app$$[$func_string_key$$+"_string"]=moment($data_report_v$$).format("DD/MM/YYYY"));$app$$.detail=$app$$.details=$data_e$$;$app$$.datasource={...$app$$};if($rptConfig$$&&$rptConfig$$.handle_data_expression){if(0<=$rptConfig$$.handle_data_expression.indexOf("async "))return $callback$jscomp$0$$({error:"async function is not allow"});$func_string_key$$=`return (async ()=>{ try{ ${$rptConfig$$.handle_data_expression} }catch(e){ return {error:e} } })`;try{if($func_string$$=await evalute($func_string_key$$,{data:$app$$,moment,user:$req$$.user,utils,numeral,getData:getParameterData})()){if($func_string$$.error)return $callback$jscomp$0$$($func_string$$.error);$app$$=$func_string$$}}catch($e$$){return console.error("via app: handle data before export",$e$$,$func_string_key$$),$e$$.error?$callback$jscomp$0$$($e$$):$callback$jscomp$0$$({error:$e$$.message||$e$$})}}var $func_string$$=await global.getModel("reportinfo").findOne({code:($req$$.query.report_info_code|| $rptId$$).toLowerCase()}).lean();if($func_string$$&&$func_string$$.handle_data_expression){if(0<=$func_string$$.handle_data_expression.indexOf("async "))return $callback$jscomp$0$$({error:"async function is not allow"});$func_string$$=`return (async ()=>{ try{ ${$func_string$$.handle_data_expression} }catch(e){ return {error:e} } })`;try{const $rs$$=await evalute($func_string$$,{data:$data_e$$,moment,user:$req$$.user,utils,numeral,getData:getParameterData})();if($rs$$){if($rs$$.error)return console.error("global: handle data before export",$rs$$.error,$func_string$$),$callback$jscomp$0$$({error:$rs$$.error.message||$rs$$.error});$app$$.detail=$app$$.details=$rs$$}}catch($e$$){return console.error("global: handle data before export",$e$$,$func_string$$),$callback$jscomp$0$$({error:$e$$.message||$e$$})}}else $app$$.detail.forEach($r$$=> {for(let $_key$$ in $r$$){let $_v$$=$r$$[$_key$$];if($_v$$&&(0<=$_key$$.indexOf("ngay")||0<=$_key$$.indexOf("date")))try{let $d$$=moment($_v$$);$d$$.isValid()&&($r$$[`${$_key$$}`]=$d$$.toDate(),$r$$[`${$_key$$}_string`]=$d$$.format("DD/MM/YYYY"))}catch($e$$){console.error("Error convert to date",$_v$$,$e$$)}}});$rptConfig$$&&$rptConfig$$.parameters&&await prepareParameters($rptConfig$$.parameters,$app$$,$app$$);if($req$$.query.json)$callback$jscomp$0$$(null,{type:"json",data:$app$$});else $options$$.onExport($app$$, function(){setImmediate(()=>{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$jscomp$0$$(null,{type:"html",data:$rs$$})},$error$$=>{$callback$jscomp$0$$({error:$error$$.message||$error$$.error||$error$$})});else{let $ext$$= $templatePath$$.split(".").pop();"xlsx"===$ext$$?excelReport($templatePath$$,$app$$,function($error$$,$result$$){if($error$$)return console.error("Error export to excel",$error$$),$callback$jscomp$0$$({error:$error$$.message||$error$$.error||$error$$});$callback$jscomp$0$$(null,{type:"xlsx",data:$result$$})},{timezone:configs.timezone||"Asia/Ho_Chi_Minh"}):textReport($templatePath$$,$app$$,function($error$$,$result$$){if($error$$)return console.error("Error export to text",$error$$),$callback$jscomp$0$$({error:$error$$.message|| $error$$.error||$error$$});if("docx"===$ext$$)$callback$jscomp$0$$(null,{type:"docx",data:$result$$});else return $callback$jscomp$0$$(null,{type:"json",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$$&&global.mongoose.Types.ObjectId.isValid($id_rpt$$))global.getModel("rpt").findOne({_id:$id_rpt$$}).lean().exec(async function($error$$, $r$$){if($error$$||!$r$$)return console.error("Not found excel template",$id_rpt$$,$error$$),$reject$$($error$$||"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(0<$r$$.file_mau_in.indexOf("/file/download")){$error$$=$r$$.file_mau_in.split("/").pop();const $file$$=global.getModel("file");try{const $_fileMauIn$$=await $file$$.findOne({_id:$error$$}).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$$)||(console.log("file template not found", $templatePath$$),$templatePath$$=`${path.dirname($dir_root_templates$$)}/templates/excels/reports/${$module$$}.xlsx`);fs.existsSync($templatePath$$)||($templatePath$$=`${path.dirname(__dirname)}/templates/excels/reports/${$module$$}.xlsx`);if(!fs.existsSync($templatePath$$))return $reject$$("M\u1eabu kh\u00f4ng t\u1ed3n t\u1ea1i")}$rptConfig$$=$r$$;return $resolve$$($templatePath$$,$html_template$$)});else if($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$$))return $reject$$("M\u1eabu excel kh\u00f4ng t\u1ed3n t\u1ea1i")})).then(async()=>{!1===$options$$.require_id_app?$streamData$$({}):permission.hasRight($req$$.params.id_app,$req$$.user.email,$module$$,"view",function($error$$,$hr$$,$app$$){$hr$$?$streamData$$({...$app$$}):$callback$jscomp$0$$({error:"B\u1ea1n kh\u00f4ng c\u00f3 quy\u1ec1n xu\u1ea5t excel b\u00e1o c\u00e1o n\u00e0y"})}, {notNeedRight:$notNeedRight$$})}).catch($e$$=>{console.error($e$$);return $e$$.error?$callback$jscomp$0$$($e$$):$callback$jscomp$0$$({error:$e$$.message||$e$$})})}catch($e$$){return $e$$.error?$callback$jscomp$0$$($e$$):$callback$jscomp$0$$({error:$e$$.message||$e$$})}};module.exports=rptExcelHandler;