zet-lib 1.4.4 → 1.4.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/lib/zAppRouter.js CHANGED
@@ -1,189 +1,208 @@
1
- const express = require('express')
2
- const router = express.Router()
3
- const csrf = require('csurf')
4
- const csrfProtection = csrf({ cookie: true })
5
- const zRoute = require('./zRoute')
6
- const connection = require('./connection')
7
- const access = require('./access')
8
- const myCache = require('./cache')
9
- const Util = require('./Util')
10
- const moment = require('moment')
11
- const fs = require('fs-extra')
12
- const moduleLib = require('./moduleLib')
13
- var env = process.env.NODE_ENV || 'development'
14
- var ecosystem = require(`./../../../ecosystem.config.js`)
15
- const config = require('dotenv').config()
16
- const debug = require('./debug')
17
- const io = require('./io')
18
- const Mail = require('./Mail')
19
- const zCache = require('./zCache')
20
- const pm2 = require('pm2')
21
- const zFunction = require('./zFunction')
22
- const qs = require('qs')
23
- const zip = require('express-zip')
1
+ const express = require("express");
2
+ const router = express.Router();
3
+ const csrf = require("csurf");
4
+ const csrfProtection = csrf({ cookie: true });
5
+ const zRoute = require("./zRoute");
6
+ const connection = require("./connection");
7
+ const access = require("./access");
8
+ const myCache = require("./cache");
9
+ const Util = require("./Util");
10
+ const moment = require("moment");
11
+ const fs = require("fs-extra");
12
+ const moduleLib = require("./moduleLib");
13
+ var env = process.env.NODE_ENV || "development";
14
+ var ecosystem = require(`./../../../ecosystem.config.js`);
15
+ const config = require("dotenv").config();
16
+ const debug = require("./debug");
17
+ const io = require("./io");
18
+ const Mail = require("./Mail");
19
+ const zCache = require("./zCache");
20
+ const pm2 = require("pm2");
21
+ const zFunction = require("./zFunction");
22
+ const qs = require("qs");
23
+ const zip = require("express-zip");
24
+ const sharp = require("sharp");
24
25
 
25
26
  /*
26
27
  ajax Post
27
28
  */
28
- router.post('/zajax', zRoute.ajax)
29
- router.get('/ztypeahead/:table/:field', zRoute.typeahead)
30
- router.post('/ztypeaheadpost/:table/:field', zRoute.typeaheadpost)
29
+ router.post("/zajax", zRoute.ajax);
30
+ router.get("/ztypeahead/:table/:field", zRoute.typeahead);
31
+ router.post("/ztypeaheadpost/:table/:field", zRoute.typeaheadpost);
31
32
 
32
33
  //password
33
- router.post('/password-change', zRoute.changePassword)
34
- router.post('/reset-password/:forgot_password', zRoute.resetPassword)
34
+ router.post("/password-change", zRoute.changePassword);
35
+ router.post("/reset-password/:forgot_password", zRoute.resetPassword);
35
36
  //logout
36
- router.get('/logout', zRoute.logout)
37
+ router.get("/logout", zRoute.logout);
37
38
  /*
38
39
  function for build form for table type
39
40
  */
40
- router.post('/buildform', csrfProtection, zRoute.buildForm)
41
+ router.post("/buildform", csrfProtection, zRoute.buildForm);
41
42
  /*
42
43
  function for tab access if any
43
44
  */
44
- router.post('/ztab-access', csrfProtection, zRoute.tabAccess)
45
-
46
- router.get('/profile', csrfProtection, access, async (req, res) => {
47
- const MYMODELS = myCache.get('MYMODELS')
48
- let MYMODEL = MYMODELS['zuser']
49
- let result = await connection.result({ table: 'zuser', where: { id: res.locals.userId } })
50
- let role = await connection.result({ table: 'zrole', where: { id: result.role_id } })
51
- let canEditCompany = false
45
+ router.post("/ztab-access", csrfProtection, zRoute.tabAccess);
46
+
47
+ router.get("/profile", csrfProtection, access, async (req, res) => {
48
+ const MYMODELS = myCache.get("MYMODELS");
49
+ let MYMODEL = MYMODELS["zuser"];
50
+ let result = await connection.result({
51
+ table: "zuser",
52
+ where: { id: res.locals.userId },
53
+ });
54
+ let role = await connection.result({
55
+ table: "zrole",
56
+ where: { id: result.role_id },
57
+ });
58
+ let canEditCompany = false;
52
59
  if (result.role_id == 1 || result.role_id == 2) {
53
- canEditCompany = true
60
+ canEditCompany = true;
54
61
  }
55
- let company = await connection.result({ table: 'zcompany', where: { id: res.locals.companyId } })
56
- let verify_signed = result.verify_signed ? '/uploads/zuser/' + result.verify_signed : '/img/user.png'
57
- res.render('layouts/' + layout, {
58
- menu: { menu: 'profile' },
62
+ let company = await connection.result({
63
+ table: "zcompany",
64
+ where: { id: res.locals.companyId },
65
+ });
66
+ let verify_signed = result.verify_signed
67
+ ? "/uploads/zuser/" + result.verify_signed
68
+ : "/img/user.png";
69
+ res.render("layouts/" + layout, {
70
+ menu: { menu: "profile" },
59
71
  data: result,
60
72
  attributeData: MYMODEL,
61
73
  role: role,
62
74
  company: company,
63
75
  canEditCompany: canEditCompany,
64
76
  verify_signed: verify_signed,
65
- routeName: 'zuser',
77
+ routeName: "zuser",
66
78
  csrfToken: req.csrfToken(),
67
- renderHead: 'index/profile_head.ejs',
68
- renderBody: 'index/profile.ejs',
69
- renderEnd: 'index/profilejs.ejs',
70
- })
71
- })
72
-
73
- router.post('/profile', access, async (req, res) => {
74
- const MYMODELS = myCache.get('MYMODELS')
75
- let MYMODEL = MYMODELS['zuser']
76
- let json = Util.jsonSuccess(LANGUAGE['data_saved'])
77
- let userId = req.session.user.id
78
- let dataPost = zRoute.post(req, res, MYMODEL, 'zuser', req.body)
79
- let data = dataPost['zuser']
79
+ renderHead: "index/profile_head.ejs",
80
+ renderBody: "index/profile.ejs",
81
+ renderEnd: "index/profilejs.ejs",
82
+ });
83
+ });
84
+
85
+ router.post("/profile", access, async (req, res) => {
86
+ const MYMODELS = myCache.get("MYMODELS");
87
+ let MYMODEL = MYMODELS["zuser"];
88
+ let json = Util.jsonSuccess(LANGUAGE["data_saved"]);
89
+ let userId = req.session.user.id;
90
+ let dataPost = zRoute.post(req, res, MYMODEL, "zuser", req.body);
91
+ let data = dataPost["zuser"];
80
92
  if (req.body.company) {
81
93
  await connection.update({
82
- table: 'zcompany',
94
+ table: "zcompany",
83
95
  data: { name: req.body.company },
84
96
  where: {
85
97
  id: res.locals.companyId,
86
98
  },
87
- })
99
+ });
88
100
  }
89
101
  await connection.update({
90
- table: 'zuser',
102
+ table: "zuser",
91
103
  data: data,
92
104
  where: {
93
105
  id: userId,
94
106
  },
95
- })
107
+ });
96
108
  for (var keys in data) {
97
- req.session.user[keys] = data[keys]
109
+ req.session.user[keys] = data[keys];
98
110
  }
99
- req.session.sessionFlash = json
111
+ req.session.sessionFlash = json;
100
112
  if (data.image) {
101
- json.image = Util.imageProfile(data.image)
113
+ json.image = Util.imageProfile(data.image);
102
114
  }
103
- res.json(json)
104
- })
105
-
106
- router.post('/profile-sign', access, async (req, res) => {
107
- const MYMODELS = myCache.get('MYMODELS')
108
- let MYMODEL = MYMODELS['zuser']
109
- let json = Util.jsonSuccess(LANGUAGE['data_saved'])
110
- let userId = res.locals.userId
111
- let image = req.body.image
112
- let ext = req.body.ext
113
- let base64Image = image.split(';base64,').pop()
114
- let filename = `${Util.generateUnique(10)}${res.locals.userId}.${ext}`
115
+ res.json(json);
116
+ });
117
+
118
+ router.post("/profile-sign", access, async (req, res) => {
119
+ const MYMODELS = myCache.get("MYMODELS");
120
+ let MYMODEL = MYMODELS["zuser"];
121
+ let json = Util.jsonSuccess(LANGUAGE["data_saved"]);
122
+ let userId = res.locals.userId;
123
+ let image = req.body.image;
124
+ let ext = req.body.ext;
125
+ let base64Image = image.split(";base64,").pop();
126
+ let filename = `${Util.generateUnique(10)}${res.locals.userId}.${ext}`;
115
127
  await connection.update({
116
- table: 'zuser',
128
+ table: "zuser",
117
129
  where: {
118
130
  id: res.locals.userId,
119
131
  },
120
132
  data: {
121
133
  verify_signed: filename,
122
134
  },
123
- })
124
- fs.writeFile(dirRoot + '/public/uploads/zuser/' + filename, base64Image, { encoding: 'base64' }, function (err) {})
125
- res.json(json)
126
- })
135
+ });
136
+ fs.writeFile(
137
+ dirRoot + "/public/uploads/zuser/" + filename,
138
+ base64Image,
139
+ { encoding: "base64" },
140
+ function (err) {}
141
+ );
142
+ res.json(json);
143
+ });
127
144
 
128
145
  //check status user login in session
129
- router.put('/zuser-session', csrfProtection, async (req, res) => {
130
- let json = Util.flashError('err')
146
+ router.put("/zuser-session", csrfProtection, async (req, res) => {
147
+ let json = Util.flashError("err");
131
148
  if (USER_ID > 0) {
132
- json = Util.jsonSuccess('Success')
149
+ json = Util.jsonSuccess("Success");
133
150
  }
134
- res.json(json)
135
- })
151
+ res.json(json);
152
+ });
136
153
 
