flexbiz-server 12.6.5 → 12.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "flexbiz-server",
3
3
  "main": "./server/app.js",
4
4
  "description": "Flexible Server",
5
- "version": "12.6.5",
5
+ "version": "12.6.6",
6
6
  "author": {
7
7
  "name": "Van Truong Pham",
8
8
  "email": "invncur@gmail.com"
@@ -13,7 +13,7 @@ const getData=($id_app$$,$collection$$,$field$$,$condition$$)=>{if($collection$$
13
13
  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,
14
14
  !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$$]=
15
15
  $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$$,
16
- $result$$)=>{setImmediate(()=>{if($error$$)return $fn$$($error$$);if(!$result$$)return $fn$$(null,!1);Logger.warn("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,
16
+ $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,
17
17
  ...$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,
18
18
  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=
19
19
  $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",
@@ -49,13 +49,14 @@ function($error$$){$callback$$($error$$)})})},tdttco:$callback$$=>{setImmediate(
49
49
  {setImmediate(async()=>{Tdttno_tt.deleteMany({id_ct:$obj$$._id.toString()},function($error$$){if($error$$)return $callback$$($error$$);$obj$$.tdttnos?async.mapSeries($obj$$.tdttnos,function($detail$$,$callback$$){setImmediate(()=>{Tdttno.updateOne({_id:$detail$$.id_tdtt},{$set:{tat_toan:!1}},function($error$$){setImmediate(()=>{if($error$$)return $callback$$($error$$);$callback$$()})})})},function($e$$){$e$$&&Logger.error($e$$);$callback$$()}):$callback$$()})})},tdttco_tt:$callback$$=>{setImmediate(async()=>
50
50
  {Tdttco_tt.deleteMany({id_ct:$obj$$._id.toString()},function($error$$){if($error$$)return $callback$$($error$$);$obj$$.tdttcos?async.mapSeries($obj$$.tdttcos,function($detail$$,$callback$$){setImmediate(()=>{Tdttco.updateOne({_id:$detail$$.id_tdtt},{$set:{tat_toan:!1}},function($error$$){if($error$$)return $callback$$($error$$);$callback$$()})})},function($e$$){$e$$&&Logger.error($e$$);$callback$$()}):$callback$$()})})}},async function($e$$){$e$$&&Logger.error("[controllerUtiles] [deletePost]",$e$$.message||
51
51
  $e$$.error||$e$$);$callback$$($e$$,$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");
52
- 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);
53
- 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();
54
- 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("Error find quyen chung tu",$e$$,$qct$$.dieu_kien),!1}else return!0});let $code$$=$qct$$?$qct$$._id.toString():$field$$,
55
- $id_qct$$=$qct$$?$qct$$._id.toString():$ma_ct$$;counter.getNextSequence($id_app$$,$id_qct$$,$code$$,async function($error$$,$rs$$){if($error$$)Logger.error("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("getNextSequence",
56
- $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("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$$}));
57
- $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$$=
58
- $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$$)});
52
+ 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$$={}){const $condition_qct$$={status:!0,field:$field$$,id_app:$id_app$$,cac_ma_ct:$ma_ct$$.toLowerCase()};$options$$.id_qct&&($condition_qct$$._id=$options$$.id_qct);if($options$$.ngay_ct){$condition_qct$$.$and||
53
+ ($condition_qct$$.$and=[]);var $qcts_start_date$$=moment($options$$.ngay_ct).startOf("date").toDate();let $end_date$$=moment($options$$.ngay_ct).endOf("date").toDate();$condition_qct$$.$and.push({$or:[{tu_ngay:null},{tu_ngay:{$lte:$end_date$$}}]});$condition_qct$$.$and.push({$or:[{den_ngay:null},{den_ngay:{$gte:$qcts_start_date$$}}]})}$options$$.toObject&&($options$$=utils.convertObjectIdsToStrings($options$$.toObject()));$qcts_start_date$$=await dmqct.find($condition_qct$$).lean();Logger.warn("[controllerUtils][getNextSequence]",
54
+ `\u0111\u00e3 t\u00ecm th\u1ea5y '${$qcts_start_date$$.length}' quy\u1ec3n ch\u1ee9ng t\u1eeb v\u1edbi \u0111i\u1ec1u ki\u1ec7n:`,JSON.stringify($condition_qct$$,null,2));const $keys$$=Object.keys($options$$),$qct$$=$qcts_start_date$$.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$$},
55
+ 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$$=
56
+ $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]",
57
+ $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$$>
58
+ 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$$,
59
+ ($e$$,$rs$$)=>{if($e$$)return $reject$$($e$$);$resolve$$($rs$$)},$options$$)});
59
60
  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];
60
61
  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$$)+
61
62
  "`"))($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$$()}
