@contrail/flexplm 1.1.13 → 1.1.15

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 (68) hide show
  1. package/.github/pull_request_template.md +30 -0
  2. package/.github/workflows/flexplm-lib.yml +27 -0
  3. package/lib/flexplm-utils.spec.d.ts +1 -0
  4. package/lib/flexplm-utils.spec.js +26 -0
  5. package/lib/publish/base-process-publish-assortment.spec.d.ts +1 -0
  6. package/lib/publish/base-process-publish-assortment.spec.js +1053 -0
  7. package/lib/util/config-defaults.spec.d.ts +1 -0
  8. package/lib/util/config-defaults.spec.js +264 -0
  9. package/lib/util/data-converter.d.ts +4 -0
  10. package/lib/util/data-converter.js +88 -1
  11. package/lib/util/data-converter.spec.d.ts +1 -0
  12. package/lib/util/data-converter.spec.js +591 -0
  13. package/lib/util/map-utils.d.ts +2 -2
  14. package/lib/util/map-utils.js +5 -28
  15. package/lib/util/map-utils.spec.d.ts +1 -0
  16. package/lib/util/map-utils.spec.js +89 -0
  17. package/lib/util/thumbnail-util.spec.d.ts +1 -0
  18. package/lib/util/thumbnail-util.spec.js +132 -0
  19. package/lib/util/type-conversion-utils-spec-mockData.js +21 -0
  20. package/lib/util/type-conversion-utils.d.ts +7 -0
  21. package/lib/util/type-conversion-utils.js +88 -4
  22. package/lib/util/type-conversion-utils.spec.d.ts +1 -0
  23. package/lib/util/type-conversion-utils.spec.js +547 -0
  24. package/lib/util/type-defaults.d.ts +5 -0
  25. package/lib/util/type-defaults.js +66 -0
  26. package/lib/util/type-defaults.spec.d.ts +1 -0
  27. package/lib/util/type-defaults.spec.js +460 -0
  28. package/lib/util/type-utils.spec.d.ts +1 -0
  29. package/lib/util/type-utils.spec.js +190 -0
  30. package/package.json +2 -2
  31. package/publish.bat +5 -0
  32. package/publish.sh +5 -0
  33. package/src/entity-processor/base-entity-processor.ts +183 -0
  34. package/src/flexplm-request.ts +28 -0
  35. package/src/flexplm-utils.spec.ts +27 -0
  36. package/src/flexplm-utils.ts +29 -0
  37. package/src/index.ts +20 -0
  38. package/src/interfaces/interfaces.ts +120 -0
  39. package/src/interfaces/item-family-changes.ts +67 -0
  40. package/src/interfaces/publish-change-data.ts +43 -0
  41. package/src/publish/base-process-publish-assortment-callback.ts +23 -0
  42. package/src/publish/base-process-publish-assortment.spec.ts +1239 -0
  43. package/src/publish/base-process-publish-assortment.ts +1024 -0
  44. package/src/publish/mockData.ts +4561 -0
  45. package/src/transform/identifier-conversion.ts +226 -0
  46. package/src/util/config-defaults.spec.ts +315 -0
  47. package/src/util/config-defaults.ts +79 -0
  48. package/src/util/data-converter-spec-mockData.ts +231 -0
  49. package/src/util/data-converter.spec.ts +872 -0
  50. package/src/util/data-converter.ts +507 -0
  51. package/src/util/federation.ts +172 -0
  52. package/src/util/flexplm-connect.ts +169 -0
  53. package/src/util/logger-config.ts +20 -0
  54. package/src/util/map-util-spec-mockData.ts +231 -0
  55. package/src/util/map-utils.spec.ts +103 -0
  56. package/src/util/map-utils.ts +40 -0
  57. package/src/util/mockData.ts +98 -0
  58. package/src/util/thumbnail-util.spec.ts +152 -0
  59. package/src/util/thumbnail-util.ts +128 -0
  60. package/src/util/type-conversion-utils-spec-mockData.ts +238 -0
  61. package/src/util/type-conversion-utils.spec.ts +601 -0
  62. package/src/util/type-conversion-utils.ts +345 -0
  63. package/src/util/type-defaults.spec.ts +592 -0
  64. package/src/util/type-defaults.ts +261 -0
  65. package/src/util/type-utils.spec.ts +227 -0
  66. package/src/util/type-utils.ts +124 -0
  67. package/tsconfig.json +27 -0
  68. package/tslint.json +57 -0