137
- router.get('/login', csrfProtection, async (req, res) => {
154
+ router.get("/login", csrfProtection, async (req, res) => {
138
155
  if (res.locals.isLogin) {
139
- return res.redirect(process.env.APP_AFTER_LOGIN)
156
+ return res.redirect(process.env.APP_AFTER_LOGIN);
140
157
  } else {
141
- await zFunction('form_login', req, res)
158
+ await zFunction("form_login", req, res);
142
159
  }
143
- const isError = req.query.err == 1 ? true : false
160
+ const isError = req.query.err == 1 ? true : false;
144
161
  if (isError) {
145
- res.locals.error = null
162
+ res.locals.error = null;
146
163
  }
147
- res.locals.menuApp = 'login'
148
- res.render('layouts/blank', {
164
+ res.locals.menuApp = "login";
165
+ res.render("layouts/blank", {
149
166
  isError: isError,
150
167
  csrfToken: req.csrfToken(),
151
- renderHead: 'index/logincss.ejs',
152
- renderBody: 'index/login.ejs',
153
- })
154
- })
155
-
156
- router.post('/login', csrfProtection, async (req, res) => {
157
- await zRoute.login(req.body.username, req.body.password, req, res)
158
- })
159
-
160
- router.post('/login-ajax', csrfProtection, async (req, res) => {
161
- res.json(await zRoute.loginAjax(req.body.username, req.body.password, req, res))
162
- })
163
-
164
- router.get('/signup', csrfProtection, async (req, res) => {
165
- res.locals.menuApp = 'signup'
168
+ renderHead: "index/logincss.ejs",
169
+ renderBody: "index/login.ejs",
170
+ });
171
+ });
172
+
173
+ router.post("/login", csrfProtection, async (req, res) => {
174
+ await zRoute.login(req.body.username, req.body.password, req, res);
175
+ });
176
+
177
+ router.post("/login-ajax", csrfProtection, async (req, res) => {
178
+ res.json(
179
+ await zRoute.loginAjax(req.body.username, req.body.password, req, res)
180
+ );
181
+ });
182
+
183
+ router.get("/signup", csrfProtection, async (req, res) => {
184
+ res.locals.menuApp = "signup";
166
185
  if (res.locals.isLogin) {
167
- return res.redirect(CONFIG.app.afterLogin)
186
+ return res.redirect(CONFIG.app.afterLogin);
168
187
  } else {
169
- await zFunction('form_register', req, res)
188
+ await zFunction("form_register", req, res);
170
189
  }
171
- res.render('layouts/blank', {
172
- renderBody: 'index/signup.ejs',
173
- })
174
- })
175
-
176
- router.post('/signup', async (req, res) => {
177
- let body = req.body
178
- let menuData = {}
179
- let userCompany = {}
180
- let user = {}
181
- let company = {}
190
+ res.render("layouts/blank", {
191
+ renderBody: "index/signup.ejs",
192
+ });
193
+ });
194
+
195
+ router.post("/signup", async (req, res) => {
196
+ let body = req.body;
197
+ let menuData = {};
198
+ let userCompany = {};
199
+ let user = {};
200
+ let company = {};
182
201
  try {
183
- let validation = registrationValidation(body)
202
+ let validation = registrationValidation(body);
184
203
  if (validation.status == 0) {
185
- res.json(Util.flashError(validation.message))
186
- return false
204
+ res.json(Util.flashError(validation.message));
205
+ return false;
187
206
  }
188
207
  let dataCompany = {
189
208
  code: Util.generateUnique(5),
@@ -192,18 +211,18 @@ router.post('/signup', async (req, res) => {
192
211
  updated_at: Util.now(),
193
212
  created_by: 1,
194
213
  updated_by: 1,
195
- }
214
+ };
196
215
  company = await connection.insert({
197
- table: 'zcompany',
216
+ table: "zcompany",
198
217
  data: dataCompany,
199
- })
218
+ });
200
219
  let dataCache = zCache.myCache.has(body.username)
201
220
  ? zCache.get(body.username)
202
221
  : {
203
- fullname: '',
204
- email: '',
205
- image: '',
206
- }
222
+ fullname: "",
223
+ email: "",
224
+ image: "",
225
+ };
207
226
  let dataUser = {
208
227
  company_id: company.id,
209
228
  created_at: Util.now(),
@@ -216,34 +235,34 @@ router.post('/signup', async (req, res) => {
216
235
  email: body.username,
217
236
  password: Util.hash(body.password),
218
237
  fullname: body.fullname,
219
- image: !dataCache.image ? '' : dataCache.image,
238
+ image: !dataCache.image ? "" : dataCache.image,
220
239
  active: 1,
221
- language: '1',
222
- }
240
+ language: "1",
241
+ };
223
242
  user = await connection.insert({
224
- table: 'zuser',
243
+ table: "zuser",
225
244
  data: dataUser,
226
- })
245
+ });
227
246
 
228
247
  //insert user company
229
248
  userCompany = await connection.insert({
230
- table: 'zuser_company',
249
+ table: "zuser_company",
231
250
  data: {
232
251
  role_id: 2,
233
252
  company_id: company.id,
234
253
  user_id: user.id,
235
254
  },
236
- })
255
+ });
237
256
 
238
257
  let menu = await connection.result({
239
- table: 'zmenu',
258
+ table: "zmenu",
240
259
  where: {
241
260
  id: 1,
242
261
  },
243
- })
262
+ });
244
263
  //insert menu dari user yang sudah ada menu
245
264
  menuData = await connection.insert({
246
- table: 'zmenu',
265
+ table: "zmenu",
247
266
  data: {
248
267
  company_id: company.id,
249
268
  created_at: Util.now(),
@@ -254,103 +273,103 @@ router.post('/signup', async (req, res) => {
254
273
  json: JSON.stringify(menu.json),
255
274
  active: 1,
256
275
  },
257
- })
258
- await zRoute.loginAjax(dataUser.username, body.password, req, res)
276
+ });
277
+ await zRoute.loginAjax(dataUser.username, body.password, req, res);
259
278
  //refresh cache
260
- await zCache.renew()
261
- res.json(Util.jsonSuccess(LANGUAGE.success))
279
+ await zCache.renew();
280
+ res.json(Util.jsonSuccess(LANGUAGE.success));
262
281
  } catch (e) {
263
282
  if (menuData && menuData.id) {
264
283
  await connection.delete({
265
- table: 'zmenu',
284
+ table: "zmenu",
266
285
  where: {
267
286
  id: menuData.id,
268
287
  },
269
- })
288
+ });
270
289
  }
271
290
  if (userCompany && userCompany.id) {
272
291
  await connection.delete({
273
- table: 'zuser_company',
292
+ table: "zuser_company",
274
293
  where: {
275
294
  id: userCompany.id,
276
295
  },
277
- })
296
+ });
278
297
  }
279
298
  if (user && user.id) {
280
299
  await connection.delete({
281
- table: 'zuser',
300
+ table: "zuser",
282
301
  where: {
283
302
  id: user.id,
284
303
  },
285
- })
304
+ });
286
305
  }
287
306
  if (company && company.id) {
288
307
  await connection.delete({
289
- table: 'zcompany',
308
+ table: "zcompany",
290
309
  where: {
291
310
  id: company.id,
292
311
  },
293
- })
312
+ });
294
313
  }
295
- res.json(Util.flashError(e.toString()))
314
+ res.json(Util.flashError(e.toString()));
296
315
  }
297
- })
316
+ });
298
317
 
299
318
  const registrationValidation = (body) => {
300
319
  let json = {
301
- message: 'ok',
320
+ message: "ok",
302
321
  status: 0,
303
- }
322
+ };
304
323
  if (!Util.validateEmail(body.username)) {
305
- json.message = 'Email format is wrong!!'
324
+ json.message = "Email format is wrong!!";
306
325
  }
307
326
  if (body.password != body.confirm_password) {
308
- json.message = 'Password not equal to confirm password'
327
+ json.message = "Password not equal to confirm password";
309
328
  }
310
329
  if (body.password.length < 6) {
311
- json.message = 'Password must be at least 6 chars'
330
+ json.message = "Password must be at least 6 chars";
312
331
  }
313
332
  if (body.fullname.length < 3) {
314
- json.message = 'Fullname must be at least 3 chars'
333
+ json.message = "Fullname must be at least 3 chars";
315
334
  }
316
335
  if (body.company.length < 3) {
317
- json.message = 'Company Name must be at least 3 chars'
336
+ json.message = "Company Name must be at least 3 chars";
318
337
  }
319
- json.status = json.message == 'ok' ? 1 : 0
320
- return json
321
- }
338
+ json.status = json.message == "ok" ? 1 : 0;
339
+ return json;
340
+ };
322
341
 
323
342
  const registrationCUSTOMValidation = (body) => {
324
343
  var json = {
325
- message: 'ok',
344
+ message: "ok",
326
345
  status: 0,
327
- }
346
+ };
328
347
  if (!Util.validateEmail(body.username)) {
329
- json.message = 'Format email salah'
348
+ json.message = "Format email salah";
330
349
  }
331
350
  if (body.password != body.confirm_password) {
332
- json.message = 'Password dan repasword tidak cocok'
351
+ json.message = "Password dan repasword tidak cocok";
333
352
  }
334
353
  if (body.password.length < 6) {
335
- json.message = 'Password kurang dari 6 '
354
+ json.message = "Password kurang dari 6 ";
336
355
  }
337
356
  if (body.fullname.length < 6) {
338
- json.message = 'Nama lengkap kurang lengkap'
357
+ json.message = "Nama lengkap kurang lengkap";
339
358
  }
340
359
  if (body.phone.length < 6) {
341
- json.message = 'No telp kurang lengkap'
360
+ json.message = "No telp kurang lengkap";
342
361
  }
343
- json.status = json.message == 'ok' ? 1 : 0
344
- return json
345
- }
362
+ json.status = json.message == "ok" ? 1 : 0;
363
+ return json;
364
+ };
346
365
 
347
- router.post('/signup-custom', async (req, res) => {
348
- var body = req.body
366
+ router.post("/signup-custom", async (req, res) => {
367
+ var body = req.body;
349
368
  try {
350
- var validation = registrationCUSTOMValidation(body)
369
+ var validation = registrationCUSTOMValidation(body);
351
370
  if (validation.status == 0) {
352
- res.json(Util.flashError(validation.message))
353
- return false
371
+ res.json(Util.flashError(validation.message));
372
+ return false;
354
373
  }
355
374
 
356
375
  var dataUser = {
@@ -366,116 +385,117 @@ router.post('/signup-custom', async (req, res) => {
366
385
  password: Util.hash(body.password),
367
386
  fullname: body.fullname,
368
387
  phone: body.phone,
369
- verify_signed: 'lizhn63iqA8CVDQeOw8.png',
388
+ verify_signed: "lizhn63iqA8CVDQeOw8.png",
370
389
  active: 0,
371
- language: '2',
372
- }
390
+ language: "2",
391
+ };
373
392
  var user = await connection.insert({
374
- table: 'zuser',
393
+ table: "zuser",
375
394
  data: dataUser,
376
- })
395
+ });
377
396
  var userCompany = await connection.insert({
378
- table: 'zuser_company',
397
+ table: "zuser_company",
379
398
  data: {
380
399
  role_id: 4,
381
400
  company_id: 1,
382
401
  user_id: user.id,
383
402
  },
384
- })
403
+ });
385
404
  /* await zRoute.loginAjax(dataUser.username, body.password, req, res);
386
405
  //refresh cache
387
406
  await zCache.renew();*/
388
407
 
389
- res.json(Util.jsonSuccess('Successfuly'))
408
+ res.json(Util.jsonSuccess("Successfuly"));
390
409
  } catch (e) {
391
- res.json(Util.flashError(e.toString()))
410
+ res.json(Util.flashError(e.toString()));
392
411
  }
393
- })
412
+ });
394
413
 
395
- router.post('/gridprint', async (req, res) => {
396
- let html = ''
397
- let id = req.body.id
398
- let table = req.body.table
414
+ router.post("/gridprint", async (req, res) => {
415
+ let html = "";
416
+ let id = req.body.id;
417
+ let table = req.body.table;
399
418
  if (id) {
400
419
  let results = await connection.results({
401
- table: 'zapprovals',
420
+ table: "zapprovals",
402
421
  where: {
403
422
  id_data: id,
404
423
  table: table,
405
424
  },
406
- })
425
+ });
407
426
  if (results.length) {
408
- let result = results[0]
427
+ let result = results[0];
409
428
  if (result.status == 3 || result.status == 4) {
410
- html += `<button class="btn btn-sm btn-info gridprint" data-token="${result.token}"><span class="fa fa-print"></span></button> `
429
+ html += `<button class="btn btn-sm btn-info gridprint" data-token="${result.token}"><span class="fa fa-print"></span></button> `;
411
430
  }
412
431
  }
413
432
  }
414
- res.json(html)
415
- })
416
-
417
- router.get('/failed', async function (req, res) {
418
- let template = 'fronts'
419
- res.render('layouts/' + template, {
420
- menu: 'failed',
421
- renderBody: 'index/failed.ejs',
433
+ res.json(html);
434
+ });
435
+
436
+ router.get("/failed", async function (req, res) {
437
+ let template = "fronts";
438
+ res.render("layouts/" + template, {
439
+ menu: "failed",
440
+ renderBody: "index/failed.ejs",
422
441
  Util: Util,
423
- })
424
- })
442
+ });
443
+ });
425
444
 