@@ -14,20 +14,19 @@ $listinfo_code$$||$ctrl$$.name;const $condition_qct$$={status:!0,id_app:$obj$$.i
14
14
  {if($qct$$.dieu_kien&&$keys_options$$.length>0)try{let $str_func$$=$qct$$.dieu_kien;$str_func$$.indexOf("return ")!==0&&($str_func$$=`return ${$str_func$$}`);return $str_func$$.indexOf("async ")>0?!1:evalute($str_func$$,{...$_options_qct$$,master:{...$_options_qct$$},moment,numeral})}catch($e$$){return Logger.error("Error find quyen chung tu",$e$$.message,$qct$$.dieu_kien),!1}else return!0});async.mapSeries($qcts$$,($qct$$,$cb$$)=>{let $field$$=$qct$$.field,$_options$$={...$_options_qct$$};$_options$$.id_qct=
15
15
  $qct$$._id.toString();let $count$$=0;async.whilst(function($cb$$){$cb$$(null,$count$$<10)},function($callback$$){getNextSequence($obj$$.id_app,$ma_ct$$,$field$$,function($e$$,$rs$$){setImmediate(async()=>{if($e$$)return $callback$$($e$$);$obj$$[$field$$]=$rs$$[$field$$];$qct$$.check_duplicate?await $model$$.findOne({id_app:$obj$$.id_app,[$field$$]:$obj$$[$field$$]},{[$field$$]:1}).lean()?$count$$>=9?$callback$$(`Kh\u00f4ng th\u1ec3 t\u1ef1 \u0111\u1ed9ng t\u1ea1o gi\u00e1 tr\u1ecb cho field ${$field$$}. Gi\u00e1 tr\u1ecb "${$obj$$[$field$$]}" \u0111\u00e3 t\u1ed3n t\u1ea1i. H\u00e3y ki\u1ec3m tra l\u1ea1i th\u00f4ng s\u1ed1 quy\u1ec3n ch\u1ee9ng t\u1eeb sao cho gi\u00e1 tr\u1ecb s\u1ebd t\u1ea1o ra kh\u00f4ng b\u1ecb tr\u00f9ng v\u1edbi gi\u00e1 tr\u1ecb \u0111\u00e3 c\u00f3`):
16
16
  ($count$$++,$callback$$()):($count$$=99999,$callback$$()):($count$$=99999,$callback$$())})},$_options$$)},function($err$$){$cb$$($err$$)})},$e$$=>{$callback$$($e$$)})})}).catch($e$$=>{Logger.error($e$$)})})},$callback$$=>{setImmediate(function(){if((!$voucher_options$$?.trang_thai_create_voucher_numbers||$voucher_options$$?.trang_thai_create_voucher_numbers.length==0||$voucher_options$$?.trang_thai_create_voucher_numbers?.indexOf($obj$$.trang_thai)>=0)&&$model$$.schema.paths.so_ct)if($obj$$.so_ct&&
17
- $obj$$.so_ct.toUpperCase()!==($listinfo_code$$||$ctrl$$.name).toUpperCase()&&$obj$$.so_ct.toUpperCase()!==$ctrl$$.name.toUpperCase())$checkVoucherNumber$$($error$$=>{$callback$$($error$$)});else{let $count$$=0;async.whilst(function($cb$$){$cb$$(null,$count$$<100)},function($callback$$){getNextSequence($obj$$.id_app,$listinfo_code$$||$ctrl$$.name,"so_ct",function($e$$,$rs$$){setImmediate(()=>{if($e$$)return $callback$$($e$$);$obj$$.so_ct=$rs$$.so_ct;$checkVoucherNumber$$($error$$=>{$error$$?$count$$>=
18
- 99?$callback$$($error$$):($count$$++,$callback$$()):($count$$=99999,$callback$$())})})},$obj$$)},function($err$$){$callback$$($err$$)})}else $callback$$()})},function($callback$$){setImmediate(async()=>{if($model$$.schema.paths.ma_dvcs&&$ctrl$$.name!=="dvcs")if($obj$$.ma_dvcs)if(global.mongoose.Types.ObjectId.isValid($obj$$.ma_dvcs)){let $_id_dvcs$$=global.mongoose.Types.ObjectId($obj$$.ma_dvcs);await global.getModel("dvcs").findOne({_id:$_id_dvcs$$})?$callback$$():global.getModel("dvcs").create({_id:$_id_dvcs$$,
19
- ma_dvcs:"IMPORTED",ten_dvcs:"Imported"},$e$$=>{setImmediate(()=>{$e$$&&Logger.error("Can't import dvcs",$e$$);$callback$$()})})}else $callback$$();else global.getModel("dvcs").findOne({id_app:$obj$$.id_app,status:!0}).lean().then(function($rs$$){setImmediate(()=>{$rs$$&&($obj$$.ma_dvcs=$rs$$._id.toString());$callback$$()})}).catch($e$$=>{Logger.error($e$$)});else $callback$$()})},$callback$$=>{$ctrl$$.validating||($ctrl$$.validating=($user$$,$obj$$,$next$$)=>{$next$$(null,$obj$$)});$ctrl$$.validating($user$$,
20
- $obj$$,$e$$=>{if($e$$)return $callback$$($e$$);setImmediate(()=>{$obj$$.user_created=$action$$=="import"?$obj$$.user_created||$user$$.email:$user$$.email;$obj$$.user_updated=$user$$.email;$obj$$.date_created=new Date;$obj$$.date_updated=new Date;validate($obj$$,async $error$$=>{setImmediate(async()=>{if($error$$){let $msgError$$=$error$$;if($ctrl$$.options.onErrorCreating)$ctrl$$.options.onErrorCreating($user$$,$obj$$,$e$$=>{$e$$&&($msgError$$=$msgError$$+"\n"+$e$$);$callback$$($msgError$$)});else $callback$$($msgError$$)}else{if($id_be_supply_by_user$$&&
21
- global.mongoose.Types.ObjectId.isValid($id_be_supply_by_user$$)){let $_id$$=global.mongoose.Types.ObjectId($id_be_supply_by_user$$);await $model$$.findOne({_id:$_id$$},{_id:1})||($obj$$._id=$_id$$)}$callback$$()}})},$voucher_options$$)})},{action:$action$$})},function($callback$$){setImmediate(function(){isExists($model$$,$ctrl$$.unique,$obj$$,$ctrl$$.replaceIfExists,async($error$$,$kq$$)=>{setImmediate(async()=>{if($error$$||$kq$$){let $msgError$$=$error$$||ERRORS.ERR_ALREADY_EXIST;if($ctrl$$.options.onErrorCreating)$ctrl$$.options.onErrorCreating($user$$,
17
+ $obj$$.so_ct.toUpperCase()!==($listinfo_code$$||$ctrl$$.name).toUpperCase()&&$obj$$.so_ct.toUpperCase()!==$ctrl$$.name.toUpperCase())$checkVoucherNumber$$($error$$=>{$callback$$($error$$)});else{let $count$$=0;async.whilst(function($cb$$){$cb$$(null,$count$$<100)},function($callback$$){getNextSequence($obj$$.id_app,$listinfo_code$$||$ctrl$$.name,"so_ct",function($e$$,$rs$$){if($e$$)return $callback$$($e$$);$obj$$.so_ct=$rs$$.so_ct;$checkVoucherNumber$$($error$$=>{$error$$?$count$$>=99?$callback$$($error$$):
18
+ ($count$$++,$callback$$()):($count$$=99999,$callback$$())})},$obj$$)},function($err$$){$callback$$($err$$)})}else $callback$$()})},function($callback$$){setImmediate(async()=>{if($model$$.schema.paths.ma_dvcs&&$ctrl$$.name!=="dvcs")if($obj$$.ma_dvcs)if(global.mongoose.Types.ObjectId.isValid($obj$$.ma_dvcs)){let $_id_dvcs$$=global.mongoose.Types.ObjectId($obj$$.ma_dvcs);await global.getModel("dvcs").findOne({_id:$_id_dvcs$$})?$callback$$():global.getModel("dvcs").create({_id:$_id_dvcs$$,ma_dvcs:"IMPORTED",
19
+ ten_dvcs:"Imported"},$e$$=>{setImmediate(()=>{$e$$&&Logger.error("Can't import dvcs",$e$$);$callback$$()})})}else $callback$$();else global.getModel("dvcs").findOne({id_app:$obj$$.id_app,status:!0}).lean().then(function($rs$$){setImmediate(()=>{$rs$$&&($obj$$.ma_dvcs=$rs$$._id.toString());$callback$$()})}).catch($e$$=>{Logger.error($e$$)});else $callback$$()})},$callback$$=>{$ctrl$$.validating||($ctrl$$.validating=($user$$,$obj$$,$next$$)=>{$next$$(null,$obj$$)});$ctrl$$.validating($user$$,$obj$$,
20
+ $e$$=>{if($e$$)return $callback$$($e$$);setImmediate(()=>{$obj$$.user_created=$action$$=="import"?$obj$$.user_created||$user$$.email:$user$$.email;$obj$$.user_updated=$user$$.email;$obj$$.date_created=new Date;$obj$$.date_updated=new Date;validate($obj$$,async $error$$=>{setImmediate(async()=>{if($error$$){let $msgError$$=$error$$;if($ctrl$$.options.onErrorCreating)$ctrl$$.options.onErrorCreating($user$$,$obj$$,$e$$=>{$e$$&&($msgError$$=$msgError$$+"\n"+$e$$);$callback$$($msgError$$)});else $callback$$($msgError$$)}else{if($id_be_supply_by_user$$&&
21
+ global.mongoose.Types.ObjectId.isValid($id_be_supply_by_user$$)){let $_id$$=global.mongoose.Types.ObjectId($id_be_supply_by_user$$);await $model$$.findOne({_id:$_id$$},{_id:1})||($obj$$._id=$_id$$)}$callback$$()}})},$voucher_options$$)})},{action:$action$$})},function($callback$$){isExists($model$$,$ctrl$$.unique,$obj$$,$ctrl$$.replaceIfExists,async($error$$,$kq$$)=>{setImmediate(async()=>{if($error$$||$kq$$){let $msgError$$=$error$$||ERRORS.ERR_ALREADY_EXIST;if($ctrl$$.options.onErrorCreating)$ctrl$$.options.onErrorCreating($user$$,
22
22
  $obj$$,$e$$=>{$e$$&&($msgError$$=$msgError$$+"\n"+$e$$);$callback$$({error:$msgError$$,code:ERRORS.ERR_ALREADY_EXIST_CODE})});else $callback$$({error:$msgError$$,code:ERRORS.ERR_ALREADY_EXIST_CODE})}else{for(let $k$$ in $ctrl$$.keyValues)$obj$$[$k$$]=$ctrl$$.keyValues[$k$$];Object.keys($model$$.schema.paths).filter($model_path$$=>$obj$$[$model_path$$]&&_.isArray($obj$$[$model_path$$])).forEach($model_path$$=>{$model$$.schema.paths[$model_path$$].schema&&$model$$.schema.paths[$model_path$$].schema.paths&&
23
23
  Object.keys($model$$.schema.paths[$model_path$$].schema.paths).filter($path$$=>$path$$!=="line"&&$path$$!=="_id"&&$path$$!=="__v"&&fields_sync_master_detail.indexOf($path$$)>=0).forEach($path$$=>{$obj$$[$path$$]&&$obj$$[$model_path$$].filter($detail$$=>!$detail$$[$path$$]).forEach($detail$$=>{$detail$$[$path$$]=$obj$$[$path$$]})})});await createIdRef($model$$,$obj$$);if($ctrl$$.saving)try{await $ctrl$$.saving($user$$,$obj$$,$action$$)}catch($e$$){return $callback$$({error:$e$$.message||$e$$.error||
24
24
  $e$$})}$ctrl$$.emit("saving",$obj$$);$obj$$.save(function($error$$,$obj_created$$){setImmediate(async()=>{if($error$$){if($ctrl$$.options.onErrorSave)$ctrl$$.options.onErrorSave($user$$,$obj$$,$error$$,$action$$);let $msgErrors$$=[];for(let $k$$ in $error$$.errors)$msgErrors$$.push($error$$.errors[$k$$].message);$msgErrors$$.length==0&&($msgErrors$$=$error$$.message);$msgErrors$$||=JSON.stringify($error$$);if($ctrl$$.options.onErrorCreating)$ctrl$$.options.onErrorCreating($user$$,$obj$$,$e$$=>{$e$$&&
25
25
  Logger.error("onErrorCreating",$e$$);$callback$$($msgErrors$$)});else $callback$$($msgErrors$$)}else $ctrl$$.populate&&($obj_created$$=$model$$.findById($obj_created$$._id).inTxn(),$obj_created$$=await $ctrl$$.populate($obj_created$$)),postData($obj_created$$,$ctrl$$,function($msgErrors$$){if($msgErrors$$)if($ctrl$$.options.onErrorCreating)$ctrl$$.options.onErrorCreating($user$$,$obj$$,$e$$=>{$e$$&&($msgErrors$$=$msgErrors$$+"\n"+$e$$);$callback$$($msgErrors$$)});else $callback$$($msgErrors$$);else{const $obj_created_cv$$=
26
26
  convertObjectIdsToStrings($obj_created$$.toObject());onAfterCommit(async()=>{$ctrl$$.emit("saved",$obj_created$$);$ctrl$$.emit("created",$obj_created$$);global.getModel("customer").updateActives&&global.getModel("customer").updateActives($obj_created$$);$req$$&&setImmediate(()=>{global.getModel("log").create({id_app:$user$$.current_id_app,id_func:$ctrl$$.name,action:$action$$.toUpperCase(),data:{id:$obj_created_cv$$._id.toString(),data:$obj_created_cv$$}},$user$$.email,$req$$.user_agent,$req$$)});
27
- runWebhooks($ctrl$$,$obj_created_cv$$,$action$$.toUpperCase(),$voucher_options$$);await $ctrl$$.cacheData($obj_created_cv$$,void 0,$action$$)});$callback$$(null,$obj_created_cv$$)}},{req:$req$$})})})}})})})},function($obj$$,$callback$$){setImmediate(async function(){let $co_gia_tri_tam$$=!1;$obj$$.exfields&&$obj$$.exfields.__files__&&($obj$$.exfields.__files__.forEach($_file$$=>{$File$$.updateOne({_id:$_file$$._id},{id_link:$obj$$._id.toString(),collection_link:$ctrl$$.collection_name}).lean().then(()=>
28
- {}).catch($e$$=>{Logger.error("File updateone",$e$$)})}),delete $obj$$.exfields.__files__,$co_gia_tri_tam$$=!0);$obj$$.exfields&&$obj$$.exfields.__supports__&&($obj$$.exfields.__supports__.forEach($_file$$=>{$Support$$.updateOne({_id:$_file$$._id},{id_link:$obj$$._id.toString(),collection_link:$ctrl$$.collection_name}).lean().then(()=>{})}).catch($e$$=>{Logger.error("support updateone",$e$$)}),delete $obj$$.exfields.__supports__,$co_gia_tri_tam$$=!0);$co_gia_tri_tam$$&&await $model$$.updateOne({_id:$obj$$._id},
29
- {exfields:$obj$$.exfields});$ctrl$$.created?$ctrl$$.created($user$$,$obj$$,function($error$$,$rs$$){setImmediate(()=>{if($error$$)return $callback$$($error$$);$ctrl$$.dynamicCreated?$ctrl$$.dynamicCreated($user$$,$rs$$,function($error$$){if($error$$)return $callback$$($error$$);$callback$$(null,$rs$$)},{listinfo_code:$listinfo_code$$}):$callback$$(null,$rs$$)})}):$ctrl$$.dynamicCreated?$ctrl$$.dynamicCreated($user$$,$obj$$,function($error$$){if($error$$)return $callback$$($error$$);$callback$$(null,
30
- $obj$$)},{listinfo_code:$listinfo_code$$}):$callback$$(null,$obj$$)})},function($obj$$,$callback$$){$ctrl$$.requestApprove($user$$.current_app_info,$user$$,$obj$$,$callback$$,$voucher_options$$)},function($obj_created_cv$$,$callback$$){$action$$==="import"||$req$$&&($req$$.query||{}).return_data==0?$callback$$(null,{_id:$obj_created_cv$$._id.toString()}):($obj_created_cv$$.collection_name=$ctrl$$.collection_name,$ctrl$$.onView($user$$,[$obj_created_cv$$],($error$jscomp$13_html_rs$$,$viewValues$$)=>
31
- {if($error$jscomp$13_html_rs$$)return $callback$$($error$jscomp$13_html_rs$$);$error$jscomp$13_html_rs$$=$viewValues$$?$viewValues$$[0]:$obj_created_cv$$;$req$$&&$req$$.uploadFile?($error$jscomp$13_html_rs$$="<html><title>OK</title><body>"+JSON.stringify($error$jscomp$13_html_rs$$)+"</body></html>",$callback$$(null,$error$jscomp$13_html_rs$$)):$callback$$(null,$error$jscomp$13_html_rs$$)},{req:$req$$}))}],($e$$,$obj_created$$)=>{$e$$?(Logger.error($e$$),$callback$$($e$$)):($e$$=$model$$.collection.name,
32
- $user$$.current_id_app&&($e$$+=$user$$.current_id_app),delete global.cacheDatas[$e$$],$callback$$(null,{obj_created:$obj_created$$}))})}catch($e$$){Logger.error($e$$),$callback$$($e$$)}},createHandlerAsync=($ctrl$$,$req$$)=>new Promise(($resolve$$,$reject$$)=>{createHandler($ctrl$$,$req$$,($e$$,$rs$$)=>{if($e$$)return $reject$$($e$$);$resolve$$($rs$$)})}),withSesssion=async($ctrl$$,$req$$,$callback$$)=>{try{const $rs$$=await executeInTransaction(async()=>createHandlerAsync($ctrl$$,$req$$));$callback$$(null,
33
- $rs$$)}catch($e$$){$callback$$($e$$)}};module.exports=withSesssion;module.exports.createHandler=createHandler;
27
+ runWebhooks($ctrl$$,$obj_created_cv$$,$action$$.toUpperCase(),$voucher_options$$);await $ctrl$$.cacheData($obj_created_cv$$,void 0,$action$$)});$callback$$(null,$obj_created_cv$$)}},{req:$req$$})})})}})})},function($obj$$,$callback$$){setImmediate(async()=>{let $co_gia_tri_tam$$=!1;if($obj$$.exfields&&$obj$$.exfields.__files__){for(let $_file$$ of $obj$$.exfields.__files__)await $File$$.updateOne({_id:$_file$$._id},{id_link:$obj$$._id.toString(),collection_link:$ctrl$$.collection_name});delete $obj$$.exfields.__files__;
28
+ $co_gia_tri_tam$$=!0}if($obj$$.exfields&&$obj$$.exfields.__supports__){for(let $_support$$ of $obj$$.exfields.__supports__)await $Support$$.updateOne({_id:$_support$$._id},{id_link:$obj$$._id.toString(),collection_link:$ctrl$$.collection_name});delete $obj$$.exfields.__supports__;$co_gia_tri_tam$$=!0}$co_gia_tri_tam$$&&await $model$$.updateOne({_id:$obj$$._id},{exfields:$obj$$.exfields});$ctrl$$.created?$ctrl$$.created($user$$,$obj$$,function($error$$,$rs$$){if($error$$)return $callback$$($error$$);
29
+ $ctrl$$.dynamicCreated?$ctrl$$.dynamicCreated($user$$,$rs$$,function($error$$){if($error$$)return $callback$$($error$$);$callback$$(null,$rs$$)},{listinfo_code:$listinfo_code$$}):$callback$$(null,$rs$$)}):$ctrl$$.dynamicCreated?$ctrl$$.dynamicCreated($user$$,$obj$$,function($error$$){if($error$$)return $callback$$($error$$);$callback$$(null,$obj$$)},{listinfo_code:$listinfo_code$$}):$callback$$(null,$obj$$)})},function($obj$$,$callback$$){$ctrl$$.requestApprove($user$$.current_app_info,$user$$,$obj$$,
30
+ $callback$$,$voucher_options$$)},function($obj_created_cv$$,$callback$$){$action$$==="import"||$req$$&&($req$$.query||{}).return_data==0?$callback$$(null,{_id:$obj_created_cv$$._id.toString()}):($obj_created_cv$$.collection_name=$ctrl$$.collection_name,$ctrl$$.onView($user$$,[$obj_created_cv$$],($error$jscomp$13_html_rs$$,$viewValues$$)=>{if($error$jscomp$13_html_rs$$)return $callback$$($error$jscomp$13_html_rs$$);$error$jscomp$13_html_rs$$=$viewValues$$?$viewValues$$[0]:$obj_created_cv$$;$req$$&&
31
+ $req$$.uploadFile?($error$jscomp$13_html_rs$$="<html><title>OK</title><body>"+JSON.stringify($error$jscomp$13_html_rs$$)+"</body></html>",$callback$$(null,$error$jscomp$13_html_rs$$)):$callback$$(null,$error$jscomp$13_html_rs$$)},{req:$req$$}))}],($e$$,$obj_created$$)=>{$e$$?(Logger.error($e$$),$callback$$($e$$)):($e$$=$model$$.collection.name,$user$$.current_id_app&&($e$$+=$user$$.current_id_app),delete global.cacheDatas[$e$$],$callback$$(null,{obj_created:$obj_created$$}))})}catch($e$$){Logger.error("[createHanlder]",
32
+ $ctrl$$.name,$e$$),$callback$$($e$$)}},createHandlerAsync=($ctrl$$,$req$$)=>new Promise(($resolve$$,$reject$$)=>{createHandler($ctrl$$,$req$$,($e$$,$rs$$)=>{if($e$$)return $reject$$($e$$);$resolve$$($rs$$)})}),withSesssion=async($ctrl$$,$req$$,$callback$$)=>{try{const $rs$$=await executeInTransaction(async()=>createHandlerAsync($ctrl$$,$req$$));$callback$$(null,$rs$$)}catch($e$$){$callback$$($e$$)}};module.exports=withSesssion;module.exports.createHandler=createHandler;
@@ -36,5 +36,5 @@ $callback$$(null,$obj$$)}):$callback$$(null,$obj$$)},$current_obj$$):$ctrl$$.dyn
36
36
  setImmediate(async()=>{let $approve_data$$;$obj$$.trang_thai!=void 0&&($approve_data$$=await global.getModel("approve").findOne({id_ct:$obj_created_cv$$._id.toString(),"update_after_approve.data.trang_thai":$obj_created_cv$$.trang_thai.toString()}).lean(),!$approve_data$$||$approve_data$$.user_approved||$approve_data$$.user_denied?$approve_data$$=null:($approve_data$$.user_approved=$req$$.user.email,$approve_data$$.user_approved_name=$req$$.user.name,$approve_data$$.date_approved=new Date,await global.getModel("approve").updateOne({_id:$approve_data$$._id},
37
37
  $approve_data$$)));$req$$&&$_action$$!="import"&&$req$$.query.return_data!==!1?($obj_created_cv$$.collection_name=$ctrl$$.collection_name,(await permission.getFieldNotRight($obj_created_cv$$.id_app,$user$$.email,$ctrl$$.name)).forEach($f$$=>{delete $obj_created_cv$$[$f$$]}),$ctrl$$.onView($user$$,[$obj_created_cv$$],function($error$$,$viewValue$$){setImmediate(()=>{if($error$$)return $callback$$($error$$);$approve_data$$&&onAfterCommit(async()=>{global.getModel("approve").sendNotifyApproved($approve_data$$,
38
38
  $req$$.query.access_token);let $channel$$=`${$ctrl$$.name.toLowerCase()}-${"request_approved"}`;$obj$$.id_app&&($channel$$=`${$channel$$}-${$obj$$.id_app}`);let $message$$=JSON.stringify($viewValue$$[0]);try{await global.clientRedis.publish($channel$$,$message$$)}catch($e$$){Logger.error("[approve] [sendNotifyApproved] fire event","request_approved",$e$$)}});$callback$$(null,$viewValue$$[0])})},{req:$req$$})):(Logger.info("[updateHanlder] tr\u1ea3 v\u1ec1 k\u1ebft qu\u1ea3 sau khi import..."),$callback$$(null,
39
- {_id:$obj_created_cv$$._id}))})}],($e$$,$rs$$)=>{$e$$?(Logger.error($e$$),$callback$$($e$$)):($e$$=$model$$.collection.name,$user$$.current_id_app&&($e$$+=$user$$.current_id_app),delete global.cacheDatas[$e$$],$callback$$(null,{new_obj:$rs$$,old_obj:$current_obj$$}))})}catch($e$$){Logger.error($e$$),$callback$$($e$$)}},updateHandlerAsync=($ctrl$$,$req$$)=>new Promise(($resolve$$,$reject$$)=>{updateHandler($ctrl$$,$req$$,($e$$,$rs$$)=>{if($e$$)return $reject$$($e$$);$resolve$$($rs$$)})}),withSesssion=
40
- async($ctrl$$,$req$$,$callback$$)=>{try{const $rs$$=await executeInTransaction(async()=>updateHandlerAsync($ctrl$$,$req$$));$callback$$(null,$rs$$)}catch($e$$){$callback$$($e$$)}};module.exports=withSesssion;module.exports.updateHandler=updateHandler;
39
+ {_id:$obj_created_cv$$._id}))})}],($e$$,$rs$$)=>{$e$$?(Logger.error($e$$),$callback$$($e$$)):($e$$=$model$$.collection.name,$user$$.current_id_app&&($e$$+=$user$$.current_id_app),delete global.cacheDatas[$e$$],$callback$$(null,{new_obj:$rs$$,old_obj:$current_obj$$}))})}catch($e$$){Logger.error("[updateHanlder]",$ctrl$$.name,$e$$),$callback$$($e$$)}},updateHandlerAsync=($ctrl$$,$req$$)=>new Promise(($resolve$$,$reject$$)=>{updateHandler($ctrl$$,$req$$,($e$$,$rs$$)=>{if($e$$)return $reject$$($e$$);
40
+ $resolve$$($rs$$)})}),withSesssion=async($ctrl$$,$req$$,$callback$$)=>{try{const $rs$$=await executeInTransaction(async()=>updateHandlerAsync($ctrl$$,$req$$));$callback$$(null,$rs$$)}catch($e$$){$callback$$($e$$)}};module.exports=withSesssion;module.exports.updateHandler=updateHandler;
package/server/global.js CHANGED
@@ -3,9 +3,9 @@ function globalListinfoCodePlugin($schema$$){$schema$$.path("listinfo_code")||$s
3
3
  global.socketContainer={loadConnectionId:async()=>new Promise($res$$=>{global.clientRedis.get("client-io",function($err$$,$reply$$){if($err$$)return console.error($err$$),$res$$({});if($reply$$)try{let $ios$$=JSON.parse($reply$$);return $res$$($ios$$||{})}catch($e$$){return console.error($e$$),$res$$({})}else return $res$$({})})}),saveConnectionId:async($clientIO$$={})=>new Promise(($res$$,$rej$$)=>{global.clientRedis.set("client-io",JSON.stringify($clientIO$$),$e$$=>{if($e$$)return console.error($e$$),
4
4
  $rej$$($e$$);$res$$($clientIO$$)})})};global.clientIO={};global.model_books="socai socaitmp socainpp vsocai sokho sokhott sokhonpp sokhokhongton sosanxuat vatvao vatra phucap".split(" ");global.secu_models="asskey assproduct assperiod assinvestment asssell assbuy assneedtobuy asswithdraw asscashwithdraw wallet assfindhash assbank asstransaction assissue token tokens user app listinfo right otp payload usergroup smsaccount emailaccount".split(" ");global.webPush=require("web-push");
5
5
  global.mongoose=require("mongoose");require("./libs/mongoosePatch.js");global.mongoose.plugin(leanID);global.mongoose.plugin(deletePost);global.mongoose.plugin(globalListinfoCodePlugin);global.mongoose.plugin(function($schema$$){$schema$$.set("versionKey",!1)});global.Schema=global.mongoose.Schema;
6
- global.getModel=$model_name$$=>{$model_name$$=$model_name$$.split(".js")[0];$model_name$$==="kbmpttct"&&($model_name$$="kbmPttct");$model_name$$==="kbmtkgtgt"&&($model_name$$="kbmTkgtgt");$model_name$$==="token"&&($model_name$$="tokens");$model_name$$==="bn1"&&($model_name$$="pc1");$model_name$$==="bc1"&&($model_name$$="pt1");var $_requireFields_model_model_path_mySchema$$=mongoose.models[$model_name$$];if($_requireFields_model_model_path_mySchema$$)return $_requireFields_model_model_path_mySchema$$;
7
- if(((global.configs||{}).paths||{}).models&&($_requireFields_model_model_path_mySchema$$=((global.configs||{}).paths||{}).models+"/"+$model_name$$+".js",fs.existsSync($_requireFields_model_model_path_mySchema$$)))return require($_requireFields_model_model_path_mySchema$$);$_requireFields_model_model_path_mySchema$$=__dirname+"/models/"+$model_name$$+".js";if(fs.existsSync($_requireFields_model_model_path_mySchema$$))return require($_requireFields_model_model_path_mySchema$$);console.error("model",
8
- $model_name$$,"is not exists. create new model");$_requireFields_model_model_path_mySchema$$={...require("./models/listinfo").requireFields};$_requireFields_model_model_path_mySchema$$=new global.Schema($_requireFields_model_model_path_mySchema$$,{strict:!1});return global.mongoose.model($model_name$$,$_requireFields_model_model_path_mySchema$$)};global.getLib=$lib_name$$=>require("./libs/"+$lib_name$$);
6
+ global.getModel=$model_name_name$$=>{$model_name_name$$=$model_name_name$$.split(".js")[0];var $_requireFields_manualMap_model_model_path_mySchema$$={kbmpttct:"kbmPttct",kbmtkgtgt:"kbmTkgtgt",token:"tokens",bn1:"pc1",bc1:"pt1"};$_requireFields_manualMap_model_model_path_mySchema$$[$model_name_name$$]&&($model_name_name$$=$_requireFields_manualMap_model_model_path_mySchema$$[$model_name_name$$]);if($_requireFields_manualMap_model_model_path_mySchema$$=mongoose.models[$model_name_name$$])return $_requireFields_manualMap_model_model_path_mySchema$$;
7
+ if(((global.configs||{}).paths||{}).models&&($_requireFields_manualMap_model_model_path_mySchema$$=((global.configs||{}).paths||{}).models+"/"+$model_name_name$$+".js",fs.existsSync($_requireFields_manualMap_model_model_path_mySchema$$)))return require($_requireFields_manualMap_model_model_path_mySchema$$);$_requireFields_manualMap_model_model_path_mySchema$$=__dirname+"/models/"+$model_name_name$$+".js";if(fs.existsSync($_requireFields_manualMap_model_model_path_mySchema$$))return require($_requireFields_manualMap_model_model_path_mySchema$$);
8
+ console.error("model",$model_name_name$$,"is not exists. create new model");$_requireFields_manualMap_model_model_path_mySchema$$={...require("./models/listinfo").requireFields};$_requireFields_manualMap_model_model_path_mySchema$$=new global.Schema($_requireFields_manualMap_model_model_path_mySchema$$,{strict:!1});return global.mongoose.model($model_name_name$$,$_requireFields_manualMap_model_model_path_mySchema$$)};global.getLib=$lib_name$$=>require("./libs/"+$lib_name$$);
9
9
  const pointSchema=new global.mongoose.Schema({type:{type:String,enum:["Point"],required:!0,default:"Point"},coordinates:{type:[Number],required:!0}}),polygonSchema=new global.mongoose.Schema({type:{type:String,enum:["Polygon"],required:!0,default:"Polygon"},coordinates:{type:[[[Number]]],required:!0}});global.customTypes={Point:pointSchema,Polygon:polygonSchema};const EventEmitter=require("events");class GlobalEmitter extends EventEmitter{}global.globalEvents=new GlobalEmitter;
10
10
  global.getSysConfig=async $cf_code$$=>{if($cf_code$$=await global.getModel("sysconfig").findOne({code:$cf_code$$}))return $cf_code$$.value};global.asyncCountUnRead=async $email$$=>{const $Message$$=global.getModel("message");return new Promise($resolve$$=>{setImmediate(()=>{$Message$$.countDocuments({email:$email$$,read:!1},($e$$,$rs$$)=>{$resolve$$($rs$$||0)})})})};
11
11
  global.alertMessage=function($email$$){onAfterCommit(()=>{const $Message$$=global.getModel("message"),$User$$=global.getModel("user");$Message$$.countDocuments({email_owner:$email$$,email_receiver:$email$$,read:!1},function($error$$,$count$$){$error$$?console.log($error$$):$User$$.emitEvent($email$$,"message:count",$count$$,!1)})})};
@@ -1,9 +1,9 @@
1
1
  const fs=require("fs"),path=require("path"),async=require("async"),parameter_model=global.getModel("parameter"),rpt_model=global.getModel("rpt"),app=global.getModel("app"),parameter=require("../data/parameter"),rpt=require("../data/rpt"),utils=require("./utils"),Logger=require("./logger.js");
2
- exports.init=async function($id_app$$,$fn$$){let $_app$$=await app.findOne({_id:$id_app$$}).lean();if(!$_app$$)return $fn$$("C\u00f4ng ty kh\u00f4ng t\u1ed3n t\u1ea1i");Logger.info("[initDatabase] kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u cho c\u00f4ng ty",$_app$$.name);var $data_init_dir_files$$=($_app$$.options||{}).data_init_dir||"data";$data_init_dir_files$$=fs.readdirSync(path.dirname(__dirname)+"/"+$data_init_dir_files$$);async.mapSeries($data_init_dir_files$$,function($file$$,$callback$$){if($file$$.substr(-3)==
3
- ".js"){const $data$$=JSON.parse(JSON.stringify(require("../data/"+$file$$).data)),$model$$=global.getModel(""+$file$$);Logger.info("[initDatabase] kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u ",$file$$);setImmediate(async()=>{try{const $rows$$=$data$$.map($r$$=>{$r$$.id_app=$id_app$$;$r$$._id&&delete $r$$._id;return $r$$});await $model$$.create($rows$$);$callback$$()}catch($e$$){Logger.error("[initDatabase] kh\u00f4ng th\u1ec3 kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u",$file$$,$e$$),$callback$$()}})}else $callback$$()},
4
- async function($error$$){if($error$$)return $fn$$($error$$);if($_app$$.menu_code){Logger.info("[initDatabase] kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u t\u1eeb menuinfo",app.name,$_app$$.menu_code);let $menuinfo$$=await global.getModel("menuinfo").findOne({code:$_app$$.menu_code}).lean();$menuinfo$$&&$menuinfo$$.default_datas&&await new Promise($rs$$=>{async.mapSeries($menuinfo$$.default_datas.filter($d$$=>$d$$.data&&$d$$.api_code),($d$$,$callback$$)=>{setImmediate(async()=>{try{let $data$$=utils.JSONParser($d$$.data);
5
- const $model$$=global.getModel($d$$.api_code);Logger.info("[initDatabase] kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u",$d$$.api_code);await $model$$.deleteMany({id_app:$id_app$$});const $rows$$=$data$$.map($r$$=>{$r$$.id_app=$id_app$$;$r$$._id&&delete $r$$._id;return $r$$});await $model$$.create($rows$$);$callback$$()}catch($e$$){Logger.error("[initDatabase] kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u",$d$$.api_code,$e$$),$callback$$()}})},()=>{$rs$$()})})}Logger.info("[initDatabase] kh\u1edfi t\u1ea1o m\u1eabu b\u00e1o c\u00e1o cho c\u00f4ng ty",
6
- app.name);rpt_model.find({id_app:$id_app$$}).lean().then(function($rpts$$){$rpts$$.forEach(function($rpt$$){parameter_model.update({id_rpt:$rpt$$._id_o,id_app:$id_app$$},{id_rpt:$rpt$$._id},{multi:!0},function($e$$){$e$$&&Logger.info($e$$)})})}).catch($e$$=>{Logger.error($e$$)});Logger.info("[initDatabase] \u0110\u00e3 kh\u1edfi t\u1ea1o xong d\u1eef li\u1ec7u cho c\u00f4ng ty",app.name);$fn$$()})};
2
+ exports.init=async function($id_app$$,$fn$$){let $_app$$=await app.findOne({_id:$id_app$$}).inTxn().lean();if(!$_app$$)return $fn$$("C\u00f4ng ty kh\u00f4ng t\u1ed3n t\u1ea1i");Logger.info("[initDatabase] kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u cho c\u00f4ng ty",$_app$$.name);var $data_data_init_dir_files$$=($_app$$.options||{}).data_init_dir||"data";$data_data_init_dir_files$$=fs.readdirSync(path.dirname(__dirname)+"/"+$data_data_init_dir_files$$);for(var $file_menuinfo$$ of $data_data_init_dir_files$$)if($file_menuinfo$$.substring(-3)==
3
+ ".js"){$data_data_init_dir_files$$=JSON.parse(JSON.stringify(require("../data/"+$file_menuinfo$$).data));const $model$$=global.getModel(""+$file_menuinfo$$);Logger.warn("[initDatabase] \u0111ang kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u ",$file_menuinfo$$,"....");try{const $rows$$=$data_data_init_dir_files$$.map($r$$=>{$r$$.id_app=$id_app$$;$r$$._id&&delete $r$$._id;return $r$$});await $model$$.create($rows$$)}catch($e$$){return Logger.error("[initDatabase] L\u1ed7i kh\u00f4ng th\u1ec3 kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u",
4
+ $file_menuinfo$$,$e$$),$fn$$($e$$)}}if($_app$$.menu_code&&(Logger.warn("[initDatabase] kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u t\u1eeb menuinfo",$_app$$.name,$_app$$.menu_code),($file_menuinfo$$=await global.getModel("menuinfo").findOne({code:$_app$$.menu_code}).lean())&&$file_menuinfo$$.default_datas))for(var $d_rpts$$ of $file_menuinfo$$.default_datas.filter($d$$=>$d$$.data&&$d$$.api_code))try{let $data$$=utils.JSONParser($d_rpts$$.data);const $model$$=global.getModel($d_rpts$$.api_code);Logger.warn("[initDatabase] \u0111ang kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u",
5
+ $d_rpts$$.api_code,"....");Logger.warn("[initDatabase] \u0111ang xo\u00e1 d\u1eef li\u1ec7u c\u0169",$d_rpts$$.api_code,"....");await $model$$.deleteMany({id_app:$id_app$$});Logger.warn("[initDatabase] \u0111ang t\u1ea1o d\u1eef li\u1ec7u m\u1edbi",$d_rpts$$.api_code,"....");const $rows$$=$data$$.map($r$$=>{$r$$.id_app=$id_app$$;$r$$._id&&delete $r$$._id;return $r$$});await $model$$.create($rows$$)}catch($e$$){return Logger.error("[initDatabase] L\u1ed7i kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u",$d_rpts$$.api_code,
6
+ $e$$),$fn$$($e$$)}Logger.warn("[initDatabase] kh\u1edfi t\u1ea1o m\u1eabu b\u00e1o c\u00e1o cho c\u00f4ng ty",$_app$$.name);$d_rpts$$=await rpt_model.find({id_app:$id_app$$}).inTxn().lean();for(let $rpt$$ of $d_rpts$$)await parameter_model.update({id_rpt:$rpt$$._id_o,id_app:$id_app$$},{id_rpt:$rpt$$._id},{multi:!0});Logger.warn("[initDatabase] \u0110\u00e3 kh\u1edfi t\u1ea1o xong d\u1eef li\u1ec7u cho c\u00f4ng ty",$_app$$.name);$fn$$()};
7
7
  exports.initRpt=function(){app.find({}).lean().then(function($apps$$){$apps$$.forEach(function($a$$){async.series({r:function($callback$$){let $rpt_data$$=JSON.parse(JSON.stringify(rpt.data));async.mapSeries($rpt_data$$,function($r$$,$callback$$){$r$$.id_app=$a$$._id;rpt_model.create($r$$,function($error$$){if($error$$)return $callback$$($error$$);$callback$$()})},function($error$$,$rs$$){$callback$$($error$$,$rs$$)})},p:function($callback$$){async.mapSeries(parameter.data,function($r$$,$callback$$){$r$$.id_app=
8
8
  $a$$._id;parameter_model.create($r$$,function($error$$){if($error$$)return $callback$$($error$$);$callback$$()})},function($error$$,$rs$$){$callback$$($error$$,$rs$$)})}},function($e$$){if($e$$)return Logger.info($e$$);rpt_model.find({id_app:$a$$._id}).lean().then(function($rpts$$){$rpts$$.forEach(function($rpt$$){parameter_model.update({id_rpt:$rpt$$._id_o,id_app:$a$$._id},{id_rpt:$rpt$$._id},{multi:!0},function($e$$){$e$$&&Logger.info($e$$)})})}).catch($e$$=>{Logger.error($e$$)})})})}).catch($e$$=>
9
9
  {Logger.error($e$$)})};
@@ -1,6 +1,6 @@
1
1
  /*
2
2
  Prevent Closure Compiler rename this file */
3
- const {AsyncLocalStorage}=require("node:async_hooks"),storage=new AsyncLocalStorage;exports.storage=storage;global.SESSION_STORE_MAP=new Map;exports.getCurrentStore=function(){return storage.getStore()};const SESSION_EXCLUDE_MODELS="app log counter dmqct token trangthai trangthaiapp otp cache notification email tontucthoi listinfo reportinfo options labelinfo dmqddvt".split(" ");let globalStoreCounter=0,globalSessionCounter=0;
3
+ const {AsyncLocalStorage}=require("node:async_hooks"),storage=new AsyncLocalStorage;exports.storage=storage;global.SESSION_STORE_MAP=new Map;exports.getCurrentStore=function(){return storage.getStore()};const SESSION_EXCLUDE_MODELS="log token trangthai trangthaiapp otp cache notification email tontucthoi listinfo reportinfo options labelinfo dmqddvt".split(" ");let globalStoreCounter=0,globalSessionCounter=0;
4
4
  exports.runWithSession=async function($session$$,$fn$$){if(!$session$$)throw Error("Session kh\u00f4ng t\u1ed3n t\u1ea1i");if(exports.getCurrentStore())return $fn$$();const $storeId$$=++globalStoreCounter,$sessionId$$=$session$$?._debugId||`txn-${++globalSessionCounter}`;$session$$&&!$session$$._debugId&&($session$$._debugId=$sessionId$$);Logger.info(`[runWithSession] start storeId=${$storeId$$}, sessionId=${$sessionId$$}, ctrl=${$session$$?.ctrl_name}`);return storage.run({session:$session$$,storeId:$storeId$$,
5
5
  sessionId:$sessionId$$},async()=>await $fn$$())};
6
6
  exports.handlerWithSession=async function($handler$$,$ctrl$$,$req$$,$callback$$,...$extraArgs$$){let $attempt$$=0;for(;$attempt$$<3;){const $session$$=await mongoose.startSession();$session$$.ctrl_name=$ctrl$$.name;let $afterCommitCallbacks$$=[],$storeId_for_log$$="unknown";var $err_transactionResult$$=null;try{$err_transactionResult$$=await exports.runWithSession($session$$,()=>{const $label_time$$=`\u2705 Th\u1eddi gian ch\u1ea1y session ${$session$$._debugId}:`;console.time($label_time$$);$storeId_for_log$$=
@@ -1,5 +1,5 @@
1
- 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");
2
- 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}
1
+ 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;
2
+ $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}
3
3
  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$$]:
4
4
  $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;
5
5
  function JSONParser($str_func$$){if(typeof $str_func$$=="object")return $str_func$$;$str_func$$.toString().indexOf("return ")<0&&($str_func$$="return "+$str_func$$);return evalute($str_func$$)}exports.JSONParser=JSONParser;
@@ -44,9 +44,9 @@ const aggregate=async($model_name$jscomp$2_rs$$,$id_app$$,$stages$$=[])=>{if(glo
44
44
  const base64toJSON=$b$$=>{$b$$=Buffer.from($b$$,"base64");return xml2json($b$$.toString("utf8"))};exports.base64toJSON=base64toJSON;const isMobilePhone=($str$$,$locale$$)=>$str$$&&$str$$.toString().trim()?/^\d+$/.test($str$$):!1;exports.isMobilePhone=isMobilePhone;const generatePasswordHash=function($password$$){return crypto.createHash("sha256").update($password$$+":STP").digest("hex")};exports.generatePasswordHash=generatePasswordHash;
45
45
  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()?
46
46
  $_app_ngay_ks$$:!1}exports.isBookLocked=isBookLocked;
47
- const isImpossibleQuery=$condition$$=>$condition$$?Object.keys($condition$$).some($key$$=>($key$$=$condition$$[$key$$])&&$key$$.$in&&Array.isArray($key$$.$in)&&$key$$.$in.length===0||Array.isArray($key$$)&&$key$$.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$$)?
48
- $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:",
49
- $error$$),$error$$;}};exports.sumByCondition=sumByCondition;
47
+ 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$$:
48
+ [$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$$=
49
+ {};$fieldsArray$$.forEach($f$$=>$zeroResult$$[$f$$]=0);return $zeroResult$$}return $result$$[0]}catch($error$$){throw console.error("[sumByCondition] Error:",$error$$),$error$$;}};exports.sumByCondition=sumByCondition;
50
50
  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$$=
