flexbiz-server
Version:
Flexible Server
73 lines (72 loc) • 32.8 kB
JavaScript
const _=require("lodash"),Socai=global.getModel("socai"),OptionsModel=global.getModel("options"),trangthai=global.getModel("trangthai"),app=global.getModel("app"),Participant=global.getModel("participant"),dmqct=global.getModel("dmqct"),counter=global.getModel("counter"),async=require("async"),utils=require("../libs/utils"),fs=require("fs"),Moment=require("moment-timezone"),moment=$time$$=>Moment.tz($time$$,configs.timezone||"Asia/Ho_Chi_Minh"),numeral=require("numeral"),{stripHtmlTags,compileHtml,
evalute,JSONParser,numberToWord}=require("../libs/utils"),{getCurrentSession}=require("../libs/sessionContext.js"),path=require("path"),StaticPool=require("../libs/WorkerStaticPool"),fields_sync_master_detail=["ma_ct","so_ct","ngay_ct"],ERRORS={ERR_NOT_FOUND:"ERR_NOT_FOUND: \u0110\u1ed1i t\u01b0\u1ee3ng n\u00e0y kh\u00f4ng t\u1ed3n t\u1ea1i",ERR_NOT_FOUND_CODE:1100,ERR_NOT_PERMIT:"ERR_NOT_PERMIT: Kh\u00f4ng c\u00f3 quy\u1ec1n th\u1ef1c hi\u1ec7n t\u00e1c v\u1ee5 n\u00e0y",ERR_NOT_PERMIT_CODE:1200,
ERR_ALREADY_EXIST:"ERR_ALREADY_EXIST: \u0110\u1ed1i t\u01b0\u1ee3ng n\u00e0y \u0111\u00e3 t\u1ed3n t\u1ea1i",ERR_ALREADY_EXIST_CODE:1300,ERR_NOT_HAVE_DATA:"ERR_NOT_HAVE_DATA: Kh\u00f4ng c\u00f3 d\u1eef li\u1ec7u",ERR_NOT_HAVE_DATA_CODE:1400,ERR_CAN_NOT_UPDATE:"ERR_CAN_NOT_UPDATE: Kh\u00f4ng th\u1ec3 c\u1eadp nh\u1eadt \u0111\u1ed1i t\u01b0\u1ee3ng n\u00e0y",ERR_CAN_NOT_UPDATE_CODE:1500,ERR_DATA_GENERATED:"ERR_DATA_GENERATED: \u0110\u00e3 ph\u00e1t sinh d\u1eef li\u1ec7u li\u00ean quan",ERR_DATA_GENERATED_CODE:1600,
ERR_ID_INVALID:"ERR_ID_INVALID: Id kh\u00f4ng h\u1ee3p l\u1ec7",ERR_ID_INVALID_CODE:1700,ERR_KEY_ARISE:"ERR_KEY_ARISE_DATA: ",ERR_KEY_ARISE_CODE:1800,ERR_ARISE:"ERR_ARISE_DATA: ",ERR_ARISE_CODE:1900,ERR_VERIFY_OTP:4001,BOOK_LOCK:4444};
async function createIdRef($model_pathsHaveRef$$,$data$$){$model_pathsHaveRef$$=Object.values($model_pathsHaveRef$$.schema.paths).filter($path$$=>$path$$.options&&$path$$.options.ref&&$path$$.options.localField&&$path$$.options.foreignField);try{return await Promise.all($model_pathsHaveRef$$.map($path$$=>new Promise($resove$$=>{setImmediate(async()=>{let $namePath$$=$path$$.path;var $modelRef_modelRefName$$=$path$$.options.ref,$localField_obj$$=$path$$.options.localField;let $foreignField$$=$path$$.options.foreignField;
$data$$[$localField_obj$$]&&($foreignField$$!=="_id"||global.mongoose.Types.ObjectId.isValid($data$$[$localField_obj$$]))?($modelRef_modelRefName$$=mongoose.models[$modelRef_modelRefName$$.toLowerCase()])?($localField_obj$$=await $modelRef_modelRefName$$.findOne({id_app:$data$$.id_app,[$foreignField$$]:$data$$[$localField_obj$$]}).lean(),$data$$[$namePath$$]=$localField_obj$$?$localField_obj$$._id.toString():null):$data$$[$namePath$$]=null:$data$$[$namePath$$]=null;$resove$$($path$$)})})))}catch($e2$$){return Logger.error("error create ref data",
$e2$$),null}}function deleteEmptyArray($condition$$,$key$$){$condition$$&&$condition$$[$key$$]&&_.isArray($condition$$[$key$$])&&($condition$$[$key$$].length===0?delete $condition$$[$key$$]:($condition$$[$key$$].forEach($item$$=>{deleteEmptyArray($item$$,"$and");deleteEmptyArray($item$$,"$or");deleteEmptyArray($item$$,"$nor")}),$condition$$[$key$$].length===0&&delete $condition$$[$key$$]))}
function bodyToJson($body$$){try{return $body$$&&$body$$.json&&($body$$=JSONParser($body$$.json)),$body$$||={},delete $body$$._id,delete $body$$.__v,$body$$}catch($e$$){return Logger.error("parse body data",$e$$,$body$$),{}}}
async function asyncBodyToJson($body$$,$ctrl$$,$id_app$$,$voucher_options$$){$voucher_options$$||($voucher_options$$=(await OptionsModel.findOne({id_app:$id_app$$,id_func:$ctrl$$.name},{option:1}).lean()||{}).option);$body$$=bodyToJson($body$$);if($voucher_options$$)for(let $field$$ in $voucher_options$$)!$body$$[$field$$]&&$field$$!=="_id"&&$voucher_options$$[$field$$]&&_.has($ctrl$$.model.schema.paths,$field$$)&&($body$$[$field$$]=$voucher_options$$[$field$$]);for(let $key$$ in $body$$)if(Array.isArray($body$$[$key$$])&&
$body$$[$key$$].forEach($r$$=>{_.isObject($r$$)&&delete $r$$._id}),$body$$[$key$$]&&$body$$[$key$$]instanceof String&&($body$$[$key$$].trim().indexOf("[")==0||$body$$[$key$$].trim().indexOf("{")==0)&&($ctrl$$.model.schema.paths[$key$$].instance.toLowerCase()=="mixed"||$ctrl$$.model.schema.paths[$key$$].instance.toLowerCase()=="array"))try{$body$$[$key$$]=JSONParser($body$$[$key$$])}catch($e$$){Logger.error($e$$)}return $body$$}
const getData=($id_app$$,$collection$$,$field$$,$condition$$)=>{if($collection$$==="token"||$collection$$==="asskey")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$$&&$field$$.split(",").forEach($f$$=>
{$fields$$={[$f$$]:1}});if($collection$$==="user"||$collection$$==="participant")$fields$$={name:1};$collection$$==="app"&&($fields$$||={},$fields$$={...$fields$$,viettel_user:0,viettel_password:0,viettel_url_service:0,viettel_token: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 data: Collection ${$collection$$} is not exists`;},isExists=function($model$$,$unique$$,$obj$$,$replaceIfExists$$,$fn$$){if(!$unique$$||$unique$$.length===0)return $fn$$(null,
!1);let $condition$$={};$unique$$=$unique$$.filter($key$$=>$model$$.schema.paths[$key$$]);for(let $i$$=0;$i$$<$unique$$.length;$i$$++){let $key$$=$unique$$[$i$$],$v$$=$obj$$[$key$$];$v$$!=void 0&&$model$$.schema.paths[$key$$]&&($v$$!==null?$model$$.schema.paths[$key$$].instance.toLowerCase()=="number"?$condition$$[$key$$]=Number($v$$):$model$$.schema.paths[$key$$].instance.toLowerCase()=="date"?$condition$$[$key$$]=new Date($v$$):$model$$.schema.paths[$key$$].instance.toLowerCase()=="string"?$condition$$[$key$$]=
$v$$.toString():$condition$$[$key$$]=$v$$:$condition$$[$key$$]=$v$$)}if($condition$$.id_app&&Object.values($condition$$).length<2||Object.values($condition$$).length<1)return $fn$$("D\u1eef li\u1ec7u c\u1ea7n c\u00f3 \u00edt nh\u1eadt m\u1ed9t gi\u00e1 tr\u1ecb: "+$unique$$.join(","));$obj$$.id_app&&($condition$$.id_app=$obj$$.id_app);$replaceIfExists$$?$model$$.deleteMany($condition$$,$e$$=>{setImmediate(()=>{if($e$$)return $fn$$($e$$);$fn$$(null,!1)})}):$model$$.findOne($condition$$,{_id:1},($error$$,
$result$$)=>{setImmediate(()=>{if($error$$)return $fn$$($error$$);if(!$result$$)return $fn$$(null,!1);Logger.error("object exists",$condition$$,"unique fields",$unique$$);$fn$$(null,!0)})})},postData=function($obj$$,$ctrl$$,$mainCallback$$,$options$$={}){const $post$$=$ctrl$$.dynamicPost||$ctrl$$.post;if(!$post$$)return $mainCallback$$();if(!getCurrentSession())return $mainCallback$$("T\u00ednh n\u0103ng [postData] c\u1ea7n ch\u1ea1y trong m\u1ed9t transaction");const $postOptions$$={...$ctrl$$.options,
...$options$$};let $obj_created$$=$obj$$.toObject?utils.convertObjectIdsToStrings($obj$$.toObject()):{...$obj$$};Object.keys($obj_created$$).forEach($key$$=>{let $p$$=$obj_created$$[$key$$];$p$$&&($p$$.toObject&&($obj_created$$[$key$$]=utils.convertObjectIdsToStrings($p$$.toObject())),_.isArray($p$$)&&($obj_created$$[$key$$]=$p$$.map($el$$=>$el$$?$el$$.toObject?utils.convertObjectIdsToStrings($el$$.toObject()):$el$$:$el$$)))});$ctrl$$.beforePost||($ctrl$$.beforePost=function($obj_created$$,$callback$$){$callback$$(null,
null)});$ctrl$$.beforePost($obj_created$$,function($e$$){if($e$$)return $mainCallback$$($e$$);deletePost($obj_created$$.user_updated,$obj_created$$,async function($e$$){if($e$$)return $mainCallback$$($e$$);const $callback$$=async($e$$,$rs$$)=>{$mainCallback$$($e$$,$rs$$)};if($ctrl$$.dynamicDeletePost)try{await $ctrl$$.dynamicDeletePost($obj_created$$)}catch($e$$){return $callback$$($e$$.message||$e$$.error||$e$$)}setImmediate(async()=>{if($obj_created$$.trang_thai||$obj_created$$.trang_thai==0)$obj_created$$.trang_thai=
$obj_created$$.trang_thai.toString();const $listinfo_code$$=$obj_created$$.listinfo_code;let $trang_thai$$;if($obj_created$$.trang_thai&&($listinfo_code$$&&($trang_thai$$=await trangthai.findOne({ma_ct:($listinfo_code$$||"").toUpperCase(),ma_trang_thai:$obj_created$$.trang_thai})),$trang_thai$$||=await trangthai.findOne({ma_ct:($obj_created$$.ma_ct||"").toUpperCase(),ma_trang_thai:$obj_created$$.trang_thai}),!$trang_thai$$||!$trang_thai$$.post))return Logger.info("[controllerUtils][postData] tr\u1ea1ng th\u00e1i kh\u00f4ng t\u1ed3n t\u1ea1i ho\u1eb7c kh\u00f4ng y\u00eau c\u1ea7u post d\u1eef li\u1ec7u",
$listinfo_code$$,$obj_created$$.trang_thai),$callback$$();setImmediate(()=>{$post$$($obj_created$$,function($e$$,$rs$$){$e$$?(Logger.error("[controllerUtils] [postData] error post data",$obj_created$$._id,$e$$.message||$e$$.error||$e$$.toString()),$callback$$($e$$)):$callback$$(null,$rs$$)},{...$postOptions$$})})})})})},asyncPostData=function($obj$$,$ctrl$$,$options$$={}){return new Promise(($resolve$$,$reject$$)=>{postData($obj$$,$ctrl$$,($e$$,$rs$$)=>{if($e$$)return $reject$$($e$$);$resolve$$($rs$$)},
$options$$)})},pushNotification=($ctrl$$,$_obj$$,$eventName$$="new",$old_obj$$=null,$justFireEvents$$=!1,$options$$={title:"",data:{}})=>{let $obj$$;$obj$$=$_obj$$.toObject?utils.convertObjectIdsToStrings($_obj$$.toObject()):{...$_obj$$};$obj$$._id&&($obj$$._id=$obj$$._id.toString());setImmediate(async()=>{var $channel_id_func_old_trang_thai$$=`${$ctrl$$.name.toLowerCase()}-${$eventName$$}`;$_obj$$.id_app&&($channel_id_func_old_trang_thai$$=`${$channel_id_func_old_trang_thai$$}-${$_obj$$.id_app}`);
let $message$$=JSON.stringify($obj$$);try{await global.clientRedis.publish($channel_id_func_old_trang_thai$$,$message$$)}catch($e$$){Logger.error("[controllerUtiles][pushNotification] fire event",$eventName$$,$e$$)}if($_obj$$.status){$options$$||={};var $exclude_token$$=$options$$.exclude_token,$trang_thai$$=($obj$$.trang_thai||($obj$$.progress==0?"0":$obj$$.progress)||"").toString();$old_obj$$&&!$justFireEvents$$&&($channel_id_func_old_trang_thai$$=($old_obj$$.trang_thai||($old_obj$$.progress==0?
"0":$old_obj$$.progress)||"").toString(),$channel_id_func_old_trang_thai$$===$trang_thai$$&&($justFireEvents$$=!0));var $listinfos_notifications_setting_users_receive_notification_v_options$$;($channel_id_func_old_trang_thai$$=$obj$$.listinfo_code)&&($listinfos_notifications_setting_users_receive_notification_v_options$$=await OptionsModel.find({id_app:$obj$$.id_app,id_func:$channel_id_func_old_trang_thai$$,option:{$exists:!0}},{option:1}).lean());$channel_id_func_old_trang_thai$$&&$listinfos_notifications_setting_users_receive_notification_v_options$$.length!=
0||($listinfos_notifications_setting_users_receive_notification_v_options$$=(await global.getModel("listinfo").find({api_code:$ctrl$$.name},{code:1}).lean()).map($a$$=>$a$$.code),$listinfos_notifications_setting_users_receive_notification_v_options$$.push($ctrl$$.name),$listinfos_notifications_setting_users_receive_notification_v_options$$=[...(new Set($listinfos_notifications_setting_users_receive_notification_v_options$$))],$channel_id_func_old_trang_thai$$={$in:$listinfos_notifications_setting_users_receive_notification_v_options$$},
$listinfos_notifications_setting_users_receive_notification_v_options$$=await OptionsModel.find({id_app:$obj$$.id_app,id_func:$channel_id_func_old_trang_thai$$,option:{$exists:!0}},{option:1}).lean());$listinfos_notifications_setting_users_receive_notification_v_options$$=$listinfos_notifications_setting_users_receive_notification_v_options$$.filter($v$$=>$v$$.option&&$v$$.option.users_receive_notification).map($v$$=>$v$$.option.users_receive_notification).reduce(($a$$,$b$$)=>$a$$.concat($b$$),[]);
$listinfos_notifications_setting_users_receive_notification_v_options$$.length===0&&($listinfos_notifications_setting_users_receive_notification_v_options$$=await Promise.all((($ctrl$$.options||{}).users_receive_notification_default||[]).map($n$$=>new Promise($resolve$$=>{setImmediate(async()=>{_.isFunction($n$$)?$resolve$$(await $n$$($obj$$)):$resolve$$($n$$)})}))));$listinfos_notifications_setting_users_receive_notification_v_options$$&&($listinfos_notifications_setting_users_receive_notification_v_options$$=
$listinfos_notifications_setting_users_receive_notification_v_options$$.filter($u$$=>!$u$$.trang_thai||$u$$.trang_thai.toString()===$trang_thai$$||$u$$.trang_thai.toString()==="delete"),$listinfos_notifications_setting_users_receive_notification_v_options$$=$listinfos_notifications_setting_users_receive_notification_v_options$$.filter($func_string_n$$=>{if(!$func_string_n$$.condition||!$func_string_n$$.condition.trim())return!0;$func_string_n$$=$func_string_n$$.condition;$func_string_n$$.indexOf("return ")<
0&&($func_string_n$$=`return ${$func_string_n$$}`);try{return evalute($func_string_n$$,{...$obj$$,master:$obj$$,data:$obj$$,old_obj:$old_obj$$})}catch($e$$){return Logger.error("[controllerUtiles][pushNotification]",$e$$,$func_string_n$$),!1}}),$listinfos_notifications_setting_users_receive_notification_v_options$$.forEach(async $p$$=>{setImmediate(async()=>{let $_justFireEvents$$=$justFireEvents$$;if($p$$.just_fire_events||$p$$.condition&&!$trang_thai$$)$_justFireEvents$$=$p$$.just_fire_events;let $notificationData$$=
{_id:$obj$$._id,trang_thai:$trang_thai$$,id_app:$obj$$.id_app,code:$obj$$.ma_ct||$ctrl$$.name,id_link:$obj$$.id_link||$obj$$.id_product,code_link:$obj$$.code_link||$obj$$.colection_name_product,event:$eventName$$,action:$eventName$$.toUpperCase(),data:$options$$.data,key:$options$$.key,not_send_email:$p$$.not_send_email,justFireEvents:$_justFireEvents$$};if($_justFireEvents$$||$eventName$$.toLowerCase()==="delete")$notificationData$$.title="",$notificationData$$.body="";else{try{$notificationData$$.body=
$p$$.body?compileHtml($p$$.body,$obj$$):""}catch($e$$){$notificationData$$.body=$p$$.body,Logger.error("[controllerUtiles][pushNotification]",$ctrl$$.name,"compileHtml body",$e$$,$obj$$)}try{$notificationData$$.title=stripHtmlTags(compileHtml($options$$.title||$p$$.title||$p$$.content||"",$obj$$))}catch($e$$){$notificationData$$.title=$options$$.title||$p$$.title||$p$$.content||"",Logger.error("[controllerUtiles][pushNotification]",$ctrl$$.name,"compileHtml title",$e$$,$obj$$)}}if($p$$.email_content)try{$notificationData$$.email_content=
compileHtml($p$$.email_content,$obj$$)}catch($e$$){$notificationData$$.email_content=$p$$.email_content,Logger.error("[controllerUtiles][pushNotification]",$ctrl$$.name,"compileHtml email_content",$e$$,$obj$$)}$notificationData$$.title||$notificationData$$.body||($exclude_token$$=null);let $users_will_receive$$=$p$$.users;$users_will_receive$$||=[];$options$$.users_will_receive&&$options$$.users_will_receive.length>0&&($users_will_receive$$=$users_will_receive$$.concat($options$$.users_will_receive));
$p$$.send_phu_trach&&$obj$$.phu_trach&&($users_will_receive$$=$users_will_receive$$.concat([$obj$$.phu_trach]));if($p$$.send_admin){var $admins_of_user_sandbox_us$$=(await Participant.find({id_app:$obj$$.id_app,admin:!0}).lean()).map($p$$=>$p$$.email);$users_will_receive$$=$users_will_receive$$.concat($admins_of_user_sandbox_us$$)}$p$$.send_attends&&$obj$$.attends&&($users_will_receive$$=$users_will_receive$$.concat($obj$$.attends));$p$$.group_id&&($admins_of_user_sandbox_us$$=(await Participant.find({id_app:$obj$$.id_app,
group_id:$p$$.group_id}).lean()).map($u$$=>$u$$.email),$users_will_receive$$=$users_will_receive$$.concat($admins_of_user_sandbox_us$$));$p$$.send_to_customer&&($obj$$.ma_kh||$obj$$.id_kh)&&($admins_of_user_sandbox_us$$=await mongoose.models.customer.getInfo($obj$$.id_app,{$or:[{ma_kh:$obj$$.ma_kh},{_id:$obj$$.id_kh}]},"of_user"))&&($users_will_receive$$=$users_will_receive$$.concat([$admins_of_user_sandbox_us$$]));$p$$.send_to_user_created?$users_will_receive$$=$users_will_receive$$.concat([$obj$$.user_created]):
$p$$.send_to_user_created===!1&&($users_will_receive$$=$users_will_receive$$.filter($u$$=>$u$$!==$obj$$.user_created));if($p$$.handle_receivers){$admins_of_user_sandbox_us$$={obj:$obj$$,users_will_receive:$users_will_receive$$,utils};try{let $str_func$$=$p$$.handle_receivers;if($str_func$$.indexOf("async ")<0){$str_func$$.indexOf("return ")<0&&($str_func$$=`return ${$str_func$$}`);let $cust_users_will_receive$$=await evalute(`return (async ()=>{
try{
${$str_func$$}
}catch(e){
return {error:e}
}
})`,$admins_of_user_sandbox_us$$)();_.isArray($cust_users_will_receive$$)?$users_will_receive$$=$cust_users_will_receive$$:Logger.error("handle user will receive notify:",$cust_users_will_receive$$,$p$$.handle_receivers)}}catch($e$$){Logger.error("[controllerUtiles][pushNotification]",$e$$)}}$ctrl$$.options||($ctrl$$.options={});$ctrl$$.options.onEmitEvent||($ctrl$$.options.onEmitEvent=($obj$$,$users_will_receive$$,$next$$,$_notificationData$$)=>{$next$$(null,$users_will_receive$$,
$_notificationData$$)});$ctrl$$.options.onEmitEvent(Object.assign({},$obj$$),$users_will_receive$$,($e$$,$_users_will_receive$$,$_notificationData$$)=>{setImmediate(()=>{if($e$$)return Logger.error("[controllerUtiles][pushNotification]","Error emit events",$e$$);$_users_will_receive$$=_.uniq($_users_will_receive$$);Logger.info("[controllerUtiles][pushNotification] Emit event to users",`${$ctrl$$.name.toLowerCase()}:${$eventName$$}`,$_users_will_receive$$,$_notificationData$$||$notificationData$$);
$_users_will_receive$$.length>0&&app.emitEvent($obj$$.id_app,`${$ctrl$$.name.toLowerCase()}:${$eventName$$}`,$_notificationData$$||$notificationData$$,$exclude_token$$,$_users_will_receive$$,!$_justFireEvents$$)})},Object.assign({},$notificationData$$),Object.assign({},$p$$))})}))}})},PostBook=require("../libs/post-book"),Sokho=global.getModel("sokho"),Sokhott=global.getModel("sokhott"),Sokhokhongton=global.getModel("sokhokhongton"),Tdttno=global.getModel("tdttno"),Tdttno_tt=global.getModel("tdttno_tt"),
Tdttco_tt=global.getModel("tdttco_tt"),Tdttco=global.getModel("tdttco"),Vatra=global.getModel("vatra"),Vatvao=global.getModel("vatvao"),deletePost=async function($query_delete_user$$,$obj$$,$callback$$){$obj$$.toObject&&($obj$$=utils.convertObjectIdsToStrings($obj$$.toObject()));if(!$obj$$._id)return Logger.error("Error when delete post: obj does not have _id",$obj$$),$callback$$("Error when delete post: obj does not have _id",$obj$$);if(!getCurrentSession())return $callback$$("T\u00ednh n\u0103ng [deletePost] c\u1ea7n ch\u1ea1y trong m\u1ed9t transaction");
$query_delete_user$$={id_ct:$obj$$._id.toString()};$obj$$.id_app&&($query_delete_user$$.id_app=$obj$$.id_app);try{if(global.model_books){const $excludedBooks$$="sokho sokhonpp sokhott sokhokhongton socai socaitmp".split(" ");var $filteredBooks_removePostBook$$=global.model_books.filter($d$$=>!$excludedBooks$$.includes($d$$));for(const $bookName$$ of $filteredBooks_removePostBook$$){let $bookModel$$=mongoose.models[$bookName$$.toLowerCase()];$bookModel$$&&await $bookModel$$.deleteMany($query_delete_user$$).exec()}}$filteredBooks_removePostBook$$=
($model$$,$data$$,$details$$)=>new Promise(($resolve$$,$reject$$)=>{(new PostBook($data$$,$details$$,$model$$,($detail$$,$cb$$)=>$cb$$($detail$$))).remove($err$$=>$err$$?$reject$$($err$$):$resolve$$())});await $filteredBooks_removePostBook$$(Sokho,$obj$$,$obj$$.details);await $filteredBooks_removePostBook$$(Sokhott,$obj$$,$obj$$.details);await $filteredBooks_removePostBook$$(Sokhokhongton,$obj$$,$obj$$.details);await $filteredBooks_removePostBook$$(global.getModel("sokhonpp"),$obj$$,$obj$$.details);
await Socai.deleteMany($query_delete_user$$).exec();await global.getModel("socaitmp").deleteMany($query_delete_user$$).exec();const $registeredBooks$$=global.model_books||[];$registeredBooks$$.includes("vatra")||await Vatra.deleteMany($query_delete_user$$).exec();$registeredBooks$$.includes("vatvao")||await Vatvao.deleteMany($query_delete_user$$).exec();let $tdttsNo$$=await Tdttno.find($query_delete_user$$,{_id:1,tat_toan:1}).lean();if($tdttsNo$$.length>0){const $isAnySettled$$=$tdttsNo$$.some($t$$=>
$t$$.tat_toan),$ids$$=$tdttsNo$$.map($t$$=>$t$$._id.toString()),$cttt$$=await Tdttno_tt.findOne({id_tdtt:{$in:$ids$$},id_app:$obj$$.id_app});$isAnySettled$$||$cttt$$||await Tdttno.deleteMany($query_delete_user$$).exec()}let $tdttsCo$$=await Tdttco.find($query_delete_user$$,{_id:1,tat_toan:1}).lean();if($tdttsCo$$.length>0){const $isAnySettled$$=$tdttsCo$$.some($t$$=>$t$$.tat_toan),$ids$$=$tdttsCo$$.map($t$$=>$t$$._id.toString()),$cttt$$=await Tdttco_tt.findOne({id_tdtt:{$in:$ids$$}});$isAnySettled$$||
$cttt$$||await Tdttco.deleteMany($query_delete_user$$).exec()}await Tdttno_tt.deleteMany($query_delete_user$$).exec();if($obj$$.tdttnos&&Array.isArray($obj$$.tdttnos))for(const $detail$$ of $obj$$.tdttnos)await Tdttno.updateOne({_id:$detail$$.id_tdtt},{$set:{tat_toan:!1}}).exec();await Tdttco_tt.deleteMany($query_delete_user$$).exec();if($obj$$.tdttcos&&Array.isArray($obj$$.tdttcos))for(const $detail$$ of $obj$$.tdttcos)await Tdttco.updateOne({_id:$detail$$.id_tdtt},{$set:{tat_toan:!1}}).exec();return $callback$$(null,
$obj$$)}catch($error$$){return Logger.error("[controllerUtils] [deletePost] Error:",$error$$.message||$error$$),$callback$$($error$$,$obj$$)}},runWebhooks=async($ctrl$$,$obj$$,$action$$,$voucher_options$$)=>{$voucher_options$$||($voucher_options$$=(await OptionsModel.findOne({id_app:$obj$$.id_app,id_func:$ctrl$$.name},{option:1}).lean()||{}).option);if($voucher_options$$&&$voucher_options$$.option_webhooks&&($ctrl$$=$voucher_options$$.option_webhooks.find($w$$=>$w$$.action.toUpperCase()===$action$$.toUpperCase()&&
$w$$.url))){$voucher_options$$=path.dirname(__dirname)+"/workers/webhook.js";if(!fs.existsSync($voucher_options$$))return Logger.error("webhook process is not exitst");global.webhookPool||(global.webhookPool=new StaticPool($voucher_options$$,0,1));global.webhookPool.exec({data:$obj$$,webhook_configs:$ctrl$$},$response$$=>{$response$$.error?Logger.error("runWebhooks",$response$$.error):Logger.info($response$$)})}},getNextSequence=async function($id_app$$,$ma_ct$$,$field$$,$callback$$,$options$$={}){var $condition_qct_qcts$$=
{status:!0,field:$field$$,id_app:$id_app$$,cac_ma_ct:$ma_ct$$.toLowerCase()};$options$$.id_qct&&($condition_qct_qcts$$._id=$options$$.id_qct);if($options$$.ngay_ct){$condition_qct_qcts$$.$and||($condition_qct_qcts$$.$and=[]);let $start_date$$=moment($options$$.ngay_ct).startOf("date").toDate(),$end_date$$=moment($options$$.ngay_ct).endOf("date").toDate();$condition_qct_qcts$$.$and.push({$or:[{tu_ngay:null},{tu_ngay:{$lte:$end_date$$}}]});$condition_qct_qcts$$.$and.push({$or:[{den_ngay:null},{den_ngay:{$gte:$start_date$$}}]})}$options$$.toObject&&
($options$$=utils.convertObjectIdsToStrings($options$$.toObject()));$condition_qct_qcts$$=await dmqct.find($condition_qct_qcts$$).lean();const $keys$$=Object.keys($options$$),$qct$$=$condition_qct_qcts$$.find($qct$$=>{if($qct$$.dieu_kien&&$keys$$.length>0)try{let $str_func$$=$qct$$.dieu_kien;if($str_func$$.indexOf("async ")>=0)return!1;$str_func$$.indexOf("return ")!==0&&($str_func$$=`return ${$str_func$$}`);return evalute($str_func$$,{...$options$$,master:{...$options$$},moment,numeral})}catch($e$$){return Logger.error("[controllerUtils][getNextSequence] Error find quyen chung tu",
$e$$,$qct$$.dieu_kien),!1}else return!0});let $code$$=$qct$$?$qct$$._id.toString():$field$$,$id_qct$$=$qct$$?$qct$$._id.toString():$ma_ct$$;counter.getNextSequence($id_app$$,$id_qct$$,$code$$,async function($error$$,$rs$$){if($error$$)Logger.error("[controllerUtils][getNextSequence] auto create code for qct: ",$id_qct$$,$code$$,$error$$),$callback$$($error$$);else{if($qct$$){let $tien_to$$=$qct$$.tien_to||"";if($tien_to$$.indexOf("return ")>=0&&$tien_to$$.indexOf("async ")<0)try{$tien_to$$=evalute($tien_to$$,
{...$options$$,moment,numeral}),$tien_to$$=$tien_to$$.toString().trim()}catch($e$$){Logger.error("[controllerUtils][getNextSequence]",$e$$)}let $hau_to$$=$qct$$.hau_to||"";if($hau_to$$.indexOf("return ")>=0&&$hau_to$$.indexOf("async ")<0)try{$hau_to$$=evalute($hau_to$$,{...$options$$,moment,numeral}),$hau_to$$=$hau_to$$.toString().trim()}catch($e$$){Logger.error("[controllerUtils][getNextSequence]",$e$$)}!$qct$$.tu_dong_reset||$qct$$.tien_to_ht==void 0||$qct$$.hau_to_ht==void 0||$qct$$.tien_to_ht==
$tien_to$$&&$qct$$.hau_to_ht==$hau_to$$||($rs$$=1,await counter.updateOne({id_app:$id_app$$,name:$id_qct$$.toUpperCase(),field:$code$$},{sequence:$rs$$}));$rs$$=($qct$$.tu_so||0)+$rs$$;$error$$=$rs$$.toString();var $den_so_so_ky_tu_them$$=$qct$$.den_so;$den_so_so_ky_tu_them$$||=999999;$den_so_so_ky_tu_them$$=$den_so_so_ky_tu_them$$.toString().length-$error$$.length;$error$$=$den_so_so_ky_tu_them$$>0?($tien_to$$||"")+"0000000000000000000000".substring(0,$den_so_so_ky_tu_them$$)+$error$$+$hau_to$$:
($tien_to$$||"")+$error$$+$hau_to$$;$qct$$.so_ht=$rs$$;$qct$$.tien_to_ht=$tien_to$$;$qct$$.hau_to_ht=$hau_to$$;await dmqct.updateOne({_id:$qct$$._id},$qct$$)}else $error$$=$rs$$.toString();$rs$$={};$rs$$[$field$$]=$error$$;$callback$$(null,$rs$$)}})},asyncGetNextSequence=async($id_app$$,$ma_ct$$,$field$$,$options$$={})=>new Promise(($resolve$$,$reject$$)=>{getNextSequence($id_app$$,$ma_ct$$,$field$$,($e$$,$rs$$)=>{if($e$$)return $reject$$($e$$);$resolve$$($rs$$)},$options$$)});
function checkReference($model$$,$obj$$,$fn$$,$keys$$){$model$$.referenceKeys?($keys$$||=_.keys($model$$.referenceKeys),async.map($keys$$,function($key$$,$callback$$){setImmediate(()=>{let $ref$$=$model$$.referenceKeys[$key$$];if(!$ref$$)return $callback$$();let $value$$=$obj$$[$key$$];$key$$==="_id"&&($value$$=$value$$.toString());if($value$$==void 0||$value$$==null||$value$$=="")return $callback$$();async.map($ref$$,function($r$$,$cb$$){setImmediate(()=>{let $model$$=mongoose.models[$r$$.model];
if($model$$){let $query$$={id_app:$obj$$.id_app};var $_w_k$$=$r$$.key;$_w_k$$&&($query$$[$_w_k$$]=$value$$);$r$$.where&&(_.isObject($r$$.where)&&($query$$=Object.assign($query$$,$r$$.where)),_.isFunction($r$$.where)&&($_w_k$$=$r$$.where($obj$$),$query$$=Object.assign($query$$,$_w_k$$)));$model$$.find($query$$).limit(1).lean().then(function($o$$){setImmediate(()=>{if($o$$&&$o$$.length>0){let $msgError$$;$msgError$$=$r$$.error?(new Function("obj","return `"+$r$$.error.replace("{{VALUE}}",$value$$)+
"`"))($obj$$):ERRORS.ERR_DATA_GENERATED;return $cb$$({error:$msgError$$,code:ERRORS.ERR_DATA_GENERATED_CODE})}$cb$$()})}).catch($error$$=>{$cb$$($error$$)})}else $cb$$()})},function($e$$){if($e$$)return $callback$$($e$$);$callback$$()})})},$error$$=>{$fn$$($error$$)})):$fn$$()}
const getParameters=($id_app$$,$rps_rpt_ids$$,$callback$$)=>{let $parameters$$=$rps_rpt_ids$$.filter($r$$=>$r$$.parameters).map($r$$=>$r$$.parameters).reduce(($a$$,$b$$)=>$a$$.concat($b$$),[]);$parameters$$.length>0?$callback$$(null,$parameters$$):($rps_rpt_ids$$=$rps_rpt_ids$$.map($r$$=>$r$$._id),global.getModel("parameter").find({id_app:$id_app$$,id_rpt:{$in:$rps_rpt_ids$$}}).lean().then(function($parameters$$){setImmediate(()=>{$callback$$(null,$parameters$$)})}).catch($e$$=>{$callback$$($e$$)}))},
prepareParameters=function($ctrl$$,$parameters$$,$app$$,$obj$$,$callback$$){async.mapLimit($parameters$$,100,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("prepareParameters",$e$$),$app$$[$p$$.name]=$e$$.message}else if($p$$.type==="Q")try{var $query$jscomp$1_sandbox$$=await evalute("return {"+$p$$.value+"}",{});
if($query$jscomp$1_sandbox$$.collection&&$query$jscomp$1_sandbox$$.field){$query$jscomp$1_sandbox$$.collection=="dmkh"&&($query$jscomp$1_sandbox$$.collection="customer");$query$jscomp$1_sandbox$$.collection=="dmtk"&&($query$jscomp$1_sandbox$$.collection="account");var $condition$$=$query$jscomp$1_sandbox$$.condition;if($condition$$){$condition$$=JSON.stringify($condition$$);for(let $m$$ in $obj$$)$condition$$=$condition$$.replace(new RegExp("m."+$m$$,"g"),$obj$$[$m$$]);$condition$$=JSONParser($condition$$)}else $condition$$=
{};$app$$[$p$$.name]=await getData($app$$.id_app,$query$jscomp$1_sandbox$$.collection,$query$jscomp$1_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";$query$jscomp$1_sandbox$$={m:$obj$$,master:$obj$$,data:$obj$$,Moment:moment,Numeral:numeral,numberToWord,
getData,round:utils.round};try{$app$$[$p$$.name]=await evalute(`return (async ()=>{
${$condition$$}
})`,$query$jscomp$1_sandbox$$)()}catch($e$$){$app$$[$p$$.name]=$e$$.message}}else $app$$[$p$$.name]=$p$$.value})().then(()=>{$callback$$()}).catch(()=>{$callback$$()})})},function($e$jscomp$25_v$$){if($e$jscomp$25_v$$)return $callback$$($e$jscomp$25_v$$);_.extend($app$$,$obj$$);if($ctrl$$.getData4Export)$ctrl$$.getData4Export($app$$,function($error$jscomp$7_v$$){if($error$jscomp$7_v$$)return $callback$$($error$jscomp$7_v$$);for(let $key$$ in $app$$)$error$jscomp$7_v$$=$app$$[$key$$],
_.isDate($error$jscomp$7_v$$)&&($app$$[$key$$+"_string"]=moment($error$jscomp$7_v$$).format("DD/MM/YYYY"));$callback$$()});else{for(let $key$$ in $app$$)$e$jscomp$25_v$$=$app$$[$key$$],_.isDate($e$jscomp$25_v$$)&&($app$$[$key$$+"_string"]=moment($e$jscomp$25_v$$).format("DD/MM/YYYY"));$callback$$()}})},cleanDataByMongooseSchema=($rawData$$,$mongooseSchema_paths$$)=>{if(!$rawData$$||typeof $rawData$$!=="object")return{};const $cleanedData$$={};$mongooseSchema_paths$$=$mongooseSchema_paths$$.paths;
for(const $key$$ in $rawData$$){if(!$mongooseSchema_paths$$[$key$$])continue;var $parsedDate_val$$=$rawData$$[$key$$];const $schemaType$$=$mongooseSchema_paths$$[$key$$];var $instanceType_numVal$$=$schemaType$$.instance;if($parsedDate_val$$!==void 0){if($parsedDate_val$$===null)if($instanceType_numVal$$==="String")$parsedDate_val$$="";else{Logger.warn("[controllerUtiles][cleanDataByMongooseSchema]",{instanceType:$instanceType_numVal$$,val:$parsedDate_val$$});continue}if(typeof $parsedDate_val$$!==
"object"||Array.isArray($parsedDate_val$$)||$parsedDate_val$$ instanceof Date||!Object.keys($parsedDate_val$$).some($k$$=>$k$$.startsWith("$")))switch($instanceType_numVal$$){case "String":typeof $parsedDate_val$$!=="string"&&($parsedDate_val$$=String($parsedDate_val$$));$parsedDate_val$$=$parsedDate_val$$.trim();$cleanedData$$[$key$$]=$parsedDate_val$$;break;case "Number":typeof $parsedDate_val$$==="string"&&($parsedDate_val$$=$parsedDate_val$$.replace(/,/g,""));$instanceType_numVal$$=Number($parsedDate_val$$);
isNaN($instanceType_numVal$$)||$parsedDate_val$$===""||($cleanedData$$[$key$$]=$instanceType_numVal$$);break;case "Boolean":$cleanedData$$[$key$$]=$parsedDate_val$$===!0||$parsedDate_val$$==="true"||$parsedDate_val$$===1||$parsedDate_val$$==="1";break;case "Date":$parsedDate_val$$!==""&&($parsedDate_val$$=new Date($parsedDate_val$$),isNaN($parsedDate_val$$.getTime())||($cleanedData$$[$key$$]=$parsedDate_val$$));break;case "ObjectID":case "ObjectId":typeof $parsedDate_val$$==="string"&&$parsedDate_val$$.trim()!==
""&&($cleanedData$$[$key$$]=$parsedDate_val$$.trim());break;case "Array":Array.isArray($parsedDate_val$$)||($parsedDate_val$$=$parsedDate_val$$!==""?[$parsedDate_val$$]:[]);$cleanedData$$[$key$$]=$schemaType$$.schema?$parsedDate_val$$.filter($item$$=>typeof $item$$!=="object"||$item$$===null||Array.isArray($item$$)||Object.keys($item$$).length===0?!1:!0).map($item$$=>cleanDataByMongooseSchema($item$$,$schemaType$$.schema)):$parsedDate_val$$.filter($v$$=>$v$$!==""&&$v$$!==null);break;default:$cleanedData$$[$key$$]=
$parsedDate_val$$}}}return $cleanedData$$};module.exports={createIdRef,postData,asyncPostData,pushNotification,ERRORS,isExists,getData,asyncBodyToJson,bodyToJson,deleteEmptyArray,fields_sync_master_detail,runWebhooks,deletePost,getNextSequence,asyncGetNextSequence,checkReference,getParameters,prepareParameters,cleanDataByMongooseSchema};