426
- router.get('/forgot', csrfProtection, async (req, res) => {
427
- const MYMODELS = myCache.get('MYMODELS')
428
- let MYMODEL = MYMODELS['zuser']
445
+ router.get("/forgot", csrfProtection, async (req, res) => {
446
+ const MYMODELS = myCache.get("MYMODELS");
447
+ let MYMODEL = MYMODELS["zuser"];
429
448
  if (res.locals.isLogin) {
430
- return res.redirect('/dashboard')
449
+ return res.redirect("/dashboard");
431
450
  }
432
451
  let script = `submitForm('forgot-form',"","",function(data){if (data.status == 1) {
433
452
  toastrForm(data);spinner.hide();
434
453
  setTimeout(function () {location.href='/';},6000);
435
- }});`
436
- await moduleLib.custom(req, res, script)
454
+ }});`;
455
+ await moduleLib.custom(req, res, script);
437
456
 
438
- res.render('layouts/fronts', {
457
+ res.render("layouts/fronts", {
439
458
  csrfToken: req.csrfToken(),
440
459
  attributeData: MYMODEL,
441
- routeName: 'zuser',
460
+ routeName: "zuser",
442
461
  data: MYMODEL.datas,
443
- renderBody: 'index/forgot.ejs',
444
- })
445
- })
446
-
447
- router.post('/forgot', csrfProtection, async (req, res) => {
448
- let json = Util.jsonError('email', 'Email not found in our database')
449
- let routeName = 'user'
450
- const MYMODELS = myCache.get('MYMODELS')
451
- let MYMODEL = MYMODELS['zuser']
452
- let data = zRoute.post(req, res, MYMODEL)['zuser']
453
- var port = ecosystem.apps[0].env.PORT
454
- var url = env == 'production' ? process.env.APP_URL : 'http://localhost:' + port
455
- let email = data.email || ' '
456
- email = email.trim()
462
+ renderBody: "index/forgot.ejs",
463
+ });
464
+ });
465
+
466
+ router.post("/forgot", csrfProtection, async (req, res) => {
467
+ let json = Util.jsonError("email", "Email not found in our database");
468
+ let routeName = "user";
469
+ const MYMODELS = myCache.get("MYMODELS");
470
+ let MYMODEL = MYMODELS["zuser"];
471
+ let data = zRoute.post(req, res, MYMODEL)["zuser"];
472
+ var port = ecosystem.apps[0].env.PORT;
473
+ var url =
474
+ env == "production" ? process.env.APP_URL : "http://localhost:" + port;
475
+ let email = data.email || " ";
476
+ email = email.trim();
457
477
  if (email.length > 5) {
458
478
  let rows = await connection.results({
459
- table: 'zuser',
479
+ table: "zuser",
460
480
  where: {
461
481
  email: email,
462
482
  },
463
- })
483
+ });
464
484
  if (rows.length > 0) {
465
485
  let post = {
466
486
  forgot_password: Util.generateUnique(23),
467
- }
487
+ };
468
488
  await connection.update({
469
- table: 'zuser',
489
+ table: "zuser",
470
490
  where: {
471
491
  id: rows[0].id,
472
492
  },
473
493
  data: post,
474
- })
494
+ });
475
495
  let options = {
476
496
  to: email,
477
- subject: 'Forgot Password',
478
- }
497
+ subject: "Forgot Password",
498
+ };
479
499
  let datas = {
480
500
  config: {
481
501
  app: {
@@ -483,194 +503,206 @@ router.post('/forgot', csrfProtection, async (req, res) => {
483
503
  },
484
504
  },
485
505
  url: url,
486
- link: url + '/reset-password/' + post.forgot_password,
487
- }
488
- Mail.forgotPassword(datas, options)
489
- json = Util.jsonSuccess('Please check your email to reset ')
506
+ link: url + "/reset-password/" + post.forgot_password,
507
+ };
508
+ Mail.forgotPassword(datas, options);
509
+ json = Util.jsonSuccess("Please check your email to reset ");
490
510
  }
491
511
  }
492
512
 
493
- res.json(json)
494
- })
495
-
496
- router.get('/reset-password/:forgot_password', csrfProtection, async (req, res) => {
497
- let forgot_password = req.params.forgot_password || ''
498
- let activated = false
499
- if (forgot_password != '') {
500
- let results = await connection.results({
501
- table: 'zuser',
502
- where: {
503
- forgot_password: forgot_password,
504
- },
505
- })
506
- if (results.length > 0) {
507
- activated = true
513
+ res.json(json);
514
+ });
515
+
516
+ router.get(
517
+ "/reset-password/:forgot_password",
518
+ csrfProtection,
519
+ async (req, res) => {
520
+ let forgot_password = req.params.forgot_password || "";
521
+ let activated = false;
522
+ if (forgot_password != "") {
523
+ let results = await connection.results({
524
+ table: "zuser",
525
+ where: {
526
+ forgot_password: forgot_password,
527
+ },
528
+ });
529
+ if (results.length > 0) {
530
+ activated = true;
531
+ }
508
532
  }
509
- }
510
- var script = `submitForm('form-group','','',function(data){
533
+ var script = `submitForm('form-group','','',function(data){
511
534
  if(data.status==1){
512
535
  location.href = '/login'
513
536
  }
514
- });`
515
- await moduleLib.custom(req, res, script)
516
- res.render('layouts/fronts', {
517
- activated: activated,
518
- csrfToken: req.csrfToken(),
519
- forgot_password: forgot_password,
520
- renderBody: 'index/reset-password.ejs',
521
- })
522
- })
537
+ });`;
538
+ await moduleLib.custom(req, res, script);
539
+ res.render("layouts/fronts", {
540
+ activated: activated,
541
+ csrfToken: req.csrfToken(),
542
+ forgot_password: forgot_password,
543
+ renderBody: "index/reset-password.ejs",
544
+ });
545
+ }
546
+ );
523
547
 
524
- router.get('/no-access', async (req, res) => {
525
- let myview = 'fronts'
548
+ router.get("/no-access", async (req, res) => {
549
+ let myview = "fronts";
526
550
  if (req.session.user) {
527
- myview = 'main'
551
+ myview = "main";
528
552
  }
529
- res.render('layouts/' + myview, {
530
- data: { table: 'error' },
531
- menu: 'error',
532
- renderBody: 'index/no-access.ejs',
533
- })
534
- })
535
-
536
- router.get('/page_not_found', async (req, res) => {
537
- res.render('layouts/page_not_found', {
538
- data: { table: 'error' },
539
- menu: 'error',
553
+ res.render("layouts/" + myview, {
554
+ data: { table: "error" },
555
+ menu: "error",
556
+ renderBody: "index/no-access.ejs",
557
+ });
558
+ });
559
+
560
+ router.get("/page_not_found", async (req, res) => {
561
+ res.render("layouts/page_not_found", {
562
+ data: { table: "error" },
563
+ menu: "error",
540
564
  //renderBody: "index/no-found.ejs",
541
- })
542
- })
565
+ });
566
+ });
543
567
 
544
568
  // for change company session
545
- router.get('/session/:id', access, async (req, res) => {
546
- let companies = res.locals.zcompanies
569
+ router.get("/session/:id", access, async (req, res) => {
570
+ let companies = res.locals.zcompanies;
547
571
  let user = await connection.result({
548
- table: 'zuser',
572
+ table: "zuser",
549
573
  where: {
550
574
  id: res.locals.userId,
551
575
  },
552
- })
576
+ });
553
577
  for (let i = 0; i < companies.length; i++) {
554
578
  if (companies[i].id == req.params.id) {
555
- user.company_id = req.params.id
556
- await zRoute.handleSession(req, user)
579
+ user.company_id = req.params.id;
580
+ await zRoute.handleSession(req, user);
557
581
  var post = {
558
582
  company_id: companies[i].id,
559
583
  role_id: companies[i].role_id,
560
- }
584
+ };
561
585
  await connection.update({
562
- table: 'zuser',
586
+ table: "zuser",
563
587
  data: post,
564
588
  where: {
565
589
  id: res.locals.userId,
566
590
  },
567
- })
591
+ });
568
592
  }
569
593
  }
570
- var backURL = req.header('Referer') || '/'
594
+ var backURL = req.header("Referer") || "/";
571
595
  // do your thang
572
- res.redirect(backURL)
573
- })
596
+ res.redirect(backURL);
597
+ });
574
598
 
575
599
  //RESTART
576
- router.get('/restart', access, async (req, res) => {
577
- var room = res.locals.user.token
578
- if (env == 'production') {
600
+ router.get("/restart", access, async (req, res) => {
601
+ var room = res.locals.user.token;
602
+ if (env == "production") {
579
603
  pm2.connect(function (err) {
580
604
  if (err) {
581
- io.to(room).emit('error', err.toString())
605
+ io.to(room).emit("error", err.toString());
582
606
  }
583
607
  pm2.restart(process.env.PM2_NAME, (err, proc) => {
584
- io.to(room).emit('message', 'Restart done')
585
- })
586
- })
608
+ io.to(room).emit("message", "Restart done");
609
+ });
610
+ });
587
611
  } else {
588
- io.to(room).emit('message', 'Restart done')
612
+ io.to(room).emit("message", "Restart done");
589
613
  }
590
- res.json('ok')
591
- })
614
+ res.json("ok");
615
+ });
592
616
 
593
617
  //ERROR UI
594
- router.get('/error', async (err, req, res, next) => {
595
- res.locals.message = err.message
596
- res.locals.error = req.app.get('env') === 'development' ? err : err
618
+ router.get("/error", async (err, req, res, next) => {
619
+ res.locals.message = err.message;
620
+ res.locals.error = req.app.get("env") === "development" ? err : err;
597
621
  // render the error page
598
- res.status(err.status || 500)
599
- debug(req, res, err)
600
- res.render('layouts/' + layout, {
601
- renderBody: 'index/error.ejs',
602
- })
603
- })
622
+ res.status(err.status || 500);
623
+ debug(req, res, err);
624
+ res.render("layouts/" + layout, {
625
+ renderBody: "index/error.ejs",
626
+ });
627
+ });
604
628
 
605
629
  //APPROVAL SYSTEMS
606
- router.post('/zzapproval', async (req, res) => {
607
- let json = Util.jsonSuccess(LANGUAGE['data_saved'])
608
- const MYMODELS = myCache.get('MYMODELS')
609
- let MYMODEL = MYMODELS['zapprovals']
610
- const port = ecosystem.apps[0].env.PORT
611
- let users = Util.arrayToObject(await connection.results({ table: 'zuser' }), 'id')
630
+ router.post("/zzapproval", async (req, res) => {
631
+ let json = Util.jsonSuccess(LANGUAGE["data_saved"]);
632
+ const MYMODELS = myCache.get("MYMODELS");
633
+ let MYMODEL = MYMODELS["zapprovals"];
634
+ const port = ecosystem.apps[0].env.PORT;
635
+ let users = Util.arrayToObject(
636
+ await connection.results({ table: "zuser" }),
637
+ "id"
638
+ );
612
639
  try {
613
- let userId = res.locals.userId
614
- let data = zRoute.post(req, res, MYMODEL)[MYMODEL.table]
615
- let validator = zRoute.validator(data, MYMODEL)
616
- if (validator.status == 0) return res.json(validator.message)
640
+ let userId = res.locals.userId;
641
+ let data = zRoute.post(req, res, MYMODEL)[MYMODEL.table];
642
+ let validator = zRoute.validator(data, MYMODEL);
643
+ if (validator.status == 0) return res.json(validator.message);
617
644
  if (data.status == 2) {
618
645
  if (!data.approvers) {
619
- return res.json(Util.flashError('Approvers empty'))
646
+ return res.json(Util.flashError("Approvers empty"));
620
647
  }
621
- if (data.title == '') {
622
- return res.json(Util.flashError('Title empty', 'title'))
648
+ if (data.title == "") {
649
+ return res.json(Util.flashError("Title empty", "title"));
623
650
  }
624
651
  }
625
652
  //update template for newst
626
- var row = await connection.result({ table: 'zfields', where: { table: data.table } })
627
- var jsonApproval = row.approval_json || {}
628
- data.template = jsonApproval.content || {}
629
- var approvers = []
630
- if (typeof data.approvers == 'string') {
631
- data.approvers = JSON.parse(data.approvers)
653
+ var row = await connection.result({
654
+ table: "zfields",
655
+ where: { table: data.table },
656
+ });
657
+ var jsonApproval = row.approval_json || {};
658
+ data.template = jsonApproval.content || {};
659
+ var approvers = [];
660
+ if (typeof data.approvers == "string") {
661
+ data.approvers = JSON.parse(data.approvers);
632
662
  }
633
- approvers = data.approvers || []
663
+ approvers = data.approvers || [];
634
664
  if (approvers.length > 1) {
635
- approvers = approvers.filter(Util.arrayUnique)
665
+ approvers = approvers.filter(Util.arrayUnique);
636
666
  }
637
- data.approvers = JSON.stringify(approvers)
638
- let knowings = []
639
- if (typeof data.knowings == 'string') {
640
- data.knowings = JSON.parse(data.knowings)
667
+ data.approvers = JSON.stringify(approvers);
668
+ let knowings = [];
669
+ if (typeof data.knowings == "string") {
670
+ data.knowings = JSON.parse(data.knowings);
641
671
  }
642
- knowings = data.knowings || []
672
+ knowings = data.knowings || [];
643
673
  if (knowings.length > 1) {
644
- knowings = knowings.filter(Util.arrayUnique)
674
+ knowings = knowings.filter(Util.arrayUnique);
645
675
  }
646
- data.knowings = JSON.stringify(knowings)
647
- let allUsers = [...approvers, ...knowings]
676
+ data.knowings = JSON.stringify(knowings);
677
+ let allUsers = [...approvers, ...knowings];
648
678
 
649
679
  let statusApprovers = approvers.reduce((result, item) => {
650
- return [...result, { user: item, status: 2 }]
651
- }, [])
680
+ return [...result, { user: item, status: 2 }];
681
+ }, []);
652
682
  data.approved_stats = JSON.stringify({
653
683
  stats: `0/${approvers.length}`,
654
684
  status: statusApprovers,
655
- })
685
+ });
656
686
  let knowingStatus = knowings.reduce((result, item) => {
657
- return [...result, { user: item, status: 7 }]
658
- }, [])
687
+ return [...result, { user: item, status: 7 }];
688
+ }, []);
659
689
 
660
690
  data.knowing_stats = JSON.stringify({
661
691
  stats: `0/${knowings.length}`,
662
692
  status: knowingStatus,
663
- })
693
+ });
664
694
  let results = await connection.results({
665
695
  table: MYMODEL.table,
666
696
  where: { table: data.table, id_data: data.id_data },
667
- })
697
+ });
668
698
  if (results.length) {
669
- let query = await zRoute.updateSQL(req, res, MYMODEL.table, data, { id: results[0].id })
670
- data.id = results[0].id
699
+ let query = await zRoute.updateSQL(req, res, MYMODEL.table, data, {
700
+ id: results[0].id,
701
+ });
702
+ data.id = results[0].id;
671
703
  } else {
672
- var query = await zRoute.insertSQL(req, res, MYMODEL.table, data)
673
- data.id = query.id
704
+ var query = await zRoute.insertSQL(req, res, MYMODEL.table, data);
705
+ data.id = query.id;
674
706
  }
675
707
  if (data.status == 2) {
676
708
  //send activity
@@ -686,32 +718,32 @@ router.post('/zzapproval', async (req, res) => {
686
718
  });*/
687
719
  //if serial
688
720
  if (data.type == 2) {
689
- approvers = [approvers[0]]
721
+ approvers = [approvers[0]];
690
722
  }
691
723
  let sectionsAprrovers = approvers.reduce((temp, item, index) => {
692
724
  return [
693
725
  ...temp,
694
726
  {
695
727
  title: users[item].fullname,
696
- description: '@' + users[item].fullname,
697
- rowId: 'row' + index,
728
+ description: "@" + users[item].fullname,
729
+ rowId: "row" + index,
698
730
  },
699
- ]
700
- }, [])
731
+ ];
732
+ }, []);
701
733
  let sectionsKnowings = knowings.reduce((temp, item, index) => {
702
734
  return [
703
735
  ...temp,
704
736
  {
705
737
  title: users[item].fullname,
706
- description: '@' + users[item].fullname,
707
- rowId: 'row' + index,
738
+ description: "@" + users[item].fullname,
739
+ rowId: "row" + index,
708
740
  },
709
- ]
710
- }, [])
711
- let sections = []
712
- sections.push({ title: 'Approvers', rows: sectionsAprrovers })
741
+ ];
742
+ }, []);
743
+ let sections = [];
744
+ sections.push({ title: "Approvers", rows: sectionsAprrovers });
713
745
  if (sectionsKnowings) {
714
- sections.push({ title: 'Knowings', rows: sectionsKnowings })
746
+ sections.push({ title: "Knowings", rows: sectionsKnowings });
715
747
  }
716
748
  approvers.forEach(async (item, num) => {
717
749
  let post = {
@@ -720,32 +752,37 @@ router.post('/zzapproval', async (req, res) => {
720
752
  status: 7,
721
753
  type: 1,
722
754
  token: Util.uuid(),
723
- }
724
- await zRoute.insertSQL(req, res, 'zapprovals_details', post)
725
- let link = env == 'production' ? process.env.APP_URL + '/za/' + post.token : `http://localhost:${port}/za/${post.token}`
726
- let email = users[post.user_id].email
727
-
728
- post.subject = `Need Approve ${data.title}`
729
- post.buttonTitle = `Approve Now`
730
- post.title = `NEED APPROVE DOCUMENT`
731
- post.link = link
732
- post.url = CONFIG.app.url
755
+ };
756
+ await zRoute.insertSQL(req, res, "zapprovals_details", post);
757
+ let link =
758
+ env == "production"
759
+ ? process.env.APP_URL + "/za/" + post.token
760
+ : `http://localhost:${port}/za/${post.token}`;
761
+ let email = users[post.user_id].email;
762
+
763
+ post.subject = `Need Approve ${data.title}`;
764
+ post.buttonTitle = `Approve Now`;
765
+ post.title = `NEED APPROVE DOCUMENT`;
766
+ post.link = link;
767
+ post.url = CONFIG.app.url;
733
768
  post.description = `Hai ${users[post.user_id].fullname} <br>
734
769
 
735
770
 
736
771
  We have some document for you.<br>
737
- Please click the link above to view the document.`
772
+ Please click the link above to view the document.`;
738
773
 
739
- post.note = `If you click the link, it's will be automatically acknowledged`
740
- Mail.gmail(req, res, post, email)
774
+ post.note = `If you click the link, it's will be automatically acknowledged`;
775
+ Mail.gmail(req, res, post, email);
741
776
 