51
51
  $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}),{})}];
52
52
  return await $Model$$.aggregate($pipeline$$)}catch($error$$){throw console.error("[groupByCondition] Error:",$error$$),$error$$;}};exports.groupByCondition=groupByCondition;
@@ -2,9 +2,9 @@ const Moment=require("moment"),fs=require("fs"),path=require("path"),app=require
2
2
  $data_schedule$$,$e$$);return}if($data_schedule$$&&$data_schedule$$.users_will_receive&&$data_schedule$$.title){var $notificationData$$={_id:$data_schedule$$._id,trang_thai:$data_schedule$$.trang_thai,id_app:$data_schedule$$.id_app,title:$data_schedule$$.title,body:$data_schedule$$.body,code:$data_schedule$$.ma_ct||$data_schedule$$.code,event:$data_schedule$$.event||"reminder",action:($data_schedule$$.event||"reminder").toUpperCase()};app.emitEvent($data_schedule$$.id_app,$data_schedule$$.event,$notificationData$$,
3
3
  null,$data_schedule$$.users_will_receive,!0)}},updateData:async $module_name_schedule$$=>{let $data$$=$module_name_schedule$$.data;_.isString($data$$)&&($data$$=JSON.parse($data$$));if($data$$&&$data$$._id&&global.mongoose.Types.ObjectId.isValid($data$$._id)&&($module_name_schedule$$=$data$$.module||$data$$.model)&&!(["token","tokens","user","asskey"].indexOf($module_name_schedule$$.toLowerCase())>=0)){var $module$$=global.controllers[$module_name_schedule$$.toUpperCase()];if($module$$){let $_model$$=
4
4
  $module$$.model||global.getModel("module_name");delete $data$$.module;delete $data$$.model;try{await executeInTransaction(async()=>{await $_model$$.updateOne({id_app:$data$$.id_app,_id:$data$$._id},$data$$);let $obj$$=await $_model$$.findOne({_id:$data$$._id});await Controller.asyncPostData($obj$$,$module$$)})}catch($e$$){Logger.error("[schedule] [updateData]",$e$$)}}else Logger.error("[schedule] [updateData] module"+$data$$.module,"is not exists")}},runScript:$processPath_schedule$$=>{let $script$$=
5
- $processPath_schedule$$.script;if($script$$){$processPath_schedule$$=path.dirname(__dirname)+"/workers/runScript.js";if(!fs.existsSync($processPath_schedule$$))return Logger.error("runScript process is not exitst");if(!global.runScriptPool){const $StaticPool$$=require("../libs/WorkerStaticPool");global.runScriptPool=new $StaticPool$$($processPath_schedule$$,0,1)}return new Promise(($rs$$,$rj$$)=>{global.runScriptPool.exec({script:$script$$,configs:global.configs},$response$$=>{$response$$.error?(Logger.error($response$$.error),
6
- $rj$$($response$$.error)):(Logger.info("run script result:",$response$$),$rs$$($response$$))})})}}},scheduleSchema=new Schema({id_link:{type:String},title:{type:String,required:!0},action:{type:String,required:!0},data:{type:Schema.Types.Mixed},script:String,time_run:{type:Date,required:!0},repeat:{type:Number,default:0},next_run:Date,finish_run:Date,trang_thai:{type:String,default:"0"},exfields:Schema.Types.Mixed,status:{type:Boolean,default:!0},date_created:{type:Date,default:Date.now},date_updated:{type:Date,
7
- default:Date.now},user_created:{type:String,default:""},user_updated:{type:String,default:""}});(global.configs||{}).createIndexes&&(scheduleSchema.index({trang_thai:1}),scheduleSchema.index({time_run:1}),scheduleSchema.index({action:1}),scheduleSchema.index({id_link:1}),scheduleSchema.index({title:"text"}),scheduleSchema.index({status:1}),scheduleSchema.index({user_created:1,visible_to:1,visible_to_users:1}));
5
+ $processPath_schedule$$.script;if($script$$){$processPath_schedule$$=path.dirname(__dirname)+"/workers/runScript.js";if(!fs.existsSync($processPath_schedule$$))return Logger.error("runScript process is not exitst");if(!global.runScriptPool){const $StaticPool$$=require("../libs/WorkerStaticPool");global.runScriptPool=new $StaticPool$$($processPath_schedule$$,0,1)}return new Promise(($rs$$,$rj$$)=>{global.runScriptPool.exec({script:$script$$,configs:JSON.parse(JSON.stringify(global.configs))},$response$$=>
6
+ {$response$$.error?(Logger.error($response$$.error),$rj$$($response$$.error)):(Logger.info("run script result:",$response$$),$rs$$($response$$))})})}}},scheduleSchema=new Schema({id_link:{type:String},title:{type:String,required:!0},action:{type:String,required:!0},data:{type:Schema.Types.Mixed},script:String,time_run:{type:Date,required:!0},repeat:{type:Number,default:0},next_run:Date,finish_run:Date,trang_thai:{type:String,default:"0"},exfields:Schema.Types.Mixed,status:{type:Boolean,default:!0},
7
+ date_created:{type:Date,default:Date.now},date_updated:{type:Date,default:Date.now},user_created:{type:String,default:""},user_updated:{type:String,default:""}});(global.configs||{}).createIndexes&&(scheduleSchema.index({trang_thai:1}),scheduleSchema.index({time_run:1}),scheduleSchema.index({action:1}),scheduleSchema.index({id_link:1}),scheduleSchema.index({title:"text"}),scheduleSchema.index({status:1}),scheduleSchema.index({user_created:1,visible_to:1,visible_to_users:1}));
8
8
  const model=mongoose.models.schedule||mongoose.model("schedule",scheduleSchema),redis_key="schedule_key";model.loadFromRedis=async()=>new Promise(($resolve$$,$reject$$)=>{global.clientRedis.get(redis_key,($e$$,$string_rs$$)=>{if($e$$)return $reject$$($e$$);if($string_rs$$)try{const $rs$$=JSON.parse($string_rs$$);$resolve$$($rs$$)}catch($e$$){$resolve$$([])}else $resolve$$([])})});
9
9
  model.saveToRedis=async $rs$$=>new Promise(($resolve$$,$reject$$)=>{global.clientRedis.set(redis_key,JSON.stringify($rs$$),$e$$=>{if($e$$)return $reject$$($e$$);$resolve$$()})});
10
10
  model.addSchedule=$schedule$$=>{model.create($schedule$$,async($e$$,$rs$$)=>{if($e$$)return Logger.error("error add schedule to db",$e$$);try{const $schedules$$=await model.loadFromRedis();$schedules$$.push($rs$$.toObject());await model.saveToRedis($schedules$$);Logger.info("added a schedule, time state at",$schedule$$.time_run)}catch($e$$){Logger.error("error add schedule to redis",$e$$)}})};
