@contrail/flexplm 3.0.1 → 3.1.0-alpha.6c6914d

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.
@@ -89,6 +89,25 @@ export interface SeasonalPayload extends EntityPayloadType {
89
89
  LCSProduct?: ProductFederation;
90
90
  LCSSKU?: SkuFederation;
91
91
  carriedFromSeason?: object;
92
+ /** Id of the project-item this event is for. Used to identify / group events. */
93
+ projectItemId?: string;
94
+ /** Id of the item family. Set on LCSSKUSeasonLink events so it can be used for the dynamicMessageGroupId. */
95
+ itemFamilyId?: string;
96
+ }
97
+ /** Shape of the VibeIQ external-event created for each seasonal event when
98
+ * sendMode.ASYNC_PUBLISH_SEASON is 'separateVibeIQEvents'.
99
+ * originSystemType + objectClass => trigger key 'VibeIQ-SendSeasonalEventToFlexPLM'. */
100
+ export interface SendSeasonalEventPayload {
101
+ originSystemType: 'VibeIQ';
102
+ objectClass: 'SendSeasonalEventToFlexPLM';
103
+ /** The event that the sendEventToFlexPLM action sends to FlexPLM as is. */
104
+ eventToSend: SeasonalPayload;
105
+ /** The project-item id. */
106
+ id: string;
107
+ /** Item family id (also for SKU / colorway events). Used in dynamicMessageGroupId. */
108
+ itemFamilyId: string;
109
+ /** The publish event that started this; included for easier debugging. */
110
+ initialEvent: object;
92
111
  }