742
777
  //send to whatsapp
743
- let phone = Util.phoneWA(users[post.user_id].phone)
778
+ let phone = Util.phoneWA(users[post.user_id].phone);
744
779
  if (phone) {
745
- var textWa = ''
746
- textWa += `*NEED APPROVE DOCUMENT* \r\n_${data.title}_\r\nHai ${users[post.user_id].fullname} \r\n \r\n`
747
- textWa += 'We have some document for you.\r\n'
748
- textWa += `Please click the link above to view the document.\r\n${link}`
780
+ var textWa = "";
781
+ textWa += `*NEED APPROVE DOCUMENT* \r\n_${data.title}_\r\nHai ${
782
+ users[post.user_id].fullname
783
+ } \r\n \r\n`;
784
+ textWa += "We have some document for you.\r\n";
785
+ textWa += `Please click the link above to view the document.\r\n${link}`;
749
786
 
750
787
  /* await whatsapp({
751
788
  to: phone,
@@ -782,8 +819,8 @@ router.post('/zzapproval', async (req, res) => {
782
819
  });*/
783
820
 
784
821
  //send toastr using socket.io
785
- io.to(users[item].token).emit('message', 'Need Approve ' + data.title)
786
- })
822
+ io.to(users[item].token).emit("message", "Need Approve " + data.title);
823
+ });
787
824
 
788
825
  knowings.map(async (item) => {
789
826
  let post = {
@@ -792,33 +829,38 @@ router.post('/zzapproval', async (req, res) => {
792
829
  status: 7,
793
830
  type: 2,
794
831
  token: Util.uuid(),
795
- }
796
- await zRoute.insertSQL(req, res, 'zapprovals_details', post)
797
- let link = env == 'production' ? process.env.APP_URL + '/za/' + post.token : `http://localhost:${port}/za/${post.token}`
798
- let email = users[post.user_id].email
799
-
800
- post.subject = `Need acknowledge ${data.title}`
801
- post.buttonTitle = `Acknowledge Now`
802
- post.title = `NEED ACKNOWLEDGE DOCUMENT`
803
-
804
- post.link = link
805
- post.url = CONFIG.app.url
832
+ };
833
+ await zRoute.insertSQL(req, res, "zapprovals_details", post);
834
+ let link =
835
+ env == "production"
836
+ ? process.env.APP_URL + "/za/" + post.token
837
+ : `http://localhost:${port}/za/${post.token}`;
838
+ let email = users[post.user_id].email;
839
+
840
+ post.subject = `Need acknowledge ${data.title}`;
841
+ post.buttonTitle = `Acknowledge Now`;
842
+ post.title = `NEED ACKNOWLEDGE DOCUMENT`;
843
+
844
+ post.link = link;
845
+ post.url = CONFIG.app.url;
806
846
  post.description = `Hai ${users[post.user_id].fullname} <br>
807
847
 
808
848
 
809
849
  We have some document for you.<br>
810
- Please click the link above to view the document.`
850
+ Please click the link above to view the document.`;
811
851
 
812
- post.note = `If you click the link, it's will be automatically acknowledged`
813
- Mail.gmail(req, res, post, email)
852
+ post.note = `If you click the link, it's will be automatically acknowledged`;
853
+ Mail.gmail(req, res, post, email);
814
854
 
815
855
  //send to whatsapp
816
- let phone = Util.phoneWA(users[post.user_id].phone)
856
+ let phone = Util.phoneWA(users[post.user_id].phone);
817
857
  if (phone) {
818
- var textWa = ''
819
- textWa += `*NEED ACKNOWLEDGE DOCUMENT* \r\n_${data.title}_\r\nHai ${users[post.user_id].fullname} \r\n \r\n`
820
- textWa += 'We have some document for you.\r\n'
821
- textWa += `Please click the link above to view the document.\r\n${link}`
858
+ var textWa = "";
859
+ textWa += `*NEED ACKNOWLEDGE DOCUMENT* \r\n_${data.title}_\r\nHai ${
860
+ users[post.user_id].fullname
861
+ } \r\n \r\n`;
862
+ textWa += "We have some document for you.\r\n";
863
+ textWa += `Please click the link above to view the document.\r\n${link}`;
822
864
  /* await whatsapp({
823
865
  to: phone,
824
866
  text: textWa,
@@ -864,104 +906,140 @@ router.post('/zzapproval', async (req, res) => {
864
906
  description: data.title,
865
907
  users: JSON.stringify(allUsers)
866
908
  });*/
867
- io.to(users[item].token).emit('message', 'Need Acknowledge ' + data.title)
868
- })
909
+ io.to(users[item].token).emit(
910
+ "message",
911
+ "Need Acknowledge " + data.title
912
+ );
913
+ });
869
914
  }
870
915
  } catch (err) {
871
- if (Object.prototype.hasOwnProperty.call(err, 'sqlMessage')) {
872
- json = Util.flashError(err.sqlMessage)
916
+ if (Object.prototype.hasOwnProperty.call(err, "sqlMessage")) {
917
+ json = Util.flashError(err.sqlMessage);
873
918
  } else {
874
- json = Util.flashError(err.toString())
919
+ json = Util.flashError(err.toString());
875
920
  }
876
- debug(req, res, err)
921
+ debug(req, res, err);
877
922
  }
878
- res.json(json)
879
- })
923
+ res.json(json);
924
+ });
880
925
 
