@simitgroup/simpleapp-generator 1.6.7-i-alpha → 1.6.7-j-alpha
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ReleaseNote.md +7 -1
- package/package.json +1 -1
- package/templates/basic/miniApi/resource.controller.ts.eta +119 -56
- package/templates/basic/miniApi/resource.service.ts.eta +54 -25
- package/templates/miniApi/src/constants/api-scopes.ts.eta +21 -3
- package/templates/miniApi/src/constants/available-custom-field.ts.eta +22 -0
- package/templates/nest/src/simpleapp/generate/processors/simpleapp.processor.ts.eta +125 -441
|
@@ -4,48 +4,25 @@
|
|
|
4
4
|
* last change 2024-01-27
|
|
5
5
|
* Author: Ks Tan
|
|
6
6
|
*/
|
|
7
|
-
import { Injectable, Logger
|
|
8
|
-
import { InjectModel } from '@nestjs/mongoose';
|
|
7
|
+
import { Inject, Injectable, Logger } from '@nestjs/common';
|
|
9
8
|
import jsonpath from 'jsonpath';
|
|
10
9
|
import _ from 'lodash';
|
|
11
10
|
|
|
12
|
-
import {
|
|
13
|
-
import { foreignkeys } from '../commons/dicts/foreignkeys';
|
|
11
|
+
import { BadRequestException, ForbiddenException, HttpExceptionOptions, InternalServerErrorException, NotFoundException } from '@nestjs/common/exceptions';
|
|
14
12
|
import { EventEmitter2 } from '@nestjs/event-emitter';
|
|
15
|
-
import {
|
|
16
|
-
Model,
|
|
17
|
-
Types,
|
|
18
|
-
PipelineStage,
|
|
19
|
-
mongo,
|
|
20
|
-
FilterQuery,
|
|
21
|
-
ProjectionType,
|
|
22
|
-
} from 'mongoose';
|
|
23
13
|
import Ajv from 'ajv';
|
|
24
|
-
import addFormats from 'ajv-formats';
|
|
25
14
|
import addErrors from 'ajv-errors';
|
|
26
|
-
import
|
|
27
|
-
|
|
28
|
-
HttpException,
|
|
29
|
-
BadRequestException,
|
|
30
|
-
ForbiddenException,
|
|
31
|
-
InternalServerErrorException,
|
|
32
|
-
HttpExceptionOptions,
|
|
33
|
-
} from '@nestjs/common/exceptions';
|
|
34
|
-
import { UserContext } from '../commons/user.context';
|
|
15
|
+
import addFormats from 'ajv-formats';
|
|
16
|
+
import { FilterQuery, Model, PipelineStage, mongo } from 'mongoose';
|
|
35
17
|
import { CloudApiService } from 'src/cloudapi/cloudapi.service';
|
|
18
|
+
import { CustomException } from 'src/customexception';
|
|
36
19
|
import { PrintApiService } from 'src/printapi/printapi.service';
|
|
20
|
+
import { AuditTrail } from '../commons/audittrail.service';
|
|
21
|
+
import { foreignkeys } from '../commons/dicts/foreignkeys';
|
|
37
22
|
import { DocNumberFormatGenerator } from '../commons/docnogenerator.service';
|
|
38
23
|
import { RunWebhookService } from '../commons/runwebhook.service';
|
|
39
|
-
import {
|
|
40
|
-
|
|
41
|
-
DefaultHooks,
|
|
42
|
-
MoreProjectionType,
|
|
43
|
-
DeleteResultType,
|
|
44
|
-
WorkflowName,
|
|
45
|
-
TextSearchBody,
|
|
46
|
-
CheckMutipleUnionExistResponse,
|
|
47
|
-
} from '../types';
|
|
48
|
-
import { CustomException } from 'src/customexception';
|
|
24
|
+
import { UserContext } from '../commons/user.context';
|
|
25
|
+
import { CheckMutipleUnionExistResponse, DefaultHooks, DeleteResultType, IsolationType, MoreProjectionType, TextSearchBody, WorkflowName } from '../types';
|
|
49
26
|
|
|
50
27
|
@Injectable()
|
|
51
28
|
export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
@@ -56,7 +33,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
56
33
|
@Inject(PrintApiService)
|
|
57
34
|
protected printapi: PrintApiService;
|
|
58
35
|
@Inject(RunWebhookService)
|
|
59
|
-
protected runWebHook:RunWebhookService;
|
|
36
|
+
protected runWebHook: RunWebhookService;
|
|
60
37
|
protected hooks: DefaultHooks<T> = {};
|
|
61
38
|
protected logger = new Logger();
|
|
62
39
|
protected strictIsolation = true;
|
|
@@ -88,12 +65,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
88
65
|
|
|
89
66
|
// protected userprovider = new UserContext() ;
|
|
90
67
|
|
|
91
|
-
constructor(
|
|
92
|
-
doctype: string,
|
|
93
|
-
docname: string,
|
|
94
|
-
newdoc: Model<T>,
|
|
95
|
-
isolationtype: IsolationType = IsolationType.org,
|
|
96
|
-
) {
|
|
68
|
+
constructor(doctype: string, docname: string, newdoc: Model<T>, isolationtype: IsolationType = IsolationType.org) {
|
|
97
69
|
// console.log("-------init simpleapp service abstract class -------userprovider=",typeof this.userprovider)
|
|
98
70
|
this.documentType = doctype.toUpperCase();
|
|
99
71
|
this.documentName = docname;
|
|
@@ -104,8 +76,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
104
76
|
// this.tenantdoc = tenantdoc
|
|
105
77
|
}
|
|
106
78
|
getDocumentType = () => this.documentType;
|
|
107
|
-
getDocumentName = (capFirst: boolean = false) =>
|
|
108
|
-
capFirst ? _.upperFirst(this.documentName) : this.documentName;
|
|
79
|
+
getDocumentName = (capFirst: boolean = false) => (capFirst ? _.upperFirst(this.documentName) : this.documentName);
|
|
109
80
|
getRecordId = (): string => this.data._id;
|
|
110
81
|
setSchema = (newschema) => (this.jsonschema = newschema);
|
|
111
82
|
getSchema = () => this.doc.schema.obj;
|
|
@@ -125,7 +96,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
125
96
|
public isReadOnly(): boolean {
|
|
126
97
|
return false;
|
|
127
98
|
}
|
|
128
|
-
reCalculateValue(data: T) {}
|
|
99
|
+
reCalculateValue(data: T) { }
|
|
129
100
|
getIsolationFilter = (appuser: UserContext) => {
|
|
130
101
|
let isolationFilter = {};
|
|
131
102
|
switch (this.isolationtype) {
|
|
@@ -173,10 +144,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
173
144
|
const filter1 = {};
|
|
174
145
|
const filter2 = {};
|
|
175
146
|
const filters: any[] = [];
|
|
176
|
-
if (
|
|
177
|
-
this.jsonschema.properties[this.documentIdentityCode]['type'] ==
|
|
178
|
-
'string'
|
|
179
|
-
) {
|
|
147
|
+
if (this.jsonschema.properties[this.documentIdentityCode]['type'] == 'string') {
|
|
180
148
|
filter1[this.documentIdentityCode] = { $regex: keyword, $options: 'i' };
|
|
181
149
|
filters.push(filter1);
|
|
182
150
|
}
|
|
@@ -213,14 +181,12 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
213
181
|
*/
|
|
214
182
|
async searchNoIsolation(appuser: UserContext, filters: FilterQuery<T>) {
|
|
215
183
|
try {
|
|
216
|
-
if (this.hooks.beforeSearch)
|
|
217
|
-
await this.hooks.beforeSearch(appuser, filters);
|
|
184
|
+
if (this.hooks.beforeSearch) await this.hooks.beforeSearch(appuser, filters);
|
|
218
185
|
const products = await this.doc.find(filters);
|
|
219
186
|
const productlist = products.map((p) => {
|
|
220
187
|
return p;
|
|
221
188
|
});
|
|
222
|
-
if (this.hooks.afterSearch)
|
|
223
|
-
await this.hooks.afterSearch(appuser, productlist);
|
|
189
|
+
if (this.hooks.afterSearch) await this.hooks.afterSearch(appuser, productlist);
|
|
224
190
|
|
|
225
191
|
// console.log(products);
|
|
226
192
|
return productlist;
|
|
@@ -241,9 +207,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
241
207
|
throw new InternalServerErrorException(err);
|
|
242
208
|
}
|
|
243
209
|
} else {
|
|
244
|
-
throw new InternalServerErrorException(
|
|
245
|
-
'first aggregate pipelinestage shall use $match',
|
|
246
|
-
);
|
|
210
|
+
throw new InternalServerErrorException('first aggregate pipelinestage shall use $match');
|
|
247
211
|
}
|
|
248
212
|
}
|
|
249
213
|
async aggregate(appuser: UserContext, pipeline: PipelineStage[]) {
|
|
@@ -261,18 +225,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
261
225
|
throw new InternalServerErrorException(err);
|
|
262
226
|
}
|
|
263
227
|
} else {
|
|
264
|
-
throw new InternalServerErrorException(
|
|
265
|
-
'first aggregate pipelinestage shall use $match',
|
|
266
|
-
);
|
|
228
|
+
throw new InternalServerErrorException('first aggregate pipelinestage shall use $match');
|
|
267
229
|
}
|
|
268
230
|
}
|
|
269
|
-
async search(
|
|
270
|
-
appuser: UserContext,
|
|
271
|
-
filters: FilterQuery<T>,
|
|
272
|
-
projection: string[] = undefined,
|
|
273
|
-
sort: any = undefined,
|
|
274
|
-
lookup: { [key: string]: string } = undefined,
|
|
275
|
-
) {
|
|
231
|
+
async search(appuser: UserContext, filters: FilterQuery<T>, projection: string[] = undefined, sort: any = undefined, lookup: { [key: string]: string } = undefined) {
|
|
276
232
|
try {
|
|
277
233
|
const isolationFilter = { ...this.getIsolationFilter(appuser) };
|
|
278
234
|
this.polishIsolationFilter(isolationFilter);
|
|
@@ -280,24 +236,15 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
280
236
|
// console.log("initial search",filters)
|
|
281
237
|
const newfilters: FilterQuery<T> = { ...filters, ...isolationFilter };
|
|
282
238
|
|
|
283
|
-
if (this.hooks.beforeSearch)
|
|
284
|
-
await this.hooks.beforeSearch(appuser, newfilters);
|
|
239
|
+
if (this.hooks.beforeSearch) await this.hooks.beforeSearch(appuser, newfilters);
|
|
285
240
|
// console.log("before _find",newfilters)
|
|
286
241
|
// console.log("this.doc",this.doc)
|
|
287
242
|
let searchResults: T[] = [];
|
|
288
243
|
if (lookup === undefined) {
|
|
289
244
|
this.logger.debug('after search', newfilters);
|
|
290
|
-
searchResults = await this.doc
|
|
291
|
-
.find(newfilters, projection, { session: appuser.getDBSession() })
|
|
292
|
-
.sort(sort);
|
|
245
|
+
searchResults = await this.doc.find(newfilters, projection, { session: appuser.getDBSession() }).sort(sort);
|
|
293
246
|
} else {
|
|
294
|
-
const pipelines = this.searchToAggregate(
|
|
295
|
-
appuser,
|
|
296
|
-
newfilters,
|
|
297
|
-
projection,
|
|
298
|
-
sort,
|
|
299
|
-
lookup,
|
|
300
|
-
);
|
|
247
|
+
const pipelines = this.searchToAggregate(appuser, newfilters, projection, sort, lookup);
|
|
301
248
|
this.logger.debug('after aggregate', pipelines);
|
|
302
249
|
searchResults = await this.aggregate(appuser, pipelines);
|
|
303
250
|
}
|
|
@@ -326,20 +273,12 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
326
273
|
const orConditions: any[] = [];
|
|
327
274
|
if (body.fields && body.fields.length > 0) {
|
|
328
275
|
body.fields.forEach((field: string) => {
|
|
329
|
-
if (
|
|
330
|
-
field != 'defaultPrice' &&
|
|
331
|
-
field != 'amount' &&
|
|
332
|
-
field != 'active' &&
|
|
333
|
-
field != 'updated'
|
|
334
|
-
) {
|
|
276
|
+
if (field != 'defaultPrice' && field != 'amount' && field != 'active' && field != 'updated') {
|
|
335
277
|
orConditions.push({
|
|
336
278
|
[field]: { $regex: keyword, $options: 'i' },
|
|
337
279
|
});
|
|
338
280
|
} else {
|
|
339
|
-
if (
|
|
340
|
-
!isNaN(Number(keyword)) &&
|
|
341
|
-
(field == 'defaultPrice' || field == 'amount')
|
|
342
|
-
) {
|
|
281
|
+
if (!isNaN(Number(keyword)) && (field == 'defaultPrice' || field == 'amount')) {
|
|
343
282
|
orConditions.push({
|
|
344
283
|
[field]: { $gte: keyword },
|
|
345
284
|
});
|
|
@@ -360,10 +299,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
360
299
|
const sorts = body.sorts || {};
|
|
361
300
|
|
|
362
301
|
// Ensure `this.doc` is a Mongoose model or similar
|
|
363
|
-
const results = await this.doc
|
|
364
|
-
.find(newfilters, fields)
|
|
365
|
-
.sort(sorts)
|
|
366
|
-
.exec();
|
|
302
|
+
const results = await this.doc.find(newfilters, fields).sort(sorts).exec();
|
|
367
303
|
|
|
368
304
|
return results;
|
|
369
305
|
} catch (error) {
|
|
@@ -373,12 +309,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
373
309
|
}
|
|
374
310
|
}
|
|
375
311
|
async findById(appuser: UserContext, id: string) {
|
|
376
|
-
if (this.hooks.beforeFetchRecord)
|
|
377
|
-
await this.hooks.beforeFetchRecord(appuser, id);
|
|
312
|
+
if (this.hooks.beforeFetchRecord) await this.hooks.beforeFetchRecord(appuser, id);
|
|
378
313
|
|
|
379
314
|
const data = await this.search(appuser, { _id: id as any });
|
|
380
|
-
if (this.hooks.afterFetchRecord)
|
|
381
|
-
await this.hooks.afterFetchRecord(appuser, data[0]);
|
|
315
|
+
if (this.hooks.afterFetchRecord) await this.hooks.afterFetchRecord(appuser, data[0]);
|
|
382
316
|
|
|
383
317
|
if (data.length == 1) {
|
|
384
318
|
// console.log('data0', data[0]);
|
|
@@ -389,12 +323,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
389
323
|
}
|
|
390
324
|
|
|
391
325
|
async findByIdNoIsolation(appuser: UserContext, id: string) {
|
|
392
|
-
if (this.hooks.beforeFetchRecord)
|
|
393
|
-
await this.hooks.beforeFetchRecord(appuser, id);
|
|
326
|
+
if (this.hooks.beforeFetchRecord) await this.hooks.beforeFetchRecord(appuser, id);
|
|
394
327
|
|
|
395
328
|
const data = await this.searchNoIsolation(appuser, { _id: id as any });
|
|
396
|
-
if (this.hooks.afterFetchRecord)
|
|
397
|
-
await this.hooks.afterFetchRecord(appuser, data[0]);
|
|
329
|
+
if (this.hooks.afterFetchRecord) await this.hooks.afterFetchRecord(appuser, data[0]);
|
|
398
330
|
|
|
399
331
|
if (data.length == 1) {
|
|
400
332
|
// console.log('data0', data[0]);
|
|
@@ -418,17 +350,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
418
350
|
}
|
|
419
351
|
|
|
420
352
|
const result = await this.doc.insertMany(datas);
|
|
421
|
-
await this.audittrail.addManyEvents(
|
|
422
|
-
appuser,
|
|
423
|
-
this.documentName,
|
|
424
|
-
'createMany',
|
|
425
|
-
datas,
|
|
426
|
-
);
|
|
353
|
+
await this.audittrail.addManyEvents(appuser, this.documentName, 'createMany', datas);
|
|
427
354
|
return result;
|
|
428
355
|
} else {
|
|
429
|
-
throw new BadRequestException(
|
|
430
|
-
this.getDocumentType() + ': create many only support array',
|
|
431
|
-
);
|
|
356
|
+
throw new BadRequestException(this.getDocumentType() + ': create many only support array');
|
|
432
357
|
}
|
|
433
358
|
}
|
|
434
359
|
|
|
@@ -445,7 +370,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
445
370
|
let result;
|
|
446
371
|
const dbsession = appuser.getDBSession();
|
|
447
372
|
if (dbsession && !dbsession.inTransaction()) {
|
|
448
|
-
dbsession.startTransaction();
|
|
373
|
+
dbsession.startTransaction({ readPreference: 'primary' });
|
|
449
374
|
}
|
|
450
375
|
|
|
451
376
|
if (this.withDocNumberFormat && !data[this.documentIdentityCode]) {
|
|
@@ -459,29 +384,18 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
459
384
|
this.reCalculateValue(data);
|
|
460
385
|
await this.validateData(appuser, data);
|
|
461
386
|
this.applyNestedDateTime(appuser, data, 'create');
|
|
462
|
-
if (this.hooks.beforeCreate)
|
|
463
|
-
await this.hooks.beforeCreate(appuser, data);
|
|
387
|
+
if (this.hooks.beforeCreate) await this.hooks.beforeCreate(appuser, data);
|
|
464
388
|
const newdoc = new this.doc(data);
|
|
465
389
|
|
|
466
390
|
try {
|
|
467
391
|
result = await newdoc.save({ session: dbsession });
|
|
468
|
-
await this.audittrail.addEvent(
|
|
469
|
-
appuser,
|
|
470
|
-
this.documentName,
|
|
471
|
-
result._id,
|
|
472
|
-
'create',
|
|
473
|
-
data,
|
|
474
|
-
);
|
|
392
|
+
await this.audittrail.addEvent(appuser, this.documentName, result._id, 'create', data);
|
|
475
393
|
appuser.addInsertedRecordId(this.documentName, result._id);
|
|
476
394
|
} catch (err) {
|
|
477
395
|
this.logger.error(err);
|
|
478
|
-
const processdata = await this.runWorker(
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
{
|
|
482
|
-
err: err,
|
|
483
|
-
},
|
|
484
|
-
);
|
|
396
|
+
const processdata = await this.runWorker(appuser, 'processdata.processError', {
|
|
397
|
+
err: err,
|
|
398
|
+
});
|
|
485
399
|
|
|
486
400
|
if (!processdata) {
|
|
487
401
|
throw new InternalServerErrorException(err);
|
|
@@ -491,22 +405,16 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
491
405
|
}
|
|
492
406
|
|
|
493
407
|
try {
|
|
494
|
-
if (this.hooks.afterCreate)
|
|
495
|
-
await this.hooks.afterCreate(appuser, result);
|
|
408
|
+
if (this.hooks.afterCreate) await this.hooks.afterCreate(appuser, result);
|
|
496
409
|
await this.callWebhook(appuser, 'create', result);
|
|
497
410
|
|
|
498
411
|
// return result as T;
|
|
499
412
|
} catch (err) {
|
|
500
|
-
throw new InternalServerErrorException(
|
|
501
|
-
`createHook ${this.documentType} error: ${JSON.stringify(err)}`,
|
|
502
|
-
`${this.documentType} createHook error`,
|
|
503
|
-
);
|
|
413
|
+
throw new InternalServerErrorException(`createHook ${this.documentType} error: ${JSON.stringify(err)}`, `${this.documentType} createHook error`);
|
|
504
414
|
}
|
|
505
415
|
}
|
|
506
416
|
} else {
|
|
507
|
-
throw new BadRequestException(
|
|
508
|
-
this.getDocumentType() + ': create many only support array',
|
|
509
|
-
);
|
|
417
|
+
throw new BadRequestException(this.getDocumentType() + ': create many only support array');
|
|
510
418
|
}
|
|
511
419
|
return 'ok';
|
|
512
420
|
}
|
|
@@ -530,17 +438,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
530
438
|
}
|
|
531
439
|
|
|
532
440
|
const result = await this.doc.insertMany(datas);
|
|
533
|
-
await this.audittrail.addManyEvents(
|
|
534
|
-
appuser,
|
|
535
|
-
this.documentName,
|
|
536
|
-
'createMany',
|
|
537
|
-
datas,
|
|
538
|
-
);
|
|
441
|
+
await this.audittrail.addManyEvents(appuser, this.documentName, 'createMany', datas);
|
|
539
442
|
return result;
|
|
540
443
|
} else {
|
|
541
|
-
throw new BadRequestException(
|
|
542
|
-
this.getDocumentType() + ': create many only support array',
|
|
543
|
-
);
|
|
444
|
+
throw new BadRequestException(this.getDocumentType() + ': create many only support array');
|
|
544
445
|
}
|
|
545
446
|
}
|
|
546
447
|
async createWithId(appuser: UserContext, data: T) {
|
|
@@ -551,16 +452,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
551
452
|
}
|
|
552
453
|
const dbsession = appuser.getDBSession();
|
|
553
454
|
if (dbsession && !dbsession.inTransaction()) {
|
|
554
|
-
dbsession.startTransaction();
|
|
455
|
+
dbsession.startTransaction({ readPreference: 'primary' });
|
|
555
456
|
}
|
|
556
457
|
|
|
557
|
-
this.logger.debug(
|
|
558
|
-
'this.withDocNumberFormat :' +
|
|
559
|
-
this.withDocNumberFormat +
|
|
560
|
-
' && ' +
|
|
561
|
-
'!data[this.documentIdentityCode] ==' +
|
|
562
|
-
!data[this.documentIdentityCode],
|
|
563
|
-
);
|
|
458
|
+
this.logger.debug('this.withDocNumberFormat :' + this.withDocNumberFormat + ' && ' + '!data[this.documentIdentityCode] ==' + !data[this.documentIdentityCode]);
|
|
564
459
|
if (this.withDocNumberFormat && !data[this.documentIdentityCode]) {
|
|
565
460
|
await this.genNewDocNo(appuser, data);
|
|
566
461
|
}
|
|
@@ -584,23 +479,13 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
584
479
|
await this.identifyForeignKeys(appuser, data);
|
|
585
480
|
try {
|
|
586
481
|
result = await newdoc.save({ session: dbsession });
|
|
587
|
-
await this.audittrail.addEvent(
|
|
588
|
-
appuser,
|
|
589
|
-
this.documentName,
|
|
590
|
-
result._id,
|
|
591
|
-
'create',
|
|
592
|
-
data,
|
|
593
|
-
);
|
|
482
|
+
await this.audittrail.addEvent(appuser, this.documentName, result._id, 'create', data);
|
|
594
483
|
appuser.addInsertedRecordId(this.documentName, result._id);
|
|
595
484
|
} catch (err) {
|
|
596
485
|
this.logger.error(err);
|
|
597
|
-
const processdata = await this.runWorker(
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
{
|
|
601
|
-
err: err,
|
|
602
|
-
},
|
|
603
|
-
);
|
|
486
|
+
const processdata = await this.runWorker(appuser, 'processdata.processError', {
|
|
487
|
+
err: err,
|
|
488
|
+
});
|
|
604
489
|
|
|
605
490
|
if (!processdata) {
|
|
606
491
|
throw new InternalServerErrorException(err);
|
|
@@ -614,18 +499,11 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
614
499
|
await this.callWebhook(appuser, 'create', result);
|
|
615
500
|
return result as T;
|
|
616
501
|
} catch (err) {
|
|
617
|
-
throw new InternalServerErrorException(
|
|
618
|
-
`createHook ${this.documentType} error: ${JSON.stringify(err)}`,
|
|
619
|
-
`${this.documentType} createHook error`,
|
|
620
|
-
);
|
|
502
|
+
throw new InternalServerErrorException(`createHook ${this.documentType} error: ${JSON.stringify(err)}`, `${this.documentType} createHook error`);
|
|
621
503
|
}
|
|
622
504
|
}
|
|
623
505
|
|
|
624
|
-
async create(
|
|
625
|
-
appuser: UserContext,
|
|
626
|
-
data: T,
|
|
627
|
-
noStartTransaction: boolean = false,
|
|
628
|
-
) {
|
|
506
|
+
async create(appuser: UserContext, data: T, noStartTransaction: boolean = false) {
|
|
629
507
|
let result;
|
|
630
508
|
|
|
631
509
|
if (!data._id) {
|
|
@@ -633,16 +511,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
633
511
|
}
|
|
634
512
|
const dbsession = appuser.getDBSession();
|
|
635
513
|
if (dbsession && !dbsession.inTransaction() && !noStartTransaction) {
|
|
636
|
-
dbsession.startTransaction();
|
|
514
|
+
dbsession.startTransaction({ readPreference: 'primary' });
|
|
637
515
|
}
|
|
638
516
|
|
|
639
|
-
this.logger.debug(
|
|
640
|
-
'this.withDocNumberFormat :' +
|
|
641
|
-
this.withDocNumberFormat +
|
|
642
|
-
' && ' +
|
|
643
|
-
'!data[this.documentIdentityCode] ==' +
|
|
644
|
-
!data[this.documentIdentityCode],
|
|
645
|
-
);
|
|
517
|
+
this.logger.debug('this.withDocNumberFormat :' + this.withDocNumberFormat + ' && ' + '!data[this.documentIdentityCode] ==' + !data[this.documentIdentityCode]);
|
|
646
518
|
if (this.withDocNumberFormat && !data[this.documentIdentityCode]) {
|
|
647
519
|
await this.genNewDocNo(appuser, data);
|
|
648
520
|
}
|
|
@@ -666,23 +538,13 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
666
538
|
await this.identifyForeignKeys(appuser, data);
|
|
667
539
|
try {
|
|
668
540
|
result = await newdoc.save({ session: dbsession });
|
|
669
|
-
await this.audittrail.addEvent(
|
|
670
|
-
appuser,
|
|
671
|
-
this.documentName,
|
|
672
|
-
result._id,
|
|
673
|
-
'create',
|
|
674
|
-
data,
|
|
675
|
-
);
|
|
541
|
+
await this.audittrail.addEvent(appuser, this.documentName, result._id, 'create', data);
|
|
676
542
|
appuser.addInsertedRecordId(this.documentName, result._id);
|
|
677
543
|
} catch (err) {
|
|
678
544
|
this.logger.error(err);
|
|
679
|
-
const processdata = await this.runWorker(
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
{
|
|
683
|
-
err: err,
|
|
684
|
-
},
|
|
685
|
-
);
|
|
545
|
+
const processdata = await this.runWorker(appuser, 'processdata.processError', {
|
|
546
|
+
err: err,
|
|
547
|
+
});
|
|
686
548
|
|
|
687
549
|
if (!processdata) {
|
|
688
550
|
throw new InternalServerErrorException(err);
|
|
@@ -696,40 +558,23 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
696
558
|
await this.callWebhook(appuser, 'create', result);
|
|
697
559
|
return result as T;
|
|
698
560
|
} catch (err) {
|
|
699
|
-
throw new InternalServerErrorException(
|
|
700
|
-
`createHook ${this.documentType} error: ${JSON.stringify(err)}`,
|
|
701
|
-
`${this.documentType} createHook error`,
|
|
702
|
-
);
|
|
561
|
+
throw new InternalServerErrorException(`createHook ${this.documentType} error: ${JSON.stringify(err)}`, `${this.documentType} createHook error`);
|
|
703
562
|
}
|
|
704
563
|
}
|
|
705
564
|
|
|
706
|
-
applyNestedDateTime = (
|
|
707
|
-
appuser: UserContext,
|
|
708
|
-
data: any,
|
|
709
|
-
transtype: string,
|
|
710
|
-
) => {
|
|
565
|
+
applyNestedDateTime = (appuser: UserContext, data: any, transtype: string) => {
|
|
711
566
|
const props = Object.getOwnPropertyNames(data);
|
|
712
567
|
for (let i = 0; i < props.length; i++) {
|
|
713
568
|
const key = props[i];
|
|
714
569
|
//need to apply nested
|
|
715
|
-
if (
|
|
716
|
-
Array.isArray(data[key]) &&
|
|
717
|
-
data[key].length > 0 &&
|
|
718
|
-
typeof data[key][0] == 'object'
|
|
719
|
-
) {
|
|
570
|
+
if (Array.isArray(data[key]) && data[key].length > 0 && typeof data[key][0] == 'object') {
|
|
720
571
|
for (let j = 0; j < data[key].length; j++) {
|
|
721
572
|
this.applyNestedDateTime(appuser, data[key][j], transtype);
|
|
722
573
|
}
|
|
723
574
|
} else if (key == 'created') {
|
|
724
|
-
data['created'] =
|
|
725
|
-
transtype == 'create' || !data['created']
|
|
726
|
-
? new Date().toISOString()
|
|
727
|
-
: data['created'];
|
|
575
|
+
data['created'] = transtype == 'create' || !data['created'] ? new Date().toISOString() : data['created'];
|
|
728
576
|
} else if (key == 'createdBy') {
|
|
729
|
-
data['createdBy'] =
|
|
730
|
-
transtype == 'create' || !data['createdBy']
|
|
731
|
-
? appuser.getUid()
|
|
732
|
-
: data['createdBy'];
|
|
577
|
+
data['createdBy'] = transtype == 'create' || !data['createdBy'] ? appuser.getUid() : data['createdBy'];
|
|
733
578
|
} else if (key == 'updated') {
|
|
734
579
|
data['updated'] = new Date().toISOString();
|
|
735
580
|
} else if (key == 'updatedBy') {
|
|
@@ -764,10 +609,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
764
609
|
errormsg.push(this.errorlist[i].message);
|
|
765
610
|
}
|
|
766
611
|
|
|
767
|
-
throw new BadRequestException(
|
|
768
|
-
'Before validation hook failed',
|
|
769
|
-
errormsg as HttpExceptionOptions,
|
|
770
|
-
);
|
|
612
|
+
throw new BadRequestException('Before validation hook failed', errormsg as HttpExceptionOptions);
|
|
771
613
|
}
|
|
772
614
|
|
|
773
615
|
let validate;
|
|
@@ -781,14 +623,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
781
623
|
if (!valid) {
|
|
782
624
|
this.logger.error(JSON.stringify(data));
|
|
783
625
|
this.logger.error(JSON.stringify(validate.errors), 'validate errors:');
|
|
784
|
-
throw new BadRequestException(
|
|
785
|
-
'Data validation failed',
|
|
786
|
-
validate.errors as HttpExceptionOptions,
|
|
787
|
-
);
|
|
626
|
+
throw new BadRequestException('Data validation failed', validate.errors as HttpExceptionOptions);
|
|
788
627
|
}
|
|
789
628
|
//no check for duplicate those
|
|
790
|
-
if (this.hooks.afterValidation)
|
|
791
|
-
await this.hooks.afterValidation(appuser, data, _id);
|
|
629
|
+
if (this.hooks.afterValidation) await this.hooks.afterValidation(appuser, data, _id);
|
|
792
630
|
}
|
|
793
631
|
|
|
794
632
|
polishIsolationFilter = (filterIsolation: any, data: any = {}) => {
|
|
@@ -825,13 +663,12 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
825
663
|
}
|
|
826
664
|
const dbsession = appuser.getDBSession();
|
|
827
665
|
if (dbsession && !dbsession.inTransaction()) {
|
|
828
|
-
dbsession.startTransaction();
|
|
666
|
+
dbsession.startTransaction({ readPreference: 'primary' });
|
|
829
667
|
}
|
|
830
668
|
|
|
831
669
|
let dependency;
|
|
832
670
|
try {
|
|
833
|
-
if (this.hooks.beforeDelete)
|
|
834
|
-
await this.hooks.beforeDelete(appuser, id, deletedata);
|
|
671
|
+
if (this.hooks.beforeDelete) await this.hooks.beforeDelete(appuser, id, deletedata);
|
|
835
672
|
this.logger.debug('delete record', this.documentName, id);
|
|
836
673
|
dependency = await this.getRelatedRecords(appuser, id);
|
|
837
674
|
//console.log('dependency', dependency);
|
|
@@ -841,40 +678,25 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
841
678
|
|
|
842
679
|
filterIsolation['_id'] = id;
|
|
843
680
|
this.logger.debug('delete filter', filterIsolation);
|
|
844
|
-
const result = await this.doc
|
|
845
|
-
|
|
846
|
-
.session(dbsession);
|
|
847
|
-
await this.audittrail.addEvent(
|
|
848
|
-
appuser,
|
|
849
|
-
this.documentName,
|
|
850
|
-
id,
|
|
851
|
-
'delete',
|
|
852
|
-
deletedata,
|
|
853
|
-
);
|
|
681
|
+
const result = await this.doc.deleteOne(filterIsolation).session(dbsession);
|
|
682
|
+
await this.audittrail.addEvent(appuser, this.documentName, id, 'delete', deletedata);
|
|
854
683
|
|
|
855
684
|
appuser.addDeletedRecordId(this.documentName, id);
|
|
856
685
|
const deleteresult: DeleteResultType<T> = {
|
|
857
686
|
result: result,
|
|
858
687
|
data: deletedata,
|
|
859
688
|
};
|
|
860
|
-
this.logger.debug(
|
|
861
|
-
deleteresult,
|
|
862
|
-
' delete result' + this.doc.collection.name,
|
|
863
|
-
);
|
|
689
|
+
this.logger.debug(deleteresult, ' delete result' + this.doc.collection.name);
|
|
864
690
|
// this.doc.findByIdAndDelete(id)
|
|
865
691
|
|
|
866
|
-
if (this.hooks.afterDelete)
|
|
867
|
-
await this.hooks.afterDelete(appuser, deleteresult, id);
|
|
692
|
+
if (this.hooks.afterDelete) await this.hooks.afterDelete(appuser, deleteresult, id);
|
|
868
693
|
//this.doc.findByIdAndDelete(id);
|
|
869
694
|
await this.callWebhook(appuser, 'delete', deletedata);
|
|
870
695
|
return deleteresult;
|
|
871
696
|
} else {
|
|
872
697
|
this.logger.debug('reject query', dependency);
|
|
873
698
|
|
|
874
|
-
throw new ForbiddenException(
|
|
875
|
-
`This system detected that the [${this.documentName}] data has been used in other record`,
|
|
876
|
-
'Foreignkey constraint',
|
|
877
|
-
);
|
|
699
|
+
throw new ForbiddenException(`This system detected that the [${this.documentName}] data has been used in other record`, 'Foreignkey constraint');
|
|
878
700
|
}
|
|
879
701
|
} catch (err) {
|
|
880
702
|
if (err instanceof ForbiddenException) {
|
|
@@ -889,29 +711,15 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
889
711
|
// this.doc.updateOne(data);
|
|
890
712
|
// };
|
|
891
713
|
|
|
892
|
-
findIdThenUpdate = async (
|
|
893
|
-
appuser: UserContext,
|
|
894
|
-
id: string,
|
|
895
|
-
data: T,
|
|
896
|
-
noStartTransaction: boolean = false,
|
|
897
|
-
) => {
|
|
714
|
+
findIdThenUpdate = async (appuser: UserContext, id: string, data: T, noStartTransaction: boolean = false) => {
|
|
898
715
|
try {
|
|
899
716
|
//version exists, need ensure different only 1
|
|
900
717
|
const existingdata = await this.findById(appuser, id);
|
|
901
|
-
if (!existingdata)
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
'not found',
|
|
905
|
-
);
|
|
906
|
-
|
|
907
|
-
this.logger.debug(
|
|
908
|
-
'update id:' + id,
|
|
909
|
-
this.documentName + ' findIdThenUpdate',
|
|
910
|
-
);
|
|
718
|
+
if (!existingdata) throw new NotFoundException(`${this.documentName} findIdThenUpdate: _id:${id} not found`, 'not found');
|
|
719
|
+
|
|
720
|
+
this.logger.debug('update id:' + id, this.documentName + ' findIdThenUpdate');
|
|
911
721
|
if (typeof data.__v == 'number' && data.__v != existingdata.__v) {
|
|
912
|
-
throw new BadRequestException(
|
|
913
|
-
`You submit older version data "v${data.__v}"" but latest version = "v${existingdata.__v}"`,
|
|
914
|
-
);
|
|
722
|
+
throw new BadRequestException(`You submit older version data "v${data.__v}"" but latest version = "v${existingdata.__v}"`);
|
|
915
723
|
}
|
|
916
724
|
// this.logger.debug('warn1', existingdata);
|
|
917
725
|
data.__v = existingdata.__v + 1;
|
|
@@ -919,15 +727,14 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
919
727
|
// throw new NotFoundException(`${id} not found`, 'not found');
|
|
920
728
|
// }
|
|
921
729
|
// this.logger.debug('warn2');
|
|
922
|
-
|
|
730
|
+
|
|
923
731
|
await this.identifyForeignKeys(appuser, data);
|
|
924
732
|
|
|
925
|
-
if (this.hooks.beforeUpdate)
|
|
926
|
-
await this.hooks.beforeUpdate(appuser, id, existingdata, data);
|
|
733
|
+
if (this.hooks.beforeUpdate) await this.hooks.beforeUpdate(appuser, id, existingdata, data);
|
|
927
734
|
|
|
928
735
|
const dbsession = appuser.getDBSession();
|
|
929
736
|
if (dbsession && !dbsession.inTransaction() && !noStartTransaction) {
|
|
930
|
-
dbsession.startTransaction();
|
|
737
|
+
dbsession.startTransaction({ readPreference: 'primary' });
|
|
931
738
|
}
|
|
932
739
|
// try {
|
|
933
740
|
Object.assign(data, appuser.getUpdateFilter());
|
|
@@ -948,17 +755,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
948
755
|
session: dbsession,
|
|
949
756
|
new: true,
|
|
950
757
|
});
|
|
951
|
-
await this.audittrail.addEvent(
|
|
952
|
-
appuser,
|
|
953
|
-
this.documentName,
|
|
954
|
-
id,
|
|
955
|
-
'update',
|
|
956
|
-
data,
|
|
957
|
-
);
|
|
758
|
+
await this.audittrail.addEvent(appuser, this.documentName, id, 'update', data);
|
|
958
759
|
|
|
959
760
|
appuser.addUpdatedRecordId(this.documentName, data._id);
|
|
960
|
-
if (this.hooks.afterUpdate)
|
|
961
|
-
await this.hooks.afterUpdate(appuser, id, existingdata, result);
|
|
761
|
+
if (this.hooks.afterUpdate) await this.hooks.afterUpdate(appuser, id, existingdata, result);
|
|
962
762
|
await this.callWebhook(appuser, 'update', result);
|
|
963
763
|
return result; // await this.findById(appuser, id);
|
|
964
764
|
} catch (err) {
|
|
@@ -967,28 +767,15 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
967
767
|
}
|
|
968
768
|
};
|
|
969
769
|
|
|
970
|
-
findIdThenUpdateNoIsolation = async (
|
|
971
|
-
appuser: UserContext,
|
|
972
|
-
id: string,
|
|
973
|
-
data: T,
|
|
974
|
-
) => {
|
|
770
|
+
findIdThenUpdateNoIsolation = async (appuser: UserContext, id: string, data: T) => {
|
|
975
771
|
try {
|
|
976
772
|
//version exists, need ensure different only 1
|
|
977
773
|
const existingdata = await this.findByIdNoIsolation(appuser, id);
|
|
978
|
-
if (!existingdata)
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
'not found',
|
|
982
|
-
);
|
|
983
|
-
|
|
984
|
-
this.logger.debug(
|
|
985
|
-
'update id:' + id,
|
|
986
|
-
this.documentName + ' findIdThenUpdate',
|
|
987
|
-
);
|
|
774
|
+
if (!existingdata) throw new NotFoundException(`${this.documentName} findIdThenUpdate: _id:${id} not found`, 'not found');
|
|
775
|
+
|
|
776
|
+
this.logger.debug('update id:' + id, this.documentName + ' findIdThenUpdate');
|
|
988
777
|
if (typeof data.__v == 'number' && data.__v != existingdata.__v) {
|
|
989
|
-
throw new BadRequestException(
|
|
990
|
-
`You submit older version data "v${data.__v}"" but latest version = "v${existingdata.__v}"`,
|
|
991
|
-
);
|
|
778
|
+
throw new BadRequestException(`You submit older version data "v${data.__v}"" but latest version = "v${existingdata.__v}"`);
|
|
992
779
|
}
|
|
993
780
|
// this.logger.debug('warn1', existingdata);
|
|
994
781
|
data.__v = existingdata.__v + 1;
|
|
@@ -996,15 +783,14 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
996
783
|
// throw new NotFoundException(`${id} not found`, 'not found');
|
|
997
784
|
// }
|
|
998
785
|
// this.logger.debug('warn2');
|
|
999
|
-
|
|
786
|
+
|
|
1000
787
|
await this.identifyForeignKeys(appuser, data);
|
|
1001
788
|
|
|
1002
|
-
if (this.hooks.beforeUpdate)
|
|
1003
|
-
await this.hooks.beforeUpdate(appuser, id, existingdata, data);
|
|
789
|
+
if (this.hooks.beforeUpdate) await this.hooks.beforeUpdate(appuser, id, existingdata, data);
|
|
1004
790
|
|
|
1005
791
|
const dbsession = appuser.getDBSession();
|
|
1006
792
|
if (dbsession && !dbsession.inTransaction()) {
|
|
1007
|
-
dbsession.startTransaction();
|
|
793
|
+
dbsession.startTransaction({ readPreference: 'primary' });
|
|
1008
794
|
}
|
|
1009
795
|
// try {
|
|
1010
796
|
// Object.assign(data, appuser.getUpdateFilter());
|
|
@@ -1025,17 +811,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1025
811
|
session: dbsession,
|
|
1026
812
|
new: true,
|
|
1027
813
|
});
|
|
1028
|
-
await this.audittrail.addEvent(
|
|
1029
|
-
appuser,
|
|
1030
|
-
this.documentName,
|
|
1031
|
-
id,
|
|
1032
|
-
'update',
|
|
1033
|
-
data,
|
|
1034
|
-
);
|
|
814
|
+
await this.audittrail.addEvent(appuser, this.documentName, id, 'update', data);
|
|
1035
815
|
|
|
1036
816
|
appuser.addUpdatedRecordId(this.documentName, data._id);
|
|
1037
|
-
if (this.hooks.afterUpdate)
|
|
1038
|
-
await this.hooks.afterUpdate(appuser, id, existingdata, result);
|
|
817
|
+
if (this.hooks.afterUpdate) await this.hooks.afterUpdate(appuser, id, existingdata, result);
|
|
1039
818
|
await this.callWebhook(appuser, 'update', result);
|
|
1040
819
|
return result; // await this.findById(appuser, id);
|
|
1041
820
|
} catch (err) {
|
|
@@ -1044,32 +823,24 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1044
823
|
}
|
|
1045
824
|
};
|
|
1046
825
|
|
|
1047
|
-
findIdThenPatch = async (
|
|
1048
|
-
appuser: UserContext,
|
|
1049
|
-
id: string,
|
|
1050
|
-
data: T,
|
|
1051
|
-
session: mongo.ClientSession = undefined,
|
|
1052
|
-
) => {
|
|
826
|
+
findIdThenPatch = async (appuser: UserContext, id: string, data: T, session: mongo.ClientSession = undefined) => {
|
|
1053
827
|
const existingdata = await this.findById(appuser, id);
|
|
1054
828
|
if (!existingdata) {
|
|
1055
829
|
throw new NotFoundException(`${id} not found`, 'not found');
|
|
1056
830
|
}
|
|
1057
831
|
if (typeof data.__v == 'number' && data.__v != existingdata.__v) {
|
|
1058
|
-
throw new BadRequestException(
|
|
1059
|
-
`You submit older version data "v${data.__v}"" but latest version = "v${existingdata.__v}"`,
|
|
1060
|
-
);
|
|
832
|
+
throw new BadRequestException(`You submit older version data "v${data.__v}"" but latest version = "v${existingdata.__v}"`);
|
|
1061
833
|
}
|
|
1062
834
|
|
|
1063
835
|
data.__v = existingdata.__v + 1;
|
|
1064
|
-
|
|
836
|
+
|
|
1065
837
|
await this.identifyForeignKeys(appuser, data);
|
|
1066
838
|
|
|
1067
|
-
if (this.hooks.beforeUpdate)
|
|
1068
|
-
await this.hooks.beforeUpdate(appuser, id, existingdata, data);
|
|
839
|
+
if (this.hooks.beforeUpdate) await this.hooks.beforeUpdate(appuser, id, existingdata, data);
|
|
1069
840
|
|
|
1070
841
|
const dbsession = appuser.getDBSession();
|
|
1071
842
|
if (dbsession && !dbsession.inTransaction()) {
|
|
1072
|
-
dbsession.startTransaction();
|
|
843
|
+
dbsession.startTransaction({ readPreference: 'primary' });
|
|
1073
844
|
}
|
|
1074
845
|
// try {
|
|
1075
846
|
Object.assign(data, appuser.getUpdateFilter());
|
|
@@ -1094,17 +865,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1094
865
|
session: dbsession,
|
|
1095
866
|
new: true,
|
|
1096
867
|
});
|
|
1097
|
-
await this.audittrail.addEvent(
|
|
1098
|
-
appuser,
|
|
1099
|
-
this.documentName,
|
|
1100
|
-
id,
|
|
1101
|
-
'patch',
|
|
1102
|
-
data,
|
|
1103
|
-
);
|
|
868
|
+
await this.audittrail.addEvent(appuser, this.documentName, id, 'patch', data);
|
|
1104
869
|
appuser.addUpdatedRecordId(this.documentName, data._id);
|
|
1105
870
|
|
|
1106
|
-
if (this.hooks.afterUpdate)
|
|
1107
|
-
await this.hooks.afterUpdate(appuser, id, existingdata, result);
|
|
871
|
+
if (this.hooks.afterUpdate) await this.hooks.afterUpdate(appuser, id, existingdata, result);
|
|
1108
872
|
await this.callWebhook(appuser, 'update', result);
|
|
1109
873
|
return result; //await this.findById(appuser, id);
|
|
1110
874
|
} catch (err) {
|
|
@@ -1144,10 +908,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1144
908
|
session: appuser.getDBSession(),
|
|
1145
909
|
});
|
|
1146
910
|
if (result) {
|
|
1147
|
-
this.logger.error(
|
|
1148
|
-
result,
|
|
1149
|
-
`related result found in ${collectionname} ${fkey} = ${id}`,
|
|
1150
|
-
);
|
|
911
|
+
this.logger.error(result, `related result found in ${collectionname} ${fkey} = ${id}`);
|
|
1151
912
|
return result;
|
|
1152
913
|
}
|
|
1153
914
|
}
|
|
@@ -1170,62 +931,34 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1170
931
|
* @param docstatus
|
|
1171
932
|
* @returns Promise
|
|
1172
933
|
*/
|
|
1173
|
-
async setDocumentStatus(
|
|
1174
|
-
appuser: UserContext,
|
|
1175
|
-
id: string,
|
|
1176
|
-
data: T,
|
|
1177
|
-
docstatus: string,
|
|
1178
|
-
) {
|
|
934
|
+
async setDocumentStatus(appuser: UserContext, id: string, data: T, docstatus: string) {
|
|
1179
935
|
id = id.trim();
|
|
1180
936
|
|
|
1181
937
|
if (!id) {
|
|
1182
|
-
throw new BadRequestException(
|
|
1183
|
-
'undefined path para "id"',
|
|
1184
|
-
'undefined "id"',
|
|
1185
|
-
);
|
|
938
|
+
throw new BadRequestException('undefined path para "id"', 'undefined "id"');
|
|
1186
939
|
}
|
|
1187
940
|
if (data['_id'] && data['_id'] != id) {
|
|
1188
|
-
throw new BadRequestException(
|
|
1189
|
-
`_id in data(${data['_id']} different with path param ${id})`,
|
|
1190
|
-
'set documentstatus id not match with submited data',
|
|
1191
|
-
);
|
|
941
|
+
throw new BadRequestException(`_id in data(${data['_id']} different with path param ${id})`, 'set documentstatus id not match with submited data');
|
|
1192
942
|
}
|
|
1193
943
|
const existdata = await this.findById(appuser, id);
|
|
1194
944
|
if (existdata && existdata['documentStatus'] == docstatus) {
|
|
1195
|
-
throw new BadRequestException(
|
|
1196
|
-
`Same document status "${docstatus}" is not allowed`,
|
|
1197
|
-
);
|
|
945
|
+
throw new BadRequestException(`Same document status "${docstatus}" is not allowed`);
|
|
1198
946
|
}
|
|
1199
947
|
data['documentStatus'] = docstatus;
|
|
1200
948
|
// await this.hook(appuser, HookType.beforeSetStatus, data);
|
|
1201
|
-
if (this.hooks.beforeSetStatus)
|
|
1202
|
-
await this.hooks.beforeSetStatus(appuser, docstatus, data, existdata);
|
|
949
|
+
if (this.hooks.beforeSetStatus) await this.hooks.beforeSetStatus(appuser, docstatus, data, existdata);
|
|
1203
950
|
|
|
1204
951
|
if (data && !data['created']) {
|
|
1205
952
|
const createresult = await this.create(appuser, data);
|
|
1206
|
-
if (this.hooks.afterSetStatus)
|
|
1207
|
-
|
|
1208
|
-
await this.audittrail.addEvent(
|
|
1209
|
-
appuser,
|
|
1210
|
-
this.documentName,
|
|
1211
|
-
id,
|
|
1212
|
-
docstatus,
|
|
1213
|
-
data,
|
|
1214
|
-
);
|
|
953
|
+
if (this.hooks.afterSetStatus) await this.hooks.afterSetStatus(appuser, docstatus, createresult);
|
|
954
|
+
await this.audittrail.addEvent(appuser, this.documentName, id, docstatus, data);
|
|
1215
955
|
|
|
1216
956
|
return createresult;
|
|
1217
957
|
} else {
|
|
1218
958
|
const updateresult = await this.findIdThenPatch(appuser, id, data);
|
|
1219
959
|
const finaldata = await this.findById(appuser, id);
|
|
1220
|
-
if (this.hooks.afterSetStatus)
|
|
1221
|
-
|
|
1222
|
-
await this.audittrail.addEvent(
|
|
1223
|
-
appuser,
|
|
1224
|
-
this.documentName,
|
|
1225
|
-
id,
|
|
1226
|
-
docstatus,
|
|
1227
|
-
data,
|
|
1228
|
-
);
|
|
960
|
+
if (this.hooks.afterSetStatus) await this.hooks.afterSetStatus(appuser, docstatus, finaldata);
|
|
961
|
+
await this.audittrail.addEvent(appuser, this.documentName, id, docstatus, data);
|
|
1229
962
|
|
|
1230
963
|
await this.callWebhook(appuser, docstatus, finaldata);
|
|
1231
964
|
return updateresult;
|
|
@@ -1274,33 +1007,18 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1274
1007
|
if (result?.name && result?.name.includes('Exception')) throw result;
|
|
1275
1008
|
return result;
|
|
1276
1009
|
}
|
|
1277
|
-
startWorkflow(
|
|
1278
|
-
appuser
|
|
1279
|
-
processName: WorkflowName,
|
|
1280
|
-
workflowData: any,
|
|
1281
|
-
) {
|
|
1282
|
-
return this.eventEmitter.emit(
|
|
1283
|
-
'workflow.start',
|
|
1284
|
-
appuser,
|
|
1285
|
-
processName,
|
|
1286
|
-
workflowData,
|
|
1287
|
-
);
|
|
1010
|
+
startWorkflow(appuser: UserContext, processName: WorkflowName, workflowData: any) {
|
|
1011
|
+
return this.eventEmitter.emit('workflow.start', appuser, processName, workflowData);
|
|
1288
1012
|
}
|
|
1289
1013
|
|
|
1290
1014
|
async genNewDocNo(appuser: UserContext, data: T) {
|
|
1291
1015
|
this.logger.debug('genNewDocNo');
|
|
1292
|
-
const result = await this.docnogenerator.generateNextNumberFromDocument(
|
|
1293
|
-
appuser,
|
|
1294
|
-
this.documentType,
|
|
1295
|
-
data,
|
|
1296
|
-
);
|
|
1016
|
+
const result = await this.docnogenerator.generateNextNumberFromDocument(appuser, this.documentType, data);
|
|
1297
1017
|
this.logger.debug(result, 'genNewDocNo');
|
|
1298
1018
|
data[this.documentIdentityCode] = result;
|
|
1299
1019
|
}
|
|
1300
1020
|
async runDefault(appuser: UserContext): Promise<unknown> {
|
|
1301
|
-
return (
|
|
1302
|
-
'Hello this is ' + this.getDocumentType() + ': ' + this.getDocumentName()
|
|
1303
|
-
);
|
|
1021
|
+
return 'Hello this is ' + this.getDocumentType() + ': ' + this.getDocumentName();
|
|
1304
1022
|
}
|
|
1305
1023
|
async identifyForeignKeys(appuser: UserContext, data: T) {
|
|
1306
1024
|
/**
|
|
@@ -1322,9 +1040,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1322
1040
|
let results: string[] = [];
|
|
1323
1041
|
fks.forEach((fieldpath) => {
|
|
1324
1042
|
//console.log("fieldpath:",fieldpath,"vdata",data,vdata)
|
|
1325
|
-
const tmp = jsonpath
|
|
1326
|
-
.query(vdata, fieldpath)
|
|
1327
|
-
.filter((item: string) => item != '');
|
|
1043
|
+
const tmp = jsonpath.query(vdata, fieldpath).filter((item: string) => item != '');
|
|
1328
1044
|
// console.log("tmp",tmp)
|
|
1329
1045
|
|
|
1330
1046
|
results = results.concat(tmp);
|
|
@@ -1342,11 +1058,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1342
1058
|
const stagefilter: PipelineStage = {
|
|
1343
1059
|
$unionWith: {
|
|
1344
1060
|
coll: collectionname,
|
|
1345
|
-
pipeline: [
|
|
1346
|
-
{ $match: { _id: { $in: results } } },
|
|
1347
|
-
addfield,
|
|
1348
|
-
{ $project: { collection: 1 } },
|
|
1349
|
-
],
|
|
1061
|
+
pipeline: [{ $match: { _id: { $in: results } } }, addfield, { $project: { collection: 1 } }],
|
|
1350
1062
|
},
|
|
1351
1063
|
};
|
|
1352
1064
|
pipelines.push(stagefilter);
|
|
@@ -1358,10 +1070,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1358
1070
|
|
|
1359
1071
|
if (!unionresult) {
|
|
1360
1072
|
this.logger.error('foreign key control failed ', 'identifyForeignKeys');
|
|
1361
|
-
throw new InternalServerErrorException(
|
|
1362
|
-
'Foreignkey check execution error',
|
|
1363
|
-
pipelines as HttpExceptionOptions,
|
|
1364
|
-
);
|
|
1073
|
+
throw new InternalServerErrorException('Foreignkey check execution error', pipelines as HttpExceptionOptions);
|
|
1365
1074
|
} else {
|
|
1366
1075
|
const searchresult: any = {};
|
|
1367
1076
|
unionresult.forEach((item) => {
|
|
@@ -1382,26 +1091,15 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1382
1091
|
}
|
|
1383
1092
|
for (let k = 0; k < keys.length; k++) {
|
|
1384
1093
|
const key = keys[k];
|
|
1385
|
-
if (
|
|
1386
|
-
searchresult[collectionname] &&
|
|
1387
|
-
searchresult[collectionname].includes(key)
|
|
1388
|
-
) {
|
|
1094
|
+
if (searchresult[collectionname] && searchresult[collectionname].includes(key)) {
|
|
1389
1095
|
this.logger.debug(`foreignkey ${collectionname}->${key} exists`);
|
|
1390
1096
|
} else if (appuser.searchInsertedRecordId(collectionname, key)) {
|
|
1391
|
-
this.logger.debug(
|
|
1392
|
-
`foreignkey ${collectionname} exists in user context which not yet commited`,
|
|
1393
|
-
);
|
|
1097
|
+
this.logger.debug(`foreignkey ${collectionname} exists in user context which not yet commited`);
|
|
1394
1098
|
} else {
|
|
1395
|
-
this.logger.warn(
|
|
1396
|
-
`${this.documentType}: Foreignkey ${key} at collection ${collectionname} does not exist`,
|
|
1397
|
-
'identifyForeignKeys',
|
|
1398
|
-
);
|
|
1099
|
+
this.logger.warn(`${this.documentType}: Foreignkey ${key} at collection ${collectionname} does not exist`, 'identifyForeignKeys');
|
|
1399
1100
|
this.logger.debug(appuser.getModifieds, 'appuser.getModifieds');
|
|
1400
1101
|
const errordata = { key: key, collection: collectionname };
|
|
1401
|
-
throw new BadRequestException(
|
|
1402
|
-
`${this.documentType}: Foreignkey ${key} at collection ${collectionname} does not exist`,
|
|
1403
|
-
JSON.stringify(errordata),
|
|
1404
|
-
);
|
|
1102
|
+
throw new BadRequestException(`${this.documentType}: Foreignkey ${key} at collection ${collectionname} does not exist`, JSON.stringify(errordata));
|
|
1405
1103
|
}
|
|
1406
1104
|
}
|
|
1407
1105
|
}
|
|
@@ -1413,10 +1111,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1413
1111
|
return pdfresult;
|
|
1414
1112
|
}
|
|
1415
1113
|
|
|
1416
|
-
async checkMultipleUnionExist(
|
|
1417
|
-
appuser: UserContext,
|
|
1418
|
-
data: string[],
|
|
1419
|
-
): Promise<CheckMutipleUnionExistResponse> {
|
|
1114
|
+
async checkMultipleUnionExist(appuser: UserContext, data: string[]): Promise<CheckMutipleUnionExistResponse> {
|
|
1420
1115
|
const response: CheckMutipleUnionExistResponse = [];
|
|
1421
1116
|
const unionKey = this.getDocumentIdentityCode();
|
|
1422
1117
|
const searchQuery: any = { [unionKey]: { $in: data } };
|
|
@@ -1430,13 +1125,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1430
1125
|
return response;
|
|
1431
1126
|
}
|
|
1432
1127
|
|
|
1433
|
-
searchToAggregate(
|
|
1434
|
-
appuser: UserContext,
|
|
1435
|
-
filter: FilterQuery<T>,
|
|
1436
|
-
columns: string[],
|
|
1437
|
-
sort: string[][],
|
|
1438
|
-
lookup: { [key: string]: string },
|
|
1439
|
-
) {
|
|
1128
|
+
searchToAggregate(appuser: UserContext, filter: FilterQuery<T>, columns: string[], sort: string[][], lookup: { [key: string]: string }) {
|
|
1440
1129
|
const pipelines: PipelineStage[] = [];
|
|
1441
1130
|
const projection = {};
|
|
1442
1131
|
// console.log('sortsort', sort);
|
|
@@ -1470,8 +1159,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1470
1159
|
if (Object.keys(projection).length > 0) projection['_' + to] = 1;
|
|
1471
1160
|
});
|
|
1472
1161
|
|
|
1473
|
-
if (Object.keys(projection).length > 0)
|
|
1474
|
-
pipelines.push({ $project: projection });
|
|
1162
|
+
if (Object.keys(projection).length > 0) pipelines.push({ $project: projection });
|
|
1475
1163
|
|
|
1476
1164
|
if (Array.isArray(sort) && sort.length > 0) {
|
|
1477
1165
|
const sortobj = {};
|
|
@@ -1485,16 +1173,12 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
|
|
|
1485
1173
|
return pipelines;
|
|
1486
1174
|
}
|
|
1487
1175
|
|
|
1488
|
-
|
|
1489
1176
|
//only realtime webhook supported at this moment
|
|
1490
1177
|
async callWebhook(appuser: UserContext, actionName: string, data: any) {
|
|
1491
|
-
try{
|
|
1492
|
-
await this.runWebHook.run(appuser,this.documentName, actionName,data)
|
|
1493
|
-
}
|
|
1494
|
-
catch(e)
|
|
1495
|
-
{
|
|
1178
|
+
try {
|
|
1179
|
+
await this.runWebHook.run(appuser, this.documentName, actionName, data);
|
|
1180
|
+
} catch (e) {
|
|
1496
1181
|
throw new InternalServerErrorException(e);
|
|
1497
1182
|
}
|
|
1498
|
-
|
|
1499
1183
|
}
|
|
1500
1184
|
}
|