@@ -1,24 +1,344 @@
1
- const model=global.getModel("checkin"),customer=global.getModel("customer"),moment=require("moment"),dmnv=global.getModel("dmnv"),chamcong=global.getModel("chamcong"),User=global.getModel("user"),controller=require("../../controllers/controller"),PostBook=require("../../libs/post-book");function deg2rad($deg$$){return Math.PI/180*$deg$$}
2
- function getDistanceFromLatLonInM($a$$,$dLon_lon1$$,$lat2$$,$lon2$$){const $dLat$$=deg2rad($lat2$$-$a$$);$dLon_lon1$$=deg2rad($lon2$$-$dLon_lon1$$);$a$$=Math.sin($dLat$$/2)*Math.sin($dLat$$/2)+Math.cos(deg2rad($a$$))*Math.cos(deg2rad($lat2$$))*Math.sin($dLon_lon1$$/2)*Math.sin($dLon_lon1$$/2);return 2*Math.atan2(Math.sqrt($a$$),Math.sqrt(1-$a$$))*6371E3}
3
- const postData=async($obj$$,$callback$$)=>{if($obj$$.trang_thai!="1")return $callback$$();if(global.configs?.required_device_id&&!$obj$$.device_id)return $callback$$("C\u1ea7n th\u00f4ng tin ID c\u1ee7a thi\u1ebft b\u1ecb (device_id)");const $nv$$=await global.getModel("dmnv").findOne({id_app:$obj$$.id_app,$or:[{device_user_id:$obj$$.device_user_id},{user:$obj$$.device_user_id}]}).lean();if(!$nv$$)return $callback$$(`Ch\u01b0a khai b\u00e1o th\u00f4ng tin nh\u00e2n vi\u00ean cho '${$obj$$.device_user_id}'.`);
4
- if($nv$$.trusted_device_id){if($nv$$.trusted_device_id!=$obj$$.device_id)return $callback$$("Thi\u1ebft b\u1ecb ch\u1ea5m c\u00f4ng kh\u00f4ng h\u1ee3p l\u1ec7. B\u1ea1n c\u1ea7n d\u00f9ng thi\u1ebft b\u1ecb \u0111\u00e3 ch\u1ea5m c\u00f4ng l\u1ea7n tr\u01b0\u1edbc ho\u1eb7c li\u00ean h\u1ec7 v\u1edbi admin \u0111\u1ec3 \u0111\u0103ng k\u00fd thi\u1ebft b\u1ecb m\u1edbi.");$nv$$.trusted_device_id=$obj$$.device_id}if($obj$$.device_id){var $cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$=
5
- await global.getModel("dmnv").findOne({id_app:$obj$$.id_app,trusted_device_id:$obj$$.device_id},{_id:1}).lean();if($cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$&&$cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$._id!==$nv$$._id)return $callback$$("Thi\u1ebft b\u1ecb n\u00e0y \u0111\u00e3 \u0111\u01b0\u1ee3c s\u1eed d\u1ee5ng \u0111\u1ec3 ch\u1ea5m cho nh\u00e2n vi\u00ean kh\u00e1c. N\u1ebfu b\u1ea1n c\u1ea7n thay \u0111\u1ed5i h\u00e3y li\u00ean h\u1ec7 v\u1edbi admin.")}if($obj$$.location&&
6
- $obj$$.location.latitude&&$obj$$.location.longitude){var $candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$=null;$nv$$.ma_cn&&($candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$=await global.getModel("dmchinhanh").findOne({id_app:$obj$$.id_app,ma_cn:$nv$$.ma_cn,status:!0}).lean());if(!$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$)return $callback$$("Ch\u01b0a khai b\u00e1o chi nh\u00e1nh l\u00e0m vi\u1ec7c cho nh\u00e2n vi\u00ean n\u00e0y");
7
- if(!$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$.location||!$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$.location.latitude||!$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$.location.longitude)return $callback$$(`Ch\u01b0a khai b\u00e1o v\u1ecb tr\u00ed c\u1ee7a chi nh\u00e1nh ${$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$.ten_cn}`);$cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$=
8
- getDistanceFromLatLonInM($obj$$.location.latitude,$obj$$.location.longitude,$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$.location.latitude,$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$.location.longitude);$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$=$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$.location.allowed_radius||50;if($cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$>
9
- $candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$&&!$obj$$.ma_kh)return Logger.warn(`[CheckIn Fail] Distance: ${$cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$}m. User: ${$obj$$.device_user_id}`),$callback$$(`V\u1ecb tr\u00ed ch\u1ea5m c\u00f4ng kh\u00f4ng h\u1ee3p l\u1ec7. B\u1ea1n \u0111ang c\u00e1ch c\u00f4ng ty ${Math.round($cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$)}m (Cho ph\u00e9p: ${$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$}m).`)}else if(global.configs?.required_device_id)return $callback$$("Kh\u00f4ng x\u00e1c \u0111\u1ecbnh \u0111\u01b0\u1ee3c v\u1ecb tr\u00ed c\u1ee7a b\u1ea1n.");
10
- $cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$=await model.find({id_app:$obj$$.id_app,device_user_id:$obj$$.device_user_id,record_time:{$gte:moment($obj$$.record_time).startOf("date").toDate(),$lte:moment($obj$$.record_time).endOf("date").toDate()}}).inTxn().sort({record_time:1}).lean();let $gio_vao$$,$gio_ra$$,$ma_loai_cong$$;$cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$.length>0&&($gio_vao$$=$cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$[0].record_time);
11
- $cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$.length>1&&($gio_ra$$=$cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$[$cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$.length-1].record_time);$cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$=$gio_vao$$&&$gio_ra$$?moment($gio_ra$$).diff(moment($gio_vao$$),"hours"):0;if($gio_vao$$){$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$=moment($obj$$.record_time).day().toString();
12
- $candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$={id_app:$obj$$.id_app,status:!0,$and:[{$or:[{nhung_ngay_trong_tuan:{$exists:!1}},{nhung_ngay_trong_tuan:$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$}]},{$or:[{tong_gio_lam_den:{$gte:$cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$}},{tong_gio_lam_den:0}]},{$or:[{tong_gio_lam_tu:{$lte:$cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$}},{tong_gio_lam_tu:0}]}]};
13
- $candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$=await global.getModel("dmloaicong").find($candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$).sort({tong_gio_lam_tu:-1,ngay_cong:-1}).lean();const $getMinutesFromMidnight$$=$dateStr_m$$=>{if(!$dateStr_m$$)return null;$dateStr_m$$=moment($dateStr_m$$);return $dateStr_m$$.hours()*60+$dateStr_m$$.minutes()},$input_vao_mins$$=$getMinutesFromMidnight$$($gio_vao$$),$input_ra_mins$$=$getMinutesFromMidnight$$($gio_ra$$||
14
- $gio_vao$$);if($candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$=$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$.find($lc$$=>$lc$$.gio_vao_toi_thieu&&$getMinutesFromMidnight$$($lc$$.gio_vao_toi_thieu)<$input_vao_mins$$||$lc$$.gio_ra_toi_thieu&&$getMinutesFromMidnight$$($lc$$.gio_ra_toi_thieu)>$input_ra_mins$$?!1:!0))$ma_loai_cong$$=$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$.ma_loai_cong}$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$=
15
- $nv$$.ma_bp;$nv$$.bo_phan&&$nv$$.bo_phan.length>0&&($candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$=$nv$$.bo_phan[0].ma_bp);let $data$$=$obj$$.toObject?$obj$$.toObject():{...$obj$$};$data$$.id_checkin=$obj$$.device_user_id;$data$$.ngay=$obj$$.record_time;$data$$.ma_loai_cong=$ma_loai_cong$$||"UNKNOW";$data$$.ma_nv=$nv$$.ma_nv;$data$$.ma_bp=$candidates_chiNhanh_loaicong_ma_bp_max_radius_ngay_trong_tuan_query_loai_cong$$;delete $data$$._id;delete $data$$.trang_thai;
16
- $data$$.gio_vao=$gio_vao$$;$data$$.gio_ra=$gio_ra$$;$data$$.tong_gio_lam=$cac_lan_cham_cong_trong_ngay_distance_nv_device_id_tong_gio_lam$$;await chamcong.deleteMany({id_app:$obj$$.id_app,id_checkin:$obj$$.device_user_id,ngay:{$gte:moment($obj$$.record_time).startOf("date").toDate(),$lte:moment($obj$$.record_time).endOf("date").toDate()}});(new PostBook($obj$$,[$data$$],chamcong)).run(async($e$$,$rs$$)=>{$e$$||await global.getModel("dmnv").updateOne({_id:$nv$$._id},{trusted_device_id:$obj$$.device_id});
17
- $callback$$($e$$,$rs$$)})};
18
- module.exports=function($router$$){(new controller($router$$,model,"checkin",{notNeedRight:!0,sort:{record_time:-1},onView:async($user$$,$items$$,$next$$)=>{await $items$$.filter($item$$=>$item$$.trang_thai==="1").asyncJoinModel2($user$$.current_id_app,dmnv,{where:$item$$=>({$or:[{device_user_id:$item$$.device_user_id},{user:$item$$.device_user_id}]}),fields:["ma_nv","ten_nv","picture"]});await $items$$.filter($item$$=>$item$$.trang_thai==="2"||$item$$.trang_thai==="3").asyncJoinModel2($user$$.current_id_app,customer,
19
- {where:$item$$=>({$or:[{device_user_id:$item$$.device_user_id},{of_user:$item$$.device_user_id}]}),fields:["ma_kh","ten_kh","picture"]});await $items$$.filter($item$$=>$item$$.trang_thai==="3"&&$item$$.device_user_id2).asyncJoinModel2($user$$.current_id_app,dmnv,{where:{device_user_id2:"device_user_id"},fields:["ma_nv","ten_nv",{picture_nv:"picture"}]});await $items$$.filter($item$$=>!$item$$.picture).asyncJoinModel2(null,User,{where:{of_user:"email"},fields:["picture"]});await $items$$.filter($item$$=>
20
- !$item$$.picture).asyncJoinModel2(null,User,{where:{user:"email"},fields:["picture"]});await $items$$.filter($item$$=>$item$$.ma_kh).asyncJoinModel2($user$$.current_id_app,"customer",{where:"ma_kh",fields:["ten_kh"]});$next$$(null,$items$$)},onCreating:async($user$$,$obj$$,$next$$)=>{global.configs?.required_device_id&&$obj$$.location&&($obj$$.record_time=$user$$.email==="invncur@gmail.com"?$obj$$.record_time||new Date:new Date);await chamcong.deleteMany({id_app:$obj$$.id_app,id_checkin:$obj$$.device_user_id||
21
- $user$$.email,ngay:{$gte:moment($obj$$.record_time).startOf("date").toDate(),$lte:moment($obj$$.record_time).endOf("date").toDate()}});$next$$(null,$obj$$)},onUpdating:async($user$$,$data$$,$obj$$,$next$$)=>{$data$$.device_user_id=$obj$$.device_user_id;delete $data$$.record_time;await chamcong.deleteMany({id_app:$obj$$.id_app,id_checkin:$obj$$.device_user_id,ngay:{$gte:moment($obj$$.record_time).startOf("date").toDate(),$lte:moment($obj$$.record_time).endOf("date").toDate()}});$next$$(null,$data$$,
22
- $obj$$)},onDeleting:async($user$$,$obj$$,$next$$)=>{await chamcong.deleteMany({id_app:$obj$$.id_app,id_checkin:$obj$$.device_user_id,ngay:{$gte:moment($obj$$.record_time).startOf("date").toDate(),$lte:moment($obj$$.record_time).endOf("date").toDate()}});$next$$(null,$obj$$)},onUpdated:async($user$$,$obj$$,$next$$)=>{postData($obj$$,async $e$$=>{if($e$$)return Logger.info("l\u1ed7i l\u00fd checkin..."),await model.deleteOne({_id:$obj$$._id}),$next$$($e$$);$next$$(null,$obj$$)})},onDeleted:async($obj_post_query_checkin_user$$,
23
- $obj$$,$next$$)=>{$obj_post_query_checkin_user$$={id_app:$obj$$.id_app,device_user_id:$obj$$.device_user_id,record_time:{$gte:moment($obj$$.record_time).startOf("date").toDate(),$lte:moment($obj$$.record_time).endOf("date").toDate()}};($obj_post_query_checkin_user$$=await model.findOne($obj_post_query_checkin_user$$).lean())?postData($obj_post_query_checkin_user$$,$e$$=>{if($e$$)return $next$$($e$$);$next$$(null,$obj$$)}):$next$$(null,$obj$$)},onCreated:async($user$$,$obj$$,$next$$)=>{postData($obj$$,
24
- async $e$$=>{if($e$$)return await model.deleteOne({_id:$obj$$._id}),$next$$($e$$);$next$$(null,$obj$$)})}})).route()};
1
+ const model = global.getModel('checkin');
2
+ const customer = global.getModel('customer');
3
+ const moment = require("moment");
4
+ const dmnv = global.getModel('dmnv');
5
+ const chamcong = global.getModel('chamcong');
6
+ const User = global.getModel('user');
7
+ const controller = require('../../controllers/controller');
8
+ const PostBook = require('../../libs/post-book');
9
+
10
+ function deg2rad(deg) {
11
+ return deg * (Math.PI / 180);
12
+ }
13
+
14
+ function getDistanceFromLatLonInM(lat1, lon1, lat2, lon2) {
15
+ const R = 6371000; // Bán kính trái đất tính bằng mét
16
+ const dLat = deg2rad(lat2 - lat1);
17
+ const dLon = deg2rad(lon2 - lon1);
18
+ const a =
19
+ Math.sin(dLat / 2) * Math.sin(dLat / 2) +
20
+ Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
21
+ Math.sin(dLon / 2) * Math.sin(dLon / 2);
22
+ const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
23
+ const d = R * c; // Khoảng cách theo mét
24
+ return d;
25
+ }
26
+ const postData = async (obj,callback)=>{
27
+ if(obj.trang_thai!="1") return callback();
28
+ if(global.configs?.required_device_id && !obj.device_id) return callback("Cần thông tin ID của thiết bị (device_id)");
29
+ //Tìm nhân viên theo device_user_id
30
+ const nv = await global.getModel("dmnv").findOne({
31
+ id_app:obj.id_app,
32
+ $or:[
33
+ {device_user_id:obj.device_user_id},
34
+ {user:obj.device_user_id}
35
+ ]
36
+ }).lean();
37
+ if(!nv){
38
+ //Logger.error("Nhân viên không tồn tại",{id_app:obj.id_app,device_user_id:obj.device_user_id})
39
+ return callback(`Chưa khai báo thông tin nhân viên cho '${obj.device_user_id}'.`);
40
+ }
41
+ //Kiểm tra id thiết bị
42
+ if(nv.trusted_device_id){
43
+ if(nv.trusted_device_id!=obj.device_id){
44
+ return callback(`Thiết bị chấm công không hợp lệ. Bạn cần dùng thiết bị đã chấm công lần trước hoặc liên hệ với admin để đăng ký thiết bị mới.`);
45
+ }else{
46
+ nv.trusted_device_id = obj.device_id;
47
+ }
48
+ }
49
+ //Kiểm tra xem device_id này đã được sử dụng cho nhân viên nào khác không? nếu có thì không cho phép
50
+ if(obj.device_id){
51
+ const nv_device_id = await global.getModel("dmnv").findOne({id_app:obj.id_app,trusted_device_id:obj.device_id},{_id:1}).lean();
52
+ if(nv_device_id && nv_device_id._id!==nv._id){
53
+ return callback(`Thiết bị này đã được sử dụng để chấm cho nhân viên khác. Nếu bạn cần thay đổi hãy liên hệ với admin.`);
54
+ }
55
+ }
56
+ // Kiểm tra xem dữ liệu gửi lên có toạ độ không
57
+ if (obj.location && obj.location.latitude && obj.location.longitude) {
58
+ if (nv.ma_cn) {
59
+ //Lấy thông tin chi nhánh của nhân viên đó
60
+ let chiNhanh = await global.getModel("dmchinhanh").findOne({
61
+ id_app: obj.id_app,
62
+ ma_cn: nv.ma_cn,
63
+ status: true
64
+ }).lean();
65
+
66
+ if(!chiNhanh){
67
+ return callback("Chi nhánh làm việc không tồn tại");
68
+ }
69
+ if(!chiNhanh.location || !chiNhanh.location.latitude || !chiNhanh.location.longitude){
70
+ return callback(`Chưa khai báo vị trí của chi nhánh ${chiNhanh.ten_cn}`);
71
+ }
72
+ //Tính khoảng cách
73
+ const distance = getDistanceFromLatLonInM(
74
+ obj.location.latitude,
75
+ obj.location.longitude,
76
+ chiNhanh.location.latitude,
77
+ chiNhanh.location.longitude
78
+ );
79
+ const max_radius = chiNhanh.location.allowed_radius || 50;
80
+ if (distance > max_radius) {
81
+ // Kiểm tra nếu KHÔNG có mã khách hàng (tức là chấm công tại văn phòng nhưng bị xa)
82
+ if (!obj.ma_kh) {
83
+ Logger.warn(`[CheckIn Fail] Distance: ${distance}m. User: ${obj.device_user_id}`);
84
+ return callback(`Vị trí chấm công không hợp lệ. Bạn đang cách công ty ${Math.round(distance)}m (Cho phép: ${max_radius}m).`);
85
+ }
86
+ // Nếu có obj.ma_kh -> Hợp lệ (đi công tác/gặp khách hàng), code chạy tiếp xuống dưới...
87
+ }
88
+ }
89
+ } else {
90
+ if(global.configs?.required_device_id ) return callback("Không xác định được vị trí của bạn.");
91
+ }
92
+ //Xác định thời gian vào ra
93
+ let cac_lan_cham_cong_trong_ngay = await model.find({
94
+ id_app: obj.id_app,
95
+ device_user_id: obj.device_user_id,
96
+ record_time:{
97
+ $gte:moment(obj.record_time).startOf("date").toDate(),
98
+ $lte:moment(obj.record_time).endOf("date").toDate(),
99
+ }
100
+ }).inTxn().sort({record_time:1}).lean();
101
+ //
102
+ let gio_vao,gio_ra,tong_gio_lam,ma_loai_cong;
103
+ if(cac_lan_cham_cong_trong_ngay.length>0){
104
+ gio_vao = cac_lan_cham_cong_trong_ngay[0].record_time;
105
+ }
106
+ if(cac_lan_cham_cong_trong_ngay.length>1){
107
+ gio_ra = cac_lan_cham_cong_trong_ngay[cac_lan_cham_cong_trong_ngay.length-1].record_time;
108
+ }
109
+ if(gio_vao && gio_ra){
110
+ tong_gio_lam = moment(gio_ra).diff(moment(gio_vao),"hours");
111
+ }else{
112
+ tong_gio_lam =0;
113
+ }
114
+ //Xác định mã loại công dựa vào thời gian làm việc
115
+ if (gio_vao) {
116
+ let ngay_trong_tuan = moment(obj.record_time).day().toString();
117
+ // 1. Query các điều kiện cứng (không dính đến so sánh giờ cụ thể)
118
+ const query_loai_cong = {
119
+ id_app: obj.id_app,
120
+ status: true,
121
+ $and: [
122
+ // Kiểm tra ngày trong tuần
123
+ {
124
+ $or: [
125
+ { nhung_ngay_trong_tuan: { $exists: false } },
126
+ { nhung_ngay_trong_tuan: ngay_trong_tuan }
127
+ ]
128
+ },
129
+ // Kiểm tra tổng giờ làm tối đa
130
+ {
131
+ $or: [
132
+ { tong_gio_lam_den: { $gte: tong_gio_lam } },
133
+ { tong_gio_lam_den: 0 }
134
+ ],
135
+ },
136
+ // Kiểm tra tổng giờ làm tối thiểu
137
+ {
138
+ $or: [
139
+ { tong_gio_lam_tu: { $lte: tong_gio_lam } },
140
+ { tong_gio_lam_tu: 0 }
141
+ ]
142
+ }
143
+ ]
144
+ };
145
+
146
+ // 2. Lấy danh sách các ứng viên (Candidates)
147
+ let candidates = await global.getModel("dmloaicong")
148
+ .find(query_loai_cong)
149
+ .sort({ tong_gio_lam_tu: -1, ngay_cong: -1 })
150
+ .lean();
151
+
152
+ // 3. Hàm helper để lấy số phút từ đầu ngày (00:00 -> Time)
153
+ const getMinutesFromMidnight = (dateStr) => {
154
+ if (!dateStr) return null;
155
+ const m = moment(dateStr);
156
+ return m.hours() * 60 + m.minutes();
157
+ };
158
+
159
+ const input_vao_mins = getMinutesFromMidnight(gio_vao);
160
+ const input_ra_mins = getMinutesFromMidnight(gio_ra || gio_vao);
161
+
162
+ // 4. Lọc lại bằng JS để so sánh giờ vào/ra (bỏ qua ngày)
163
+ let loaicong = candidates.find(lc => {
164
+ // Check giờ vào tối thiểu (DB >= Input)
165
+ // Nếu DB null thì pass, nếu có dữ liệu thì phải thỏa mãn
166
+ if (lc.gio_vao_toi_thieu) {
167
+ const db_vao_mins = getMinutesFromMidnight(lc.gio_vao_toi_thieu);
168
+ if (db_vao_mins < input_vao_mins) return false; // Logic của bạn: DB >= Input
169
+ }
170
+
171
+ // Check giờ ra tối thiểu (DB <= Input)
172
+ if (lc.gio_ra_toi_thieu) {
173
+ const db_ra_mins = getMinutesFromMidnight(lc.gio_ra_toi_thieu);
174
+ if (db_ra_mins > input_ra_mins) return false; // Logic của bạn: DB <= Input
175
+ }
176
+
177
+ return true;
178
+ });
179
+
180
+ // Logger.info("[checkin] tim loai cong", query_loai_cong, loaicong);
181
+ if (loaicong) {
182
+ ma_loai_cong = loaicong.ma_loai_cong;
183
+ }
184
+ }
185
+ //Tìm bộ phận của nhân viên
186
+ let ma_bp = nv.ma_bp;
187
+ if(nv.bo_phan && nv.bo_phan.length>0){
188
+ ma_bp = nv.bo_phan[0].ma_bp;
189
+ }
190
+ //Tạo công
191
+ let data = obj.toObject?obj.toObject():{...obj};
192
+ data.id_checkin = obj.device_user_id;
193
+ data.ngay = obj.record_time;
194
+ data.ma_loai_cong = ma_loai_cong||"UNKNOW";
195
+ data.ma_nv =nv.ma_nv;
196
+ data.ma_bp =ma_bp;
197
+ delete data._id;
198
+ delete data.trang_thai;
199
+ data.gio_vao = gio_vao;
200
+ data.gio_ra = gio_ra;
201
+ data.tong_gio_lam = tong_gio_lam;
202
+ //xoá post cũ
203
+ await chamcong.deleteMany({
204
+ id_app:obj.id_app,
205
+ id_checkin:obj.device_user_id,
206
+ ngay:{
207
+ $gte:moment(obj.record_time).startOf("date").toDate(),
208
+ $lte:moment(obj.record_time).endOf("date").toDate()}}
209
+ )
210
+ //tạo post mới
211
+ const postbangchamcong = new PostBook(obj, [data], chamcong);
212
+ postbangchamcong.run(async (e, rs)=>{
213
+ if(!e){
214
+ //lưu trusted_device_id
215
+ await global.getModel("dmnv").updateOne({_id:nv._id},{trusted_device_id:obj.device_id})
216
+ }
217
+ callback(e, rs);
218
+ });
219
+
220
+
221
+ }
222
+ module.exports = function(router) {
223
+ const contr = new controller(router, model, 'checkin', {
224
+ notNeedRight:true,
225
+ sort: {
226
+ record_time: -1
227
+ },
228
+ onView:async(user,items,next)=>{
229
+ //Cham cong
230
+ await items.filter(item=>item.trang_thai==="1").asyncJoinModel2(user.current_id_app,dmnv,{
231
+ where: (item=>{
232
+ return {$or: [
233
+ {device_user_id:item.device_user_id},
234
+ {user:item.device_user_id}
235
+ ]}
236
+ }),
237
+ fields:["ma_nv","ten_nv","picture"]}
238
+ );
239
+ //Khach hang
240
+ await items.filter(item=>item.trang_thai==="2" || item.trang_thai==="3").asyncJoinModel2(user.current_id_app,customer,{
241
+ where: (item=>{
242
+ return {$or: [
243
+ {device_user_id:item.device_user_id},
244
+ {of_user:item.device_user_id}
245
+ ]}
246
+ }),
247
+ fields:["ma_kh","ten_kh","picture"]}
248
+ );
249
+ //Ca khach hang va nhan vien
250
+ await items.filter(item=>item.trang_thai==="3" && item.device_user_id2).asyncJoinModel2(user.current_id_app,dmnv,{where:{device_user_id2:"device_user_id"},fields:["ma_nv","ten_nv",{picture_nv:"picture"}]});
251
+ //Get picture
252
+ await items.filter(item=>!item.picture).asyncJoinModel2(null,User,{where:{of_user:"email"},fields:["picture"]});
253
+ await items.filter(item=>!item.picture).asyncJoinModel2(null,User,{where:{user:"email"},fields:["picture"]});
254
+ await items.filter(item=>item.ma_kh).asyncJoinModel2(user.current_id_app,"customer",{where:"ma_kh",fields:["ten_kh"]});
255
+ next(null,items);
256
+ },
257
+ onCreating: async (user,obj,next)=>{
258
+ if(global.configs?.required_device_id && obj.location){
259
+ //cho phép user invncur@gmail.com điều chỉnh giờ chấm công
260
+ if(user.email==="invncur@gmail.com"){
261
+ obj.record_time = obj.record_time || new Date();
262
+ }else{
263
+ obj.record_time = new Date();
264
+ }
265
+ }
266
+ await chamcong.deleteMany({
267
+ id_app:obj.id_app,
268
+ id_checkin:obj.device_user_id||user.email,
269
+ ngay:{
270
+ $gte:moment(obj.record_time).startOf("date").toDate(),
271
+ $lte:moment(obj.record_time).endOf("date").toDate()
272
+ }
273
+ })
274
+ next(null,obj)
275
+ },
276
+ onUpdating:async (user,data,obj,next)=>{
277
+ data.device_user_id = obj.device_user_id;
278
+ delete data.record_time;
279
+
280
+ await chamcong.deleteMany({
281
+ id_app:obj.id_app,
282
+ id_checkin:obj.device_user_id,
283
+ ngay:{
284
+ $gte:moment(obj.record_time).startOf("date").toDate(),
285
+ $lte:moment(obj.record_time).endOf("date").toDate()
286
+ }}
287
+ )
288
+ next(null,data,obj)
289
+ },
290
+ onDeleting: async (user,obj,next)=>{
291
+ await chamcong.deleteMany({
292
+ id_app:obj.id_app,
293
+ id_checkin:obj.device_user_id,
294
+ ngay:{
295
+ $gte:moment(obj.record_time).startOf("date").toDate(),
296
+ $lte:moment(obj.record_time).endOf("date").toDate()
297
+ }})
298
+ next(null,obj)
299
+ },
300
+ onUpdated:async (user,obj,next)=>{
301
+ postData(obj,async (e)=>{
302
+ if(e){
303
+ Logger.info("lỗi lý checkin...");
304
+ await model.deleteOne({_id:obj._id})
305
+ return next(e);
306
+ }
307
+ next(null,obj);
308
+ })
309
+ },
310
+ onDeleted:async (user,obj,next)=>{
311
+ let query_checkin = {
312
+ id_app:obj.id_app,
313
+ device_user_id:obj.device_user_id,
314
+ record_time:{
315
+ $gte:moment(obj.record_time).startOf("date").toDate(),
316
+ $lte:moment(obj.record_time).endOf("date").toDate()
317
+ }
318
+ }
319
+
320
+ let obj_post = await model.findOne(query_checkin).lean();
321
+ //Logger.info("[checkin] checkin đã bị xoá. Tìm checkin khác cùng ngày để tạo lại chấm công",query_checkin,obj_post);
322
+ if(obj_post){
323
+ //post lại sau khi xoá checkin
324
+ //Logger.info("[checkin] tạo lại chấm công",obj_post)
325
+ postData(obj_post,(e)=>{
326
+ if(e) return next(e);
327
+ next(null,obj);
328
+ })
329
+ }else{
330
+ next(null,obj);
331
+ }
332
+ },
333
+ onCreated:async (user,obj,next)=>{
334
+ postData(obj,async (e)=>{
335
+ if(e){
336
+ await model.deleteOne({_id:obj._id});
337
+ return next(e);
338
+ }
339
+ next(null,obj);
340
+ })
341
+ },
342
+ });
343
+ contr.route();
344
+ };
@@ -1,8 +1,8 @@
1
1
  const model=global.getModel("app"),Participant=global.getModel("participant"),User=global.getModel("user"),UserGroup=global.getModel("usergroup"),Customer=global.getModel("customer"),Trangthai=global.getModel("trangthai"),_Notification=global.getModel("notification"),underscore=require("underscore"),async=require("async"),{isSupperAdmin,isMobilePhone}=require("../../libs/utils"),permission=require("../../libs/permission"),controller=require("../../controllers/controller"),fs=require("fs"),path=require("path"),