881
- router.get('/za/:token', csrfProtection, async (req, res) => {
882
- let token = req.params.token
926
+ router.get("/za/:token", csrfProtection, async (req, res) => {
927
+ let token = req.params.token;
883
928
  let data = {},
884
- data2 = {}
885
- let template = ''
886
- let result
887
- let isClosed = false
888
- let footers = ''
889
- let details = []
890
- let routeName = env == 'production' ? process.env.APP_URL : `http://localhost:${port}`
891
- let statusLabel = ''
892
- let knowings = []
893
- const MYMODELS = myCache.get('MYMODELS')
894
- let MYMODEL = MYMODELS['zapprovals']
895
- let users = Util.arrayToObject(await connection.results({ table: 'zuser' }), 'id')
929
+ data2 = {};
930
+ let template = "";
931
+ let result;
932
+ let isClosed = false;
933
+ let footers = "";
934
+ let details = [];
935
+ let routeName =
936
+ env == "production" ? process.env.APP_URL : `http://localhost:${port}`;
937
+ let statusLabel = "";
938
+ let knowings = [];
939
+ const MYMODELS = myCache.get("MYMODELS");
940
+ let MYMODEL = MYMODELS["zapprovals"];
941
+ let users = Util.arrayToObject(
942
+ await connection.results({ table: "zuser" }),
943
+ "id"
944
+ );
896
945
  try {
897
946
  result = await connection.result({
898
- select: '*, zapprovals.id as ide, zapprovals_details.token as usertoken, zapprovals.status as statuse, zapprovals_details.status as mystatus, zapprovals_details.type as user_type, zapprovals_details.updated_at',
899
- table: 'zapprovals_details',
900
- joins: ['LEFT JOIN zapprovals ON (zapprovals_details.title_id = zapprovals.id)', 'LEFT JOIN employee ON (zapprovals_details.user_id = employee.id)'],
901
- where: { 'zapprovals_details.token': token },
902
- })
903
- let approvers = result.approvers
904
- knowings = result.knowings ? result.knowings : []
905
-
906
- statusLabel = MYMODEL.widgets.status.fields[result.statuse]
907
- routeName = routeName + '/' + result.table + '/view/' + result.id_data
908
- if (result.statuse == 3 || result.statuse == 4 || result.mystatus == 3 || result.mystatus == 4) {
909
- isClosed = true
947
+ select:
948
+ "*, zapprovals.id as ide, zapprovals_details.token as usertoken, zapprovals.status as statuse, zapprovals_details.status as mystatus, zapprovals_details.type as user_type, zapprovals_details.updated_at",
949
+ table: "zapprovals_details",
950
+ joins: [
951
+ "LEFT JOIN zapprovals ON (zapprovals_details.title_id = zapprovals.id)",
952
+ "LEFT JOIN employee ON (zapprovals_details.user_id = employee.id)",
953
+ ],
954
+ where: { "zapprovals_details.token": token },
955
+ });
956
+ let approvers = result.approvers;
957
+ knowings = result.knowings ? result.knowings : [];
958
+
959
+ statusLabel = MYMODEL.widgets.status.fields[result.statuse];
960
+ routeName = routeName + "/" + result.table + "/view/" + result.id_data;
961
+ if (
962
+ result.statuse == 3 ||
963
+ result.statuse == 4 ||
964
+ result.mystatus == 3 ||
965
+ result.mystatus == 4
966
+ ) {
967
+ isClosed = true;
910
968
  }
911
- details = await connection.results({ table: 'zapprovals_details', where: { title_id: result.ide } })
969
+ details = await connection.results({
970
+ table: "zapprovals_details",
971
+ where: { title_id: result.ide },
972
+ });
912
973
  if (result.user_type == 2) {
913
- isClosed = true
974
+ isClosed = true;
914
975
  var post = {
915
976
  status: 6, //read
916
- }
917
- await connection.update({ table: 'zapprovals_details', data: post, where: { token: token } })
977
+ };
978
+ await connection.update({
979
+ table: "zapprovals_details",
980
+ data: post,
981
+ where: { token: token },
982
+ });
918
983
 
919
984
  //set stats
920
985
  //{"stats":"0/1","status":[{"user":"12","status":0}]}
921
- let knowing_stats = result.knowing_stats || {}
922
- let statuses = knowing_stats.status
923
- let stats = knowing_stats.stats
924
- let explode = stats.split('/')
925
- let count = parseInt(explode[0])
926
- let newStatus = []
927
- knowings = result.knowings || []
986
+ let knowing_stats = result.knowing_stats || {};
987
+ let statuses = knowing_stats.status;
988
+ let stats = knowing_stats.stats;
989
+ let explode = stats.split("/");
990
+ let count = parseInt(explode[0]);
991
+ let newStatus = [];
992
+ knowings = result.knowings || [];
928
993
  statuses.map((item) => {
929
994
  if (item.user == result.user_id && result.mystatus != 3) {
930
- item.status = 3
995
+ item.status = 3;
931
996
  if (count < knowings.length) {
932
- count = count + 1
997
+ count = count + 1;
933
998
  }
934
- newStatus.push(item)
999
+ newStatus.push(item);
935
1000
  } else {
936
- newStatus.push(item)
1001
+ newStatus.push(item);
937
1002
  }
938
- })
1003
+ });
939
1004
  if (result.mystatus != 3) {
940
1005
  post = {
941
- knowing_stats: JSON.stringify({ stats: count + '/' + explode[1], status: newStatus }),
942
- }
943
- await connection.update({ table: 'zapprovals', data: post, where: { id: result.ide } })
1006
+ knowing_stats: JSON.stringify({
1007
+ stats: count + "/" + explode[1],
1008
+ status: newStatus,
1009
+ }),
1010
+ };
1011
+ await connection.update({
1012
+ table: "zapprovals",
1013
+ data: post,
1014
+ where: { id: result.ide },
1015
+ });
944
1016
  //var users = await zRoute.getUsers();
945
- var message = users[result.user_id].fullname + ' has readed document ' + result.title
1017
+ var message =
1018
+ users[result.user_id].fullname +
1019
+ " has readed document " +
1020
+ result.title;
946
1021
  details.forEach(function (item) {
947
- io.to(users[item.user_id].token).emit('message', message)
948
- })
1022
+ io.to(users[item.user_id].token).emit("message", message);
1023
+ });
949
1024
  }
950
1025
  }
951
1026
 
952
- MYMODEL = MYMODELS[result.table]
953
- let row = await connection.result({ table: MYMODEL.table, where: { id: result.id_data } })
954
- data = await zRoute.viewTable(req, res, MYMODEL, row)
955
- template = result.template
1027
+ MYMODEL = MYMODELS[result.table];
1028
+ let row = await connection.result({
1029
+ table: MYMODEL.table,
1030
+ where: { id: result.id_data },
1031
+ });
1032
+ data = await zRoute.viewTable(req, res, MYMODEL, row);
1033
+ template = result.template;
956
1034
  for (var key in data) {
957
- template = Util.replaceAll(template, '{{' + key + '}}', data[key])
1035
+ template = Util.replaceAll(template, "{{" + key + "}}", data[key]);
958
1036
  }
959
1037
 
960
- footers = await zRoute.approversFooter(details)
1038
+ footers = await zRoute.approversFooter(details);
961
1039
 
962
1040
  //send activity
963
1041
  if (result.mystatus == 7) {
964
- MYMODEL = MYMODELS['zapprovals']
1042
+ MYMODEL = MYMODELS["zapprovals"];
965
1043
  /* await connection.insert({
966
1044
  table: "zactivity",
967
1045
  data: {
@@ -982,18 +1060,18 @@ router.get('/za/:token', csrfProtection, async (req, res) => {
982
1060
  */
983
1061
 
984
1062
  await connection.update({
985
- table: 'zapprovals_details',
1063
+ table: "zapprovals_details",
986
1064
  where: {
987
1065
  token: token,
988
1066
  },
989
1067
  data: { status: 6 },
990
- })
1068
+ });
991
1069
  }
992
1070
  } catch (err) {
993
- debug(req, res, err)
994
- res.send('Not Found')
1071
+ debug(req, res, err);
1072
+ res.send("Not Found");
995
1073
  }
996
- res.render('layouts/blank', {
1074
+ res.render("layouts/blank", {
997
1075
  routeName: routeName,
998
1076
  Util: Util,
999
1077
  data: data,
@@ -1006,87 +1084,104 @@ router.get('/za/:token', csrfProtection, async (req, res) => {
1006
1084
  csrfToken: req.csrfToken(),
1007
1085
  token: result.usertoken,
1008
1086
  tokendoc: token,
1009
- renderHead: 'index/zacss.ejs',
1010
- renderBody: 'index/za.ejs',
1011
- renderEnd: 'index/zajs.ejs',
1012
- })
1013
- })
1014
-
1015
- router.post('/za/:token', csrfProtection, async (req, res) => {
1016
- let token = req.params.token
1017
- let comments = req.body.comments
1018
- let status = req.body.status
1019
- let json = Util.jsonSuccess('Success')
1087
+ renderHead: "index/zacss.ejs",
1088
+ renderBody: "index/za.ejs",
1089
+ renderEnd: "index/zajs.ejs",
1090
+ });
1091
+ });
1092
+
1093
+ router.post("/za/:token", csrfProtection, async (req, res) => {
1094
+ let token = req.params.token;
1095
+ let comments = req.body.comments;
1096
+ let status = req.body.status;
1097
+ let json = Util.jsonSuccess("Success");
1020
1098
  let data = {},
1021
- data2 = {}
1022
- let template = ''
1099
+ data2 = {};
1100
+ let template = "";
1023
1101
  let approvers = [],
1024
- knowings = []
1025
- let users = Util.arrayToObject(await connection.results({ table: 'zuser' }), 'id')
1026
- let employee_user = users
1027
- const MYMODELS = myCache.get('MYMODELS')
1028
- let MYMODEL = MYMODELS['zapprovals']
1029
- let post = {}
1102
+ knowings = [];
1103
+ let users = Util.arrayToObject(
1104
+ await connection.results({ table: "zuser" }),
1105
+ "id"
1106
+ );
1107
+ let employee_user = users;
1108
+ const MYMODELS = myCache.get("MYMODELS");
1109
+ let MYMODEL = MYMODELS["zapprovals"];
1110
+ let post = {};
1030
1111
  try {
1031
1112
  var results = await connection.results({
1032
- select: '*,zapprovals_details.status as approvers_status, zapprovals.created_by as submiter, zapprovals.type as typee, zapprovals.status as statuse, zapprovals_details.id as detaild_id, zapprovals.id as ide, zapprovals.approvers as approvers ',
1033
- table: 'zapprovals_details',
1034
- joins: ['LEFT JOIN zapprovals ON (zapprovals_details.title_id = zapprovals.id)'],
1035
- where: { 'zapprovals_details.token': token },
1036
- })
1113
+ select:
1114
+ "*,zapprovals_details.status as approvers_status, zapprovals.created_by as submiter, zapprovals.type as typee, zapprovals.status as statuse, zapprovals_details.id as detaild_id, zapprovals.id as ide, zapprovals.approvers as approvers ",
1115
+ table: "zapprovals_details",
1116
+ joins: [
1117
+ "LEFT JOIN zapprovals ON (zapprovals_details.title_id = zapprovals.id)",
1118
+ ],
1119
+ where: { "zapprovals_details.token": token },
1120
+ });
1037
1121
  if (!results.length) {
1038
- return res.json(Util.jsonError('Data not found!'))
1122
+ return res.json(Util.jsonError("Data not found!"));
1039
1123
  }
1040
1124
 
1041
- var result = results[0]
1125
+ var result = results[0];
1042
1126
  if (result.approvers_status == 3 || result.approvers_status == 4) {
1043
- return res.json(Util.jsonError('You have submited.'))
1127
+ return res.json(Util.jsonError("You have submited."));
1044
1128
  }
1045
1129
  post = {
1046
1130
  status: status,
1047
1131
  comments: comments,
1048
1132
  updated_at: Util.now(),
1049
- }
1050
- let update = await connection.update({ table: 'zapprovals_details', data: post, where: { id: result.detaild_id } })
1051
- let details = await connection.results({ table: 'zapprovals_details', where: { title_id: result.ide } })
1052
- approvers = result.approvers
1053
- knowings = result.knowings || []
1054
- let stats = 0
1055
- let status_stats = []
1056
- let approversSigned = []
1133
+ };
1134
+ let update = await connection.update({
1135
+ table: "zapprovals_details",
1136
+ data: post,
1137
+ where: { id: result.detaild_id },
1138
+ });
1139
+ let details = await connection.results({
1140
+ table: "zapprovals_details",
1141
+ where: { title_id: result.ide },
1142
+ });
1143
+ approvers = result.approvers;
1144
+ knowings = result.knowings || [];
1145
+ let stats = 0;
1146
+ let status_stats = [];
1147
+ let approversSigned = [];
1057
1148
  //{"stats":"0/2","status":[{"user":"12","status":2},{"user":"35","status":2}]}
