-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathworkflow.controller.e2e.ts
More file actions
1461 lines (1271 loc) · 54.9 KB
/
workflow.controller.e2e.ts
File metadata and controls
1461 lines (1271 loc) · 54.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Novu } from '@novu/api';
import {
ContentIssueEnum,
CreateWorkflowDto,
DigestStepUpsertDto,
EmailStepResponseDto,
EmailStepUpsertDto,
InAppStepResponseDto,
InAppStepUpsertDto,
ListWorkflowResponse,
ResourceOriginEnum,
UpdateWorkflowDto,
UpdateWorkflowDtoSteps,
WorkflowCreationSourceEnum,
WorkflowListResponseDto,
WorkflowStatusEnum,
} from '@novu/api/models/components';
import { ErrorDto } from '@novu/api/models/errors';
import { WorkflowResponseDto } from '@novu/api/src/models/components';
import { buildSlug, JSONSchemaDto } from '@novu/application-generic';
import { PreferencesRepository } from '@novu/dal';
import {
ApiServiceLevelEnum,
DEFAULT_WORKFLOW_PREFERENCES,
FeatureNameEnum,
getFeatureForTierAsNumber,
ShortIsPrefixEnum,
StepTypeEnum,
slugify,
} from '@novu/shared';
import { UserSession } from '@novu/testing';
import chai, { expect } from 'chai';
import chaiSubset from 'chai-subset';
import {
expectSdkExceptionGeneric,
expectSdkValidationExceptionGeneric,
initNovuClassSdkInternalAuth,
} from '../shared/helpers/e2e/sdk/e2e-sdk.helper';
chai.use(chaiSubset);
// TODO: Introduce test factories for steps and workflows and move the following build functions there
function buildInAppStep(overrides: Partial<InAppStepUpsertDto> = {}): InAppStepUpsertDto {
return {
name: 'In-App Test Step',
type: 'in_app',
controlValues: {
subject: 'Test Subject',
body: 'Test Body',
},
...overrides,
} as InAppStepUpsertDto;
}
function buildDigestStep(overrides: Partial<DigestStepUpsertDto> = {}): DigestStepUpsertDto {
return {
name: 'Digest Test Step',
type: 'digest',
controlValues: {
amount: 1,
unit: 'hours',
},
...overrides,
} as DigestStepUpsertDto;
}
function buildEmailStep(overrides: Partial<EmailStepUpsertDto> = {}): EmailStepUpsertDto {
return {
name: 'Email Test Step',
type: 'email',
controlValues: {
subject: 'Test Email Subject',
body: 'Test Email Body',
disableOutputSanitization: false,
},
...overrides,
} as EmailStepUpsertDto;
}
// biome-ignore lint/suspicious/noExportsInTest: <explanation>
export function buildWorkflow(overrides: Partial<CreateWorkflowDto> = {}): CreateWorkflowDto {
const name = overrides.name || 'Test Workflow';
return {
source: WorkflowCreationSourceEnum.Editor,
name,
workflowId: slugify(name),
description: 'This is a test workflow',
active: true,
tags: ['tag1', 'tag2'],
steps: [buildEmailStep(), buildInAppStep()],
...overrides,
} as CreateWorkflowDto;
}
let session: UserSession;
function buildHeaders(overrideEnv?: string): HeadersInit {
return {
Authorization: session.token,
'Novu-Environment-Id': overrideEnv || session.environment._id,
};
}
async function createWorkflowAndExpectError(
apiClient: Novu,
createWorkflowDto: CreateWorkflowDto,
expectedPartialErrorMsg?: string
): Promise<ErrorDto> {
const res = await expectSdkExceptionGeneric(() => apiClient.workflows.create(createWorkflowDto));
expect(res.error).to.be.ok;
if (expectedPartialErrorMsg) {
expect(res.error?.message).to.include(expectedPartialErrorMsg);
}
return res.error!;
}
async function createWorkflowAndExpectValidationError(
apiClient: Novu,
createWorkflowDto: CreateWorkflowDto,
expectedPartialErrorMsg?: string
): Promise<ErrorDto> {
const res = await expectSdkValidationExceptionGeneric(() => apiClient.workflows.create(createWorkflowDto));
expect(res.error).to.be.ok;
if (expectedPartialErrorMsg) {
expect(JSON.stringify(res.error?.errors)).to.include(expectedPartialErrorMsg);
}
return res.error!;
}
async function createWorkflow(apiClient: Novu, createWorkflowDto: CreateWorkflowDto) {
return (await apiClient.workflows.create(createWorkflowDto)).result;
}
describe('Workflow Controller E2E API Testing #novu-v2', () => {
let apiClient: Novu;
beforeEach(async () => {
session = new UserSession();
await session.initialize();
apiClient = initNovuClassSdkInternalAuth(session);
});
describe('Create workflow', () => {
it('should allow creating two workflows for the same user with the same name', async () => {
const name = `Test Workflow${new Date().toISOString()}`;
await createWorkflowAndValidate(name);
const createWorkflowDto: CreateWorkflowDto = buildWorkflow({ name });
const workflowCreated = await createWorkflow(apiClient, createWorkflowDto);
expect(workflowCreated.workflowId).to.include(`${slugify(name)}-`);
});
it('should generate a payload schema if only control values are provided during workflow creation', async () => {
const steps: UpdateWorkflowDtoSteps[] = [
{
...buildEmailStep(),
controlValues: {
body: 'Welcome {{payload.name}}',
subject: 'Hello {{payload.name}}',
},
} as UpdateWorkflowDtoSteps,
];
const createWorkflowDto: CreateWorkflowDto = buildWorkflow({
steps,
payloadSchema: {
type: 'object',
properties: {
name: { type: 'string' },
},
required: [],
additionalProperties: false,
},
});
const workflow = await createWorkflow(apiClient, createWorkflowDto);
expect(workflow).to.be.ok;
expect(workflow.steps[0].variables).to.be.ok;
const stepData = await getStepData(workflow.id, workflow.steps[0].id);
expect(stepData.variables).to.be.ok;
const { properties } = stepData.variables as JSONSchemaDto;
expect(properties).to.be.ok;
const payloadProperties = properties?.payload as JSONSchemaDto;
expect(payloadProperties).to.be.ok;
expect(payloadProperties.properties?.name).to.be.ok;
});
it('should not allow to create more than 20 workflows for a free organization', async () => {
await session.updateOrganizationServiceLevel(ApiServiceLevelEnum.FREE);
getFeatureForTierAsNumber(FeatureNameEnum.PLATFORM_MAX_WORKFLOWS, ApiServiceLevelEnum.FREE, false);
for (let i = 0; i < 20; i += 1) {
const createWorkflowDto: CreateWorkflowDto = buildWorkflow({ name: new Date().toISOString() + i });
await createWorkflow(apiClient, createWorkflowDto);
}
const createWorkflowDto: CreateWorkflowDto = buildWorkflow({ name: new Date().toISOString() });
const error = await createWorkflowAndExpectError(apiClient, createWorkflowDto);
expect(error?.statusCode).eq(400);
});
it('should create workflow with payloadSchema and validatePayload fields', async () => {
const payloadSchema = {
type: 'object',
properties: {
name: {
type: 'string',
description: 'User name',
},
age: {
type: 'number',
minimum: 0,
},
},
required: ['name'],
};
const createWorkflowDto: CreateWorkflowDto = {
...buildWorkflow({
name: `Test Workflow with Schema ${new Date().toISOString()}`,
}),
payloadSchema,
validatePayload: true,
};
const workflowCreated = await createWorkflow(apiClient, createWorkflowDto);
expect(workflowCreated).to.be.ok;
expect(workflowCreated.payloadSchema).to.deep.equal(payloadSchema);
expect(workflowCreated.validatePayload).to.be.true;
});
it('should create workflow with validatePayload false', async () => {
const createWorkflowDto: CreateWorkflowDto = {
...buildWorkflow({
name: `Test Workflow No Validation ${new Date().toISOString()}`,
}),
validatePayload: false,
};
const workflowCreated = await createWorkflow(apiClient, createWorkflowDto);
expect(workflowCreated).to.be.ok;
expect(workflowCreated.validatePayload).to.be.false;
});
it('should create workflow with skip condition on a step using payload variable', async () => {
const skipCondition = {
'!=': [{ var: 'payload.skipStep' }, 'true'],
};
const steps = [
buildEmailStep({
controlValues: {
subject: 'Test Email Subject',
body: 'Test Email Body',
disableOutputSanitization: false,
skip: skipCondition,
},
}),
buildInAppStep({
controlValues: {
body: 'In-App Body',
},
}),
];
const payloadSchema = {
type: 'object',
properties: {
skipStep: { type: 'string' },
},
required: ['skipStep'],
additionalProperties: false,
};
const createWorkflowDto: CreateWorkflowDto = buildWorkflow({
name: `Skip Logic Workflow ${new Date().toISOString()}`,
steps: steps as any,
payloadSchema,
});
const workflow = await createWorkflow(apiClient, createWorkflowDto);
expect(workflow).to.be.ok;
expect(workflow.steps).to.have.lengthOf(2);
expect(Object.keys(workflow.issues || {}).length).to.equal(0);
const emailStep = workflow.steps[0] as EmailStepResponseDto;
expect(emailStep.type).to.equal('email');
expect(emailStep.controls.values.skip).to.deep.equal(skipCondition);
expect(emailStep.controls.values.subject).to.equal('Test Email Subject');
const inAppStep = workflow.steps[1] as InAppStepResponseDto;
expect(inAppStep.type).to.equal('in_app');
expect(inAppStep.controls.values.skip).to.be.undefined;
const retrievedWorkflow = await getWorkflow(workflow.id);
const retrievedEmailStep = retrievedWorkflow.steps[0] as EmailStepResponseDto;
expect(retrievedEmailStep.controls.values.skip).to.deep.equal(skipCondition);
const retrievedInAppStep = retrievedWorkflow.steps[1] as InAppStepResponseDto;
expect(retrievedInAppStep.controls.values.skip).to.be.undefined;
expect(retrievedWorkflow.payloadSchema).to.deep.equal(payloadSchema);
});
it('should reject workflow creation with invalid JSON schema', async () => {
const invalidPayloadSchema = {
type: 'invalid-type',
properties: 'not-an-object',
};
const createWorkflowDto: CreateWorkflowDto = {
...buildWorkflow({
name: `Test Invalid Schema ${new Date().toISOString()}`,
}),
payloadSchema: invalidPayloadSchema,
};
const error = await createWorkflowAndExpectValidationError(apiClient, createWorkflowDto);
expect(error?.statusCode).to.equal(422);
expect(JSON.stringify(error)).to.include('payloadSchema must be a valid JSON schema');
});
});
describe('Update workflow', () => {
it('should update control values', async () => {
const nameSuffix = `Test Workflow${new Date().toISOString()}`;
const workflowCreated: WorkflowResponseDto = await createWorkflowAndValidate(nameSuffix);
const inAppControlValue = 'In-App Test';
const emailControlValue = 'Email Test';
const updateRequest: UpdateWorkflowDto = {
origin: ResourceOriginEnum.NovuCloud,
name: workflowCreated.name,
preferences: {
user: null,
},
steps: [
buildInAppStep({ controlValues: { subject: inAppControlValue } }),
buildEmailStep({ controlValues: { subject: emailControlValue } }),
],
workflowId: workflowCreated.workflowId,
} as UpdateWorkflowDto;
const updatedWorkflow: WorkflowResponseDto = await updateWorkflow(
workflowCreated.id,
updateRequest as UpdateWorkflowDto
);
// TODO: Control values must be typed and accept only valid control values
expect((updatedWorkflow.steps[0] as InAppStepResponseDto).controls.values.subject).to.be.equal(inAppControlValue);
expect((updatedWorkflow.steps[1] as EmailStepResponseDto).controls.values.subject).to.be.equal(emailControlValue);
});
it('should keep the step id on updated ', async () => {
const nameSuffix = `Test Workflow${new Date().toISOString()}`;
const workflowCreated: WorkflowResponseDto = await createWorkflowAndValidate(nameSuffix);
const updatedWorkflow = await updateWorkflow(workflowCreated.id, mapResponseToUpdateDto(workflowCreated));
const updatedStep = updatedWorkflow.steps[0];
const originalStep = workflowCreated.steps[0];
expect(updatedStep.id).to.be.ok;
expect(updatedStep.id).to.be.equal(originalStep.id);
});
it('should keep the step id on updated ', async () => {
const nameSuffix = `Test Workflow${new Date().toISOString()}`;
const workflowCreated: WorkflowResponseDto = await createWorkflowAndValidate(nameSuffix);
expect(workflowCreated.steps.length).to.be.equal(2);
// Verify that all step ids are unique
const stepIds1 = workflowCreated.steps.map((step) => step.id);
const uniqueStepIds1 = [...new Set(stepIds1)];
expect(stepIds1.length).to.equal(uniqueStepIds1.length, 'All step ids should be unique on creation');
// Add a step of an existing channel at the beginning of the steps array
workflowCreated.steps = [buildInAppStep(), ...workflowCreated.steps] as any;
const updatedWorkflow = await updateWorkflow(workflowCreated.id, mapResponseToUpdateDto(workflowCreated));
expect(updatedWorkflow.steps.length).to.be.equal(3);
// Verify that all step ids are unique
const stepIds2 = workflowCreated.steps.map((step) => step.id);
const uniqueStepIds2 = [...new Set(stepIds2)];
expect(stepIds2.length).to.equal(uniqueStepIds2.length, 'All step ids should be unique after update');
});
it('should update user preferences', async () => {
const nameSuffix = `Test Workflow${new Date().toISOString()}`;
const workflowCreated: WorkflowResponseDto = await createWorkflowAndValidate(nameSuffix);
const updatedWorkflow = await updateWorkflow(workflowCreated.id, {
...mapResponseToUpdateDto(workflowCreated),
preferences: {
user: { ...DEFAULT_WORKFLOW_PREFERENCES, all: { ...DEFAULT_WORKFLOW_PREFERENCES.all, enabled: false } },
},
});
expect(updatedWorkflow.preferences.user, JSON.stringify(updatedWorkflow, null, 2)).to.be.ok;
expect(updatedWorkflow.preferences?.user?.all.enabled, JSON.stringify(updatedWorkflow, null, 2)).to.be.false;
const updatedWorkflow2 = await updateWorkflow(workflowCreated.id, {
...mapResponseToUpdateDto(workflowCreated),
preferences: {
user: null,
},
});
expect(updatedWorkflow2.preferences.user).to.be.null;
expect(updatedWorkflow2.preferences.default).to.be.ok;
});
it('should update by slugify ids', async () => {
const workflowCreated = await createWorkflowAndValidate();
const { id, workflowId, slug, updatedAt } = workflowCreated;
await updateWorkflowAndValidate(id, updatedAt, {
...mapResponseToUpdateDto(workflowCreated),
name: 'Test Workflow 1',
});
await updateWorkflowAndValidate(workflowId, updatedAt, {
...mapResponseToUpdateDto(workflowCreated),
name: 'Test Workflow 2',
});
await updateWorkflowAndValidate(slug, updatedAt, {
...mapResponseToUpdateDto(workflowCreated),
name: 'Test Workflow 3',
});
});
it('should update workflow with payloadSchema and validatePayload fields', async () => {
const workflowCreated = await createWorkflowAndValidate();
const payloadSchema = {
type: 'object',
properties: {
email: {
type: 'string',
format: 'email',
},
count: {
type: 'number',
minimum: 1,
},
},
required: ['email'],
};
const updateRequest: UpdateWorkflowDto = {
...mapResponseToUpdateDto(workflowCreated),
payloadSchema,
validatePayload: true,
} as UpdateWorkflowDto;
const updatedWorkflow = await updateWorkflow(workflowCreated.id, updateRequest);
expect(updatedWorkflow).to.be.ok;
expect(updatedWorkflow.payloadSchema).to.deep.equal(payloadSchema);
expect(updatedWorkflow.validatePayload).to.be.true;
});
it('should update workflow to disable payload validation', async () => {
const workflowCreated = await createWorkflowAndValidate();
const updateRequest: UpdateWorkflowDto = {
...mapResponseToUpdateDto(workflowCreated),
validatePayload: false,
} as UpdateWorkflowDto;
const updatedWorkflow = await updateWorkflow(workflowCreated.id, updateRequest);
expect(updatedWorkflow).to.be.ok;
expect(updatedWorkflow.validatePayload).to.be.false;
});
});
describe('List workflows', () => {
it('should not return workflows with if not matching query', async () => {
await createWorkflowAndValidate('XYZ');
await createWorkflowAndValidate('XYZ2');
const workflowSummaries = await getAllAndValidate({
searchQuery: 'ABC',
expectedTotalResults: 0,
expectedArraySize: 0,
});
expect(workflowSummaries).to.be.empty;
});
it('should not return workflows if offset is bigger than the amount of available workflows', async () => {
await create10Workflows('Test Workflow');
await getAllAndValidate({
searchQuery: 'Test Workflow',
offset: 11,
limit: 15,
expectedTotalResults: 10,
expectedArraySize: 0,
});
});
it('should return all results within range', async () => {
await create10Workflows('Test Workflow');
await getAllAndValidate({
searchQuery: 'Test Workflow',
offset: 0,
limit: 15,
expectedTotalResults: 10,
expectedArraySize: 10,
});
});
it('should return results without query', async () => {
await create10Workflows('Test Workflow');
await getAllAndValidate({
searchQuery: 'Test Workflow',
offset: 0,
limit: 15,
expectedTotalResults: 10,
expectedArraySize: 10,
});
});
it('paginate workflows without overlap', async () => {
await create10Workflows('Test Workflow');
const listWorkflowResponse1 = await getAllAndValidate({
searchQuery: 'Test Workflow',
offset: 0,
limit: 5,
expectedTotalResults: 10,
expectedArraySize: 5,
});
const listWorkflowResponse2 = await getAllAndValidate({
searchQuery: 'Test Workflow',
offset: 5,
limit: 5,
expectedTotalResults: 10,
expectedArraySize: 5,
});
const idsDeduplicated = new Set([
...listWorkflowResponse1.map((workflow) => workflow.id),
...listWorkflowResponse2.map((workflow) => workflow.id),
]);
expect(idsDeduplicated.size).to.be.equal(10);
});
async function createV0Workflow(id: number) {
return await createWorkflowsV1({
name: `Test V0 Workflow${id}`,
description: 'This is a test description',
tags: ['test-tag-api'],
notificationGroupId: session.notificationGroups[0]._id,
steps: [],
});
}
async function searchWorkflowsV0(workflowId?: string) {
return await searchWorkflowsV1(workflowId);
}
async function getV2WorkflowIdAndExternalId(prefix: string) {
await create10Workflows(prefix);
const listWorkflowResponse: ListWorkflowResponse = await listWorkflows(prefix, 0, 5);
const workflowV2Id = listWorkflowResponse.workflows[0].id;
const { workflowId } = listWorkflowResponse.workflows[0];
return { workflowV2Id, workflowId, name: listWorkflowResponse.workflows[0].name };
}
it('old list endpoint should not retrieve the new workflow', async () => {
const { workflowV2Id, name } = await getV2WorkflowIdAndExternalId('Test Workflow');
const [, , workflowV0Created] = await Promise.all([
createV0Workflow(1),
createV0Workflow(2),
createV0Workflow(3),
]);
let workflowsFromSearch = await searchWorkflowsV0(workflowV0Created?.name);
expect(workflowsFromSearch[0]._id).to.deep.eq(workflowV0Created._id);
workflowsFromSearch = await searchWorkflowsV0();
const ids = workflowsFromSearch?.map((workflow) => workflow._id);
const found = ids?.some((localId) => localId === workflowV2Id);
expect(found, `FoundIds:${ids} SearchedID:${workflowV2Id}`).to.be.false;
workflowsFromSearch = await searchWorkflowsV0(name);
expect(workflowsFromSearch?.length).to.eq(0);
});
});
describe('Promote workflow', () => {
it('should promote by creating a new workflow in production environment with the same properties', async () => {
// Create a workflow in the development environment
const createWorkflowDto = buildWorkflow({
name: 'Promote Workflow',
steps: [
buildEmailStep({
controlValues: { body: 'Example body', subject: 'Example subject', disableOutputSanitization: false },
}),
buildInAppStep({
controlValues: { body: 'Example body' },
}),
],
} as CreateWorkflowDto);
let devWorkflow = await createWorkflow(apiClient, createWorkflowDto);
// Update the workflow name to make sure the workflow identifier is the same after promotion
devWorkflow = await updateWorkflow(devWorkflow.id, {
...mapResponseToUpdateDto(devWorkflow),
name: `${devWorkflow.name}-updated`,
});
devWorkflow = await getWorkflow(devWorkflow.id);
// Switch to production environment and get its ID
await session.switchToProdEnvironment();
const prodEnvironmentId = session.environment._id;
await session.switchToDevEnvironment();
// Promote the workflow to production
const prodWorkflow = await syncWorkflow(devWorkflow, prodEnvironmentId);
// Verify that the promoted workflow has a new ID but the same workflowId
expect(prodWorkflow.id).to.not.equal(devWorkflow.id);
expect(prodWorkflow.workflowId).to.equal(devWorkflow.workflowId);
// Check that all non-environment-specific properties are identical
const propertiesToCompare = ['name', 'description', 'tags', 'preferences', 'status', 'type', 'origin'];
propertiesToCompare.forEach((prop) => {
expect(prodWorkflow[prop]).to.deep.equal(devWorkflow[prop], `Property ${prop} should match`);
});
// Verify that steps are correctly promoted
expect(prodWorkflow.steps).to.have.lengthOf(devWorkflow.steps.length);
for (const prodStep of prodWorkflow.steps) {
const index = prodWorkflow.steps.indexOf(prodStep);
const devStep = devWorkflow.steps[index];
expect(prodStep.stepId).to.equal(devStep.stepId, 'Step ID should be the same');
expect(prodStep.controls.values).to.deep.equal(devStep.controls.values, 'Step controlValues should match');
expect(prodStep.name).to.equal(devStep.name, 'Step name should match');
expect(prodStep.type).to.equal(devStep.type, 'Step type should match');
}
});
it('should promote by updating an existing workflow in production environment', async () => {
// Switch to production environment and get its ID
await session.switchToProdEnvironment();
const prodEnvironmentId = session.environment._id;
await session.switchToDevEnvironment();
// Create a workflow in the development environment
const createWorkflowDto = buildWorkflow({
name: 'Promote Workflow',
steps: [
buildEmailStep({
controlValues: {
body: 'Example body',
subject: 'Example subject',
disableOutputSanitization: false,
editorType: 'html',
},
}),
buildInAppStep({
controlValues: { body: 'Example body', disableOutputSanitization: false },
}),
],
} as CreateWorkflowDto);
const devWorkflow = await createWorkflow(apiClient, createWorkflowDto);
// Promote the workflow to production
const resPromoteCreate = await apiClient.workflows.sync(
{
targetEnvironmentId: prodEnvironmentId,
},
devWorkflow.id
);
const prodWorkflowCreated = resPromoteCreate.result;
// Update the workflow in the development environment
const updateDto: UpdateWorkflowDto = {
...mapResponseToUpdateDto(devWorkflow),
name: 'Updated Name',
description: 'Updated Description',
// modify existing Email Step, add new InApp Steps, previously existing InApp Step is removed
steps: [
{
...buildEmailStep({
controlValues: {
body: 'Example body',
editorType: 'html',
subject: 'Example subject',
disableOutputSanitization: false,
},
}),
id: devWorkflow.steps[0].id,
name: 'Updated Email Step',
},
{
...buildInAppStep({ controlValues: { body: 'Example body', disableOutputSanitization: false } }),
name: 'New InApp Step',
},
],
} as UpdateWorkflowDto;
await updateWorkflowAndValidate(devWorkflow.id, devWorkflow.updatedAt, updateDto);
// Promote the updated workflow to production
const resPromoteUpdate = await apiClient.workflows.sync(
{
targetEnvironmentId: prodEnvironmentId,
},
devWorkflow.id
);
const prodWorkflowUpdated = resPromoteUpdate.result;
// Verify that IDs remain unchanged
expect(prodWorkflowUpdated.id).to.equal(prodWorkflowCreated.id);
expect(prodWorkflowUpdated.workflowId).to.equal(prodWorkflowCreated.workflowId);
// Verify updated properties
expect(prodWorkflowUpdated.name).to.equal('Updated Name');
expect(prodWorkflowUpdated.description).to.equal('Updated Description');
// Verify unchanged properties
['status', 'type', 'origin'].forEach((prop) => {
expect(prodWorkflowUpdated[prop]).to.deep.equal(prodWorkflowCreated[prop], `Property ${prop} should match`);
});
// Verify updated steps
expect(prodWorkflowUpdated.steps).to.have.lengthOf(2);
expect(prodWorkflowUpdated.steps[0].name).to.equal('Updated Email Step');
expect(prodWorkflowUpdated.steps[0].id).to.equal(prodWorkflowCreated.steps[0].id);
expect(prodWorkflowUpdated.steps[0].stepId).to.equal(prodWorkflowCreated.steps[0].stepId);
expect(prodWorkflowUpdated.steps[0].controls.values).to.deep.equal({
body: 'Example body',
subject: 'Example subject',
disableOutputSanitization: false,
editorType: 'html',
});
// Verify new created step
expect(prodWorkflowUpdated.steps[1].name).to.equal('New InApp Step');
expect(prodWorkflowUpdated.steps[1].id).to.not.equal(prodWorkflowCreated.steps[1].id);
expect(prodWorkflowUpdated.steps[1].stepId).to.equal('new-in-app-step');
expect(prodWorkflowUpdated.steps[1].controls.values).to.deep.equal({
body: 'Example body',
disableOutputSanitization: false,
});
});
it('should throw an error if trying to promote to the same environment', async () => {
const devWorkflow = await createWorkflowAndValidate('-promote-workflow');
const { error } = await expectSdkExceptionGeneric(() =>
apiClient.workflows.sync(
{
targetEnvironmentId: session.environment._id,
},
devWorkflow.id
)
);
expect(error?.statusCode).to.equal(400);
expect(error?.message).to.equal('Cannot sync workflow to the same environment');
});
it('should throw an error if the target environment is not found', async () => {
const { error } = await expectSdkExceptionGeneric(() =>
apiClient.workflows.sync({ targetEnvironmentId: '123' }, '123')
);
expect(error?.statusCode).to.equal(404);
expect(error?.message).to.equal('Environment 123 not found');
});
it('should throw an error if the workflow to promote is not found', async () => {
await session.switchToProdEnvironment();
const prodEnvironmentId = session.environment._id;
await session.switchToDevEnvironment();
const { error } = await expectSdkExceptionGeneric(() =>
apiClient.workflows.sync({ targetEnvironmentId: prodEnvironmentId }, '123')
);
expect(error?.statusCode).to.equal(404);
expect(error?.message).to.equal('Workflow cannot be found');
expect(error?.ctx?.workflowId).to.equal('123');
});
});
describe('Get workflow', () => {
it('should get by slugify ids', async () => {
const workflowCreated = await createWorkflowAndValidate('XYZ');
const internalId = workflowCreated.id;
const workflowRetrievedByInternalId = await getWorkflow(internalId);
expect(workflowRetrievedByInternalId.id).to.equal(internalId);
const slugPrefixAndEncodedInternalId = buildSlug(`my-workflow`, ShortIsPrefixEnum.WORKFLOW, internalId);
const workflowRetrievedBySlugPrefixAndEncodedInternalId = await getWorkflow(slugPrefixAndEncodedInternalId);
expect(workflowRetrievedBySlugPrefixAndEncodedInternalId.id).to.equal(internalId);
const workflowIdentifier = workflowCreated.workflowId;
const workflowRetrievedByWorkflowIdentifier = await getWorkflow(workflowIdentifier);
expect(workflowRetrievedByWorkflowIdentifier.id).to.equal(internalId);
});
it('should return 404 if workflow does not exist', async () => {
const notExistingId = '123';
const novuRestResult = await expectSdkExceptionGeneric(() => apiClient.workflows.get(notExistingId));
expect(novuRestResult.error).to.be.ok;
expect(novuRestResult.error!.statusCode).to.equal(404);
expect(novuRestResult.error!.message).to.contain('Workflow');
expect(novuRestResult.error!.ctx?.workflowId).to.contain(notExistingId);
});
});
describe('Duplicate workflow', () => {
it('should duplicate a workflow', async () => {
const workflowCreated = await createWorkflowAndValidate('XYZ');
const duplicatedWorkflow = (
await apiClient.workflows.duplicate(
{
name: 'Duplicated Workflow',
},
workflowCreated.id
)
).result;
expect(duplicatedWorkflow?.id).to.not.equal(workflowCreated.id);
expect(duplicatedWorkflow?.active).to.be.false;
expect(duplicatedWorkflow?.name).to.equal('Duplicated Workflow');
expect(duplicatedWorkflow?.description).to.equal(workflowCreated.description);
expect(duplicatedWorkflow?.tags).to.deep.equal(workflowCreated.tags);
expect(duplicatedWorkflow?.steps.length).to.equal(workflowCreated.steps.length);
duplicatedWorkflow?.steps.forEach((step, index) => {
expect(step.name).to.equal(workflowCreated.steps[index].name);
expect(step.id).to.not.equal(workflowCreated.steps[index].id);
});
expect(duplicatedWorkflow?.preferences).to.deep.equal(workflowCreated.preferences);
});
it('should duplicate a workflow with overrides', async () => {
const workflowCreated = await createWorkflowAndValidate('XYZ');
const duplicatedWorkflow = (
await apiClient.workflows.duplicate(
{
name: 'Duplicated Workflow',
tags: ['tag1', 'tag2'],
description: 'New Description',
},
workflowCreated.id
)
).result;
expect(duplicatedWorkflow?.id).to.not.equal(workflowCreated.id);
expect(duplicatedWorkflow?.active).to.be.false;
expect(duplicatedWorkflow?.name).to.equal('Duplicated Workflow');
expect(duplicatedWorkflow?.description).to.equal('New Description');
expect(duplicatedWorkflow?.tags).to.deep.equal(['tag1', 'tag2']);
});
it('should throw an error if the workflow to duplicate is not found', async () => {
const res = await expectSdkExceptionGeneric(() =>
apiClient.workflows.duplicate({ name: 'Duplicated Workflow' }, '123')
);
expect(res.error).to.be.ok;
expect(res.error!.statusCode).to.equal(404);
expect(res.error!.message).to.contain('Workflow');
expect(res.error!.ctx?.workflowId).to.contain('123');
});
it('should duplicate a workflow with payloadSchema, validatePayload, and severity', async () => {
const payloadSchema = {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string' },
},
required: ['name'],
};
const createWorkflowDto: CreateWorkflowDto = buildWorkflow({
name: 'Test Workflow with Schema',
payloadSchema,
validatePayload: true,
});
const workflowCreated = await createWorkflow(apiClient, createWorkflowDto);
const duplicatedWorkflow = (
await apiClient.workflows.duplicate(
{
name: 'Duplicated Workflow with Schema',
},
workflowCreated.id
)
).result;
expect(duplicatedWorkflow?.id).to.not.equal(workflowCreated.id);
expect(duplicatedWorkflow?.payloadSchema).to.deep.equal(payloadSchema);
expect(duplicatedWorkflow?.validatePayload).to.equal(true);
expect(duplicatedWorkflow?.severity).to.equal(workflowCreated.severity);
});
});
describe('Get step data', () => {
it('should get step by worflow slugify ids', async () => {
const workflowCreated = await createWorkflowAndValidate('XYZ');
const internalWorkflowId = workflowCreated.id;
const stepId = workflowCreated.steps[0].id;
const stepRetrievedByWorkflowInternalId = await getStepData(internalWorkflowId, stepId);
expect(stepRetrievedByWorkflowInternalId.id).to.equal(stepId);
const slugPrefixAndEncodedWorkflowInternalId = buildSlug(
`my-workflow`,
ShortIsPrefixEnum.WORKFLOW,
internalWorkflowId
);
const stepRetrievedBySlugPrefixAndEncodedWorkflowInternalId = await getStepData(
slugPrefixAndEncodedWorkflowInternalId,
stepId
);
expect(stepRetrievedBySlugPrefixAndEncodedWorkflowInternalId.id).to.equal(stepId);
const workflowIdentifier = workflowCreated.workflowId;
const stepRetrievedByWorkflowIdentifier = await getStepData(workflowIdentifier, stepId);
expect(stepRetrievedByWorkflowIdentifier.id).to.equal(stepId);
});
it('should get step by step slugify ids', async () => {
const workflowCreated = await createWorkflowAndValidate('XYZ');
const internalWorkflowId = workflowCreated.id;
const stepId = workflowCreated.steps[0].id;
const stepRetrievedByStepInternalId = await getStepData(internalWorkflowId, stepId);
expect(stepRetrievedByStepInternalId.id).to.equal(stepId);
const slugPrefixAndEncodedStepId = buildSlug(`my-step`, ShortIsPrefixEnum.STEP, stepId);
const stepRetrievedBySlugPrefixAndEncodedStepId = await getStepData(
internalWorkflowId,
slugPrefixAndEncodedStepId
);
expect(stepRetrievedBySlugPrefixAndEncodedStepId.id).to.equal(stepId);
const stepIdentifier = workflowCreated.steps[0].stepId;
const stepRetrievedByStepIdentifier = await getStepData(internalWorkflowId, stepIdentifier);
expect(stepRetrievedByStepIdentifier.id).to.equal(stepId);
});
describe('Variables', () => {
it('should get step available variables', async () => {
const steps = [
{
...buildEmailStep(),
controlValues: {
body: 'Welcome to our newsletter {{subscriber.nonExistentValue}}{{payload.prefixBodyText2}}{{payload.prefixBodyText}}',
editorType: 'html',
subject: 'Welcome to our newsletter {{subjectText}} {{payload.prefixSubjectText}}',
},
},
{ ...buildInAppStep(), controlValues: { subject: 'Welcome to our newsletter {{inAppSubjectText}}' } },
];
const createWorkflowDto: CreateWorkflowDto = buildWorkflow({
steps: steps as UpdateWorkflowDtoSteps[],
payloadSchema: {
type: 'object',
properties: {
prefixBodyText2: { type: 'string' },
prefixBodyText: { type: 'string' },
prefixSubjectText: { type: 'string' },
},
required: [],
additionalProperties: false,
},
});
const res = await createWorkflow(apiClient, createWorkflowDto);
const stepData = await getStepData(res.id, res.steps[0].id);
const { variables } = stepData;
if (typeof variables === 'boolean') throw new Error('Variables is not an object');
const { properties } = variables;
expect(properties).to.be.ok;
if (!properties) throw new Error('Payload schema is not valid');
const payloadVariables = properties.payload;
expect(payloadVariables).to.be.ok;
if (!payloadVariables) throw new Error('Payload schema is not valid');
expect(JSON.stringify(payloadVariables)).to.contain('prefixBodyText2');
expect(JSON.stringify(payloadVariables)).to.contain('prefixSubjectText');
});
it('should serve previous step variables with payload schema', async () => {
const steps = [
buildDigestStep(),
{ ...buildInAppStep(), controlValues: { subject: 'Welcome to our newsletter {{payload.inAppSubjectText}}' } },
];
const createWorkflowDto: CreateWorkflowDto = buildWorkflow({
steps: steps as UpdateWorkflowDtoSteps[],
payloadSchema: {
type: 'object',
properties: {
inAppSubjectText: { type: 'string' },
},
required: [],
additionalProperties: false,
},
});
const res = await createWorkflow(apiClient, createWorkflowDto);
const novuRestResult = await apiClient.workflows.steps.retrieve(res.id, res.steps[1].id);
const { variables } = novuRestResult.result;
const variableList = getJsonSchemaPrimitiveProperties(variables as JSONSchemaDto);