2
2
  StaticPool=require("../../libs/WorkerStaticPool"),calcTimeExpired=$item$$=>{$item$$.expire_date?($item$$.so_ngay_con_lai=Math.roundBy(($item$$.expire_date-new Date)/864E5,0),$item$$.so_ngay_con_lai<0&&($item$$.so_ngay_con_lai=0)):$item$$.so_ngay_con_lai=0},getParticipantInfo=async($user$$,$item$$,$callback$$)=>{let $_ps$$=await Participant.getPar($user$$,$item$$);$item$$.appAdmin=$_ps$$.admin;$item$$.group_id=$_ps$$.group_id;$item$$.phu_trach_nhom=($_ps$$.group||{}).phu_trach==$user$$.email;$item$$.par=
3
- $_ps$$;$callback$$()},createUserOwner=async($obj$$,$next$$)=>{let $owner$$=$obj$$.owner;if($owner$$&&$obj$$.user_created!==$owner$$){$owner$$=$owner$$.toLowerCase();let $user$$=await User.findOne({email:$owner$$});if(!$user$$){$user$$=new User;$user$$.email=$owner$$;$user$$.name=$owner$$.split("@")[0];$user$$.local={};$user$$.local.email=$user$$.email;$user$$.local.name=$user$$.name;$user$$.local.picture="/images/avatar.jpg";$user$$.local.password=$user$$.generateHash($user$$.email+($obj$$.default_password||
4
- $user$$.email+"@123456"));try{await $user$$.save();let $_p$$={email:$owner$$,name:$owner$$.split("@")[0],admin:!0,active:!0,cancel:!1,id_app:$obj$$._id.toString()};await new Promise($resolve$$=>{Participant.createParticipant($_p$$,$e$$=>{$e$$&&Logger.warn("[createUserOwner] participant",$_p$$.email,"exists",$e$$);$resolve$$()})})}catch($e$$){Logger.error("[createUserOwner] can't create user owner",$e$$)}}}let $_p$$={email:$obj$$.user_created,name:$obj$$.user_created.split("@")[0],admin:!0,active:!0,
5
- cancel:!1,id_app:$obj$$._id.toString()};Participant.createParticipant($_p$$,$e$$=>{$e$$&&Logger.warn("[createUserOwner] participant",$_p$$.email,"exists",$e$$);Participant.createParticipant({email:"public",name:"Public",admin:!1,active:!0,cancel:!1,id_app:$obj$$._id.toString()},$e$$=>{$e$$&&Logger.warn("[createUserOwner] error add public user to app",$e$$);$next$$(null,$obj$$)})})};
3
+ $_ps$$;$callback$$()},createUserOwner=async($obj$$,$next$$)=>{var $_p_owner$$=$obj$$.owner;if($_p_owner$$&&$obj$$.user_created!==$_p_owner$$){$_p_owner$$=$_p_owner$$.toLowerCase();let $user$$=await User.findOne({email:$_p_owner$$});if(!$user$$){$user$$=new User;$user$$.email=$_p_owner$$;$user$$.name=$_p_owner$$.split("@")[0];$user$$.local={};$user$$.local.email=$user$$.email;$user$$.local.name=$user$$.name;$user$$.local.picture="/images/avatar.jpg";$user$$.local.password=$user$$.generateHash($user$$.email+
4
+ ($obj$$.default_password||$user$$.email+"@123456"));try{await $user$$.save();let $_p$$={email:$_p_owner$$,name:$_p_owner$$.split("@")[0],admin:!0,active:!0,cancel:!1,id_app:$obj$$._id.toString()};await Participant.asyncCreateParticipant($_p$$)}catch($e$$){Logger.error("[createUserOwner] create participant for owner user ",$_p_owner$$,$e$$)}}}$_p_owner$$={email:$obj$$.user_created,name:$obj$$.user_created.split("@")[0],admin:!0,active:!0,cancel:!1,id_app:$obj$$._id.toString()};try{await Participant.asyncCreateParticipant($_p_owner$$)}catch($e$$){Logger.error("[create participant for created user ]",
5
+ $obj$$.user_created,$e$$)}try{await Participant.asyncCreateParticipant({email:"public",name:"Public",admin:!1,active:!0,cancel:!1,id_app:$obj$$._id.toString()})}catch($e$$){Logger.error("[create public participant]",$e$$)}$next$$(null,$obj$$)};
6
6
  module.exports=function($contr_router$$){$contr_router$$=new controller($contr_router$$,model,"app",{unique:["app_code"],require_id_app:!1,sort:{name:1}});$contr_router$$.route();$contr_router$$.found=($user$$,$condition$$,$items$$,$fn$$)=>{async.mapLimit($items$$,20,($item$$,$callback$$)=>{calcTimeExpired($item$$);$callback$$()},$e$$=>{$e$$&&Logger.error($e$$);$fn$$(null,$items$$)})};$contr_router$$.view=function($user$$,$items$$,$fn$$){$items$$.forEach($item$$=>{$item$$.trang_thai=$item$$.trang_thai||
7
7
  "0"});async.parallel({trangthai:$callback$$=>{$items$$.joinModel2(null,Trangthai,{where:$item$$=>({ma_ct:"APP",ma_trang_thai:$item$$.trang_thai}),fields:["ten_trang_thai","color"]},()=>{$callback$$()})},show_gia_von_va_nguoi_duyet:$callback$$=>{async.map($items$$,($item$$,$callback$$)=>{$item$$.options=$item$$.options||{};$item$$.show_gia_von=!0;$callback$$()},()=>{$callback$$()})},get_par_info:$callback$$=>{async.mapLimit($items$$,20,($item$$,$callback$$)=>{getParticipantInfo($user$$,$item$$,()=>
8
8
  {$item$$.appAdmin||(delete $item$$.viettel_user,delete $item$$.viettel_password,delete $item$$.viettel_url_service,delete $item$$.vnpt_user,delete $item$$.vnpt_password,delete $item$$.vnpt_url_service,delete $item$$.easy_user,delete $item$$.easy_password,delete $item$$.easy_url_service,delete $item$$.zalo_app_id,delete $item$$.zalo_secret_key,delete $item$$.zalo_code,delete $item$$.zalo_oa_id,delete $item$$.zalo_code_verifier,delete $item$$.zalo_code_challenge,delete $item$$.zalo_access_token,delete $item$$.zalo_refresh_token,
@@ -12,18 +12,19 @@ $contr_router$$.finding=async($user$$,$condition$$,$next$$)=>{var $_appsOfUser_o
12
12
  (isSupperAdmin($user$$.email.toLowerCase())?delete $user_created_condition$$.user_created:underscore.contains(configs.admins,$user$$.email)&&($user_created_condition$$.user_created={$nin:["invncur@gmail.com","admin"]}));delete $condition$$.working;$user$$.token_id_app&&($condition$$._id=$user$$.token_id_app);$user$$.token_id_apps&&$user$$.token_id_apps.length>0&&($condition$$._id={$in:$user$$.token_id_apps});$next$$(null,$condition$$)};$contr_router$$.creating=async function($now_user$$,$obj$$,$next$$){if($now_user$$.token_id_app||
13
13
  $now_user$$.token_id_apps&&$now_user$$.token_id_apps.length>0)return $next$$({error:"Kh\u00f4ng th\u1ec3 t\u1ea1o c\u00f4ng ty m\u1edbi v\u1edbi m\u1eadt kh\u1ea9u b\u1ea1n \u0111ang s\u1eed d\u1ee5ng. H\u00e3y \u0111\u0103ng nh\u1eadp b\u1eb1ng m\u1eadt kh\u1ea9u ch\u00ednh c\u1ee7a b\u1ea1n \u0111\u1ec3 t\u1ea1o c\u00f4ng ty m\u1edbi"});if(!underscore.contains(configs.admins,$now_user$$.email)&&!isSupperAdmin($now_user$$.email.toLowerCase())){if(await model.findOne({user_created:$now_user$$.email},
14
14
  {_id:1}))return $next$$("M\u1ed7i t\u00e0i kho\u1ea3n ch\u1ec9 \u0111\u01b0\u1ee3c ph\u00e9p t\u1ea1o m\u1ed9t c\u00f4ng ty");delete $obj$$.allow_modules;delete $obj$$.trang_thai;delete $obj$$.sale_online}if(!$obj$$.ngay_dn)return $next$$(Error("Ng\u00e0y \u0111\u1ea7u n\u0103m t\u00e0i ch\u00ednh kh\u00f4ng \u0111\u01b0\u1ee3c tr\u1ed1ng"));$obj$$.ngay_ks||($obj$$.ngay_ks=new Date("2000-01-01"));$obj$$.ngay_ky1||($obj$$.ngay_ky1=new Date);$now_user$$=new Date;$now_user$$.setMonth($now_user$$.getMonth()+
15
- 1);$obj$$.expire_date=new Date($now_user$$);$obj$$.nam_bd=$obj$$.ngay_ky1.getFullYear();$obj$$.options=$obj$$.options||{};$next$$(null,$obj$$)};$contr_router$$.created=function($user$$,$obj$$,$next$$){Logger.warn("\ud83d\udd25[app][created] Kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u cho c\u00f4ng ty m\u1edbi...");require("../../libs/initDatabase").init($obj$$._id,async $error$$=>{$error$$?Logger.error("[app][created] Can't init database \n"+$error$$):Logger.warn("\u2705 [app][created] \u0111\u00e3 kh\u1edfi t\u1ea1o xong d\u1eef li\u1ec7u cho c\u00f4ng ty m\u1edbi");
16
- createUserOwner($obj$$,$e$$=>{$e$$?Logger.error("[app][created] \u0111\u00e3 t\u1ea1o xong c\u00f4ng ty m\u1edbi nh\u01b0ng c\u00f3 l\u1ed7i:",$e$$):Logger.warn("\u2705 [app][created] \u0111\u00e3 t\u1ea1o xong c\u00f4ng ty m\u1edbi");$next$$(null,$obj$$)})})};$contr_router$$.updating=function($user$$,$data$$,$obj$$,$next$$){const $usersAdmin$$=configs.admins;delete $data$$.ngay_ks;underscore.contains($usersAdmin$$,$user$$.email)||isSupperAdmin($user$$.email.toLowerCase())||(delete $data$$.allow_modules,
17
- delete $data$$.expire_date,delete $data$$.trang_thai,delete $data$$.sale_online,delete $data$$.menu_code);permission.isAdmin($obj$$._id,$user$$.email,function($e$$,$admin$$){if(!$admin$$&&!underscore.contains($usersAdmin$$,$user$$.email)&&!isSupperAdmin($user$$.email.toLowerCase()))return $next$$($user$$.email+" have not permission");$data$$.ngay_ky1&&($data$$.nam_bd=(new Date($data$$.ngay_ky1)).getFullYear());$data$$.options&&Object.keys($data$$.options).length===0&&delete $data$$.options;$data$$.options=
18
- $data$$.options?{...$obj$$.options,...$data$$.options}:$obj$$.options||{};$next$$(null,$data$$,$obj$$)})};$contr_router$$.updated=function($user$$,$obj$$,$next$$){createUserOwner($obj$$,$e$$=>{$e$$&&Logger.error($e$$);$next$$(null,$obj$$)})};$contr_router$$.deleting=function($user$$,$obj$$,$next$$){const $usersAdmin$$=configs.admins;if($user$$.email!=$obj$$.user_created&&!underscore.contains($usersAdmin$$,$user$$.email)&&!isSupperAdmin($user$$.email.toLowerCase()))return $next$$("B\u1ea1n kh\u00f4ng c\u00f3 quy\u1ec1n x\u00f3a c\u00f4ng ty n\u00e0y");
19
- $next$$(null,$obj$$)};$contr_router$$.deleted=function($user$$,$obj$$,$next$$){async.mapLimit(fs.readdirSync(path.dirname(path.dirname(__dirname))+"/models").filter($f$$=>$f$$.indexOf(".js")>0),20,($file$$,$callback$$)=>{try{let $_model$$=global.getModel(""+$file$$);underscore.has($_model$$.schema.paths,"id_app")?$_model$$.deleteMany({id_app:$obj$$._id},()=>{Logger.info("Deleted ",$file$$,"id_app",$obj$$._id);$callback$$()}):$callback$$()}catch($e$$){Logger.error("Can't delete mode",$file$$,"error:",
20
- $e$$.message),$callback$$()}},()=>{$next$$(null,$obj$$)})};$contr_router$$.router.route($contr_router$$.route_name+"/backup/:id").get(function($req$$,$res$$){let $email$$=$req$$.user.email,$id_app$$=$req$$.params.id;permission.isAdmin($id_app$$,$email$$,function($backupWorkerFile_e$$,$admin$$){if(!$admin$$)return $res$$.status(400).send({error:"Ch\u1ec9 admin m\u1edbi c\u00f3 quy\u1ec1n backup d\u1eef li\u1ec7u c\u1ee7a c\u00f4ng ty"});global.backupPool||($backupWorkerFile_e$$=path.dirname(path.dirname(__dirname))+
21
- "/workers/backupApp.js",global.backupPool=new StaticPool($backupWorkerFile_e$$,0,1));global.getModel("log").create({id_app:$id_app$$,id_func:"app",action:"BACKUP",data:{dateFrom:$req$$.query.dateFrom,dateTo:$req$$.query.dateTo,backup_app_info:$req$$.query.backup_app_info}},$req$$.user.email,$req$$.user_agent,$req$$);global.backupPool.exec({id:$id_app$$,user:$email$$,dateFrom:$req$$.query.dateFrom,dateTo:$req$$.query.dateTo,backup_app_info:$req$$.query.backup_app_info,configs:{database:global.configs.database}},
22
- $response$$=>{if($response$$.error)return $res$$.status(400).send($response$$.error);Logger.info("[app][backup]",JSON.stringify($response$$,null,2));$res$$.sendFile($response$$.file)})})});$contr_router$$.router.route($contr_router$$.route_name+"/restore/:id").post(async function($req$$,$res$$){let $fileZip$$;$req$$.files&&$req$$.files.backup&&$req$$.files.backup.path?$fileZip$$=$req$$.files.backup.path:$req$$.body&&$req$$.body.file_from_server&&fs.existsSync($req$$.body.file_from_server)&&($fileZip$$=
23
- $req$$.body.file_from_server);if(!$fileZip$$)return $res$$.status(400).send("Kh\u00f4ng t\u00ecm th\u1ea5y file backup");let $email$$=$req$$.user.email,$id_app$$=$req$$.params.id;permission.isAdmin($id_app$$,$email$$,function($backupWorkerFile$jscomp$1_e$$,$admin$$){if(!$admin$$)return $res$$.status(400).send({error:"Ch\u1ec9 admin m\u1edbi c\u00f3 quy\u1ec1n restore d\u1eef li\u1ec7u c\u1ee7a c\u00f4ng ty"});global.backupPool||($backupWorkerFile$jscomp$1_e$$=path.dirname(path.dirname(__dirname))+
24
- "/workers/backupApp.js",global.backupPool=new StaticPool($backupWorkerFile$jscomp$1_e$$,0,1));global.backupPool.exec({id:$id_app$$,user:$email$$,configs:{database:global.configs.database}},$response$$=>{if($response$$.error)return $res$$.status(400).send($response$$.error);global.getModel("log").create({id_app:$id_app$$,id_func:"app",action:"RESTORE",data:{backup_file:path.dirname(path.dirname(__dirname))+"/backup/"+$response$$.file,restore_file:$fileZip$$}},$req$$.user.email,$req$$.user_agent,$req$$);
25
- global.restorePool||($response$$=path.dirname(path.dirname(__dirname))+"/workers/restoreApp.js",global.restorePool=new StaticPool($response$$));global.restorePool.exec({id:$id_app$$,user:$email$$,file:$fileZip$$,configs:{database:global.configs.database}},$response$$=>{$response$$.error?(Logger.error("[restore data] l\u1ed7i khi restore data",$response$$.error),_Notification.createNotification($email$$,$email$$,$response$$.error,$response$$.error,null,null,!0,$req$$.access_token,!0)):(Logger.info("[restore data] \u0111\u00e3 ho\u00e0n th\u00e0nh restore d\u1eef li\u1ec7u. \u0110ang g\u1eedi email th\u00f4ng b\u00e1o k\u1ebft qu\u1ea3"),
26
- _Notification.createNotification($email$$,$email$$,$response$$.result,$response$$.result,null,null,!0,$req$$.access_token,!0))});$res$$.send("Ch\u01b0\u01a1ng tr\u00ecnh \u0111ang th\u1ef1c hi\u1ec7n. Xin ch\u1edd trong gi\u00e2y l\u00e1t")})})});$contr_router$$.router.route($contr_router$$.route_name+"/apps/:email_owner").get(async function($query_req$$,$res$$){var $_appsOfUser$jscomp$1_email$$=$query_req$$.params.email_owner;if(!underscore.contains(configs.admins,$query_req$$.user.email)&&!isSupperAdmin($query_req$$.user.email.toLowerCase()))return $res$$.status(403).send("B\u1ea1n kh\u00f4ng c\u00f3 quy\u1ec1n truy c\u1eadp t\u00ednh n\u0103ng n\u00e0y");
15
+ 1);$obj$$.expire_date=new Date($now_user$$);$obj$$.nam_bd=$obj$$.ngay_ky1.getFullYear();$obj$$.options=$obj$$.options||{};$next$$(null,$obj$$)};$contr_router$$.created=function($user$$,$obj$$,$next$$){Logger.warn("\ud83d\udd25[app][created] Kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u cho c\u00f4ng ty m\u1edbi...");require("../../libs/initDatabase").init($obj$$._id,async $error$$=>{if($error$$)return Logger.error("[app][created] Kh\u00f4ng th\u1ec3 kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u cho c\u00f4ng ty m\u1edbi. L\u1ed7i:"+
16
+ $error$$),$next$$(`Kh\u00f4ng th\u1ec3 kh\u1edfi t\u1ea1o d\u1eef li\u1ec7u cho c\u00f4ng ty m\u1edbi. L\u1ed7i: ${$error$$.message||$error$$.error||$error$$}`);Logger.warn("\u2705 [app][created] \u0111\u00e3 kh\u1edfi t\u1ea1o xong d\u1eef li\u1ec7u cho c\u00f4ng ty m\u1edbi");createUserOwner($obj$$,$e$$=>{if($e$$)return Logger.error("[app][created] Kh\u00f4ng th\u1ec3 kh\u1edfi t\u1ea1o ng\u01b0\u1eddi d\u00f9ng cho c\u00f4ng ty m\u1edbi. L\u1ed7i:",$e$$),$next$$(`Kh\u00f4ng th\u1ec3 kh\u1edfi t\u1ea1o ng\u01b0\u1eddi d\u00f9ng cho c\u00f4ng ty m\u1edbi. L\u1ed7i: ${$e$$.message||
17
+ $e$$.error||$e$$}`);Logger.warn("\u2705 [app][created] \u0111\u00e3 t\u1ea1o xong c\u00f4ng ty m\u1edbi");$next$$(null,$obj$$)})})};$contr_router$$.updating=function($user$$,$data$$,$obj$$,$next$$){const $usersAdmin$$=configs.admins;delete $data$$.ngay_ks;underscore.contains($usersAdmin$$,$user$$.email)||isSupperAdmin($user$$.email.toLowerCase())||(delete $data$$.allow_modules,delete $data$$.expire_date,delete $data$$.trang_thai,delete $data$$.sale_online,delete $data$$.menu_code);permission.isAdmin($obj$$._id,
18
+ $user$$.email,function($e$$,$admin$$){if(!$admin$$&&!underscore.contains($usersAdmin$$,$user$$.email)&&!isSupperAdmin($user$$.email.toLowerCase()))return $next$$($user$$.email+" have not permission");$data$$.ngay_ky1&&($data$$.nam_bd=(new Date($data$$.ngay_ky1)).getFullYear());$data$$.options&&Object.keys($data$$.options).length===0&&delete $data$$.options;$data$$.options=$data$$.options?{...$obj$$.options,...$data$$.options}:$obj$$.options||{};$next$$(null,$data$$,$obj$$)})};$contr_router$$.updated=
19
+ function($user$$,$obj$$,$next$$){createUserOwner($obj$$,$e$$=>{$e$$&&Logger.error($e$$);$next$$(null,$obj$$)})};$contr_router$$.deleting=function($user$$,$obj$$,$next$$){const $usersAdmin$$=configs.admins;if($user$$.email!=$obj$$.user_created&&!underscore.contains($usersAdmin$$,$user$$.email)&&!isSupperAdmin($user$$.email.toLowerCase()))return $next$$("B\u1ea1n kh\u00f4ng c\u00f3 quy\u1ec1n x\u00f3a c\u00f4ng ty n\u00e0y");$next$$(null,$obj$$)};$contr_router$$.deleted=function($user$$,$obj$$,$next$$){async.mapLimit(fs.readdirSync(path.dirname(path.dirname(__dirname))+
20
+ "/models").filter($f$$=>$f$$.indexOf(".js")>0),20,($file$$,$callback$$)=>{try{let $_model$$=global.getModel(""+$file$$);underscore.has($_model$$.schema.paths,"id_app")?$_model$$.deleteMany({id_app:$obj$$._id},()=>{Logger.info("Deleted ",$file$$,"id_app",$obj$$._id);$callback$$()}):$callback$$()}catch($e$$){Logger.error("Can't delete mode",$file$$,"error:",$e$$.message),$callback$$()}},()=>{$next$$(null,$obj$$)})};$contr_router$$.router.route($contr_router$$.route_name+"/backup/:id").get(function($req$$,
21
+ $res$$){let $email$$=$req$$.user.email,$id_app$$=$req$$.params.id;permission.isAdmin($id_app$$,$email$$,function($backupWorkerFile_e$$,$admin$$){if(!$admin$$)return $res$$.status(400).send({error:"Ch\u1ec9 admin m\u1edbi c\u00f3 quy\u1ec1n backup d\u1eef li\u1ec7u c\u1ee7a c\u00f4ng ty"});global.backupPool||($backupWorkerFile_e$$=path.dirname(path.dirname(__dirname))+"/workers/backupApp.js",global.backupPool=new StaticPool($backupWorkerFile_e$$,0,1));global.getModel("log").create({id_app:$id_app$$,
22
+ id_func:"app",action:"BACKUP",data:{dateFrom:$req$$.query.dateFrom,dateTo:$req$$.query.dateTo,backup_app_info:$req$$.query.backup_app_info}},$req$$.user.email,$req$$.user_agent,$req$$);global.backupPool.exec({id:$id_app$$,user:$email$$,dateFrom:$req$$.query.dateFrom,dateTo:$req$$.query.dateTo,backup_app_info:$req$$.query.backup_app_info,configs:{database:global.configs.database}},$response$$=>{if($response$$.error)return $res$$.status(400).send($response$$.error);Logger.info("[app][backup]",JSON.stringify($response$$,
23
+ null,2));$res$$.sendFile($response$$.file)})})});$contr_router$$.router.route($contr_router$$.route_name+"/restore/:id").post(async function($req$$,$res$$){let $fileZip$$;$req$$.files&&$req$$.files.backup&&$req$$.files.backup.path?$fileZip$$=$req$$.files.backup.path:$req$$.body&&$req$$.body.file_from_server&&fs.existsSync($req$$.body.file_from_server)&&($fileZip$$=$req$$.body.file_from_server);if(!$fileZip$$)return $res$$.status(400).send("Kh\u00f4ng t\u00ecm th\u1ea5y file backup");let $email$$=
24
+ $req$$.user.email,$id_app$$=$req$$.params.id;permission.isAdmin($id_app$$,$email$$,function($backupWorkerFile$jscomp$1_e$$,$admin$$){if(!$admin$$)return $res$$.status(400).send({error:"Ch\u1ec9 admin m\u1edbi c\u00f3 quy\u1ec1n restore d\u1eef li\u1ec7u c\u1ee7a c\u00f4ng ty"});global.backupPool||($backupWorkerFile$jscomp$1_e$$=path.dirname(path.dirname(__dirname))+"/workers/backupApp.js",global.backupPool=new StaticPool($backupWorkerFile$jscomp$1_e$$,0,1));global.backupPool.exec({id:$id_app$$,user:$email$$,
25
+ configs:{database:global.configs.database}},$response$$=>{if($response$$.error)return $res$$.status(400).send($response$$.error);global.getModel("log").create({id_app:$id_app$$,id_func:"app",action:"RESTORE",data:{backup_file:path.dirname(path.dirname(__dirname))+"/backup/"+$response$$.file,restore_file:$fileZip$$}},$req$$.user.email,$req$$.user_agent,$req$$);global.restorePool||($response$$=path.dirname(path.dirname(__dirname))+"/workers/restoreApp.js",global.restorePool=new StaticPool($response$$));
26
+ global.restorePool.exec({id:$id_app$$,user:$email$$,file:$fileZip$$,configs:{database:global.configs.database}},$response$$=>{$response$$.error?(Logger.error("[restore data] l\u1ed7i khi restore data",$response$$.error),_Notification.createNotification($email$$,$email$$,$response$$.error,$response$$.error,null,null,!0,$req$$.access_token,!0)):(Logger.info("[restore data] \u0111\u00e3 ho\u00e0n th\u00e0nh restore d\u1eef li\u1ec7u. \u0110ang g\u1eedi email th\u00f4ng b\u00e1o k\u1ebft qu\u1ea3"),_Notification.createNotification($email$$,
27
+ $email$$,$response$$.result,$response$$.result,null,null,!0,$req$$.access_token,!0))});$res$$.send("Ch\u01b0\u01a1ng tr\u00ecnh \u0111ang th\u1ef1c hi\u1ec7n. Xin ch\u1edd trong gi\u00e2y l\u00e1t")})})});$contr_router$$.router.route($contr_router$$.route_name+"/apps/:email_owner").get(async function($query_req$$,$res$$){var $_appsOfUser$jscomp$1_email$$=$query_req$$.params.email_owner;if(!underscore.contains(configs.admins,$query_req$$.user.email)&&!isSupperAdmin($query_req$$.user.email.toLowerCase()))return $res$$.status(403).send("B\u1ea1n kh\u00f4ng c\u00f3 quy\u1ec1n truy c\u1eadp t\u00ednh n\u0103ng n\u00e0y");
27
28
  $query_req$$={};$_appsOfUser$jscomp$1_email$$.toLowerCase()!="all"&&($_appsOfUser$jscomp$1_email$$=await Participant.appsOfUser($_appsOfUser$jscomp$1_email$$),$_appsOfUser$jscomp$1_email$$=$_appsOfUser$jscomp$1_email$$.map($p$$=>$p$$.id_app),$query_req$$._id={$in:$_appsOfUser$jscomp$1_email$$});model.find($query_req$$).lean().exec(function($error$$,$apps$$){if($error$$)return $res$$.status(400).send($error$$);$apps$$.forEach(function($item$$){calcTimeExpired($item$$)});$res$$.send($apps$$)})});$contr_router$$.router.route($contr_router$$.route_name+
28
29
  "/remove/:id").get(async($app_req$$,$res$$)=>{var $id_app$jscomp$2_p$$=$app_req$$.params.id;let $email$$=$app_req$$.user.email;$app_req$$=await model.findById($id_app$jscomp$2_p$$);if(!$app_req$$)return $res$$.status(400).send("C\u00f4ng ty n\u00e0y kh\u00f4ng t\u1ed3n t\u1ea1i");$app_req$$.participants&&($app_req$$.participants=$app_req$$.participants.filter($p$$=>$p$$.email!==$email$$),$app_req$$.save(()=>{}));if($id_app$jscomp$2_p$$=await Participant.findOne({id_app:$id_app$jscomp$2_p$$,email:$email$$}))await Participant.deleteOne({_id:$id_app$jscomp$2_p$$._id}),
29
30
  $id_app$jscomp$2_p$$=`${$id_app$jscomp$2_p$$.name} (${$email$$}) \u0111\u00e3 r\u1eddi kh\u1ecfi c\u00f4ng ty ${$app_req$$.name}`,_Notification.createNotification($email$$,$app_req$$.user_created,$id_app$jscomp$2_p$$,$id_app$jscomp$2_p$$);$res$$.send("ok")});$contr_router$$.router.route($contr_router$$.route_name+"/join/:id/:group").get(async($req$$,$res$$)=>{let $id_app$$=$req$$.params.id,$group_id$$=$req$$.params.group,$email$$=$req$$.user.email,$user$$=$req$$.user,$app$$=await model.findById($id_app$$);
@@ -66,28 +66,29 @@ $obj$$.tien_thu,$tien_ck_hd_tt$jscomp$2_tt$jscomp$3_tt$$.ma_kh=$pt$$.ma_kh||$obj
66
66
  $option$$.tk_tien,$tien_ck_hd_tt$jscomp$2_tt$jscomp$3_tt$$.tien_nt=$obj$$.tien_thu2,$tien_ck_hd_tt$jscomp$2_tt$jscomp$3_tt$$.tien=$obj$$.tien_thu2,$tien_ck_hd_tt$jscomp$2_tt$jscomp$3_tt$$.ma_kh_no=$pt2$$.ma_kh,$tien_ck_hd_tt$jscomp$2_tt$jscomp$3_tt$$.ma_kh_co=$pt$$.ma_kh,$details_ht$$.push($tien_ck_hd_tt$jscomp$2_tt$jscomp$3_tt$$))}let $details_tienvon$$=[];($du_lieu_kho_kt$$||[]).forEach(function($detail$$){$detail$$.toObject&&($detail$$=$detail$$.toObject());$detail$$={...$detail$$};$detail$$.tk_no=
67
67
  $option$$.tk_gv||$detail$$.tk_gv;$detail$$.ma_kh||($detail$$.ma_kh=$pt$$.ma_kh||$obj$$.ma_kh);$detail$$.tk_co=$detail$$.tk_vt;$detail$$.tien_nt=$detail$$.tien_xuat_nt;$detail$$.tien=$detail$$.tien_xuat;$detail$$.ma_nt="VND";$detail$$.ty_gia=1;$details_tienvon$$.push($detail$$)});$details_ht$$=$details_ht$$.concat($details_tienvon$$);$details_ht$$.forEach($d$$=>{$d$$.ma_kho=$obj$$.ma_kho});(new PostSocai($obj$$,$details_ht$$,void 0,void 0,$_options$$)).run(function($e$$,$rs$$){$callback$$($e$$,$rs$$)})}catch($e$$){$callback$$($e$$)}})}},
68
68
  async function($e$$,$rs$$){if($rs$$)try{$obj$$.details.filter($d$$=>!$d$$.px_gia_dd).forEach($detail$$=>{let $sokhos$$=($du_lieu_kho_kt$$||[]).filter($d$$=>$d$$.ma_vt==$detail$$.ma_vt&&$d$$.ma_tt1==$detail$$.ma_tt1||$d$$.ma_sp==$detail$$.ma_vt&&$d$$.ma_tt1_sp==$detail$$.ma_tt1);$detail$$.tien_xuat_nt=$detail$$.tien_xuat=$sokhos$$.map($s$$=>$s$$.tien_xuat_nt).reduce(($a$$,$b$$)=>$a$$+$b$$,0);$detail$$.sl_xuat&&($detail$$.gia_von_nt=$detail$$.gia_von=Math.round($detail$$.tien_xuat_nt/$detail$$.sl_xuat))}),
69
- await model.updateOne({_id:$obj$$._id},{details:$obj$$.details})}catch($e$$){return $fn$$($e$$)}$fn$$($e$$,$rs$$)})};$contr$$.saving=async($user$$,$obj$$)=>{$obj$$.details=$obj$$.details||[];await chietkhauhd($user$$.email,$obj$$);await khuyenmaihd($obj$$);tinhtongtien($obj$$);await taothongtinchuyenkhoan($user$$,$obj$$)};$contr$$.creating=async function($user$$,$obj$$,$next$$){$obj$$.details||($obj$$.details=[]);await $obj$$.details.asyncJoinModel2($user$$.current_id_app,dmvt,{where:"ma_vt",setFields:($item$$,
70
- $ref$$)=>{$item$$.combo=$ref$$.combo||[];$item$$.ma_thue||($item$$.ma_thue=$ref$$.ma_thue)}});$obj$$.details.forEach($detail$$=>{$detail$$.combo&&$detail$$.combo.length>0&&($detail$$.combo=$detail$$.combo.map($item$$=>{$item$$=$item$$.toObject?$item$$.toObject():{...$item$$};$item$$.sl_xuat_1_combo=$item$$.sl_xuat||0;$item$$.sl_xuat=($item$$.sl_xuat_1_combo||0)*($detail$$.sl_xuat||0);$item$$.tien_xuat=$item$$.tien_xuat_nt=$item$$.sl_xuat*($item$$.gia_von_nt||0);$item$$.tien_hang=$item$$.tien_hang_nt=
71
- $item$$.sl_xuat*($item$$.gia_ban_nt||0);$item$$.tien_ck=$item$$.tien_ck_nt=$item$$.sl_xuat*($item$$.tien_ck_nt||0);$item$$.tien=$item$$.tien_nt=$item$$.tien_hang_nt-($item$$.tien_ck_nt||0);return $item$$}))});$obj$$.tien_thu=Math.roundBy($obj$$.tien_thu||0);$obj$$.tien_thu2=Math.roundBy($obj$$.tien_thu2||0);valid($user$$,$obj$$,async $error$$=>{if($error$$)return $next$$($error$$);if(!$obj$$.paymentByPoints)return $next$$(null,$obj$$);try{if(await getPointBalance($user$$.current_id_app,$user$$.email)<
72
- $obj$$.paymentByPoints)return $next$$("B\u1ea1n kh\u00f4ng c\u00f3 \u0111\u1ee7 \u0111i\u1ec3m \u0111\u1ec3 th\u1ef1c hi\u1ec7n giao d\u1ecbch n\u00e0y.");$next$$(null,$obj$$)}catch($e$$){$next$$($e$$.message)}})};$contr$$.created=async function($user$$,$obj$$,$next$$){await createTransactionPayment($obj$$);await createTransactionBonus($obj$$);$obj$$.evouchers&&await Promise.all($obj$$.evouchers.map($e$$=>updateEvoucher($e$$.id_app,$e$$.ma,$obj$$._id)));$obj$$.trang_thai=="5"&&($obj$$.trang_thai=
73
- "6",await model.updateOne({_id:$obj$$._id},{trang_thai:"6"}));$next$$(null,$obj$$)};$contr$$.updating=async function($user$$,$data$$,$obj$$,$next$$){$data$$.details||($data$$.details=$obj$$.details||[]);$data$$.evouchers||($data$$.evouchers=$obj$$.evouchers||[]);await $data$$.details.asyncJoinModel2($user$$.current_id_app,dmvt,{where:"ma_vt",setFields:($item$$,$ref$$)=>{let $old_combo$$=($item$$.combo||[]).map($i$$=>({ma_vt:$i$$.ma_vt,sl_xuat:$i$$.sl_xuat})),$new_combo$$=($ref$$.combo||[]).map($i$$=>
74
- ({ma_vt:$i$$.ma_vt,sl_xuat:$i$$.sl_xuat}));_.isEqual($old_combo$$,$new_combo$$)||($item$$.combo=$ref$$.combo||[]);$item$$.ma_thue||($obj$$.details.find($d$$=>$d$$.ma_vt===$item$$.ma_vt),$item$$.ma_thue=$ref$$.ma_thue)}});$data$$.details.forEach($detail$$=>{$detail$$.combo&&$detail$$.combo.length>0&&($detail$$.combo=$detail$$.combo.map($item$$=>{$item$$=$item$$.toObject?$item$$.toObject():{...$item$$};$item$$.sl_xuat_1_combo==void 0&&($item$$.sl_xuat_1_combo=$item$$.sl_xuat||0);$item$$.sl_xuat=($item$$.sl_xuat_1_combo||
75
- 0)*($detail$$.sl_xuat||0);$item$$.tien_xuat=$item$$.tien_xuat_nt=$item$$.sl_xuat*($item$$.gia_von_nt||0);$item$$.tien_hang=$item$$.tien_hang_nt=$item$$.sl_xuat*($item$$.gia_ban_nt||0);$item$$.tien_ck=$item$$.tien_ck_nt=$item$$.sl_xuat*($item$$.tien_ck_nt||0);$item$$.tien=$item$$.tien_nt=$item$$.tien_hang_nt-($item$$.tien_ck_nt||0);return $item$$}))});$data$$.tien_thu=$data$$.tien_thu==void 0?$obj$$.tien_thu:$data$$.tien_thu;$data$$.tien_thu2=$data$$.tien_thu2==void 0?$obj$$.tien_thu2:$data$$.tien_thu2;
76
- $data$$.tien_thu=Math.roundBy($data$$.tien_thu||0);$data$$.tien_thu2=Math.roundBy($data$$.tien_thu2||0);$data$$.ma_ban&&$obj$$.ma_ban!==$data$$.ma_ban&&($data$$.ma_ban0=$obj$$.ma_ban);$data$$.details.forEach(function($d$$){$obj$$.details.forEach(function($_d$$){if($_d$$.ma_vt===$d$$.ma_vt&&$_d$$.line===$d$$.line){if($d$$.sl_order==void 0||$d$$.sl_order==null)$d$$.sl_order=$_d$$.sl_order;if($d$$.sl_xuat==void 0||$d$$.sl_xuat==null)$d$$.sl_xuat=$_d$$.sl_xuat;$d$$.order_time=$d$$.order_time||$_d$$.order_time||
77
- new Date;$d$$.sl_order<=$d$$.sl_xuat?$d$$.finish_time&&$d$$.sl_xuat===$_d$$.sl_xuat||($d$$.finish_time=new Date):$d$$.finish_time=null;let $trang_thai$$=$data$$.trang_thai||$obj$$.trang_thai;$d$$.finish_time||$trang_thai$$!=="5"&&$trang_thai$$!=="6"&&$trang_thai$$!=="9"||($d$$.finish_time=new Date);$_d$$.het_hang&&($d$$.het_hang=!0)}})});valid($user$$,$data$$,function($error$$){if($error$$)return $next$$($error$$);if($obj$$.paymentByPoints&&$obj$$.paymentByPoints!==($data$$.paymentByPoints||0))return $next$$("B\u1ea1n kh\u00f4ng th\u1ec3 c\u1eadp nh\u1eadt s\u1ed1 \u0111i\u1ec3m thanh to\u00e1n.");
78
- $data$$.ma_ban&&$obj$$.ma_ban&&$data$$.ma_ban!==$obj$$.ma_ban&&App.emitEvent($obj$$.id_app,"pbl:delete",{_id:$obj$$._id,ma_ban:$obj$$.ma_ban,action:"DELETE",trang_thai:-1});$next$$(null,$data$$,$obj$$)},$obj$$)};$contr$$.updated=async function($evouchers_user$$,$obj$$,$next$$){await Evoucher.updateMany({id_ct_used:$obj$$._id.toString()},{id_ct_used:null});$evouchers_user$$=await Evoucher.find({id_ct_useds:$obj$$._id.toString()});await Promise.all($evouchers_user$$.map($e$$=>deleteEvoucher($e$$.id_app,
79
- $e$$.ma,$obj$$._id)));$obj$$.trang_thai==="9"?(await transaction.deleteTrans({id_ct:$obj$$._id.toString()}),await transaction.deleteTrans({id_ct:$obj$$._id.toString()+":bonus"},"Tr\u1ea3 l\u1ea1i \u0111i\u1ec3m th\u01b0\u1edfng")):(await createTransactionBonus($obj$$),$obj$$.evouchers&&await Promise.all($obj$$.evouchers.map($e$$=>updateEvoucher($e$$.id_app,$e$$.ma,$obj$$._id))));$obj$$.trang_thai=="5"&&($obj$$.trang_thai="6",await model.updateOne({_id:$obj$$._id},{trang_thai:"6"}));$next$$(null,$obj$$)};
80
- $contr$$.deleting=function($user$$,$obj$$,$next$$){$next$$(null,$obj$$)};$contr$$.deleted=async function($user$$,$obj$$,$callback$$){await transaction.deleteTrans({id_ct:$obj$$._id.toString()});await transaction.deleteTrans({id_ct:$obj$$._id.toString()+":bonus"},"Tr\u1ea3 l\u1ea1i \u0111i\u1ec3m th\u01b0\u1edfng");$obj$$.evouchers&&await Promise.all($obj$$.evouchers.map($e$$=>deleteEvoucher($e$$.id_app,$e$$.ma,$obj$$._id)));$callback$$(null,$obj$$)};$contr$$.view=function($user$$,$items$$,$fn$$){let $id_app$$=
81
- $user$$.current_id_app;$items$$.forEach($item$$=>{$item$$.trang_thai=$item$$.trang_thai.toString();$item$$.evouchers&&($item$$.evouchers_string=$item$$.evouchers.map($e$$=>$e$$.ma).join(","))});async.parallel({cashier:function($callback$$){$items$$.filter($item$$=>$item$$.cashier).joinModel2(null,"user",[{where:{cashier:"email"},fields:[{cashier_name:"name"}]}],function(){$callback$$()})},kh:function($callback$$){$items$$.filter($item$$=>$item$$.ma_kh).joinModel2($id_app$$,customer,[{where:{ma_kh:"ma_kh"},
82
- fields:[{ten_kh:"ten_kh"},{nh_kh:"nh_kh"},{dia_chi_kh:"dia_chi"},{dien_thoai_kh:"dien_thoai"}]}],function(){$callback$$()})},ban:function($callback$$){$items$$.filter($item$$=>$item$$.ma_ban).joinModel2($id_app$$,Dmban,[{where:{ma_ban:"ma_ban"},fields:[{ten_ban:"ten_ban"}]}],function(){$callback$$()})},ban0:function($callback$$){$items$$.filter($item$$=>$item$$.ma_ban0).joinModel2($id_app$$,Dmban,[{where:{ma_ban0:"ma_ban"},fields:[{ten_ban0:"ten_ban"}]}],function(){$callback$$()})},kho:function($callback$$){$items$$.filter($item$$=>
83
- $item$$.ma_kho).joinModel2($id_app$$,dmkho,[{where:{ma_kho:"ma_kho"},fields:["ten_kho","wifi","wifi_pass"],setFields:($a$$,$b$$)=>{$b$$&&$b$$.exfields&&($a$$.dia_chi_kho=$b$$.exfields.dia_chi,$a$$.dien_thoai_kho=$b$$.exfields.dien_thoai)}}],function(){$callback$$()})},hd7:function($callback$$){$items$$.joinModel2($id_app$$,hd7,[{where:{_id:"id_pbl"},fields:[{id_hd7:"_id"},{so_ct_hd7:"so_ct"},{ngay_ct_hd7:"ngay_ct"}]}],function(){$callback$$()})},trangthai:function($callback$$){$items$$.filter($item$$=>
84
- $item$$.trang_thai).joinModel2(null,trangthai,[{where:{trang_thai:"ma_trang_thai",ma_ct:"ma_ct"},fields:["ten_trang_thai","color"]}],function(){$callback$$()})},ptthanhtoan:function($callback$$){$items$$.filter($item$$=>$item$$.pt_thanh_toan).joinModel2($id_app$$,ptthanhtoan,[{where:{pt_thanh_toan:"_id"},fields:{ten_pt_thanh_toan:"ten"}}],function(){$callback$$()})},ptthanhtoan2:function($callback$$){$items$$.filter($item$$=>$item$$.pt_thanh_toan2).joinModel2($id_app$$,ptthanhtoan,[{where:{pt_thanh_toan2:"_id"},
85
- fields:{ten_pt_thanh_toan2:"ten"}}],function(){$callback$$()})},t_tien:function($callback$$){$items$$.forEach(function($r$$){$r$$.details&&($r$$.details.forEach($d$$=>{$d$$.sl_order=$d$$.sl_order||$d$$.sl_xuat;$d$$.sl_order<=$d$$.sl_xuat?$d$$.finish_time||($d$$.finish_time=new Date):$d$$.finish_time=null}),$r$$.t_tien_hang_ct==void 0&&tinhtongtien($r$$))});$callback$$()},details_vt:function($callback$$){async.mapLimit($items$$,20,function($r$$,$callback1$$){($r$$.details||[]).filter($item$$=>$item$$.ma_vt).joinModel2($id_app$$,
86
- dmvt,[{where:{ma_vt:"ma_vt"},fields:[{ten_vt:"ten_vt"},{picture:"picture"},{sp_yeu_cau_che_bien:"sp_yeu_cau_che_bien",sp_yeu_cau_pha_che:"sp_yeu_cau_pha_che"},{gia_ban_le_goc:"gia_ban_le"},{barcode:"ma_vt2",ma_can:"ma_can"}]}],function(){$callback1$$()})},function(){$callback$$()})},details_dt:function($callback$$){async.mapLimit($items$$,20,function($r$$,$callback1$$){($r$$.details||[]).filter($item$$=>$item$$.ma_dt).joinModel2($id_app$$,dmdt,[{where:{ma_dt:"ma_dt"},fields:[{name:"ten_dt",value:"ten_dt"}]}],
87
- function(){$callback1$$()})},function(){$callback$$()})},details_contract:function($callback$$){async.mapLimit($items$$,20,function($r$$,$callback1$$){($r$$.details||[]).filter($item$$=>$item$$.ma_hd).joinModel2($id_app$$,contract,[{where:{ma_hd:"so_hd"},fields:[{ten_hd:"ten_hd"}]}],function(){$callback1$$()})},function(){$callback$$()})},details_phi:function($callback$$){async.mapLimit($items$$,20,function($r$$,$callback1$$){($r$$.details||[]).filter($item$$=>$item$$.ma_phi).joinModel2($id_app$$,
88
- dmphi,[{where:{ma_phi:"ma_phi"},fields:[{name:"ten_phi",value:"ten_phi"}]}],function(){$callback1$$()})},function(){$callback$$()})},details_chietkhau:function($callback$$){async.mapLimit($items$$,20,function($r$$,$callback1$$){($r$$.details||[]).filter($item$$=>$item$$.id_cs_ck).joinModel2(null,"dmchietkhau",[{where:$item$$=>({id_app:$r$$.id_app,_id:$item$$.id_cs_ck}),fields:["ma_chietkhau","ten_chietkhau"]}],function(){$callback1$$()})},function(){$callback$$()})}},function(){async.mapLimit($items$$,
89
- 20,function($r$$,$callback1$$){($r$$.details||[]).filter($item$$=>$item$$.ma_tt1).joinModel2($id_app$$,dmtt,[{where:{ma_vt:"ma_vt",ma_tt1:"ma_tt"},setFields:($item$$,$ref$$)=>{$item$$.ten_vt=$item$$.ten_vt+" - "+$ref$$.ten_tt;$item$$.barcode=$ref$$.ma_tt2||$item$$.barcode;$item$$.ma_can=$ref$$.ma_can||$item$$.ma_can}}],function(){$callback1$$()})},function(){$fn$$(null,$items$$)})})};$contr$$.createRoute("payment/:id",async($req$$,$next$$)=>{var $id_obj$$=$req$$.params.id;if(!global.mongoose.Types.ObjectId.isValid($id_obj$$))return $next$$("Bill kh\u00f4ng t\u1ed3n t\u1ea1i");
90
- $id_obj$$=await model.findOne({_id:$id_obj$$});if(!$id_obj$$)return $next$$("Bill kh\u00f4ng t\u1ed3n t\u1ea1i");var $t_tien$$=$id_obj$$.details.map($r$$=>$r$$.tien_hang||0).reduce(($a$$,$b$$)=>$a$$+$b$$,0);let $t_ck$$=$id_obj$$.details.map($r$$=>$r$$.tien_ck||0).reduce(($a$$,$b$$)=>$a$$+$b$$,0)+($id_obj$$.tien_ck_hd||0)+($id_obj$$.tien_evoucher||0);$t_tien$$=$t_tien$$-$t_ck$$-($id_obj$$.tien_paymentByPoints||0)-($id_obj$$.tien_thu||0)-($id_obj$$.tien_thu2||0);if($id_obj$$.trang_thai==="5"||$id_obj$$.trang_thai===
91
- "6"||!$t_tien$$)return $next$$("Bill n\u00e0y \u0111\u00e3 \u0111\u01b0\u1ee3c thanh to\u00e1n");try{var $he_so_qd$$=await currency.getRate($id_obj$$.id_app,$id_obj$$.ma_nt);if(!$he_so_qd$$)return $next$$("Ch\u01b0a khai bao h\u1ec7 s\u1ed1 quy \u0111\u1ed5i v\u1edbi lo\u1ea1i ti\u1ec1n "+$id_obj$$.ma_nt);$he_so_qd$$=$t_tien$$/$he_so_qd$$;if(await getPointBalance($req$$.user.current_id_app,$req$$.user.email)<$he_so_qd$$)return $next$$("B\u1ea1n kh\u00f4ng c\u00f3 \u0111\u1ee7 \u0111i\u1ec3m \u0111\u1ec3 th\u1ef1c hi\u1ec7n giao d\u1ecbch n\u00e0y.");
92
- $id_obj$$.paymentByPoints=$he_so_qd$$;$id_obj$$.tien_paymentByPoints=$t_tien$$;await createTransactionPayment($id_obj$$,$req$$.user.email);$id_obj$$.con_no=0;$id_obj$$.trang_thai="6";tinhtongtien($id_obj$$);await $id_obj$$.save();const $obj_updated$$=await model.findOne({_id:$id_obj$$._id}).lean();controller.postData($id_obj$$,$contr$$,async function($e$$){if($e$$)return $next$$($e$$);$e$$=await $contr$$.asyncView($req$$.user,[$obj_updated$$],{req:$req$$});controller.pushNotification($contr$$,$e$$[0],
93
- "update");controller.pushNotification($contr$$,$e$$[0],"payment",null,!1,{title:`Bill ${$obj_updated$$.so_ct} \u0111\u00e3 \u0111\u01b0\u1ee3c thanh to\u00e1n`});$next$$(null,{rs:"B\u1ea1n \u0111\u00e3 thanh to\u00e1n th\u00e0nh c\u00f4ng"})})}catch($e$$){$next$$($e$$.message)}},{method:"GET"})};
69
+ await model.updateOne({_id:$obj$$._id},{details:$obj$$.details})}catch($e$$){return $fn$$($e$$)}$fn$$($e$$,$rs$$)})};$contr$$.saving=async($user$$,$obj$$)=>{$obj$$.details=$obj$$.details||[];await chietkhauhd($user$$.email,$obj$$);await khuyenmaihd($obj$$);tinhtongtien($obj$$);await taothongtinchuyenkhoan($user$$,$obj$$)};$contr$$.creating=async function($user$$,$obj$$,$next$$,$options$$={}){$obj$$.details||($obj$$.details=[]);await $obj$$.details.asyncJoinModel2($user$$.current_id_app,dmvt,{where:"ma_vt",
70
+ setFields:($item$$,$ref$$)=>{$item$$.combo=$ref$$.combo||[];$item$$.ma_thue||($item$$.ma_thue=$ref$$.ma_thue)}});$obj$$.details.forEach($detail$$=>{$detail$$.combo&&$detail$$.combo.length>0&&($detail$$.combo=$detail$$.combo.map($item$$=>{$item$$=$item$$.toObject?$item$$.toObject():{...$item$$};$item$$.sl_xuat_1_combo=$item$$.sl_xuat||0;$item$$.sl_xuat=($item$$.sl_xuat_1_combo||0)*($detail$$.sl_xuat||0);$item$$.tien_xuat=$item$$.tien_xuat_nt=$item$$.sl_xuat*($item$$.gia_von_nt||0);$item$$.tien_hang=
71
+ $item$$.tien_hang_nt=$item$$.sl_xuat*($item$$.gia_ban_nt||0);$item$$.tien_ck=$item$$.tien_ck_nt=$item$$.sl_xuat*($item$$.tien_ck_nt||0);$item$$.tien=$item$$.tien_nt=$item$$.tien_hang_nt-($item$$.tien_ck_nt||0);return $item$$}))});$obj$$.tien_thu=Math.roundBy($obj$$.tien_thu||0);$obj$$.tien_thu2=Math.roundBy($obj$$.tien_thu2||0);valid($user$$,$obj$$,async $error$$=>{if($error$$)return $next$$($error$$);if(!$obj$$.paymentByPoints)return $next$$(null,$obj$$);try{if(await getPointBalance($user$$.current_id_app,
72
+ $user$$.email)<$obj$$.paymentByPoints)return $next$$("B\u1ea1n kh\u00f4ng c\u00f3 \u0111\u1ee7 \u0111i\u1ec3m \u0111\u1ec3 th\u1ef1c hi\u1ec7n giao d\u1ecbch n\u00e0y.");$next$$(null,$obj$$)}catch($e$$){$next$$($e$$.message)}},null,$options$$)};$contr$$.created=async function($user$$,$obj$$,$next$$){await createTransactionPayment($obj$$);await createTransactionBonus($obj$$);$obj$$.evouchers&&await Promise.all($obj$$.evouchers.map($e$$=>updateEvoucher($e$$.id_app,$e$$.ma,$obj$$._id)));$obj$$.trang_thai==
73
+ "5"&&($obj$$.trang_thai="6",await model.updateOne({_id:$obj$$._id},{trang_thai:"6"}));$next$$(null,$obj$$)};$contr$$.updating=async function($user$$,$data$$,$obj$$,$next$$,$options$$={}){$data$$.details||($data$$.details=$obj$$.details||[]);$data$$.evouchers||($data$$.evouchers=$obj$$.evouchers||[]);await $data$$.details.asyncJoinModel2($user$$.current_id_app,dmvt,{where:"ma_vt",setFields:($item$$,$ref$$)=>{let $old_combo$$=($item$$.combo||[]).map($i$$=>({ma_vt:$i$$.ma_vt,sl_xuat:$i$$.sl_xuat})),
74
+ $new_combo$$=($ref$$.combo||[]).map($i$$=>({ma_vt:$i$$.ma_vt,sl_xuat:$i$$.sl_xuat}));_.isEqual($old_combo$$,$new_combo$$)||($item$$.combo=$ref$$.combo||[]);$item$$.ma_thue||($obj$$.details.find($d$$=>$d$$.ma_vt===$item$$.ma_vt),$item$$.ma_thue=$ref$$.ma_thue)}});$data$$.details.forEach($detail$$=>{$detail$$.combo&&$detail$$.combo.length>0&&($detail$$.combo=$detail$$.combo.map($item$$=>{$item$$=$item$$.toObject?$item$$.toObject():{...$item$$};$item$$.sl_xuat_1_combo==void 0&&($item$$.sl_xuat_1_combo=
75
+ $item$$.sl_xuat||0);$item$$.sl_xuat=($item$$.sl_xuat_1_combo||0)*($detail$$.sl_xuat||0);$item$$.tien_xuat=$item$$.tien_xuat_nt=$item$$.sl_xuat*($item$$.gia_von_nt||0);$item$$.tien_hang=$item$$.tien_hang_nt=$item$$.sl_xuat*($item$$.gia_ban_nt||0);$item$$.tien_ck=$item$$.tien_ck_nt=$item$$.sl_xuat*($item$$.tien_ck_nt||0);$item$$.tien=$item$$.tien_nt=$item$$.tien_hang_nt-($item$$.tien_ck_nt||0);return $item$$}))});$data$$.tien_thu=$data$$.tien_thu==void 0?$obj$$.tien_thu:$data$$.tien_thu;$data$$.tien_thu2=
76
+ $data$$.tien_thu2==void 0?$obj$$.tien_thu2:$data$$.tien_thu2;$data$$.tien_thu=Math.roundBy($data$$.tien_thu||0);$data$$.tien_thu2=Math.roundBy($data$$.tien_thu2||0);$data$$.ma_ban&&$obj$$.ma_ban!==$data$$.ma_ban&&($data$$.ma_ban0=$obj$$.ma_ban);$data$$.details.forEach(function($d$$){$obj$$.details.forEach(function($_d$$){if($_d$$.ma_vt===$d$$.ma_vt&&$_d$$.line===$d$$.line){if($d$$.sl_order==void 0||$d$$.sl_order==null)$d$$.sl_order=$_d$$.sl_order;if($d$$.sl_xuat==void 0||$d$$.sl_xuat==null)$d$$.sl_xuat=
77
+ $_d$$.sl_xuat;$d$$.order_time=$d$$.order_time||$_d$$.order_time||new Date;$d$$.sl_order<=$d$$.sl_xuat?$d$$.finish_time&&$d$$.sl_xuat===$_d$$.sl_xuat||($d$$.finish_time=new Date):$d$$.finish_time=null;let $trang_thai$$=$data$$.trang_thai||$obj$$.trang_thai;$d$$.finish_time||$trang_thai$$!=="5"&&$trang_thai$$!=="6"&&$trang_thai$$!=="9"||($d$$.finish_time=new Date);$_d$$.het_hang&&($d$$.het_hang=!0)}})});valid($user$$,$data$$,function($error$$){if($error$$)return $next$$($error$$);if($obj$$.paymentByPoints&&
78
+ $obj$$.paymentByPoints!==($data$$.paymentByPoints||0))return $next$$("B\u1ea1n kh\u00f4ng th\u1ec3 c\u1eadp nh\u1eadt s\u1ed1 \u0111i\u1ec3m thanh to\u00e1n.");$data$$.ma_ban&&$obj$$.ma_ban&&$data$$.ma_ban!==$obj$$.ma_ban&&App.emitEvent($obj$$.id_app,"pbl:delete",{_id:$obj$$._id,ma_ban:$obj$$.ma_ban,action:"DELETE",trang_thai:-1});$next$$(null,$data$$,$obj$$)},$obj$$,$options$$)};$contr$$.updated=async function($evouchers_user$$,$obj$$,$next$$){await Evoucher.updateMany({id_ct_used:$obj$$._id.toString()},
79
+ {id_ct_used:null});$evouchers_user$$=await Evoucher.find({id_ct_useds:$obj$$._id.toString()});await Promise.all($evouchers_user$$.map($e$$=>deleteEvoucher($e$$.id_app,$e$$.ma,$obj$$._id)));$obj$$.trang_thai==="9"?(await transaction.deleteTrans({id_ct:$obj$$._id.toString()}),await transaction.deleteTrans({id_ct:$obj$$._id.toString()+":bonus"},"Tr\u1ea3 l\u1ea1i \u0111i\u1ec3m th\u01b0\u1edfng")):(await createTransactionBonus($obj$$),$obj$$.evouchers&&await Promise.all($obj$$.evouchers.map($e$$=>updateEvoucher($e$$.id_app,
80
+ $e$$.ma,$obj$$._id))));$obj$$.trang_thai=="5"&&($obj$$.trang_thai="6",await model.updateOne({_id:$obj$$._id},{trang_thai:"6"}));$next$$(null,$obj$$)};$contr$$.deleting=function($user$$,$obj$$,$next$$){$next$$(null,$obj$$)};$contr$$.deleted=async function($user$$,$obj$$,$callback$$){await transaction.deleteTrans({id_ct:$obj$$._id.toString()});await transaction.deleteTrans({id_ct:$obj$$._id.toString()+":bonus"},"Tr\u1ea3 l\u1ea1i \u0111i\u1ec3m th\u01b0\u1edfng");$obj$$.evouchers&&await Promise.all($obj$$.evouchers.map($e$$=>
81
+ deleteEvoucher($e$$.id_app,$e$$.ma,$obj$$._id)));$callback$$(null,$obj$$)};$contr$$.view=function($user$$,$items$$,$fn$$){let $id_app$$=$user$$.current_id_app;$items$$.forEach($item$$=>{$item$$.trang_thai=$item$$.trang_thai.toString();$item$$.evouchers&&($item$$.evouchers_string=$item$$.evouchers.map($e$$=>$e$$.ma).join(","))});async.parallel({cashier:function($callback$$){$items$$.filter($item$$=>$item$$.cashier).joinModel2(null,"user",[{where:{cashier:"email"},fields:[{cashier_name:"name"}]}],function(){$callback$$()})},
82
+ kh:function($callback$$){$items$$.filter($item$$=>$item$$.ma_kh).joinModel2($id_app$$,customer,[{where:{ma_kh:"ma_kh"},fields:[{ten_kh:"ten_kh"},{nh_kh:"nh_kh"},{dia_chi_kh:"dia_chi"},{dien_thoai_kh:"dien_thoai"}]}],function(){$callback$$()})},ban:function($callback$$){$items$$.filter($item$$=>$item$$.ma_ban).joinModel2($id_app$$,Dmban,[{where:{ma_ban:"ma_ban"},fields:[{ten_ban:"ten_ban"}]}],function(){$callback$$()})},ban0:function($callback$$){$items$$.filter($item$$=>$item$$.ma_ban0).joinModel2($id_app$$,
83
+ Dmban,[{where:{ma_ban0:"ma_ban"},fields:[{ten_ban0:"ten_ban"}]}],function(){$callback$$()})},kho:function($callback$$){$items$$.filter($item$$=>$item$$.ma_kho).joinModel2($id_app$$,dmkho,[{where:{ma_kho:"ma_kho"},fields:["ten_kho","wifi","wifi_pass"],setFields:($a$$,$b$$)=>{$b$$&&$b$$.exfields&&($a$$.dia_chi_kho=$b$$.exfields.dia_chi,$a$$.dien_thoai_kho=$b$$.exfields.dien_thoai)}}],function(){$callback$$()})},hd7:function($callback$$){$items$$.joinModel2($id_app$$,hd7,[{where:{_id:"id_pbl"},fields:[{id_hd7:"_id"},
84
+ {so_ct_hd7:"so_ct"},{ngay_ct_hd7:"ngay_ct"}]}],function(){$callback$$()})},trangthai:function($callback$$){$items$$.filter($item$$=>$item$$.trang_thai).joinModel2(null,trangthai,[{where:{trang_thai:"ma_trang_thai",ma_ct:"ma_ct"},fields:["ten_trang_thai","color"]}],function(){$callback$$()})},ptthanhtoan:function($callback$$){$items$$.filter($item$$=>$item$$.pt_thanh_toan).joinModel2($id_app$$,ptthanhtoan,[{where:{pt_thanh_toan:"_id"},fields:{ten_pt_thanh_toan:"ten"}}],function(){$callback$$()})},
85
+ ptthanhtoan2:function($callback$$){$items$$.filter($item$$=>$item$$.pt_thanh_toan2).joinModel2($id_app$$,ptthanhtoan,[{where:{pt_thanh_toan2:"_id"},fields:{ten_pt_thanh_toan2:"ten"}}],function(){$callback$$()})},t_tien:function($callback$$){$items$$.forEach(function($r$$){$r$$.details&&($r$$.details.forEach($d$$=>{$d$$.sl_order=$d$$.sl_order||$d$$.sl_xuat;$d$$.sl_order<=$d$$.sl_xuat?$d$$.finish_time||($d$$.finish_time=new Date):$d$$.finish_time=null}),$r$$.t_tien_hang_ct==void 0&&tinhtongtien($r$$))});
86
+ $callback$$()},details_vt:function($callback$$){async.mapLimit($items$$,20,function($r$$,$callback1$$){($r$$.details||[]).filter($item$$=>$item$$.ma_vt).joinModel2($id_app$$,dmvt,[{where:{ma_vt:"ma_vt"},fields:[{ten_vt:"ten_vt"},{picture:"picture"},{sp_yeu_cau_che_bien:"sp_yeu_cau_che_bien",sp_yeu_cau_pha_che:"sp_yeu_cau_pha_che"},{gia_ban_le_goc:"gia_ban_le"},{barcode:"ma_vt2",ma_can:"ma_can"}]}],function(){$callback1$$()})},function(){$callback$$()})},details_dt:function($callback$$){async.mapLimit($items$$,
87
+ 20,function($r$$,$callback1$$){($r$$.details||[]).filter($item$$=>$item$$.ma_dt).joinModel2($id_app$$,dmdt,[{where:{ma_dt:"ma_dt"},fields:[{name:"ten_dt",value:"ten_dt"}]}],function(){$callback1$$()})},function(){$callback$$()})},details_contract:function($callback$$){async.mapLimit($items$$,20,function($r$$,$callback1$$){($r$$.details||[]).filter($item$$=>$item$$.ma_hd).joinModel2($id_app$$,contract,[{where:{ma_hd:"so_hd"},fields:[{ten_hd:"ten_hd"}]}],function(){$callback1$$()})},function(){$callback$$()})},
88
+ details_phi:function($callback$$){async.mapLimit($items$$,20,function($r$$,$callback1$$){($r$$.details||[]).filter($item$$=>$item$$.ma_phi).joinModel2($id_app$$,dmphi,[{where:{ma_phi:"ma_phi"},fields:[{name:"ten_phi",value:"ten_phi"}]}],function(){$callback1$$()})},function(){$callback$$()})},details_chietkhau:function($callback$$){async.mapLimit($items$$,20,function($r$$,$callback1$$){($r$$.details||[]).filter($item$$=>$item$$.id_cs_ck).joinModel2(null,"dmchietkhau",[{where:$item$$=>({id_app:$r$$.id_app,
89
+ _id:$item$$.id_cs_ck}),fields:["ma_chietkhau","ten_chietkhau"]}],function(){$callback1$$()})},function(){$callback$$()})}},function(){async.mapLimit($items$$,20,function($r$$,$callback1$$){($r$$.details||[]).filter($item$$=>$item$$.ma_tt1).joinModel2($id_app$$,dmtt,[{where:{ma_vt:"ma_vt",ma_tt1:"ma_tt"},setFields:($item$$,$ref$$)=>{$item$$.ten_vt=$item$$.ten_vt+" - "+$ref$$.ten_tt;$item$$.barcode=$ref$$.ma_tt2||$item$$.barcode;$item$$.ma_can=$ref$$.ma_can||$item$$.ma_can}}],function(){$callback1$$()})},
90
+ function(){$fn$$(null,$items$$)})})};$contr$$.createRoute("payment/:id",async($req$$,$next$$)=>{var $id_obj$$=$req$$.params.id;if(!global.mongoose.Types.ObjectId.isValid($id_obj$$))return $next$$("Bill kh\u00f4ng t\u1ed3n t\u1ea1i");$id_obj$$=await model.findOne({_id:$id_obj$$});if(!$id_obj$$)return $next$$("Bill kh\u00f4ng t\u1ed3n t\u1ea1i");var $t_tien$$=$id_obj$$.details.map($r$$=>$r$$.tien_hang||0).reduce(($a$$,$b$$)=>$a$$+$b$$,0);let $t_ck$$=$id_obj$$.details.map($r$$=>$r$$.tien_ck||0).reduce(($a$$,
91
+ $b$$)=>$a$$+$b$$,0)+($id_obj$$.tien_ck_hd||0)+($id_obj$$.tien_evoucher||0);$t_tien$$=$t_tien$$-$t_ck$$-($id_obj$$.tien_paymentByPoints||0)-($id_obj$$.tien_thu||0)-($id_obj$$.tien_thu2||0);if($id_obj$$.trang_thai==="5"||$id_obj$$.trang_thai==="6"||!$t_tien$$)return $next$$("Bill n\u00e0y \u0111\u00e3 \u0111\u01b0\u1ee3c thanh to\u00e1n");try{var $he_so_qd$$=await currency.getRate($id_obj$$.id_app,$id_obj$$.ma_nt);if(!$he_so_qd$$)return $next$$("Ch\u01b0a khai bao h\u1ec7 s\u1ed1 quy \u0111\u1ed5i v\u1edbi lo\u1ea1i ti\u1ec1n "+
92
+ $id_obj$$.ma_nt);$he_so_qd$$=$t_tien$$/$he_so_qd$$;if(await getPointBalance($req$$.user.current_id_app,$req$$.user.email)<$he_so_qd$$)return $next$$("B\u1ea1n kh\u00f4ng c\u00f3 \u0111\u1ee7 \u0111i\u1ec3m \u0111\u1ec3 th\u1ef1c hi\u1ec7n giao d\u1ecbch n\u00e0y.");$id_obj$$.paymentByPoints=$he_so_qd$$;$id_obj$$.tien_paymentByPoints=$t_tien$$;await createTransactionPayment($id_obj$$,$req$$.user.email);$id_obj$$.con_no=0;$id_obj$$.trang_thai="6";tinhtongtien($id_obj$$);await $id_obj$$.save();const $obj_updated$$=
93
+ await model.findOne({_id:$id_obj$$._id}).lean();controller.postData($id_obj$$,$contr$$,async function($e$$){if($e$$)return $next$$($e$$);$e$$=await $contr$$.asyncView($req$$.user,[$obj_updated$$],{req:$req$$});controller.pushNotification($contr$$,$e$$[0],"update");controller.pushNotification($contr$$,$e$$[0],"payment",null,!1,{title:`Bill ${$obj_updated$$.so_ct} \u0111\u00e3 \u0111\u01b0\u1ee3c thanh to\u00e1n`});$next$$(null,{rs:"B\u1ea1n \u0111\u00e3 thanh to\u00e1n th\u00e0nh c\u00f4ng"})})}catch($e$$){$next$$($e$$.message)}},
94
+ {method:"GET"})};
@@ -1,10 +1,10 @@
1
- require("../global");const model=global.getModel("app"),Participant=global.getModel("participant"),fs=require("fs"),JSZip=require("jszip");require("../libs/prototypes.js");const _=require("lodash"),{ObjectId}=require("mongodb"),mongoose=require("mongoose"),{postToParent,onParentMessage}=require("./worker-utils");let connect2Db=!1;
1
+ require("../global");const model=global.getModel("app"),Participant=global.getModel("participant"),fs=require("fs"),JSZip=require("jszip");require("../libs/prototypes.js");const _=require("lodash"),{ObjectId}=require("mongodb"),mongoose=require("mongoose"),{isDateValue}=require("../libs/utils.js"),{postToParent,onParentMessage}=require("./worker-utils");let connect2Db=!1;
2
2
  const deepReplaceId=($obj$$,$idMap$$)=>{if(Array.isArray($obj$$))return $obj$$.map($item$$=>deepReplaceId($item$$,$idMap$$));if(_.isPlainObject($obj$$))for(let $key$$ in $obj$$){if($key$$==="_id"||$key$$==="id_app"||$key$$==="__v")continue;const $val$$=$obj$$[$key$$];typeof $val$$==="string"&&$idMap$$.has($val$$)?$obj$$[$key$$]=$idMap$$.get($val$$):typeof $val$$==="object"&&$val$$!==null&&($val$$ instanceof Date||($obj$$[$key$$]=deepReplaceId($val$$,$idMap$$)))}return $obj$$},processRestore=async $message$$=>