1058
- let last_status
1149
+ let last_status;
1059
1150
  details.map((item) => {
1060
1151
  if (item.type == 1) {
1061
1152
  if (item.status == 4 || item.status == 3) {
1062
- stats++
1063
- approversSigned.push(item.user_id + '')
1153
+ stats++;
1154
+ approversSigned.push(item.user_id + "");
1064
1155
  }
1065
1156
  status_stats.push({
1066
1157
  user: item.user_id,
1067
1158
  status: item.status,
1068
- })
1069
- last_status = item.status
1159
+ });
1160
+ last_status = item.status;
1070
1161
  }
1071
- })
1162
+ });
1072
1163
 
1073
1164
  post.approved_stats = JSON.stringify({
1074
- stats: stats + '/' + approvers.length,
1165
+ stats: stats + "/" + approvers.length,
1075
1166
  status: status_stats,
1076
- })
1167
+ });
1077
1168
  if (stats == approvers.length) {
1078
- post.status = last_status
1169
+ post.status = last_status;
1079
1170
  } else {
1080
- post.status = 5
1171
+ post.status = 5;
1081
1172
  }
1082
1173
  if (status == 4) {
1083
- post.status = 4
1174
+ post.status = 4;
1084
1175
  }
1085
- await connection.update({ table: 'zapprovals', data: post, where: { id: result.ide } })
1176
+ await connection.update({
1177
+ table: "zapprovals",
1178
+ data: post,
1179
+ where: { id: result.ide },
1180
+ });
1086
1181
 
1087
1182
  //send activity
1088
1183
  await connection.insert({
1089
- table: 'zactivity',
1184
+ table: "zactivity",
1090
1185
  data: {
1091
1186
  company_id: result.company_id,
1092
1187
  created_at: Util.now(),
@@ -1101,14 +1196,14 @@ router.post('/za/:token', csrfProtection, async (req, res) => {
1101
1196
  description: comments,
1102
1197
  data: JSON.stringify(post),
1103
1198
  },
1104
- })
1199
+ });
1105
1200
 
1106
1201
  //send notification
1107
1202
  if (status == 3 || status == 4) {
1108
- let message = `Document ${result.title} has ${MYMODEL.widgets.status[status]};`
1203
+ let message = `Document ${result.title} has ${MYMODEL.widgets.status[status]};`;
1109
1204
  approvers.forEach(function (item) {
1110
- io.to(users[item].token).emit('message', message)
1111
- })
1205
+ io.to(users[item].token).emit("message", message);
1206
+ });
1112
1207
  if (status == 3) {
1113
1208
  // if type is serial is step by step
1114
1209
  //send notification and generate email
@@ -1116,11 +1211,11 @@ router.post('/za/:token', csrfProtection, async (req, res) => {
1116
1211
  if (result.typee == 2) {
1117
1212
  //get approvers has already sign
1118
1213
 
1119
- approversSigned.push(result.user_id)
1214
+ approversSigned.push(result.user_id);
1120
1215
  var newApprovers = approvers.filter((item) => {
1121
- return !approversSigned.includes(item)
1122
- })
1123
- var item = newApprovers.length ? newApprovers[0] : ''
1216
+ return !approversSigned.includes(item);
1217
+ });
1218
+ var item = newApprovers.length ? newApprovers[0] : "";
1124
1219
  if (item) {
1125
1220
  post = {
1126
1221
  title_id: result.ide,
@@ -1134,57 +1229,59 @@ router.post('/za/:token', csrfProtection, async (req, res) => {
1134
1229
  updated_at: Util.now(),
1135
1230
  created_by: employee_user[item].user_id,
1136
1231
  updated_by: employee_user[item].user_id,
1137
- }
1232
+ };
1138
1233
  await connection.insert({
1139
- table: 'zapprovals_details',
1234
+ table: "zapprovals_details",
1140
1235
  data: post,
1141
- })
1142
- let link = CONFIG.app.url + '/za/' + post.token
1143
- let email = users[item].username
1144
-
1145
- post.subject = `Need Approve ${result.title}`
1146
- post.buttonTitle = `Approve Now`
1147
- post.title = `NEED APPROVE DOCUMENT`
1148
- post.link = link
1149
- post.url = CONFIG.app.url
1236
+ });
1237
+ let link = CONFIG.app.url + "/za/" + post.token;
1238
+ let email = users[item].username;
1239
+
1240
+ post.subject = `Need Approve ${result.title}`;
1241
+ post.buttonTitle = `Approve Now`;
1242
+ post.title = `NEED APPROVE DOCUMENT`;
1243
+ post.link = link;
1244
+ post.url = CONFIG.app.url;
1150
1245
  post.description = `Hai ${users[item].fullname} <br>
1151
1246
 
1152
1247
 
1153
1248
  We have some document for you.<br>
1154
- Please click the link above to view the document.`
1249
+ Please click the link above to view the document.`;
1155
1250
 
1156
- post.note = `If you click the link, it's will be automatically acknowledged`
1157
- Mail.gmail(req, res, post, email)
1251
+ post.note = `If you click the link, it's will be automatically acknowledged`;
1252
+ Mail.gmail(req, res, post, email);
1158
1253
 
1159
1254
  //send to whatsapp
1160
1255
  let sectionsAprrovers = approvers.reduce((temp, item, index) => {
1161
1256
  return [
1162
1257
  ...temp,
1163
1258
  {
1164
- title: users[item].fullname + ' ' + users[item].position,
1165
- description: '@' + users[item].fullname + ' ' + users[item].position,
1166
- rowId: 'roe' + index,
1259
+ title: users[item].fullname + " " + users[item].position,
1260
+ description:
1261
+ "@" + users[item].fullname + " " + users[item].position,
1262
+ rowId: "roe" + index,
1167
1263
  },
1168
- ]
1169
- }, [])
1264
+ ];
1265
+ }, []);
1170
1266
  let sectionsKnowings = knowings.reduce((temp, item, index) => {
1171
1267
  return [
1172
1268
  ...temp,
1173
1269
  {
1174
- title: users[item].fullname + ' ' + users[item].position,
1175
- description: '@' + users[item].fullname + ' ' + users[item].position,
1176
- rowId: 'roe' + index,
1270
+ title: users[item].fullname + " " + users[item].position,
1271
+ description:
1272
+ "@" + users[item].fullname + " " + users[item].position,
1273
+ rowId: "roe" + index,
1177
1274
  },
1178
- ]
1179
- }, [])
1180
- let sections = []
1181
- sections.push({ title: 'Approvers', rows: sectionsAprrovers })
1275
+ ];
1276
+ }, []);
1277
+ let sections = [];
1278
+ sections.push({ title: "Approvers", rows: sectionsAprrovers });
1182
1279
  if (sectionsKnowings) {
1183
- sections.push({ title: 'Knowings', rows: sectionsKnowings })
1280
+ sections.push({ title: "Knowings", rows: sectionsKnowings });
1184
1281
  }
1185
1282
  //send notification
1186
1283
  await connection.insert({
1187
- table: 'znotification',
1284
+ table: "znotification",
1188
1285
  data: {
1189
1286
  company_id: result.company_id,
1190
1287
  created_at: Util.now(),
@@ -1194,17 +1291,17 @@ router.post('/za/:token', csrfProtection, async (req, res) => {
1194
1291
  table: MYMODEL.table,
1195
1292
  id_data: data.id,
1196
1293
  status: 1,
1197
- link: '/za/' + post.token,
1198
- status_label: 'Unread',
1294
+ link: "/za/" + post.token,
1295
+ status_label: "Unread",
1199
1296
  title: `Need Approve`,
1200
1297
  description: data.title,
1201
1298
  token: post.token,
1202
1299
  },
1203
- })
1300
+ });
1204
1301
 
1205
1302
  //send todolist
1206
1303
  await connection.insert({
1207
- table: 'ztodolist',
1304
+ table: "ztodolist",
1208
1305
  data: {
1209
1306
  company_id: result.company_id,
1210
1307
  created_at: Util.now(),
@@ -1214,52 +1311,55 @@ router.post('/za/:token', csrfProtection, async (req, res) => {
1214
1311
  table: MYMODEL.table,
1215
1312
  id_data: result.ide,
1216
1313
  status: 1,
1217
- link: '/za/' + post.token,
1218
- status_label: 'Unread',
1314
+ link: "/za/" + post.token,
1315
+ status_label: "Unread",
1219
1316
  title: `Need Approve`,
1220
1317
  description: result.title,
1221
1318
  users: JSON.stringify(approvers),
1222
1319
  },
1223
- })
1320
+ });
1224
1321
 
1225
1322
  //send toastr using socket.io
1226
- io.to(users[item].token).emit('message', 'Need Approve for document : ' + result.title)
1323
+ io.to(users[item].token).emit(
1324
+ "message",
1325
+ "Need Approve for document : " + result.title
1326
+ );
1227
1327
  }
1228
1328
  }
1229
1329
  }
1230
1330
  }
1231
1331
  } catch (err) {
1232
- debug(req, res, err)
1233
- json = Util.flashError(err.toString())
1332
+ debug(req, res, err);
1333
+ json = Util.flashError(err.toString());
1234
1334
  }
1235
1335
 
1236
- res.json(json)
1237
- })
1336
+ res.json(json);
1337
+ });
1238
1338
 
