@contrail/flexplm 1.3.2-alpha.30ca8bf → 1.3.2-alpha.3ffe557

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