@contrail/flexplm 3.0.0-alpha.fbb6338 → 3.1.0-alpha.9d81aaa

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_BATCH_SIZE: number;
11
14
  private dc;
12
15
  private config;
13
16
  private mapFileUtil;
@@ -91,8 +94,27 @@ 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 created (all batches) before any SKU-season event is created.
109
+ * - Events are created in batches because there can be thousands.
110
+ */
111
+ private sendAsSeparateVibeIQEvents;
112
+ /** Builds the VibeIQ external-event body for one seasonal event. */
113
+ private buildSendSeasonalEventPayload;
114
+ private getSeparateEventsBatchSize;
115
+ /** Creates the external-events in sequential batches. After each successful batch the
116
+ * count for `key` is increased, so a caller can report progress if a later batch fails. */
117
+ private batchCreateExternalEvents;
96
118
  private getCurrentDateString;
97
119
  getItemFamilyChanges(pcd: PublishChangeData, changeDetail: any, assortmentItemFullChangeMap: Map<string, any>, assortmentItemDeleteMap: Map<string, any>): Map<string, ItemFamilyChanges>;
98
120
  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,106 @@ 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 created (all batches) before any SKU-season event is created.
744
+ * - Events are created in batches because there can be thousands.
745
+ */
746
+ async sendAsSeparateVibeIQEvents(events, eventType) {
747
+ const uploadFile = await this.uploadEventsFile(events);
748
+ const initialEvent = this.getInitialEvent();
749
+ const productWrappers = [];
750
+ const skuWrappers = [];
751
+ for (const event of events) {
752
+ const wrapper = this.buildSendSeasonalEventPayload(event, initialEvent);
753
+ if (event.objectClass === 'LCSProductSeasonLink') {
754
+ productWrappers.push(wrapper);
755
+ }
756
+ else {
757
+ skuWrappers.push(wrapper);
758
+ }
759
+ }
760
+ const eventsCreated = { productSeasons: 0, colorwaySeasons: 0 };
761
+ try {
762
+ // Product Season events must be created (and so queued) before the SKU Season events.
763
+ await this.batchCreateExternalEvents(productWrappers, eventsCreated, 'productSeasons');
764
+ await this.batchCreateExternalEvents(skuWrappers, eventsCreated, 'colorwaySeasons');
765
+ }
766
+ catch (e) {
767
+ const error = e instanceof Error ? e : new Error(String(e));
768
+ // Events created before the failure are already queued; report that so a re-publish is understood.
769
+ error.eventsCreatedBeforeFailure = { ...eventsCreated };
770
+ error.eventsFileId = uploadFile.id;
771
+ console.error('sendAsSeparateVibeIQEvents(): failed after creating: ' + JSON.stringify(eventsCreated) + ': ' + error.message);
772
+ throw error;
773
+ }
774
+ console.info('sendAsSeparateVibeIQEvents(): eventsCreated: ' + JSON.stringify(eventsCreated));
775
+ return {
776
+ message: 'Successfully created separate VibeIQ events.',
777
+ eventType,
778
+ eventsFileId: uploadFile.id,
779
+ eventsDownloadLink: uploadFile.downloadUrl,
780
+ eventsAdminDownloadLink: uploadFile.adminDownloadUrl,
781
+ eventsCreated
782
+ };
783
+ }
784
+ /** Builds the VibeIQ external-event body for one seasonal event. */
785
+ buildSendSeasonalEventPayload(event, initialEvent) {
786
+ const itemIdFromReference = String(event.entityReference || '').replace(/^item:/, '');
787
+ // Product events: entityReference is 'item:<itemFamilyId>'. SKU events carry itemFamilyId.
788
+ let itemFamilyId = (event.objectClass === 'LCSProductSeasonLink') ? itemIdFromReference : event.itemFamilyId;
789
+ if (!itemFamilyId) {
790
+ console.warn('buildSendSeasonalEventPayload(): no itemFamilyId for ' + event.entityReference
791
+ + '; using item id for the message group.');
792
+ itemFamilyId = itemIdFromReference;
793
+ }
794
+ let id = event.projectItemId;
795
+ if (!id) {
796
+ console.warn('buildSendSeasonalEventPayload(): no projectItemId for ' + event.entityReference
797
+ + '; using item id as id.');
798
+ id = itemIdFromReference;
799
+ }
800
+ return {
801
+ originSystemType: 'VibeIQ',
802
+ objectClass: BaseProcessPublishAssortment.SEND_SEASONAL_EVENT_OBJECT_CLASS,
803
+ eventToSend: event,
804
+ id,
805
+ itemFamilyId,
806
+ initialEvent
807
+ };
808
+ }
809
+ getSeparateEventsBatchSize() {
810
+ const configured = Number(this.config?.separateEventsBatchSize);
811
+ return (Number.isInteger(configured) && configured > 0)
812
+ ? configured
813
+ : BaseProcessPublishAssortment.DEFAULT_SEPARATE_EVENTS_BATCH_SIZE;
814
+ }
815
+ /** Creates the external-events in sequential batches. After each successful batch the
816
+ * count for `key` is increased, so a caller can report progress if a later batch fails. */
817
+ async batchCreateExternalEvents(wrappers, counts, key) {
818
+ const batchSize = this.getSeparateEventsBatchSize();
819
+ for (let i = 0; i < wrappers.length; i += batchSize) {
820
+ const batch = wrappers.slice(i, i + batchSize);
821
+ await new sdk_1.Entities().batchCreate({
822
+ entityName: 'external-event',
823
+ objects: batch
824
+ });
825
+ counts[key] += batch.length;
826
+ }
827
+ }
725
828
  getCurrentDateString() {
726
829
  const d = new Date();
727
830
  return '' + d.getUTCFullYear()
@@ -918,6 +1021,7 @@ class BaseProcessPublishAssortment {
918
1021
  eventType,
919
1022
  objectClass: 'LCSProductSeasonLink',
920
1023
  entityReference: 'item:' + entityReference,
1024
+ projectItemId: projectItem?.id,
921
1025
  LCSSeason,
922
1026
  LCSProduct,
923
1027
  data: seasonalData
@@ -954,6 +1058,8 @@ class BaseProcessPublishAssortment {
954
1058
  eventType,
955
1059
  objectClass: 'LCSSKUSeasonLink',
956
1060
  entityReference: 'item:' + entityReference,
1061
+ projectItemId: projectItem?.id,
1062
+ itemFamilyId: itemFamilyChanges.itemFamilyId,
957
1063
  LCSSeason,
958
1064
  LCSSKU,
959
1065
  data: seasonalData
@@ -1092,3 +1198,6 @@ exports.BaseProcessPublishAssortment = BaseProcessPublishAssortment;
1092
1198
  BaseProcessPublishAssortment.ASSORTMENT_NOT_PUBLISHABLE = 'Assortment isn\'t marked for publishing to FlexPLM';
1093
1199
  BaseProcessPublishAssortment.ASSORTMENT_NO_FED_INFO = 'Assortment doesn\'t have all "identifier" properties, so there is no processing. Identifier properties: ';
1094
1200
  BaseProcessPublishAssortment.NOT_ABLE_TO_PROCESS_DELETE_CHANGES = 'Error: Not able to process delete changes';
1201
+ BaseProcessPublishAssortment.SEND_MODE_SEPARATE_VIBEIQ_EVENTS = 'separatevibeiqevents'; // compared lower-cased
1202
+ BaseProcessPublishAssortment.SEND_SEASONAL_EVENT_OBJECT_CLASS = 'SendSeasonalEventToFlexPLM';
1203
+ BaseProcessPublishAssortment.DEFAULT_SEPARATE_EVENTS_BATCH_SIZE = 100;
@@ -33,6 +33,8 @@ jest.mock('../util/federation', () => {
33
33
  let entityObject = {};
34
34
  let getOptionsObject = {};
35
35
  let createCallArg = undefined;
36
+ let batchCreateCalls = [];
37
+ let batchCreateImpl = () => Promise.resolve([]);
36
38
  let fileUploadCalls = [];
37
39
  let fileUploadResult = {
38
40
  id: 'file-123',
@@ -50,6 +52,10 @@ jest.mock('@contrail/sdk', () => {
50
52
  createCallArg = arg;
51
53
  return Promise.resolve({});
52
54
  }
55
+ batchCreate(arg) {
56
+ batchCreateCalls.push(arg);
57
+ return batchCreateImpl(arg);
58
+ }
53
59
  },
54
60
  Files: class {
55
61
  createAndUploadFileFromBuffer(buffer, mimeType, fileName, _x, ttl) {
@@ -1575,6 +1581,78 @@ describe('getEventsForItemFamilyChanges - conditional eventType', () => {
1575
1581
  expect(events[0].objectClass).toBe('LCSProductSeasonLink');
1576
1582
  expect(type_conversion_utils_1.TypeConversionUtils.isOutboundCreatableFromEntity).toHaveBeenCalledWith(undefined, mapFileUtil, projectItem, { item: prodEntityData, assortment });
1577
1583
  });
1584
+ it('LCSProductSeasonLink event includes projectItemId and no itemFamilyId', async () => {
1585
+ const bppa = new base_process_publish_assortment_1.BaseProcessPublishAssortment(config, dc, mapFileUtil);
1586
+ const itemFamilyId = 'family123';
1587
+ const prodEntityData = { id: itemFamilyId, identifier: 'FAM-123', itemNumber: 'FAM-123' };
1588
+ const projectItem = { id: 'proj1', updatedOn: '2023-01-15T00:00:00.000Z' };
1589
+ const assortment = { id: 'assort123', name: 'Fall 2023 Assortment', publishToFlexPLM: true };
1590
+ const seasonFed = {
1591
+ entityReference: 'assortment:assort123',
1592
+ objectClass: 'LCSSeason',
1593
+ flexPLMSeasonName: 'Fall 2023'
1594
+ };
1595
+ const itemFamilyChanges = new item_family_changes_1.ItemFamilyChanges(itemFamilyId, new Date('2023-01-01T00:00:00.000Z'));
1596
+ itemFamilyChanges.familyAdd = true;
1597
+ itemFamilyChanges.assortmentItemFullChangeMap.set(itemFamilyId, {
1598
+ item: prodEntityData,
1599
+ projectItem
1600
+ });
1601
+ jest.spyOn(bppa, 'getAssortment').mockResolvedValue(assortment);
1602
+ jest.spyOn(bppa, 'getProjectItem').mockReturnValue(projectItem);
1603
+ jest.spyOn(bppa, 'getSeasonalData').mockResolvedValue({ someData: 'value' });
1604
+ jest.spyOn(map_utils_1.MapUtil, 'applyTransformMap').mockResolvedValue({ transformedData: 'value' });
1605
+ jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getIdentifierProperties').mockResolvedValue(['identifier']);
1606
+ jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getInformationalProperties').mockResolvedValue([]);
1607
+ jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'isOutboundCreatableFromEntity').mockResolvedValue(true);
1608
+ const events = await bppa.getEventsForItemFamilyChanges(itemFamilyChanges, 'assort123', seasonFed, new Map());
1609
+ expect(events).toHaveLength(1);
1610
+ expect(events[0].objectClass).toBe('LCSProductSeasonLink');
1611
+ expect(events[0].projectItemId).toBe('proj1');
1612
+ expect(events[0].itemFamilyId).toBeUndefined();
1613
+ });
1614
+ it('LCSSKUSeasonLink event includes projectItemId and itemFamilyId', async () => {
1615
+ const bppa = new base_process_publish_assortment_1.BaseProcessPublishAssortment(config, dc, mapFileUtil);
1616
+ const itemFamilyId = 'family123';
1617
+ const colorId = 'color456';
1618
+ const familyItemData = { id: itemFamilyId, identifier: 'FAM-123', itemNumber: 'FAM-123' };
1619
+ const itemData = { id: colorId, identifier: 'COLOR-456', itemNumber: 'COLOR-456' };
1620
+ const familyProjectItem = { id: 'proj0', updatedOn: '2023-01-14T00:00:00.000Z' };
1621
+ const projectItem = { id: 'proj1', updatedOn: '2023-01-15T00:00:00.000Z' };
1622
+ const assortment = { id: 'assort123', name: 'Fall 2023 Assortment', publishToFlexPLM: true };
1623
+ const seasonFed = {
1624
+ entityReference: 'assortment:assort123',
1625
+ objectClass: 'LCSSeason',
1626
+ flexPLMSeasonName: 'Fall 2023'
1627
+ };
1628
+ const itemFamilyChanges = new item_family_changes_1.ItemFamilyChanges(itemFamilyId, new Date('2023-01-01T00:00:00.000Z'));
1629
+ itemFamilyChanges.colorAdds.push(colorId);
1630
+ itemFamilyChanges.assortmentItemFullChangeMap.set(itemFamilyId, {
1631
+ item: familyItemData,
1632
+ projectItem: familyProjectItem
1633
+ });
1634
+ itemFamilyChanges.assortmentItemFullChangeMap.set(colorId, {
1635
+ item: itemData,
1636
+ projectItem
1637
+ });
1638
+ jest.spyOn(bppa, 'getAssortment').mockResolvedValue(assortment);
1639
+ jest.spyOn(bppa, 'getProjectItem')
1640
+ .mockReturnValueOnce(familyProjectItem)
1641
+ .mockReturnValueOnce(projectItem);
1642
+ jest.spyOn(bppa, 'getSeasonalData').mockResolvedValue({ someData: 'value' });
1643
+ jest.spyOn(map_utils_1.MapUtil, 'applyTransformMap').mockResolvedValue({ transformedData: 'value' });
1644
+ jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getIdentifierProperties').mockResolvedValue(['identifier']);
1645
+ jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'getInformationalProperties').mockResolvedValue([]);
1646
+ jest.spyOn(type_conversion_utils_1.TypeConversionUtils, 'isOutboundCreatableFromEntity').mockResolvedValue(true);
1647
+ const events = await bppa.getEventsForItemFamilyChanges(itemFamilyChanges, 'assort123', seasonFed, new Map());
1648
+ expect(events).toHaveLength(2);
1649
+ const productEvent = events.find(e => e.objectClass === 'LCSProductSeasonLink');
1650
+ const skuEvent = events.find(e => e.objectClass === 'LCSSKUSeasonLink');
1651
+ expect(productEvent.projectItemId).toBe('proj0');
1652
+ expect(productEvent.itemFamilyId).toBeUndefined();
1653
+ expect(skuEvent.projectItemId).toBe('proj1');
1654
+ expect(skuEvent.itemFamilyId).toBe('family123');
1655
+ });
1578
1656
  it('should use UPSERT_ON_SEASON for LCSSKUSeasonLink when isOutboundCreatableFromEntity returns true', async () => {
1579
1657
  const bppa = new base_process_publish_assortment_1.BaseProcessPublishAssortment(config, dc, mapFileUtil);
1580
1658
  const itemFamilyId = 'family123';
@@ -2211,3 +2289,179 @@ describe('released family with pre-development options', () => {
2211
2289
  expect(await ppa.getEventsForItemFamilyChanges(ifc, 'a1', eventSeasonFed, new Map())).toHaveLength(0);
2212
2290
  });
2213
2291
  });
2292
+ describe('sendEvents - separateVibeIQEvents', () => {
2293
+ const buildConfig = (extra = {}) => ({
2294
+ taskId: 'task-abc',
2295
+ event: '{"sourceEventId":"src-1"}',
2296
+ sendMode: { ASYNC_PUBLISH_SEASON: 'separateVibeIQEvents' },
2297
+ ...extra
2298
+ });
2299
+ const mapFileUtil = new transform_data_1.MapFileUtil(new sdk_1.Entities());
2300
+ const productEvent = (n) => ({
2301
+ eventType: 'UPSERT_ON_SEASON',
2302
+ objectClass: 'LCSProductSeasonLink',
2303
+ entityReference: 'item:fam' + n,
2304
+ projectItemId: 'pi-fam' + n,
2305
+ LCSSeason: {},
2306
+ LCSProduct: {},
2307
+ data: {}
2308
+ });
2309
+ const skuEvent = (n, familyN) => ({
2310
+ eventType: 'UPSERT_ON_SEASON',
2311
+ objectClass: 'LCSSKUSeasonLink',
2312
+ entityReference: 'item:sku' + n,
2313
+ projectItemId: 'pi-sku' + n,
2314
+ itemFamilyId: 'fam' + familyN,
2315
+ LCSSeason: {},
2316
+ LCSSKU: {},
2317
+ data: {}
2318
+ });
2319
+ const newBppa = (config) => new base_process_publish_assortment_1.BaseProcessPublishAssortment(config, new data_converter_1.DataConverter(config, mapFileUtil), mapFileUtil);
2320
+ const allCreatedObjects = () => batchCreateCalls.reduce((acc, call) => acc.concat(call.objects), []);
2321
+ beforeEach(() => {
2322
+ createCallArg = undefined;
2323
+ fileUploadCalls = [];
2324
+ batchCreateCalls = [];
2325
+ batchCreateImpl = () => Promise.resolve([]);
2326
+ fileUploadResult = {
2327
+ id: 'file-123',
2328
+ downloadUrl: 'https://download.url',
2329
+ adminDownloadUrl: 'https://admin.download.url'
2330
+ };
2331
+ });
2332
+ afterEach(() => {
2333
+ jest.restoreAllMocks();
2334
+ });
2335
+ it('creates one external-event per seasonal event, with the expected shape', async () => {
2336
+ const bppa = newBppa(buildConfig());
2337
+ const events = [productEvent(1), skuEvent(1, 1)];
2338
+ await bppa.sendEvents(events);
2339
+ expect(batchCreateCalls.length).toBeGreaterThan(0);
2340
+ batchCreateCalls.forEach(call => expect(call.entityName).toBe('external-event'));
2341
+ const objects = allCreatedObjects();
2342
+ expect(objects).toHaveLength(2);
2343
+ expect(objects[0]).toEqual({
2344
+ originSystemType: 'VibeIQ',
2345
+ objectClass: 'SendSeasonalEventToFlexPLM',
2346
+ eventToSend: productEvent(1),
2347
+ id: 'pi-fam1',
2348
+ itemFamilyId: 'fam1',
2349
+ initialEvent: { sourceEventId: 'src-1' }
2350
+ });
2351
+ expect(objects[1]).toEqual({
2352
+ originSystemType: 'VibeIQ',
2353
+ objectClass: 'SendSeasonalEventToFlexPLM',
2354
+ eventToSend: skuEvent(1, 1),
2355
+ id: 'pi-sku1',
2356
+ itemFamilyId: 'fam1',
2357
+ initialEvent: { sourceEventId: 'src-1' }
2358
+ });
2359
+ });
2360
+ it('creates all product-season events before any sku-season event, even when the input is interleaved', async () => {
2361
+ const bppa = newBppa(buildConfig());
2362
+ const events = [skuEvent(1, 1), productEvent(1), skuEvent(2, 2), productEvent(2)];
2363
+ await bppa.sendEvents(events);
2364
+ const classes = allCreatedObjects().map(o => o.eventToSend.objectClass);
2365
+ expect(classes).toEqual([
2366
+ 'LCSProductSeasonLink', 'LCSProductSeasonLink',
2367
+ 'LCSSKUSeasonLink', 'LCSSKUSeasonLink'
2368
+ ]);
2369
+ });
2370
+ it('splits creation into batches of separateEventsBatchSize and keeps product batches first', async () => {
2371
+ const bppa = newBppa(buildConfig({ separateEventsBatchSize: 2 }));
2372
+ const events = [];
2373
+ for (let i = 1; i <= 5; i++) {
2374
+ events.push(productEvent(i));
2375
+ }
2376
+ for (let i = 1; i <= 3; i++) {
2377
+ events.push(skuEvent(i, 1));
2378
+ }
2379
+ const result = await bppa.sendEvents(events);
2380
+ expect(batchCreateCalls.map(c => c.objects.length)).toEqual([2, 2, 1, 2, 1]);
2381
+ expect(result.eventsCreated).toEqual({ productSeasons: 5, colorwaySeasons: 3 });
2382
+ });
2383
+ it('uses a batch size of 100 when separateEventsBatchSize is not a valid number', async () => {
2384
+ const bppa = newBppa(buildConfig({ separateEventsBatchSize: 'abc' }));
2385
+ const events = [];
2386
+ for (let i = 1; i <= 150; i++) {
2387
+ events.push(productEvent(i));
2388
+ }
2389
+ await bppa.sendEvents(events);
2390
+ expect(batchCreateCalls.map(c => c.objects.length)).toEqual([100, 50]);
2391
+ });
2392
+ it('uploads the events file, and does not call FlexPLM or create AssortmentPublishedToFlexPLM', async () => {
2393
+ const bppa = newBppa(buildConfig());
2394
+ const events = [productEvent(1), skuEvent(1, 1)];
2395
+ const spyFlex = jest.spyOn(flexplm_connect_1.FlexPLMConnect.prototype, 'sendToFlexPLM').mockResolvedValue({ status: 200 });
2396
+ const result = await bppa.sendEvents(events);
2397
+ expect(fileUploadCalls).toHaveLength(1);
2398
+ expect(JSON.parse(fileUploadCalls[0].buffer.toString('utf-8'))).toEqual(events);
2399
+ expect(spyFlex).not.toHaveBeenCalled();
2400
+ expect(createCallArg).toBeUndefined();
2401
+ expect(result).toEqual({
2402
+ message: 'Successfully created separate VibeIQ events.',
2403
+ eventType: 'ASYNC_PUBLISH_SEASON',
2404
+ eventsFileId: 'file-123',
2405
+ eventsDownloadLink: 'https://download.url',
2406
+ eventsAdminDownloadLink: 'https://admin.download.url',
2407
+ eventsCreated: { productSeasons: 1, colorwaySeasons: 1 }
2408
+ });
2409
+ });
2410
+ it('stops at the failing batch and reports events already created', async () => {
2411
+ const bppa = newBppa(buildConfig({ separateEventsBatchSize: 2 }));
2412
+ const events = [];
2413
+ for (let i = 1; i <= 5; i++) {
2414
+ events.push(productEvent(i));
2415
+ }
2416
+ events.push(skuEvent(1, 1));
2417
+ let callCount = 0;
2418
+ batchCreateImpl = () => {
2419
+ callCount++;
2420
+ return callCount === 2 ? Promise.reject(new Error('batch failed')) : Promise.resolve([]);
2421
+ };
2422
+ jest.spyOn(console, 'error').mockImplementation(() => undefined);
2423
+ await expect(bppa.sendEvents(events)).rejects.toMatchObject({
2424
+ message: 'batch failed',
2425
+ eventsCreatedBeforeFailure: { productSeasons: 2, colorwaySeasons: 0 },
2426
+ eventsFileId: 'file-123'
2427
+ });
2428
+ expect(batchCreateCalls).toHaveLength(2);
2429
+ });
2430
+ it('falls back to the item id when projectItemId or itemFamilyId are missing', async () => {
2431
+ const bppa = newBppa(buildConfig());
2432
+ const prod = productEvent(9);
2433
+ delete prod.projectItemId;
2434
+ const sku = skuEvent(9, 9);
2435
+ delete sku.projectItemId;
2436
+ delete sku.itemFamilyId;
2437
+ const spyWarn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
2438
+ await bppa.sendEvents([prod, sku]);
2439
+ const objects = allCreatedObjects();
2440
+ expect(objects[0].id).toBe('fam9');
2441
+ expect(objects[0].itemFamilyId).toBe('fam9');
2442
+ expect(objects[1].id).toBe('sku9');
2443
+ expect(objects[1].itemFamilyId).toBe('sku9');
2444
+ expect(spyWarn).toHaveBeenCalled();
2445
+ });
2446
+ it('returns {} and creates nothing for an unknown sendMode', async () => {
2447
+ const bppa = newBppa(buildConfig({ sendMode: { ASYNC_PUBLISH_SEASON: 'bogus' } }));
2448
+ jest.spyOn(console, 'warn').mockImplementation(() => undefined);
2449
+ const result = await bppa.sendEvents([productEvent(1)]);
2450
+ expect(result).toEqual({});
2451
+ expect(batchCreateCalls).toHaveLength(0);
2452
+ expect(fileUploadCalls).toHaveLength(0);
2453
+ });
2454
+ it('returns {} and does not throw when sendMode is missing', async () => {
2455
+ const config = { taskId: 'task-abc' };
2456
+ const bppa = newBppa(config);
2457
+ jest.spyOn(console, 'warn').mockImplementation(() => undefined);
2458
+ const result = await bppa.sendEvents([productEvent(1)]);
2459
+ expect(result).toEqual({});
2460
+ expect(batchCreateCalls).toHaveLength(0);
2461
+ });
2462
+ it('is case-insensitive about the sendMode value', async () => {
2463
+ const bppa = newBppa(buildConfig({ sendMode: { ASYNC_PUBLISH_SEASON: 'SEPARATEVIBEIQEVENTS' } }));
2464
+ await bppa.sendEvents([productEvent(1)]);
2465
+ expect(allCreatedObjects()).toHaveLength(1);
2466
+ });
2467
+ });
@@ -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.0-alpha.fbb6338",
3
+ "version": "3.1.0-alpha.9d81aaa",
4
4
  "description": "Library used for integration with flexplm.",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",