1239
- router.get('/zdownload/zgenerator/:table', async (req, res) => {
1240
- var table = req.params.table
1241
- var path = `${dirRoot}/public/uploads/zgenerator/${table}.json`
1339
+ router.get("/zdownload/zgenerator/:table", async (req, res) => {
1340
+ var table = req.params.table;
1341
+ var path = `${dirRoot}/public/uploads/zgenerator/${table}.json`;
1242
1342
  res.download(path, function (err) {
1243
1343
  if (err) {
1244
1344
  //console.log(err);
1245
1345
  }
1246
- })
1247
- })
1248
-
1249
- router.post('/zlock-unlock/:table', async (req, res) => {
1250
- let json = Util.jsonSuccess('Success')
1251
- let table = req.params.table
1252
- let cacheRoles = myCache.get('ROLES')
1253
- let roleId = res.locals.roleId
1254
- let myrole = cacheRoles[roleId]
1255
- let tableRole = myrole.params[table] || []
1256
- let hasAccess = tableRole.includes('lock') ? true : false
1346
+ });
1347
+ });
1348
+
1349
+ router.post("/zlock-unlock/:table", async (req, res) => {
1350
+ let json = Util.jsonSuccess("Success");
1351
+ let table = req.params.table;
1352
+ let cacheRoles = myCache.get("ROLES");
1353
+ let roleId = res.locals.roleId;
1354
+ let myrole = cacheRoles[roleId];
1355
+ let tableRole = myrole.params[table] || [];
1356
+ let hasAccess = tableRole.includes("lock") ? true : false;
1257
1357
  if (hasAccess) {
1258
- let type = req.body.type
1259
- let datas = req.body.datas || []
1358
+ let type = req.body.type;
1359
+ let datas = req.body.datas || [];
1260
1360
  if (datas.length > 0) {
1261
1361
  for (const data of datas) {
1262
- let id = data.name.replace('ck[', '').replace(']', '')
1362
+ let id = data.name.replace("ck[", "").replace("]", "");
1263
1363
  await connection.update({
1264
1364
  table: table,
1265
1365
  data: {
@@ -1268,90 +1368,90 @@ router.post('/zlock-unlock/:table', async (req, res) => {
1268
1368
  where: {
1269
1369
  id: id,
1270
1370
  },
1271
- })
1371
+ });
1272
1372
  }
1273
1373
  } else {
1274
- json = Util.flashError('No Data')
1374
+ json = Util.flashError("No Data");
1275
1375
  }
1276
1376
  } else {
1277
- json = Util.flashError('No Access')
1377
+ json = Util.flashError("No Access");
1278
1378
  }
1279
1379
 
1280
- res.json(json)
1281
- })
1282
-
1283
- router.post('/zdeleted-selected/:table', async (req, res) => {
1284
- let json = Util.jsonSuccess('Success')
1285
- let table = req.params.table
1286
- let cacheRoles = myCache.get('ROLES')
1287
- let roleId = res.locals.roleId
1288
- let myrole = cacheRoles[roleId]
1289
- let tableRole = myrole.params[table] || []
1290
- let hasAccess = tableRole.includes('lock') ? true : false
1380
+ res.json(json);
1381
+ });
1382
+
1383
+ router.post("/zdeleted-selected/:table", async (req, res) => {
1384
+ let json = Util.jsonSuccess("Success");
1385
+ let table = req.params.table;
1386
+ let cacheRoles = myCache.get("ROLES");
1387
+ let roleId = res.locals.roleId;
1388
+ let myrole = cacheRoles[roleId];
1389
+ let tableRole = myrole.params[table] || [];
1390
+ let hasAccess = tableRole.includes("lock") ? true : false;
1291
1391
  if (hasAccess) {
1292
- let type = req.body.type
1293
- let datas = req.body.datas || []
1392
+ let type = req.body.type;
1393
+ let datas = req.body.datas || [];
1294
1394
  if (datas.length > 0) {
1295
1395
  for (const data of datas) {
1296
- let id = data.name.replace('ck[', '').replace(']', '')
1396
+ let id = data.name.replace("ck[", "").replace("]", "");
1297
1397
  try {
1298
1398
  await connection.delete({
1299
1399
  table: table,
1300
1400
  where: {
1301
1401
  id: id,
1302
1402
  },
1303
- })
1403
+ });
1304
1404
  } catch (e) {
1305
- io.emit('error', e + '')
1405
+ io.emit("error", e + "");
1306
1406
  }
1307
1407
  }
1308
1408
  } else {
1309
- json = Util.flashError('No Data')
1409
+ json = Util.flashError("No Data");
1310
1410
  }
1311
1411
  } else {
1312
- json = Util.flashError('No Access')
1412
+ json = Util.flashError("No Access");
1313
1413
  }
1314
1414
 
1315
- res.json(json)
1316
- })
1317
-
1318
- router.post('/zapproval-update/:table', async (req, res) => {
1319
- let json = Util.jsonSuccess('Success')
1320
- let table = req.params.table
1321
- let value = req.body.value
1322
- let text = req.body.text
1323
- let datas = req.body.datas || []
1324
- let roles = myCache.get('ROLES')[res.locals.roleId] || {}
1325
- let myaccess = roles.approvals[table]
1326
- let hasAccess = myaccess.hasOwnProperty(value) ? true : false
1327
- let canUpdate = true
1328
- let dataStatus = []
1329
- if (text == '') {
1330
- res.json(Util.flashError('please type a message'))
1331
- return false
1415
+ res.json(json);
1416
+ });
1417
+
1418
+ router.post("/zapproval-update/:table", async (req, res) => {
1419
+ let json = Util.jsonSuccess("Success");
1420
+ let table = req.params.table;
1421
+ let value = req.body.value;
1422
+ let text = req.body.text;
1423
+ let datas = req.body.datas || [];
1424
+ let roles = myCache.get("ROLES")[res.locals.roleId] || {};
1425
+ let myaccess = roles.approvals[table];
1426
+ let hasAccess = myaccess.hasOwnProperty(value) ? true : false;
1427
+ let canUpdate = true;
1428
+ let dataStatus = [];
1429
+ if (text == "") {
1430
+ res.json(Util.flashError("please type a message"));
1431
+ return false;
1332
1432
  }
1333
1433
  if (hasAccess) {
1334
1434
  if (datas.length > 0) {
1335
1435
  for (const data of datas) {
1336
- let id = data.name.replace('ck[', '').replace(']', '')
1436
+ let id = data.name.replace("ck[", "").replace("]", "");
1337
1437
  let result = await connection.result({
1338
- select: 'id,approval_status,approval_history',
1438
+ select: "id,approval_status,approval_history",
1339
1439
  table: table,
1340
1440
  where: {
1341
1441
  id: id,
1342
1442
  },
1343
- })
1344
- let approval_status = result.approval_status || null
1345
- let approval_history = result.approval_history || []
1443
+ });
1444
+ let approval_status = result.approval_status || null;
1445
+ let approval_history = result.approval_history || [];
1346
1446
  if (approval_status == null) {
1347
- canUpdate = true
1447
+ canUpdate = true;
1348
1448
  } else if (approval_status == 22) {
1349
- canUpdate = true
1449
+ canUpdate = true;
1350
1450
  } else {
1351
1451
  if (+value > +approval_status) {
1352
- canUpdate = true
1452
+ canUpdate = true;
1353
1453
  } else {
1354
- canUpdate = false
1454
+ canUpdate = false;
1355
1455
  }
1356
1456
  }
1357
1457
  if (canUpdate) {
@@ -1360,16 +1460,16 @@ router.post('/zapproval-update/:table', async (req, res) => {
1360
1460
  user_id: res.locals.userId,
1361
1461
  created_at: Util.now(),
1362
1462
  text: text,
1363
- })
1463
+ });
1364
1464
  let mydata = {
1365
1465
  approval_status: value,
1366
1466
  approval_history: Util.array_to_jsonb(approval_history),
1367
- }
1467
+ };
1368
1468
  if (+value > 1 && +value < 22) {
1369
- mydata.lock = 1
1469
+ mydata.lock = 1;
1370
1470
  }
1371
1471
  if (+value === 22) {
1372
- mydata.lock = 0
1472
+ mydata.lock = 0;
1373
1473
  }
1374
1474
  await connection.update({
1375
1475
  table: table,
@@ -1377,261 +1477,319 @@ router.post('/zapproval-update/:table', async (req, res) => {
1377
1477
  id: id,
1378
1478
  },
1379
1479
  data: mydata,
1380
- })
1480
+ });
1381
1481
  } else {
1382
- dataStatus.push(`${id} -> Status has been delivered`)
1482
+ dataStatus.push(`${id} -> Status has been delivered`);
1383
1483
  }
1384
1484
  }
1385
1485
  } else {
1386
- json = Util.flashError('No Data')
1486
+ json = Util.flashError("No Data");
1387
1487
  }
1388
1488
  } else {
1389
- json = Util.flashError('No Access')
1489
+ json = Util.flashError("No Access");
1390
1490
  }
1391
- json.dataStatus = dataStatus
1392
- res.json(json)
1393
- })
1491
+ json.dataStatus = dataStatus;
1492
+ res.json(json);
1493
+ });
1394
1494
 
1395
- router.get('/addlock-fields', async (req, res) => {
1396
- let tables = await connection.query(connection.showTables)
1495
+ router.get("/addlock-fields", async (req, res) => {
1496
+ let tables = await connection.query(connection.showTables);
1397
1497
  for (const table of tables) {
1398
- let tablename = table.tablename
1399
- let sql = `ALTER TABLE ${tablename} ADD COLUMN "lock" smallint DEFAULT 0 `
1498
+ let tablename = table.tablename;
1499
+ let sql = `ALTER TABLE ${tablename} ADD COLUMN "lock" smallint DEFAULT 0 `;
1400
1500
  try {
1401
- await connection.query(sql)
1501
+ await connection.query(sql);
1402
1502
  } catch (e) {
1403
- console.log(e)
1503
+ console.log(e);
1404
1504
  }
1405
1505
  }
1406
- res.send(tables)
1407
- })
1506
+ res.send(tables);
1507
+ });
1408
1508
 
1409
- router.get('/addlock-models', async (req, res) => {
1410
- let text = ''
1509
+ router.get("/addlock-models", async (req, res) => {
1510
+ let text = "";
1411
1511
  let results = await connection.results({
1412
- table: 'zfields',
1413
- })
1512
+ table: "zfields",
1513
+ });
1414
1514
  for (const result of results) {
1415
- let labels = result.labels
1416
- let arr = Object.keys(labels)
1417
- if (!Util.in_array('lock', arr)) {
1418
- text += result.id + ' tidak ada'
1419
- labels.lock = 'Lock/Unlock'
1515
+ let labels = result.labels;
1516
+ let arr = Object.keys(labels);
1517
+ if (!Util.in_array("lock", arr)) {
1518
+ text += result.id + " tidak ada";
1519
+ labels.lock = "Lock/Unlock";
1420
1520
  try {
1421
1521
  await connection.update({
1422
- table: 'zfields',
1522
+ table: "zfields",
1423
1523
  data: {
1424
1524
  labels: JSON.stringify(labels),
1425
1525
  },
1426
1526
  where: {
1427
1527
  id: result.id,
1428
1528
  },
1429
- })
1529
+ });
1430
1530
  } catch (err) {
1431
- console.log(err)
1531
+ console.log(err);
1432
1532
  }
1433
1533
  }
1434
1534
  }
1435
1535
 
1436
- res.send(text)
1437
- })
1536
+ res.send(text);
1537
+ });
1438
1538
 
1439
- router.get('/addapprovals-data', async (req, res) => {
1440
- let tables = await connection.query(connection.showTables)
1539
+ router.get("/addapprovals-data", async (req, res) => {
1540
+ let tables = await connection.query(connection.showTables);
1441
1541
  for (const table of tables) {
1442
- let tablename = table.tablename
1443
- let sql = `ALTER TABLE ${tablename} ADD COLUMN "approval_status" smallint DEFAULT NULL`
1444
- let sql2 = `ALTER TABLE ${tablename} ADD COLUMN "approval_history" jsonb[] DEFAULT NULL `
1542
+ let tablename = table.tablename;
1543
+ let sql = `ALTER TABLE ${tablename} ADD COLUMN "approval_status" smallint DEFAULT NULL`;
1544
+ let sql2 = `ALTER TABLE ${tablename} ADD COLUMN "approval_history" jsonb[] DEFAULT NULL `;
1445
1545
  try {
1446
- await connection.query(sql)
1546
+ await connection.query(sql);
1447
1547
  } catch (e) {
1448
- console.log(e)
1548
+ console.log(e);
1449
1549
  }
1450
1550
  try {
1451
- await connection.query(sql2)
1551
+ await connection.query(sql2);
1452
1552
  } catch (e) {
1453
- console.log(e)
1553
+ console.log(e);
1454
1554
  }
1455
1555
  }
1456
- res.send(tables)
1457
- })
1556
+ res.send(tables);
1557
+ });
1458
1558
 
1459
- router.get('/addapproval-models', async (req, res) => {
1460
- let text = ''
1559
+ router.get("/addapproval-models", async (req, res) => {
1560
+ let text = "";
1461
1561
  let results = await connection.results({
1462
- table: 'zfields',
1463
- })
1562
+ table: "zfields",
1563
+ });
1464
1564
  for (const result of results) {
1465
- let labels = result.labels
1466
- let arr = Object.keys(labels)
1467
- if (!Util.in_array('approval_status', arr)) {
1468
- text += result.id + ' tidak ada'
1565
+ let labels = result.labels;
1566
+ let arr = Object.keys(labels);
1567
+ if (!Util.in_array("approval_status", arr)) {
1568
+ text += result.id + " tidak ada";
1469
1569
  //approval_status_id : "Approval Status",
1470
- labels.approval_status = 'Approval Status'
1471
- labels.approval_history = 'Approval History'
1570
+ labels.approval_status = "Approval Status";
1571
+ labels.approval_history = "Approval History";
1472
1572
  try {
1473
1573
  await connection.update({
1474
- table: 'zfields',
1574
+ table: "zfields",
1475
1575
  data: {
1476
1576
  labels: JSON.stringify(labels),
1477
1577
  },
1478
1578
  where: {
1479
1579
  id: result.id,
1480
1580
  },
1481
- })
1581
+ });
1482
1582
  } catch (err) {
1483
- console.log(err)
1583
+ console.log(err);
1484
1584
  }
1485
1585
  }
1486
1586
  }
1487
1587
 
1488
- res.send(text)
1489
- })
1588
+ res.send(text);
1589
+ });
1490
1590
 
