-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathreceiver.service.spec.ts
More file actions
1570 lines (1271 loc) · 56.5 KB
/
Copy pathreceiver.service.spec.ts
File metadata and controls
1570 lines (1271 loc) · 56.5 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 { Test } from '@nestjs/testing';
import { ReceiverService } from './receiver.service';
import { EntityManager, In } from 'typeorm';
import { DismissedNotificationReceiverDto, TransactionSignatureService } from '@app/common';
import { NatsPublisherService } from '@app/common/nats/nats.publisher';
import {
Notification,
NotificationReceiver,
NotificationType,
Transaction,
TransactionApprover,
TransactionStatus,
User,
NOTIFICATION_CHANNELS,
} from '@entities';
import {
emitDeleteNotifications,
emitEmailNotifications,
emitNewNotifications,
emitNotifyClients,
} from './emit-notifications';
import { keysRequiredToSign } from '@app/common';
jest.mock('./emit-notifications', () => ({
emitDeleteNotifications: jest.fn(),
emitEmailNotifications: jest.fn(),
emitNewNotifications: jest.fn(),
emitNotifyClients: jest.fn(),
}));
jest.mock('@app/common', () => ({
...jest.requireActual('@app/common'),
keysRequiredToSign: jest.fn(),
}));
const mockEntityManager = () => ({
find: jest.fn(),
findOne: jest.fn(),
save: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
query: jest.fn(),
transaction: jest.fn(),
});
const mockTransactionSignatureService = () => ({
someMethod: jest.fn(),
});
const mockPublisher = () => ({
publish: jest.fn(),
});
describe('ReceiverService', () => {
let service: ReceiverService;
let em: ReturnType<typeof mockEntityManager>;
let tss: ReturnType<typeof mockTransactionSignatureService>;
let publisher: ReturnType<typeof mockPublisher>;
beforeEach(async () => {
em = mockEntityManager();
tss = mockTransactionSignatureService();
publisher = mockPublisher();
// Make transaction execute the callback with our mock em
em.transaction.mockImplementation(async (cb: any) => cb(em));
const module = await Test.createTestingModule({
providers: [
ReceiverService,
{ provide: EntityManager, useValue: em },
{ provide: TransactionSignatureService, useValue: tss },
{ provide: NatsPublisherService, useValue: publisher },
],
}).compile();
service = module.get(ReceiverService);
jest.clearAllMocks();
});
it('getInAppNotificationType and getEmailNotificationType cover all mapped statuses', () => {
const inAppMap = (ReceiverService as any).IN_APP_NOTIFICATION_TYPES as Record<string, any>;
for (const key of Object.keys(inAppMap)) {
expect((service as any).getInAppNotificationType(key)).toBe(inAppMap[key]);
}
const emailMap = (ReceiverService as any).EMAIL_NOTIFICATION_TYPES as Record<string, any>;
for (const key of Object.keys(emailMap)) {
expect((service as any).getEmailNotificationType(key)).toBe(emailMap[key]);
}
});
it('returns null when status is not mapped', () => {
// use a value that is not present in the maps and cast to TransactionStatus
const unknownStatus = (9999 as unknown) as TransactionStatus;
expect((service as any).getInAppNotificationType(unknownStatus)).toBeNull();
expect((service as any).getEmailNotificationType(unknownStatus)).toBeNull();
expect((service as any).getInAppNotificationType(null)).toBeNull();
expect((service as any).getEmailNotificationType(null)).toBeNull();
});
it('fetchTransactionsWithRelations returns map', async () => {
const tx = { id: 1 } as any;
em.find.mockResolvedValue([tx]);
const result = await (service as any).fetchTransactionsWithRelations([1], false);
expect(em.find).toHaveBeenCalledWith(Transaction, expect.any(Object));
expect(result.get(1)).toBe(tx);
});
it('fetchTransactionsWithRelations uses default withDeleted = false when omitted', async () => {
const tx = { id: 2 } as any;
em.find.mockResolvedValueOnce([tx]);
const result = await (service as any).fetchTransactionsWithRelations([2]); // omit second arg
expect(em.find).toHaveBeenCalledWith(Transaction, expect.objectContaining({ withDeleted: false }));
expect(result.get(2)).toBe(tx);
});
it('fetchTransactionsWithRelations forwards withDeleted = true when provided', async () => {
const tx = { id: 3 } as any;
em.find.mockResolvedValueOnce([tx]);
const result = await (service as any).fetchTransactionsWithRelations([3], true);
expect(em.find).toHaveBeenCalledWith(Transaction, expect.objectContaining({ withDeleted: true }));
expect(result.get(3)).toBe(tx);
});
it('getApproversByTransactionIds groups approvers', async () => {
em.query.mockResolvedValue([
{ id: 10, transactionId: 1, userId: 50 },
{ id: 11, transactionId: 1, userId: 51 },
{ id: 12, transactionId: 2, userId: 52 },
]);
const result = await (service as any).getApproversByTransactionIds(em as any, [1, 2]);
expect(result.get(1)!.length).toBe(2);
expect(result.get(2)!.length).toBe(1);
});
it('getApproversByTransactionIds returns empty Map when transactionIds is empty', async () => {
// ensure no DB calls are made for empty input
em.query.mockClear();
const result = await (service as any).getApproversByTransactionIds(em as any, []);
expect(result).toBeInstanceOf(Map);
expect(result.size).toBe(0);
expect(em.query).not.toHaveBeenCalled();
});
it('getUsersIdsRequiredToSign calls keysRequiredToSign and dedups', async () => {
(keysRequiredToSign as jest.Mock).mockResolvedValue([
{ userId: 10, user: { id: 10 } },
{ userId: 10, user: { id: 10 } },
{ userId: 11, user: { id: 11 } },
]);
const tx = {} as any;
const res = await (service as any).getUsersIdsRequiredToSign(em as any, tx, new Map());
expect(keysRequiredToSign).toHaveBeenCalled();
expect(res).toEqual([10, 11]);
});
it('getUsersIdsRequiredToSign filters out soft-deleted users', async () => {
(keysRequiredToSign as jest.Mock).mockResolvedValue([
{ userId: 10, user: { id: 10, deletedAt: null } },
{ userId: 11, user: { id: 11, deletedAt: new Date() } }, // deleted user
{ userId: 12, user: { id: 12, deletedAt: null } },
]);
const tx = {} as any;
const res = await (service as any).getUsersIdsRequiredToSign(em as any, tx, new Map());
expect(res).toEqual([10, 12]);
expect(res).not.toContain(11);
});
it('getUsersIdsRequiredToSign filters out soft-deleted keys', async () => {
(keysRequiredToSign as jest.Mock).mockResolvedValue([
{ userId: 10, deletedAt: null, user: { id: 10, deletedAt: null } },
{ userId: 11, deletedAt: new Date(), user: { id: 11, deletedAt: null } }, // deleted key
{ userId: 12, deletedAt: null, user: { id: 12, deletedAt: null } },
]);
const tx = {} as any;
const res = await (service as any).getUsersIdsRequiredToSign(em as any, tx, new Map());
expect(res).toEqual([10, 12]);
expect(res).not.toContain(11);
});
it('getUsersIdsRequiredToSign filters out keys with missing user relation', async () => {
(keysRequiredToSign as jest.Mock).mockResolvedValue([
{ userId: 10, deletedAt: null, user: { id: 10, deletedAt: null } },
{ userId: 11, deletedAt: null, user: null }, // missing user (orphaned key)
{ userId: 12, deletedAt: null, user: { id: 12, deletedAt: null } },
]);
const tx = {} as any;
const res = await (service as any).getUsersIdsRequiredToSign(em as any, tx, new Map());
expect(res).toEqual([10, 12]);
expect(res).not.toContain(11);
});
it('getUsersIdsRequiredToSign filters out all inactive keys leaving empty result', async () => {
(keysRequiredToSign as jest.Mock).mockResolvedValue([
{ userId: 10, deletedAt: new Date(), user: { id: 10, deletedAt: null } }, // deleted key
{ userId: 11, deletedAt: null, user: { id: 11, deletedAt: new Date() } }, // deleted user
{ userId: 12, deletedAt: null, user: null }, // missing user
]);
const tx = {} as any;
const res = await (service as any).getUsersIdsRequiredToSign(em as any, tx, new Map());
expect(res).toEqual([]);
});
it('getTransactionParticipants computes participants correctly', async () => {
(keysRequiredToSign as jest.Mock).mockResolvedValue([{ userId: 100, user: { id: 100 } }]);
const tx: any = {
creatorKey: { userId: 1 },
signers: [{ userId: 2 }],
observers: [{ userId: 3 }],
status: TransactionStatus.WAITING_FOR_SIGNATURES,
};
const approvers = [
{ userId: 4, approved: null } as TransactionApprover,
{ userId: 5, approved: true } as TransactionApprover,
];
const result = await (service as any).getTransactionParticipants(em as any, tx, approvers, new Map());
expect(result.participants).toEqual(expect.arrayContaining([1, 2, 3, 4, 100]));
expect(result.requiredUserIds).toEqual([100]);
});
it('getTransactionParticipants omits creatorId and does not include it in participants when creatorKey is null', async () => {
(keysRequiredToSign as jest.Mock).mockResolvedValue([{ userId: 100, user: { id: 100 } }]);
const tx: any = {
creatorKey: null,
signers: [{ userId: 2 }],
observers: [{ userId: 3 }],
status: TransactionStatus.WAITING_FOR_SIGNATURES,
};
const approvers = [
{ userId: 4, approved: null } as TransactionApprover,
{ userId: 5, approved: true } as TransactionApprover,
];
const result = await (service as any).getTransactionParticipants(em as any, tx, approvers, new Map());
expect('creatorId' in result).toBe(false);
expect(result.participants).toEqual(expect.arrayContaining([2, 3, 4, 5, 100]));
expect(result.participants).not.toContain(null);
expect(result.participants).not.toContain(undefined);
});
it('getTransactionParticipants yields empty approversShouldChooseUserIds when status is not waiting', async () => {
(keysRequiredToSign as jest.Mock).mockResolvedValue([{ userId: 100, user: { id: 100 } }]);
const tx: any = {
creatorKey: { userId: 1 },
signers: [{ userId: 2 }],
observers: [{ userId: 3 }],
status: TransactionStatus.EXECUTED, // not in waiting set
};
const approvers: any[] = [
{ userId: 4, approved: null },
{ userId: 5, approved: null },
];
const res = await (service as any).getTransactionParticipants(em as any, tx, approvers, new Map());
expect(res.approversShouldChooseUserIds).toEqual([]);
});
it('getTransactionParticipants yields empty approversShouldChooseUserIds when no approver is pending (all approved !== null) even if status is waiting', async () => {
(keysRequiredToSign as jest.Mock).mockResolvedValue([{ userId: 200, user: { id: 200 } }]);
const tx: any = {
creatorKey: { userId: 1 },
signers: [{ userId: 2 }],
observers: [{ userId: 3 }],
status: TransactionStatus.WAITING_FOR_SIGNATURES, // in waiting set
};
const approvers: any[] = [
{ userId: 4, approved: true },
{ userId: 5, approved: false }, // explicitly not null
{ userId: null, approved: true }, // falsy userId should be filtered out
];
const res = await (service as any).getTransactionParticipants(em as any, tx, approvers, new Map());
expect(res.approversShouldChooseUserIds).toEqual([]);
});
describe('getNotificationReceiverIds', () => {
const participantsMock = {
approversUserIds: [2, 3],
approversShouldChooseUserIds: [4],
observerUserIds: [5],
requiredUserIds: [6, 7],
creatorId: 1,
// other fields are ignored by the function under test
};
beforeEach(() => {
jest
.spyOn(service as any, 'getTransactionParticipants')
.mockResolvedValue(participantsMock);
});
it('returns creator + approvers + observers for APPROVAL_REJECTION / INDICATOR_REJECTED', async () => {
const resA = await (service as any).getNotificationReceiverIds(
em as any,
{} as any,
NotificationType.TRANSACTION_APPROVAL_REJECTION,
[] as any,
);
expect(resA).toEqual([1, 2, 3, 5]);
const resB = await (service as any).getNotificationReceiverIds(
em as any,
{} as any,
NotificationType.TRANSACTION_INDICATOR_REJECTED,
[] as any,
);
expect(resB).toEqual([1, 2, 3, 5]);
});
it('returns approversShouldChooseUserIds for APPROVED / INDICATOR_APPROVE', async () => {
const res = await (service as any).getNotificationReceiverIds(
em as any,
{} as any,
NotificationType.TRANSACTION_APPROVED,
[] as any,
);
expect(res).toEqual([4]);
const res2 = await (service as any).getNotificationReceiverIds(
em as any,
{} as any,
NotificationType.TRANSACTION_INDICATOR_APPROVE,
[] as any,
);
expect(res2).toEqual([4]);
});
it('returns requiredUserIds for WAITING_FOR_SIGNATURES and reminder variants / INDICATOR_SIGN', async () => {
const types = [
NotificationType.TRANSACTION_WAITING_FOR_SIGNATURES,
NotificationType.TRANSACTION_WAITING_FOR_SIGNATURES_REMINDER,
NotificationType.TRANSACTION_WAITING_FOR_SIGNATURES_REMINDER_MANUAL,
NotificationType.TRANSACTION_INDICATOR_SIGN,
];
for (const t of types) {
const res = await (service as any).getNotificationReceiverIds(
em as any,
{} as any,
t,
[] as any,
);
expect(res).toEqual([6, 7]);
}
});
it('returns creator + approvers + observers + required for execution/expired/archived etc.', async () => {
const types = [
NotificationType.TRANSACTION_READY_FOR_EXECUTION,
NotificationType.TRANSACTION_INDICATOR_EXECUTABLE,
NotificationType.TRANSACTION_EXECUTED,
NotificationType.TRANSACTION_INDICATOR_EXECUTED,
NotificationType.TRANSACTION_INDICATOR_FAILED,
NotificationType.TRANSACTION_EXPIRED,
NotificationType.TRANSACTION_INDICATOR_EXPIRED,
NotificationType.TRANSACTION_INDICATOR_ARCHIVED,
];
const expected = [1, 2, 3, 5, 6, 7];
for (const t of types) {
const res = await (service as any).getNotificationReceiverIds(
em as any,
{} as any,
t,
[] as any,
);
expect(res).toEqual(expected);
}
});
it('returns approvers + observers + required for CANCELLED / INDICATOR_CANCELLED', async () => {
const res = await (service as any).getNotificationReceiverIds(
em as any,
{} as any,
NotificationType.TRANSACTION_CANCELLED,
[] as any,
);
expect(res).toEqual([2, 3, 5, 6, 7]);
const res2 = await (service as any).getNotificationReceiverIds(
em as any,
{} as any,
NotificationType.TRANSACTION_INDICATOR_CANCELLED,
[] as any,
);
expect(res2).toEqual([2, 3, 5, 6, 7]);
});
it('logs a warning and returns empty array for unknown types', async () => {
const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
const res = await (service as any).getNotificationReceiverIds(
em as any,
{} as any,
999 as any,
[] as any,
);
expect(res).toEqual([]);
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('No recipient logic for'));
warnSpy.mockRestore();
});
});
describe('filterReceiversByPreferenceForType', () => {
beforeEach(() => { jest.clearAllMocks(); });
it('filterReceiversByPreferenceForType loads cache and filters', async () => {
em.find.mockResolvedValue([
{ id: 1, notificationPreferences: [{ type: NotificationType.TRANSACTION_EXECUTED, inApp: false }] },
{ id: 2, notificationPreferences: [{ type: NotificationType.TRANSACTION_EXECUTED, inApp: true }] },
]);
const cache = new Map<number, User>();
const res = await (service as any).filterReceiversByPreferenceForType(
em as any,
NotificationType.TRANSACTION_EXECUTED,
new Set([1, 2]),
cache,
);
expect(res).toEqual([2]);
// second call uses cache (no DB call)
em.find.mockClear();
const res2 = await (service as any).filterReceiversByPreferenceForType(
em as any,
NotificationType.TRANSACTION_EXECUTED,
new Set([1, 2]),
cache,
);
expect(em.find).not.toHaveBeenCalled();
expect(res2).toEqual([2]);
});
it('filterReceiversByPreferenceForType continues when user not found after load', async () => {
// em.find returns no users -> cache stays empty -> user is undefined -> continue branch
em.find.mockResolvedValueOnce([]);
const cache = new Map<number, User>();
const res = await (service as any).filterReceiversByPreferenceForType(
em as any,
NotificationType.TRANSACTION_EXECUTED,
new Set([3]),
cache,
);
expect(res).toEqual([]);
});
it('filterReceiversByPreferenceForType treats missing preferences as allowed (default true)', async () => {
// user returned without notificationPreferences -> preference is undefined -> default true
em.find.mockResolvedValueOnce([{ id: 4 }]);
const cache = new Map<number, User>();
const res = await (service as any).filterReceiversByPreferenceForType(
em as any,
NotificationType.TRANSACTION_EXECUTED,
new Set([4]),
cache,
);
expect(res).toEqual([4]);
});
});
it('createNotificationReceivers returns saved receivers or empty when none', async () => {
const notification = { id: 5, type: NotificationType.TRANSACTION_WAITING_FOR_SIGNATURES } as any;
em.save.mockResolvedValueOnce([{ id: 500 }]);
const empty = await (service as any).createNotificationReceivers(em as any, notification, []);
expect(empty).toEqual([]);
const res = await (service as any).createNotificationReceivers(em as any, notification, [1, 2]);
expect(em.save).toHaveBeenCalled();
expect(res[0].id).toBe(500);
});
it('deleteExistingIndicators deletes and returns mapping', async () => {
const nr = [{ id: 10, userId: 1 }];
em.find.mockResolvedValueOnce([
{ id: 100, notificationReceivers: nr },
]);
em.delete.mockResolvedValue({ raw: [], affected: 1 });
const result = await (service as any).deleteExistingIndicators(em as any, { id: 5 } as any);
expect(em.delete).toHaveBeenCalledTimes(2);
expect(result).toEqual([{ userId: 1, receiverId: 10 }]);
});
it('processNotificationType creates new and updates existing receivers', async () => {
const notification = {
id: 200,
notificationReceivers: [{ id: 700, userId: 1 }],
type: NotificationType.TRANSACTION_EXECUTED,
} as any;
em.findOne.mockResolvedValueOnce(notification);
em.save.mockResolvedValueOnce([{ id: 800, userId: 2 }]); // new created
em.update.mockResolvedValueOnce({ raw: [], affected: 1 });
em.find.mockResolvedValueOnce([{ id: 700, userId: 1, notification } as any]); // reloaded updated receivers
const cache = new Map<number, User>();
cache.set(1 as any, { id: 1 } as any);
cache.set(2 as any, { id: 2 } as any);
jest
.spyOn(service as any, 'filterReceiversByPreferenceForType')
.mockResolvedValue([1, 2]);
const { newReceivers, updatedReceivers } = await (service as any).processNotificationType(
em as any,
55,
NotificationType.TRANSACTION_EXECUTED,
new Set([1, 2]),
cache,
);
expect(newReceivers.length).toBe(1);
expect(updatedReceivers.length).toBe(1);
expect(em.update).toHaveBeenCalled();
});
it('processNotificationType uses in-app update fields when channel.email is falsey', async () => {
const notificationType = NotificationType.TRANSACTION_INDICATOR_SIGN;
// Stub existing notification with two receivers
const notification = { id: 123, notificationReceivers: [{ id: 10, userId: 1 }, { id: 11, userId: 2 }] } as any;
em.findOne.mockResolvedValueOnce(notification);
// Ensure all users pass preference filter
jest.spyOn(service as any, 'filterReceiversByPreferenceForType').mockResolvedValue([1, 2]);
// Temporarily override NOTIFICATION_CHANNELS for this type to have email = false
const originalChannel = NOTIFICATION_CHANNELS[notificationType];
NOTIFICATION_CHANNELS[notificationType] = { email: false, inApp: true };
// Mock DB update/find/save flows used by the method
em.update.mockResolvedValueOnce({});
em.find.mockResolvedValueOnce([{ id: 10, userId: 1, notification } as any, { id: 11, userId: 2, notification } as any]);
em.save.mockResolvedValueOnce([]); // createNotificationReceivers -> none
const cache = new Map<number, User>();
cache.set(1, { id: 1 } as any);
cache.set(2, { id: 2 } as any);
await (service as any).processNotificationType(
em as any,
/* transactionId */ 999,
notificationType,
new Set([1, 2]),
cache,
);
// verify update used in-app fields (email false => in-app update)
expect(em.update).toHaveBeenCalled();
const updateArgs = em.update.mock.calls[0];
expect(updateArgs[2]).toEqual({ isRead: false, isInAppNotified: false });
// cleanup: restore original channels mapping
NOTIFICATION_CHANNELS[notificationType] = originalChannel;
});
it('processReminderEmail creates a new notification and receivers', async () => {
const tx: any = { id: 1, validStart: 1, transactionId: 'tx1', mirrorNetwork: 'net' };
em.save.mockResolvedValueOnce({ id: 900 }); // notification
(service as any).filterReceiversByPreferenceForType = jest.fn().mockResolvedValue([10]);
(service as any).createNotificationReceivers = jest.fn().mockResolvedValue([{ id: 901 }]);
const res = await (service as any).processReminderEmail(em as any, tx, new Set([10]), new Map());
expect(em.save).toHaveBeenCalled();
expect(res[0].id).toBe(901);
});
describe('collectEmailNotifications', () => {
beforeEach(() => jest.clearAllMocks());
it('collects notifications when user has an email', () => {
const cache = new Map<number, any>();
cache.set(2, { id: 2, email: 'ok@example.com' });
const newReceivers = [
{ id: 12, userId: 2, notification: { id: 102 } },
] as any[];
const updatedReceivers: any[] = [];
const emailNotifications: { [email: string]: any[] } = {};
const receiverIds: number[] = [];
(service as any).collectEmailNotifications(newReceivers, updatedReceivers, emailNotifications, receiverIds, cache);
expect(Object.keys(emailNotifications)).toEqual(['ok@example.com']);
expect(emailNotifications['ok@example.com'][0].id).toBe(102);
expect(receiverIds).toContain(12);
});
it('logs and skips receivers when user missing or has no email', () => {
const cache = new Map<number, any>();
cache.set(1, { id: 1, email: null }); // present but no email
// user 3 is not set in cache -> should also be logged/skipped
const newReceivers = [
{ id: 11, userId: 1, notification: { id: 101 } },
] as any[];
const updatedReceivers = [
{ id: 13, userId: 3, notification: { id: 103 } },
] as any[];
const emailNotifications: { [email: string]: any[] } = {};
const receiverIds: number[] = [];
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
(service as any).collectEmailNotifications(newReceivers, updatedReceivers, emailNotifications, receiverIds, cache);
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('User 1 not found in cache or missing email'));
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('User 3 not found in cache or missing email'));
expect(Object.keys(emailNotifications)).toEqual([]);
expect(receiverIds).toEqual([]);
consoleSpy.mockRestore();
});
});
it('sendDeletionNotifications emits delete events', async () => {
await (service as any).sendDeletionNotifications({ 1: [100, 101] });
expect(emitDeleteNotifications).toHaveBeenCalled();
});
it('sendInAppNotifications emits and marks notified', async () => {
em.update.mockResolvedValue({});
await (service as any).sendInAppNotifications({ 1: [{ id: 10 }, { id: 11 }] }, [10, 11]);
expect(emitNewNotifications).toHaveBeenCalled();
expect(em.update).toHaveBeenCalledWith(
NotificationReceiver,
{ id: In([10, 11]) },
{ isInAppNotified: true },
);
});
describe('sendEmailNotifications', () => {
beforeEach(() => jest.clearAllMocks());
it('calls onSuccess and updates receivers when emit succeeds', async () => {
em.update.mockResolvedValue({});
(emitEmailNotifications as jest.Mock).mockImplementation(async (_pub, _dtos, onSuccess, _onError) => {
await onSuccess();
});
await (service as any).sendEmailNotifications(
{ 'test@example.com': [{ id: 1 } as any] },
[99],
);
expect(em.update).toHaveBeenCalledWith(
NotificationReceiver,
{ id: In([99]) },
{ isEmailSent: true },
);
});
it('calls onError and logs when emit fails (no DB update)', async () => {
em.update.mockResolvedValue({});
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
(emitEmailNotifications as jest.Mock).mockImplementation(async (_pub, _dtos, _onSuccess, onError) => {
await onError(new Error('send-failed'));
});
await (service as any).sendEmailNotifications(
{ 'no-reply@example.com': [{ id: 10 } as any] },
[10],
);
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Failed to send email notifications:'), expect.any(Error));
expect(em.update).not.toHaveBeenCalled();
consoleSpy.mockRestore();
});
});
describe('buildAdditionData', () => {
it('buildAdditionalData includes groupId when present', () => {
const transaction: any = {
transactionId: 'tx-1',
mirrorNetwork: 'net-1',
groupItem: { groupId: 'group-123' },
};
const res = (service as any).buildAdditionalData(transaction);
expect(res).toEqual({
transactionId: 'tx-1',
network: 'net-1',
groupId: 'group-123',
});
});
it('buildAdditionalData omits groupId when missing', () => {
const transaction: any = {
transactionId: 'tx-2',
mirrorNetwork: 'net-2',
groupItem: {}, // or `groupItem: undefined`
};
const res = (service as any).buildAdditionalData(transaction);
expect(res).toEqual({
transactionId: 'tx-2',
network: 'net-2',
});
expect(res).not.toHaveProperty('groupId');
});
it('buildAdditionalData includes isManual and validStart when isManual is true', () => {
const validStart = new Date('2025-01-01T00:00:00.000Z');
const transaction: any = {
transactionId: 'tx-3',
mirrorNetwork: 'net-3',
isManual: true,
validStart,
};
const res = (service as any).buildAdditionalData(transaction);
expect(res).toEqual({
transactionId: 'tx-3',
network: 'net-3',
isManual: true,
validStart,
});
});
it('buildAdditionalData omits isManual and validStart when isManual is falsey', () => {
const transaction: any = {
transactionId: 'tx-4',
mirrorNetwork: 'net-4',
isManual: false,
validStart: new Date('2025-01-01T00:00:00.000Z'),
};
const res = (service as any).buildAdditionalData(transaction);
expect(res).toEqual({
transactionId: 'tx-4',
network: 'net-4',
});
expect(res).not.toHaveProperty('isManual');
expect(res).not.toHaveProperty('validStart');
});
it('buildAdditionalData includes statusCode when it is a number', () => {
const transaction: any = {
transactionId: 'tx-5',
mirrorNetwork: 'net-5',
statusCode: 22,
};
const res = (service as any).buildAdditionalData(transaction);
expect(res).toEqual({
transactionId: 'tx-5',
network: 'net-5',
statusCode: 22,
});
});
it('buildAdditionalData includes statusCode when it is 0', () => {
const transaction: any = {
transactionId: 'tx-6',
mirrorNetwork: 'net-6',
statusCode: 0,
};
const res = (service as any).buildAdditionalData(transaction);
expect(res).toEqual({
transactionId: 'tx-6',
network: 'net-6',
statusCode: 0,
});
});
it('buildAdditionalData omits statusCode when it is null', () => {
const transaction: any = {
transactionId: 'tx-7',
mirrorNetwork: 'net-7',
statusCode: null,
};
const res = (service as any).buildAdditionalData(transaction);
expect(res).toEqual({
transactionId: 'tx-7',
network: 'net-7',
});
expect(res).not.toHaveProperty('statusCode');
});
it('buildAdditionalData omits statusCode when it is undefined', () => {
const transaction: any = {
transactionId: 'tx-8',
mirrorNetwork: 'net-8',
statusCode: undefined,
};
const res = (service as any).buildAdditionalData(transaction);
expect(res).toEqual({
transactionId: 'tx-8',
network: 'net-8',
});
expect(res).not.toHaveProperty('statusCode');
});
it('buildAdditionalData composes groupId + isManual + statusCode together', () => {
const validStart = new Date('2025-02-02T00:00:00.000Z');
const transaction: any = {
transactionId: 'tx-9',
mirrorNetwork: 'net-9',
groupItem: { groupId: 999 },
isManual: true,
validStart,
statusCode: 104,
};
const res = (service as any).buildAdditionalData(transaction);
expect(res).toEqual({
transactionId: 'tx-9',
network: 'net-9',
groupId: 999,
isManual: true,
validStart,
statusCode: 104,
});
});
});
describe('handleTransactionStatusUpdateNotifications', () => {
beforeEach(() => jest.clearAllMocks());
it('processes deletions, creates in-app receivers and collects email receivers', async () => {
const deletionNotifications: { [userId: number]: number[] } = {};
const inAppNotifications: { [userId: number]: any[] } = {};
const inAppReceiverIds: number[] = [];
const emailNotifications: { [email: string]: any[] } = {};
const emailReceiverIds: number[] = [];
const affectedUsers = new Map<number, { transactionIds: Set<number>; groupIds: Set<number> }>();
const transaction = { id: 42, transactionId: 'tx-42', mirrorNetwork: 'net' } as any;
const approvers: any[] = [];
// deleteExistingIndicators returns one deleted receiver
jest.spyOn(service as any, 'deleteExistingIndicators').mockResolvedValue([
{ userId: 1, receiverId: 10 },
]);
// createNotificationWithReceivers: first call for sync (in-app), second call for email
const createdInApp = [{ id: 101, userId: 2 } as any];
const createdEmail = [{ id: 102, userId: 3, notification: { id: 201 } } as any];
const createSpy = jest.spyOn(service as any, 'createNotificationWithReceivers')
.mockImplementationOnce(async () => createdInApp)
.mockImplementationOnce(async () => createdEmail);
const collectEmailSpy = jest.spyOn(service as any, 'collectEmailNotifications').mockImplementation(() => {});
await (service as any).handleTransactionStatusUpdateNotifications(
em as any,
transaction,
approvers,
NotificationType.TRANSACTION_INDICATOR_EXECUTED, // syncType present
NotificationType.TRANSACTION_EXECUTED, // emailType present
new Map(),
new Map(),
deletionNotifications,
inAppNotifications,
inAppReceiverIds,
emailNotifications,
emailReceiverIds,
affectedUsers,
123,
);
// deletedReceiverIds.forEach updated deletionNotifications and affectedUsers
expect((service as any).deleteExistingIndicators).toHaveBeenCalledWith(em as any, transaction);
expect(deletionNotifications[1]).toEqual([10]);
expect(affectedUsers.has(1)).toBe(true);
expect(affectedUsers.get(1)!.transactionIds.has(123)).toBe(true);
// new in-app receivers were added to inAppNotifications and inAppReceiverIds
expect(inAppNotifications[2]).toBeDefined();
expect(inAppNotifications[2].length).toBeGreaterThan(0);
expect(inAppReceiverIds).toContain(101);
// createNotificationWithReceivers called twice (sync + email) and collectEmailNotifications invoked for email receivers
expect(createSpy).toHaveBeenCalledTimes(2);
expect(collectEmailSpy).toHaveBeenCalledWith(createdEmail, [], emailNotifications, emailReceiverIds, expect.any(Map));
});
it('logs an error when internal call throws', async () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
jest.spyOn(service as any, 'deleteExistingIndicators').mockRejectedValue(new Error('boom'));
await (service as any).handleTransactionStatusUpdateNotifications(
em as any,
{ transactionId: 'tx', mirrorNetwork: 'n' } as any,
[],
NotificationType.TRANSACTION_INDICATOR_EXECUTED,
null,
new Map(),
new Map(),
{},
{},
[],
{},
[],
new Map(),
123,
);
expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining('Error processing notifications for transaction 123:'),
expect.any(Error),
);
consoleSpy.mockRestore();
});
});
describe('handleUserRegisteredNotifications', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('returns early when no admin recipients (allReceiverIds.size === 0)', async () => {
// make both preference calls return empty arrays -> early return
jest
.spyOn(service as any, 'filterReceiversByPreferenceForType')
.mockResolvedValueOnce([]) // in-app
.mockResolvedValueOnce([]); // email
// ensure save is not called
if ((em as any).save) (em as any).save.mockClear?.();
const inAppNotifications: { [userId: number]: NotificationReceiver[] } = {};
const emailNotifications: { [email: string]: Notification[] } = {};
const inAppReceiverIds: number[] = [];
const emailReceiverIds: number[] = [];
await (service as any).handleUserRegisteredNotifications(
em as any,
77, // userId
new Set([2, 3]),
{ foo: 'bar' },
new Map(),
inAppNotifications,
emailNotifications,
inAppReceiverIds,
emailReceiverIds,
);
expect((em as any).save).not.toHaveBeenCalled();
expect(Object.keys(inAppNotifications).length).toBe(0);
expect(Object.keys(emailNotifications).length).toBe(0);
expect(inAppReceiverIds).toEqual([]);
expect(emailReceiverIds).toEqual([]);
});
it('creates notification and receivers and collects in-app + email notifications', async () => {
// in-app recipients: [2], email recipients: [3]