@contrail/flexplm 1.5.0-alpha.98b8b06 → 1.5.0

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