93
112
  export interface ExportPayloadType extends AsyncPayloadType {
94
113
  flexPLMTypePath: string;
@@ -8,6 +8,9 @@ export declare class BaseProcessPublishAssortment {
8
8
  static ASSORTMENT_NOT_PUBLISHABLE: string;
9
9
  static ASSORTMENT_NO_FED_INFO: string;
10
10
  static NOT_ABLE_TO_PROCESS_DELETE_CHANGES: string;
11
+ static SEND_MODE_SEPARATE_VIBEIQ_EVENTS: string;
12
+ static SEND_SEASONAL_EVENT_OBJECT_CLASS: string;
13
+ static DEFAULT_SEPARATE_EVENTS_CONCURRENCY: number;
11
14
  private dc;
12
15
  private config;
13
16
  private mapFileUtil;
@@ -91,8 +94,34 @@ export declare class BaseProcessPublishAssortment {
91
94
  private sendToFlexPLM;
92
95
  private sendAndRecordPublishEvent;
93
96
  private saveToLocalFile;
97
+ /** Uploads the events to a VibeIQ file (auto-deleted after TTL) and returns the file entity. */
98
+ private uploadEventsFile;
94
99
  private handleVibeIQFile;
95
100
  private sendPublishPayloadEvent;
101
+ /** The event that triggered the publish (from the action config); {} when not available. */
102
+ private getInitialEvent;
103
+ /**
104
+ * sendMode 'separateVibeIQEvents' (ET-392).
105
+ * Creates one VibeIQ external-event per seasonal event. Each external-event triggers the
106
+ * 'VibeIQ-SendSeasonalEventToFlexPLM' workflow, which sends that single event to FlexPLM.
107
+ * - The events are still uploaded to a VibeIQ file (auto-deleted) to make troubleshooting easier.
108
+ * - Product-season events are all created before any SKU-season event is created.
109
+ * - The external-event entity has no batch endpoint, so the events are created one by one,
110
+ * a small group at a time (separateEventsConcurrency, default 10) because there can be thousands.
111
+ */
112
+ private sendAsSeparateVibeIQEvents;
113
+ /** Builds the VibeIQ external-event body for one seasonal event. */
114
+ private buildSendSeasonalEventPayload;
115
+ /** How many external-events are created at the same time (config separateEventsConcurrency). */
116
+ private getSeparateEventsConcurrency;
117
+ /** Makes sure that what was thrown is an Error with a readable message. The SDK can throw a plain
118
+ * object such as { statusCode: 404, message: '...' }, which has no usable String() value. */
119
+ private toError;
120
+ /** Creates the external-events one by one, `concurrency` at a time, in order. The next group only
121
+ * starts when the current one has finished. After each group the count for `key` is increased
122
+ * by the events that were created, so a caller can report progress if a later group fails.
123
+ * If any event in a group fails, the remaining events are not created and the error is thrown. */
124
+ private createExternalEvents;
96
125
  private getCurrentDateString;
97
126
  getItemFamilyChanges(pcd: PublishChangeData, changeDetail: any, assortmentItemFullChangeMap: Map<string, any>, assortmentItemDeleteMap: Map<string, any>): Map<string, ItemFamilyChanges>;
98
127
  getEventsForPublishChangeData(publishChangeData: PublishChangeData): Promise<SeasonalPayload[]>;
@@ -594,7 +594,8 @@ class BaseProcessPublishAssortment {
594
594
  async sendEvents(events) {
595
595
  console.info('sendEvents()');
596
596
  const eventType = 'ASYNC_PUBLISH_SEASON';
597
- const sendMode = (this.config?.sendMode[eventType] || '').toLowerCase();
597
+ const sendMode = (this.config?.sendMode?.[eventType] || '').toLowerCase();
598
+ console.info('sendEvents(): sendMode: ' + sendMode);
598
599
  switch (sendMode) {
599
600
  case 'sendtoflexplm':
600
601
  return this.sendToFlexPLM(events, eventType);
@@ -603,7 +604,10 @@ class BaseProcessPublishAssortment {
603
604
  case 'vibeiqfile':
604
605
  case 'vibeiqfile-dontsendtoflexplm':
605
606
  return this.handleVibeIQFile(events, eventType, sendMode);
607
+ case BaseProcessPublishAssortment.SEND_MODE_SEPARATE_VIBEIQ_EVENTS:
608
+ return this.sendAsSeparateVibeIQEvents(events, eventType);
606
609
  default:
610
+ console.warn('sendEvents(): unknown sendMode "' + sendMode + '" for ' + eventType + '; no events were sent.');
607
611
  return {}; // Or handle other cases as required
608
612
  }
609
613
  }
@@ -675,10 +679,14 @@ class BaseProcessPublishAssortment {
675
679
  }
676
680
  return results;
677
681
  }
678
- async handleVibeIQFile(events, eventType, sendMode) {
682
+ /** Uploads the events to a VibeIQ file (auto-deleted after TTL) and returns the file entity. */
683
+ async uploadEventsFile(events) {
679
684
  const eventBuffer = Buffer.from(JSON.stringify(events), 'utf-8');
680
685
  const fileName = 'ASYNC_PUBLISH_SEASON-events.json';
681
- const uploadFile = await new sdk_1.Files().createAndUploadFileFromBuffer(eventBuffer, 'application/json', fileName, null, this.TTL);
686
+ return await new sdk_1.Files().createAndUploadFileFromBuffer(eventBuffer, 'application/json', fileName, null, this.TTL);
687
+ }
688
+ async handleVibeIQFile(events, eventType, sendMode) {
689
+ const uploadFile = await this.uploadEventsFile(events);
682
690
  const outboundPublishEvent = {
683
691
  taskId: this.config.taskId,
684
692
  eventType,
@@ -705,12 +713,7 @@ class BaseProcessPublishAssortment {
705
713
  }
706
714
  async sendPublishPayloadEvent(outboundPublishEvent) {
707
715
  console.info('sendPublishPayloadEvent()');
708
- let initialEvent = {};
709
- if (this.config?.event) {
710
- initialEvent = (typeof this.config?.event === 'string')
711
- ? JSON.parse(this.config?.event)
712
- : this.config?.event;
713
- }
716
+ const initialEvent = this.getInitialEvent();
714
717
  const eventBody = {
715
718
  originSystemType: 'VibeIQ',
716
719
  objectClass: 'AssortmentPublishedToFlexPLM',
@@ -722,6 +725,126 @@ class BaseProcessPublishAssortment {
722
725
  object: eventBody
723
726
  });
724
727
  }
728
+ /** The event that triggered the publish (from the action config); {} when not available. */
729
+ getInitialEvent() {
730
+ let initialEvent = {};
731
+ if (this.config?.event) {
732
+ initialEvent = (typeof this.config?.event === 'string')
733
+ ? JSON.parse(this.config?.event)
734
+ : this.config?.event;
735
+ }
736
+ return initialEvent;
737
+ }
738
+ /**
739
+ * sendMode 'separateVibeIQEvents' (ET-392).
740
+ * Creates one VibeIQ external-event per seasonal event. Each external-event triggers the
741
+ * 'VibeIQ-SendSeasonalEventToFlexPLM' workflow, which sends that single event to FlexPLM.
742
+ * - The events are still uploaded to a VibeIQ file (auto-deleted) to make troubleshooting easier.
743
+ * - Product-season events are all created before any SKU-season event is created.
744
+ * - The external-event entity has no batch endpoint, so the events are created one by one,
745
+ * a small group at a time (separateEventsConcurrency, default 10) because there can be thousands.
746
+ */
747
+ async sendAsSeparateVibeIQEvents(events, eventType) {
748
+ const uploadFile = await this.uploadEventsFile(events);
749
+ const initialEvent = this.getInitialEvent();
750
+ const productWrappers = [];
751
+ const skuWrappers = [];
752
+ for (const event of events) {
753
+ const wrapper = this.buildSendSeasonalEventPayload(event, initialEvent);
754
+ if (event.objectClass === 'LCSProductSeasonLink') {
755
+ productWrappers.push(wrapper);
756
+ }
757
+ else {
758
+ skuWrappers.push(wrapper);
759
+ }
760
+ }
761
+ const eventsCreated = { productSeasons: 0, colorwaySeasons: 0 };
762
+ try {
763
+ // Product Season events must be created (and so queued) before the SKU Season events.
764
+ await this.createExternalEvents(productWrappers, eventsCreated, 'productSeasons');
765
+ await this.createExternalEvents(skuWrappers, eventsCreated, 'colorwaySeasons');
766
+ }
767
+ catch (e) {
768
+ const error = this.toError(e);
769
+ // Events created before the failure are already queued; report that so a re-publish is understood.
770
+ error.eventsCreatedBeforeFailure = { ...eventsCreated };
771
+ error.eventsFileId = uploadFile.id;
772
+ console.error('sendAsSeparateVibeIQEvents(): failed after creating: ' + JSON.stringify(eventsCreated) + ': ' + error.message);
773
+ throw error;
774
+ }
775
+ console.info('sendAsSeparateVibeIQEvents(): eventsCreated: ' + JSON.stringify(eventsCreated));
776
+ return {
777
+ message: 'Successfully created separate VibeIQ events.',
778
+ eventType,
779
+ eventsFileId: uploadFile.id,
780
+ eventsDownloadLink: uploadFile.downloadUrl,
781
+ eventsAdminDownloadLink: uploadFile.adminDownloadUrl,
782
+ eventsCreated
783
+ };
784
+ }
785
+ /** Builds the VibeIQ external-event body for one seasonal event. */
786
+ buildSendSeasonalEventPayload(event, initialEvent) {
787
+ const itemIdFromReference = String(event.entityReference || '').replace(/^item:/, '');
788
+ // Product events: entityReference is 'item:<itemFamilyId>'. SKU events carry itemFamilyId.
789
+ let itemFamilyId = (event.objectClass === 'LCSProductSeasonLink') ? itemIdFromReference : event.itemFamilyId;
790
+ if (!itemFamilyId) {
791
+ console.warn('buildSendSeasonalEventPayload(): no itemFamilyId for ' + event.entityReference
792
+ + '; using item id for the message group.');
793
+ itemFamilyId = itemIdFromReference;
794
+ }
795
+ let id = event.projectItemId;
796
+ if (!id) {
797
+ console.warn('buildSendSeasonalEventPayload(): no projectItemId for ' + event.entityReference
798
+ + '; using item id as id.');
799
+ id = itemIdFromReference;
800
+ }
801
+ return {
802
+ originSystemType: 'VibeIQ',
803
+ objectClass: BaseProcessPublishAssortment.SEND_SEASONAL_EVENT_OBJECT_CLASS,
804
+ eventToSend: event,
805
+ id,
806
+ itemFamilyId,
807
+ initialEvent
808
+ };
809
+ }
810
+ /** How many external-events are created at the same time (config separateEventsConcurrency). */
811
+ getSeparateEventsConcurrency() {
812
+ const configured = Number(this.config?.separateEventsConcurrency);
813
+ return (Number.isInteger(configured) && configured > 0)
814
+ ? configured
815
+ : BaseProcessPublishAssortment.DEFAULT_SEPARATE_EVENTS_CONCURRENCY;
816
+ }
817
+ /** Makes sure that what was thrown is an Error with a readable message. The SDK can throw a plain
818
+ * object such as { statusCode: 404, message: '...' }, which has no usable String() value. */
819
+ toError(e) {
820
+ if (e instanceof Error) {
821
+ return e;
822
+ }
823
+ const text = (typeof e === 'string') ? e : (e?.message || JSON.stringify(e) || String(e));
824
+ const error = new Error(text);
825
+ if (e && typeof e === 'object') {
826
+ error.details = e;
827
+ }
828
+ return error;
829
+ }
830
+ /** Creates the external-events one by one, `concurrency` at a time, in order. The next group only
831
+ * starts when the current one has finished. After each group the count for `key` is increased
832
+ * by the events that were created, so a caller can report progress if a later group fails.
833
+ * If any event in a group fails, the remaining events are not created and the error is thrown. */
834
+ async createExternalEvents(wrappers, counts, key) {
835
+ const concurrency = this.getSeparateEventsConcurrency();
836
+ for (let i = 0; i < wrappers.length; i += concurrency) {
837
+ const group = wrappers.slice(i, i + concurrency);
838
+ const results = await Promise.allSettled(group.map(wrapper => new sdk_1.Entities().create({ entityName: 'external-event', object: wrapper })));
839
+ counts[key] += results.filter(r => r.status === 'fulfilled').length;
840
+ const failed = results.filter(r => r.status === 'rejected');
841
+ if (failed.length > 0) {
842
+ const error = this.toError(failed[0].reason);
843
+ error.failedEventsInGroup = failed.length;
844
+ throw error;
845
+ }
846
+ }
847
+ }
725
848
  getCurrentDateString() {
726
849
  const d = new Date();
727
850
  return '' + d.getUTCFullYear()
@@ -918,6 +1041,7 @@ class BaseProcessPublishAssortment {
918
1041
  eventType,
919
1042
  objectClass: 'LCSProductSeasonLink',
920
1043
  entityReference: 'item:' + entityReference,
1044
+ projectItemId: projectItem?.id,
921
1045
  LCSSeason,
922
1046
  LCSProduct,
923
1047
  data: seasonalData
@@ -954,6 +1078,8 @@ class BaseProcessPublishAssortment {
954
1078
  eventType,
955
1079
  objectClass: 'LCSSKUSeasonLink',
956
1080
  entityReference: 'item:' + entityReference,
1081
+ projectItemId: projectItem?.id,
1082
+ itemFamilyId: itemFamilyChanges.itemFamilyId,
957
1083
  LCSSeason,
958
1084
  LCSSKU,
959
1085
  data: seasonalData
@@ -1092,3 +1218,6 @@ exports.BaseProcessPublishAssortment = BaseProcessPublishAssortment;
1092
1218
  BaseProcessPublishAssortment.ASSORTMENT_NOT_PUBLISHABLE = 'Assortment isn\'t marked for publishing to FlexPLM';
1093
1219
  BaseProcessPublishAssortment.ASSORTMENT_NO_FED_INFO = 'Assortment doesn\'t have all "identifier" properties, so there is no processing. Identifier properties: ';
1094
1220
  BaseProcessPublishAssortment.NOT_ABLE_TO_PROCESS_DELETE_CHANGES = 'Error: Not able to process delete changes';
1221
+ BaseProcessPublishAssortment.SEND_MODE_SEPARATE_VIBEIQ_EVENTS = 'separatevibeiqevents'; // compared lower-cased
1222
+ BaseProcessPublishAssortment.SEND_SEASONAL_EVENT_OBJECT_CLASS = 'SendSeasonalEventToFlexPLM';
1223
+ BaseProcessPublishAssortment.DEFAULT_SEPARATE_EVENTS_CONCURRENCY = 10;
@@ -33,6 +33,8 @@ jest.mock('../util/federation', () => {
33
33
  let entityObject = {};
34
34
  let getOptionsObject = {};
35
35
  let createCallArg = undefined;
36
+ let createCalls = [];
37
+ let createImpl = () => Promise.resolve({});
36
38
  let fileUploadCalls = [];
37
39
  let fileUploadResult = {
38
40
  id: 'file-123',
@@ -48,7 +50,8 @@ jest.mock('@contrail/sdk', () => {
48
50
  }
49
51
  create(arg) {
50
52
  createCallArg = arg;
51
- return Promise.resolve({});
53
+ createCalls.push(arg);
54
+ return createImpl(arg);
52
55
  }
53
56
  },
54
57
  Files: class {
@@ -1575,6 +1578,78 @@ describe('getEventsForItemFamilyChanges - conditional eventType', () => {
1575
1578
  expect(events[0].objectClass).toBe('LCSProductSeasonLink');
1576
1579
  expect(type_conversion_utils_1.TypeConversionUtils.isOutboundCreatableFromEntity).toHaveBeenCalledWith(undefined, mapFileUtil, projectItem, { item: prodEntityData, assortment });
1577
1580
  });
1581
+ it('LCSProductSeasonLink event includes projectItemId and no itemFamilyId', async () => {
1582
+ const bppa = new base_process_publish_assortment_1.BaseProcessPublishAssortment(config, dc, mapFileUtil);
1583
+ const itemFamilyId = 'family123';
1584
+ const prodEntityData = { id: itemFamilyId, identifier: 'FAM-123', itemNumber: 'FAM-123' };
1585
+ const projectItem = { id: 'proj1', updatedOn: '2023-01-15T00:00:00.000Z' };
1586
+ const assortment = { id: 'assort123', name: 'Fall 2023 Assortment', publishToFlexPLM: true };
1587
+ const seasonFed = {
1588
+ entityReference: 'assortment:assort123',
1589
+ objectClass: 'LCSSeason',
1590
+ flexPLMSeasonName: 'Fall 2023'
1591
+ };
1592
+ const itemFamilyChanges = new item_family_changes_1.ItemFamilyChanges(itemFamilyId, new Date('2023-01-01T00:00:00.000Z'));
1593
+ itemFamilyChanges.familyAdd = true;
1594
+ itemFamilyChanges.assortmentItemFullChangeMap.set(itemFamilyId, {
1595
+ item: prodEntityData,
1596
+ projectItem
1597
+ });
1598
+ jest.spyOn(bppa, 'getAssortment').mockResolvedValue(assortment);
1599
+ jest.spyOn(bppa, 'getProjectItem').mockReturnValue(projectItem);
1600
+ jest.spyOn(bppa, 'getSeasonalData').mockResolvedValue({ someData: 'value' });
1601
+ jest.spyOn(map_utils_1.MapUtil, 'applyTransformMap').mockResolvedValue({ transformedData: 'value' });
1602
+ jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getIdentifierProperties').mockResolvedValue(['identifier']);
1603
+ jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getInformationalProperties').mockResolvedValue([]);
1604
+ jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'isOutboundCreatableFromEntity').mockResolvedValue(true);
1605
+ const events = await bppa.getEventsForItemFamilyChanges(itemFamilyChanges, 'assort123', seasonFed, new Map());
1606
+ expect(events).toHaveLength(1);
1607
+ expect(events[0].objectClass).toBe('LCSProductSeasonLink');
1608
+ expect(events[0].projectItemId).toBe('proj1');
1609
+ expect(events[0].itemFamilyId).toBeUndefined();
1610
+ });
1611
+ it('LCSSKUSeasonLink event includes projectItemId and itemFamilyId', async () => {
1612
+ const bppa = new base_process_publish_assortment_1.BaseProcessPublishAssortment(config, dc, mapFileUtil);
1613
+ const itemFamilyId = 'family123';
1614
+ const colorId = 'color456';
1615
+ const familyItemData = { id: itemFamilyId, identifier: 'FAM-123', itemNumber: 'FAM-123' };
1616
+ const itemData = { id: colorId, identifier: 'COLOR-456', itemNumber: 'COLOR-456' };
1617
+ const familyProjectItem = { id: 'proj0', updatedOn: '2023-01-14T00:00:00.000Z' };
1618
+ const projectItem = { id: 'proj1', updatedOn: '2023-01-15T00:00:00.000Z' };
1619
+ const assortment = { id: 'assort123', name: 'Fall 2023 Assortment', publishToFlexPLM: true };
1620
+ const seasonFed = {
1621
+ entityReference: 'assortment:assort123',
1622
+ objectClass: 'LCSSeason',
1623
+ flexPLMSeasonName: 'Fall 2023'
1624
+ };
1625
+ const itemFamilyChanges = new item_family_changes_1.ItemFamilyChanges(itemFamilyId, new Date('2023-01-01T00:00:00.000Z'));
1626
+ itemFamilyChanges.colorAdds.push(colorId);
1627
+ itemFamilyChanges.assortmentItemFullChangeMap.set(itemFamilyId, {
1628
+ item: familyItemData,
1629
+ projectItem: familyProjectItem
1630
+ });
1631
+ itemFamilyChanges.assortmentItemFullChangeMap.set(colorId, {
1632
+ item: itemData,
1633
+ projectItem
1634
+ });
1635
+ jest.spyOn(bppa, 'getAssortment').mockResolvedValue(assortment);
1636
+ jest.spyOn(bppa, 'getProjectItem')
1637
+ .mockReturnValueOnce(familyProjectItem)
1638
+ .mockReturnValueOnce(projectItem);
1639
+ jest.spyOn(bppa, 'getSeasonalData').mockResolvedValue({ someData: 'value' });
1640
+ jest.spyOn(map_utils_1.MapUtil, 'applyTransformMap').mockResolvedValue({ transformedData: 'value' });
1641
+ jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getIdentifierProperties').mockResolvedValue(['identifier']);
1642
+ jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getInformationalProperties').mockResolvedValue([]);
1643
+ jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'isOutboundCreatableFromEntity').mockResolvedValue(true);
1644
+ const events = await bppa.getEventsForItemFamilyChanges(itemFamilyChanges, 'assort123', seasonFed, new Map());
1645
+ expect(events).toHaveLength(2);
1646
+ const productEvent = events.find(e => e.objectClass === 'LCSProductSeasonLink');
1647
+ const skuEvent = events.find(e => e.objectClass === 'LCSSKUSeasonLink');
1648
+ expect(productEvent.projectItemId).toBe('proj0');
1649
+ expect(productEvent.itemFamilyId).toBeUndefined();
1650
+ expect(skuEvent.projectItemId).toBe('proj1');
1651
+ expect(skuEvent.itemFamilyId).toBe('family123');
1652
+ });
1578
1653
  it('should use UPSERT_ON_SEASON for LCSSKUSeasonLink when isOutboundCreatableFromEntity returns true', async () => {
1579
1654
  const bppa = new base_process_publish_assortment_1.BaseProcessPublishAssortment(config, dc, mapFileUtil);
1580
1655
  const itemFamilyId = 'family123';
@@ -2211,3 +2286,215 @@ describe('released family with pre-development options', () => {
2211
2286
  expect(await ppa.getEventsForItemFamilyChanges(ifc, 'a1', eventSeasonFed, new Map())).toHaveLength(0);
2212
2287
  });
2213
2288
  });
2289
+ describe('sendEvents - separateVibeIQEvents', () => {
2290
+ const buildConfig = (extra = {}) => ({
2291
+ taskId: 'task-abc',
2292
+ event: '{"sourceEventId":"src-1"}',
2293
+ sendMode: { ASYNC_PUBLISH_SEASON: 'separateVibeIQEvents' },
2294
+ ...extra
2295
+ });
2296
+ const mapFileUtil = new transform_data_1.MapFileUtil(new sdk_1.Entities());
2297
+ const productEvent = (n) => ({
2298
+ eventType: 'UPSERT_ON_SEASON',
2299
+ objectClass: 'LCSProductSeasonLink',
2300
+ entityReference: 'item:fam' + n,
2301
+ projectItemId: 'pi-fam' + n,
2302
+ LCSSeason: {},
2303
+ LCSProduct: {},
2304
+ data: {}
2305
+ });
2306
+ const skuEvent = (n, familyN) => ({
2307
+ eventType: 'UPSERT_ON_SEASON',
2308
+ objectClass: 'LCSSKUSeasonLink',
2309
+ entityReference: 'item:sku' + n,
2310
+ projectItemId: 'pi-sku' + n,
2311
+ itemFamilyId: 'fam' + familyN,
2312
+ LCSSeason: {},
2313
+ LCSSKU: {},
2314
+ data: {}
2315
+ });
2316
+ const newBppa = (config) => new base_process_publish_assortment_1.BaseProcessPublishAssortment(config, new data_converter_1.DataConverter(config, mapFileUtil), mapFileUtil);
2317
+ const createdObjects = () => createCalls.map(call => call.object);
2318
+ /** An external-event create that takes a few ms and records how many run at the same time,
2319
+ * and whether a product-season and a sku-season event were ever in flight together. */
2320
+ const trackConcurrency = () => {
2321
+ const state = { inFlight: 0, maxInFlight: 0, mixed: false, active: [] };
2322
+ createImpl = async (arg) => {
2323
+ const objectClass = arg.object.eventToSend.objectClass;
2324
+ state.active.push(objectClass);
2325
+ state.inFlight++;
2326
+ state.maxInFlight = Math.max(state.maxInFlight, state.inFlight);
2327
+ if (state.active.includes('LCSProductSeasonLink') && state.active.includes('LCSSKUSeasonLink')) {
2328
+ state.mixed = true;
2329
+ }
2330
+ await new Promise(resolve => setTimeout(resolve, 5));
2331
+ state.active.splice(state.active.indexOf(objectClass), 1);
2332
+ state.inFlight--;
2333
+ return {};
2334
+ };
2335
+ return state;
2336
+ };
2337
+ beforeEach(() => {
2338
+ createCallArg = undefined;
2339
+ fileUploadCalls = [];
2340
+ createCalls = [];
2341
+ createImpl = () => Promise.resolve({});
2342
+ fileUploadResult = {
2343
+ id: 'file-123',
2344
+ downloadUrl: 'https://download.url',
2345
+ adminDownloadUrl: 'https://admin.download.url'
2346
+ };
2347
+ });
2348
+ afterEach(() => {
2349
+ createImpl = () => Promise.resolve({});
2350
+ jest.restoreAllMocks();
2351
+ });
2352
+ it('creates one external-event per seasonal event, with the expected shape', async () => {
2353
+ const bppa = newBppa(buildConfig());
2354
+ const events = [productEvent(1), skuEvent(1, 1)];
2355
+ await bppa.sendEvents(events);
2356
+ expect(createCalls).toHaveLength(2);
2357
+ createCalls.forEach(call => expect(call.entityName).toBe('external-event'));
2358
+ const objects = createdObjects();
2359
+ expect(objects[0]).toEqual({
2360
+ originSystemType: 'VibeIQ',
2361
+ objectClass: 'SendSeasonalEventToFlexPLM',
2362
+ eventToSend: productEvent(1),
2363
+ id: 'pi-fam1',
2364
+ itemFamilyId: 'fam1',
2365
+ initialEvent: { sourceEventId: 'src-1' }
2366
+ });
2367
+ expect(objects[1]).toEqual({
2368
+ originSystemType: 'VibeIQ',
2369
+ objectClass: 'SendSeasonalEventToFlexPLM',
2370
+ eventToSend: skuEvent(1, 1),
2371
+ id: 'pi-sku1',
2372
+ itemFamilyId: 'fam1',
2373
+ initialEvent: { sourceEventId: 'src-1' }
2374
+ });
2375
+ });
2376
+ it('creates all product-season events before any sku-season event, even when the input is interleaved', async () => {
2377
+ const bppa = newBppa(buildConfig());
2378
+ const events = [skuEvent(1, 1), productEvent(1), skuEvent(2, 2), productEvent(2)];
2379
+ await bppa.sendEvents(events);
2380
+ const classes = createdObjects().map(o => o.eventToSend.objectClass);
2381
+ expect(classes).toEqual([
2382
+ 'LCSProductSeasonLink', 'LCSProductSeasonLink',
2383
+ 'LCSSKUSeasonLink', 'LCSSKUSeasonLink'
2384
+ ]);
2385
+ });
2386
+ it('creates at most separateEventsConcurrency events at a time and never mixes product and sku events', async () => {
2387
+ const bppa = newBppa(buildConfig({ separateEventsConcurrency: 2 }));
2388
+ const state = trackConcurrency();
2389
+ const events = [];
2390
+ for (let i = 1; i <= 5; i++) {
2391
+ events.push(productEvent(i));
2392
+ }
2393
+ for (let i = 1; i <= 3; i++) {
2394
+ events.push(skuEvent(i, 1));
2395
+ }
2396
+ const result = await bppa.sendEvents(events);
2397
+ expect(createCalls).toHaveLength(8);
2398
+ expect(state.maxInFlight).toBe(2);
2399
+ expect(state.mixed).toBe(false);
2400
+ expect(result.eventsCreated).toEqual({ productSeasons: 5, colorwaySeasons: 3 });
2401
+ });
2402
+ it('creates 10 events at a time when separateEventsConcurrency is not a valid number', async () => {
2403
+ const bppa = newBppa(buildConfig({ separateEventsConcurrency: 'abc' }));
2404
+ const state = trackConcurrency();
2405
+ const events = [];
2406
+ for (let i = 1; i <= 25; i++) {
2407
+ events.push(productEvent(i));
2408
+ }
2409
+ await bppa.sendEvents(events);
2410
+ expect(createCalls).toHaveLength(25);
2411
+ expect(state.maxInFlight).toBe(10);
2412
+ });
2413
+ it('uploads the events file, and does not call FlexPLM or create AssortmentPublishedToFlexPLM', async () => {
2414
+ const bppa = newBppa(buildConfig());
2415
+ const events = [productEvent(1), skuEvent(1, 1)];
2416
+ const spyFlex = jest.spyOn(flexplm_connect_1.FlexPLMConnect.prototype, 'sendToFlexPLM').mockResolvedValue({ status: 200 });
2417
+ const result = await bppa.sendEvents(events);
2418
+ expect(fileUploadCalls).toHaveLength(1);
2419
+ expect(JSON.parse(fileUploadCalls[0].buffer.toString('utf-8'))).toEqual(events);
2420
+ expect(spyFlex).not.toHaveBeenCalled();
2421
+ createdObjects().forEach(o => expect(o.objectClass).toBe('SendSeasonalEventToFlexPLM'));
2422
+ expect(createdObjects().some(o => o.objectClass === 'AssortmentPublishedToFlexPLM')).toBe(false);
2423
+ expect(result).toEqual({
2424
+ message: 'Successfully created separate VibeIQ events.',
2425
+ eventType: 'ASYNC_PUBLISH_SEASON',
2426
+ eventsFileId: 'file-123',
2427
+ eventsDownloadLink: 'https://download.url',
2428
+ eventsAdminDownloadLink: 'https://admin.download.url',
2429
+ eventsCreated: { productSeasons: 1, colorwaySeasons: 1 }
2430
+ });
2431
+ });
2432
+ it('stops after the group with the failing event and reports the events already created', async () => {
2433
+ const bppa = newBppa(buildConfig({ separateEventsConcurrency: 2 }));
2434
+ const events = [];
2435
+ for (let i = 1; i <= 5; i++) {
2436
+ events.push(productEvent(i));
2437
+ }
2438
+ events.push(skuEvent(1, 1));
2439
+ let callCount = 0;
2440
+ createImpl = () => {
2441
+ callCount++;
2442
+ return callCount === 4 ? Promise.reject(new Error('create failed')) : Promise.resolve({});
2443
+ };
2444
+ jest.spyOn(console, 'error').mockImplementation(() => undefined);
2445
+ await expect(bppa.sendEvents(events)).rejects.toMatchObject({
2446
+ message: 'create failed',
2447
+ eventsCreatedBeforeFailure: { productSeasons: 3, colorwaySeasons: 0 },
2448
+ eventsFileId: 'file-123',
2449
+ failedEventsInGroup: 1
2450
+ });
2451
+ expect(createCalls).toHaveLength(4);
2452
+ });
2453
+ it('keeps a readable message when the SDK rejects with a plain object instead of an Error', async () => {
2454
+ const bppa = newBppa(buildConfig({ separateEventsConcurrency: 1 }));
2455
+ createImpl = () => Promise.reject({ statusCode: 404, message: 'Internal Server Error' });
2456
+ jest.spyOn(console, 'error').mockImplementation(() => undefined);
2457
+ await expect(bppa.sendEvents([productEvent(1)])).rejects.toMatchObject({
2458
+ message: 'Internal Server Error',
2459
+ details: { statusCode: 404, message: 'Internal Server Error' },
2460
+ eventsCreatedBeforeFailure: { productSeasons: 0, colorwaySeasons: 0 }
2461
+ });
2462
+ });
2463
+ it('falls back to the item id when projectItemId or itemFamilyId are missing', async () => {
2464
+ const bppa = newBppa(buildConfig());
2465
+ const prod = productEvent(9);
2466
+ delete prod.projectItemId;
2467
+ const sku = skuEvent(9, 9);
2468
+ delete sku.projectItemId;
2469
+ delete sku.itemFamilyId;
2470
+ const spyWarn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
2471
+ await bppa.sendEvents([prod, sku]);
2472
+ const objects = createdObjects();
2473
+ expect(objects[0].id).toBe('fam9');
2474
+ expect(objects[0].itemFamilyId).toBe('fam9');
2475
+ expect(objects[1].id).toBe('sku9');
2476
+ expect(objects[1].itemFamilyId).toBe('sku9');
2477
+ expect(spyWarn).toHaveBeenCalled();
2478
+ });
2479
+ it('returns {} and creates nothing for an unknown sendMode', async () => {
2480
+ const bppa = newBppa(buildConfig({ sendMode: { ASYNC_PUBLISH_SEASON: 'bogus' } }));
2481
+ jest.spyOn(console, 'warn').mockImplementation(() => undefined);
2482
+ const result = await bppa.sendEvents([productEvent(1)]);
2483
+ expect(result).toEqual({});
2484
+ expect(createCalls).toHaveLength(0);
2485
+ expect(fileUploadCalls).toHaveLength(0);
2486
+ });
2487
+ it('returns {} and does not throw when sendMode is missing', async () => {
2488
+ const config = { taskId: 'task-abc' };
2489
+ const bppa = newBppa(config);
2490
+ jest.spyOn(console, 'warn').mockImplementation(() => undefined);
2491
+ const result = await bppa.sendEvents([productEvent(1)]);
2492
+ expect(result).toEqual({});
2493
+ expect(createCalls).toHaveLength(0);
2494
+ });
2495
+ it('is case-insensitive about the sendMode value', async () => {
2496
+ const bppa = newBppa(buildConfig({ sendMode: { ASYNC_PUBLISH_SEASON: 'SEPARATEVIBEIQEVENTS' } }));
2497
+ await bppa.sendEvents([productEvent(1)]);
2498
+ expect(createdObjects()).toHaveLength(1);
2499
+ });
2500
+ });
@@ -1,6 +1,7 @@
1
1
  import { FCConfig } from '../interfaces/interfaces';
2
2
  export declare class ConfigDefaults {
3
3
  static NEED_CONFIG_VALUES: string;
4
+ static INVALID_SEND_MODE: string;
4
5
  static STATIC_CONFIG_CACHE: {};
5
6
  static PROTO_KEYS: string[];
6
7
  static stripProtoKeys(obj: any): any;
@@ -27,6 +27,21 @@ class ConfigDefaults {
27
27
  Object.assign(config, ConfigDefaults.stripProtoKeys(config.complexConfig));
28
28
  delete config.complexConfig;
29
29
  }
30
+ // sendMode can arrive as a JSON string (for example from an action configuration field).
31
+ // Normalise it to an object so it merges with the defaults instead of replacing them.
32
+ if (typeof config.sendMode === 'string') {
33
+ let parsedSendMode;
34
+ try {
35
+ parsedSendMode = JSON.parse(config.sendMode);
36
+ }
37
+ catch (e) {
38
+ throw new Error(ConfigDefaults.INVALID_SEND_MODE + config.sendMode);
39
+ }
40
+ if (parsedSendMode === null || typeof parsedSendMode !== 'object' || Array.isArray(parsedSendMode)) {
41
+ throw new Error(ConfigDefaults.INVALID_SEND_MODE + config.sendMode);
42
+ }
43
+ config.sendMode = ConfigDefaults.stripProtoKeys(parsedSendMode);
44
+ }
30
45
  // List will be comma separated list in UI, so convert to array
31
46
  if (config?.itemPreDevelopmentLifecycleStages && !(config?.itemPreDevelopmentLifecycleStages instanceof Array)) {
32
47
  config.itemPreDevelopmentLifecycleStages = config.itemPreDevelopmentLifecycleStages.split(',');
@@ -113,5 +128,6 @@ class ConfigDefaults {
113
128
  }
114
129
  exports.ConfigDefaults = ConfigDefaults;
115
130
  ConfigDefaults.NEED_CONFIG_VALUES = 'To connect to FlexPLM all these APP values need to be set apiHost, userName, and password';
131
+ ConfigDefaults.INVALID_SEND_MODE = 'sendMode must be an object, or a JSON string of an object. Ex: {"ASYNC_PUBLISH_SEASON": "separateVibeIQEvents"}. Value: ';
116
132
  ConfigDefaults.STATIC_CONFIG_CACHE = {};
117
133
  ConfigDefaults.PROTO_KEYS = ['__proto__', 'constructor', 'prototype'];
@@ -139,6 +139,41 @@ describe('all tests', () => {
139
139
  const fcConfig = await config_defaults_1.ConfigDefaults.setConfigDefaults(startConfig);
140
140
  expect(fcConfig['sendMode']['NO_DEFAULT']).toEqual('vibeiqfile-dontsendtoflexplm');
141
141
  });
142
+ it('sendMode as JSON string is parsed and merged with the defaults', async () => {
143
+ const startConfig = Object.assign({}, config);
144
+ startConfig['sendMode'] = '{"ASYNC_PUBLISH_SEASON": "separateVibeIQEvents", "OTHER": "x"}';
145
+ const fcConfig = await config_defaults_1.ConfigDefaults.setConfigDefaults(startConfig);
146
+ expect(fcConfig['sendMode']['ASYNC_PUBLISH_SEASON']).toEqual('separateVibeIQEvents');
147
+ expect(fcConfig['sendMode']['OTHER']).toEqual('x');
148
+ });
149
+ it('sendMode as JSON string without ASYNC_PUBLISH_SEASON keeps the default for it', async () => {
150
+ const startConfig = Object.assign({}, config);
151
+ startConfig['sendMode'] = '{"OTHER": "x"}';
152
+ const fcConfig = await config_defaults_1.ConfigDefaults.setConfigDefaults(startConfig);
153
+ expect(fcConfig['sendMode']['ASYNC_PUBLISH_SEASON']).toEqual('vibeiqfile');
154
+ expect(fcConfig['sendMode']['OTHER']).toEqual('x');
155
+ });
156
+ it('sendMode as invalid JSON string throws', async () => {
157
+ const startConfig = Object.assign({}, config);
158
+ startConfig['sendMode'] = '{not json';
159
+ await expect(config_defaults_1.ConfigDefaults.setConfigDefaults(startConfig)).rejects.toThrow(config_defaults_1.ConfigDefaults.INVALID_SEND_MODE);
160
+ });
161
+ it('sendMode as JSON string that is not an object throws', async () => {
162
+ const startConfig = Object.assign({}, config);
163
+ startConfig['sendMode'] = '"separateVibeIQEvents"';
164
+ await expect(config_defaults_1.ConfigDefaults.setConfigDefaults(startConfig)).rejects.toThrow(config_defaults_1.ConfigDefaults.INVALID_SEND_MODE);
165
+ });
166
+ it('sendMode as JSON string of an array throws', async () => {
167
+ const startConfig = Object.assign({}, config);
168
+ startConfig['sendMode'] = '["separateVibeIQEvents"]';
169
+ await expect(config_defaults_1.ConfigDefaults.setConfigDefaults(startConfig)).rejects.toThrow(config_defaults_1.ConfigDefaults.INVALID_SEND_MODE);
170
+ });
171
+ it('sendMode from complexConfig as JSON string is parsed', async () => {
172
+ const startConfig = Object.assign({}, config);
173
+ startConfig['complexConfig'] = { sendMode: '{"ASYNC_PUBLISH_SEASON": "separateVibeIQEvents"}' };
174
+ const fcConfig = await config_defaults_1.ConfigDefaults.setConfigDefaults(startConfig);
175
+ expect(fcConfig['sendMode']['ASYNC_PUBLISH_SEASON']).toEqual('separateVibeIQEvents');
176
+ });
142
177
  it('itemPreDevelopmentLifecycleStages-get default', async () => {
143
178
  const startConfig = Object.assign({}, config);
144
179
  const fcConfig = await config_defaults_1.ConfigDefaults.setConfigDefaults(startConfig);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrail/flexplm",
3
- "version": "3.0.1",
3
+ "version": "3.1.0-alpha.6c6914d",
4
4
  "description": "Library used for integration with flexplm.",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",