zet-lib 1.4.5 → 1.4.7

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