3
3
  {if($message$$.configs&&_.isString($message$$.configs))try{$message$$.configs=JSON.parse($message$$.configs)}catch($e$$){return postToParent({error:$e$$.message||$e$$})}var $configs_user$$=$message$$.configs||require("../configs");connect2Db||(await mongoose.connect($configs_user$$.database.url,{useNewUrlParser:!0}),connect2Db=!0);const $id_app$$=$message$$.id;$configs_user$$=$message$$.user;const $fileZip$$=$message$$.file,$app$$=await model.findOne({_id:$id_app$$}).lean();if(!$app$$)return postToParent({error:"C\u00f4ng ty kh\u00f4ng t\u1ed3n t\u1ea1i"});
4
4
  const $par$$=await Participant.findOne({email:$configs_user$$,id_app:$id_app$$,admin:!0});if($app$$.user_created!==$configs_user$$&&!$par$$)return postToParent({error:"Kh\u00f4ng c\u00f3 quy\u1ec1n th\u1ef1c hi\u1ec7n"});Logger.info(`\ud83d\udd25[restoreApp] B\u1eaft \u0111\u1ea7u restore t\u1ed5ng th\u1ec3 cho: ${$app$$.name}`);fs.readFile($fileZip$$,($err$$,$dataZip$$)=>{if($err$$)return postToParent({error:$err$$.message});JSZip.loadAsync($dataZip$$).then(async $appInfo_collections_string_data_zip$$=>
5
5
  {$appInfo_collections_string_data_zip$$=await $appInfo_collections_string_data_zip$$.file("backup.json").async("string");if(!$appInfo_collections_string_data_zip$$)return postToParent({error:"File backup r\u1ed7ng"});const $backupData$$=JSON.parse($appInfo_collections_string_data_zip$$),$globalIdMap$$=new Map;Logger.info("[restoreApp] \u0110ang t\u1ea1o b\u1ea3n \u0111\u1ed3 ID m\u1edbi...");$backupData$$["app.js"]&&($appInfo_collections_string_data_zip$$=$backupData$$["app.js"],delete $appInfo_collections_string_data_zip$$._id,
6
6
  delete $appInfo_collections_string_data_zip$$.__v,await model.updateOne({_id:$id_app$$},$appInfo_collections_string_data_zip$$),delete $backupData$$["app.js"]);$appInfo_collections_string_data_zip$$=Object.keys($backupData$$);$appInfo_collections_string_data_zip$$.forEach($colName$$=>{($backupData$$[$colName$$]||[]).forEach($row$$=>{if($row$$._id){const $newId$$=(new ObjectId).toString();$globalIdMap$$.set($row$$._id,$newId$$);$row$$._new_id_assigned=$newId$$}})});Logger.info(`[restoreApp] \u0110\u00e3 map ${$globalIdMap$$.size} IDs.`);
7
7
  for(const $colName$$ of $appInfo_collections_string_data_zip$$){const $rows$$=$backupData$$[$colName$$];$rows$$&&$rows$$.length!==0&&(Logger.info(`[restoreApp] Processing collection: ${$colName$$} (${$rows$$.length} docs)`),await new Promise(($resolve$$,$reject$$)=>{mongoose.connection.db.collection($colName$$,async($bulkOps_err$$,$coll$$)=>{if($bulkOps_err$$)return $reject$$($bulkOps_err$$);await $coll$$.deleteMany({id_app:$id_app$$});$bulkOps_err$$=$rows$$.map($row$$=>{const $newIdStr$$=$row$$._new_id_assigned||
8
- (new ObjectId).toString();delete $row$$._id;delete $row$$.__v;delete $row$$.pkey;delete $row$$._new_id_assigned;$row$$.id_app=$id_app$$;for(let $key$$ in $row$$)$row$$[$key$$]&&_.isString($row$$[$key$$])&&($key$$.includes("ngay_")||$key$$.includes("date")||$key$$==="createdAt"||$key$$==="updatedAt")&&!$key$$.includes("user")&&($row$$[$key$$]=new Date($row$$[$key$$]));deepReplaceId($row$$,$globalIdMap$$);return{insertOne:{document:{...$row$$,_id:new ObjectId($newIdStr$$)}}}});if($bulkOps_err$$.length>
8
+ (new ObjectId).toString();delete $row$$._id;delete $row$$.__v;delete $row$$.pkey;delete $row$$._new_id_assigned;$row$$.id_app=$id_app$$;for(let $key$$ in $row$$)if($row$$[$key$$]&&isDateValue($row$$[$key$$]))try{$row$$[$key$$]=new Date($row$$[$key$$])}catch($e$$){Logger.warn("[restoreApp] kh\u00f4ng th\u1ec3 convert gi\u00e1 tr\u1ecb sau ra ki\u1ec3u Date",$row$$[$key$$],$e$$)}deepReplaceId($row$$,$globalIdMap$$);return{insertOne:{document:{...$row$$,_id:new ObjectId($newIdStr$$)}}}});if($bulkOps_err$$.length>
9
9
  0)try{await $coll$$.bulkWrite($bulkOps_err$$),$resolve$$()}catch($e$$){$reject$$($e$$)}else $resolve$$()})}))}Logger.info("\u2705 [restoreApp] Kh\u00f4i ph\u1ee5c ho\u00e0n t\u1ea5t to\u00e0n b\u1ed9.");postToParent({result:"Kh\u00f4i ph\u1ee5c d\u1eef li\u1ec7u th\u00e0nh c\u00f4ng",id_task:$message$$.id_task})}).catch($e$$=>{Logger.error($e$$);postToParent({error:"L\u1ed7i x\u1eed l\u00fd file backup: "+$e$$.message,id_task:$message$$.id_task})})})};
10
10
  onParentMessage($msg$$=>{if($msg$$)try{_.isString($msg$$)&&($msg$$=JSON.parse($msg$$)),$msg$$.id&&processRestore($msg$$)}catch($e$$){Logger.error($e$$)}});