@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,1134 @@
1
+ import { Entities, Files, Request } from '@contrail/sdk';
2
+ import { AsyncEventsPayloadType, FCConfig, ProductFederation, SeasonalPayload, SeasonFederation, SkuFederation } from '../interfaces/interfaces';
3
+ import { DataConverter } from '../util/data-converter';
4
+ import { FlexPLMConnect } from '../util/flexplm-connect';
5
+ import { ItemFamilyChanges } from '../interfaces/item-family-changes';
6
+ import { PublishChangeData } from '../interfaces/publish-change-data';
7
+ import { MapUtil } from '../util/map-utils';
8
+ import { TypeConversionUtils } from '../util/type-conversion-utils';
9
+
10
+ import fsPromise = require('fs/promises');
11
+ import path = require('path');
12
+ import { MapFileUtil } from '@contrail/transform-data';
13
+ import { Logger } from '@contrail/app-framework';
14
+ import { EventShortMessageStatus } from '../util/event-short-message-status';
15
+
16
+ export class BaseProcessPublishAssortment {
17
+
18
+ private TTL = 30 * 24 * 60 * 60 * 1_000; // 30 days
19
+ static ASSORTMENT_NOT_PUBLISHABLE = 'Assortment isn\'t marked for publishing to FlexPLM';
20
+ static ASSORTMENT_NO_FED_INFO = 'Assortment doesn\'t have all "identifier" properties, so there is no processing. Identifier properties: ';
21
+ static NOT_ABLE_TO_PROCESS_DELETE_CHANGES = 'Error: Not able to process delete changes';
22
+ private dc: DataConverter;
23
+ private config: FCConfig;
24
+ private mapFileUtil: MapFileUtil;
25
+ private transformMapFile: string;
26
+ protected orgSlug: string;
27
+ private cache = {
28
+ carriedFromSeason: {}
29
+ };
30
+ private assortment: any;
31
+
32
+ constructor(_config: FCConfig, _dc: DataConverter, _mapFileUtil: MapFileUtil) {
33
+ this.config = _config;
34
+ this.dc = _dc;
35
+ this.mapFileUtil = _mapFileUtil;
36
+ this.transformMapFile = this.config?.transformMapFile;
37
+ this.orgSlug = this.config?.orgSlug || 'unset-orgSlug';
38
+ }
39
+
40
+ public async process(event) {
41
+
42
+ const assortmentPublishChangeId = event.assortmentPublishChangeId;
43
+ let apcHistory;
44
+ let publisher;
45
+ const assortmentId = event.assortmentId;
46
+ try {
47
+ console.info('process-start!');
48
+ let seasonFed: SeasonFederation;
49
+ try {
50
+ seasonFed = await this.getSeasonFederation(assortmentId);
51
+ } catch (e) {
52
+ const message = e.message;
53
+ const eventStatus =
54
+ (message.includes(BaseProcessPublishAssortment.ASSORTMENT_NOT_PUBLISHABLE)) ? EventShortMessageStatus.NOT_PUBLISHABLE :
55
+ (message.startsWith(BaseProcessPublishAssortment.ASSORTMENT_NO_FED_INFO)) ? EventShortMessageStatus.NO_FEDERATION_INFO :
56
+ EventShortMessageStatus.FAILURE;
57
+ const processStatus = 'BaseProcessPublishAssortment: ' + eventStatus
58
+ + ': assortmentId: ' + event.assortmentId + ': assortmentPublishChangeId: ' + event.assortmentPublishChangeId
59
+ + ', orgSlug: ' + this.orgSlug;
60
+ console.log(JSON.stringify(processStatus));
61
+ console.log(message);
62
+ const output = {
63
+ results: { message, event },
64
+ skip_await: true
65
+ };
66
+ return output;
67
+ }
68
+
69
+ apcHistory = await this.getApcHistory(assortmentId);
70
+
71
+ const sinceDate = await this.getSinceDate(assortmentId, assortmentPublishChangeId, apcHistory);
72
+
73
+ //Get detail information
74
+ const assortmentPublishChange = await this.downloadAssortmentPublishChange(assortmentId, assortmentPublishChangeId);
75
+ publisher = this.getPublisher(assortmentPublishChange);
76
+
77
+ const changeDetail = await this.downloadHydratedChangeDetail(assortmentPublishChange);
78
+
79
+ const assortmentBaseline = await this.downloadAssortmentBaseline(assortmentPublishChange);
80
+
81
+ const deleteChanges = await this.getDeleteChanges(assortmentPublishChange, apcHistory, assortmentBaseline, sinceDate);
82
+
83
+ const releasedForDevelopmentItemIds = this.getReleasedForDevelopmentItemAndFamilyIds(assortmentBaseline, deleteChanges);
84
+ const itemToFederatedIdMapping = await this.getItemFederatedIds(/*allItemIds*/);
85
+
86
+ const pcd = new PublishChangeData(assortmentId, seasonFed, assortmentPublishChangeId, sinceDate, publisher);
87
+ pcd.itemToFederatedIdMapping = itemToFederatedIdMapping;
88
+
89
+ pcd.releasedForDevelopmentItemIds = releasedForDevelopmentItemIds;
90
+
91
+ const output = await this.processPublish(pcd, changeDetail, assortmentBaseline, deleteChanges);
92
+ output ['publishInfo'] = await this.getPublishInfo(assortmentId, assortmentPublishChangeId, apcHistory, publisher);
93
+ console.info('process-end');
94
+
95
+ return output;
96
+ } catch (e) {
97
+ try {
98
+ const publishInfo = await this.getPublishInfo(assortmentId, assortmentPublishChangeId, apcHistory, publisher);
99
+ e.publishInfo = publishInfo;
100
+ }catch(e2){
101
+ console.log('catch e2: ' + e2.message);
102
+ }
103
+ console.log('catch e: ' + e.message);
104
+ throw e;
105
+ }
106
+ }
107
+ async getPublishInfo(assortmentId: string, assortmentPublishChangeId: string, apcHistory: any, publisher: any): Promise<any> {
108
+ const apc = apcHistory?.find(apc => apc?.id === assortmentPublishChangeId) || {};
109
+ const assortment = await this.getAssortment(assortmentId);
110
+ const assortmentName = assortment?.name;
111
+ const versionHistoryNumber = await this.getSnapshotVersion(assortment, apc);
112
+ const publishInfo = {
113
+ assortmentName,
114
+ versionName: apc?.versionName,
115
+ versionComments: apc?.versionComments,
116
+ publishDate: apc?.createdOn,
117
+ publisher,
118
+ versionHistoryNumber
119
+ };
120
+
121
+ return publishInfo;
122
+ }
123
+
124
+ /** Gets the version number of the snapshot that was created for the publish change.
125
+ * But if no snapshot was found for the publish change, and the last snapshot was
126
+ * created before the publish change, then it returns 'after: versionNumber' where
127
+ * versionNumber is the version number of the last snapshot.
128
+ * If no snapshot was found for the publish change, and the last snapshot was
129
+ * created after the publish change, then it returns 'unknown'.
130
+ *
131
+ * @returns versionNumber or 'unknown' or 'after: versionNumber'
132
+ */
133
+ async getSnapshotVersion(assortment: any, apc: any ): Promise<number|string>{
134
+ const entityReference = assortment?.createdForReference;
135
+ const createdOnString = apc?.createdOn;
136
+ if(!entityReference || !createdOnString || !apc?.id){
137
+ return 'unknown';
138
+ }
139
+ const createdOnDate = new Date(createdOnString);
140
+ createdOnDate.setMonth(createdOnDate.getMonth() - 1);//subtract 1 month
141
+ const createdOnStringMinus1 = createdOnDate.toISOString();
142
+ const createdOn = 'ISGREATERTHAN ' + createdOnStringMinus1;
143
+
144
+ const snapshots = await new Entities().get({
145
+ entityName: 'entity-snapshot',
146
+ criteria: {
147
+ entityReference,
148
+ createdOn
149
+ }
150
+ });
151
+
152
+ const assortmentPublishChangeId = apc?.id;
153
+ const snapshot = snapshots.find(snap => snap?.assortmentChangeId === assortmentPublishChangeId);
154
+ let snapshotVersion = 'unknown';
155
+ if(snapshot && snapshot.versionNumber){
156
+ snapshotVersion = snapshot.versionNumber;
157
+ } else if(!snapshot && snapshots.length > 0){
158
+ const createdOnTime = new Date(createdOnString).getTime();
159
+ const lastSnapshot = snapshots[snapshots.length - 1];
160
+ if(lastSnapshot?.createdOn && createdOnTime > new Date(lastSnapshot.createdOn).getTime()){
161
+ snapshotVersion = 'after: ' + lastSnapshot.versionNumber;
162
+ }
163
+
164
+ }
165
+
166
+ return snapshotVersion;
167
+ }
168
+ async getSeasonFederation(assortmentId): Promise<SeasonFederation> {
169
+ const assortment = await this.getAssortment(assortmentId);
170
+ console.error('assortment-name: ' + assortment?.name);
171
+
172
+ const publishToFlexPLM = assortment?.publishToFlexPLM;
173
+ if (!publishToFlexPLM) {
174
+ throw new Error(BaseProcessPublishAssortment.ASSORTMENT_NOT_PUBLISHABLE);
175
+ }
176
+
177
+ const assortmentObj = await this.dc.getFlexPLMObjectData(assortment, [], true);
178
+ let seasonObj: any = {
179
+ entityReference: 'assortment:' + assortmentId,
180
+ objectClass: 'LCSSeason' as const,
181
+ };
182
+
183
+ const identifierKeys: string[] = await TypeConversionUtils.getIdentifierProperties(this.transformMapFile, this.mapFileUtil, assortmentObj);
184
+ const informationKeys: string[] = await TypeConversionUtils.getInformationalProperties(this.transformMapFile, this.mapFileUtil, assortmentObj);
185
+ for (const key of identifierKeys.concat(informationKeys)) {
186
+ if (assortmentObj[key]) {
187
+ seasonObj[key] = assortmentObj[key];
188
+ }
189
+ }
190
+ const objectKeys = Object.keys(seasonObj);
191
+ const hasAllIdentifiers = identifierKeys.every(key => objectKeys.includes(key));
192
+
193
+ if (!hasAllIdentifiers) {
194
+ throw new Error(BaseProcessPublishAssortment.ASSORTMENT_NO_FED_INFO + identifierKeys);
195
+ }
196
+
197
+ seasonObj = await MapUtil.applyTransformMap(this.transformMapFile, this.mapFileUtil, seasonObj, 'LCSSeason', 'vibe2flex');
198
+ return seasonObj as SeasonFederation;
199
+ }
200
+
201
+ async getAssortment(assortmentId: any) {
202
+ if(this.assortment != undefined){
203
+ return this.assortment;
204
+ }
205
+
206
+ this.assortment = await new Entities().get({
207
+ entityName: 'assortment',
208
+ id: assortmentId
209
+ });
210
+ return this.assortment;
211
+ }
212
+
213
+ public async getSinceDate(assortmentId: any, assortmentPublishChangeId: any, apcHistory: object[]): Promise<Date> {
214
+
215
+ let sinceDate = null;
216
+
217
+ let pastPublishCount = 1;
218
+ if (this.config?.sinceDate) {
219
+ const sinceDateString = '' + this.config?.sinceDate;
220
+ if(sinceDateString && sinceDateString.indexOf('-') > 0){
221
+ const sinceDateParts = sinceDateString.split('-');
222
+ if(sinceDateParts.length == 3){
223
+ const year = parseInt(sinceDateParts[0]);
224
+ const month = parseInt(sinceDateParts[1]) - 1;
225
+ const day = parseInt(sinceDateParts[2]);
226
+ const minutes = 0 - new Date().getTimezoneOffset();
227
+ sinceDate = this.getSinceDateFromAPCSpecificDate(apcHistory, assortmentPublishChangeId, new Date(year, month, day, 0, minutes, 0));
228
+ }
229
+ } else if(sinceDateString && sinceDateString.indexOf(':') > 0){
230
+ const sinceDateParts = sinceDateString.split(':');
231
+ const type = sinceDateParts[0];
232
+ const count = parseInt(sinceDateParts[1]);
233
+ if('numberofdays' == type.toLocaleLowerCase()){
234
+ sinceDate = this.getSinceDateDaysPrevious(apcHistory, assortmentPublishChangeId, count);
235
+ } else if('numberofpublishes' == type.toLocaleLowerCase()){
236
+ pastPublishCount = count;
237
+ }
238
+
239
+ }
240
+ }
241
+
242
+ if(sinceDate == null) {
243
+ sinceDate = this.getSinceDateFromAPCs(apcHistory, assortmentPublishChangeId, pastPublishCount);
244
+ }
245
+ if(sinceDate == null){
246
+ throw new Error('Couldnt set sinceDate');
247
+ }
248
+ console.info('getSinceDate: ' + sinceDate);
249
+ return sinceDate;
250
+ }
251
+
252
+ async getApcHistory(assortmentId: any) {
253
+ const resource = `/assortments/${assortmentId}/history/`;
254
+ return Request.request(resource, {
255
+ method: 'GET',
256
+ headers: {
257
+ Accept: 'application/json',
258
+ 'Content-Type': 'application/json'
259
+ }
260
+ });
261
+ }
262
+
263
+ protected updatedSinceDate(entity, sinceDate: Date): boolean {
264
+ const updatedOn = entity?.updatedOn;
265
+ return (updatedOn && new Date(updatedOn) > sinceDate);
266
+ }
267
+
268
+ getSinceDateFromAPCSpecificDate(apcHistory: any[], assortmentPublishChangeId: string, specificDate: Date):Date {
269
+ const apc = apcHistory.find(apc => apc?.id === assortmentPublishChangeId);
270
+ const apcDate = new Date(apc?.createdOn);
271
+ let afterDate = apcDate;
272
+ let beforeDate = new Date(0);
273
+ const sinceDate = specificDate;
274
+ for (const tempapc of apcHistory) {
275
+ if (assortmentPublishChangeId !== tempapc?.id) {
276
+ const tempDate = new Date(tempapc?.createdOn);
277
+ if (tempDate < apcDate) {
278
+ if(tempDate > sinceDate && tempDate < afterDate){
279
+ afterDate = tempDate;
280
+ } else if(tempDate < sinceDate && tempDate > beforeDate){
281
+ beforeDate = tempDate;
282
+ }
283
+ }
284
+ }
285
+ }
286
+ const selectedDate = (beforeDate.getTime() !== 0)?beforeDate : afterDate;
287
+ return selectedDate;
288
+ }
289
+ getSinceDateDaysPrevious(apcHistory: any[], assortmentPublishChangeId: string, daysBack):Date {
290
+ const apc = apcHistory.find(apc => apc?.id === assortmentPublishChangeId);
291
+ const apcDate = new Date(apc?.createdOn);
292
+ let afterDate = apcDate;
293
+ let beforeDate = new Date(0);
294
+ const sinceDate = new Date(
295
+ apcDate.getUTCFullYear(),
296
+ apcDate.getUTCMonth(),
297
+ apcDate.getUTCDate()-daysBack,
298
+ 0,
299
+ (0 - apcDate.getTimezoneOffset()),
300
+ 0);
301
+
302
+ for (const tempapc of apcHistory) {
303
+ if (assortmentPublishChangeId !== tempapc?.id) {
304
+ const tempDate = new Date(tempapc?.createdOn);
305
+ if (tempDate < apcDate) {
306
+ if(tempDate > sinceDate && tempDate < afterDate){
307
+ afterDate = tempDate;
308
+ } else if(tempDate < sinceDate && tempDate > beforeDate){
309
+ beforeDate = tempDate;
310
+ }
311
+ }
312
+ }
313
+ }
314
+ const selectedDate = (beforeDate.getTime() !== 0)?beforeDate : afterDate;
315
+ return selectedDate;
316
+ }
317
+
318
+ getSinceDateFromAPCs(apcHistory: any[], assortmentPublishChangeId: string, pastPublishCount = 1): Date {
319
+ if(apcHistory.length === 1){
320
+ return new Date(0);
321
+ }
322
+ const apcIndex = apcHistory.findIndex(apc => apc.id === assortmentPublishChangeId);
323
+ if(apcIndex === 0){
324
+ return new Date(0);
325
+ }
326
+ const apc = apcHistory[apcIndex];
327
+ const apcDate = new Date(apc?.createdOn);
328
+ let sinceDate = new Date(0);
329
+ const dateArray = [];
330
+ for (const tempapc of apcHistory) {
331
+ if (assortmentPublishChangeId !== tempapc?.id) {
332
+ const tempDate = new Date(tempapc?.createdOn);
333
+ if (tempDate < apcDate) {
334
+ dateArray.push(tempDate);
335
+ }
336
+ }
337
+ }
338
+ dateArray.sort((a,b) => { return Date.parse(a) - Date.parse(b);});
339
+ const arrIndex = (dateArray.length - pastPublishCount > 0)? dateArray.length - pastPublishCount: 0;
340
+ sinceDate = dateArray[arrIndex];
341
+ return sinceDate;
342
+ }
343
+ protected getPublisher(assortmentPublishChange) {
344
+ const createdBy = assortmentPublishChange?.createdBy;
345
+ const publisher = {};
346
+ const includeKeys = ['email', 'firstName', 'isSsoUser', 'lastName'];
347
+ for(const [key, value] of Object.entries(createdBy)){
348
+ if(includeKeys.includes(key)){
349
+ publisher[key] = value;
350
+ }
351
+ }
352
+
353
+ return publisher;
354
+
355
+ }
356
+
357
+ async downloadAssortmentPublishChange(assortmentId: string, assortmentPublishChangeId: string) {
358
+ const resourceString = '/assortments/' + assortmentId + '/history/' + assortmentPublishChangeId + '?relations=createdBy';
359
+ return await Request.request(
360
+ resourceString,
361
+ {
362
+ method: 'GET',
363
+ Headers: {
364
+ Accept: 'application/json',
365
+ 'Content-Type': 'application/json'
366
+ }
367
+ }
368
+ );
369
+ }
370
+
371
+ async downloadHydratedChangeDetail(assortmentPublishChange) {
372
+ try {
373
+ console.info('downloadHydratedChangeDetail-start');
374
+ const link = assortmentPublishChange?.hydratedDetailDownloadLink;
375
+ const response = await fetch(link);
376
+ const data = await response.json();
377
+ return data;
378
+
379
+ } catch (e) {
380
+ console.log('Error hydratedDetailDownloadLink: ' + e.message);
381
+ }
382
+ return undefined;
383
+ }
384
+
385
+ async downloadAssortmentBaseline(assortmentPublishChange) {
386
+ console.info('downloadAssortmentBaseline-start');
387
+ try {
388
+ const link = assortmentPublishChange?.assortmentBaselineDownloadLink;
389
+ const response = await fetch(link);
390
+ const data = await response.json();
391
+ return data;
392
+
393
+ } catch (e) {
394
+ console.log('Error assortmentBaselineDownloadLink: ' + e.message);
395
+ }
396
+ return undefined;
397
+ }
398
+
399
+ async getDeleteChanges(assortmentPublishChange, apcHistory: any[], assortmentBaseline, sinceDate: Date): Promise<[]>{
400
+ console.info('getDeleteChanges(): ' + assortmentPublishChange?.id);
401
+ console.info(sinceDate);
402
+ const currentAPCIndex = apcHistory.findIndex(pc => pc?.id === assortmentPublishChange?.id);
403
+ console.info(' currentAPCIndex: ' + currentAPCIndex);
404
+ if(currentAPCIndex == 0){
405
+ return [];
406
+ }
407
+ const previousApcIndex = (currentAPCIndex > 0)? currentAPCIndex-1: 0;
408
+
409
+ const apcCreatedOn = apcHistory[previousApcIndex]?.createdOn;
410
+ const apcDeletes = await this.downloadDeleteChanges(assortmentPublishChange);
411
+
412
+ let previousApcDate = Date.parse(apcCreatedOn);
413
+ const sinceDateMilliseconds = sinceDate.getTime();
414
+ if(Logger.isInfoOn()){
415
+ console.info('apcCreatedOn: ' + apcCreatedOn);
416
+ console.info('sinceDate: ' + sinceDate);
417
+ console.info('sinceDateMilliseconds: ' + sinceDateMilliseconds);
418
+ console.info('apcDateMilliseconds: ' + previousApcDate);
419
+ }
420
+ //if only 1 apc, no processing needed
421
+ if(sinceDateMilliseconds !== previousApcDate){
422
+ console.info('sinceDateMilliseconds !== apcDateMilliseconds');
423
+ const currentAssortmentItemIds = this.getBaselineItemIds(assortmentBaseline);
424
+ const deleteIds = (apcDeletes.length === 0)
425
+ ?[]
426
+ :apcDeletes.map(item => item?.itemId);
427
+
428
+ for(let i = currentAPCIndex -1; i > 0; i--) {
429
+ const workingAPC = apcHistory[i];
430
+ previousApcDate = Date.parse(workingAPC?.createdOn);
431
+ if(sinceDateMilliseconds === previousApcDate){
432
+ break;
433
+ }
434
+ if(workingAPC?.deletes > 0){
435
+ const previousApc = (i > 0)
436
+ ?apcHistory[i-1]
437
+ :undefined;
438
+ const deleteChanges = await this.buildDeleteChanges(workingAPC, previousApc);
439
+ console.info('checking deleteChanges');
440
+ for(const dItem of deleteChanges){
441
+ const dItemId = dItem?.itemId;
442
+ console.info(dItemId);
443
+ if(!currentAssortmentItemIds.includes(dItemId) && !deleteIds.includes(dItemId)){
444
+ console.info('adding');
445
+ deleteIds.push(dItemId);
446
+ apcDeletes.push(dItem);
447
+ }
448
+ }
449
+ }
450
+ }
451
+ console.info('getDeleteChanges()-currentAssortmentItemIds: ' + currentAssortmentItemIds);
452
+ console.info('getDeleteChanges()-deleteIds: ' + deleteIds);
453
+ }
454
+
455
+ return apcDeletes;
456
+ }
457
+
458
+ getBaselineItemIds(assortmentBaseline): string[]{
459
+ const itemIds = [];
460
+ const assortmentItemsArray = assortmentBaseline?.assortmentItems;
461
+
462
+ for (const aItem of assortmentItemsArray) {
463
+ itemIds.push(aItem?.itemId);
464
+ }
465
+
466
+ return itemIds;
467
+ }
468
+
469
+ async downloadDeleteChanges(apc) {
470
+ console.info('deleteDataDownloadLink-start');
471
+ try {
472
+ const link = apc?.deleteDataDownloadLink;
473
+ const response = await fetch(link);
474
+ const data = await response.json();
475
+ return data;
476
+
477
+ } catch (e) {
478
+ console.log('Error deleteDataDownloadLink: ' + e.message);
479
+ }
480
+ return undefined;
481
+ }
482
+
483
+ async buildDeleteChanges(apc, previousApc) {
484
+ console.info('buildDeleteChanges()');
485
+
486
+ if(apc?.deleteDataDownloadLink){
487
+ const deleteChanges = await this.downloadDeleteChanges(apc);
488
+ if(deleteChanges){
489
+ return deleteChanges;
490
+ }
491
+ }
492
+ console.info('pulling down full APC');
493
+ apc = await this.downloadAssortmentPublishChange(apc?.assortmentId, apc?.id);
494
+ if(apc?.deleteDataDownloadLink){
495
+ const deleteChanges = await this.downloadDeleteChanges(apc);
496
+ if(deleteChanges){
497
+ return deleteChanges;
498
+ }
499
+ }
500
+ if(!previousApc){
501
+ throw new Error(BaseProcessPublishAssortment.NOT_ABLE_TO_PROCESS_DELETE_CHANGES);
502
+ }
503
+
504
+ let previousBaseline;
505
+ console.info('check previousApc');
506
+ if(previousApc?.assortmentBaselineDownloadLink){
507
+ previousBaseline = await this.downloadAssortmentBaseline(previousApc);
508
+ }else {
509
+ console.info('previousApc pulling down full APC');
510
+ previousApc = await this.downloadAssortmentPublishChange(previousApc?.assortmentId, previousApc?.id);
511
+ previousBaseline = await this.downloadAssortmentBaseline(previousApc);
512
+ }
513
+
514
+ const deleteIds = apc?.detail?.deletes.map(dItem => dItem?.id);
515
+
516
+ //building deletes based on previous baseline; because some APCs don't have delete data
517
+ const deleteArray = previousBaseline?.assortmentItems.filter(aItem => deleteIds.includes(aItem?.itemId));
518
+ console.info('deleteArray.length: ' + deleteArray.length);
519
+ return deleteArray;
520
+ }
521
+
522
+ async getItemFederatedIds(/*itemIds*/): Promise<Map<string, string>> {
523
+
524
+ const itemFederatedIds = new Map<string, string>();
525
+ // const expandedItemIds = itemIds.map(id => 'item:' + id);
526
+ // const fedRecords = await new Federation(this.logger).getFederationRecordsFromIdsBulk(expandedItemIds);
527
+ // for (let i = 0; i < fedRecords.length; i++) {
528
+ // const federationRecord = fedRecords[i];
529
+ // // console.log('federationRecord: ' + JSON.stringify(federationRecord));
530
+ // // console.log('federationRecord.reference: ' + federationRecord.reference);
531
+ // // console.log('federationRecord.mappedReference: ' + federationRecord.mappedReference);
532
+ // let vibeId = federationRecord.reference;
533
+ // if (vibeId && vibeId.startsWith('item:')) {
534
+ // vibeId = vibeId.substring(5);
535
+ // }
536
+ // itemFederatedIds.set(vibeId, federationRecord.mappedReference);
537
+ // }
538
+ // console.log('itemFederatedIds: ' + JSON.stringify(Object.fromEntries(itemFederatedIds)));
539
+ return itemFederatedIds;
540
+ }
541
+
542
+ getFullChangeAssortmentMap(fullChange: any): Map<string, object> {
543
+ const assortmentItemsArray = fullChange?.assortmentItems || [];
544
+ const assortmentItemsMap = new Map<string, object>();
545
+
546
+ for (const aItem of assortmentItemsArray) {
547
+ const itemId = aItem?.itemId;
548
+ assortmentItemsMap.set(itemId, aItem);
549
+ }
550
+
551
+ return assortmentItemsMap;
552
+ }
553
+
554
+ getDeleteChangesAssortmentMap(deleteChanges: any[]): Map<string, object> {
555
+ const deleteItems = new Map<string, object>();
556
+
557
+ for (const dItem of deleteChanges) {
558
+ deleteItems.set(dItem?.itemId, dItem);
559
+ }
560
+
561
+ return deleteItems;
562
+ }
563
+
564
+ getReleasedForDevelopmentItemAndFamilyIds(fullChange, deleteChanges): string[] {
565
+ console.info('getReleasedForDevelopmentItemAndFamilyIds');
566
+ const releasedForDevelopmentItemIds:string[] = [];
567
+ const itemFamilySet = new Set<string>();
568
+ const assortmentItemsArray = fullChange?.assortmentItems;
569
+
570
+ for (const aItem of assortmentItemsArray) {
571
+ const meetsCriteria= this.meetsCriteria(aItem);
572
+ const item = aItem?.item;
573
+ const itemId = item?.id;
574
+ const itemFamilyId = item?.itemFamilyId;
575
+ if(meetsCriteria){
576
+ releasedForDevelopmentItemIds.push(itemId);
577
+ if(!itemFamilySet.has(itemFamilyId) && itemId !== itemFamilyId){
578
+ const familyItem = item?.itemFamily;
579
+ const familyItemMeetsCriteria = this.meetsCriteria({item: familyItem});
580
+ if(familyItemMeetsCriteria){
581
+ releasedForDevelopmentItemIds.push(itemFamilyId);
582
+ }
583
+ itemFamilySet.add(itemFamilyId);
584
+ }
585
+ }
586
+ }
587
+
588
+ for(const dItem of deleteChanges){
589
+ const meetsCriteria = this.meetsCriteria(dItem);
590
+ const item = dItem?.item;
591
+ const itemId = item?.id;
592
+ const itemFamilyId = item?.itemFamilyId;
593
+ if(meetsCriteria) {
594
+ releasedForDevelopmentItemIds.push(itemId);
595
+ if(!itemFamilySet.has(itemFamilyId) && itemId !== itemFamilyId){
596
+ const familyItem = item?.itemFamily;
597
+ if(familyItem){
598
+ const familyItemMeetsCriteria = this.meetsCriteria({item: familyItem});
599
+ if(familyItemMeetsCriteria){
600
+ releasedForDevelopmentItemIds.push(itemFamilyId);
601
+ }
602
+ itemFamilySet.add(itemFamilyId);
603
+ }else{
604
+ itemFamilySet.add(itemFamilyId);
605
+ }
606
+ }
607
+ }
608
+ }
609
+ console.info('releasedForDevelopmentItemIds: ' + releasedForDevelopmentItemIds);
610
+ return releasedForDevelopmentItemIds;
611
+ }
612
+
613
+ meetsCriteria(aItem): boolean {
614
+ const item = aItem?.item;
615
+ const lifecycleStage = item?.lifecycleStage;
616
+
617
+ return !!lifecycleStage && !this.config.itemPreDevelopmentLifecycleStages.includes(lifecycleStage);
618
+ }
619
+ async processPublish(pcd: PublishChangeData, changeDetail, fullChange, deleteChanges) {
620
+ console.info('processPublish-start');
621
+ const event = {
622
+ assortmentId: pcd.assortmentId,
623
+ assortmentPublishChangeId: pcd.assortmentPublishChangeId
624
+ };
625
+
626
+ const assortmentItemFullChangeMap = this.getFullChangeAssortmentMap(fullChange);
627
+ const assortmentItemDeleteMap = this.getDeleteChangesAssortmentMap(deleteChanges);
628
+ pcd.itemFamilyChanges = this.getItemFamilyChanges(pcd, changeDetail, assortmentItemFullChangeMap, assortmentItemDeleteMap);
629
+
630
+ const events = await this.getEventsForPublishChangeData(pcd);
631
+ if (events.length === 0) {
632
+ const processStatus = 'BaseProcessPublishAssortment: ' + EventShortMessageStatus.NO_EVENTS_TO_SEND
633
+ + ': assortmentId: ' + pcd.assortmentId + ': assortmentPublishChangeId: ' + pcd.assortmentPublishChangeId
634
+ + ', orgSlug: ' + this.orgSlug;
635
+ console.log(processStatus);
636
+ const message = 'No Events to Send; returning';
637
+ console.log(message);
638
+ return {
639
+ results: { message, event },
640
+ skip_await: true
641
+ };
642
+
643
+ }
644
+
645
+ const results = await this.sendEvents(events);
646
+ const resultsCount = this.getResultsCount(events);
647
+ const processStatus = 'BaseProcessPublishAssortment: ' + EventShortMessageStatus.SENDING_EVENTS
648
+ + ': assortmentId: ' + pcd.assortmentId + ': assortmentPublishChangeId: ' + pcd.assortmentPublishChangeId
649
+ + ': resultsCount: ' + JSON.stringify(resultsCount)
650
+ + ', orgSlug: ' + this.orgSlug;
651
+ console.log(processStatus);
652
+ return { results, event, resultsCount };
653
+
654
+ }
655
+
656
+ getResultsCount(events) {
657
+ return events.reduce((acc, event) => {
658
+ const objectClass = event?.objectClass;
659
+ if (objectClass === 'LCSProductSeasonLink') {
660
+ acc.productSeasons++;
661
+ }
662
+ else if (objectClass === 'LCSSKUSeasonLink') {
663
+ acc.colorwaySeasons++;
664
+ }
665
+ return acc;
666
+ }, { productSeasons: 0, colorwaySeasons: 0 });
667
+ }
668
+
669
+ private async sendEvents(events: SeasonalPayload[]): Promise<any> {
670
+ console.info('sendEvents()');
671
+ const eventType = 'ASYNC_PUBLISH_SEASON';
672
+ const sendMode = (this.config?.sendMode[eventType] || '').toLowerCase();
673
+
674
+ switch (sendMode) {
675
+ case 'sendtoflexplm':
676
+ return this.sendToFlexPLM(events, eventType);
677
+ case 'localfile':
678
+ return this.saveToLocalFile(events, eventType);
679
+ case 'vibeiqfile':
680
+ case 'vibeiqfile-dontsendtoflexplm':
681
+ return this.handleVibeIQFile(events, eventType, sendMode);
682
+ default:
683
+ return {}; // Or handle other cases as required
684
+ }
685
+ }
686
+
687
+ private async sendToFlexPLM(events: SeasonalPayload[], eventType: string) {
688
+ const asyncEvent: AsyncEventsPayloadType = {
689
+ taskId: this.config.taskId,
690
+ eventType,
691
+ objectClass: 'LCSSeason',
692
+ events
693
+ };
694
+
695
+ const flexPLMConnect = new FlexPLMConnect(this.config);
696
+ return await flexPLMConnect.sendToFlexPLM(asyncEvent);
697
+ }
698
+
699
+ private async saveToLocalFile(events: SeasonalPayload[], eventType: string) {
700
+ let results = {};
701
+ let fileHandle;
702
+
703
+ try {
704
+ const dateString = this.getCurrentDateString();
705
+ const dirName = await path.resolve();
706
+ await fsPromise.mkdir(dirName, { recursive: true });
707
+ const eventDirName = 'events-output';
708
+ const fileName = `${path.sep}${eventDirName}${path.sep}events-${dateString}.json`;
709
+ fileHandle = await fsPromise.open('.' + fileName, 'a');
710
+
711
+ const asyncEvent: AsyncEventsPayloadType = {
712
+ taskId: this.config.taskId,
713
+ eventType,
714
+ objectClass: 'LCSSeason',
715
+ events
716
+ };
717
+
718
+ await fileHandle.writeFile(JSON.stringify(asyncEvent));
719
+
720
+ results = {
721
+ message: 'Successfully Saved File',
722
+ fileLocation: dirName + fileName
723
+ };
724
+ } catch (e) {
725
+ results['error'] = e.message;
726
+ } finally {
727
+ await fileHandle?.close();
728
+ }
729
+
730
+ return results;
731
+ }
732
+
733
+ private async handleVibeIQFile(events: SeasonalPayload[], eventType: string, sendMode: string) {
734
+ const eventBuffer = Buffer.from(JSON.stringify(events), 'utf-8');
735
+ const fileName = 'ASYNC_PUBLISH_SEASON-events.json';
736
+ const uploadFile = await new Files().createAndUploadFileFromBuffer(eventBuffer, 'application/json', fileName, null, this.TTL);
737
+
738
+ const asyncEvent: AsyncEventsPayloadType = {
739
+ taskId: this.config.taskId,
740
+ eventType,
741
+ objectClass: 'LCSSeason',
742
+ eventsFileId: uploadFile.id,
743
+ eventsDownloadLink: uploadFile.downloadUrl,
744
+ eventsAdminDownloadLink: uploadFile.adminDownloadUrl
745
+ };
746
+
747
+ if (sendMode === 'vibeiqfile') {
748
+ const flexPLMConnect = new FlexPLMConnect(this.config);
749
+ return await flexPLMConnect.sendToFlexPLM(asyncEvent);
750
+ } else {
751
+ return {
752
+ message: 'Successfully Uploaded File.',
753
+ asyncEvent
754
+ };
755
+ }
756
+ }
757
+
758
+ private getCurrentDateString() {
759
+ const d = new Date();
760
+ return '' + d.getUTCFullYear()
761
+ + '-' + d.getUTCMonth()
762
+ + '-' + (d.getUTCDate() + 1)
763
+ + '-' + d.getUTCHours()
764
+ + '-' + d.getUTCMinutes()
765
+ + '-' + d.getUTCSeconds()
766
+ + '-' + d.getUTCMilliseconds();
767
+ }
768
+
769
+ getItemFamilyChanges(pcd: PublishChangeData, changeDetail, assortmentItemFullChangeMap: Map<string, any>, assortmentItemDeleteMap: Map<string, any>): Map<string, ItemFamilyChanges> {
770
+ console.info('getItemFamilyChanges-start');
771
+
772
+ const itemFamilyChanges = new Map<string, ItemFamilyChanges>();
773
+ const { adds, deletes, updates, familyItemsRemoved } = changeDetail;
774
+ const addIds = adds.map(item => item.id);
775
+ const deleteIds = deletes.map(item => item.id);
776
+ const updateIds = updates.map(item => item.id);
777
+ const familyItemsRemovedIds = familyItemsRemoved.map(item => item.itemId);
778
+
779
+ for (const [itemId, aItem] of assortmentItemFullChangeMap) {
780
+ const projectItem = aItem?.projectItem;
781
+ const itemFamilyId = aItem?.item?.itemFamilyId;
782
+
783
+ if (!pcd.releasedForDevelopmentItemIds.includes(itemFamilyId) || !pcd.releasedForDevelopmentItemIds.includes(itemId)) {
784
+ continue;
785
+ }
786
+
787
+ const ifc = itemFamilyChanges.get(itemFamilyId) || new ItemFamilyChanges(itemFamilyId, pcd.sinceDate);
788
+ if (!itemFamilyChanges.has(itemFamilyId)) {
789
+ ifc.itemFamilyObject = itemId === itemFamilyId ? aItem?.item : aItem?.item?.itemFamily;
790
+ itemFamilyChanges.set(itemFamilyId, ifc);
791
+ }
792
+
793
+ ifc.assortmentItemFullChangeMap.set(itemId, aItem);
794
+ if (pcd.itemToFederatedIdMapping.has(itemId)) {
795
+ ifc.itemToFederatedIdMapping.set(itemId, pcd.itemToFederatedIdMapping.get(itemId));
796
+ }
797
+
798
+ if (itemId === itemFamilyId) {
799
+ if (addIds.includes(itemId)) ifc.familyAdd = true;
800
+ else if (deleteIds.includes(itemId)) ifc.familyDelete = true;
801
+ else if (updateIds.includes(itemId)) ifc.familyUpdate = true;
802
+ else if (familyItemsRemovedIds.includes(itemId)) ifc.familyItemRemoved = true;
803
+
804
+ if (projectItem) {
805
+ const updatedOnDate = new Date(projectItem.updatedOn);
806
+ if (updatedOnDate > pcd.sinceDate) {
807
+ ifc.familyUpdate = true;
808
+ }
809
+ }
810
+
811
+ if (projectItem && !projectItem?.roles && aItem?.item?.roles) {
812
+ projectItem.roles = aItem?.item?.roles;
813
+ }
814
+
815
+ } else {
816
+ if (addIds.includes(itemId)) ifc.colorAdds.push(itemId);
817
+ else if (deleteIds.includes(itemId)) ifc.colorDeletes.push(itemId);
818
+ else if (updateIds.includes(itemId)) ifc.colorUpdates.push(itemId);
819
+ else if (projectItem && new Date(projectItem.updatedOn) > pcd.sinceDate) ifc.colorUpdates.push(itemId);
820
+ else ifc.colorUnchanged.push(itemId);
821
+
822
+ if (projectItem && !projectItem?.roles && aItem?.item?.roles) {
823
+ projectItem.roles = aItem?.item?.roles;
824
+ }
825
+ }
826
+ }
827
+
828
+ for(const [itemId, delEntity] of assortmentItemDeleteMap){
829
+ const itemFamilyId = delEntity?.item?.itemFamilyId;
830
+
831
+ const item = delEntity?.item;
832
+ if(!pcd.releasedForDevelopmentItemIds.includes(itemFamilyId) || !pcd.releasedForDevelopmentItemIds.includes(itemId)){
833
+ continue;
834
+ } else {
835
+ if(!item){
836
+ console.error('Failed to find deleted item entity');
837
+ console.error(' itemFamilyId: ' + itemFamilyId + ' -itemId: ' + itemId);
838
+ continue;
839
+ }
840
+
841
+ }
842
+
843
+ let ifc = itemFamilyChanges.get(itemFamilyId);
844
+ if(!ifc){
845
+ ifc = new ItemFamilyChanges(itemFamilyId, pcd.sinceDate);
846
+ if(itemId === itemFamilyId){
847
+ ifc.familyDelete = true;
848
+ ifc.itemFamilyObject = item;
849
+ } else{
850
+ ifc.itemFamilyObject = item?.itemFamily;
851
+ }
852
+ itemFamilyChanges.set(itemFamilyId, ifc);
853
+ }
854
+ if(pcd.itemToFederatedIdMapping.has(itemId)){
855
+ ifc.itemToFederatedIdMapping.set(itemId, pcd.itemToFederatedIdMapping.get(itemId));
856
+ }
857
+ ifc.assortmentItemDeleteMap.set(itemId, delEntity);
858
+ ifc.assortmentItemFullChangeMap.set(itemId, delEntity);
859
+
860
+ if(itemId === itemFamilyId){
861
+ ifc.familyDelete = true;
862
+ }else {
863
+ ifc.colorDeletes.push(itemId);
864
+ }
865
+ }//End deletes for loop
866
+ if(Logger.isDebugOn()){
867
+ console.debug('returning size: ' + itemFamilyChanges.size);
868
+ for (const [key, value] of itemFamilyChanges){
869
+ console.debug(key + ' => ' + value);
870
+ }
871
+ }
872
+
873
+
874
+ return itemFamilyChanges;
875
+ }
876
+
877
+ async getEventsForPublishChangeData(publishChangeData: PublishChangeData): Promise<SeasonalPayload[]> {
878
+ console.info('getEventsForPublishChangeData-start');
879
+ const seasonalPayloads: SeasonalPayload[] = [];
880
+ for (const itemFamilyChange of publishChangeData.itemFamilyChanges.values()) {
881
+ const events = await this.getEventsForItemFamilyChanges(itemFamilyChange, publishChangeData.assortmentId, publishChangeData.seasonFed, publishChangeData.itemToFederatedIdMapping);
882
+ if (events.length > 0) {
883
+ seasonalPayloads.push(...events);
884
+ }
885
+ }
886
+ return seasonalPayloads;
887
+ }
888
+
889
+ /**Returns the events for a given ItemFamilyChanges object
890
+ *
891
+ * Cases:
892
+ * Add just family:
893
+ * Add option to family (with existing option):
894
+ * Add option to family (no options on assortment):
895
+ * Remove family and option:
896
+ * Remove only option and leave family:
897
+ * Remove one option of multiple for family:
898
+ *
899
+ * @param itemFamilyChanges
900
+ * @param assortmentId
901
+ * @param assortmentFederationId
902
+ * @param itemToFederatedIdMapping
903
+ * @returns
904
+ */
905
+ async getEventsForItemFamilyChanges(itemFamilyChanges: ItemFamilyChanges, assortmentId: string, seasonFed: SeasonFederation, itemToFederatedIdMapping: Map<string, string>): Promise<SeasonalPayload[]> {
906
+ console.info('getEventsForItemFamilyChanges()');
907
+ const events: SeasonalPayload[] = [];
908
+ const LCSSeason = Object.assign({}, seasonFed);
909
+ const assortment = await this.getAssortment(assortmentId);
910
+ const projectItem = this.getProjectItem(itemFamilyChanges, itemFamilyChanges.itemFamilyId);
911
+ const familyAssortmentItem = itemFamilyChanges.familyAdd || itemFamilyChanges.familyUpdate || itemFamilyChanges.familyDelete
912
+ || itemFamilyChanges.colorAdds.length > 0 || itemFamilyChanges.colorUpdates.length > 0 || itemFamilyChanges.colorDeletes.length > 0
913
+ || (projectItem && this.updatedSinceDate(projectItem, itemFamilyChanges.sinceDate));
914
+ //familyItemRemoved is used when adding the first option to an assortment
915
+ //and will have updates for the family item.
916
+
917
+ if (familyAssortmentItem) {
918
+ //Product-season add
919
+ const entityReference = itemFamilyChanges.itemFamilyId;
920
+ const prodEntityData = (itemFamilyChanges.assortmentItemFullChangeMap.has(entityReference))
921
+ ? itemFamilyChanges.assortmentItemFullChangeMap.get(entityReference)?.item
922
+ : itemFamilyChanges.itemFamilyObject;
923
+
924
+ let seasonalData = await this.getSeasonalData(projectItem);
925
+ seasonalData = await MapUtil.applyTransformMap(this.transformMapFile, this.mapFileUtil, seasonalData, 'LCSProductSeasonLink', 'vibe2flex');
926
+
927
+ const LCSProduct: ProductFederation = await this.getProductFederation(entityReference, itemToFederatedIdMapping, prodEntityData);
928
+
929
+ const isCreatable = await TypeConversionUtils.isOutboundCreatableFromEntity(this.transformMapFile, this.mapFileUtil, projectItem, { item: prodEntityData, assortment });
930
+ const eventType = isCreatable ? 'UPSERT_ON_SEASON' : 'UPDATE_ON_SEASON';
931
+
932
+ const psUpsert: SeasonalPayload = {
933
+ eventType,
934
+ objectClass: 'LCSProductSeasonLink',
935
+ entityReference: 'item:' + entityReference,
936
+ LCSSeason,
937
+ LCSProduct,
938
+ data: seasonalData
939
+ };
940
+
941
+ if('ASSORTMENT' === projectItem.addedFromSource && projectItem.addedFromAssortment){
942
+ const carriedFromSeason = await this.getCarriedFromSeason(projectItem);
943
+ if(carriedFromSeason){
944
+ psUpsert['carriedFromSeason'] = carriedFromSeason;
945
+ }
946
+ }
947
+
948
+ events.push(psUpsert);
949
+ }
950
+ //colorway-season adds
951
+ //colorAdds
952
+ //colorUpdates
953
+ const colorwayChanges = [];
954
+ colorwayChanges.push(...itemFamilyChanges.colorAdds);
955
+ colorwayChanges.push(...itemFamilyChanges.colorUpdates);
956
+ colorwayChanges.push(...itemFamilyChanges.colorDeletes);
957
+
958
+ for (const entityReference of colorwayChanges) {
959
+ let item = {};
960
+ if (itemFamilyChanges.assortmentItemFullChangeMap.has(entityReference)) {
961
+ const fullAi = itemFamilyChanges.assortmentItemFullChangeMap.get(entityReference);
962
+ item = fullAi?.item;
963
+ }
964
+ const projectItem = this.getProjectItem(itemFamilyChanges, entityReference);
965
+ let seasonalData = await this.getSeasonalData(projectItem);
966
+ seasonalData = await MapUtil.applyTransformMap(this.transformMapFile, this.mapFileUtil, seasonalData, 'LCSSKUSeasonLink', 'vibe2flex');
967
+
968
+ const LCSSKU: SkuFederation = await this.getSKUFederation(entityReference, itemToFederatedIdMapping, item);
969
+
970
+ const isCreatable = await TypeConversionUtils.isOutboundCreatableFromEntity(this.transformMapFile, this.mapFileUtil, projectItem, { item, assortment });
971
+ const eventType = isCreatable ? 'UPSERT_ON_SEASON' : 'UPDATE_ON_SEASON';
972
+
973
+ const csUpsert: SeasonalPayload = {
974
+ eventType,
975
+ objectClass: 'LCSSKUSeasonLink',
976
+ entityReference: 'item:' + entityReference,
977
+ LCSSeason,
978
+ LCSSKU,
979
+ data: seasonalData
980
+
981
+ };
982
+
983
+ if('ASSORTMENT' === projectItem.addedFromSource && projectItem.addedFromAssortment){
984
+ const carriedFromSeason = await this.getCarriedFromSeason(projectItem);
985
+ if(carriedFromSeason){
986
+ csUpsert['carriedFromSeason'] = carriedFromSeason;
987
+ }
988
+ }
989
+
990
+ events.push(csUpsert);
991
+ }
992
+
993
+ return events;
994
+
995
+ }
996
+
997
+ getProjectItem(itemFamilyChanges: ItemFamilyChanges, id: string) {
998
+ let projectItem: any = {};
999
+ if (itemFamilyChanges?.assortmentItemFullChangeMap.has(id)) {
1000
+ const aItem = itemFamilyChanges?.assortmentItemFullChangeMap.get(id);
1001
+ projectItem = aItem?.projectItem;
1002
+ }
1003
+ /////////////////////////////////////////////////////////////////////////////
1004
+ //Get from option assortmentItem because family not in assortmentItemFullChangeMap:start
1005
+ /////////////////////////////////////////////////////////////////////////////
1006
+ if (id === itemFamilyChanges.itemFamilyId && Object.keys(projectItem).length == 0) {
1007
+ for (const asstItem of itemFamilyChanges.assortmentItemFullChangeMap.values()) {
1008
+ if(asstItem?.familyProjectItem){
1009
+ projectItem = asstItem?.familyProjectItem;
1010
+ break;
1011
+ }
1012
+ }
1013
+ }
1014
+ /////////////////////////////////////////////////////////////////////////////
1015
+ //Get from option assortmentItem because family not in assortmentItemFullChangeMap:end
1016
+ /////////////////////////////////////////////////////////////////////////////
1017
+ return projectItem;
1018
+ }
1019
+
1020
+ async getSeasonalData(projectItem): Promise<object> {
1021
+ return await this.dc.getFlexPLMObjectData(projectItem, [], true);
1022
+ }
1023
+
1024
+ protected async getProductFederation(entityReference: string, itemToFederatedIdMapping: Map<string, string>, itemFamilyObject): Promise<ProductFederation> {
1025
+ const itemObj = await this.dc.getFlexPLMObjectData(itemFamilyObject, [], true);
1026
+ let prodObj: ProductFederation = {
1027
+ entityReference: 'item:' + entityReference,
1028
+ objectClass: 'LCSProduct' as const,
1029
+ };
1030
+
1031
+ const identifierKeys: string[] = await TypeConversionUtils.getIdentifierProperties(this.transformMapFile, this.mapFileUtil, itemFamilyObject);
1032
+ const informationKeys: string[] = await TypeConversionUtils.getInformationalProperties(this.transformMapFile, this.mapFileUtil, itemFamilyObject);
1033
+ for (const key of identifierKeys.concat(informationKeys)) {
1034
+ if (itemObj[key]) {
1035
+ prodObj[key] = itemObj[key];
1036
+ }
1037
+ }
1038
+
1039
+ if (!prodObj?.vibeIQIdentifier) {
1040
+ prodObj.vibeIQIdentifier = itemFamilyObject?.identifier || itemFamilyObject?.itemNumber;
1041
+ }
1042
+
1043
+ prodObj = await MapUtil.applyTransformMap(this.transformMapFile, this.mapFileUtil, prodObj, 'LCSProduct', 'vibe2flex');
1044
+ return prodObj as ProductFederation;
1045
+ }
1046
+
1047
+ protected async getSKUFederation(entityReference: string, itemToFederatedIdMapping: Map<string, string>, itemObject): Promise<SkuFederation> {
1048
+ const itemObj = await this.dc.getFlexPLMObjectData(itemObject, [], true);
1049
+ let skuObj: SkuFederation = {
1050
+ entityReference: 'item:' + entityReference,
1051
+ objectClass: 'LCSSKU' as const,
1052
+ };
1053
+ const identifierKeys: string[] = await TypeConversionUtils.getIdentifierProperties(this.transformMapFile, this.mapFileUtil, itemObject);
1054
+ const informationKeys: string[] = await TypeConversionUtils.getInformationalProperties(this.transformMapFile, this.mapFileUtil, itemObject);
1055
+ for (const key of identifierKeys.concat(informationKeys)) {
1056
+ if (itemObj[key]) {
1057
+ skuObj[key] = itemObj[key];
1058
+ }
1059
+ }
1060
+
1061
+ if (!skuObj?.vibeIQIdentifier) {
1062
+ skuObj.vibeIQIdentifier = itemObject?.identifier || itemObject?.itemNumber;
1063
+ }
1064
+
1065
+ skuObj = await MapUtil.applyTransformMap(this.transformMapFile, this.mapFileUtil, skuObj, 'LCSSKU', 'vibe2flex');
1066
+ return skuObj as SkuFederation;
1067
+ }
1068
+
1069
+ async getCarriedFromSeason(projectItem): Promise<SeasonFederation> {
1070
+ const addedFromAssortment = projectItem.addedFromAssortment;
1071
+ if(this.cache.carriedFromSeason[addedFromAssortment]){
1072
+ return this.cache.carriedFromSeason[addedFromAssortment];
1073
+ }
1074
+ let seasonFederation = undefined;
1075
+ const assortmentEntity = await this.getAssormentEntityFromId(addedFromAssortment);
1076
+ if(assortmentEntity){
1077
+ seasonFederation = await this.getSeasonFederationFromAssortment(assortmentEntity);
1078
+ }
1079
+ this.cache.carriedFromSeason[addedFromAssortment] = seasonFederation;
1080
+
1081
+ return seasonFederation;
1082
+ }
1083
+
1084
+ async getAssormentEntityFromId(assortmentId) {
1085
+ let assortment;
1086
+ try {
1087
+ assortment = await new Entities().get({
1088
+ entityName: 'assortment',
1089
+ id: assortmentId
1090
+ });
1091
+ } catch (e) {
1092
+ console.warn(`No Assortment found for id: ${assortmentId}`);
1093
+ }
1094
+ return assortment;
1095
+ }
1096
+
1097
+ async getSeasonFederationFromAssortment(assortment): Promise<SeasonFederation>{
1098
+
1099
+ assortment['flex2vibeMapKeyRoot'] = 'LCSSeason';
1100
+ const flexPLMTypePath = await TypeConversionUtils.getObjectTypePath(this.transformMapFile, this.mapFileUtil, assortment);
1101
+
1102
+ let seasonObj: any = {
1103
+ entityReference: 'assortment:' + assortment.id,
1104
+ objectClass: 'LCSSeason' as const,
1105
+ flexPLMTypePath
1106
+ };
1107
+
1108
+ try{
1109
+ const assortmentObj = await this.dc.getFlexPLMObjectData(assortment, [], true);
1110
+ const identifierKeys: string[] = await TypeConversionUtils.getIdentifierProperties(this.transformMapFile, this.mapFileUtil, assortment);
1111
+ const informationKeys: string[] = await TypeConversionUtils.getInformationalProperties(this.transformMapFile, this.mapFileUtil, assortment);
1112
+ for(const key of identifierKeys.concat(informationKeys)){
1113
+ if(assortmentObj[key]){
1114
+ seasonObj[key] = assortmentObj[key];
1115
+ }
1116
+ }
1117
+ const objectKeys = Object.keys(seasonObj);
1118
+ const hasAllIdentifiers = identifierKeys.every(key => objectKeys.includes(key));
1119
+
1120
+ if(!hasAllIdentifiers){
1121
+ return undefined;
1122
+ }
1123
+
1124
+ const mapKey:string = await TypeConversionUtils.getMapKey(this.transformMapFile, this.mapFileUtil, assortment, TypeConversionUtils.VIBE2FLEX_DIRECTION);
1125
+ seasonObj = await MapUtil.applyTransformMap(this.transformMapFile, this.mapFileUtil, seasonObj, mapKey, TypeConversionUtils.VIBE2FLEX_DIRECTION);
1126
+ } finally {
1127
+ delete assortment['flex2vibeMapKeyRoot'];
1128
+ }
1129
+
1130
+ return seasonObj as SeasonFederation;
1131
+
1132
+ }
1133
+
1134
+ }