@pxp-nd/core 1.2.72 → 1.2.75

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 (67) hide show
  1. package/README.md +1 -1
  2. package/dist/PxpApp.d.ts +54 -54
  3. package/dist/PxpApp.js +283 -305
  4. package/dist/ScriptManager.d.ts +1 -1
  5. package/dist/ScriptManager.js +130 -130
  6. package/dist/database/script.d.ts +16 -16
  7. package/dist/database/script.js +143 -143
  8. package/dist/db.datasource.d.ts +2 -2
  9. package/dist/db.datasource.js +86 -86
  10. package/dist/entities/Log.d.ts +32 -32
  11. package/dist/entities/Log.js +95 -95
  12. package/dist/entities/ScriptVersion.d.ts +19 -19
  13. package/dist/entities/ScriptVersion.js +43 -43
  14. package/dist/index.d.ts +11 -11
  15. package/dist/index.js +28 -28
  16. package/dist/interfaces.d.ts +49 -49
  17. package/dist/interfaces.js +3 -3
  18. package/dist/lib/pxp/Controller.d.ts +51 -51
  19. package/dist/lib/pxp/Controller.js +377 -377
  20. package/dist/lib/pxp/ControllerInterface.d.ts +18 -18
  21. package/dist/lib/pxp/ControllerInterface.js +2 -2
  22. package/dist/lib/pxp/Decorators.d.ts +23 -23
  23. package/dist/lib/pxp/Decorators.js +123 -123
  24. package/dist/lib/pxp/ListParamInterface.d.ts +23 -23
  25. package/dist/lib/pxp/ListParamInterface.js +2 -2
  26. package/dist/lib/pxp/PxpError.d.ts +24 -24
  27. package/dist/lib/pxp/PxpError.js +57 -57
  28. package/dist/lib/pxp/RouteDefinition.d.ts +26 -26
  29. package/dist/lib/pxp/RouteDefinition.js +26 -26
  30. package/dist/lib/pxp/index.d.ts +20 -20
  31. package/dist/lib/pxp/index.js +33 -33
  32. package/dist/lib/pxp/loadControllers.d.ts +4 -4
  33. package/dist/lib/pxp/loadControllers.js +89 -89
  34. package/dist/lib/pxp/middlewares/ParseParams.d.ts +4 -4
  35. package/dist/lib/pxp/middlewares/ParseParams.js +71 -71
  36. package/dist/lib/pxp/middlewares/isReportMiddleware.d.ts +2 -2
  37. package/dist/lib/pxp/middlewares/isReportMiddleware.js +13 -13
  38. package/dist/lib/pxp/utils/Security.d.ts +23 -23
  39. package/dist/lib/pxp/utils/Security.js +79 -77
  40. package/dist/lib/pxp/utils/crypto.d.ts +3 -3
  41. package/dist/lib/pxp/utils/crypto.js +15 -15
  42. package/dist/lib/reports/fonts/Roboto-Regular-normal.d.ts +2 -2
  43. package/dist/lib/reports/fonts/Roboto-Regular-normal.js +4 -4
  44. package/dist/lib/reports/generated.d.ts +4 -4
  45. package/dist/lib/reports/generated.js +200 -200
  46. package/dist/lib/reports/helper.d.ts +8 -8
  47. package/dist/lib/reports/helper.js +49 -49
  48. package/dist/lib/reports/pdf.d.ts +3 -3
  49. package/dist/lib/reports/pdf.js +119 -119
  50. package/dist/lib/reports/report-routes.d.ts +3 -3
  51. package/dist/lib/reports/report-routes.js +24 -24
  52. package/dist/lib/reports/xlsx.d.ts +1 -1
  53. package/dist/lib/reports/xlsx.js +65 -65
  54. package/dist/sockets/basic-sockets.d.ts +5 -5
  55. package/dist/sockets/basic-sockets.js +38 -38
  56. package/dist/sockets/entities/UserIo.d.ts +6 -6
  57. package/dist/sockets/entities/UserIo.js +30 -30
  58. package/dist/sockets/entities/index.d.ts +5 -5
  59. package/dist/sockets/entities/index.js +9 -9
  60. package/dist/sockets/index.d.ts +2 -2
  61. package/dist/sockets/index.js +19 -19
  62. package/dist/sockets/pxp-io-server.d.ts +6 -6
  63. package/dist/sockets/pxp-io-server.js +50 -50
  64. package/dist/swaggerOptions.d.ts +16 -16
  65. package/dist/swaggerOptions.js +20 -20
  66. package/package.json +65 -65
  67. package/yalc.lock +9 -9
