flexbiz-server 12.4.5 → 12.4.7

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.4.5",
5
+ "version": "12.4.7",
6
6
  "author": {
7
7
  "name": "Van Truong Pham",
8
8
  "email": "invncur@gmail.com"
@@ -1,12 +1,264 @@
1
- const moment=require("moment"),_=require("lodash"),permission=require("../libs/permission"),{JSONParser}=require("../libs/utils"),{getCacheReport,setCacheReport}=require("../libs/redis-cache"),cache_time=5,{getCurrentSession}=require("../libs/sessionContext"),rptHandler=async($ctrl$$,$req$$,$callback$$,$res$$)=>{console.log(`\u2705 [rptHanlder] sessionID=${getCurrentSession()?._debugId}`);const $rptId$$=$ctrl$$.module,$module$$=$ctrl$$.module,$options$$=$ctrl$$.options;let $notNeedRight$$=await $ctrl$$.notNeedRight($req$$.user);
2
- delete $req$$.query.rpt;let $body$$={};_.isObject($req$$.body)&&($body$$=$req$$.body);let $query$$={...$req$$.query,...$body$$};try{$query$$.tu_ngay&&($query$$.tu_ngay=moment($query$$.tu_ngay).startOf("date").toDate());$query$$.den_ngay&&($query$$.den_ngay=moment($query$$.den_ngay).endOf("date").toDate());$query$$.tu_ngay_kt&&($query$$.tu_ngay_kt=moment($query$$.tu_ngay_kt).startOf("date").toDate());$query$$.den_ngay_kt&&($query$$.den_ngay_kt=moment($query$$.den_ngay_kt).endOf("date").toDate());$query$$.tu_ngay_gio&&
3
- ($query$$.tu_ngay=moment($query$$.tu_ngay_gio).toDate());$query$$.den_ngay_gio&&($query$$.den_ngay=moment($query$$.den_ngay_gio).toDate());$query$$.tu_ngay_gio_kt&&($query$$.tu_ngay_kt=moment($query$$.tu_ngay_gio_kt).toDate());$query$$.den_ngay_gio_kt&&($query$$.den_ngay_kt=moment($query$$.den_ngay_gio_kt).toDate());for(let $q$$ in $query$$)if(!$query$$[$q$$])delete $query$$[$q$$];else if(_.isString($query$$[$q$$])&&($query$$[$q$$].indexOf("[")>=0||$query$$[$q$$].indexOf("{")>=0))try{$query$$[$q$$]=
4
- JSONParser($query$$[$q$$])}catch($e$$){console.error("[rptHanlder]can't parse json",$query$$[$q$$],$rptId$$)}$req$$.query=$query$$;const $_query$$=Object.assign({},$query$$);delete $_query$$.id_rpt;delete $_query$$.t;delete $_query$$.jsonstream;delete $_query$$.cType;delete $_query$$.refresh_required;delete $_query$$.isDrilldown;let $getData$$;const $getDataFromServer$$=$ctrl$$.getDataFunc();if($options$$.cache==0||$query$$.refresh_required||$options$$.stream)$getData$$=$getDataFromServer$$;else{let $cacheData$$=
5
- await getCacheReport($req$$.user.email,$req$$.user.current_id_app,$rptId$$,$_query$$,$options$$.cache_time||cache_time);if($cacheData$$){let $_data$$=$cacheData$$.data;$getData$$=$_data$$?function($req$$,$callback$$){$callback$$(null,$_data$$,!1,!0);setImmediate(()=>{$getDataFromServer$$($req$$,($error$$,$data$$)=>{$data$$&&setCacheReport($req$$.user.email,$req$$.user.current_id_app,$rptId$$,$_query$$,{data:$data$$,time:new Date,query:$_query$$})})})}:$getDataFromServer$$}else $getData$$=$getDataFromServer$$}let $streamData$$=
6
- function(){let $prechunk$$,$_interval$$,$sendHeader_yn$$,$rows$$=[];console.log(`\u2705 [rptHanlder] sessionID=${getCurrentSession()?._debugId}`);$getData$$($req$$,async($error$$,$data$$,$stream$$,$from_cache$$)=>{if($error$$){if(!$sendHeader_yn$$||!$options$$.stream||!$res$$)return $callback$$({error:$error$$.message||$error$$});$_interval$$&&clearInterval($_interval$$);setTimeout(()=>{$res$$.end(JSON.stringify({error:$error$$.toString()}))},1E3)}else if($options$$.stream&&$res$$)switch($stream$$){case "begin":console.log("begin stream",
7
- $rptId$$,"...");$query$$.jsonstream?$res$$.setHeader("Content-Type","application/jsonstream"):($res$$.setHeader("Content-Type","application/json"),$res$$.setHeader("status",200),$res$$.write(""));$sendHeader_yn$$=!0;$_interval$$=setInterval(()=>{console.log("running stream","log",$rptId$$,"...");$res$$.write("")},100);break;case "running":console.log("running stream",$rptId$$,"...");$res$$.write("");break;case "data":console.log("data stream",$rptId$$,"...");_.isArray($data$$)?$rows$$=$rows$$.concat($data$$):
8
- $rows$$.push($data$$);$query$$.jsonstream?$res$$.write(JSON.stringify($data$$)+"$$end%"):$prechunk$$?$res$$.write(","+JSON.stringify($data$$)):$res$$.write(JSON.stringify($data$$));$prechunk$$=$data$$;break;case "end":$_interval$$&&clearInterval($_interval$$);setImmediate(()=>{global.getModel("log").create({id_app:$req$$.user.current_id_app,id_func:$rptId$$,action:"VIEWRPT",data:{condition:JSON.stringify($query$$)}},$req$$.user.email,$req$$.user_agent,$req$$)});setImmediate(()=>{setCacheReport($req$$.user.email,
9
- $req$$.user.current_id_app,$rptId$$,$_query$$,{data:$rows$$,time:new Date,query:$_query$$})});setTimeout(function(){console.log("end stream",$rptId$$,"...");$res$$.end();$callback$$(null,"__end_stream__")},1E3);break;default:console.log($stream$$,$rptId$$,"..."),$res$$.write("")}else setImmediate(()=>{global.getModel("log").create({id_app:$req$$.user.current_id_app,id_func:$rptId$$,action:"VIEWRPT",data:{condition:JSON.stringify($query$$)}},$req$$.user.email,$req$$.user_agent,$req$$)}),$options$$.cache==
10
- 0||$from_cache$$||setCacheReport($req$$.user.email,$req$$.user.current_id_app,$rptId$$,$_query$$,{data:$data$$,time:new Date,query:$_query$$}),setImmediate(async()=>{let $report$$=$data$$;if(_.isArray($report$$)){if($query$$.fields){let $fields$$=$query$$.fields.split(",");$report$$=$report$$.map($item$$=>{let $_item$$={};$fields$$.forEach($field$$=>{$_item$$[$field$$]=$item$$[$field$$]});return $_item$$})}if($query$$.group_by&&$query$$.group_by_summary)try{$report$$=await $report$$.asyncGroupBy($query$$.group_by.split(","),
11
- $query$$.group_by_summary.split(","))}catch($e$$){return console.error("report groupBy data",$e$$,$rptId$$,"..."),$e$$.error?$callback$$($e$$):$callback$$({error:$e$$.message||$e$$})}}$callback$$(null,$report$$)})})};$options$$.require_id_app===!1?$streamData$$():permission.hasRight($req$$.params.id_app,$req$$.user.email,$module$$,"view",($error$$,$hr$$)=>{$hr$$?$streamData$$():$callback$$({error:"B\u1ea1n kh\u00f4ng c\u00f3 quy\u1ec1n xem b\u00e1o c\u00e1o n\u00e0y"})},{notNeedRight:$notNeedRight$$})}catch($e$$){return $e$$.error?
12
- $callback$$($e$$):$callback$$({error:$e$$.message||$e$$})}},{handlerWithSession}=require("../libs/sessionContext.js"),withSesssion=async($ctrl$$,$req$$,$callback$$,$res$$)=>{$ctrl$$.options?.useSession?handlerWithSession(rptHandler,$ctrl$$,$req$$,$callback$$,$res$$):rptHandler($ctrl$$,$req$$,$callback$$,$res$$)};module.exports=withSesssion;
1
+ const moment = require("moment");
2
+ const _ = require("lodash");
3
+ const permission = require('../libs/permission');
4
+ const {JSONParser} = require('../libs/utils');
5
+ const {getCacheReport,setCacheReport} = require("../libs/redis-cache")
6
+ const cache_time = 5;//minutes
7
+ const {getCurrentSession} = require("../libs/sessionContext")
8
+
9
+ const rptHandler = async (ctrl,req,callback,res=undefined)=> {
10
+ console.log(`✅ [rptHanlder] sessionID=${getCurrentSession()?._debugId}`);
11
+ const rptId = ctrl.module;
12
+ const module = ctrl.module;
13
+ const options = ctrl.options;
14
+ let notNeedRight = await ctrl.notNeedRight(req.user);
15
+ delete req.query["rpt"];
16
+ let body = {};
17
+ if(_.isObject(req.body)) body =req.body;
18
+ let query = {...req.query,...body};
19
+ try{
20
+ if (query.tu_ngay) {
21
+ query.tu_ngay = moment(query.tu_ngay).startOf("date").toDate();
22
+ }
23
+ if (query.den_ngay) {
24
+ query.den_ngay = moment(query.den_ngay).endOf("date").toDate();
25
+ }
26
+
27
+ if (query.tu_ngay_kt) {
28
+ query.tu_ngay_kt = moment(query.tu_ngay_kt).startOf("date").toDate();
29
+ }
30
+ if (query.den_ngay_kt) {
31
+ query.den_ngay_kt = moment(query.den_ngay_kt).endOf("date").toDate();
32
+ }
33
+
34
+ if(query.tu_ngay_gio) query.tu_ngay = moment(query.tu_ngay_gio).toDate();//ưu tiên lấy điều kiện tu_ngay_gio;
35
+ if(query.den_ngay_gio) query.den_ngay = moment(query.den_ngay_gio).toDate();//ưu tiên lấy điều kiện den_ngay_gio;
36
+ if(query.tu_ngay_gio_kt) query.tu_ngay_kt = moment(query.tu_ngay_gio_kt).toDate();//ưu tiên lấy điều kiện tu_ngay_gio;
37
+ if(query.den_ngay_gio_kt) query.den_ngay_kt = moment(query.den_ngay_gio_kt).toDate() ;//ưu tiên lấy điều kiện den_ngay_gio;
38
+
39
+
40
+ for (let q in query) {
41
+ if (!query[q]){
42
+ delete query[q];
43
+ }else{
44
+ if( _.isString(query[q]) && (query[q].indexOf("[")>=0 || query[q].indexOf("{")>=0)){
45
+ try{
46
+ query[q] = JSONParser(query[q]);
47
+ }catch(e){
48
+ console.error("[rptHanlder]can't parse json",query[q],rptId);
49
+ }
50
+ }
51
+ }
52
+ }
53
+ req.query = query;
54
+
55
+ ///create query cache
56
+ const _query = Object.assign({},query);
57
+ delete _query.id_rpt;
58
+ delete _query.t;
59
+ delete _query.jsonstream;
60
+ delete _query.cType;
61
+ delete _query.refresh_required;
62
+ delete _query.isDrilldown;
63
+ //
64
+ let getData;
65
+ let name_cached = rptId;
66
+ const getDataFromServer = ctrl.getDataFunc();
67
+ if (options.cache!=false && !query.refresh_required && !options.stream) {
68
+ //console.log("get cache",rptId,_query,"...");
69
+ let cacheData = await getCacheReport(req.user.email,req.user.current_id_app,name_cached,_query,options.cache_time||cache_time);
70
+ if(cacheData){
71
+ let _data = cacheData.data;
72
+ if (_data) {
73
+ //console.log("cache",rptId,_query,"...");
74
+ getData = function(req, callback) {
75
+ callback(null, _data,false,true);
76
+ setImmediate(()=>{
77
+ //cache report
78
+ getDataFromServer(req,(error,data)=>{
79
+ if(data){
80
+ setCacheReport(req.user.email,req.user.current_id_app,name_cached,_query, {
81
+ data: data,
82
+ time: new Date(),
83
+ query: _query
84
+ })
85
+ }
86
+ })
87
+ })
88
+ }
89
+ } else {
90
+ getData = getDataFromServer;
91
+ }
92
+ }else{
93
+ getData = getDataFromServer;
94
+ }
95
+ } else {
96
+ getData = getDataFromServer;
97
+ }
98
+ ///
99
+ let streamData = function() {
100
+ let prechunk,_interval,sendHeader_yn;
101
+ let rows = [];
102
+ console.log(`✅ [rptHanlder] sessionID=${getCurrentSession()?._debugId}`);
103
+ getData(req, async (error, data, stream,from_cache) => {
104
+ if (error) {
105
+ if (!sendHeader_yn || !options.stream || !res) return callback({error:error.message||error});
106
+ if (_interval) clearInterval(_interval);
107
+ setTimeout(() => {
108
+ res.end(JSON.stringify({error: error.toString()}));
109
+ }, 1000);
110
+ return;
111
+ }
112
+ //stream
113
+ if (options.stream && res) {
114
+ switch (stream) {
115
+ case "begin":
116
+ //begin stream
117
+ console.log("begin stream",rptId,"...")
118
+ if (!query.jsonstream) {
119
+ res.setHeader('Content-Type', 'application/json');
120
+ res.setHeader('status', 200);
121
+ res.write("");
122
+ } else {
123
+ res.setHeader('Content-Type', 'application/jsonstream');
124
+ }
125
+ sendHeader_yn = true;
126
+ //lien tuc gui thong tin toi client de tranh tinh trang disconnect
127
+ _interval = setInterval(() => {
128
+ console.log("running stream","log",rptId,"...");
129
+ res.write("");
130
+ }, 100);
131
+ break;
132
+ case "running":
133
+ console.log("running stream",rptId,"...")
134
+ res.write("");
135
+ break;
136
+ case "data":
137
+ console.log("data stream",rptId,"...")
138
+ if(_.isArray(data)){
139
+ rows = rows.concat(data);
140
+ }else{
141
+ rows.push(data);
142
+ }
143
+ if (!query.jsonstream) {
144
+ if (prechunk) {
145
+ res.write("," + JSON.stringify(data));
146
+ } else {
147
+ res.write(JSON.stringify(data));
148
+ }
149
+ } else {
150
+ res.write(JSON.stringify(data) + "$$end%");
151
+ }
152
+ prechunk = data;
153
+ break;
154
+ case "end":{
155
+ if (_interval) clearInterval(_interval);
156
+ setImmediate(()=>{
157
+ global.getModel("log").create({
158
+ id_app: req.user.current_id_app,
159
+ id_func: rptId,
160
+ action: 'VIEWRPT',
161
+ data: {
162
+ condition: JSON.stringify(query)
163
+ }
164
+ }, req.user.email, req.user_agent, req);
165
+ })
166
+ setImmediate(()=>{
167
+ //cache report
168
+ setCacheReport(req.user.email,req.user.current_id_app,name_cached,_query, {
169
+ data: rows,
170
+ time: new Date(),
171
+ query: _query
172
+ })
173
+ })
174
+ setTimeout(function() {
175
+ console.log("end stream",rptId,"...")
176
+ res.end();
177
+ callback(null,"__end_stream__");
178
+ }, 1000);
179
+ break;
180
+ }
181
+ default:
182
+ console.log(stream,rptId,"...")
183
+ res.write("");
184
+ }
185
+ } else {
186
+ setImmediate(()=>{
187
+ global.getModel("log").create({
188
+ id_app: req.user.current_id_app,
189
+ id_func: rptId,
190
+ action: 'VIEWRPT',
191
+ data: {
192
+ condition: JSON.stringify(query)
193
+ }
194
+ }, req.user.email, req.user_agent, req);
195
+ })
196
+ if(options.cache!=false && !from_cache){
197
+ //cache report
198
+ setCacheReport(req.user.email,req.user.current_id_app,name_cached,_query, {
199
+ data: data,
200
+ time: new Date(),
201
+ query: _query
202
+ })
203
+ }
204
+ //handle data
205
+ setImmediate(async ()=>{
206
+ let report = data;
207
+ if(_.isArray(report)){
208
+ if(query.fields){
209
+ let fields = query.fields.split(",");
210
+ report = report.map(item=>{
211
+ let _item={};
212
+ fields.forEach(field => {
213
+ _item[field] = item[field]
214
+ });
215
+ return _item;
216
+ })
217
+ }
218
+ if(query.group_by && query.group_by_summary){
219
+ try{
220
+ report = await report.asyncGroupBy(query.group_by.split(","), query.group_by_summary.split(","));
221
+ }catch(e){
222
+ console.error("report groupBy data",e,rptId,"...")
223
+ if(e.error){
224
+ return callback(e);
225
+ }
226
+ return callback({error:e.message || e});
227
+ }
228
+ }
229
+ }
230
+ callback(null,report);
231
+ })
232
+ }
233
+ });
234
+ }
235
+ if (options.require_id_app === false) {
236
+ streamData();
237
+ } else {
238
+ let id_app = req.params.id_app;
239
+ permission.hasRight(id_app, req.user.email, module, 'view', (error, hr) => {
240
+ if (hr) {
241
+ streamData();
242
+ } else {
243
+ callback({error:'Bạn không có quyền xem báo cáo này'});
244
+ }
245
+ }, {notNeedRight});
246
+ }
247
+ }catch(e){
248
+ if(e.error){
249
+ return callback(e);
250
+ }
251
+ return callback({error:e.message || e});
252
+ }
253
+ }
254
+
255
+ const { handlerWithSession } = require("../libs/sessionContext.js");
256
+ const withSesssion = async (ctrl,req,callback,res)=>{
257
+ if(ctrl.options?.useSession){
258
+ handlerWithSession(rptHandler,ctrl,req,callback,res)
259
+ }else{
260
+ rptHandler(ctrl,req,callback,res)
261
+ }
262
+
263
+ }
264
+ module.exports =withSesssion;