@@ -0,0 +1,507 @@
1
+ import { Entities, TypeClientOptions } from '@contrail/sdk';
2
+ import { TypeUtils } from './type-utils';
3
+ import { FCConfig } from '../interfaces/interfaces';
4
+ import { MapFileUtil } from '@contrail/transform-data';
5
+ import { Logger } from '@contrail/app-framework';
6
+ import { ObjectDiff, ObjectUtil } from '@contrail/util';
7
+ import { TypeConversionUtils } from './type-conversion-utils';
8
+ import { MapUtil } from './map-utils';
9
+
10
+ export class DataConverter {
11
+ private typeUtils: TypeUtils;
12
+ private transformMapFile: string;
13
+ private useDisplayForEnumerationMatching = false;
14
+ private objRefCache = {};
15
+ private userRefCache = {};
16
+ constructor(private config: FCConfig, private mapFileUtil: MapFileUtil){
17
+ this.typeUtils = new TypeUtils();
18
+ this.transformMapFile = this.config['transformMapFile'];
19
+ this.useDisplayForEnumerationMatching = this.config['dataConverter']
20
+ && this.config['dataConverter']['useDisplayForEnumerationMatching'];
21
+ }
22
+
23
+ async getFlexPLMObjectDataFromEvent(event, dataToSkip: string[]) {
24
+ return this.getFlexPLMObjectData(event.newData, dataToSkip, true);
25
+ }
26
+
27
+ async getFlexPLMObjectData(newData, dataToSkip: string[], inflateObjRef: boolean) {
28
+ if(Logger.isDebugOn()) {
29
+ console.debug('newData: ' + JSON.stringify(newData));
30
+ }
31
+ //Using event to get propertyDiffs to find emptied values
32
+ //Add standard atts to skip
33
+ dataToSkip = dataToSkip.concat(['updatedOn', 'updatedById', 'createdOn', 'createdById', 'modifiedAt', 'orgId', 'createdAt', 'id', 'typeId', 'workspaceId']);
34
+ // const oldData = event.oldData;
35
+ const data = {};
36
+ const typeId = newData?.typeId;
37
+ if (!typeId) {
38
+ return;// Don't have a type; so can't process
39
+ }
40
+ data['typePath'] = newData['typePath'];
41
+ const type = await this.typeUtils.getTypeById(typeId);
42
+ const typeProps = this.typeUtils.filterTypeProperties(type, newData);
43
+ for(const prop of typeProps){
44
+ // if(this.logger.isTraceOn()){
45
+ // this.logger.log('prop: ' + JSON.stringify(prop));
46
+ // }
47
+ const slug = prop['slug'];
48
+ if (dataToSkip.includes(slug)) {
49
+ continue;
50
+ }
51
+ data[slug] = await this.getFlexPLMValue(prop, newData, inflateObjRef);
52
+ }
53
+
54
+ if(Logger.isDebugOn()) {
55
+ console.debug('getFlexPLMObjectData-data: ' + JSON.stringify(data));
56
+ }
57
+ return data;
58
+
59
+ }
60
+
61
+ async getFlexPLMValue(prop, newData, inflateObjRef: boolean) {
62
+ const propertyType = prop['propertyType'];
63
+ const slug = prop['slug'];
64
+ const nd = newData[slug];
65
+ // console.log('getFlexPLMValue: ' + propertyType + ', ' +slug + ', ' + nd + ', ' + od);
66
+ let value;
67
+ if(['string', 'text'].includes(propertyType)){
68
+ value = nd || '';
69
+ }else if(['number', 'currency', 'percent', 'sequence'].includes(propertyType)){
70
+ value = nd || 0;
71
+ }else if('date' === propertyType){
72
+ if(nd){
73
+ value = nd;
74
+ // const d = new Date(nd);
75
+ // console.log('Date.getTimezoneOffset(): ' + d.getTimezoneOffset());
76
+ // value = d.toISOString();
77
+ // console.log('date: ' + nd + ' -- ' + value);
78
+ } else {
79
+ value = null;
80
+ }
81
+ }else if('boolean' === propertyType){
82
+ value =(nd)? true: false;
83
+ }else if('choice' === propertyType){
84
+ value = this.getEnumerationValue(prop, nd);
85
+ }else if('multi_select' === propertyType){
86
+ value = this.getEnumerationValue(prop, nd);
87
+ }else if('object_reference' === propertyType){
88
+ value = await this.getObjectReferenceValue(prop, newData, inflateObjRef);
89
+ if(Logger.isDebugOn()){
90
+ console.debug('object_reference: ' + JSON.stringify(value));
91
+ }
92
+ } else if ('image' === propertyType) {
93
+ // console.log('image-TODO');
94
+ }else if('formula' === propertyType){
95
+ value = nd;
96
+ }else if('json' === propertyType){
97
+ // console.log('json-TODO');
98
+ value = nd;
99
+ } else if ('userList' === propertyType) {
100
+ value = await this.getUserListValue(prop, newData);
101
+ }
102
+
103
+ return value;
104
+
105
+ }
106
+ /** Returns the display values for list properties (choice & multi_select)
107
+ *
108
+ * @param prop
109
+ * @param newData
110
+ * @returns
111
+ */
112
+ getEnumerationValue(prop, nd){
113
+ const propertyType = prop['propertyType'];
114
+ let value;
115
+ if(['choice', 'multi_select'].includes(propertyType)){
116
+ const options: [{value:string, display:string}] = prop['options'] || [];
117
+ if('choice' === propertyType){
118
+ if(nd){
119
+ const option = options.find(option => option.value == nd );
120
+ if(option){
121
+ value = Object.assign({},option);
122
+ }
123
+ }
124
+ if(!value) {
125
+ value = {};
126
+ }
127
+ } else if ('multi_select' === propertyType) {
128
+ value = [];
129
+ if (nd instanceof Array) {
130
+ nd.forEach(key => {
131
+ const optionObject = options.find(option => option.value == key);
132
+ if(optionObject){
133
+ const option = Object.assign({},optionObject);
134
+ value.push(option);
135
+ }
136
+ });
137
+ } else if( typeof nd === 'string' && '' !== nd) {
138
+ const optionObject = options.find(option => option.value == nd);
139
+ if(optionObject){
140
+ const option = Object.assign({},optionObject);
141
+ value.push(option);
142
+ }
143
+ }
144
+ }
145
+ }
146
+ return value;
147
+ }
148
+
149
+ public async getObjectReferenceValue(prop: any, newData: any, inflateObjRef = false) {
150
+ const slug = prop['slug'];
151
+ if(Logger.isDebugOn()) {
152
+ console.debug('getObjectReferenceValue-prop: ' + slug);
153
+ }
154
+ let value = newData[slug];
155
+ const entityType = prop['referencedTypeRootSlug'];
156
+ const entityId = newData[slug + 'Id'];
157
+ if ((!value || typeof value === 'string' )&& inflateObjRef) {
158
+ if (entityId) {
159
+ if(this.objRefCache[entityId]){
160
+ if(Logger.isDebugOn()) {
161
+ console.debug('cache hit: ' + entityId);
162
+ }
163
+ return this.objRefCache[entityId];
164
+ }
165
+ const criteria = {
166
+ id: entityId
167
+ };
168
+ const entities = await new Entities().get({
169
+ entityName: entityType,
170
+ criteria
171
+ });
172
+ value = (entities && entities[0]) ? entities[0] : undefined;
173
+ }
174
+ }
175
+
176
+ if(value && !(typeof value === 'string')){
177
+ const unprocessedValue = value;
178
+ const objectClass = await TypeConversionUtils.getObjectClass(this.transformMapFile, this.mapFileUtil, unprocessedValue);
179
+ const flexPLMTypePath = await TypeConversionUtils.getObjectTypePath(this.transformMapFile, this.mapFileUtil, unprocessedValue);
180
+ value = await this.getFlexPLMObjectData(value, [], false);
181
+ value['entityReference'] = entityType + ':' + entityId;
182
+ value['objectClass'] = objectClass;
183
+ value['flexPLMTypePath'] = flexPLMTypePath;
184
+
185
+ if(this.transformMapFile){
186
+ const mapKey = await TypeConversionUtils.getMapKey(this.transformMapFile, this.mapFileUtil, unprocessedValue, TypeConversionUtils.VIBE2FLEX_DIRECTION);
187
+ value = await MapUtil.applyTransformMap(this.transformMapFile, this.mapFileUtil, value, mapKey, TypeConversionUtils.VIBE2FLEX_DIRECTION)
188
+ }
189
+
190
+ } else {
191
+ value = {};
192
+ }
193
+ this.objRefCache[entityId] = value;
194
+ return value;
195
+ }
196
+
197
+ /** (Deprecated) Use TypeConversionUtils.getMapKey()
198
+ * Will return the class to use to get mapping.
199
+ * This is needed because mappings will be different for different sub types
200
+ * of custom-entity
201
+ *
202
+ * @param obj: Entity being checked
203
+ * @param mapping: The whole mapping file
204
+ */
205
+ getMappingClass(entity: object, mapping: any): string{
206
+ const entityTypePath = entity['typePath'];
207
+ const typeMapKey = mapping['typeMapKey'];
208
+ let objClass = typeMapKey[entityTypePath];
209
+ const entityType = entity['entityType'];
210
+
211
+ if(!objClass){
212
+ objClass = this.typeUtils.getEventObjectClass(entityType, entity);
213
+ }
214
+ if(!objClass){
215
+ objClass = entityType;
216
+ }
217
+ return objClass;
218
+ }
219
+
220
+ /** Sets entity values from FlexPLM data passed in
221
+ * Assumes the entity has a VibeIQ typeId and 'roles' value to filter if necessary.
222
+ * @param entity the entity to update
223
+ * @param data the FlexPLM data
224
+ * @param keysToSkip properties to skip
225
+ * @returns the modified entity with VibeIQ values
226
+ */
227
+ async setEntityValues(entity, data, keysToSkip: string[] = []){
228
+ // this.logger.log('setEntityValues: ' + JSON.stringify(entity));
229
+ // this.logger.log('data: ' + JSON.stringify(data));
230
+ const type = await this.typeUtils.getTypeById(entity.typeId);
231
+ keysToSkip = keysToSkip.concat(['updatedOn', 'updatedById', 'createdOn', 'createdById', 'modifiedAt', 'orgId', 'createdAt', 'id', 'typeId', 'workspaceId']);
232
+ let typeProps = this.typeUtils.filterTypeProperties(type, entity);
233
+ typeProps = typeProps.filter( prop => !keysToSkip.includes(prop['slug']));
234
+ //Only process properties that had a value sent; to not accidentally clear out values
235
+ //for properties that weren't sent.
236
+ const dataKeys = Object.getOwnPropertyNames(data);
237
+ typeProps = typeProps.filter( prop => dataKeys.includes(prop['slug']));
238
+
239
+ for(const prop of typeProps){
240
+ const propertyType = prop['propertyType'];
241
+ const slug = prop['slug'];
242
+ let keyName = slug;
243
+ if(propertyType === 'userList') {
244
+ keyName = slug + 'Id';
245
+ }
246
+ entity[keyName] = await this.getEntityValue(prop, data);
247
+ // console.log('entity[slug]: ' + entity[slug]);
248
+ }
249
+
250
+ return entity;
251
+
252
+ }
253
+
254
+ /** Gets the entity values from FlexPLM data
255
+ * Assumes there isn't a VibeIQ typeId, so uses FlexPLM data to determine type
256
+ * @param objectClass FlexPLM object class
257
+ * @param data object data
258
+ * @param keysToSkip type properties to not process
259
+ * @returns object with VibeIQ values
260
+ */
261
+ async getEntityValues(objectClass: string, data: any, keysToSkip: string[] = []){
262
+ const entityValues = {};
263
+ const tco: TypeClientOptions = this.typeUtils.getEntityTypeClientOptions(objectClass,data);
264
+ const type = await this.typeUtils.getByRootAndPath(tco);
265
+ const typePath = type['typePath'];
266
+ if(typePath && (typePath.startsWith('item') || typePath.startsWith('project-item'))){
267
+ if(['LCSProduct', 'LCSProductSeasonLink'].includes(objectClass)){
268
+ entityValues['roles'] = ['family'];
269
+ }else{
270
+ entityValues['roles'] = ['color', 'option'];
271
+ }
272
+ }
273
+
274
+ let typeProps = this.typeUtils.filterTypeProperties(type, entityValues);
275
+ typeProps = typeProps.filter( prop => !keysToSkip.includes(prop['slug']));
276
+
277
+ for(const prop of typeProps){
278
+ const slug = prop['slug'];
279
+ const value = await this.getEntityValue(prop, data);
280
+ if(value){
281
+ entityValues[slug] = value;
282
+ }
283
+ }
284
+
285
+ return entityValues;
286
+ }
287
+
288
+ /** Gets the VibeIQ value for the property from data
289
+ *
290
+ * @param prop the VibeIQ property
291
+ * @param data the FlexPLM data
292
+ * @returns value to be set in VibeIQ
293
+ */
294
+ async getEntityValue(prop, data) {
295
+ const propertyType = prop['propertyType'];
296
+ const slug = prop['slug'];
297
+ const nd = data[slug];
298
+ // this.logger.log('getValue: ' + propertyType + ', ' +slug + ', ' + nd);
299
+
300
+ let value;
301
+ if (['string', 'text'].includes(propertyType)) {
302
+ value = nd;
303
+ }else if(['number', 'currency', 'percent', 'sequence'].includes(propertyType)){
304
+ value = (null === nd)? 0 : nd;
305
+ }else if('date' === propertyType){
306
+ if(nd){
307
+ // const offset = new Date(nd).getTimezoneOffset() * 60 * 1_000;
308
+ // this.logger.log('nd: ' + nd);
309
+ // this.logger.log(offset);
310
+ // this.logger.log('No Offset: ' + new Date(nd).toISOString());
311
+ // const d = new Date(nd + offset);// Take system Timezone into account.
312
+ const d = new Date(nd);
313
+ value = d.toISOString();
314
+
315
+ } else {
316
+ value = null;
317
+ }
318
+ }else if('boolean' === propertyType){
319
+ value =(nd)? true: false;
320
+ }else if('choice' === propertyType){
321
+ value = this.setEnumerationKeys(prop, nd, this.useDisplayForEnumerationMatching);
322
+ }else if('multi_select' === propertyType){
323
+ value = this.setEnumerationKeys(prop, nd, this.useDisplayForEnumerationMatching);
324
+
325
+ } else if ('object_reference' === propertyType) {
326
+ //TODO write code
327
+ //use referencedTypeRootSlug to get the entity type
328
+ } else if ('image' === propertyType) {
329
+ // console.log('TODO-image');
330
+ } else if ('formula' === propertyType) {
331
+ // console.log('TODO-formula');
332
+ } else if ('json' === propertyType) {
333
+ // console.log('TODO-json');
334
+ } else if ('userList' === propertyType) {
335
+ value = await this.setUserListValue(prop, nd);
336
+ }
337
+
338
+ // console.log(value);
339
+ return value;
340
+ }
341
+
342
+ setEnumerationKeys(prop, nd, matchByDisplay) {
343
+ const propertyType = prop['propertyType'];
344
+ let value;
345
+ if(['choice', 'multi_select'].includes(propertyType)){
346
+ //If there are no options, use empty array to not error out and don't set anything
347
+ const options: [{value:string, display:string}] = prop['options'] || [];
348
+ if('choice' === propertyType){
349
+ if(nd){
350
+ const matchKey = (matchByDisplay)? 'display' : 'value';
351
+ const option = options.find(option => option[matchKey] == nd[matchKey] );
352
+ if(option){
353
+ value = option.value;
354
+ }
355
+ } else {
356
+ value = undefined;
357
+ }
358
+ }else if('multi_select' === propertyType){
359
+ value = [];
360
+ const matchKey = (matchByDisplay)? 'display' : 'value';
361
+ if(nd instanceof Array){
362
+ nd.forEach(selectedOpt =>{
363
+ const optionObject = options.find(option => option[matchKey] == selectedOpt[matchKey]);
364
+ if(optionObject){
365
+ const option = optionObject.value;
366
+ value.push(option);
367
+ }
368
+ });
369
+
370
+ }
371
+ }
372
+ }
373
+ return value;
374
+ }
375
+
376
+ /** Compares the potential changes to the entity and returns only the actual differences.
377
+ *
378
+ * @param entity the full entity
379
+ * @param changes the potential changes
380
+ * @returns only the change values that are different from the entity's value
381
+ */
382
+ getPersistableChanges(entity: object, changes: object): object {
383
+ const entityCompareValues = {};
384
+ for(const key of (Object.getOwnPropertyNames(changes))){
385
+ entityCompareValues[key] = entity[key];
386
+ }
387
+ const diffs: ObjectDiff[] = ObjectUtil.compareDeep(entityCompareValues, changes, '');
388
+ const diffValues = {};
389
+ if(diffs && diffs.length > 0){
390
+ for(const diff of diffs){
391
+ diffValues[diff.propertyName] = diff.newValue;
392
+ }
393
+ }
394
+ return diffValues;
395
+
396
+ }
397
+
398
+ /** Sets userListId value from FlexPLM data passed in
399
+ *
400
+ * @param prop the VibeIQ property
401
+ * @param nd the VibeIQ data
402
+ * @returns the modified entity with FlexPLM values
403
+ */
404
+ async setUserListValue(prop, nd) {
405
+ if(!nd?.email) {
406
+ return "";
407
+ }
408
+
409
+ if (this.userRefCache[nd.email]) {
410
+ if (Logger.isDebugOn()) {
411
+ console.debug('user cache hit: ' + nd.email);
412
+ }
413
+
414
+ await this.processGroupMemberCheck(prop, nd.email);
415
+ return this.userRefCache[nd.email];
416
+ }
417
+
418
+ const entities = await new Entities().get({
419
+ entityName: 'user-org',
420
+ take: 1000
421
+ });
422
+
423
+ const result = entities.find(element => element['userEmail'] === nd.email);
424
+ const value = (result) ? result.id : undefined;
425
+
426
+ if(value) {
427
+ this.userRefCache[nd.email] = value;
428
+ await this.processGroupMemberCheck(prop, nd.email);
429
+ }
430
+
431
+ return value;
432
+ }
433
+
434
+ /** Shows warning if user email address not present in group associated to property
435
+ *
436
+ * @param prop the VibeIQ property
437
+ * @param userEmail user email address
438
+ */
439
+ async processGroupMemberCheck(prop, userEmail) {
440
+ let arrUserList = [];
441
+ if(this.userRefCache[prop.typePropertyUserListId]) {
442
+ arrUserList = this.userRefCache[prop.typePropertyUserListId];
443
+ } else {
444
+ const userListResult = await new Entities().get({
445
+ entityName: 'user-list',
446
+ id: prop.typePropertyUserListId
447
+ });
448
+
449
+ if(userListResult && Object.keys(userListResult).length) {
450
+ arrUserList = userListResult.userList;
451
+ this.userRefCache[prop.typePropertyUserListId] = arrUserList;
452
+ }
453
+ }
454
+
455
+ if(arrUserList.length) {
456
+ const result = arrUserList.find(element => element['display'] === userEmail);
457
+ if(!result) {
458
+ console.warn(`The passed in user ${userEmail} in property slug ${prop.slug} should be a member of the group associated with the property 'typePropertyUserListId'`)
459
+ }
460
+ }
461
+ }
462
+
463
+ /** Gets the VibeIQ value for the userList property from data
464
+ *
465
+ * @param prop the VibeIQ property
466
+ * @param newData the FlexPLM data
467
+ * @returns value to be set in VibeIQ
468
+ */
469
+ async getUserListValue(prop, newData) {
470
+ const slug = prop['slug'];
471
+ if (Logger.isDebugOn()) {
472
+ console.debug('getUserListValue-prop: ' + slug);
473
+ }
474
+
475
+ const entityId = newData[slug + 'Id'];
476
+
477
+ if(!entityId) {
478
+ return {};
479
+ }
480
+
481
+ if (this.userRefCache[entityId]) {
482
+ if (Logger.isDebugOn()) {
483
+ console.debug('user cache hit: ' + entityId);
484
+ }
485
+ return this.userRefCache[entityId];
486
+ }
487
+
488
+ const entities = await new Entities().get({
489
+ entityName: 'user-org',
490
+ id: entityId
491
+ });
492
+
493
+ const value = (entities) ? {
494
+ email: entities.userEmail,
495
+ firstName: entities.first,
496
+ lastName: entities.last,
497
+ isSsoUser: entities.isSsoUser,
498
+ } : undefined;
499
+
500
+ if(value) {
501
+ this.userRefCache[entityId] = value;
502
+ }
503
+
504
+ return value;
505
+ }
506
+
507
+ }
@@ -0,0 +1,172 @@
1
+ import { Entities } from '@contrail/sdk';
2
+
3
+ import { FederationRecord } from '../interfaces/interfaces';
4
+ import pLimit from 'p-limit';
5
+ const limit = pLimit(30);
6
+
7
+ interface fedConfigDef {
8
+ appIdentifier: string,
9
+ federationSchema: string
10
+ }
11
+ const FED_CONFIG: fedConfigDef = {
12
+ appIdentifier: '@vibeiq/flexplm-connector',
13
+ federationSchema: 'DEFAULT'
14
+ };
15
+ export class Federation {
16
+
17
+ private CHUNK_SIZE = 50;
18
+
19
+ async getFederatedMappedRefId(entityType: string, entityId: string) {
20
+ const criteria = {
21
+ reference: entityType + ':' + entityId,
22
+ appIdentifier: FED_CONFIG.appIdentifier,
23
+ federationSchema: FED_CONFIG.federationSchema
24
+ };
25
+ console.log('getFederatedMappedRefId: ' + JSON.stringify(criteria));
26
+ const fedRecords: FederationRecord[] = await new Entities().get({
27
+ entityName: 'federation',
28
+ criteria
29
+ });
30
+
31
+ const federatedId = (fedRecords[0])
32
+ ? fedRecords[0]['mappedReference']
33
+ : '';
34
+
35
+ return federatedId;
36
+ }
37
+
38
+ async createFederatedRecord(eventBody) {
39
+ const itemResults = eventBody.payload;
40
+ for (let i = 0; i < itemResults.length; i++) {
41
+ if (!itemResults[i].federatedId) {
42
+ continue;
43
+ }
44
+ const payload: FederationRecord = {
45
+ appIdentifier: FED_CONFIG.appIdentifier,
46
+ reference: itemResults[i].entityReference,
47
+ mappedReference: itemResults[i].federatedId,
48
+ federationSchema: FED_CONFIG.federationSchema
49
+ };
50
+ // console.log('createFederatedRecord: ' + JSON.stringify(payload));
51
+
52
+ try {
53
+ const results = await new Entities().create({ entityName: 'federation', object: payload });
54
+ return results;
55
+ // console.log(JSON.stringify(results));
56
+ } catch (error) {
57
+ console.log('createFederatedRecord-error: ', error);
58
+ throw new Error('Error creating federation record: ' + error.message);
59
+ }
60
+ }
61
+ }
62
+
63
+ async getFederationRecordFromMappedRefId(mappedRefId: string) {
64
+ const criteria = {
65
+ appIdentifier: FED_CONFIG.appIdentifier,
66
+ mappedReference: mappedRefId,
67
+ federationSchema: FED_CONFIG.federationSchema
68
+ };
69
+ try {
70
+ const fedRecords: FederationRecord[] = await new Entities().get({
71
+ entityName: 'federation',
72
+ criteria
73
+ });
74
+ return (fedRecords && fedRecords[0]) ? fedRecords[0] : undefined;
75
+ } catch (e) {
76
+ console.log('getFederationData-error: ' + e.message);
77
+ }
78
+ return undefined;
79
+ }
80
+
81
+ static getEntityId(fedRecord: FederationRecord) {
82
+ const entityString = fedRecord['reference'];
83
+ const entitySplit = entityString.split(':');
84
+ const entityType = entitySplit[0];
85
+ const entityId = entitySplit[1];
86
+
87
+ return { entityType, entityId };
88
+
89
+ }
90
+
91
+ async getEntityFromMappedRefId(mappedRefId: string) {
92
+ // console.log('!---getEntityFromMappedRefId: ' + mappedRefId);
93
+ const fedRecord = await this.getFederationRecordFromMappedRefId(mappedRefId);
94
+ console.log('fedRecord: ' + JSON.stringify(fedRecord));
95
+ if (!fedRecord) {
96
+ //Not creating from FlexPLM at this time.
97
+ console.log('Federation Record doesnt exist. Cant get entity!');
98
+ return;
99
+ }
100
+
101
+ const { entityType, entityId } = Federation.getEntityId(fedRecord);
102
+ // console.log(entityType + ':' + entityId);
103
+ const criteria = {
104
+ id: entityId
105
+ };
106
+ const entities = await new Entities().get({
107
+ entityName: entityType,
108
+ criteria
109
+ });
110
+ const entity = (entities && entities[0]) ? entities[0] : undefined;
111
+ // console.log(' entities: ' +JSON.stringify(entities));
112
+ return entity;
113
+ }
114
+
115
+ async getFederationRecordsFromIds(ids: string[]): Promise<FederationRecord[]> {
116
+ const fedRecords = [];
117
+ for (let i = 0; i < ids.length; i++) {
118
+ const criteria = {
119
+ reference: ids[i],
120
+ appIdentifier: FED_CONFIG.appIdentifier,
121
+ federationSchema: FED_CONFIG.federationSchema
122
+ };
123
+ // this.logger.log('getFederatedMappedRefId: ' + JSON.stringify(criteria));
124
+ const recs: FederationRecord[] = await new Entities().get({
125
+ entityName: 'federation',
126
+ criteria
127
+ });
128
+ if (recs[0]) {
129
+ fedRecords.push(recs[0]);
130
+ }
131
+ }
132
+
133
+ return fedRecords;
134
+ }
135
+
136
+ async getFederationRecordsFromIdsBulk(ids: string[]): Promise<FederationRecord[]> {
137
+
138
+ const chunks: string[][] = this.splitIntoChunksByLen(ids, this.CHUNK_SIZE);
139
+ const fedRecords = [];
140
+ const federatedPromises = [];
141
+ const entities: Entities = new Entities();
142
+ for (const chunk of chunks) {
143
+ const fedPromise = limit(async () => {
144
+ const criteria = {
145
+ references: chunk,
146
+ appIdentifier: FED_CONFIG.appIdentifier,
147
+ federationSchema: FED_CONFIG.federationSchema
148
+ };
149
+ // this.logger.log('getFederatedMappedRefId: ' + JSON.stringify(criteria));
150
+ const records: FederationRecord[] = await entities.get({
151
+ entityName: 'federation',
152
+ criteria
153
+ });
154
+ fedRecords.push(...records);
155
+
156
+ });
157
+ federatedPromises.push(fedPromise);
158
+ }
159
+ await Promise.all(federatedPromises);
160
+
161
+ return fedRecords;
162
+ }
163
+
164
+ splitIntoChunksByLen(arr, len) {
165
+ const chunks = [], n = arr?.length;
166
+ let i = 0;
167
+ while (i < n) {
168
+ chunks.push(arr.slice(i, i += len));
169
+ }
170
+ return chunks;
171
+ }
172
+ }