@@ -1,377 +1,377 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
- Object.defineProperty(o, "default", { enumerable: true, value: v });
11
- }) : function(o, v) {
12
- o["default"] = v;
13
- });
14
- var __importStar = (this && this.__importStar) || function (mod) {
15
- if (mod && mod.__esModule) return mod;
16
- var result = {};
17
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
- __setModuleDefault(result, mod);
19
- return result;
20
- };
21
- var __importDefault = (this && this.__importDefault) || function (mod) {
22
- return (mod && mod.__esModule) ? mod : { "default": mod };
23
- };
24
- Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.Controller = void 0;
26
- /**
27
- * Kplian Ltda 2020
28
- *
29
- * MIT
30
- *
31
- * Controller Class.
32
- *
33
- * @summary All common controllers functionality go here (all controllers should inherit this class).
34
- * @author Jaime Rivera
35
- *
36
- * Created at : 2020-06-13 18:09:48
37
- * Last modified : 2020-10-13 15:36:31
38
- * Last modified : 2021-03-10 15:36:31 - Favio Figueroa
39
- * Last modified : 2021-05-01 18:35:31 - Favio Figueroa
40
- */
41
- const typeorm_1 = require("typeorm");
42
- const class_validator_1 = require("class-validator");
43
- const lodash_1 = __importDefault(require("lodash"));
44
- const express_1 = require("express");
45
- const joi_1 = __importDefault(require("joi"));
46
- const RouteDefinition_1 = require("./RouteDefinition");
47
- const index_1 = require("./index");
48
- // import { User } from '@pxp-nd/entities';
49
- // import { isAuthenticated } from '@pxp-nd/auth';
50
- const ParseParams_1 = require("./middlewares/ParseParams");
51
- const isReportMiddleware_1 = require("./middlewares/isReportMiddleware");
52
- const pdf_1 = require("../reports/pdf");
53
- const xlsx_1 = require("../reports/xlsx");
54
- // import * as entities from '@pxp-nd/entities';
55
- // const pxpEntities: any = entities;
56
- class Controller {
57
- constructor(module, Entity = null, config = {
58
- apiPrefix: '/api',
59
- defaultDbSettings: 'Orm',
60
- middlewares: [],
61
- entities: {},
62
- }, io = null) {
63
- this.router = express_1.Router();
64
- this.path = '';
65
- this.module = '';
66
- this.modelString = '';
67
- this.transactionCode = '';
68
- this.user = {}; //User;
69
- this.basicRoutes = [
70
- { requestMethod: RouteDefinition_1.Method.post, path: '/add', methodName: 'add' },
71
- { requestMethod: RouteDefinition_1.Method.delete, path: '/delete/:id', methodName: 'delete' },
72
- { requestMethod: RouteDefinition_1.Method.patch, path: '/edit/:id', methodName: 'edit' },
73
- { requestMethod: RouteDefinition_1.Method.get, path: '/list', methodName: 'list' }
74
- ];
75
- this.basicReadOnly = {
76
- add: false,
77
- edit: false,
78
- list: true,
79
- delete: false
80
- };
81
- this.validated = false;
82
- this.module = module;
83
- this.config = config;
84
- this.io = io;
85
- if (Reflect.hasMetadata('model', this.constructor)) {
86
- this.modelString = Reflect.getMetadata('model', this.constructor);
87
- const [moduleName, entityName] = this.modelString.split('/');
88
- const mainDir = process.cwd();
89
- try {
90
- if (Entity) {
91
- this.model = Entity;
92
- }
93
- else if (config.modules && config.modules[this.module]) {
94
- const moduleExternal = config.modules[this.module];
95
- this.model = moduleExternal.entities[entityName];
96
- }
97
- else {
98
- Promise.resolve().then(() => __importStar(require(`${mainDir}/dist/modules/${moduleName}/entity/${entityName}`))).then((model) => {
99
- this.model = model.default;
100
- });
101
- }
102
- }
103
- catch (_a) {
104
- throw new index_1.PxpError(500, 'Model defined in ' + this.constructor.name + ' not found.');
105
- }
106
- }
107
- this.initializeRoutes();
108
- }
109
- initializeRoutes() {
110
- let routes = Reflect.getMetadata('routes', this.constructor);
111
- this.path = '/' + this.constructor.name;
112
- // get controller path
113
- if (Reflect.hasMetadata('controller_path', this.constructor)) {
114
- this.path = Reflect.getMetadata('controller_path', this.constructor);
115
- }
116
- // get read only
117
- let readonly = Reflect.getMetadata('readonly', this.constructor) || {};
118
- // get authentication
119
- const authentication = Reflect.getMetadata('authentication', this.constructor) || {};
120
- // get permission
121
- const permission = Reflect.getMetadata('permission', this.constructor) || {};
122
- // get log
123
- const log = Reflect.getMetadata('log', this.constructor) || {};
124
- // get dbsettings
125
- const dbsettings = Reflect.getMetadata('dbsettings', this.constructor) || {};
126
- // get logConfig
127
- const logConfig = Reflect.getMetadata('logConfig', this.constructor) || {};
128
- const defaultConfig = Reflect.getMetadata('optionsRoute', this.constructor) || {};
129
- // define basic routes
130
- if (this.modelString !== '') {
131
- routes = lodash_1.default.union(this.basicRoutes, routes);
132
- readonly = Object.assign(Object.assign({}, this.basicReadOnly), readonly);
133
- }
134
- routes.forEach((route) => {
135
- const methodDbSettings = dbsettings[route.methodName] || this.config.defaultDbSettings;
136
- // readOnly
137
- const readOnlyMethod = readonly[route.methodName] !== undefined ? readonly[route.methodName] : defaultConfig[route.methodName].readOnly;
138
- // log
139
- const logMethod = log[route.methodName] !== undefined ? log[route.methodName] : (defaultConfig[route.methodName] ? defaultConfig[route.methodName].log : true);
140
- const logValue = typeof logMethod == 'object' ? logMethod : logConfig[route.methodName];
141
- const logKey = typeof logMethod == 'object' ? true : logMethod;
142
- if (readOnlyMethod === null || readOnlyMethod === undefined) {
143
- throw new index_1.PxpError(500, 'ReadOnly decorator was not defined for ' +
144
- route.methodName +
145
- ' in ' +
146
- this.constructor.name +
147
- ' controller.');
148
- }
149
- // auth
150
- const auth = authentication[route.methodName] !== undefined ? authentication[route.methodName] : (defaultConfig[route.methodName] ? defaultConfig[route.methodName].authentication : true);
151
- if (!auth) {
152
- this.router[route.requestMethod](this.config.apiPrefix + '/' + this.module + this.path + route.path,
153
- // MIDDLEWARES AREA
154
- [
155
- ParseParams_1.parseParams
156
- ], async (req, res, next) => {
157
- // Execute our method for this path and pass our express request and response object.
158
- // const params = { ...req.query, ...req.body, ...req.params };
159
- const params = Object.assign(Object.assign({}, req.files), req.paramasMerge);
160
- this.pxpParams = req.pxpParams;
161
- this.transactionCode = (this.module + this.path + route.path)
162
- .split('/')
163
- .join('.')
164
- .toLowerCase();
165
- this.validated = false;
166
- try {
167
- await index_1.__(this.genericMethodWrapper(params, req, next, res, route.methodName, methodDbSettings, readOnlyMethod, false, logKey, logValue));
168
- }
169
- catch (ex) {
170
- const now = new Date();
171
- const iniAt = req.start;
172
- const endsAt = now.valueOf() - iniAt.valueOf();
173
- res.logId = await index_1.__(index_1.insertLog('nouser', 'mac', req.ip, 'error', ex.tecMessage, this.module, this.transactionCode, '', // query
174
- params, ex.stack, ex.statusCode, endsAt, logValue));
175
- index_1.errorMiddleware(ex, req, res);
176
- }
177
- });
178
- }
179
- else {
180
- //NORMALMENTE VIENE POR AQUI RCM-20211011 *****
181
- this.router[route.requestMethod](this.config.apiPrefix + '/' + this.module + this.path + route.path,
182
- // MIDDLEWARES AREA
183
- [
184
- ...this.config.middlewares,
185
- isReportMiddleware_1.isReportMiddleware,
186
- ParseParams_1.parseParams
187
- ], async (req, res, next) => {
188
- // Execute our method for this path and pass our express request and response object.
189
- const params = Object.assign(Object.assign({}, req.files), req.paramasMerge);
190
- this.pxpParams = req.pxpParams;
191
- if (req.user) {
192
- // this.user = req.user as User;
193
- this.user = req.user;
194
- }
195
- this.transactionCode = (this.module + this.path + route.path)
196
- .split('/')
197
- .join('.')
198
- .toLowerCase();
199
- this.validated = false;
200
- try {
201
- await index_1.__(this.genericMethodWrapper(params, req, next, res, route.methodName, methodDbSettings, readOnlyMethod, permission[route.methodName], logKey, logValue));
202
- }
203
- catch (ex) {
204
- const now = new Date();
205
- const iniAt = req.start;
206
- const endsAt = now.valueOf() - iniAt.valueOf();
207
- res.logId = (await index_1.__(index_1.insertLog(this.user && this.user.username ? this.user.username : 'nouser', 'mac', req.ip, 'error', ex.tecMessage, this.module, this.transactionCode, '', // query
208
- params, ex.stack, ex.statusCode, endsAt, logValue)));
209
- index_1.errorMiddleware(ex, req, res);
210
- }
211
- });
212
- }
213
- });
214
- }
215
- async genericMethodWrapper(params, req, next, res, methodName, dbsettings, readonly, permission = true, log = true, logConfig = {}) {
216
- if (dbsettings === 'Orm') {
217
- await index_1.__(this.ormMethodWrapper(params, req, next, res, methodName, readonly, permission, log, logConfig));
218
- }
219
- else if (dbsettings === 'Procedure') {
220
- await index_1.__(this.procedureMethodWrapper(params, next, res, methodName, readonly, permission, log, logConfig));
221
- }
222
- else {
223
- await this.sqlMethodWrapper(params, next, res, methodName, readonly, permission, log, logConfig);
224
- }
225
- }
226
- async ormMethodWrapper(params, req, next, res, methodName, readonly, permission = true, log = true, logConfig = {}) {
227
- let metResponse;
228
- if (permission) {
229
- if (this.user && this.user.roles && this.user.roles.length === 0) {
230
- const hasPermission = await index_1.__(index_1.userHasPermission(this.config.entities.Role)(this.user.userId, this.transactionCode));
231
- if (!hasPermission) {
232
- throw new index_1.PxpError(403, 'Access denied to execute this method');
233
- }
234
- }
235
- }
236
- if (readonly) {
237
- metResponse = await index_1.__(eval(`this.${methodName}(params, res)`));
238
- }
239
- else {
240
- const connection = typeorm_1.getConnection(process.env.DB_WRITE_CONNECTION_NAME);
241
- const queryRunner = connection.createQueryRunner();
242
- // establish real database connection using our new query runner
243
- await index_1.__(queryRunner.connect());
244
- await index_1.__(queryRunner.startTransaction());
245
- try {
246
- metResponse = (await eval(`this.${methodName}(params, queryRunner.manager, res)`));
247
- await queryRunner.commitTransaction();
248
- }
249
- catch (err) {
250
- await queryRunner.rollbackTransaction();
251
- throw err;
252
- }
253
- finally {
254
- await index_1.__(queryRunner.release());
255
- }
256
- }
257
- if (log) {
258
- const now = new Date();
259
- const iniAt = req.start;
260
- const endsAt = now.valueOf() - iniAt.valueOf();
261
- index_1.__(index_1.insertLog(this.user && this.user.username ? this.user.username : 'nouser', 'mac', req.ip, 'success', 'successful transaction', this.module, this.transactionCode, '', params, JSON.stringify(metResponse), '200', endsAt, logConfig));
262
- }
263
- //PARA REPORTES
264
- if (req.report && req.report.type === 'pdf') {
265
- req.reportData = metResponse;
266
- pdf_1.makePdf(req, res);
267
- }
268
- else if (req.report && req.report.type === 'xlsx') {
269
- req.reportData = metResponse;
270
- xlsx_1.makeXlsx(req, res);
271
- }
272
- else {
273
- res.json(metResponse);
274
- }
275
- }
276
- async list(params) {
277
- const connection = typeorm_1.getConnection(process.env.DB_WRITE_CONNECTION_NAME);
278
- const queryRunner = connection.getMetadata(this.model).ownColumns.find(column => column.isPrimary === true);
279
- // ffp search if in the params has been sent the primary key
280
- const primaryKeyColumn = queryRunner.propertyName;
281
- if (primaryKeyColumn in params) {
282
- const findOne = await index_1.__(this.model.findOne({ where: { [primaryKeyColumn]: params[primaryKeyColumn] } }));
283
- return { data: findOne, count: 1 };
284
- }
285
- // filter by some column that exist in the entity
286
- // ffp if some column is into of params for added in the condition
287
- let ownColumnsForSchema = {};
288
- const whereOwnColumns = connection.getMetadata(this.model).ownColumns.reduce((t, column) => {
289
- if (`_${column.propertyName}` in params) {
290
- ownColumnsForSchema = Object.assign(Object.assign({}, ownColumnsForSchema), { [`_${column.propertyName}`]: joi_1.default.string() });
291
- t = Object.assign(Object.assign({}, t), { [column.propertyName]: params[`_${column.propertyName}`] });
292
- }
293
- return t;
294
- }, {});
295
- const schema = this.getListSchema(ownColumnsForSchema);
296
- const resParams = await index_1.__(this.schemaValidate(schema, params));
297
- const listParam = this.getListParams(resParams, whereOwnColumns);
298
- const [rows, count] = await index_1.__(this.model.findAndCount(listParam));
299
- return { data: rows, count };
300
- }
301
- async add(params, manager) {
302
- const modelInstance = new this.model();
303
- Object.assign(modelInstance, params);
304
- modelInstance.createdBy = this.user ? this.user.username : '_';
305
- await index_1.__(this.classValidate(modelInstance));
306
- await manager.save(modelInstance);
307
- return modelInstance;
308
- }
309
- async edit(params, manager) {
310
- const modelInstance = (await index_1.__(this.model.findOne(params.id)));
311
- if (!modelInstance) {
312
- throw new index_1.PxpError(406, 'Record not found');
313
- }
314
- const editParams = params;
315
- Object.assign(modelInstance, editParams);
316
- delete editParams.id;
317
- modelInstance.modifiedBy = this.user ? this.user.username : null;
318
- await index_1.__(this.classValidate(modelInstance));
319
- await manager.save(modelInstance);
320
- return modelInstance;
321
- }
322
- async delete(params, manager) {
323
- const modelInstance = (await index_1.__(this.model.findOne(params.id)));
324
- if (!modelInstance) {
325
- throw new index_1.PxpError(406, 'Record not found');
326
- }
327
- await manager.remove(modelInstance);
328
- return modelInstance;
329
- }
330
- getListParams(params, where) {
331
- const whereGenericFilter = [];
332
- if (params.genericFilterFields) {
333
- const genericFilterFields = params.genericFilterFields;
334
- const filterFieldsArray = genericFilterFields.split('#');
335
- filterFieldsArray.forEach((field) => {
336
- whereGenericFilter.push(Object.assign({ [field]: typeorm_1.Like('%' + params.genericFilterValue + '%') }, where));
337
- });
338
- }
339
- const res = {
340
- where: whereGenericFilter.length > 0 ? whereGenericFilter : [where],
341
- skip: params.start,
342
- take: params.limit,
343
- order: {
344
- [params.sort]: String(params.dir).toUpperCase()
345
- }
346
- };
347
- // ffp search if in this request is sending the id
348
- return res;
349
- }
350
- async procedureMethodWrapper(params, next, res, methodName, readonly, permission = true, log = true, logConfig = {}) {
351
- console.log('before function');
352
- await eval(`this.${methodName}(req, res)`);
353
- console.log('after function');
354
- }
355
- async sqlMethodWrapper(params, next, res, methodName, readonly, permission = true, log = true, logConfig = {}) {
356
- console.log('before function');
357
- await eval(`this.${methodName}(req, res)`);
358
- console.log('after function');
359
- }
360
- async classValidate(model) {
361
- const errors = await index_1.__(class_validator_1.validate(model));
362
- this.validated = true;
363
- if (errors.length > 0) {
364
- throw new index_1.PxpError(406, 'Validation failed!', errors);
365
- }
366
- }
367
- async schemaValidate(schema, params) {
368
- const value = await index_1.__(schema.validateAsync(params, { abortEarly: false }), true);
369
- this.validated = true;
370
- return value;
371
- }
372
- getListSchema(ownColumns) {
373
- const schema = joi_1.default.object(Object.assign({ start: joi_1.default.number().integer().required(), limit: joi_1.default.number().integer().positive().required(), sort: joi_1.default.string().min(2).required(), dir: joi_1.default.string().min(3).max(4).required(), genericFilterFields: joi_1.default.string().min(2), genericFilterValue: joi_1.default.string().min(1) }, ownColumns));
374
- return schema;
375
- }
376
- }
377
- exports.Controller = Controller;
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.Controller = void 0;
26
+ /**
27
+ * Kplian Ltda 2020
28
+ *
29
+ * MIT
30
+ *
31
+ * Controller Class.
32
+ *
33
+ * @summary All common controllers functionality go here (all controllers should inherit this class).
34
+ * @author Jaime Rivera
35
+ *
36
+ * Created at : 2020-06-13 18:09:48
37
+ * Last modified : 2020-10-13 15:36:31
38
+ * Last modified : 2021-03-10 15:36:31 - Favio Figueroa
39
+ * Last modified : 2021-05-01 18:35:31 - Favio Figueroa
40
+ */
41
+ const typeorm_1 = require("typeorm");
42
+ const class_validator_1 = require("class-validator");
43
+ const lodash_1 = __importDefault(require("lodash"));
44
+ const express_1 = require("express");
45
+ const joi_1 = __importDefault(require("joi"));
46
+ const RouteDefinition_1 = require("./RouteDefinition");
47
+ const index_1 = require("./index");
48
+ // import { User } from '@pxp-nd/entities';
49
+ // import { isAuthenticated } from '@pxp-nd/auth';
50
+ const ParseParams_1 = require("./middlewares/ParseParams");
51
+ const isReportMiddleware_1 = require("./middlewares/isReportMiddleware");
52
+ const pdf_1 = require("../reports/pdf");
53
+ const xlsx_1 = require("../reports/xlsx");
54
+ // import * as entities from '@pxp-nd/entities';
55
+ // const pxpEntities: any = entities;
56
+ class Controller {
57
+ constructor(module, Entity = null, config = {
58
+ apiPrefix: '/api',
59
+ defaultDbSettings: 'Orm',
60
+ middlewares: [],
61
+ entities: {},
62
+ }, io = null) {
63
+ this.router = express_1.Router();
64
+ this.path = '';
65
+ this.module = '';
66
+ this.modelString = '';
67
+ this.transactionCode = '';
68
+ this.user = {}; //User;
69
+ this.basicRoutes = [
70
+ { requestMethod: RouteDefinition_1.Method.post, path: '/add', methodName: 'add' },
71
+ { requestMethod: RouteDefinition_1.Method.delete, path: '/delete/:id', methodName: 'delete' },
72
+ { requestMethod: RouteDefinition_1.Method.patch, path: '/edit/:id', methodName: 'edit' },
73
+ { requestMethod: RouteDefinition_1.Method.get, path: '/list', methodName: 'list' }
74
+ ];
75
+ this.basicReadOnly = {
76
+ add: false,
77
+ edit: false,
78
+ list: true,
79
+ delete: false
80
+ };
81
+ this.validated = false;
82
+ this.module = module;
83
+ this.config = config;
84
+ this.io = io;
85
+ if (Reflect.hasMetadata('model', this.constructor)) {
86
+ this.modelString = Reflect.getMetadata('model', this.constructor);
87
+ const [moduleName, entityName] = this.modelString.split('/');
88
+ const mainDir = process.cwd();
89
+ try {
90
+ if (Entity) {
91
+ this.model = Entity;
92
+ }
93
+ else if (config.modules && config.modules[this.module]) {
94
+ const moduleExternal = config.modules[this.module];
95
+ this.model = moduleExternal.entities[entityName];
96
+ }
97
+ else {
98
+ Promise.resolve().then(() => __importStar(require(`${mainDir}/dist/modules/${moduleName}/entity/${entityName}`))).then((model) => {
99
+ this.model = model.default;
100
+ });
101
+ }
102
+ }
103
+ catch (_a) {
104
+ throw new index_1.PxpError(500, 'Model defined in ' + this.constructor.name + ' not found.');
105
+ }
106
+ }
107
+ this.initializeRoutes();
108
+ }
109
+ initializeRoutes() {
110
+ let routes = Reflect.getMetadata('routes', this.constructor);
111
+ this.path = '/' + this.constructor.name;
112
+ // get controller path
113
+ if (Reflect.hasMetadata('controller_path', this.constructor)) {
114
+ this.path = Reflect.getMetadata('controller_path', this.constructor);
115
+ }
116
+ // get read only
117
+ let readonly = Reflect.getMetadata('readonly', this.constructor) || {};
118
+ // get authentication
119
+ const authentication = Reflect.getMetadata('authentication', this.constructor) || {};
120
+ // get permission
121
+ const permission = Reflect.getMetadata('permission', this.constructor) || {};
122
+ // get log
123
+ const log = Reflect.getMetadata('log', this.constructor) || {};
124
+ // get dbsettings
125
+ const dbsettings = Reflect.getMetadata('dbsettings', this.constructor) || {};
126
+ // get logConfig
127
+ const logConfig = Reflect.getMetadata('logConfig', this.constructor) || {};
128
+ const defaultConfig = Reflect.getMetadata('optionsRoute', this.constructor) || {};
129
+ // define basic routes
130
+ if (this.modelString !== '') {
131
+ routes = lodash_1.default.union(this.basicRoutes, routes);
132
+ readonly = Object.assign(Object.assign({}, this.basicReadOnly), readonly);
133
+ }
134
+ routes.forEach((route) => {
135
+ const methodDbSettings = dbsettings[route.methodName] || this.config.defaultDbSettings;
136
+ // readOnly
137
+ const readOnlyMethod = readonly[route.methodName] !== undefined ? readonly[route.methodName] : defaultConfig[route.methodName].readOnly;
138
+ // log
139
+ const logMethod = log[route.methodName] !== undefined ? log[route.methodName] : (defaultConfig[route.methodName] ? defaultConfig[route.methodName].log : true);
140
+ const logValue = typeof logMethod == 'object' ? logMethod : logConfig[route.methodName];
141
+ const logKey = typeof logMethod == 'object' ? true : logMethod;
142
+ if (readOnlyMethod === null || readOnlyMethod === undefined) {
143
+ throw new index_1.PxpError(500, 'ReadOnly decorator was not defined for ' +
144
+ route.methodName +
145
+ ' in ' +
146
+ this.constructor.name +
147
+ ' controller.');
148
+ }
149
+ // auth
150
+ const auth = authentication[route.methodName] !== undefined ? authentication[route.methodName] : (defaultConfig[route.methodName] ? defaultConfig[route.methodName].authentication : true);
151
+ if (!auth) {
152
+ this.router[route.requestMethod](this.config.apiPrefix + '/' + this.module + this.path + route.path,
153
+ // MIDDLEWARES AREA
154
+ [
155
+ ParseParams_1.parseParams
156
+ ], async (req, res, next) => {
157
+ // Execute our method for this path and pass our express request and response object.
158
+ // const params = { ...req.query, ...req.body, ...req.params };
159
+ const params = Object.assign(Object.assign({}, req.files), req.paramasMerge);
160
+ this.pxpParams = req.pxpParams;
161
+ this.transactionCode = (this.module + this.path + route.path)
162
+ .split('/')
163
+ .join('.')
164
+ .toLowerCase();
165
+ this.validated = false;
166
+ try {
167
+ await index_1.__(this.genericMethodWrapper(params, req, next, res, route.methodName, methodDbSettings, readOnlyMethod, false, logKey, logValue));
168
+ }
169
+ catch (ex) {
170
+ const now = new Date();
171
+ const iniAt = req.start;
172
+ const endsAt = now.valueOf() - iniAt.valueOf();
173
+ res.logId = await index_1.__(index_1.insertLog('nouser', 'mac', req.ip, 'error', ex.tecMessage, this.module, this.transactionCode, '', // query
174
+ params, ex.stack, ex.statusCode, endsAt, logValue));
175
+ index_1.errorMiddleware(ex, req, res);
176
+ }
177
+ });
178
+ }
179
+ else {
180
+ //NORMALMENTE VIENE POR AQUI RCM-20211011 *****
181
+ this.router[route.requestMethod](this.config.apiPrefix + '/' + this.module + this.path + route.path,
182
+ // MIDDLEWARES AREA
183
+ [
184
+ ...this.config.middlewares,
185
+ isReportMiddleware_1.isReportMiddleware,
186
+ ParseParams_1.parseParams
187
+ ], async (req, res, next) => {
188
+ // Execute our method for this path and pass our express request and response object.
189
+ const params = Object.assign(Object.assign({}, req.files), req.paramasMerge);
190
+ this.pxpParams = req.pxpParams;
191
+ if (req.user) {
192
+ // this.user = req.user as User;
193
+ this.user = req.user;
194
+ }
195
+ this.transactionCode = (this.module + this.path + route.path)
196
+ .split('/')
197
+ .join('.')
198
+ .toLowerCase();
199
+ this.validated = false;
200
+ try {
201
+ await index_1.__(this.genericMethodWrapper(params, req, next, res, route.methodName, methodDbSettings, readOnlyMethod, permission[route.methodName], logKey, logValue));
202
+ }
203
+ catch (ex) {
204
+ const now = new Date();
205
+ const iniAt = req.start;
206
+ const endsAt = now.valueOf() - iniAt.valueOf();
207
+ res.logId = (await index_1.__(index_1.insertLog(this.user && this.user.username ? this.user.username : 'nouser', 'mac', req.ip, 'error', ex.tecMessage, this.module, this.transactionCode, '', // query
208
+ params, ex.stack, ex.statusCode, endsAt, logValue)));
209
+ index_1.errorMiddleware(ex, req, res);
210
+ }
211
+ });
212
+ }
213
+ });
214
+ }
215
+ async genericMethodWrapper(params, req, next, res, methodName, dbsettings, readonly, permission = true, log = true, logConfig = {}) {
216
+ if (dbsettings === 'Orm') {
217
+ await index_1.__(this.ormMethodWrapper(params, req, next, res, methodName, readonly, permission, log, logConfig));
218
+ }
219
+ else if (dbsettings === 'Procedure') {
220
+ await index_1.__(this.procedureMethodWrapper(params, next, res, methodName, readonly, permission, log, logConfig));
221
+ }
222
+ else {
223
+ await this.sqlMethodWrapper(params, next, res, methodName, readonly, permission, log, logConfig);
224
+ }
225
+ }
226
+ async ormMethodWrapper(params, req, next, res, methodName, readonly, permission = true, log = true, logConfig = {}) {
227
+ let metResponse;
228
+ if (permission) {
229
+ if (this.user && this.user.roles && this.user.roles.length === 0) {
230
+ const hasPermission = await index_1.__(index_1.userHasPermission(this.config.entities.Role)(this.user.userId, this.transactionCode));
231
+ if (!hasPermission) {
232
+ throw new index_1.PxpError(403, 'Access denied to execute this method');
233
+ }
234
+ }
235
+ }
236
+ if (readonly) {
237
+ metResponse = await index_1.__(eval(`this.${methodName}(params, res)`));
238
+ }
239
+ else {
240
+ const connection = typeorm_1.getConnection(process.env.DB_WRITE_CONNECTION_NAME);
241
+ const queryRunner = connection.createQueryRunner();
242
+ // establish real database connection using our new query runner
243
+ await index_1.__(queryRunner.connect());
244
+ await index_1.__(queryRunner.startTransaction());
245
+ try {
246
+ metResponse = (await eval(`this.${methodName}(params, queryRunner.manager, res)`));
247
+ await queryRunner.commitTransaction();
248
+ }
249
+ catch (err) {
250
+ await queryRunner.rollbackTransaction();
251
+ throw err;
252
+ }
253
+ finally {
254
+ await index_1.__(queryRunner.release());
255
+ }
256
+ }
257
+ if (log) {
258
+ const now = new Date();
259
+ const iniAt = req.start;
260
+ const endsAt = now.valueOf() - iniAt.valueOf();
261
+ index_1.__(index_1.insertLog(this.user && this.user.username ? this.user.username : 'nouser', 'mac', req.ip, 'success', 'successful transaction', this.module, this.transactionCode, '', params, JSON.stringify(metResponse), '200', endsAt, logConfig));
262
+ }
263
+ //PARA REPORTES
264
+ if (req.report && req.report.type === 'pdf') {
265
+ req.reportData = metResponse;
266
+ pdf_1.makePdf(req, res);
267
+ }
268
+ else if (req.report && req.report.type === 'xlsx') {
269
+ req.reportData = metResponse;
270
+ xlsx_1.makeXlsx(req, res);
271
+ }
272
+ else {
273
+ res.json(metResponse);
274
+ }
275
+ }
276
+ async list(params) {
277
+ const connection = typeorm_1.getConnection(process.env.DB_WRITE_CONNECTION_NAME);
278
+ const queryRunner = connection.getMetadata(this.model).ownColumns.find(column => column.isPrimary === true);
279
+ // ffp search if in the params has been sent the primary key
280
+ const primaryKeyColumn = queryRunner.propertyName;
281
+ if (primaryKeyColumn in params) {
282
+ const findOne = await index_1.__(this.model.findOne({ where: { [primaryKeyColumn]: params[primaryKeyColumn] } }));
283
+ return { data: findOne, count: 1 };
284
+ }
285
+ // filter by some column that exist in the entity
286
+ // ffp if some column is into of params for added in the condition
287
+ let ownColumnsForSchema = {};
288
+ const whereOwnColumns = connection.getMetadata(this.model).ownColumns.reduce((t, column) => {
289
+ if (`_${column.propertyName}` in params) {
290
+ ownColumnsForSchema = Object.assign(Object.assign({}, ownColumnsForSchema), { [`_${column.propertyName}`]: joi_1.default.string() });
291
+ t = Object.assign(Object.assign({}, t), { [column.propertyName]: params[`_${column.propertyName}`] });
292
+ }
293
+ return t;
294
+ }, {});
295
+ const schema = this.getListSchema(ownColumnsForSchema);
296
+ const resParams = await index_1.__(this.schemaValidate(schema, params));
297
+ const listParam = this.getListParams(resParams, whereOwnColumns);
298
+ const [rows, count] = await index_1.__(this.model.findAndCount(listParam));
299
+ return { data: rows, count };
300
+ }
301
+ async add(params, manager) {
302
+ const modelInstance = new this.model();
303
+ Object.assign(modelInstance, params);
304
+ modelInstance.createdBy = this.user ? this.user.username : '_';
305
+ await index_1.__(this.classValidate(modelInstance));
306
+ await manager.save(modelInstance);
307
+ return modelInstance;
308
+ }
309
+ async edit(params, manager) {
310
+ const modelInstance = (await index_1.__(this.model.findOne(params.id)));
311
+ if (!modelInstance) {
312
+ throw new index_1.PxpError(406, 'Record not found');
313
+ }
314
+ const editParams = params;
315
+ Object.assign(modelInstance, editParams);
316
+ delete editParams.id;
317
+ modelInstance.modifiedBy = this.user ? this.user.username : null;
318
+ await index_1.__(this.classValidate(modelInstance));
319
+ await manager.save(modelInstance);
320
+ return modelInstance;
321
+ }
322
+ async delete(params, manager) {
323
+ const modelInstance = (await index_1.__(this.model.findOne(params.id)));
324
+ if (!modelInstance) {
325
+ throw new index_1.PxpError(406, 'Record not found');
326
+ }
327
+ await manager.remove(modelInstance);
328
+ return modelInstance;
329
+ }
330
+ getListParams(params, where) {
331
+ const whereGenericFilter = [];
332
+ if (params.genericFilterFields) {
333
+ const genericFilterFields = params.genericFilterFields;
334
+ const filterFieldsArray = genericFilterFields.split('#');
335
+ filterFieldsArray.forEach((field) => {
336
+ whereGenericFilter.push(Object.assign({ [field]: typeorm_1.Like('%' + params.genericFilterValue + '%') }, where));
337
+ });
338
+ }
339
+ const res = {
340
+ where: whereGenericFilter.length > 0 ? whereGenericFilter : [where],
341
+ skip: params.start,
342
+ take: params.limit,
343
+ order: {
344
+ [params.sort]: String(params.dir).toUpperCase()
345
+ }
346
+ };
347
+ // ffp search if in this request is sending the id
348
+ return res;
349
+ }
350
+ async procedureMethodWrapper(params, next, res, methodName, readonly, permission = true, log = true, logConfig = {}) {
351
+ console.log('before function');
352
+ await eval(`this.${methodName}(req, res)`);
353
+ console.log('after function');
354
+ }
355
+ async sqlMethodWrapper(params, next, res, methodName, readonly, permission = true, log = true, logConfig = {}) {
356
+ console.log('before function');
357
+ await eval(`this.${methodName}(req, res)`);
358
+ console.log('after function');
359
+ }
360
+ async classValidate(model) {
361
+ const errors = await index_1.__(class_validator_1.validate(model));
362
+ this.validated = true;
363
+ if (errors.length > 0) {
364
+ throw new index_1.PxpError(406, 'Validation failed!', errors);
365
+ }
366
+ }
367
+ async schemaValidate(schema, params) {
368
+ const value = await index_1.__(schema.validateAsync(params, { abortEarly: false }), true);
369
+ this.validated = true;
370
+ return value;
371
+ }
372
+ getListSchema(ownColumns) {
373
+ const schema = joi_1.default.object(Object.assign({ start: joi_1.default.number().integer().required(), limit: joi_1.default.number().integer().positive().required(), sort: joi_1.default.string().min(2).required(), dir: joi_1.default.string().min(3).max(4).required(), genericFilterFields: joi_1.default.string().min(2), genericFilterValue: joi_1.default.string().min(1) }, ownColumns));
374
+ return schema;
375
+ }
376
+ }
377
+ exports.Controller = Controller;