@contrail/flexplm 1.4.0 → 1.5.0-alpha.14a4f1b

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 (112) hide show
  1. package/lib/cli/commands/compile.d.ts +4 -0
  2. package/lib/cli/commands/compile.js +73 -0
  3. package/lib/cli/commands/compile.spec.d.ts +1 -0
  4. package/lib/cli/commands/compile.spec.js +80 -0
  5. package/lib/cli/commands/create.d.ts +5 -0
  6. package/lib/cli/commands/create.js +77 -0
  7. package/lib/cli/commands/create.spec.d.ts +1 -0
  8. package/lib/cli/commands/create.spec.js +78 -0
  9. package/lib/cli/commands/upload.d.ts +17 -0
  10. package/lib/cli/commands/upload.js +228 -0
  11. package/lib/cli/commands/upload.spec.d.ts +1 -0
  12. package/lib/cli/commands/upload.spec.js +88 -0
  13. package/lib/cli/index.d.ts +5 -0
  14. package/lib/cli/index.js +70 -0
  15. package/lib/cli/index.spec.d.ts +1 -0
  16. package/lib/cli/index.spec.js +85 -0
  17. package/lib/cli/template/mapping-template.ts.template +62 -0
  18. package/lib/entity-processor/base-entity-processor.d.ts +65 -0
  19. package/lib/entity-processor/base-entity-processor.js +71 -0
  20. package/lib/entity-processor/base-entity-processor.spec.js +1 -0
  21. package/lib/index.d.ts +1 -0
  22. package/lib/index.js +1 -0
  23. package/lib/interfaces/mapping-file.d.ts +460 -0
  24. package/lib/interfaces/mapping-file.js +2 -0
  25. package/lib/publish/base-process-publish-assortment.d.ts +25 -0
  26. package/lib/publish/base-process-publish-assortment.js +60 -6
  27. package/lib/publish/base-process-publish-assortment.spec.js +22 -4
  28. package/lib/publish/mockData.js +5 -0
  29. package/lib/transform/identifier-conversion-spec-mockData.js +34 -6
  30. package/lib/transform/identifier-conversion.d.ts +36 -0
  31. package/lib/transform/identifier-conversion.js +37 -1
  32. package/lib/transform/identifier-conversion.spec.js +35 -0
  33. package/lib/util/config-defaults.d.ts +18 -0
  34. package/lib/util/config-defaults.js +25 -15
  35. package/lib/util/config-defaults.spec.js +56 -0
  36. package/lib/util/data-converter-spec-mockData.js +17 -3
  37. package/lib/util/data-converter.d.ts +102 -0
  38. package/lib/util/data-converter.js +195 -34
  39. package/lib/util/data-converter.spec.js +430 -0
  40. package/lib/util/error-response-object.d.ts +5 -0
  41. package/lib/util/error-response-object.js +7 -0
  42. package/lib/util/event-short-message-status.js +1 -0
  43. package/lib/util/federation.js +8 -0
  44. package/lib/util/flexplm-connect.d.ts +7 -0
  45. package/lib/util/flexplm-connect.js +14 -0
  46. package/lib/util/logger-config.js +1 -0
  47. package/lib/util/map-util-spec-mockData.js +17 -3
  48. package/lib/util/map-utils.d.ts +27 -0
  49. package/lib/util/map-utils.js +27 -0
  50. package/lib/util/thumbnail-util.d.ts +21 -0
  51. package/lib/util/thumbnail-util.js +28 -1
  52. package/lib/util/thumbnail-util.spec.js +6 -0
  53. package/lib/util/type-conversion-utils-spec-mockData.js +3 -3
  54. package/lib/util/type-conversion-utils.d.ts +151 -0
  55. package/lib/util/type-conversion-utils.js +154 -0
  56. package/lib/util/type-defaults.d.ts +69 -0
  57. package/lib/util/type-defaults.js +98 -4
  58. package/lib/util/type-defaults.spec.js +114 -4
  59. package/lib/util/type-utils.d.ts +21 -0
  60. package/lib/util/type-utils.js +23 -0
  61. package/lib/util/type-utils.spec.js +2 -0
  62. package/package.json +21 -6
  63. package/scripts/copy-template.js +10 -0
  64. package/.github/pull_request_template.md +0 -31
  65. package/.github/workflows/flexplm-lib.yml +0 -27
  66. package/.github/workflows/publish-to-npm.yml +0 -121
  67. package/CHANGELOG.md +0 -40
  68. package/publish.bat +0 -5
  69. package/publish.sh +0 -5
  70. package/src/entity-processor/base-entity-processor.spec.ts +0 -689
  71. package/src/entity-processor/base-entity-processor.ts +0 -583
  72. package/src/flexplm-request.ts +0 -28
  73. package/src/flexplm-utils.spec.ts +0 -27
  74. package/src/flexplm-utils.ts +0 -29
  75. package/src/index.ts +0 -22
  76. package/src/interfaces/interfaces.ts +0 -122
  77. package/src/interfaces/item-family-changes.ts +0 -67
  78. package/src/interfaces/publish-change-data.ts +0 -43
  79. package/src/publish/base-process-publish-assortment-callback.ts +0 -50
  80. package/src/publish/base-process-publish-assortment.spec.ts +0 -1992
  81. package/src/publish/base-process-publish-assortment.ts +0 -1134
  82. package/src/publish/mockData.ts +0 -4561
  83. package/src/transform/identifier-conversion-spec-mockData.ts +0 -496
  84. package/src/transform/identifier-conversion.spec.ts +0 -354
  85. package/src/transform/identifier-conversion.ts +0 -282
  86. package/src/util/config-defaults.spec.ts +0 -392
  87. package/src/util/config-defaults.ts +0 -97
  88. package/src/util/data-converter-spec-mockData.ts +0 -231
  89. package/src/util/data-converter.spec.ts +0 -1120
  90. package/src/util/data-converter.ts +0 -766
  91. package/src/util/error-response-object.spec.ts +0 -116
  92. package/src/util/error-response-object.ts +0 -50
  93. package/src/util/event-short-message-status.ts +0 -22
  94. package/src/util/federation.ts +0 -172
  95. package/src/util/flexplm-connect.spec.ts +0 -132
  96. package/src/util/flexplm-connect.ts +0 -208
  97. package/src/util/logger-config.ts +0 -20
  98. package/src/util/map-util-spec-mockData.ts +0 -231
  99. package/src/util/map-utils.spec.ts +0 -103
  100. package/src/util/map-utils.ts +0 -41
  101. package/src/util/mockData.ts +0 -101
  102. package/src/util/thumbnail-util.spec.ts +0 -508
  103. package/src/util/thumbnail-util.ts +0 -272
  104. package/src/util/type-conversion-utils-spec-mockData.ts +0 -272
  105. package/src/util/type-conversion-utils.spec.ts +0 -1031
  106. package/src/util/type-conversion-utils.ts +0 -490
  107. package/src/util/type-defaults.spec.ts +0 -669
  108. package/src/util/type-defaults.ts +0 -281
  109. package/src/util/type-utils.spec.ts +0 -227
  110. package/src/util/type-utils.ts +0 -144
  111. package/tsconfig.json +0 -24
  112. package/tslint.json +0 -57