1491
1591
  //post dropzone widget
1492
- router.post('/zdropzone', async (req, res) => {
1592
+ router.post("/zdropzone", async (req, res) => {
1493
1593
  try {
1494
- let userId = res.locals.userId
1594
+ let userId = res.locals.userId;
1495
1595
  if (userId) {
1496
- let dir = `${dirRoot}/public/zdropzone/${userId}`
1596
+ let dir = `${dirRoot}/public/zdropzone/${userId}`;
1497
1597
  if (!fs.existsSync(dir)) {
1498
- fs.mkdirSync(dir, { recursive: true })
1598
+ fs.mkdirSync(dir, { recursive: true });
1499
1599
  }
1500
- let filename = req.files.file.name
1501
- req.files.file.mv(dir + '/' + filename, function (err) {
1600
+ let filename = req.files.file.name;
1601
+ req.files.file.mv(dir + "/" + filename, function (err) {
1502
1602
  if (err) {
1503
- return res.status(500).send(err + '')
1603
+ return res.status(500).send(err + "");
1504
1604
  }
1505
- })
1605
+ });
1506
1606
  }
1507
- res.json('ok')
1607
+ res.json("ok");
1508
1608
  } catch (e) {
1509
- console.log(e)
1510
- res.status(500)
1511
- res.send(e + '')
1609
+ console.log(e);
1610
+ res.status(500);
1611
+ res.send(e + "");
1512
1612
  }
1513
- })
1613
+ });
1514
1614
 
1515
- router.post('/zdropzone-remove', async (req, res) => {
1615
+ router.post("/zdropzone-remove", async (req, res) => {
1516
1616
  try {
1517
- let userId = res.locals.userId
1518
- let cacheName = req.body.cname.replace('ZUSER___ID', userId)
1519
- let dir = `${dirRoot}/public/zdropzone/${userId}`
1617
+ let userId = res.locals.userId;
1618
+ let cacheName = req.body.cname.replace("ZUSER___ID", userId);
1619
+ let dir = `${dirRoot}/public/zdropzone/${userId}`;
1520
1620
  if (!fs.existsSync(dir)) {
1521
- fs.mkdirSync(dir, { recursive: true })
1621
+ fs.mkdirSync(dir, { recursive: true });
1522
1622
  }
1523
- let filename = `${dirRoot}/public/zdropzone/${userId}/${req.body.file}`
1623
+ let filename = `${dirRoot}/public/zdropzone/${userId}/${req.body.file}`;
1524
1624
  if (Util.fileExist(filename)) {
1525
- await fs.unlink(filename)
1625
+ await fs.unlink(filename);
1526
1626
  if (myCache.has(cacheName)) {
1527
- arr = myCache.get(name)
1627
+ arr = myCache.get(name);
1528
1628
  }
1529
- arr = Util.arrayDelete(arr, body.file)
1530
- myCache.set(name, arr)
1629
+ arr = Util.arrayDelete(arr, body.file);
1630
+ myCache.set(name, arr);
1531
1631
  }
1532
- res.json('ok')
1632
+ res.json("ok");
1533
1633
  } catch (e) {
1534
- console.log(e)
1535
- res.status(500).send(e + '')
1634
+ console.log(e);
1635
+ res.status(500).send(e + "");
1536
1636
  }
1537
- })
1538
- router.post('/zdropzone-attributes', async (req, res) => {
1637
+ });
1638
+ router.post("/zdropzone-attributes", async (req, res) => {
1539
1639
  try {
1540
- let userId = res.locals.userId
1541
- let dir = `${dirRoot}/public/zdropzone/${userId}`
1640
+ let userId = res.locals.userId;
1641
+ let dir = `${dirRoot}/public/zdropzone/${userId}`;
1542
1642
  if (!fs.existsSync(dir)) {
1543
- fs.mkdirSync(dir, { recursive: true })
1643
+ fs.mkdirSync(dir, { recursive: true });
1544
1644
  }
1545
- let body = req.body
1546
- let category = body.category
1547
- let name = `dropzone__${userId}__${body.table}__${body.field}__${body.type}`
1645
+ let body = req.body;
1646
+ let category = body.category;
1647
+ let name = `dropzone__${userId}__${body.table}__${body.field}__${body.type}`;
1548
1648
  //dropzone__${res.locals.userId}__${table}__${key}__create
1549
- let arr = []
1550
- if (category === 'add') {
1649
+ let arr = [];
1650
+ if (category === "add") {
1551
1651
  if (myCache.has(name)) {
1552
- arr = myCache.get(name)
1652
+ arr = myCache.get(name);
1553
1653
  }
1554
- arr.push(body.file)
1654
+ arr.push(body.file);
1555
1655
  } else {
1556
- name = `dropzone__${userId}__${body.table}__${body.field}__${body.type}`
1656
+ name = `dropzone__${userId}__${body.table}__${body.field}__${body.type}`;
1557
1657
  if (myCache.has(name)) {
1558
- arr = myCache.get(name)
1658
+ arr = myCache.get(name);
1559
1659
  }
1560
- arr = Util.arrayDelete(arr, body.file)
1660
+ arr = Util.arrayDelete(arr, body.file);
1561
1661
  }
1562
- myCache.set(name, arr)
1563
- res.json('ok')
1662
+ myCache.set(name, arr);
1663
+ res.json("ok");
1564
1664
  } catch (e) {
1565
- console.log(e)
1566
- res.status(500).send(e + '')
1665
+ console.log(e);
1666
+ res.status(500).send(e + "");
1567
1667
  }
1568
- })
1668
+ });
1569
1669
 
1570
- router.post('/zhistory-data', async (req, res) => {
1571
- let html = ''
1670
+ router.post("/zhistory-data", async (req, res) => {
1671
+ let html = "";
1572
1672
  try {
1573
- let id = req.body.id
1574
- let table = req.body.table
1575
- const relations = await zRoute.relations(req, res, table)
1576
- const MYMODELS = zRoute.MYMODELS()
1577
- const MYMODEL = MYMODELS[table]
1673
+ let id = req.body.id;
1674
+ let table = req.body.table;
1675
+ const relations = await zRoute.relations(req, res, table);
1676
+ const MYMODELS = zRoute.MYMODELS();
1677
+ const MYMODEL = MYMODELS[table];
1578
1678
  let results = await connection.results({
1579
- table: 'zhistory',
1679
+ table: "zhistory",
1580
1680
  where: {
1581
1681
  module: table,
1582
1682
  module_id: id,
1583
1683
  },
1584
- order_by: ['id asc'],
1585
- })
1684
+ order_by: ["id asc"],
1685
+ });
1586
1686
  if (results.length > 0) {
1587
- let users = {}
1588
- if (myCache.has('users')) {
1589
- users = myCache.get('users')
1687
+ let users = {};
1688
+ if (myCache.has("users")) {
1689
+ users = myCache.get("users");
1590
1690
  } else {
1591
1691
  users = Util.arrayToObject(
1592
1692
  await connection.results({
1593
- table: 'zuser',
1693
+ table: "zuser",
1594
1694
  }),
1595
- 'id'
1596
- )
1597
- myCache.set('users', users)
1695
+ "id"
1696
+ );
1697
+ myCache.set("users", users);
1598
1698
  }
1599
- html = await zRoute.history(req, res, relations, id, MYMODEL, users, results)
1699
+ html = await zRoute.history(
1700
+ req,
1701
+ res,
1702
+ relations,
1703
+ id,
1704
+ MYMODEL,
1705
+ users,
1706
+ results
1707
+ );
1600
1708
  }
1601
- res.json(html)
1709
+ res.json(html);
1602
1710
  } catch (e) {
1603
- console.log(e)
1604
- res.json(e + '')
1711
+ console.log(e);
1712
+ res.json(e + "");
1605
1713
  }
1606
- })
1714
+ });
1607
1715
 
1608
- router.get('/zdownloads-dropzone/:table/:field/:id', async (req, res) => {
1716
+ router.get("/zdownloads-dropzone/:table/:field/:id", async (req, res) => {
1609
1717
  try {
1610
- let table = req.params.table
1611
- let field = req.params.field
1612
- let id = req.params.id
1613
- const room = res.locals.token
1718
+ let table = req.params.table;
1719
+ let field = req.params.field;
1720
+ let id = req.params.id;
1721
+ const room = res.locals.token;
1614
1722
  let result = await connection.result({
1615
1723
  table: table,
1616
1724
  where: {
1617
1725
  id: id,
1618
1726
  },
1619
- })
1620
- let dir = `${dirRoot}/public/uploads/${table}/${field}/`
1621
- let arr = []
1622
- let files = result[field]
1727
+ });
1728
+ let dir = `${dirRoot}/public/uploads/${table}/${field}/`;
1729
+ let arr = [];
1730
+ let files = result[field];
1623
1731
  for (const file of files) {
1624
1732
  if (Util.fileExist(dir + file)) {
1625
- let filename = file.substring(13)
1626
- arr.push({ path: dir + file, name: filename })
1627
- io.to(room).emit('info', `Zip file ${filename}`)
1733
+ let filename = file.substring(13);
1734
+ arr.push({ path: dir + file, name: filename });
1735
+ //io.to(room).emit('message', `Zip file ${filename}`)
1628
1736
  }
1629
1737
  }
1630
- io.to(room).emit('info', `Zip file completed...`)
1631
- res.zip(arr, `${field}_${table}_${id}.zip`)
1738
+ io.to(room).emit("message", `Zip files complete...`);
1739
+ res.zip(arr, `${field}_${table}_${id}.zip`);
1632
1740
  } catch (e) {
1633
- console.log(e)
1634
- res.json(e + '')
1741
+ console.log(e);
1742
+ res.json(e + "");
1635
1743
  }
1636
- })
1637
- module.exports = router
1744
+ });
1745
+
1746
+ //compress image di dropzone
1747
+ router.post("/zcompress-dropzone", async (req, res) => {
1748
+ try {
1749
+ let table = req.body.table;
1750
+ let field = req.body.field;
1751
+ let id = req.body.id;
1752
+ const room = res.locals.token;
1753
+ let result = await connection.result({
1754
+ table: table,
1755
+ where: {
1756
+ id: id,
1757
+ },
1758
+ });
1759
+ if (result.lock == 1) {
1760
+ let message = `Data has been locked, please unlock first to compress images `;
1761
+ io.to(room).emit("errormessage", message);
1762
+ res.json(Util.flashError(message));
1763
+ } else {
1764
+ const config = {
1765
+ jpeg: { quality: 80 },
1766
+ webp: { quality: 80 },
1767
+ png: { compressionLevel: 8 },
1768
+ };
1769
+ let dir = `${dirRoot}/public/uploads/${table}/${field}/`;
1770
+ let arr = [];
1771
+ let files = result[field];
1772
+ for (const file of files) {
1773
+ if (Util.fileExist(dir + file)) {
1774
+ let filename = file.substring(13);
1775
+ //arr.push({ path: dir + file, name: filename })
1776
+ let attributes = Util.fileAttribute(dir + file);
1777
+ if (attributes.type == "image") {
1778
+ const image = sharp(dir + file);
1779
+ const meta = await image.metadata();
1780
+ const { format } = meta;
1781
+ await image[format](config[format]);
1782
+ io.to(room).emit("message", `Compress file ${filename} Success...`);
1783
+ }
1784
+ }
1785
+ }
1786
+ io.to(room).emit("message", `Compress images completed...`);
1787
+ res.json(Util.jsonSuccess("Compress images completed..."));
1788
+ }
1789
+ } catch (e) {
1790
+ console.log(e);
1791
+ res.json(e + "");
1792
+ }
1793
+ });
1794
+
1795
+ module.exports = router;