zet-lib 1.2.93 → 1.2.94

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.
Files changed (2) hide show
  1. package/lib/zReport.js +843 -792
  2. package/package.json +1 -1
package/lib/zReport.js CHANGED
@@ -1,438 +1,435 @@
1
- const axios = require('axios');
2
- const fs = require('fs-extra');
3
- const nodemailer = require('nodemailer');
4
- const qs = require('qs');
5
- const moment = require('moment');
6
- const XLSX = require('xlsx');
7
- const Excel = require('exceljs');
8
- const debug = require("./debug");
9
- const zRoute = require("./zRoute");
10
- const Util = require('./Util');
11
- const connection = require('./connection');
12
- const io = require('./io');
13
- const config = require('dotenv').config();
14
- const dirRoot = process.env.dirRoot;
15
- const zReport = {};
16
-
1
+ const axios = require('axios')
2
+ const fs = require('fs-extra')
3
+ const nodemailer = require('nodemailer')
4
+ const qs = require('qs')
5
+ const moment = require('moment')
6
+ const XLSX = require('xlsx')
7
+ const Excel = require('exceljs')
8
+ const debug = require('./debug')
9
+ const zRoute = require('./zRoute')
10
+ const Util = require('./Util')
11
+ const connection = require('./connection')
12
+ const io = require('./io')
13
+ const config = require('dotenv').config()
14
+ const zReport = {}
15
+ const myCache = require('./cache')
17
16
 
18
17
  /*
19
18
  Custom Reports
20
19
  Report Generator
21
20
  */
22
21
 
23
-
24
22
  /*
25
23
  UI For edit excel File
26
24
  */
