flexbiz-server
Version:
Flexible Server
98 lines (97 loc) • 41.4 kB
JavaScript
const _=require("underscore"),path=require("path"),writtenNumber=require("written-number"),async=require("async"),numeral=require("numeral"),moment=require("moment"),crypto=require("crypto"),StaticPool=require("./WorkerStaticPool"),{executeInTransaction,runWithoutSession}=require("./sessionContext"),isDateValue=$d_val$$=>{if(!$d_val$$)return!1;if(Object.prototype.toString.call($d_val$$)==="[object Date]")return!isNaN($d_val$$.getTime());if(typeof $d_val$$!=="string"||$d_val$$.length<6||/^\d+$/.test($d_val$$))return!1;
$d_val$$=new Date($d_val$$);return $d_val$$ instanceof Date&&!isNaN($d_val$$.getTime())};exports.isDateValue=isDateValue;function isPlainObject($proto$jscomp$3_value$$){if(typeof $proto$jscomp$3_value$$!=="object"||$proto$jscomp$3_value$$===null||Array.isArray($proto$jscomp$3_value$$))return!1;$proto$jscomp$3_value$$=Object.getPrototypeOf($proto$jscomp$3_value$$);return $proto$jscomp$3_value$$===Object.prototype||$proto$jscomp$3_value$$===null}
function deleteEmptyObject($obj$$){if(typeof $obj$$!=="object"||$obj$$===null)return $obj$$;if(Array.isArray($obj$$))$obj$$.forEach($item$$=>deleteEmptyObject($item$$));else{var $currentValue_keys$$=Object.keys($obj$$);for(const $key$$ of $currentValue_keys$$)deleteEmptyObject($obj$$[$key$$]),$currentValue_keys$$=$obj$$[$key$$],typeof $currentValue_keys$$==="object"&&$currentValue_keys$$!==null&&(isPlainObject($currentValue_keys$$)&&Object.keys($currentValue_keys$$).length===0?delete $obj$$[$key$$]:
$key$$!="$in"&&$key$$.startsWith("$")&&Array.isArray($currentValue_keys$$)&&$currentValue_keys$$.length===0&&delete $obj$$[$key$$])}return $obj$$}exports.deleteEmptyObject=deleteEmptyObject;const {VM}=require("vm2");function evalute($code$$,$sandbox$$={},$timeout$$=2E3){$sandbox$$.Promise=function(){};return(new VM({timeout:$timeout$$,sandbox:$sandbox$$})).run(`(()=>{${$code$$}})()`)}exports.evalute=evalute;
function JSONParser($str_func$$){if(typeof $str_func$$=="object")return $str_func$$;$str_func$$=$str_func$$.toString().trim();if($str_func$$.startsWith("[")||$str_func$$.startsWith("{")||$str_func$$.toString().indexOf("return ")<0)$str_func$$="return "+$str_func$$;return evalute($str_func$$)}exports.JSONParser=JSONParser;
function numberToWord($fractionText_number$$,$options$$){if($fractionText_number$$===void 0||$fractionText_number$$===null)return"";if($options$$&&$options$$.lang&&$options$$.lang!=="vn"){var $kq_sign$$=writtenNumber($fractionText_number$$,{lang:$options$$.lang});return $kq_sign$$.length>0?$kq_sign$$.substring(0,1).toUpperCase()+$kq_sign$$.substring(1):""}$kq_sign$$="";$fractionText_number$$<0&&($kq_sign$$="\u00e2m ",$fractionText_number$$=-$fractionText_number$$);$options$$=_.extend({thousand:"ngh\u00ecn",
decimal:"ph\u1ea9y"},$options$$);$fractionText_number$$=Number($fractionText_number$$.toFixed(2));var $integerPart_integerText$$=Math.floor($fractionText_number$$),$fractionPart$$=$fractionText_number$$%1;$fractionText_number$$="";$fractionPart$$&&($fractionText_number$$=convertFractionPart($fractionPart$$),$fractionText_number$$=" "+$options$$.decimal+" "+$fractionText_number$$);var $digitGroups$$=breakDownNumber($integerPart_integerText$$).reverse();$integerPart_integerText$$=_.chain($digitGroups$$).map(function($convertedGroup_group$$,
$index$$){$convertedGroup_group$$=convertGroup($convertedGroup_group$$,$index$$===$digitGroups$$.length-1?!1:!0);var $unit$$=unitAt($index$$,$options$$.thousand);$convertedGroup_group$$||$index$$%3===0||($unit$$="");$convertedGroup_group$$&&$unit$$&&($unit$$=" "+$unit$$);return $convertedGroup_group$$+$unit$$}).compact().reverse().join(" ");$kq_sign$$=$kq_sign$$+$integerPart_integerText$$+$fractionText_number$$;return $kq_sign$$.length>0?$kq_sign$$.substring(0,1).toUpperCase()+$kq_sign$$.substring(1):
""}exports.numberToWord=numberToWord;function unitAt($index$$,$thousand$$){if($index$$===0)return"";switch($index$$%3){case 0:return"t\u1ec9";case 1:return $thousand$$;case 2:return"tri\u1ec7u"}}
function convertGroup($group$$,$preserveZeros$$){var $DIGITS$$="kh\u00f4ng m\u1ed9t hai ba b\u1ed1n n\u0103m s\u00e1u b\u1ea3y t\u00e1m ch\u00edn".split(" "),$DIGITS_WITH_TENS$$=" m\u1ed1t hai ba b\u1ed1n l\u0103m s\u00e1u b\u1ea3y t\u00e1m ch\u00edn".split(" "),$TENS$$="linh;m\u01b0\u1eddi;hai m\u01b0\u01a1i;ba m\u01b0\u01a1i;b\u1ed1n m\u01b0\u01a1i;n\u0103m m\u01b0\u01a1i;s\u00e1u m\u01b0\u01a1i;b\u1ea3y m\u01b0\u01a1i;t\u00e1m m\u01b0\u01a1i;ch\u00edn m\u01b0\u01a1i".split(";"),$HUNDREDS$$=_.map($DIGITS$$,
function($digit$$){return $digit$$+" tr\u0103m"}),$hundred$$="",$ten$$="",$digit$$="";if($preserveZeros$$&&!$group$$.hundred&&!$group$$.ten&&!$group$$.digit)return"";if($preserveZeros$$||$group$$.hundred)$hundred$$=$HUNDREDS$$[$group$$.hundred];if($preserveZeros$$||$group$$.ten||$group$$.hundred){if($group$$.ten||$group$$.digit)$ten$$=$TENS$$[$group$$.ten];$digit$$=$group$$.ten!==1&&$group$$.ten||!$group$$.digit?$DIGITS_WITH_TENS$$[$group$$.digit]:$DIGITS$$[$group$$.digit]}else $digit$$=$DIGITS$$[$group$$.digit];
$hundred$$&&$ten$$&&($hundred$$+=" ");$ten$$&&$digit$$&&($ten$$+=" ");return[$hundred$$,$ten$$,$digit$$].join("")}
function breakDownNumber($digits_number$$){$digits_number$$=$digits_number$$.toString().split("");$digits_number$$=_.map(_.range(0,(3-$digits_number$$.length%3)%3),function(){return 0}).concat($digits_number$$);return _.chain($digits_number$$).map(Number).groupBy(function($element$$,$index$$){return Math.floor($index$$/3)}).toArray().map(function($group$$){return _.object(["hundred","ten","digit"],$group$$)}).value()}
function convertFractionPart($fractionPart$$){$fractionPart$$=convertGroup(breakDownNumber($fractionPart$$*100)[0]);var $mapping$$={"m\u01b0\u1eddi":"m\u1ed9t","hai m\u01b0\u01a1i":"hai","ba m\u01b0\u01a1i":"ba","b\u1ed1n m\u01b0\u01a1i":"b\u1ed1n","n\u0103m m\u01b0\u01a1i":"n\u0103m","s\u00e1u m\u01b0\u01a1i":"s\u00e1u","b\u1ea3y m\u01b0\u01a1i":"b\u1ea3y","t\u00e1m m\u01b0\u01a1i":"t\u00e1m","ch\u00edn m\u01b0\u01a1i":"ch\u00edn","m\u1ed9t":"kh\u00f4ng m\u1ed9t",hai:"kh\u00f4ng hai",ba:"kh\u00f4ng ba",
"b\u1ed1n":"kh\u00f4ng b\u1ed1n","n\u0103m":"kh\u00f4ng n\u0103m","s\u00e1u":"kh\u00f4ng s\u00e1u","b\u1ea3y":"kh\u00f4ng b\u1ea3y","t\u00e1m":"kh\u00f4ng t\u00e1m","ch\u00edn":"kh\u00f4ng ch\u00edn"};$fractionPart$$ in $mapping$$&&($fractionPart$$=$mapping$$[$fractionPart$$]);return $fractionPart$$}function round($number$$,$precision$$){return isNaN($number$$)||$number$$===null?0:Number(Math.round($number$$+"e"+$precision$$)+"e-"+$precision$$)}exports.round=round;
function getInfoFromQuery($obj$$,$_query$$,$callback$$){setImmediate(()=>{let $query$$;try{$_query$$=$_query$$.trim();if(!$_query$$)return $callback$$();try{$_query$$.startsWith("{")||($_query$$="{"+$_query$$+"}");$_query$$.includes("return ")||($_query$$="return "+$_query$$);if($_query$$.indexOf("async ")>=0)return $callback$$("async function is not allow");$query$$=evalute($_query$$,{obj:$obj$$})}catch($e$$){Logger.info("error when parse json",$_query$$)}if(!$query$$)return $callback$$("Query is invalid: "+
$_query$$);if(!$query$$.collection||!$query$$.field)return $callback$$();$query$$.collection=="dmkh"&&($query$$.collection="customer");$query$$.collection=="dmtk"&&($query$$.collection="account");let $condition$$=$query$$.condition;if($condition$$){$condition$$=JSON.stringify($condition$$);for(var $fields_m$$ in $obj$$)$condition$$=$condition$$.replace(new RegExp("m."+$fields_m$$,"g"),$obj$$[$fields_m$$]);$condition$$=JSON.parse($condition$$)}else $condition$$={};let $col$$=global.getModel(""+$query$$.collection);
$fields_m$$={};$fields_m$$[$query$$.field]=1;$fields_m$$.mnemonic=-1;$fields_m$$.private_key=-1;$obj$$.id_app&&($condition$$.id_app=$obj$$.id_app);$col$$.findOne($condition$$,$fields_m$$).lean().then(function($rs$$){$rs$$?$callback$$(null,$rs$$[$query$$.field]):$callback$$()}).catch($e$$=>{$callback$$($e$$)})}catch($e$$){Logger.error($e$$),$callback$$("error execute query: "+$_query$$)}})}exports.getInfoFromQuery=getInfoFromQuery;
function strip_html_tags($str$$){if(!$str$$)return"";$str$$=$str$$.toString();return $str$$.replace(/<[^>]*>/g,"")}exports.strip_html_tags=strip_html_tags;exports.stripHtmlTags=strip_html_tags;function unescapeHtml($html_text$$){return unescape($html_text$$)}exports.unescapeHtml=unescapeHtml;const ngcompile=require("ng-node-compile");
function compileHtml($template$$,$data$$){try{var $ngEnviorment_str_func$$=$template$$;$ngEnviorment_str_func$$.indexOf("return ")!==0&&($ngEnviorment_str_func$$="return `"+$ngEnviorment_str_func$$+"`");$template$$=evalute($ngEnviorment_str_func$$,{...$data$$,moment,numeral,data:$data$$,master:$data$$,obj:$data$$})}catch($e$$){Logger.error("error compile template js",$template$$,$e$$.message||$e$$,$data$$)}if($template$$.indexOf("{{")>=0&&$template$$.indexOf("}}")>=0){$ngEnviorment_str_func$$=new ngcompile([]);
try{$template$$=$ngEnviorment_str_func$$.$compile("<span>"+$template$$+"</span>")($data$$)}catch($e$$){Logger.error("error compile template angularjs",$template$$,$e$$.message||$e$$,$data$$)}}return $template$$}exports.compileHtml=compileHtml;function isSupperAdmin($email$$){return global.configs?configs.supperAdmin===$email$$:!1}exports.isSupperAdmin=isSupperAdmin;
function calcGrid($report$$,$number_columns$$,$callback$$){setImmediate(()=>{var $_number_columns_onImportProcess$$=path.dirname(__dirname)+"/workers/calcGrid.js";global.calcGridPool||(global.calcGridPool=new StaticPool($_number_columns_onImportProcess$$));$_number_columns_onImportProcess$$=_.isObject($number_columns$$)?Object.keys($number_columns$$).join(","):$number_columns$$;global.calcGridPool.exec({report:$report$$,number_columns:$_number_columns_onImportProcess$$},$response$$=>{let $result$$=
$response$$.result||$response$$||[];_.isObject($number_columns$$)?async.map(Object.keys($number_columns$$),($column$$,$cb$$)=>{setImmediate(()=>{let $cbColumn$$=$number_columns$$[$column$$];$cbColumn$$?async.map($result$$.filter($r$$=>$r$$.cong_thuc),($r$$,$cb2$$)=>{$cbColumn$$(null,$r$$);$cb2$$()},()=>{$cb$$()}):$cb$$()})},()=>{$callback$$($result$$)}):$callback$$($result$$)})})}exports.calcGrid=calcGrid;
const advMapSeries=($arr$$,$action$$,$callback$$,$options$$={number_group:1,wait_for_next:0})=>{const $number_items_one_group$$=Math.max(1,round($arr$$.length/($options$$.number_group||1)));$arr$$=_.chunk($arr$$,$number_items_one_group$$);async.mapSeries($arr$$,($group$$,$callback$$)=>{async.mapSeries($group$$,($row$$,$cb$$)=>{$action$$($row$$,$cb$$)},($e$$,$rs$$)=>{$options$$.wait_for_next?setTimeout(()=>{Logger.info("run next group...");$callback$$($e$$,$rs$$)},$options$$.wait_for_next):(Logger.info("run next group..."),
$callback$$($e$$,$rs$$))})},($e$$,$rs$$)=>{if($e$$)return $callback$$($e$$);$e$$=$rs$$.reduce(($a$$,$b$$)=>$a$$.concat($b$$),[]);$callback$$(null,$e$$)})};exports.advMapSeries=advMapSeries;
const getParameterData=($id_app$$,$collection$$,$field$$,$condition$$)=>{if(global.secu_models.indexOf($collection$$.toLowerCase())>=0)throw`Collection ${$collection$$} is not allow`;$collection$$==="dmkh"&&($collection$$="customer");$collection$$==="dmtk"&&($collection$$="account");let $col$$=mongoose.models[$collection$$];if($col$$){if($col$$.schema.paths.id_app){if(!$id_app$$)throw`Collection ${$collection$$} required id_app`;$condition$$.id_app=$id_app$$}let $fields$$;$field$$&&($fields$$={[$field$$]:1});
if($collection$$==="user"||$collection$$==="participant")$fields$$={name:1};$collection$$==="app"&&($fields$$||={},$fields$$={...$fields$$,viettel_user:0,viettel_password:0,viettel_url_service:0,vnpt_user:0,vnpt_password:0,vnpt_url_service:0,easy_user:0,easy_password:0,easy_url_service:0,zalo_app_id:0,zalo_secret_key:0,zalo_code:0,zalo_oa_id:0,zalo_code_verifier:0,zalo_code_challenge:0,zalo_access_token:0,zalo_refresh_token:0,google_credentials:0,sip_uri:0,sip_password:0,sip_websocket:0,voiip_access_token:0,
voiip_webhook:0,wallet_address:0,wallet_token:0,owner:0,default_password:0,email_host:0,email_port:0,email_secure:0,email_authMethod:0,email_user:0,email_pass:0,email_name:0,exfields:0,ssl_key:0,ssl_cert:0,ssl_ca:0});return $col$$.findOne($condition$$,$fields$$).lean()}throw`Error get param data: Collection ${$collection$$} is not exists`;};exports.getParameterData=getParameterData;
const prepareParameters=async function($parameters$$,$app$$,$obj$$){return new Promise(($resole$$,$reject$$)=>{async.mapLimit($parameters$$,50,function($p$$,$callback$$){setImmediate(()=>{(async()=>{if($p$$.type==="W"||$p$$.type==="EN")try{$app$$[$p$$.name]=$p$$.type==="EN"?numberToWord($obj$$[$p$$.value],{lang:"en"}):numberToWord($obj$$[$p$$.value])}catch($e$$){Logger.error($e$$),$app$$[$p$$.name]=$e$$.message}else if($p$$.type==="Q")try{var $query$jscomp$2_sandbox$$=await evalute("return {"+$p$$.value+
"}",{});if($query$jscomp$2_sandbox$$.collection&&$query$jscomp$2_sandbox$$.field){$query$jscomp$2_sandbox$$.collection=="dmkh"&&($query$jscomp$2_sandbox$$.collection="customer");$query$jscomp$2_sandbox$$.collection=="dmtk"&&($query$jscomp$2_sandbox$$.collection="account");var $condition$$=$query$jscomp$2_sandbox$$.condition;if($condition$$){$condition$$=JSON.stringify($condition$$);for(let $m$$ in $obj$$)$condition$$=$condition$$.replace(new RegExp("m."+$m$$,"g"),$obj$$[$m$$]);$condition$$=JSON.parse($condition$$)}else $condition$$=
{};$app$$[$p$$.name]=await getParameterData($app$$.id_app,$query$jscomp$2_sandbox$$.collection,$query$jscomp$2_sandbox$$.field,$condition$$)}}catch($e$$){$app$$[$p$$.name]=$e$$}else if($p$$.type==="E"&&$p$$.value){$condition$$=$p$$.value;$condition$$.indexOf("return ")<0&&($condition$$=`return ${$condition$$}`);if($condition$$.indexOf("async ")>=0)return $app$$[$p$$.name]="async function is not allow";$condition$$=`return (async ()=>{
${$condition$$}
})`;$query$jscomp$2_sandbox$$={m:$obj$$,master:$obj$$,data:$obj$$,Moment:moment,Numeral:numeral,numberToWord,getData:getParameterData};try{$app$$[$p$$.name]=await evalute($condition$$,$query$jscomp$2_sandbox$$)()}catch($e$$){Logger.error($e$$,$condition$$),$app$$[$p$$.name]=$e$$.message}}else $app$$[$p$$.name]=$p$$.value})().then(()=>{$callback$$()}).catch(()=>{$callback$$()})})},function($e$$){if($e$$)return $reject$$($e$$);$resole$$()})})};exports.prepareParameters=prepareParameters;
const groupBy=($arr$$,$fieldkey$$,$fieldsums$$,$options$$)=>[...$arr$$].asyncGroupBy($fieldkey$$,$fieldsums$$,$options$$);exports.groupBy=groupBy;const joinModel2=($arr$$,$id_app$$,$modelName$$,$where$$,$fields$$)=>{$where$$.fields&&$where$$.where&&($where$$=$where$$.where,$fields$$=$where$$.fields);return[...$arr$$].asyncJoinModel2($id_app$$,$modelName$$,{where:$where$$,fields:$fields$$})};exports.joinModel2=joinModel2;
const count=async($model_name$$,$condition$$)=>{if(global.secu_models.indexOf($model_name$$.toLowerCase())>=0)throw`Kh\u00f4ng \u0111\u01b0\u1ee3c ph\u00e9p query model '${$model_name$$}'`;if(!$condition$$)throw"condition missed";if(!$condition$$.id_app)throw"condition missed id_app param";return await global.getModel($model_name$$).countDocuments($condition$$)};exports.count=count;
const query=async($model_name$$,$condition$$,$options$jscomp$5_rs$$={})=>{if(global.secu_models.indexOf($model_name$$.toLowerCase())>=0)throw`Kh\u00f4ng \u0111\u01b0\u1ee3c ph\u00e9p query model '${$model_name$$}'`;if(!$condition$$)throw"condition missed";if($options$jscomp$5_rs$$.action&&$options$jscomp$5_rs$$.action!="find"){if(global.getModel($model_name$$)[$options$jscomp$5_rs$$.action]&&["getCoinBalance","getInvestBalance","getOwners"].indexOf($options$jscomp$5_rs$$.action)>=0)return global.getModel($model_name$$)[$options$jscomp$5_rs$$.action]($condition$$,
$options$jscomp$5_rs$$);throw`${$options$jscomp$5_rs$$.action} is not valid`;}if(!$condition$$.id_app)throw"condition missed id_app param";let $fields$$=$options$jscomp$5_rs$$.fields;$model_name$$=global.getModel($model_name$$).find($condition$$,$fields$$);$options$jscomp$5_rs$$.sort&&($model_name$$=$model_name$$.sort($options$jscomp$5_rs$$.sort));$options$jscomp$5_rs$$.limit&&($model_name$$=$model_name$$.limit($options$jscomp$5_rs$$.limit));$options$jscomp$5_rs$$=await $model_name$$.lean();$options$jscomp$5_rs$$.forEach($r$$=>
{delete $r$$.mnemonic;delete $r$$.private_key;delete $r$$.password;delete $r$$.token;$r$$.local&&(delete $r$$.local.password,delete $r$$.local.repassword,delete $r$$.local.pin)});return $options$jscomp$5_rs$$};exports.query=query;exports.find=query;const getLib=$lib_name$$=>global.getLib($lib_name$$);exports.getLib=getLib;
const getCodeChildren=async($model$$,$id_app$$,$code$jscomp$2_rs$$,$field_code$$,$field_mother$$,$chil_condition$$={})=>{let $nh_khs$$;$nh_khs$$=_.isArray($code$jscomp$2_rs$$)?[...$code$jscomp$2_rs$$]:[$code$jscomp$2_rs$$];$code$jscomp$2_rs$$=[...$nh_khs$$];$chil_condition$$=(await $model$$.find({id_app:$id_app$$,[$field_mother$$]:{$in:$nh_khs$$},...$chil_condition$$},{_id:1,[$field_code$$]:1,[$field_mother$$]:1}).lean()).filter($n$$=>$n$$[$field_code$$]!=$n$$[$field_mother$$]).map($d$$=>$d$$[$field_code$$]);
$chil_condition$$.length>0&&($chil_condition$$=await Promise.all($chil_condition$$.map($nh$$=>getCodeChildren($model$$,$id_app$$,$nh$$,$field_code$$,$field_mother$$))),$chil_condition$$=$chil_condition$$.reduce(($a$$,$b$$)=>$a$$.concat($b$$),[]),$code$jscomp$2_rs$$=[...$chil_condition$$,...$code$jscomp$2_rs$$]);return $code$jscomp$2_rs$$};exports.getCodeChildren=getCodeChildren;
const aggregate=async($model_name$jscomp$2_rs$$,$id_app$$,$stages$$=[])=>{if(global.secu_models.indexOf($model_name$jscomp$2_rs$$)>=0)throw"Not allow";$stages$$.forEach($stage$$=>{for(let $key$$ in $stage$$)$stage$$[$key$$].pipeline&&($stage$$[$key$$].pipeline=[{$match:{id_app:$id_app$$}},...$stage$$[$key$$].pipeline])});$stages$$=[{$match:{id_app:$id_app$$}},...$stages$$];$model_name$jscomp$2_rs$$=await global.getModel($model_name$jscomp$2_rs$$).aggregate($stages$$).lean();$model_name$jscomp$2_rs$$.forEach($r$$=>
{delete $r$$.mnemonic;delete $r$$.private_key;delete $r$$.password;delete $r$$.token;$r$$.local&&(delete $r$$.local.password,delete $r$$.local.repassword,delete $r$$.local.pin)});return $model_name$jscomp$2_rs$$};exports.aggregate=aggregate;const axios=require("axios"),querystring=require("querystring"),xml2js=require("xml2js"),xml2json=$string$$=>new Promise(($res$$,$rej$$)=>{xml2js.parseString($string$$,($e$$,$rs$$)=>{if($e$$)return $rej$$($e$$);$res$$($rs$$)})});exports.xml2json=xml2json;
const base64toJSON=$b$$=>{$b$$=Buffer.from($b$$,"base64");return xml2json($b$$.toString("utf8"))};exports.base64toJSON=base64toJSON;const isMobilePhone=($cleanStr_str$$,$locale$$)=>{if(!$cleanStr_str$$||!$cleanStr_str$$.toString().trim())return!1;$cleanStr_str$$=$cleanStr_str$$.toString().replace(/[.\s()-]+/g,"");return/^(\+84|0)(2\d{9}|[35789]\d{8})$/.test($cleanStr_str$$)};exports.isMobilePhone=isMobilePhone;
const generatePasswordHash=function($password$$){return crypto.createHash("sha256").update($password$$+":STP").digest("hex")};exports.generatePasswordHash=generatePasswordHash;
async function isBookLocked($ngay_ct_obj$$){if(!$ngay_ct_obj$$.ngay_ct||!$ngay_ct_obj$$.id_app&&!$ngay_ct_obj$$.ngay_ks)return!1;var $_app_ngay_ks$$=$ngay_ct_obj$$.ngay_ks;if(!$_app_ngay_ks$$){$_app_ngay_ks$$=await global.getModel("app").findOne({_id:$ngay_ct_obj$$.id_app});if(!$_app_ngay_ks$$)return!1;$_app_ngay_ks$$=moment($_app_ngay_ks$$.ngay_ks).endOf("date").toDate()}$ngay_ct_obj$$=moment($ngay_ct_obj$$.ngay_ct).startOf("date").toDate();return $_app_ngay_ks$$.getTime()>$ngay_ct_obj$$.getTime()?
$_app_ngay_ks$$:!1}exports.isBookLocked=isBookLocked;
const isImpossibleQuery=$condition$$=>$condition$$?Object.keys($condition$$).some($key$jscomp$12_val$$=>($key$jscomp$12_val$$=$condition$$[$key$jscomp$12_val$$])&&$key$jscomp$12_val$$.$in&&Array.isArray($key$jscomp$12_val$$.$in)&&$key$jscomp$12_val$$.$in.length===0||Array.isArray($key$jscomp$12_val$$)&&$key$jscomp$12_val$$.length===0?!0:!1):!1,sumByCondition=async($Model$$,$fields$$,$condition$$={})=>{try{if(isImpossibleQuery($condition$$)){const $zeroResult$$={};(Array.isArray($fields$$)?$fields$$:
[$fields$$]).forEach($f$$=>$zeroResult$$[$f$$]=0);return $zeroResult$$}const $fieldsArray$$=Array.isArray($fields$$)?$fields$$:[$fields$$];if($fieldsArray$$.length===0)return{};const $groupStage$$={_id:null},$projectStage$$={_id:0};$fieldsArray$$.forEach($field$$=>{$groupStage$$[$field$$]={$sum:`$${$field$$}`};$projectStage$$[$field$$]=1});const $result$$=await $Model$$.aggregate([{$match:$condition$$},{$group:$groupStage$$},{$project:$projectStage$$}]);if(!$result$$||$result$$.length===0){const $zeroResult$$=
{};$fieldsArray$$.forEach($f$$=>$zeroResult$$[$f$$]=0);return $zeroResult$$}return $result$$[0]}catch($error$$){throw console.error("[sumByCondition] Error:",$error$$),$error$$;}};exports.sumByCondition=sumByCondition;
const groupByCondition=async($Model$$,$condition$$={},$groupByFields$$,$calculations$$={})=>{try{if(isImpossibleQuery($condition$$))return[];const $groups$$=Array.isArray($groupByFields$$)?$groupByFields$$:[$groupByFields$$],$groupId$$={};$groups$$.forEach($field$$=>{$groupId$$[$field$$]=`$${$field$$}`});const $groupStage$$={_id:$groupId$$},$ops$$={sum:"$sum",min:"$min",max:"$max",avg:"$avg"};Object.keys($calculations$$).forEach($fields$$=>{const $operator$$=$ops$$[$fields$$];$operator$$&&($fields$$=
$calculations$$[$fields$$],Array.isArray($fields$$)&&$fields$$.forEach($field$$=>{$groupStage$$[$field$$]={[$operator$$]:`$${$field$$}`}}))});const $projectStage$$={_id:0};$groups$$.forEach($field$$=>{$projectStage$$[$field$$]=`$_id.${$field$$}`});Object.keys($groupStage$$).forEach($key$$=>{$key$$!=="_id"&&($projectStage$$[$key$$]=1)});const $pipeline$$=[{$match:$condition$$},{$group:$groupStage$$},{$project:$projectStage$$},{$sort:$groups$$.reduce(($acc$$,$curr$$)=>({...$acc$$,[$curr$$]:1}),{})}];
return await $Model$$.aggregate($pipeline$$)}catch($error$$){throw console.error("[groupByCondition] Error:",$error$$),$error$$;}};exports.groupByCondition=groupByCondition;
async function getLocationByAddress($address$$,$address2$$){try{let $url$$=`https://api.geoapify.com/v1/geocode/search?text=${encodeURIComponent($address$$)}&apiKey=69ba27248ee845ecae90e5acac5b1de0`,$data$$=(await axios.get($url$$)).data.features||[];if($data$$.length>0){let $lc$$=$data$$[0].properties||{};return{latitude:$lc$$.lat,longitude:$lc$$.lon}}if($address2$$){let $url$$=`https://api.geoapify.com/v1/geocode/search?text=${encodeURIComponent($address2$$)}&apiKey=69ba27248ee845ecae90e5acac5b1de0`,
$data$$=(await axios.get($url$$)).data.features||[];if($data$$.length>0){let $lc$$=$data$$[0].properties||{};return{latitude:$lc$$.lat,longitude:$lc$$.lon}}Logger.info("Kh\u00f4ng th\u1ec3 t\u00ecm th\u1ea5y v\u1ecb tr\u00ed c\u1ee7a \u0111\u1ecba ch\u1ec9 2:",{address2:$address2$$,url:$url$$})}else Logger.info("Kh\u00f4ng th\u1ec3 t\u00ecm th\u1ea5y v\u1ecb tr\u00ed c\u1ee7a \u0111\u1ecba ch\u1ec9:",{address:$address$$,url:$url$$})}catch($e$$){Logger.error("Kh\u00f4ng th\u1ec3 x\u00e1c \u0111\u1ecbnh v\u00ed tr\u00ed c\u1ee7a \u0111\u1ecba ch\u1ec9:",
$address$$,"L\u1ed7i: ",($e$$.response||{}).data||$e$$)}return null}exports.getLocationByAddress=getLocationByAddress;const {createSokhoTC,createSocaiTC}=require("./optimizeBookkeeping");exports.createSokhoTC=createSokhoTC;exports.createSocaiTC=createSocaiTC;
async function analyzeData($datas_mydata$$,$question$$="Vui l\u00f2ng ph\u00e2n t\u00edch c\u00e1c ch\u1ec9 ti\u00eau t\u00e0i ch\u00ednh ch\u00ednh y\u1ebfu.",$conversationHistory$$,$system_type$$="B\u1ea1n l\u00e0 m\u1ed9t chuy\u00ean gia t\u00e0i ch\u00ednh, h\u1ed7 tr\u1ee3 ph\u00e2n t\u00edch d\u1eef li\u1ec7u t\u00e0i ch\u00ednh d\u1ef1a tr\u00ean b\u1ea3ng c\u00e2n \u0111\u1ed1i ph\u00e1t sinh c\u00e1c t\u00e0i kho\u1ea3n. H\u00e3y t\u00ednh to\u00e1n m\u1ecdi c\u00f4ng th\u1ee9c (n\u1ebfu c\u00f3) trong c\u00e2u tr\u1ea3 l\u1eddi."){if(!configs.openapi_key)throw"H\u1ec7 th\u1ed1ng ch\u01b0a h\u1ed7 tr\u1ee3";if(!$datas_mydata$$)throw"Kh\u00f4ng c\u00f3 d\u1eef li\u1ec7u \u0111\u1ec3 ph\u00e2n t\u00edch";
Logger.info("B\u1eaft \u0111\u1ea7u ph\u00e2n t\u00edch y\u00eau c\u1ea7u");var $client_reply$$=new (require("openai"))({apiKey:configs.openapi_key,dangerouslyAllowBrowser:!0});_.isArray($datas_mydata$$)||($datas_mydata$$=[$datas_mydata$$]);$datas_mydata$$=$datas_mydata$$.map($d$$=>$d$$.title&&$d$$.data?$d$$:{title:"D\u1eef li\u1ec7u c\u1ea7n ph\u00e2n t\u00edch",data:$d$$});$conversationHistory$$&&$conversationHistory$$.length!=0||($conversationHistory$$=[{role:"system",content:$system_type$$}]);
$datas_mydata$$=$datas_mydata$$.filter($d$$=>$d$$.data).map($d$$=>({role:"user",content:`${$d$$.title}:\n${JSON.stringify($d$$.data,null,2)}.`}));if($datas_mydata$$.length)$datas_mydata$$.forEach($r$$=>{$conversationHistory$$.push($r$$)});else throw"Kh\u00f4ng c\u00f3 d\u1eef li\u1ec7u \u0111\u1ec3 ph\u00e2n t\u00edch";$conversationHistory$$.push({role:"user",content:$question$$});$client_reply$$=(await $client_reply$$.chat.completions.create({model:"gpt-4o",messages:$conversationHistory$$})).choices[0].message.content.trim();
$conversationHistory$$.push({role:"assistant",content:$client_reply$$});return{question:$question$$,reply:$client_reply$$,conversationHistory:$conversationHistory$$}}exports.analyzeData=analyzeData;
async function sendMessageZalo($app$jscomp$1_id_app$$,$message$jscomp$10_message$$,$zalo_otp_template_id$$,$template_data$$={},$tracking_id$$,$headers_secret_key$$){if(!$app$jscomp$1_id_app$$)throw"Thi\u1ebfu th\u00f4ng tin id_app";if(global.mongoose.Types.ObjectId.isValid($app$jscomp$1_id_app$$))if(($app$jscomp$1_id_app$$=await global.getModel("app").findOne({_id:$app$jscomp$1_id_app$$}))&&$app$jscomp$1_id_app$$.zalo_app_id&&$app$jscomp$1_id_app$$.zalo_secret_key&&$app$jscomp$1_id_app$$.zalo_access_token&&
$app$jscomp$1_id_app$$.zalo_refresh_token){if($headers_secret_key$$&&$headers_secret_key$$!=$app$jscomp$1_id_app$$.zalo_secret_key)throw"C\u1ea5u h\u00ecnh OA kh\u00f4ng h\u1ee3p l\u1ec7";const {zalo_app_id:$zalo_app_id$$,zalo_secret_key:$zalo_secret_key$$,zalo_refresh_token:$zalo_refresh_token$$,zalo_expires_in:$zalo_expires_in$$,zalo_updated:$zalo_updated$$}=$app$jscomp$1_id_app$$;if(moment().diff(moment($zalo_updated$$),"seconds")>$zalo_expires_in$$+1){$headers_secret_key$$={"Content-Type":"application/x-www-form-urlencoded",
secret_key:$zalo_secret_key$$};let $data$$={refresh_token:$zalo_refresh_token$$,app_id:$zalo_app_id$$,grant_type:"refresh_token"};try{let $rs$$=await axios.post("https://oauth.zaloapp.com/v4/oa/access_token",querystring.stringify($data$$),{headers:$headers_secret_key$$});if($rs$$.data.error)throw $rs$$.data;let $zalo_token$$=$rs$$.data;$app$jscomp$1_id_app$$.zalo_access_token=$zalo_token$$.access_token;$app$jscomp$1_id_app$$.zalo_refresh_token=$zalo_token$$.refresh_token;$app$jscomp$1_id_app$$.zalo_expires_in=
$zalo_token$$.expires_in;$app$jscomp$1_id_app$$.zalo_updated=new Date;await $app$jscomp$1_id_app$$.save()}catch($e$$){throw $message$jscomp$10_message$$=(($e$$.response||{}).data||{}).message,Logger.error("Can't get access token from zalo",$message$jscomp$10_message$$||$e$$),$message$jscomp$10_message$$||$e$$.message||$e$$;}}try{const $headers$$={"Content-Type":"application/json",access_token:$app$jscomp$1_id_app$$.zalo_access_token};$message$jscomp$10_message$$="84"+$message$jscomp$10_message$$.toString().substring(1);
let $rs$$=await axios({method:"post",url:"https://business.openapi.zalo.me/message/template",data:{phone:$message$jscomp$10_message$$,template_id:$zalo_otp_template_id$$,template_data:$template_data$$,tracking_id:$tracking_id$$},headers:$headers$$});if($rs$$.data.error)throw $rs$$.data.error;return $rs$$.data}catch($e$$){throw $message$jscomp$10_message$$=(($e$$.response||{}).data||{}).message,Logger.error("Can't send message from zalo",$message$jscomp$10_message$$||$e$$),$message$jscomp$10_message$$||
$e$$.message||$e$$;}}else throw"Kh\u00f4ng t\u1ed3n t\u1ea1i c\u1ea5u h\u00ecnh \u0111\u1ec3 g\u1eedi Zalo OTP";else throw"ID APP kh\u00f4ng h\u1ee3p l\u1ec7: "+$app$jscomp$1_id_app$$;}exports.sendMessageZalo=sendMessageZalo;
function isValidObjectIdValue($v$$){var {Types:$ObjectId_Types$$}=global.mongoose;$ObjectId_Types$$=$ObjectId_Types$$.ObjectId;return $v$$==null?!1:$v$$ instanceof $ObjectId_Types$$?!0:typeof $v$$==="string"?$ObjectId_Types$$.isValid($v$$):Array.isArray($v$$)?$v$$.length>0&&$v$$.every(isValidObjectIdValue):typeof $v$$==="object"?Object.values($v$$).every(isValidObjectIdValue):!1}exports.isValidObjectIdValue=isValidObjectIdValue;
function isObjectId($v$$){if($v$$==null)return!1;const $proto$$=Object.getPrototypeOf($v$$);return $proto$$==null||$proto$$.constructor==null||$proto$$.constructor.name!=="ObjectID"?!1:$v$$._bsontype==="ObjectID"}exports.isObjectId=isObjectId;
function replaceId($res$$){if(Array.isArray($res$$))$res$$.forEach($v$$=>{isObjectId($v$$)||($v$$&&$v$$._id&&($v$$._id=$v$$._id.toString()),$v$$&&Object.keys($v$$).map($k$$=>{Array.isArray($v$$[$k$$])&&replaceId($v$$[$k$$])}))});else{if(isObjectId($res$$))return $res$$;$res$$._id&&($res$$._id=$res$$._id.toString());Object.keys($res$$).map($k$$=>{Array.isArray($res$$[$k$$])&&replaceId($res$$[$k$$])})}}exports.replaceId=replaceId;
function convertObjectIdsToStrings($obj$$){replaceId($obj$$);return $obj$$}exports.convertObjectIdsToStrings=convertObjectIdsToStrings;
const updateInvoice=async($contr$$,$ct$$)=>{let $result_export_einvoice$$=$ct$$.result_export_einvoice;if(Array.isArray($result_export_einvoice$$))for(let $invoice$$ of $result_export_einvoice$$){let $transactionUuid$$=$invoice$$.transactionUuid;if($transactionUuid$$==$ct$$._id)$ct$$.so_hd=$invoice$$.result?.invoiceNo||"";else{let $vat$$=$ct$$.vatras?.find($v$$=>$v$$._id.toString()==$transactionUuid$$);$vat$$&&($vat$$.so_hd=$invoice$$.result?.invoiceNo||"")}}else $ct$$.so_hd=$result_export_einvoice$$?.result?.invoiceNo||
"";await runWithoutSession(async()=>{await executeInTransaction(async()=>{await $contr$$.model.updateOne({_id:$ct$$._id},$ct$$);$ct$$.so_hd&&await global.getModel("tdttno").updateMany({id_ct:$ct$$._id.toString(),id_app:$ct$$.id_app},{so_hd:$ct$$.so_hd});$ct$$.so_hd&&await global.getModel("tdttno_tt").updateMany({id_hd:$ct$$._id.toString(),id_app:$ct$$.id_app},{so_hd:$ct$$.so_hd});await $contr$$.asyncPostData($ct$$,{kiem_tra_han_muc_cong_no:!1});Logger.info("da cap nhat hoa don",$ct$$.result_export_einvoice)})});
return $result_export_einvoice$$};exports.updateInvoice=updateInvoice;
const viettelInvoice=require("./invoiceViettel"),easyInvoice=require("./invoiceEasy"),vnptInvoice=require("./invoiceVnpt"),exportInvoice=async($app$$,$voucher$$,$check_data$$=!1)=>{if(!$app$$)throw"Thi\u1ebfu th\u00f4ng tin c\u00f4ng ty";const $ctrl$$=global.controllers[$voucher$$?.ma_ct?.toUpperCase()];if(!$ctrl$$)throw"Kh\u00f4ng th\u1ec3 xu\u1ea5t thu\u1ebf cho ch\u1ee9ng t\u1eeb "+$voucher$$?.ma_ct;if(!$app$$)throw"Kh\u00f4ng t\u00ecm th\u1ea5y c\u00f4ng ty n\u00e0y";if(!$app$$.ma_so_thue)throw"B\u1ea1n ch\u01b0a nh\u1eadp m\u00e3 s\u1ed1 thu\u1ebf c\u1ee7a c\u00f4ng ty";
let $fnInvoice$$;switch($app$$.invoice_service){case "VIETTEL":$fnInvoice$$=viettelInvoice.exportInvoice;break;case "EASY":$fnInvoice$$=easyInvoice.exportInvoice;break;case "VNPT":$fnInvoice$$=vnptInvoice.exportInvoice}if(!$fnInvoice$$)throw"Ch\u01b0a khai b\u00e1o d\u1ecbch v\u1ee5 ho\u00e1 \u0111\u01a1n \u0111i\u1ec7n t\u1eeb ho\u1eb7c ch\u01b0a c\u00f3 gi\u00e1 tr\u1ecb";$voucher$$.toObject&&($voucher$$=$voucher$$.toObject());var $cts_transactionUuid$$=[$voucher$$];if($voucher$$.vatras?.length)for(var $result_export_einvoices_vatra$$ of $voucher$$.vatras.filter($v$$=>
$v$$.ma_thue)){$result_export_einvoices_vatra$$.toObject&&($result_export_einvoices_vatra$$=$result_export_einvoices_vatra$$.toObject());var $ct$jscomp$1_r$jscomp$5_result_export_einvoice$$={...$voucher$$,...$result_export_einvoices_vatra$$,details:$result_export_einvoices_vatra$$.details,ma_kh:$result_export_einvoices_vatra$$.ma_kh||$voucher$$.ma_kh,ten_kh:$result_export_einvoices_vatra$$.ten_kh||$voucher$$.ten_kh};let $sl_xuat$$=$result_export_einvoices_vatra$$.sl_xuat||1;$ct$jscomp$1_r$jscomp$5_result_export_einvoice$$.details&&
$ct$jscomp$1_r$jscomp$5_result_export_einvoice$$.details.length!=0||($ct$jscomp$1_r$jscomp$5_result_export_einvoice$$.details=[{...$result_export_einvoices_vatra$$,ten_vt_vat:$result_export_einvoices_vatra$$.ten_vt,ma_dvt:$result_export_einvoices_vatra$$.ma_dvt||"L\u1ea7n",sl_xuat:$sl_xuat$$,gia_ban_ct_nt:Math.round($result_export_einvoices_vatra$$.t_tien_nt/$sl_xuat$$),tien_ct_nt:$result_export_einvoices_vatra$$.t_tien_nt,tien_ck_nt:0,tien_thue_nt:$result_export_einvoices_vatra$$.t_thue_nt}]);$cts_transactionUuid$$.push($ct$jscomp$1_r$jscomp$5_result_export_einvoice$$)}$result_export_einvoices_vatra$$=
[];$cts_transactionUuid$$=$cts_transactionUuid$$.filter($d$$=>$d$$.details&&$d$$.details.length>0&&$d$$.export_yn!=0);for(let $ct$$ of $cts_transactionUuid$$){$ct$$.details=$ct$$.details.map($d$$=>$d$$.toObject?$d$$.toObject():$d$$);$cts_transactionUuid$$=$ct$$._id.toString();if(!$check_data$$&&($ct$jscomp$1_r$jscomp$5_result_export_einvoice$$=await getInvoice($app$$,$cts_transactionUuid$$))){$result_export_einvoices_vatra$$.push($ct$jscomp$1_r$jscomp$5_result_export_einvoice$$);continue}$ct$jscomp$1_r$jscomp$5_result_export_einvoice$$=
await $fnInvoice$$($app$$,$ct$$,$check_data$$);$ct$jscomp$1_r$jscomp$5_result_export_einvoice$$.transactionUuid=$cts_transactionUuid$$;$result_export_einvoices_vatra$$.push($ct$jscomp$1_r$jscomp$5_result_export_einvoice$$)}$check_data$$||(Logger.info("[utils] [exportInvoice] C\u1eadp nh\u1eadt ho\u00e1 \u0111\u01a1n...",$result_export_einvoices_vatra$$.length),$voucher$$.result_export_einvoice=$result_export_einvoices_vatra$$,await updateInvoice($ctrl$$,$voucher$$));return $result_export_einvoices_vatra$$};
exports.exportInvoice=exportInvoice;
const getInvoice=async($app$jscomp$3_invoice$$,$transactionUuid$$)=>{if(!$app$jscomp$3_invoice$$)throw"Thi\u1ebfu th\u00f4ng tin c\u00f4ng ty";if($app$jscomp$3_invoice$$.invoice_service==="VIETTEL")$app$jscomp$3_invoice$$=await viettelInvoice.getInvoice($app$jscomp$3_invoice$$,$transactionUuid$$);else if($app$jscomp$3_invoice$$.invoice_service==="EASY")$app$jscomp$3_invoice$$=await easyInvoice.getInvoice($app$jscomp$3_invoice$$,$transactionUuid$$);else if($app$jscomp$3_invoice$$.invoice_service==="VNPT")$app$jscomp$3_invoice$$=
await vnptInvoice.getInvoice($app$jscomp$3_invoice$$,$transactionUuid$$);else throw"Ch\u01b0a khai b\u00e1o d\u1ecbch v\u1ee5 ho\u00e1 \u0111\u01a1n b\u00ean th\u1ee9 3";$app$jscomp$3_invoice$$&&($app$jscomp$3_invoice$$.transactionUuid=$transactionUuid$$);return $app$jscomp$3_invoice$$};exports.getInvoice=getInvoice;
const getInvoices=async($app$$,$condition$$={})=>{if(!$app$$)throw"Thi\u1ebfu th\u00f4ng tin c\u00f4ng ty";if($app$$.invoice_service==="VNPT")return vnptInvoice.getInvoices($app$$,$condition$$);throw"Ch\u01b0a khai b\u00e1o d\u1ecbch v\u1ee5 ho\u00e1 \u0111\u01a1n b\u00ean th\u1ee9 3 ho\u1eb7c ch\u01b0\u01a1ng tr\u00ecnh ch\u01b0a h\u1ed7 tr\u1ee3 cho b\u00ean n\u00e0y";};exports.getInvoices=getInvoices;
function sanitizeHtm($html_restoredHtml$$){if(typeof $html_restoredHtml$$!=="string")return{safe:!1,cleaned:"",reason:"Input kh\u00f4ng ph\u1ea3i l\u00e0 chu\u1ed7i"};const $placeholders$$=[];var $isSafe_tempHtml$$=$html_restoredHtml$$.replace(/(\$\{[^}]+\}|\{\{[^}]+\}\})/g,$match$$=>{const $token$$=`__PLACEHOLDER_${$placeholders$$.length}__`;$placeholders$$.push($match$$);return $token$$});const $sanitizedAfterTokens$$=$isSafe_tempHtml$$;$isSafe_tempHtml$$=$isSafe_tempHtml$$.replace(RegExp("<\\/?(script|iframe|object|embed|link|meta|form|input|base)[^>]*>",
"gi"),"");$isSafe_tempHtml$$=$isSafe_tempHtml$$.replace(/<([a-z0-9]+)([^>]*)>/gi,($cleanedAttrs_match$$,$tagName$$,$attrs$$)=>{$cleanedAttrs_match$$=$attrs$$.replace(/\s+on\w+\s*=\s*("([^"]*)"|'([^']*)'|[^\s>]+)/gi,"");$cleanedAttrs_match$$=$cleanedAttrs_match$$.replace(/\s+(href|src|action|formaction)\s*=\s*("javascript:[^"]*"|'javascript:[^']*')/gi,"");return`<${$tagName$$}${$cleanedAttrs_match$$}>`});$html_restoredHtml$$=$isSafe_tempHtml$$.replace(/__PLACEHOLDER_(\d+)__/g,($match$$,$index$$)=>
$placeholders$$[parseInt($index$$,10)]||"");$isSafe_tempHtml$$=$sanitizedAfterTokens$$===$isSafe_tempHtml$$;return{safe:$isSafe_tempHtml$$,cleaned:$html_restoredHtml$$,reason:$isSafe_tempHtml$$?"Chu\u1ed7i an to\u00e0n.":"\u0110\u00e3 lo\u1ea1i b\u1ecf n\u1ed9i dung ho\u1eb7c thu\u1ed9c t\u00ednh kh\u00f4ng an to\u00e0n."}}exports.sanitizeHtm=sanitizeHtm;
exports.buildQueryByDateHour=($from_startHour$$,$conditions_endHour_to$$,$options$$={})=>{const {startOperator:$startOperator$$="gte",endOperator:$endOperator$$="lte"}=$options$$,$startOpKey$$=`$${$startOperator$$}`,$endOpKey$$=`$${$endOperator$$}`;$options$$=new Date($from_startHour$$);$options$$.setHours(0,0,0,0);const $endDay$$=new Date($conditions_endHour_to$$);$endDay$$.setHours(0,0,0,0);$from_startHour$$=$from_startHour$$.getHours();$conditions_endHour_to$$=$conditions_endHour_to$$.getHours();
if($options$$.getTime()===$endDay$$.getTime())return{ngay_ct:$options$$,gio:{[$startOpKey$$]:$from_startHour$$,[$endOpKey$$]:$conditions_endHour_to$$}};$conditions_endHour_to$$=[{ngay_ct:$options$$,gio:{[$startOpKey$$]:$from_startHour$$}},{ngay_ct:$endDay$$,gio:{[$endOpKey$$]:$conditions_endHour_to$$}}];($endDay$$.getTime()-$options$$.getTime())/864E5>1&&$conditions_endHour_to$$.push({ngay_ct:{$gt:$options$$,$lt:$endDay$$}});return{$or:$conditions_endHour_to$$}};
const ALGORITHM="aes-256-cbc",KEY_LENGTH=32,IV_LENGTH=16,SALT="KKKHHHHK";exports.encrypt=$data$$=>{var $cipher_key$$=crypto.scryptSync(configs.cryptoPassword||"PVT@1",SALT,KEY_LENGTH);const $iv$$=crypto.randomBytes(IV_LENGTH);$cipher_key$$=crypto.createCipheriv(ALGORITHM,$cipher_key$$,$iv$$);$data$$=JSON.stringify($data$$);$data$$=$cipher_key$$.update($data$$,"utf8","hex");$data$$+=$cipher_key$$.final("hex");return $iv$$.toString("hex")+":"+$data$$};
exports.decrypt=$decrypted_encryptedText_iv$$=>{var $decipher_key$jscomp$15_password$$=configs.cryptoPassword||"PVT@1";const [$ivHex$$,$encryptedData$$]=$decrypted_encryptedText_iv$$.split(":");if(!$ivHex$$||!$encryptedData$$)throw Error("\u0110\u1ecbnh d\u1ea1ng d\u1eef li\u1ec7u m\u00e3 h\u00f3a kh\u00f4ng h\u1ee3p l\u1ec7.");$decrypted_encryptedText_iv$$=Buffer.from($ivHex$$,"hex");$decipher_key$jscomp$15_password$$=crypto.scryptSync($decipher_key$jscomp$15_password$$,SALT,KEY_LENGTH);$decipher_key$jscomp$15_password$$=
crypto.createDecipheriv(ALGORITHM,$decipher_key$jscomp$15_password$$,$decrypted_encryptedText_iv$$);$decrypted_encryptedText_iv$$=$decipher_key$jscomp$15_password$$.update($encryptedData$$,"hex","utf8");$decrypted_encryptedText_iv$$+=$decipher_key$jscomp$15_password$$.final("utf8");return JSON.parse($decrypted_encryptedText_iv$$)};
exports.retryStrategyRedis=$options$$=>{if($options$$.error&&$options$$.error.code==="ECONNREFUSED")return Logger.error("L\u1ed7i k\u1ebft n\u1ed1i Redis: Server t\u1eeb ch\u1ed1i k\u1ebft n\u1ed1i."),Error("Server t\u1eeb ch\u1ed1i k\u1ebft n\u1ed1i.");if($options$$.attempt>10)return Logger.error("\u0110\u00e3 th\u1eed k\u1ebft n\u1ed1i l\u1ea1i Redis qu\u00e1 10 l\u1ea7n. B\u1ecf cu\u1ed9c."),Error("Kh\u00f4ng th\u1ec3 k\u1ebft n\u1ed1i \u0111\u1ebfn Redis sau nhi\u1ec1u l\u1ea7n th\u1eed.");const $delay$$=
Math.min($options$$.attempt*100,3E3);Logger.info(`M\u1ea5t k\u1ebft n\u1ed1i Redis. Th\u1eed k\u1ebft n\u1ed1i l\u1ea1i sau ${$delay$$}ms. L\u1ea7n th\u1eed th\u1ee9 ${$options$$.attempt}...`);return $delay$$};
const transform=require("lodash/transform"),isEqual=require("lodash/isEqual"),isObject=require("lodash/isObject"),difference=function($object$$,$base$$){return transform($object$$,($result$$,$value$$,$key$$)=>{isEqual($value$$,$base$$[$key$$])||($result$$[$key$$]=isObject($value$$)&&isObject($base$$[$key$$])?difference($value$$,$base$$[$key$$]):$value$$)})};exports.difference=difference;
const getDateRangeByType=$type$$=>{let $fromDate$$="",$toDate$$="";switch($type$$){case "today":$fromDate$$=moment().format("YYYY-MM-DD");$toDate$$=moment().format("YYYY-MM-DD");break;case "thisWeek":$fromDate$$=moment().startOf("week").format("YYYY-MM-DD");$toDate$$=moment().endOf("week").format("YYYY-MM-DD");break;case "thisMonth":$fromDate$$=moment().startOf("month").format("YYYY-MM-DD");$toDate$$=moment().endOf("month").format("YYYY-MM-DD");break;case "lastMonth":$fromDate$$=moment().subtract(1,
"month").startOf("month").format("YYYY-MM-DD");$toDate$$=moment().subtract(1,"month").endOf("month").format("YYYY-MM-DD");break;case "thisYear":$fromDate$$=moment().startOf("year").format("YYYY-MM-DD"),$toDate$$=moment().endOf("year").format("YYYY-MM-DD")}return{fromDate:$fromDate$$,toDate:$toDate$$}};exports.getDateRangeByType=getDateRangeByType;
const fs=require("fs"),getDir=$dirName$$=>{let $dirPath$$=configs.paths[$dirName$$];$dirPath$$||($dirPath$$=__dirname,$dirPath$$=path.dirname($dirPath$$),$dirPath$$=path.dirname($dirPath$$),$dirPath$$=path.join($dirPath$$,$dirName$$));fs.existsSync($dirPath$$)||fs.mkdirSync($dirPath$$);return $dirPath$$};exports.getDir=getDir;
const getPathFile=$file_file_name$$=>{if($file_file_name$$.file&&$file_file_name$$.file.name){$file_file_name$$=$file_file_name$$.file.name;var $root$$=getDir("uploads");return path.join($root$$,$file_file_name$$)}};exports.getPathFile=getPathFile;