@@ -1,766 +0,0 @@
1
- import { API_VERSION, 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 verboseDebug = false;
15
- private objRefCache = {};
16
- private userRefCache = {};
17
- static staticUserCache = {};
18
- static clearStaticUserCache() {
19
- DataConverter.staticUserCache = {};
20
- }
21
- static getFromStaticCache(id: string) {
22
- return DataConverter.staticUserCache[id];
23
- }
24
- static setToStaticCache(id: string, value: any) {
25
- DataConverter.staticUserCache[id] = value;
26
- }
27
-
28
- constructor(private config: FCConfig, private mapFileUtil: MapFileUtil){
29
- this.typeUtils = new TypeUtils();
30
- this.transformMapFile = this.config['transformMapFile'];
31
- this.useDisplayForEnumerationMatching = this.config['dataConverter']
32
- && this.config['dataConverter']['useDisplayForEnumerationMatching'];
33
- this.verboseDebug = this.config['dataConverter']
34
- && this.config['dataConverter']['verboseDebug'];
35
- }
36
-
37
- public setVerboseDebug(val: boolean = false) {
38
- this.verboseDebug= val;
39
- }
40
- public isVerboseDebugOn(): boolean {
41
- return this.verboseDebug && Logger.isDebugOn();
42
- }
43
-
44
- async getFlexPLMObjectDataFromEvent(event, dataToSkip: string[]) {
45
- return this.getFlexPLMObjectData(event.newData, dataToSkip, true);
46
- }
47
-
48
- async getFlexPLMObjectData(newData, dataToSkip: string[], inflateObjRef: boolean) {
49
- if(this.isVerboseDebugOn()) {
50
- console.debug('newData: ' + JSON.stringify(newData));
51
- }
52
- //Using event to get propertyDiffs to find emptied values
53
- //Add standard atts to skip
54
- dataToSkip = dataToSkip.concat(['updatedOn', 'updatedById', 'createdOn', 'createdById', 'modifiedAt', 'orgId', 'createdAt', 'id', 'typeId', 'workspaceId']);
55
- // const oldData = event.oldData;
56
- const data = {};
57
- const typeId = newData?.typeId;
58
- if (!typeId) {
59
- return;// Don't have a type; so can't process
60
- }
61
- data['typePath'] = newData['typePath'];
62
- const type = await this.typeUtils.getTypeById(typeId);
63
- const typeProps = this.typeUtils.filterTypeProperties(type, newData);
64
- for(const prop of typeProps){
65
- // if(this.logger.isTraceOn()){
66
- // this.logger.log('prop: ' + JSON.stringify(prop));
67
- // }
68
- const slug = prop['slug'];
69
- if (dataToSkip.includes(slug)) {
70
- continue;
71
- }
72
- data[slug] = await this.getFlexPLMValue(prop, newData, inflateObjRef);
73
- }
74
-
75
- if(this.isVerboseDebugOn()) {
76
- console.debug('getFlexPLMObjectData-data: ' + JSON.stringify(data));
77
- }
78
- return data;
79
-
80
- }
81
-
82
- async getFlexPLMValue(prop, newData, inflateObjRef: boolean) {
83
- const propertyType = prop['propertyType'];
84
- const slug = prop['slug'];
85
- const nd = newData[slug];
86
- // console.log('getFlexPLMValue: ' + propertyType + ', ' +slug + ', ' + nd + ', ' + od);
87
- let value;
88
- if(['string', 'text'].includes(propertyType)){
89
- value = nd || '';
90
- }else if(['number', 'currency', 'percent', 'sequence'].includes(propertyType)){
91
- value = nd || 0;
92
- }else if('date' === propertyType){
93
- if(nd){
94
- value = nd;
95
- // const d = new Date(nd);
96
- // console.log('Date.getTimezoneOffset(): ' + d.getTimezoneOffset());
97
- // value = d.toISOString();
98
- // console.log('date: ' + nd + ' -- ' + value);
99
- } else {
100
- value = null;
101
- }
102
- }else if('boolean' === propertyType){
103
- value =(nd)? true: false;
104
- }else if('choice' === propertyType){
105
- value = this.getEnumerationValue(prop, nd);
106
- }else if('multi_select' === propertyType){
107
- value = this.getEnumerationValue(prop, nd);
108
- }else if('object_reference' === propertyType){
109
- value = await this.getObjectReferenceValue(prop, newData, inflateObjRef);
110
- if(this.isVerboseDebugOn()){
111
- console.debug('object_reference: ' + JSON.stringify(value));
112
- }
113
- } else if ('image' === propertyType) {
114
- // console.log('image-TODO');
115
- }else if('formula' === propertyType){
116
- value = nd;
117
- }else if('json' === propertyType){
118
- // console.log('json-TODO');
119
- value = nd;
120
- } else if ('userList' === propertyType) {
121
- value = await this.getUserListValue(prop, newData);
122
- }else if ('size_range' === propertyType){
123
- value = nd;
124
- }
125
-
126
- return value;
127
-
128
- }
129
- /** Returns the display values for list properties (choice & multi_select)
130
- *
131
- * @param prop
132
- * @param newData
133
- * @returns
134
- */
135
- getEnumerationValue(prop, nd){
136
- const propertyType = prop['propertyType'];
137
- let value;
138
- if(['choice', 'multi_select'].includes(propertyType)){
139
- const options: [{value:string, display:string}] = prop['options'] || [];
140
- if('choice' === propertyType){
141
- if(nd){
142
- const option = options.find(option => option.value == nd );
143
- if(option){
144
- value = Object.assign({},option);
145
- }
146
- }
147
- if(!value) {
148
- value = {};
149
- }
150
- } else if ('multi_select' === propertyType) {
151
- value = [];
152
- if (nd instanceof Array) {
153
- nd.forEach(key => {
154
- const optionObject = options.find(option => option.value == key);
155
- if(optionObject){
156
- const option = Object.assign({},optionObject);
157
- value.push(option);
158
- }
159
- });
160
- } else if( typeof nd === 'string' && '' !== nd) {
161
- const optionObject = options.find(option => option.value == nd);
162
- if(optionObject){
163
- const option = Object.assign({},optionObject);
164
- value.push(option);
165
- }
166
- }
167
- }
168
- }
169
- return value;
170
- }
171
-
172
- public async getObjectReferenceValue(prop: any, newData: any, inflateObjRef = false) {
173
- const slug = prop['slug'];
174
- if(Logger.isDebugOn()) {
175
- console.debug('getObjectReferenceValue-prop: ' + slug);
176
- }
177
- let value = newData[slug];
178
- const entityType = prop['referencedTypeRootSlug'];
179
- const entityId = newData[slug + 'Id'];
180
- if ((!value || typeof value === 'string' )&& inflateObjRef) {
181
- if (entityId) {
182
- if(this.objRefCache[entityId]){
183
- if(Logger.isDebugOn()) {
184
- console.debug('cache hit: ' + entityId);
185
- }
186
- return this.objRefCache[entityId];
187
- }
188
- const criteria = {
189
- id: entityId
190
- };
191
- const entities = await new Entities().get({
192
- entityName: entityType,
193
- criteria
194
- });
195
- value = (entities && entities[0]) ? entities[0] : undefined;
196
- }
197
- }
198
-
199
- if(value && !(typeof value === 'string')){
200
- const unprocessedValue = value;
201
- const objectClass = await TypeConversionUtils.getObjectClass(this.transformMapFile, this.mapFileUtil, unprocessedValue);
202
- const flexPLMTypePath = await TypeConversionUtils.getObjectTypePath(this.transformMapFile, this.mapFileUtil, unprocessedValue);
203
- value = await this.getFlexPLMObjectData(value, [], false);
204
- value['entityReference'] = entityType + ':' + entityId;
205
- value['objectClass'] = objectClass;
206
- value['flexPLMTypePath'] = flexPLMTypePath;
207
-
208
- if(this.transformMapFile){
209
- const mapKey = await TypeConversionUtils.getMapKey(this.transformMapFile, this.mapFileUtil, unprocessedValue, TypeConversionUtils.VIBE2FLEX_DIRECTION);
210
- value = await MapUtil.applyTransformMap(this.transformMapFile, this.mapFileUtil, value, mapKey, TypeConversionUtils.VIBE2FLEX_DIRECTION)
211
- }
212
-
213
- } else {
214
- value = {};
215
- }
216
- this.objRefCache[entityId] = value;
217
- return value;
218
- }
219
-
220
- /** (Deprecated) Use TypeConversionUtils.getMapKey()
221
- * Will return the class to use to get mapping.
222
- * This is needed because mappings will be different for different sub types
223
- * of custom-entity
224
- *
225
- * @param obj: Entity being checked
226
- * @param mapping: The whole mapping file
227
- */
228
- getMappingClass(entity: object, mapping: any): string{
229
- const entityTypePath = entity['typePath'];
230
- const typeMapKey = mapping['typeMapKey'];
231
- let objClass = typeMapKey[entityTypePath];
232
- const entityType = entity['entityType'];
233
-
234
- if(!objClass){
235
- objClass = this.typeUtils.getEventObjectClass(entityType, entity);
236
- }
237
- if(!objClass){
238
- objClass = entityType;
239
- }
240
- return objClass;
241
- }
242
-
243
- /** Sets entity values from FlexPLM data passed in
244
- * Assumes the entity has a VibeIQ typeId and 'roles' value to filter if necessary.
245
- * @param entity the entity to update
246
- * @param data the FlexPLM data
247
- * @param keysToSkip properties to skip
248
- * @returns the modified entity with VibeIQ values
249
- */
250
- async setEntityValues(entity, data, keysToSkip: string[] = []){
251
- // this.logger.log('setEntityValues: ' + JSON.stringify(entity));
252
- // this.logger.log('data: ' + JSON.stringify(data));
253
- const type = await this.typeUtils.getTypeById(entity.typeId);
254
- keysToSkip = keysToSkip.concat(['updatedOn', 'updatedById', 'createdOn', 'createdById', 'modifiedAt', 'orgId', 'createdAt', 'id', 'typeId', 'typePath', 'workspaceId']);
255
- let typeProps = this.typeUtils.filterTypeProperties(type, entity);
256
- typeProps = typeProps.filter( prop => !keysToSkip.includes(prop['slug']));
257
- //Only process properties that had a value sent; to not accidentally clear out values
258
- //for properties that weren't sent.
259
- const dataKeys = Object.getOwnPropertyNames(data);
260
- typeProps = typeProps.filter( prop => dataKeys.includes(prop['slug']));
261
-
262
- for(const prop of typeProps){
263
- const propertyType = prop['propertyType'];
264
- const slug = prop['slug'];
265
- let keyName = slug;
266
- if (propertyType === 'userList' || propertyType === 'object_reference') {
267
- keyName = slug + 'Id';
268
- }
269
- entity[keyName] = await this.getEntityValue(prop, data);
270
- // console.log('entity[slug]: ' + entity[slug]);
271
- }
272
-
273
- return entity;
274
-
275
- }
276
-
277
- /** Gets the entity values from FlexPLM data
278
- * Assumes there isn't a VibeIQ typeId, so uses FlexPLM data to determine type
279
- * @param objectClass FlexPLM object class
280
- * @param data object data
281
- * @param keysToSkip type properties to not process
282
- * @returns object with VibeIQ values
283
- */
284
- async getEntityValues(objectClass: string, data: any, keysToSkip: string[] = []){
285
- const entityValues = {};
286
- const tco: TypeClientOptions = await this.typeUtils.getEntityTypeClientOptionsUsingMapping(this.transformMapFile, this.mapFileUtil, data);
287
- const type = await this.typeUtils.getByRootAndPath(tco);
288
- const typePath = type['typePath'];
289
- if(typePath && (typePath.startsWith('item') || typePath.startsWith('project-item'))){
290
- if(['LCSProduct', 'LCSProductSeasonLink'].includes(objectClass)){
291
- entityValues['roles'] = ['family'];
292
- }else{
293
- entityValues['roles'] = ['color', 'option'];
294
- }
295
- }
296
-
297
- let typeProps = this.typeUtils.filterTypeProperties(type, entityValues);
298
- typeProps = typeProps.filter( prop => !keysToSkip.includes(prop['slug']));
299
-
300
- for(const prop of typeProps){
301
- const slug = prop['slug'];
302
- const value = await this.getEntityValue(prop, data);
303
- if(value){
304
- entityValues[slug] = value;
305
- }
306
- }
307
-
308
- return entityValues;
309
- }
310
-
311
- /** Gets the VibeIQ value for the property from data
312
- *
313
- * @param prop the VibeIQ property
314
- * @param data the FlexPLM data
315
- * @returns value to be set in VibeIQ
316
- */
317
- async getEntityValue(prop, data) {
318
- const propertyType = prop['propertyType'];
319
- const slug = prop['slug'];
320
- const nd = data[slug];
321
- // this.logger.log('getValue: ' + propertyType + ', ' +slug + ', ' + nd);
322
-
323
- let value;
324
- if (['string', 'text'].includes(propertyType)) {
325
- value = nd;
326
- }else if(['number', 'currency', 'percent', 'sequence'].includes(propertyType)){
327
- value = (null === nd)? 0 : nd;
328
- }else if('date' === propertyType){
329
- if(nd){
330
- // const offset = new Date(nd).getTimezoneOffset() * 60 * 1_000;
331
- // this.logger.log('nd: ' + nd);
332
- // this.logger.log(offset);
333
- // this.logger.log('No Offset: ' + new Date(nd).toISOString());
334
- // const d = new Date(nd + offset);// Take system Timezone into account.
335
- const d = new Date(nd);
336
- value = d.toISOString();
337
-
338
- } else {
339
- value = null;
340
- }
341
- }else if('boolean' === propertyType){
342
- value =(nd)? true: false;
343
- }else if('choice' === propertyType){
344
- value = this.setEnumerationKeys(prop, nd, this.useDisplayForEnumerationMatching);
345
- }else if('multi_select' === propertyType){
346
- value = this.setEnumerationKeys(prop, nd, this.useDisplayForEnumerationMatching);
347
-
348
- } else if ('object_reference' === propertyType) {
349
- value = await this.setObjectReferenceValue(prop, nd);
350
- } else if ('image' === propertyType) {
351
- // console.log('TODO-image');
352
- } else if ('formula' === propertyType) {
353
- // console.log('TODO-formula');
354
- } else if ('json' === propertyType) {
355
- // console.log('TODO-json');
356
- } else if ('userList' === propertyType) {
357
- value = await this.setUserListValue(prop, nd);
358
- }else if ('size_range' === propertyType){
359
- value = nd;
360
- }
361
-
362
- // console.log(value);
363
- return value;
364
- }
365
-
366
- setEnumerationKeys(prop, nd, matchByDisplay) {
367
- const propertyType = prop['propertyType'];
368
- let value;
369
- if(['choice', 'multi_select'].includes(propertyType)){
370
- //If there are no options, use empty array to not error out and don't set anything
371
- const options: [{value:string, display:string}] = prop['options'] || [];
372
- if('choice' === propertyType){
373
- if(nd){
374
- const matchKey = (matchByDisplay)? 'display' : 'value';
375
- const option = options.find(option => option[matchKey] == nd[matchKey] );
376
- if(option){
377
- value = option.value;
378
- }
379
- } else {
380
- value = undefined;
381
- }
382
- }else if('multi_select' === propertyType){
383
- value = [];
384
- const matchKey = (matchByDisplay)? 'display' : 'value';
385
- if(nd instanceof Array){
386
- nd.forEach(selectedOpt =>{
387
- const optionObject = options.find(option => option[matchKey] == selectedOpt[matchKey]);
388
- if(optionObject){
389
- const option = optionObject.value;
390
- value.push(option);
391
- }
392
- });
393
-
394
- }
395
- }
396
- }
397
- return value;
398
- }
399
-
400
- /** Compares the potential changes to the entity and returns only the actual differences.
401
- *
402
- * @param entity the full entity
403
- * @param changes the potential changes
404
- * @returns only the change values that are different from the entity's value
405
- */
406
- getPersistableChanges(entity: object, changes: object): object {
407
- const entityCompareValues = {};
408
- for(const key of (Object.getOwnPropertyNames(changes))){
409
- entityCompareValues[key] = entity[key];
410
- }
411
- const diffs: ObjectDiff[] = ObjectUtil.compareDeep(entityCompareValues, changes, '');
412
- const diffValues = {};
413
- if(diffs && diffs.length > 0){
414
- for(const diff of diffs){
415
- diffValues[diff.propertyName] = diff.newValue;
416
- }
417
- }
418
- return diffValues;
419
-
420
- }
421
-
422
- /** Sets object reference value from FlexPLM data passed in
423
- *
424
- * @param prop the VibeIQ property
425
- * @param nd the VibeIQ data
426
- * @returns the object reference id from VibeIQ
427
- */
428
- async setObjectReferenceValue(prop, nd) {
429
- let objectReferenceId = "";
430
- if(!nd) {
431
- return objectReferenceId;
432
- }
433
- if(this.transformMapFile){
434
- const mapKey = await TypeConversionUtils.getMapKeyFromObject(this.transformMapFile, this.mapFileUtil, nd, TypeConversionUtils.FLEX2VIBE_DIRECTION);
435
- nd = await MapUtil.applyTransformMap(this.transformMapFile, this.mapFileUtil, nd, mapKey, TypeConversionUtils.FLEX2VIBE_DIRECTION)
436
- }
437
-
438
- const entityType = prop['referencedTypeRootSlug'];
439
- const entityTypePath = prop['referencedTypePath'];
440
- const entityKeys = Object.keys(nd);
441
- const identifierKeys = await TypeConversionUtils.getIdentifierPropertiesFromObject(this.transformMapFile, this.mapFileUtil, nd)
442
- const hasAllIdentifiers = identifierKeys.every(key => entityKeys.includes(key));
443
- if(identifierKeys.length == 0 || !hasAllIdentifiers){
444
- console.warn(`The inbound ${entityType} for prop '${prop['slug']}' doesnt have all "identifier" properties, so there is no processing. Identifier properties: ${identifierKeys}`);
445
- return objectReferenceId;
446
- }
447
-
448
- const rootType = await this.typeUtils.getByRootAndPath({root: entityType});
449
- const rootTypeProps = this.typeUtils.filterTypeProperties(rootType, nd);
450
-
451
- let rootTypeCriteria = {};
452
- let typeCriteria = { };
453
- identifierKeys.forEach(keyName => {
454
- const foundInObjects = rootTypeProps.some(obj => obj.slug === keyName);
455
- if (foundInObjects) {
456
- rootTypeCriteria[keyName] = nd[keyName];
457
- } else {
458
- typeCriteria[keyName] = nd[keyName];
459
- }
460
- });
461
-
462
- const combinedCriteria = { ...rootTypeCriteria, ...typeCriteria, typePath: entityTypePath };
463
- const cacheKey = Object.values(combinedCriteria).join('_');
464
-
465
- if (this.objRefCache[cacheKey]) {
466
- if (Logger.isDebugOn()) {
467
- console.debug(`object reference cache hit: ${cacheKey}`);
468
- }
469
- return this.objRefCache[cacheKey];
470
- }
471
-
472
- let arrObjectReferences = await this.getAllObjectReferences(entityType, rootTypeCriteria);
473
- if(entityType !== entityTypePath) {
474
- arrObjectReferences = this.checkKeysAndValues(typeCriteria, arrObjectReferences, entityTypePath);
475
- }
476
-
477
- if(arrObjectReferences.length) {
478
- if(arrObjectReferences.length === 1) {
479
- objectReferenceId = arrObjectReferences[0].id;
480
- } else {
481
- console.warn(`The passed in object reference criteria has duplicate records found ${JSON.stringify(combinedCriteria)}.`);
482
- }
483
- }
484
-
485
- if (!objectReferenceId) {
486
- console.warn(`The passed in object reference criteria ${JSON.stringify(combinedCriteria)} didn't match any entities.`);
487
- return objectReferenceId;
488
- }
489
-
490
- this.objRefCache[cacheKey] = objectReferenceId;
491
-
492
- return objectReferenceId;
493
- }
494
-
495
- /**
496
- * Retrieves all object references of a specified entity type based on the provided criteria.
497
- * This function handles pagination and asynchronously fetches object references until there are no more pages.
498
- * @param {string} entityType - The type of entity for which object references are to be retrieved.
499
- * @param {object} rootTypeCriteria - The criteria used to filter object references.
500
- * @returns {Promise<Array>} A Promise that resolves to an array containing all object references.
501
- */
502
- async getAllObjectReferences(entityType: string, rootTypeCriteria, postProcessCriteria = null) {
503
- const entities = new Entities();
504
- let loads = [];
505
- let nextPageKey;
506
- let usedV2 = false;
507
- do {
508
- const take = 1000;
509
- const loadPage = await entities.get({
510
- entityName: entityType,
511
- criteria: rootTypeCriteria,
512
- apiVersion: API_VERSION.V2,
513
- take,
514
- nextPageKey,
515
- });
516
- nextPageKey = loadPage?.nextPageKey;
517
- if (Object.keys(loadPage).includes('results')) {
518
- usedV2 = true;
519
- let postProcessedResults = this.filterOutArchivedAndTrashedEntities(loadPage?.results);
520
- if(postProcessedResults?.length > 0 && postProcessCriteria && Object.keys(postProcessCriteria).length !== 0) {
521
- const subEntityTypePath = rootTypeCriteria.typePath || entityType;
522
- postProcessedResults = this.checkKeysAndValues(postProcessCriteria, postProcessedResults, subEntityTypePath);
523
- }
524
- loads.push(...postProcessedResults);
525
- } else {
526
- nextPageKey = null;
527
- }
528
- } while (nextPageKey);
529
-
530
- if (!usedV2) {
531
- const take = 1000;
532
- let skip = 0;
533
- let done = false;
534
- while (!done) {
535
- const loadPage = await entities.get({
536
- entityName: entityType,
537
- criteria: rootTypeCriteria,
538
- take,
539
- skip,
540
- });
541
- let postProcessedResults = this.filterOutArchivedAndTrashedEntities(loadPage);
542
- if(postProcessCriteria && Object.keys(postProcessCriteria).length !== 0) {
543
- const subEntityTypePath = rootTypeCriteria.typePath || entityType;
544
- postProcessedResults = this.checkKeysAndValues(postProcessCriteria, postProcessedResults, subEntityTypePath);
545
- }
546
- loads.push(...postProcessedResults);
547
-
548
- if (loadPage.length !== take) {
549
- done = true;
550
- } else {
551
- skip += take;
552
- }
553
- }
554
- }
555
-
556
- return loads;
557
- }
558
-
559
- /**
560
- * Checks if all keys and values of a given object are present in an array of objects.
561
- * @param {Object} criteria - The object whose keys and values are to be checked in the array of objects.
562
- * @param {Array<Object>} arrayOfObjects - The array of objects to be searched for matching keys and values.
563
- * @param {string} entityTypePath - The type / subtype for the property; objects must be this type or a sub type of it.
564
- * @returns {(Object|boolean)} Returns the array of objects that matches all keys and values of the provided object.
565
- * If no match is found, returns empty array.
566
- */
567
- checkKeysAndValues(criteria, arrayOfObjects, entityTypePath) {
568
- let arrOfMatchObjects = [];
569
- for (let i = 0; i < arrayOfObjects.length; i++) {
570
- const currentObj = arrayOfObjects[i];
571
- let found = true;
572
-
573
- if(entityTypePath && currentObj['typePath']){
574
- const currentObjPath = '' + currentObj['typePath'];
575
- if(!currentObjPath.startsWith(entityTypePath)){
576
- found = false;
577
- }
578
- }
579
- for (const key in criteria) {
580
- if (!(key in currentObj) || currentObj[key] !== criteria[key]) {
581
- found = false;
582
- break;
583
- }
584
- }
585
-
586
- if (found) {
587
- arrOfMatchObjects.push(currentObj);
588
- }
589
- }
590
-
591
- return arrOfMatchObjects;
592
- }
593
-
594
- /** Filters out archived and trashed entities from the provided array of entities.
595
- *
596
- * @param entities
597
- * @returns
598
- */
599
-
600
- filterOutArchivedAndTrashedEntities(entities: any[]) {
601
- if(!entities || !Array.isArray(entities) || entities.length === 0){
602
- return [];
603
- }
604
- return entities.filter(entity => {
605
- const isArchived = entity?.isArchived;
606
- const isTrashed = entity?.isTrashed;
607
- return !isArchived && !isTrashed;
608
- });
609
- }
610
-
611
- /** Sets userListId value from FlexPLM data passed in
612
- *
613
- * @param prop the VibeIQ property
614
- * @param nd the VibeIQ data
615
- * @returns the modified entity with FlexPLM values
616
- */
617
- async setUserListValue(prop, nd) {
618
- if(!nd?.email) {
619
- return "";
620
- }
621
- let cacheUser = DataConverter.getFromStaticCache(nd.email);
622
- if (cacheUser) {
623
- if (Logger.isDebugOn()) {
624
- console.debug('user cache hit: ' + nd.email);
625
- }
626
-
627
- await this.processGroupMemberCheck(prop, nd.email);
628
- return cacheUser;
629
- }
630
-
631
- const user = await this.getUserByEmail(nd);
632
- const userId = (user)?user.id:undefined;
633
-
634
- if(userId) {
635
- DataConverter.setToStaticCache(nd.email, userId);
636
- await this.processGroupMemberCheck(prop, nd.email);
637
- }
638
-
639
- return userId;
640
- }
641
-
642
- /** Makes batch calls of 1000 of user-org entities until
643
- * it find one with userEmail of passed in nd.email.
644
- * Maxes out after querying for 15,000 user-org entities
645
- *
646
- * @param nd
647
- * @returns
648
- */
649
- async getUserByEmail(nd: any) {
650
- let userOrg = undefined;
651
- let count =0;
652
- let size = 0;
653
- let emailInput = nd?.email.toLowerCase();
654
-
655
- const entities = new Entities();
656
- const getOptionsCriteria = {
657
- entityName: 'user-org',
658
- take:1000
659
- }
660
-
661
- do {
662
- const userBatch: [any] = await entities.get(getOptionsCriteria);
663
- userOrg = userBatch.find(uo => uo?.userEmail.toLowerCase() === emailInput);
664
-
665
- }while( !userOrg && size == getOptionsCriteria.take && count < 15);
666
- return userOrg?.user
667
-
668
- }
669
-
670
- /** Shows warning if user email address not present in group associated to property
671
- *
672
- * @param prop the VibeIQ property
673
- * @param userEmail user email address
674
- */
675
- async processGroupMemberCheck(prop, userEmail) {
676
- let arrUserList = [];
677
- if(this.userRefCache[prop.typePropertyUserListId]) {
678
- arrUserList = this.userRefCache[prop.typePropertyUserListId];
679
- } else {
680
- const userListResult = await new Entities().get({
681
- entityName: 'user-list',
682
- id: prop.typePropertyUserListId
683
- });
684
-
685
- if(userListResult && Object.keys(userListResult).length) {
686
- arrUserList = userListResult.userList;
687
- this.userRefCache[prop.typePropertyUserListId] = arrUserList;
688
- }
689
- }
690
-
691
- if(arrUserList.length) {
692
- const result = arrUserList.find(element => element['display'] === userEmail);
693
- if(!result) {
694
- console.warn(`The passed in user ${userEmail} in property slug ${prop.slug} should be a member of the group associated with the property 'typePropertyUserListId'`)
695
- }
696
- }
697
- }
698
-
699
- /** Gets the VibeIQ value for the userList property from data
700
- *
701
- * @param prop the VibeIQ property
702
- * @param newData the FlexPLM data
703
- * @returns value to be set in VibeIQ
704
- */
705
- async getUserListValue(prop, newData) {
706
- const slug = prop['slug'];
707
- if (Logger.isDebugOn()) {
708
- console.debug('getUserListValue-prop: ' + slug);
709
- }
710
-
711
- const entityId = newData[slug + 'Id'];
712
-
713
- if(!entityId) {
714
- return {};
715
- }
716
-
717
- const cacheUser = DataConverter.getFromStaticCache(entityId);
718
- if (cacheUser) {
719
- if (Logger.isDebugOn()) {
720
- console.debug('user cache hit: ' + entityId);
721
- }
722
- return Object.assign({}, cacheUser);
723
- }
724
-
725
- const user = await this.getUserById(entityId);
726
-
727
- const value = (user) ? {
728
- email: user.email,
729
- firstName: user.first,
730
- lastName: user.last,
731
- isSsoUser: user.isSsoUser,
732
- } : undefined;
733
-
734
- if(value) {
735
- DataConverter.setToStaticCache(entityId, value);
736
- }
737
-
738
- return value;
739
- }
740
-
741
- /** Makes batch calls of 1000 of user-org entities until
742
- * it find one with user.id of passed in userId.
743
- * Maxes out after querying for 15,000 user-org entities
744
- *
745
- * @param userId
746
- * @returns
747
- */
748
- async getUserById(userId: any) {
749
- let userOrg = undefined;
750
- let count =0;
751
- let size = 0;
752
- const entities = new Entities();
753
- const getOptionsCriteria = {
754
- entityName: 'user-org',
755
- take:1000
756
- }
757
-
758
- do {
759
- const userBatch: [any] = await entities.get(getOptionsCriteria);
760
- userOrg = userBatch.find(uo => uo?.user?.id === userId);
761
-
762
- }while( !userOrg && size == getOptionsCriteria.take && count < 15);
763
- return userOrg?.user
764
- }
765
-
766
- }