27
25
  zReport.reportData = (filename, data, sessions = {}) => {
28
- console.log(filename);
29
- const workbook = XLSX.readFile(filename);
30
- const Sheets = workbook.Sheets;
31
- let sheet = Sheets[Object.keys(Sheets)[0]];
32
- let excel = Util.excelSequence();
33
- let ref = sheet["!ref"];
34
- let explode = ref.split(":");
35
- let lastchar = explode[1];
36
- let stringPattern = /[A-Z]+/i;
37
- let digitPattern = /[0-9]+/i;
38
- let stringColumn = lastchar.match(stringPattern)[0];
39
- let maxColumn = excel.indexOf(stringColumn);
40
-
41
- let maxRow = lastchar.match(digitPattern)[0];
42
- //add 5 row for input cells
43
- maxRow = parseInt(maxRow) + 5;
44
- let excelData = {};
45
- let excelValue = {};
46
- let tableModel = {};
47
- let dataForExcel = data.excel;
48
- let dataCallback = data.callback || [];
49
- let callback = {};
50
- let objQuery = {};
51
- let results = [];
52
-
53
- //set callback as object
54
- dataCallback.map((m) => {
55
- callback[m.name] = m.value;
56
- });
57
-
58
- //console.log(JSON.stringify(sessions));
59
-
60
- //create UI Button in excel cell
61
- if (dataForExcel) {
62
- dataForExcel.forEach((datafor, index) => {
63
- let button = "",
64
- name = datafor.name,
65
- callback = datafor.callback || "",
66
- value = datafor.value || "";
67
- let split = value.split(".");
68
- let len = split.length;
69
- let MYMODEL = {};
70
- let table = "", tableKey = "";
71
- if (len == 4) {
72
- table = split[2];
73
- tableKey = split[3];
74
- } else {
75
- table = split[0];
76
- tableKey = split[1];
77
- }
26
+ console.log(filename)
27
+ const workbook = XLSX.readFile(filename)
28
+ const Sheets = workbook.Sheets
29
+ let sheet = Sheets[Object.keys(Sheets)[0]]
30
+ let excel = Util.excelSequence()
31
+ let ref = sheet['!ref']
32
+ let explode = ref.split(':')
33
+ let lastchar = explode[1]
34
+ let stringPattern = /[A-Z]+/i
35
+ let digitPattern = /[0-9]+/i
36
+ let stringColumn = lastchar.match(stringPattern)[0]
37
+ let maxColumn = excel.indexOf(stringColumn)
38
+
39
+ let maxRow = lastchar.match(digitPattern)[0]
40
+ //add 5 row for input cells
41
+ maxRow = parseInt(maxRow) + 5
42
+ let excelData = {}
43
+ let excelValue = {}
44
+ let tableModel = {}
45
+ let dataForExcel = data.excel
46
+ let dataCallback = data.callback || []
47
+ let callback = {}
48
+ let objQuery = {}
49
+ let results = []
50
+
51
+ //set callback as object
52
+ dataCallback.map((m) => {
53
+ callback[m.name] = m.value
54
+ })
55
+
56
+ //console.log(JSON.stringify(sessions));
57
+
58
+ //create UI Button in excel cell
59
+ if (dataForExcel) {
60
+ dataForExcel.forEach((datafor, index) => {
61
+ let button = '',
62
+ name = datafor.name,
63
+ callback = datafor.callback || '',
64
+ value = datafor.value || ''
65
+ let split = value.split('.')
66
+ let len = split.length
67
+ let MYMODEL = {}
68
+ let table = '',
69
+ tableKey = ''
70
+ if (len == 4) {
71
+ table = split[2]
72
+ tableKey = split[3]
73
+ } else {
74
+ table = split[0]
75
+ tableKey = split[1]
76
+ }
77
+
78
+ const MYMODELS = zRoute.MYMODELS() || {}
79
+ MYMODEL = tableModel.hasOwnProperty(table) ? tableModel[table] : MYMODELS[table]
80
+ if (!objQuery[table]) {
81
+ objQuery[table] = []
82
+ }
83
+ objQuery[table].push(value)
84
+ if (!excelValue) {
85
+ excelValue[name] = ''
86
+ } else {
87
+ button = excelValue[name] || ''
88
+ }
89
+
90
+ let labels = value.indexOf('_SESSIONS_') > -1 ? value.replace('_SESSIONS_.', '') : tableKey
91
+ button += `<li class="dragged"> <button class="btn btn-info btn-excel" type="button" title="${name.replace('[', '').replace(']', '')} : ${value}">${MYMODEL.labels[labels]}
92
+ <input type="hidden" class="EXCEL" name="${name}" value='${value}_CALLBACK_SEPARATOR_${callback}'> <i class="fa fa-code call-me"></i> <i class="fa fa-trash trash-me"></i></button></li>`
93
+ excelValue[name] = button
94
+ })
95
+ }
96
+ //end UI
97
+
98
+ let table = `<table class="table table-striped table-bordered" >`
99
+ for (var x = 1; x < maxRow; x++) {
100
+ table += `<tr>`
101
+ let arr = []
102
+ for (var i = 0; i <= maxColumn; i++) {
103
+ let str = excel[i] + x
104
+ let strkey = excel[i] + '[' + x + ']'
105
+ let defaultValue = Object.prototype.hasOwnProperty.call(sheet, str) ? sheet[str].v : ''
106
+ let value = excelValue[strkey] || defaultValue
107
+ table += `<td width="80px" id="${str}" title="${str}" class="mydragable" data-col="${excel[i]}" data-row="${x}">${value}</td>`
108
+ arr.push(value)
109
+ }
110
+ table += `</tr>`
111
+ results.push(arr)
112
+ }
113
+ table += `</table>`
114
+ return {
115
+ table: table,
116
+ excelData: excelData,
117
+ results: results,
118
+ max: maxRow,
119
+ objQuery: objQuery,
120
+ }
121
+ }
78
122
 
79
- const MYMODELS = zRoute.MYMODELS() || {};
80
- MYMODEL = tableModel.hasOwnProperty(table) ? tableModel[table] : MYMODELS[table];
81
- if (!objQuery[table]) {
82
- objQuery[table] = [];
83
- }
84
- objQuery[table].push(value);
85
- if (!excelValue) {
86
- excelValue[name] = "";
87
- } else {
88
- button = excelValue[name] || "";
89
- }
123
+ //Save reports Setup
124
+ zReport.reportPostData = async (req, res) => {
125
+ let data_status = Util.jsonSuccess('Success')
126
+ try {
127
+ let body = req.body
128
+ ///console.log(body)
129
+ let post = zRoute.postData(body)
130
+ let ex = post.excel
131
+ delete post.excel
132
+ let id = body.id
133
+ let CALLBACK_SEPARATOR = '_CALLBACK_SEPARATOR_'
134
+
135
+ //remove CALLBACK in query
136
+ //sometimes bug in query callback separator in javascript
137
+ let query = body.query
138
+ query = Util.replaceAll(query, CALLBACK_SEPARATOR, '')
139
+ let callback = [],
140
+ excel = []
141
+ ex.map((e) => {
142
+ let name = e.name || ''
143
+ let value = e.value || ''
144
+ //console.log(value);
145
+ if (value.indexOf(CALLBACK_SEPARATOR) > -1) {
146
+ let split = value.split(CALLBACK_SEPARATOR)
147
+ excel.push({
148
+ name: name,
149
+ title: name.replace('[', '').replace(']', ''),
150
+ value: split[0],
151
+ callback: Util.replaceAll(split[1], "'", '"'),
152
+ })
153
+ }
154
+ })
155
+ post.excel = excel || ''
156
+ post.query = query || ''
157
+ await connection.update({
158
+ table: 'zreport',
159
+ data: { json: JSON.stringify(post) },
160
+ where: {
161
+ id: id,
162
+ },
163
+ })
164
+ } catch (err) {
165
+ debug(req, res, err)
166
+ data_status = Util.flashError(err.toString())
167
+ }
168
+ res.json(data_status)
169
+ }
90
170
 
91
- let labels = value.indexOf("_SESSIONS_") > -1 ? value.replace("_SESSIONS_.", "") : tableKey;
92
- button += `<li class="dragged"> <button class="btn btn-info btn-excel" type="button" title="${name.replace('[', '').replace(']', '')} : ${value}">${MYMODEL.labels[labels]}
93
- <input type="hidden" class="EXCEL" name="${name}" value='${value}_CALLBACK_SEPARATOR_${callback}'> <i class="fa fa-code call-me"></i> <i class="fa fa-trash trash-me"></i></button></li>`;
94
- excelValue[name] = button;
95
- });
171
+ //SUBMIT REPORT ROUTE FOR REPORT GENERATOR
172
+ zReport.submitReport = async (req, res) => {
173
+ let company_id = res.locals.companyId
174
+ let body = req.body
175
+ console.log('BODYYYYYY')
176
+ console.log(body)
177
+ delete body._csrf
178
+ const MYMODELS = zRoute.MYMODELS() || {}
179
+ //delete key where null
180
+ for (let keys in body) {
181
+ if (body[keys] == '') {
182
+ delete body[keys]
96
183
  }
97
- //end UI
98
-
99
- let table = `<table class="table table-striped table-bordered" >`;
100
- for (var x = 1; x < maxRow; x++) {
101
- table += `<tr>`;
102
- let arr = [];
103
- for (var i = 0; i <= maxColumn; i++) {
104
- let str = excel[i] + x;
105
- let strkey = excel[i] + "[" + x + "]";
106
- let defaultValue = Object.prototype.hasOwnProperty.call(sheet, str) ? sheet[str].v : "";
107
- let value = excelValue[strkey] || defaultValue;
108
- table += `<td width="80px" id="${str}" title="${str}" class="mydragable" data-col="${excel[i]}" data-row="${x}">${value}</td>`;
109
- arr.push(value)
110
- }
111
- table += `</tr>`;
112
- results.push(arr);
184
+ if (body[keys] == 'undefined') {
185
+ delete body[keys]
113
186
  }
114
- table += `</table>`;
115
- return {
116
- table: table,
117
- excelData: excelData,
118
- results: results,
119
- max: maxRow,
120
- objQuery: objQuery
187
+ }
188
+ //console.log(body);
189
+ let $session = req.session.user
190
+ try {
191
+ let reportId = body.zreport_name
192
+ let row = await connection.result({
193
+ table: 'zreport',
194
+ where: {
195
+ id: reportId,
196
+ },
197
+ })
198
+ let json = row.json ? row.json : {}
199
+ console.log(json)
200
+ let query = json.query || ''
201
+ let table = json.tables[0] || ''
202
+ if (!table) {
203
+ return res.json('error not configure!')
121
204
  }
122
- };
123
-
205
+ let title = row.title
206
+ let jsonExcels = json.excel || []
207
+ let excelObj = {}
208
+ let callback = {}
209
+ jsonExcels.map((jsonExcel) => {
210
+ if (!excelObj[jsonExcel.name]) excelObj[jsonExcel.name] = []
211
+
212
+ let jsonvalue = Util.replaceAll(jsonExcel.value, '.', '___')
213
+ let nameCallback = jsonExcel.title + '___' + jsonvalue
214
+
215
+ jsonExcel.callbackName = nameCallback
216
+
217
+ let split = jsonvalue.split('___')
218
+ if (split.length == 2) {
219
+ jsonExcel.data = jsonvalue
220
+ } else if (split.length == 3) {
221
+ jsonExcel.data = split[0] + '___' + split[1]
222
+ } else {
223
+ jsonExcel.data = jsonvalue
224
+ }
225
+
226
+ if (jsonExcel.callback) callback[nameCallback] = jsonExcel.callback
227
+
228
+ excelObj[jsonExcel.name].push(jsonExcel)
229
+ })
124
230
 
125
- //Save reports Setup
126
- zReport.reportPostData = async(req, res) => {
127
- let data_status = Util.jsonSuccess("Success");
128
- try {
129
- let body = req.body;
130
- ///console.log(body)
131
- let post = zRoute.postData(body);
132
- let ex = post.excel;
133
- delete post.excel;
134
- let id = body.id;
135
- let CALLBACK_SEPARATOR = "_CALLBACK_SEPARATOR_";
136
-
137
- //remove CALLBACK in query
138
- //sometimes bug in query callback separator in javascript
139
- let query = body.query;
140
- query = Util.replaceAll(query, CALLBACK_SEPARATOR, "");
141
- let callback = [], excel = [];
142
- ex.map((e) => {
143
- let name = e.name || "";
144
- let value = e.value || "";
145
- //console.log(value);
146
- if (value.indexOf(CALLBACK_SEPARATOR) > -1) {
147
- let split = value.split(CALLBACK_SEPARATOR);
148
- excel.push({
149
- name: name,
150
- title: name.replace("[", "").replace("]", ""),
151
- value: split[0],
152
- callback: Util.replaceAll(split[1], "'", '"')
153
- });
154
- }
155
- });
156
- post.excel = excel || "";
157
- post.query = query || "";
158
- await connection.update({
159
- table : "zreport",
160
- data : {json: JSON.stringify(post)},
161
- where : {
162
- id : id
163
- }
164
- });
165
- } catch (err) {
166
- debug(req, res, err);
167
- data_status = Util.flashError(err.toString());
231
+ delete body.zreports_name
232
+
233
+ //console.log(filterWhere);
234
+ //excel instance
235
+ var workbook = new Excel.Workbook()
236
+ let filename = `${dirRoot}/public/uploads/zreport/${row.excel}`
237
+ await workbook.xlsx.readFile(filename)
238
+ var worksheet = workbook.worksheets[0] //the first one;
239
+ let images = [] // store images
240
+ // Force workbook calculation on load
241
+ //workbook.calcProperties.fullCalcOnLoad = true;
242
+
243
+ //set images
244
+ var setExcelImages = (script, data, r, c) => {
245
+ let excelsq = Util.excelSequence()
246
+ //A1 = col=0 row=0
247
+ //convert column to integer
248
+ c = excelsq.indexOf(c)
249
+ r = r - 1
250
+ script = script || ''
251
+ if (script == '') {
252
+ return ''
253
+ }
254
+ data = data || ''
255
+ if (data == '') {
256
+ return ''
257
+ }
258
+
259
+ let str = script.replace('hasImages(', '').replace(')', '')
260
+ let explode = str.split(',')
261
+ let table = explode[0].trim() || ''
262
+ let width = parseInt(explode[1]) || 200
263
+ let height = parseInt(explode[2]) || 200
264
+ let photoName = `${dirRoot}/public/uploads/${table}/${data}`
265
+ if (!fs.existsSync(photoName)) {
266
+ return ''
267
+ }
268
+ let image = workbook.addImage({
269
+ filename: photoName,
270
+ extension: data.split('.').pop(),
271
+ })
272
+ images.push({
273
+ image: image,
274
+ width: width,
275
+ height: height,
276
+ c: c,
277
+ r: r,
278
+ })
279
+
280
+ return ''
168
281
  }
169
- res.json(data_status);
170
- };
171
-
172
-
173
- //SUBMIT REPORT ROUTE FOR REPORT GENERATOR
174
- zReport.submitReport = async(req, res) => {
175
- let company_id = res.locals.companyId;
176
- let body = req.body;
177
- console.log("BODYYYYYY");
178
- console.log(body);
179
- delete body._csrf;
180
- const MYMODELS = zRoute.MYMODELS() || {};
181
- //delete key where null
182
- for (let keys in body) {
183
- if (body[keys] == "") {
184
- delete body[keys];
185
- }
186
- if (body[keys] == "undefined") {
187
- delete body[keys];
282
+ //end set images
283
+
284
+ //query where sql;
285
+ //query executes
286
+ console.log('query')
287
+ console.log(JSON.stringify(query))
288
+ console.log('query')
289
+
290
+ let datas = []
291
+ if (query) {
292
+ var wheres = []
293
+ var whereArr = []
294
+ var where = ''
295
+ //TODO if has order by limit
296
+ var sql = json.query
297
+ console.log('sql')
298
+ console.log(sql)
299
+ console.log('sql')
300
+
301
+ var num = 1
302
+ for (var key in json.filter) {
303
+ if (body[key]) {
304
+ wheres.push(Util.replaceAll(json.filter[key], '?', `$${num}`))
305
+ if (json.filter[key].includes('LIKE')) {
306
+ whereArr.push(`%${body[key]}%`)
307
+ } else {
308
+ whereArr.push(body[key])
309
+ }
310
+ num++
188
311
  }
312
+ }
313
+
314
+ //row.wheres from database
315
+ var rowWheres = row.wheres || []
316
+ rowWheres.forEach(function (item) {
317
+ wheres.push(item)
318
+ })
319
+
320
+ if (wheres.length) {
321
+ where += ' WHERE '
322
+ where += wheres.join(' AND ')
323
+ }
324
+ var orderby = ''
325
+ if (row.orderby) {
326
+ orderby = ` ORDER BY ${row.orderby} `
327
+ }
328
+ sql = sql + where + orderby
329
+ console.log('sql')
330
+ console.log(sql)
331
+ console.log('sql')
332
+
333
+ console.log('whereArr')
334
+ console.log(JSON.stringify(whereArr))
335
+ console.log('whereArr')
336
+ datas = await connection.query(sql, whereArr)
189
337
  }
190
- //console.log(body);
191
- let $session = req.session.user;
192
- try {
193
- let reportId = body.zreport_name;
194
- let row = await connection.result({
195
- table: "zreport",
196
- where: {
197
- id: reportId
198
- }
199
- });
200
- let json = row.json ? row.json : {};
201
- console.log(json);
202
- let query = json.query || "";
203
- let table = json.tables[0] || "";
204
- if (!table) {
205
- return res.json("error not configure!");
206
- }
207
- let title = row.title;
208
- let jsonExcels = json.excel || [];
209
- let excelObj = {};
210
- let callback = {};
211
- jsonExcels.map((jsonExcel) => {
212
- if (!excelObj[jsonExcel.name])
213
- excelObj[jsonExcel.name] = [];
214
-
215
- let jsonvalue = Util.replaceAll(jsonExcel.value, ".", "___");
216
- let nameCallback = jsonExcel.title + "___" + jsonvalue;
217
-
218
- jsonExcel.callbackName = nameCallback;
219
-
220
- let split = jsonvalue.split("___");
221
- if (split.length == 2) {
222
- jsonExcel.data = jsonvalue;
223
- } else if (split.length == 3) {
224
- jsonExcel.data = split[0] + "___" + split[1];
225
- } else {
226
- jsonExcel.data = jsonvalue;
227
- }
228
338
 
229
- if (jsonExcel.callback)
230
- callback[nameCallback] = jsonExcel.callback;
231
-
232
- excelObj[jsonExcel.name].push(jsonExcel);
233
- });
234
-
235
- delete body.zreports_name;
236
-
237
- //console.log(filterWhere);
238
- //excel instance
239
- var workbook = new Excel.Workbook();
240
- let filename = `${dirRoot}/public/uploads/zreport/${row.excel}`;
241
- await workbook.xlsx.readFile(filename);
242
- var worksheet = workbook.worksheets[0]; //the first one;
243
- let images = []; // store images
244
- // Force workbook calculation on load
245
- //workbook.calcProperties.fullCalcOnLoad = true;
246
-
247
- //set images
248
- var setExcelImages = (script, data, r, c) => {
249
- let excelsq = Util.excelSequence();
250
- //A1 = col=0 row=0
251
- //convert column to integer
252
- c = excelsq.indexOf(c);
253
- r = r - 1;
254
- script = script || "";
255
- if (script == "") {
256
- return "";
257
- }
258
- data = data || "";
259
- if (data == "") {
260
- return "";
261
- }
339
+ let excelMap = {}
340
+ let beginLooping = 0
341
+ for (let keys in excelObj) {
342
+ let split = keys.split('[')
343
+ let column = split[0]
344
+ let idx = parseInt(split[1])
262
345
 
263
- let str = script.replace("hasImages(", "").replace(")", "");
264
- let explode = str.split(",");
265
- let table = explode[0].trim() || "";
266
- let width = parseInt(explode[1]) || 200;
267
- let height = parseInt(explode[2]) || 200;
268
- let photoName = `${dirRoot}/public/uploads/${table}/${data}`;
269
- if (!fs.existsSync(photoName)) {
270
- return "";
271
- }
272
- let image = workbook.addImage({
273
- filename: photoName,
274
- extension: data.split(".").pop()
275
- });
276
- images.push({
277
- image: image,
278
- width: width,
279
- height: height,
280
- c: c,
281
- r: r,
282
- });
283
-
284
- return "";
285
- };
286
- //end set images
287
-
288
- //query where sql;
289
- //query executes
290
- console.log("query")
291
- console.log(JSON.stringify(query))
292
- console.log("query")
293
-
294
- let datas = [];
295
- if (query) {
296
- var wheres = [];
297
- var whereArr = [];
298
- var where = "";
299
- //TODO if has order by limit
300
- var sql = json.query;
301
- console.log("sql");
302
- console.log(sql);
303
- console.log("sql");
304
-
305
- var num = 1;
306
- for (var key in json.filter) {
307
- if (body[key]) {
308
- wheres.push( Util.replaceAll(json.filter[key],"?",`$${num}`));
309
- if (json.filter[key].includes("LIKE")) {
310
- whereArr.push(`%${body[key]}%`)
311
- } else {
312
- whereArr.push(body[key])
313
- }
314
- num++;
315
- }
316
- }
346
+ if (!excelMap[keys]) excelMap[keys] = {}
317
347
 
318
- //row.wheres from database
319
- var rowWheres = row.wheres || [];
320
- rowWheres.forEach(function (item) {
321
- wheres.push(item);
322
- });
323
-
324
- if (wheres.length) {
325
- where += " WHERE ";
326
- where += wheres.join(" AND ");
327
- }
328
- var orderby = "";
329
- if (row.orderby) {
330
- orderby = ` ORDER BY ${row.orderby} `;
331
- }
332
- sql = sql + where + orderby;
333
- console.log("sql")
334
- console.log(sql)
335
- console.log("sql")
336
-
337
- console.log("whereArr")
338
- console.log(JSON.stringify(whereArr))
339
- console.log("whereArr")
340
- datas = await connection.query(sql, whereArr);
341
- }
342
-
343
- let excelMap = {};
344
- let beginLooping = 0
345
- for (let keys in excelObj) {
346
- let split = keys.split("[");
347
- let column = split[0];
348
- let idx = parseInt(split[1]);
348
+ excelMap[keys].column = column
349
+ excelMap[keys].row = idx
350
+ excelMap[keys].rowColumn = column + idx
351
+ if (beginLooping == 0) beginLooping = idx
352
+ }
349
353
 
350
- if (!excelMap[keys]) excelMap[keys] = {}
354
+ console.log('datas')
355
+ console.log(JSON.stringify(datas))
356
+ console.log('datas')
351
357
 
352
- excelMap[keys].column = column;
353
- excelMap[keys].row = idx;
354
- excelMap[keys].rowColumn = column + idx;
355
- if (beginLooping == 0)
356
- beginLooping = idx;
358
+ if (datas.length > 1) {
359
+ try {
360
+ for (var i = 0; i < datas.length - 1; i++) {
361
+ let r = i + beginLooping
362
+ worksheet.spliceRows(r + 1, 1, true)
363
+ worksheet.duplicateRow(r, 1, true)
357
364
  }
365
+ } catch (e) {
366
+ console.log('no style')
367
+ }
368
+ }
358
369
 
359
- console.log("datas")
360
- console.log(JSON.stringify(datas))
361
- console.log("datas")
362
-
363
- if (datas.length > 1) {
364
- try {
365
- for (var i = 0; i < (datas.length - 1); i++) {
366
- let r = i + beginLooping;
367
- worksheet.spliceRows(r + 1, 1, true);
368
- worksheet.duplicateRow(r, 1, true);
369
- }
370
- } catch (e) {
371
- console.log("no style");
372
- }
373
- }
370
+ var ioroom = function (err) {
371
+ io.to(res.locals.user.token).emit('error', err.toString())
372
+ }
374
373
 
375
- var ioroom = function (err) {
376
- io.to(res.locals.user.token).emit("error", err.toString());
377
- };
374
+ datas.forEach((data, index) => {
375
+ for (let keys in excelObj) {
376
+ let columnIndex = excelMap[keys].column
377
+ let rowIndex = parseInt(excelMap[keys].row) + index
378
+ let rowColumn = columnIndex + rowIndex
379
+ let value = excelObj[keys]
380
+ .map((m) => {
381
+ //console.log(m)
382
+ return callback.hasOwnProperty(m.callbackName) ? (callback[m.callbackName].indexOf('hasImages') > -1 ? setExcelImages(callback[m.callbackName], data[m.data], rowIndex, columnIndex) : zReport.callbackReport(callback[m.callbackName], data[m.data], rowIndex, columnIndex, null, data, ioroom, res)) : data[m.data]
383
+ })
384
+ .join(' ')
385
+
386
+ worksheet.getCell(rowColumn).value = Util.isNumeric(value) ? parseFloat(value) : value
387
+ }
388
+ })
389
+ //build images if any
390
+ images.map((m) => {
391
+ worksheet.addImage(m.image, {
392
+ tl: { col: m.c, row: m.r },
393
+ ext: { width: m.width, height: m.height },
394
+ })
395
+ })
378
396
 
379
- datas.forEach((data, index) => {
380
- for (let keys in excelObj) {
381
- let columnIndex = excelMap[keys].column;
382
- let rowIndex = parseInt(excelMap[keys].row) + index;
383
- let rowColumn = columnIndex + rowIndex;
384
- let value = excelObj[keys].map((m) => {
385
- //console.log(m)
386
- return callback.hasOwnProperty(m.callbackName) ? callback[m.callbackName].indexOf("hasImages") > -1 ? setExcelImages(callback[m.callbackName], data[m.data], rowIndex, columnIndex) : zReport.callbackReport(callback[m.callbackName], data[m.data], rowIndex, columnIndex, null, data, ioroom, res) : data[m.data]
387
- }).join(" ");
388
-
389
- worksheet.getCell(rowColumn).value = Util.isNumeric(value) ? parseFloat(value) : value;
390
- }
391
- });
392
- //build images if any
393
- images.map((m)=> {
394
- worksheet.addImage(m.image, {
395
- tl: {col: m.c, row: m.r},
396
- ext: {width: m.width, height: m.height}
397
- });
398
- });
399
-
400
- var fileName = title + '.xlsx';
401
- if (row.scripts) {
402
- return zReport.additionalScripts(req,res,row.scripts, fileName, datas, moment, Util, dirRoot, ioroom, connection, worksheet,workbook,debug)
403
- } else {
404
- res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
405
- res.setHeader('Content-Disposition', 'attachment; filename=' + fileName);
406
- await workbook.xlsx.write(res);
407
- res.end();
408
- }
409
- } catch (e) {
410
- console.log(e)
411
- debug(req, res, e);
412
- res.json(e.toString())
397
+ var fileName = title + '.xlsx'
398
+ if (row.scripts) {
399
+ return zReport.additionalScripts(req, res, row.scripts, fileName, datas, moment, Util, dirRoot, ioroom, connection, worksheet, workbook, debug)
400
+ } else {
401
+ res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
402
+ res.setHeader('Content-Disposition', 'attachment; filename=' + fileName)
403
+ await workbook.xlsx.write(res)
404
+ res.end()
413
405
  }
406
+ } catch (e) {
407
+ console.log(e)
408
+ debug(req, res, e)
409
+ res.json(e.toString())
410
+ }
414
411
  }
415
412
 
416
- zReport.additionalScripts = (req,res,script, fileName, datas, moment, Util, dirRoot, ioroom, connection, worksheet, workbook) => {
417
- script = script.trim() || "";
418
- let CALL = {
419
- Util: Util,
420
- moment: moment,
421
- datas: datas,
422
- dirRoot: dirRoot,
423
- ioroom: ioroom,
424
- res: res,
425
- req:req,
426
- fileName: fileName,
427
- connection: connection,
428
- worksheet: worksheet,
429
- workbook : workbook,
430
- };
431
- let STRINGS_VARIABLE = "";
432
- Object.keys(CALL).forEach(function (item) {
433
- STRINGS_VARIABLE += ` var ${item} = this.${item}; `;
434
- });
435
- return Function(`
413
+ zReport.additionalScripts = (req, res, script, fileName, datas, moment, Util, dirRoot, ioroom, connection, worksheet, workbook) => {
414
+ script = script.trim() || ''
415
+ let CALL = {
416
+ Util: Util,
417
+ moment: moment,
418
+ datas: datas,
419
+ dirRoot: dirRoot,
420
+ ioroom: ioroom,
421
+ res: res,
422
+ req: req,
423
+ fileName: fileName,
424
+ connection: connection,
425
+ worksheet: worksheet,
426
+ workbook: workbook,
427
+ }
428
+ let STRINGS_VARIABLE = ''
429
+ Object.keys(CALL).forEach(function (item) {
430
+ STRINGS_VARIABLE += ` var ${item} = this.${item}; `
431
+ })
432
+ return Function(`
436
433
  var runcode = async() => {
437
434
  ${STRINGS_VARIABLE}
438
435
  try {
@@ -448,38 +445,38 @@ zReport.additionalScripts = (req,res,script, fileName, datas, moment, Util, dirR
448
445
  };
449
446
  runcode();
450
447
 
451
- `).call(CALL);
452
- };
448
+ `).call(CALL)
449
+ }
453
450
 
454
451
  zReport.callbackReport = (script, data, row, column, selectFromTable, obj, ioroom, res) => {
455
- script = script.trim() || "";
456
- let results = {}
457
- for (var key in obj) {
458
- let name = key.split("___");
459
- if (name.length > 0) {
460
- results[name[1]] = obj[key];
461
- }
452
+ script = script.trim() || ''
453
+ let results = {}
454
+ for (var key in obj) {
455
+ let name = key.split('___')
456
+ if (name.length > 0) {
457
+ results[name[1]] = obj[key]
462
458
  }
463
-
464
- let first = script.charAt(0);
465
- let CALL = {
466
- Util: Util,
467
- obj: obj,
468
- moment: moment,
469
- data: data,
470
- dirRoot: dirRoot,
471
- selectFromTable: selectFromTable,
472
- row: row,
473
- col: column,
474
- results: results,
475
- ioroom,
476
- res: res
477
- };
478
- let STRINGS_VARIABLE = "";
479
- Object.keys(CALL).forEach(function (item) {
480
- STRINGS_VARIABLE += ` var ${item} = this.${item}; `;
481
- });
482
- return Function(`
459
+ }
460
+
461
+ let first = script.charAt(0)
462
+ let CALL = {
463
+ Util: Util,
464
+ obj: obj,
465
+ moment: moment,
466
+ data: data,
467
+ dirRoot: dirRoot,
468
+ selectFromTable: selectFromTable,
469
+ row: row,
470
+ col: column,
471
+ results: results,
472
+ ioroom,
473
+ res: res,
474
+ }
475
+ let STRINGS_VARIABLE = ''
476
+ Object.keys(CALL).forEach(function (item) {
477
+ STRINGS_VARIABLE += ` var ${item} = this.${item}; `
478
+ })
479
+ return Function(`
483
480
  ${STRINGS_VARIABLE}
484
481
  try {
485
482
  ${script};
@@ -487,93 +484,130 @@ zReport.callbackReport = (script, data, row, column, selectFromTable, obj, ioroo
487
484
  console.log(e);
488
485
  ioroom("CELLS : " + col+row+ " " +e.toString());
489
486
  }
490
- `).call(CALL);
491
-
492
- };
487
+ `).call(CALL)
488
+ }
493
489
 
494
490
  zReport.staticDataReport = (data, filter) => {
495
- delete data.id;
496
- delete data.password;
497
- delete data.token;
498
- let session_obj = {};
499
- let session_obj_fields = {}
500
-
501
- filter.map((m) => {
502
- let keyName = m.name;
503
- session_obj[keyName] = m.label;
504
- session_obj_fields[keyName] = {
505
- name: keyName,
506
- title: m.label,
507
- type: "text",
508
- category: "text",
509
- length: "undefined",
510
- required: false,
511
- search: "LIKE",
512
- key: "",
513
- placeholder: m.label
514
- }
515
- });
516
-
517
- for (var key in data) {
518
- let keyName = "$session." + key;
519
- session_obj[keyName] = key;
520
- session_obj_fields[keyName] = {
521
- name: keyName,
522
- title: key,
523
- type: "text",
524
- category: "text",
525
- length: "undefined",
526
- required: false,
527
- search: "LIKE",
528
- key: "",
529
- placeholder: key
530
- }
531
-
532
- if (key == "company") {
533
- for (var k in data[key]) {
534
- let keyName2 = "$session.company." + k;
535
- session_obj[keyName2] = k;
536
- session_obj_fields[keyName2] = {
537
- name: keyName2,
538
- title: key + " " + k,
539
- type: "text",
540
- category: "text",
541
- length: "undefined",
542
- required: false,
543
- search: "LIKE",
544
- key: "",
545
- placeholder: key + " " + k,
546
- }
547
- }
548
- }
491
+ delete data.id
492
+ delete data.password
493
+ delete data.token
494
+ let session_obj = {}
495
+ let session_obj_fields = {}
496
+
497
+ filter.map((m) => {
498
+ let keyName = m.name
499
+ session_obj[keyName] = m.label
500
+ session_obj_fields[keyName] = {
501
+ name: keyName,
502
+ title: m.label,
503
+ type: 'text',
504
+ category: 'text',
505
+ length: 'undefined',
506
+ required: false,
507
+ search: 'LIKE',
508
+ key: '',
509
+ placeholder: m.label,
510
+ }
511
+ })
512
+
513
+ for (var key in data) {
514
+ let keyName = '$session.' + key
515
+ session_obj[keyName] = key
516
+ session_obj_fields[keyName] = {
517
+ name: keyName,
518
+ title: key,
519
+ type: 'text',
520
+ category: 'text',
521
+ length: 'undefined',
522
+ required: false,
523
+ search: 'LIKE',
524
+ key: '',
525
+ placeholder: key,
549
526
  }
550
527
 
551
- return {
552
- table: '_SESSIONS_',
553
- routeName: "_SESSIONS_",
554
- keys: Object.keys(session_obj),
555
- labels: session_obj,
556
- fields: session_obj_fields,
557
- relations: {},
558
- dropdowns: {},
559
- modules: {}
528
+ if (key == 'company') {
529
+ for (var k in data[key]) {
530
+ let keyName2 = '$session.company.' + k
531
+ session_obj[keyName2] = k
532
+ session_obj_fields[keyName2] = {
533
+ name: keyName2,
534
+ title: key + ' ' + k,
535
+ type: 'text',
536
+ category: 'text',
537
+ length: 'undefined',
538
+ required: false,
539
+ search: 'LIKE',
540
+ key: '',
541
+ placeholder: key + ' ' + k,
542
+ }
543
+ }
560
544
  }
545
+ }
546
+
547
+ return {
548
+ table: '_SESSIONS_',
549
+ routeName: '_SESSIONS_',
550
+ keys: Object.keys(session_obj),
551
+ labels: session_obj,
552
+ fields: session_obj_fields,
553
+ relations: {},
554
+ dropdowns: {},
555
+ modules: {},
556
+ }
561
557
  }
562
558
 
563
- zReport.listReports = async(data) => {
564
- let html = "";
565
- let rows = await connection.query("select * from zreport where parent_id = ?", [data.id]);
566
- rows.forEach((obj, index) => {
567
- let action = "";
568
- if (obj.excel) {
569
- action += `<a href="/zreport/setup/${obj.id}" class="btn btn-default"> <i class="fa fa-gear" title="Setup Report"></i> </a>`;
570
- }
571
- action += `<a href="/zreport/update/${obj.id}" class="btn btn-default"><i class="fa fa-pencil" title="Edit Data"></i> </a>`;
572
- action += `<a href="#" class="btn btn-default reportdelete" data-id="${obj.id}"><i class="fa fa-trash " title="Delete Report"></i></a>`;
573
- html += `<tr><td>${index + 1}. </td><td>${obj.title}</td><td><a href="/uploads/zreport/${obj.excel}">Excel File</a></td><td>${action}</td></tr>`;
574
- });
559
+ zReport.dataHTMLList = async () => {
560
+ let html = ''
561
+ let results = await connection.results({
562
+ table: 'zreports',
563
+ whereArray: [{ field: 'parent_id', value: 'IS NULL', type: 'inline' }],
564
+ order_by: ['id desc'],
565
+ })
566
+ for (const result of results) {
567
+ let myfilter = await zReport.filters2(result.filter, result.company_id)
568
+ let childReport = ''
569
+ let rows = await connection.results({
570
+ table: 'zreports',
571
+ where: {
572
+ parent_id: result.id,
573
+ },
574
+ })
575
+ rows.forEach((row, index) => {
576
+ let action = ''
577
+ if (row.excel) {
578
+ action += `<button title="setup Report" onclick="location.href='/zreports/setup/${row.id}'" data-id="${row.id}" class="btn image-button boxy-small" type="button"><img src="/assets/icons/settings-filled.svg" class="icons-bg-black"></button>`
579
+ }
580
+ action += `<button title="edit Report" onclick="location.href='/zreports/setup/${row.id}'" data-id="${row.id}" class="btn image-button boxy-small" type="button"><img src="/assets/icons/pencil.svg" class="icons-bg-black"></button>`
581
+ action += `<button title="delete Report" onclick="deletereport('${row.id}')" data-id="${row.id}" class="btn image-button boxy-small" type="button"><img src="/assets/icons/trash.svg" class="icons-bg-black"></button>`
582
+ childReport += `<tr><td>${index + 1}. </td><td>${row.title}</td><td><a href="/uploads/zreports/${row.excel}">Excel File</a></td><td>${action}</td></tr>`
583
+ })
575
584
 
576
- return `<div class="form-group divReportList">
585
+ html += `<div class="col-xs-12 col-md-6">
586
+ <div class="boxy bottom-down">
587
+ <div class="float">
588
+ <span class="icon-small icons-primary" onclick="location.href='/zreports/update/${result.id}'" title="Ubah"><img data-id="4097" class="icons-bg-white gridupdate icon-image" src="/assets/icons/edit.svg"></span>
589
+
590
+ <span class="icon-small icons-danger deletereport float-end" data-delete="/zreports_setting/delete/${result.id}" title="Hapus"><img data-id="4097" class="icons-bg-white griddelete icon-image" src="/assets/icons/trash-filled.svg"></span>
591
+ </div>
592
+
593
+ <div class="container-fluid">
594
+ <h2 class="text text-center text-capitalize">Custom Reports: ${result.title}</h2>
595
+ <p class="card-text card-text text-center text-muted">${result.description}</p>
596
+ <div class="card">
597
+ <div class="card-body">
598
+ <a class="card-link" href="${process.env.APP_URL}/zreports/show/${result.id}" target="_blank">${process.env.APP_URL}/zreports/show/${result.id}</a>
599
+
600
+ <div class="float-end">
601
+ <img src="/assets/icons/copy.svg" class="icons-bg-black cursor" onclick="copyToClipboard('${process.env.APP_URL}/zreports/show/${result.id}')" alt="Copy"></div>
602
+ </div>
603
+ </div>
604
+
605
+ <hr>
606
+ <form method="post" action="/zreports">${myfilter}
607
+ <button type="submit" class="btn btn-block btn-success mt-3">Submit </button>
608
+ </form>
609
+ <hr>
610
+ <div class="form-group divReportList">
577
611
  <div class="panel panel-default">
578
612
  <div class="panel-heading">Report List</div>
579
613
  <div class="panel-body">
@@ -583,298 +617,315 @@ zReport.listReports = async(data) => {
583
617
  <th width="3%">#</th>
584
618
  <th width="50%">Name</th>
585
619
  <th>File</th>
586
- <th class="pull-right"><a href="/zreport/create?id=${data.id}" class="btn btn-default" title="Add" id="addReportList"><i class="fa fa-plus"></i></a></th>
620
+ <th> <button title="add Report" data-id="${result.id}" onclick="$('#parent_id').val(${result.id})" data-bs-toggle="modal" data-bs-target="#reportModal" class="btn image-button boxy-small float-end" type="button"><img src="/assets/icons/plus.svg" class="icons-bg-black"></button></th>
587
621
  </tr>
588
622
  </thead>
589
- <tbody class="body-reportList" data-value="">${html}</tbody>
623
+ <tbody class="body-reportList" data-value="">${childReport}</tbody>
590
624
  </table>
591
625
  </div>
592
626
  </div>
593
- </div>`;
594
- }
627
+ </div>
595
628
 
629
+ </div>
630
+ </div>
631
+ </div>`
632
+ }
633
+ return html
634
+ }
596
635
 
597
- zReport.filterReport = async(req, res) => {
598
- let id = req.params.id || "";
599
- let companyId = res.locals.companyId;
600
- let data = [], rows = [];
601
- if (id == "") {
602
- rows = await connection.query("select * from zreport where company_id = ? and parent_id IS NULL", [companyId])
603
- } else {
604
- rows = await connection.results({table: "zreport", where: {id: id, company_id: companyId}})
636
+ zReport.listReports = async (data) => {
637
+ let html = ''
638
+ let rows = await connection.query('select * from zreport where parent_id = ?', [data.id])
639
+ rows.forEach((obj, index) => {
640
+ let action = ''
641
+ if (obj.excel) {
642
+ action += `<a href="/zreport/setup/${obj.id}" class="btn btn-default"> <i class="fa fa-gear" title="Setup Report"></i> </a>`
605
643
  }
644
+ action += `<a href="/zreport/update/${obj.id}" class="btn btn-default"><i class="fa fa-pencil" title="Edit Data"></i> </a>`
645
+ action += `<a href="#" class="btn btn-default reportdelete" data-id="${obj.id}"><i class="fa fa-trash " title="Delete Report"></i></a>`
646
+ html += `<tr><td>${index + 1}. </td><td>${obj.title}</td><td><a href="/uploads/zreport/${obj.excel}">Excel File</a></td><td>${action}</td></tr>`
647
+ })
606
648
 
607
- console.log(rows)
608
- for (var i = 0; i < rows.length; i++) {
609
-
610
- var row = rows[i];
611
- //rows.forEach(async function (row) {
612
- let reportsRow = await connection.results({table: "zreport", where: {parent_id: row.id}});
613
- console.log(reportsRow)
614
- let filterHtml = reportsRow.length > 0 ? `<form method="post" action="/zreport" >` : '';
615
- let filters = JSON.parse(row.filter) || [];
616
- console.log("filters :")
617
- console.log(filters)
618
- row.listReports = await zReport.listReports(row);
619
- for (var x = 0; x < filters.length; x++) {
620
- let filter = filters[x];
621
- let options = `<option value="">Please Select</option>`;
622
- let html = '';
623
- if (filter.type == 1) {
624
- html = `<input type="text" class="datepicker form-control" name="${filter.name}" >`;
625
-
626
- } else if (filter.type == 2) {
627
- let values = JSON.parse(filter.value) || [];
628
- values.map(function (e) {
629
- options += `<option value="${e.key}">${e.label}</option>`;
630
- });
631
- html = `<select class="form-control form-select" name="${filter.name}">${options}</select>`;
632
-
633
- } else if (filter.type == 3) {
634
- let values = filter.value || "";
635
- let explode = values.split(".");
636
- let table = explode[0];
637
- if (table && fs.existsSync(dirRoot + "/models/" + table + ".js")) {
638
- let keycolumn = explode[1];
639
- let labelcolumn = explode[2];
640
- let MYMODEL = require('./../models/' + table);
641
- let fields = MYMODEL.keys;
642
- let where = '';
643
- if (fields.indexOf("company_id") > -1) {
644
- where = ` where company_id = ${company_id} `;
645
- }
646
- let results = await connection.query("select * from `" + table + "` " + where + " order by " + labelcolumn + " ASC");
647
- results.map(async(result) => {
648
- options += `<option value="${result[keycolumn]}">${result[labelcolumn]}</option>`;
649
- });
650
- html = `<select class="form-control form-select" name="${filter.name}">${options}</select>`;
651
- }
652
- }
653
- filterHtml += `<div class="row"><div class="form-group"><label class="control-label col-md-2">${filter.label}</label><div class="col-md-10">${html}</div></div></div><br>`;
654
- row.filterHtml = filterHtml;
655
- }
649
+ return `<div class="form-group divReportList">
650
+ <div class="panel panel-default">
651
+ <div class="panel-heading">Report List</div>
652
+ <div class="panel-body">
653
+ <table class="table table-hover">
654
+ <thead>
655
+ <tr>
656
+ <th width="3%">#</th>
657
+ <th width="50%">Name</th>
658
+ <th>File</th>
659
+ <th class="pull-right"><a href="/zreport/create?id=${data.id}" class="btn btn-default" title="Add" id="addReportList"><i class="fa fa-plus"></i></a></th>
660
+ </tr>
661
+ </thead>
662
+ <tbody class="body-reportList" data-value="">${html}</tbody>
663
+ </table>
664
+ </div>
665
+ </div>
666
+ </div>`
667
+ }
656
668
 
657
- //drop down report name
658
- let reportList = "";
659
- if (reportsRow.length > 0) {
660
- let reportOptions = "";
661
- reportsRow.map((obj) => {
662
- reportOptions += `<option value="${obj.id}">${obj.title}</option>`
663
- });
664
- reportList += `<div class="row"><div class="form-group"><label class="control-label col-md-2">Report Name</label><div class="col-md-10"><select class="form-control" id="zreports_name" name="zreports_name">${reportOptions}</select></div></div></div>`;
665
- reportList += `<br><button type="submit" class="btn btn-block btn-success">Submit </button> `;
666
- reportList += `</form>`;
669
+ zReport.filterReport = async (req, res) => {
670
+ let id = req.params.id || ''
671
+ let companyId = res.locals.companyId
672
+ let data = [],
673
+ rows = []
674
+ if (id == '') {
675
+ rows = await connection.query('select * from zreport where company_id = ? and parent_id IS NULL', [companyId])
676
+ } else {
677
+ rows = await connection.results({ table: 'zreport', where: { id: id, company_id: companyId } })
678
+ }
679
+
680
+ console.log(rows)
681
+ for (var i = 0; i < rows.length; i++) {
682
+ var row = rows[i]
683
+ //rows.forEach(async function (row) {
684
+ let reportsRow = await connection.results({ table: 'zreport', where: { parent_id: row.id } })
685
+ console.log(reportsRow)
686
+ let filterHtml = reportsRow.length > 0 ? `<form method="post" action="/zreport" >` : ''
687
+ let filters = JSON.parse(row.filter) || []
688
+ console.log('filters :')
689
+ console.log(filters)
690
+ row.listReports = await zReport.listReports(row)
691
+ for (var x = 0; x < filters.length; x++) {
692
+ let filter = filters[x]
693
+ let options = `<option value="">Please Select</option>`
694
+ let html = ''
695
+ if (filter.type == 1) {
696
+ html = `<input type="text" class="datepicker form-control" name="${filter.name}" >`
697
+ } else if (filter.type == 2) {
698
+ let values = JSON.parse(filter.value) || []
699
+ values.map(function (e) {
700
+ options += `<option value="${e.key}">${e.label}</option>`
701
+ })
702
+ html = `<select class="form-control form-select" name="${filter.name}">${options}</select>`
703
+ } else if (filter.type == 3) {
704
+ let values = filter.value || ''
705
+ let explode = values.split('.')
706
+ let table = explode[0]
707
+ if (table && fs.existsSync(dirRoot + '/models/' + table + '.js')) {
708
+ let keycolumn = explode[1]
709
+ let labelcolumn = explode[2]
710
+ let MYMODEL = require('./../models/' + table)
711
+ let fields = MYMODEL.keys
712
+ let where = ''
713
+ if (fields.indexOf('company_id') > -1) {
714
+ where = ` where company_id = ${company_id} `
715
+ }
716
+ let results = await connection.query('select * from `' + table + '` ' + where + ' order by ' + labelcolumn + ' ASC')
717
+ results.map(async (result) => {
718
+ options += `<option value="${result[keycolumn]}">${result[labelcolumn]}</option>`
719
+ })
720
+ html = `<select class="form-control form-select" name="${filter.name}">${options}</select>`
667
721
  }
668
- row.reportList = reportList;
722
+ }
723
+ filterHtml += `<div class="row"><div class="form-group"><label class="control-label col-md-2">${filter.label}</label><div class="col-md-10">${html}</div></div></div><br>`
724
+ row.filterHtml = filterHtml
725
+ }
669
726
 
670
- data.push(row);
727
+ //drop down report name
728
+ let reportList = ''
729
+ if (reportsRow.length > 0) {
730
+ let reportOptions = ''
731
+ reportsRow.map((obj) => {
732
+ reportOptions += `<option value="${obj.id}">${obj.title}</option>`
733
+ })
734
+ reportList += `<div class="row"><div class="form-group"><label class="control-label col-md-2">Report Name</label><div class="col-md-10"><select class="form-control" id="zreports_name" name="zreports_name">${reportOptions}</select></div></div></div>`
735
+ reportList += `<br><button type="submit" class="btn btn-block btn-success">Submit </button> `
736
+ reportList += `</form>`
671
737
  }
738
+ row.reportList = reportList
672
739
 
673
- return data;
740
+ data.push(row)
741
+ }
742
+
743
+ return data
674
744
  }
675
745
 
676
746
  /*
677
747
  One line
678
748
  */
679
- zReport.filters2 = async(arr, companyId) => {
680
- var html = '';
681
-
682
- for (var i = 0; i < arr.length; i++) {
683
- var filter = arr[i];
684
-
685
- html += ` <div class="mb-3 row">
686
- <label for="${filter.name}"class="col-sm-4 col-form-label">${filter.label}</label>
687
- <div class="col-sm-8">`;
688
-
689
- if (filter.type == 1) {
690
- html += `<input type="text" class="datepicker form-control" name="${filter.name}" >`;
691
-
692
- } else if (filter.type == 2) {
693
- let values = filter.value ? JSON.parse(filter.value) : [];
694
- let options = `<option value="">Please Select</option>`;
695
- if (values.length) {
696
- values.map(function (e) {
697
- options += `<option value="${e.key}">${e.label}</option>`;
698
- });
699
- html += `<select class="form-control form-select" name="${filter.name}">${options}</select>`;
700
- }
701
-
702
-
703
- } else if (filter.type == 3) {
704
- let values = filter.value || "";
705
- let explode = values.split(".");
706
- let table = explode[0];
707
- let options = `<option value="">Please Select</option>`;
708
- if (table && fs.existsSync(dirRoot + "/models/" + table + ".js")) {
709
- let keycolumn = explode[1];
710
- let labelcolumn = explode[2];
711
- let MYMODEL = require('./../models/' + table);
712
- let fields = MYMODEL.keys;
713
- let where = '';
714
- if (fields.indexOf("company_id") > -1) {
715
- where = ` where company_id = ${companyId} `;
716
- }
717
- let results = await connection.results({
718
- table : table,
719
- where : {
720
- company_id : companyId
721
- },
722
- orderby : [labelcolumn, "ASC"]
723
- })
724
- if(results.length) {
725
- results.map(async(result) => {
726
- options += `<option value="${result[keycolumn]}">${result[labelcolumn]}</option>`;
727
- });
728
- }
729
- html += `<select class="form-control form-select" name="${filter.name}">${options}</select>`;
730
- }
749
+ zReport.filters2 = async (arr, companyId) => {
750
+ console.log(arr)
751
+ console.log(companyId)
752
+ var html = ''
753
+ let MYMODELS = myCache.get('MYMODELS')
754
+ for (var i = 0; i < arr.length; i++) {
755
+ var filter = arr[i]
756
+
757
+ html += ` <div class="mb-3 row"><label for="${filter.name}"class="col-sm-4 col-form-label">${filter.label}</label><div class="col-sm-8">`
758
+ if (filter.type == 1) {
759
+ html += `<input type="text" class="datepicker form-control" name="${filter.name}" >`
760
+ } else if (filter.type == 2) {
761
+ let values = filter.value ? JSON.parse(filter.value) : []
762
+ let options = `<option value="">Please Select</option>`
763
+ if (values.length) {
764
+ values.map(function (e) {
765
+ options += `<option value="${e.key}">${e.label}</option>`
766
+ })
767
+ html += `<select class="form-control form-select" name="${filter.name}">${options}</select>`
768
+ }
769
+ } else if (filter.type == 3) {
770
+ let values = filter.value || ''
771
+ let explode = values.split('.')
772
+ let table = explode[0]
773
+ let options = `<option value="">Please Select</option>`
774
+ if (table && Object.keys(MYMODELS[table]).length > 0) {
775
+ let keycolumn = explode[1]
776
+ let labelcolumn = explode[2]
777
+ let MYMODEL = MYMODELS[table]
778
+ let fields = MYMODEL.keys
779
+ let where = ''
780
+ if (fields.indexOf('company_id') > -1) {
781
+ where = ` where company_id = ${companyId} `
731
782
  }
732
-
733
- html += `</div>
734
- </div>`;
735
-
783
+ let sql = `select * from "${table}" ${where} order by ${labelcolumn} ASC`
784
+ let results = await connection.query(sql)
785
+ for (const result of results) {
786
+ options += `<option value="${result[keycolumn]}">${result[labelcolumn]}</option>`
787
+ }
788
+ }
789
+ html += `<select class="form-control form-select" name="${filter.name}">${options}</select>`
736
790
  }
737
791
 
738
- return html;
739
- }
740
-
741
-
742
- zReport.filters = async(arr, companyId) => {
743
- var html = '';
744
-
745
- for (var i = 0; i < arr.length; i++) {
746
- var filter = arr[i];
747
-
748
- html += `<div class="mb-3"><label for="${filter.name}" class="form-label">${filter.label}</label>`;
749
- if (filter.type == 1) {
750
- html += `<input type="text" class="datepicker form-control" name="${filter.name}" >`;
751
-
752
- } else if (filter.type == 2) {
753
- let values = filter.value ? JSON.parse(filter.value) : [];
754
- let options = '';
755
- if (values.length) {
756
- values.map(function (e) {
757
- options += `<option value="${e.key}">${e.label}</option>`;
758
- });
759
- html += `<select class="form-control form-select" name="${filter.name}">${options}</select>`;
760
- }
792
+ html += `</div>
793
+ </div>`
794
+ }
761
795
 
796
+ return html
797
+ }
762
798
 
763
- } else if (filter.type == 3) {
764
- let values = filter.value || "";
765
- let explode = values.split(".");
766
- let table = explode[0];
767
- let options = '';
768
- if (table && fs.existsSync(dirRoot + "/models/" + table + ".js")) {
769
- let keycolumn = explode[1];
770
- let labelcolumn = explode[2];
771
- let MYMODEL = require('./../models/' + table);
772
- let fields = MYMODEL.keys;
773
- let where = '';
774
- if (fields.indexOf("company_id") > -1) {
775
- where = ` where company_id = ${companyId} `;
776
- }
777
- let results = await connection.query("select * from `" + table + "` " + where + " order by " + labelcolumn + " ASC");
778
- results.map(async(result) => {
779
- options += `<option value="${result[keycolumn]}">${result[labelcolumn]}</option>`;
780
- });
781
- html += `<select class="form-control form-select" name="${filter.name}">${options}</select>`;
782
- }
799
+ zReport.filters = async (arr, companyId) => {
800
+ var html = ''
801
+
802
+ for (var i = 0; i < arr.length; i++) {
803
+ var filter = arr[i]
804
+
805
+ html += `<div class="mb-3"><label for="${filter.name}" class="form-label">${filter.label}</label>`
806
+ if (filter.type == 1) {
807
+ html += `<input type="text" class="datepicker form-control" name="${filter.name}" >`
808
+ } else if (filter.type == 2) {
809
+ let values = filter.value ? JSON.parse(filter.value) : []
810
+ let options = ''
811
+ if (values.length) {
812
+ values.map(function (e) {
813
+ options += `<option value="${e.key}">${e.label}</option>`
814
+ })
815
+ html += `<select class="form-control form-select" name="${filter.name}">${options}</select>`
816
+ }
817
+ } else if (filter.type == 3) {
818
+ let values = filter.value || ''
819
+ let explode = values.split('.')
820
+ let table = explode[0]
821
+ let options = ''
822
+ if (table && fs.existsSync(dirRoot + '/models/' + table + '.js')) {
823
+ let keycolumn = explode[1]
824
+ let labelcolumn = explode[2]
825
+ let MYMODEL = require('./../models/' + table)
826
+ let fields = MYMODEL.keys
827
+ let where = ''
828
+ if (fields.indexOf('company_id') > -1) {
829
+ where = ` where company_id = ${companyId} `
783
830
  }
784
-
785
- html += `</div>`;
786
-
831
+ let results = await connection.query('select * from `' + table + '` ' + where + ' order by ' + labelcolumn + ' ASC')
832
+ results.map(async (result) => {
833
+ options += `<option value="${result[keycolumn]}">${result[labelcolumn]}</option>`
834
+ })
835
+ html += `<select class="form-control form-select" name="${filter.name}">${options}</select>`
836
+ }
787
837
  }
788
838
 
789
- return html;
790
- }
839
+ html += `</div>`
840
+ }
791
841
 
792
- zReport.showAll = async(req, res) => {
793
- var html = '';
794
- var companyId = res.locals.companyId;
795
- var rows = await connection.query("select * from zreport where company_id = ? and parent_id IS NULL", [companyId]);
796
- for (var i = 0; i < rows.length; i++) {
797
- var isEnd = false;
842
+ return html
843
+ }
798
844
 
799
- if (i == 0) html += `<div class="row">`;
845
+ zReport.showAll = async (req, res) => {
846
+ var html = ''
847
+ var companyId = res.locals.companyId
848
+ var rows = await connection.query('select * from zreport where company_id = ? and parent_id IS NULL', [companyId])
849
+ for (var i = 0; i < rows.length; i++) {
850
+ var isEnd = false
800
851
 
801
- if (i > 1) {
802
- if (i % 2 == 0) {
803
- html += `<div class="row">`;
804
- isEnd = true;
805
- }
852
+ if (i == 0) html += `<div class="row">`
806
853
 
807
- if (i == (rows.length - 1)) {
808
- isEnd = true;
809
- }
810
- }
854
+ if (i > 1) {
855
+ if (i % 2 == 0) {
856
+ html += `<div class="row">`
857
+ isEnd = true
858
+ }
811
859
 
812
- var content = await zReport.show(rows[i].id, companyId);
813
- html += `<div class="col">${content}</div>`
860
+ if (i == rows.length - 1) {
861
+ isEnd = true
862
+ }
863
+ }
814
864
 
815
- if (i == 1) html += `</div>`;
865
+ var content = await zReport.show(rows[i].id, companyId)
866
+ html += `<div class="col">${content}</div>`
816
867
 
868
+ if (i == 1) html += `</div>`
817
869
 
818
- if (i > 1) {
819
- if (isEnd) {
820
- html += `</div>`;
821
- isEnd = false;
822
- }
823
- }
870
+ if (i > 1) {
871
+ if (isEnd) {
872
+ html += `</div>`
873
+ isEnd = false
874
+ }
824
875
  }
876
+ }
825
877
 
826
- return html;
827
-
878
+ return html
828
879
  }
829
880
 
830
- zReport.show = async(id, companyId, csrfToken, isHideLink = false) => {
831
- var html = '';
832
- var result = await connection.result({
833
- table: "zreport",
881
+ zReport.show = async (id, companyId, csrfToken, isHideLink = false) => {
882
+ var html = ''
883
+ var result = await connection.result({
884
+ table: 'zreport',
885
+ where: {
886
+ id: id,
887
+ },
888
+ })
889
+ if (result.id) {
890
+ if (result.parent_id) {
891
+ result = await connection.result({
892
+ table: 'zreport',
834
893
  where: {
835
- id: id
836
- }
837
- })
838
- if (result.id) {
839
- if (result.parent_id) {
840
- result = await connection.result({
841
- table: "zreport",
842
- where: {
843
- id: result.parent_id
844
- }
845
- })
846
- }
894
+ id: result.parent_id,
895
+ },
896
+ })
897
+ }
847
898
 
848
- var arr = [];
849
- arr.push({id: result.id, label: result.title});
850
- var rows = await connection.results({
851
- table: "zreport",
852
- where: {
853
- parent_id: result.id
854
- }
855
- })
856
- rows.forEach(function (item) {
857
- arr.push({id: item.id, label: item.title});
858
- })
899
+ var arr = []
900
+ arr.push({ id: result.id, label: result.title })
901
+ var rows = await connection.results({
902
+ table: 'zreport',
903
+ where: {
904
+ parent_id: result.id,
905
+ },
906
+ })
907
+ rows.forEach(function (item) {
908
+ arr.push({ id: item.id, label: item.title })
909
+ })
859
910
 
860
- var reports = `<div class="mb-3 row"><label for="reporttype" class="col-sm-4 form-label">Report Name</label><div class="col-sm-8"><select class="form-control form-select" id="zreport_name" name="zreport_name">`;
861
- arr.forEach(function (item) {
862
- reports += `<option value="${item.id}">${item.label}</option>`
863
- })
864
- reports += `</select></div></div>`;
911
+ var reports = `<div class="mb-3 row"><label for="reporttype" class="col-sm-4 form-label">Report Name</label><div class="col-sm-8"><select class="form-control form-select" id="zreport_name" name="zreport_name">`
912
+ arr.forEach(function (item) {
913
+ reports += `<option value="${item.id}">${item.label}</option>`
914
+ })
915
+ reports += `</select></div></div>`
865
916
 
866
- var link = '';
867
- if (!isHideLink) {
868
- link = `<div class="card-footer">
917
+ var link = ''
918
+ if (!isHideLink) {
919
+ link = `<div class="card-footer">
869
920
  <i class="fa fa-copy copy-link" title="copy link" data-url="${CONFIG.app.url}/zreport/show/${result.id}/${result.title}"></i>
870
921
  <a href="${CONFIG.app.url}/zreport/show/${result.id}/${result.title}" class="card-link">${CONFIG.app.url}/zreport/show/${result.id}/${result.title}</a>
871
922
  </div>`
872
- }
873
- //one line filters2
874
- var filter = await zReport.filters2(result.filters || [], companyId);
875
- html += `<form class="form" method="post" action="/zreport/report" >`;
876
- html += `<input type="hidden" name="_csrf" value="${csrfToken}">`;
877
- html += `<div class="card boxy">
923
+ }
924
+ //one line filters2
925
+ var filter = await zReport.filters2(result.filters || [], companyId)
926
+ html += `<form class="form" method="post" action="/zreport/report" >`
927
+ html += `<input type="hidden" name="_csrf" value="${csrfToken}">`
928
+ html += `<div class="card boxy">
878
929
  <div class="card-body">
879
930
  <h2 class="card-title">${result.title}</h2>
880
931
  <p class="card-text">${result.description}</p><br>
@@ -889,42 +940,42 @@ zReport.show = async(id, companyId, csrfToken, isHideLink = false) => {
889
940
 
890
941
  ${link}
891
942
 
892
- </div></form>`;
893
- }
943
+ </div></form>`
944
+ }
894
945
 
895
- return html;
946
+ return html
896
947
  }
897
948
 
898
- zReport.updateQuery = async(req, res) => {
899
- var body = req.body;
900
- var orderby = body.orderby || "";
901
- var wheres = body.wheres || "";
902
- var scripts = body.scripts || "";
903
- var id = body.id;
904
- console.log(req.body);
905
- var json = Util.jsonSuccess("Successfully save");
906
- var data = {}
907
- if(body.hasOwnProperty("orderby")) {
908
- data.orderby = orderby;
909
- }
910
- if(body.hasOwnProperty("scripts")) {
911
- data.scripts = scripts;
912
- }
913
- if(body.hasOwnProperty("wheres")) {
914
- data.wheres = wheres ? JSON.stringify(wheres) : null;
915
- }
916
- try {
917
- await connection.update({
918
- table: "zreport",
919
- data: data,
920
- where: {
921
- id: id
922
- }
923
- });
924
- } catch (err) {
925
- json = Util.flashError("Error " + err.toString());
926
- }
927
- res.json(json);
949
+ zReport.updateQuery = async (req, res) => {
950
+ var body = req.body
951
+ var orderby = body.orderby || ''
952
+ var wheres = body.wheres || ''
953
+ var scripts = body.scripts || ''
954
+ var id = body.id
955
+ console.log(req.body)
956
+ var json = Util.jsonSuccess('Successfully save')
957
+ var data = {}
958
+ if (body.hasOwnProperty('orderby')) {
959
+ data.orderby = orderby
960
+ }
961
+ if (body.hasOwnProperty('scripts')) {
962
+ data.scripts = scripts
963
+ }
964
+ if (body.hasOwnProperty('wheres')) {
965
+ data.wheres = wheres ? JSON.stringify(wheres) : null
966
+ }
967
+ try {
968
+ await connection.update({
969
+ table: 'zreport',
970
+ data: data,
971
+ where: {
972
+ id: id,
973
+ },
974
+ })
975
+ } catch (err) {
976
+ json = Util.flashError('Error ' + err.toString())
977
+ }
978
+ res.json(json)
928
979
  }
929
980
 
930
- module.exports = zReport;
981
+ module.exports = zReport