-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcollabReports.test.js
More file actions
1172 lines (986 loc) · 38.7 KB
/
Copy pathcollabReports.test.js
File metadata and controls
1172 lines (986 loc) · 38.7 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
/* eslint-disable max-len */
import faker from '@faker-js/faker';
import { COLLAB_REPORT_PARTICIPANTS, REPORT_STATUSES } from '@ttahub/common';
import { Op } from 'sequelize';
import db, {
CollabReport,
CollabReportActivityState,
CollabReportApprover,
CollabReportDataUsed,
CollabReportReason,
CollabReportSpecialist,
CollabReportStep,
User,
} from '../models';
import {
collabReportById,
collabReportScopes,
createOrUpdateReport,
deleteReport,
getCSVReports,
getReports,
orderCollabReportsBy,
} from './collabReports';
const mockUser = {
id: 1115665161,
homeRegionId: 1,
name: 'user1115665161',
hsesUsername: 'user1115665161',
hsesUserId: 'user1115665161',
lastLogin: new Date(),
};
const mockUserTwo = {
id: 265157914,
homeRegionId: 1,
name: 'user265157914',
hsesUserId: 'user265157914',
hsesUsername: 'user265157914',
lastLogin: new Date(),
};
const mockUserThree = {
id: 39861962,
homeRegionId: 1,
name: 'user39861962',
hsesUserId: 'user39861962',
hsesUsername: 'user39861962',
lastLogin: new Date(),
};
const reportObject = {
name: faker.lorem.words(3),
description: faker.lorem.words(10),
endDate: '2020-09-01T12:00:00Z',
startDate: '2020-09-01T12:00:00Z',
submissionStatus: REPORT_STATUSES.DRAFT,
userId: mockUser.id,
regionId: 1,
lastUpdatedById: mockUser.id,
duration: 1,
conductMethod: 'in_person',
};
describe('Collab Reports Service', () => {
beforeAll(async () => {
// Delete any reports that were previously created
await CollabReport.destroy({ where: { userId: mockUser.id }, force: true });
// Delete any users that were previously created
const userIds = [mockUser.id, mockUserTwo.id, mockUserThree.id];
await User.destroy({ where: { id: userIds } });
// Create users to test with
await Promise.all([
User.create(mockUser),
User.create(mockUserTwo),
User.create(mockUserThree),
]);
});
afterAll(async () => {
const userIds = [mockUser.id, mockUserTwo.id, mockUserThree.id];
// Delete the report we created
const reports = await CollabReport.findAll({
where: {
name: reportObject.name,
description: reportObject.description,
userId: mockUser.id,
},
paranoid: true,
});
const ids = reports.map(({ id }) => id);
await CollabReport.destroy({
where: {
[Op.or]: [{ id: ids }, { userId: userIds }],
},
force: true,
});
// Delete the users we created
await User.destroy({ where: { id: userIds } });
// Close the DB connection
await db.sequelize.close();
});
describe('collabReportById', () => {
it('returns the correct report when given a valid ID', async () => {
// Create a report to test with
await CollabReport.create(reportObject);
// Find the report we created to get its ID
const createdReport = await CollabReport.findOne({ where: { userId: mockUser.id } });
const result = await collabReportById(createdReport.id);
expect(result.name).toEqual(reportObject.name);
});
it('returns null when given an invalid ID', async () => {
expect(await collabReportById(99999999)).toBeNull();
});
});
describe('createOrUpdateReport', () => {
it('creates a new report when given valid data', async () => {
const result = await createOrUpdateReport(reportObject, null);
expect(result.name).toEqual(reportObject.name);
});
it('ignores provided id when creating a new report', async () => {
const existingReport = await CollabReport.create({
...reportObject,
name: `${reportObject.name}-existing`,
});
const result = await createOrUpdateReport(
{
...reportObject,
id: existingReport.id,
name: `${reportObject.name}-new`,
},
null
);
expect(result.id).not.toEqual(existingReport.id);
expect(result.name).toEqual(`${reportObject.name}-new`);
});
it('updates an existing report when given valid data', async () => {
// Create a report to test with
await CollabReport.create(reportObject);
// Find the report we created to get its ID
const createdReport = await CollabReport.findOne({ where: { userId: mockUser.id } });
const updatedReportObject = {
...reportObject,
id: createdReport.id,
name: 'Updated Report Name',
lastUpdatedById: mockUserTwo.id,
};
const result = await createOrUpdateReport(updatedReportObject, createdReport);
expect(result.name).toEqual('Updated Report Name');
expect(result.lastUpdatedById).toEqual(mockUserTwo.id);
});
it('throws an error when trying to update a non-existent report', async () => {
const nonExistentReport = {
...reportObject,
name: 'Non-existent Report',
};
await expect(createOrUpdateReport(reportObject, nonExistentReport)).rejects.toThrow();
});
});
describe('deleteReport', () => {
let testReport;
let testReportWithRelatedData;
beforeEach(async () => {
// Create a basic test report
testReport = await CollabReport.create({
...reportObject,
name: 'Test Report for Deletion',
});
// Create a report with comprehensive related data
testReportWithRelatedData = await CollabReport.create({
...reportObject,
name: 'Test Report with Related Data',
userId: mockUserTwo.id,
lastUpdatedById: mockUserTwo.id,
});
// Add related data similar to seeder structure
await CollabReportSpecialist.create({
collabReportId: testReportWithRelatedData.id,
specialistId: mockUser.id,
});
await CollabReportApprover.create({
collabReportId: testReportWithRelatedData.id,
userId: mockUser.id,
status: 'approved',
note: 'Test approval note',
});
await CollabReportReason.create({
collabReportId: testReportWithRelatedData.id,
reasonId: 'participate_work_groups',
});
});
afterEach(async () => {
// Clean up test data
if (testReport) {
await testReport.destroy({ force: true });
}
if (testReportWithRelatedData) {
await testReportWithRelatedData.destroy({ force: true });
}
// Clean up related data
const reportIds = [testReport?.id, testReportWithRelatedData?.id].filter(Boolean);
await CollabReportSpecialist.destroy({
where: { collabReportId: reportIds },
force: true,
});
await CollabReportApprover.destroy({
where: { collabReportId: reportIds },
force: true,
});
await CollabReportReason.destroy({
where: { collabReportId: reportIds },
force: true,
});
});
it('successfully deletes a report with minimal data', async () => {
expect(testReport).toBeTruthy();
await deleteReport(testReport);
// Verify report is soft-deleted (should not be found in normal query)
const deletedReport = await CollabReport.findByPk(testReport.id);
expect(deletedReport).toBeNull();
// Verify report still exists with paranoid: false (soft delete)
const softDeletedReport = await CollabReport.findByPk(testReport.id, { paranoid: false });
expect(softDeletedReport).toBeTruthy();
expect(softDeletedReport.deletedAt).toBeTruthy();
});
it('successfully deletes a report with comprehensive related data', async () => {
expect(testReportWithRelatedData).toBeTruthy();
// Verify related data exists before deletion
const specialists = await CollabReportSpecialist.findAll({
where: { collabReportId: testReportWithRelatedData.id },
});
const approvers = await CollabReportApprover.findAll({
where: { collabReportId: testReportWithRelatedData.id },
});
const reasons = await CollabReportReason.findAll({
where: { collabReportId: testReportWithRelatedData.id },
});
expect(specialists).toHaveLength(1);
expect(approvers).toHaveLength(1);
expect(reasons).toHaveLength(1);
// Delete the report
await expect(deleteReport(testReportWithRelatedData)).resolves.not.toThrow();
// Verify report is soft-deleted
const deletedReport = await CollabReport.findByPk(testReportWithRelatedData.id);
expect(deletedReport).toBeNull();
// Verify report still exists with paranoid: false
const softDeleted = await CollabReport.findByPk(testReportWithRelatedData.id, {
paranoid: false,
});
expect(softDeleted).toBeTruthy();
expect(softDeleted.deletedAt).toBeTruthy();
// Verify related data is preserved (not cascaded)
const specialistsAfter = await CollabReportSpecialist.findAll({
where: { collabReportId: testReportWithRelatedData.id },
});
const approversAfter = await CollabReportApprover.findAll({
where: { collabReportId: testReportWithRelatedData.id },
});
const reasonsAfter = await CollabReportReason.findAll({
where: { collabReportId: testReportWithRelatedData.id },
});
expect(specialistsAfter).toHaveLength(1);
expect(approversAfter).toHaveLength(1);
expect(reasonsAfter).toHaveLength(1);
});
it('handles deletion of already deleted report', async () => {
// Delete the report first
await deleteReport(testReport);
// Verify it's deleted
const deletedReport = await CollabReport.findByPk(testReport.id);
expect(deletedReport).toBeNull();
// Get the soft-deleted report to test deleting it again
const softDeletedReport = await CollabReport.findByPk(testReport.id, { paranoid: false });
// Attempting to delete already deleted report should not throw
await expect(deleteReport(softDeletedReport)).resolves.not.toThrow();
});
it('throws error when trying to delete null or invalid report', async () => {
await expect(deleteReport(null)).rejects.toThrow();
await expect(deleteReport(undefined)).rejects.toThrow();
await expect(deleteReport({})).rejects.toThrow();
});
});
describe('orderCollabReportsBy', () => {
it('returns correct order for Activity_name ascending', () => {
const result = orderCollabReportsBy('Activity_name', 'asc');
expect(result).toEqual([['name', 'asc']]);
});
it('returns correct order for Activity_name descending', () => {
const result = orderCollabReportsBy('Activity_name', 'desc');
expect(result).toEqual([['name', 'desc']]);
});
it('returns correct order for Report_ID', () => {
const result = orderCollabReportsBy('Report_ID', 'asc');
expect(result).toEqual([['id', 'asc']]);
});
it('returns correct order for Date_started', () => {
const result = orderCollabReportsBy('Date_started', 'desc');
expect(result).toEqual([['startDate', 'desc']]);
});
it('returns correct order for Created_date', () => {
const result = orderCollabReportsBy('Created_date', 'asc');
expect(result).toEqual([['createdAt', 'asc']]);
});
it('returns correct order for Last_saved', () => {
const result = orderCollabReportsBy('Last_saved', 'desc');
expect(result).toEqual([['updatedAt', 'desc']]);
});
it('returns literal for Creator sort', () => {
const result = orderCollabReportsBy('Creator', 'asc');
expect(result).toHaveLength(1);
expect(result[0]).toHaveLength(2);
expect(result[0][1]).toBe('asc');
// Check that it's a Sequelize literal
expect(result[0][0]).toHaveProperty('val');
});
it('returns literal for Collaborators sort', () => {
const result = orderCollabReportsBy('Collaborators', 'desc');
expect(result).toHaveLength(1);
expect(result[0]).toHaveLength(2);
expect(result[0][1]).toBe('desc');
// Check that it's a Sequelize literal
expect(result[0][0]).toHaveProperty('val');
});
it('defaults to updatedAt for unknown sort key', () => {
const result = orderCollabReportsBy('UnknownField', 'asc');
expect(result).toEqual([['updatedAt', 'asc']]);
});
it('handles null or undefined sortBy', () => {
const result1 = orderCollabReportsBy(null, 'desc');
expect(result1).toEqual([['updatedAt', 'desc']]);
const result2 = orderCollabReportsBy(undefined, 'asc');
expect(result2).toEqual([['updatedAt', 'asc']]);
});
});
describe('collabReportScopes', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('returns standard scopes with calculatedStatus', async () => {
const result = await collabReportScopes({}, null, 'approved');
expect(result).toEqual({
customScopes: [],
standardScopes: {
calculatedStatus: 'approved',
},
});
});
it('adds userId filter when userId is provided', async () => {
const result = await collabReportScopes({}, 123, 'draft');
expect(result.standardScopes).toHaveProperty([Op.or]);
expect(result.standardScopes[Op.or]).toHaveLength(3);
expect(result.standardScopes[Op.or][0]).toEqual({ userId: 123 });
});
it('includes specialist subquery when userId is provided', async () => {
const result = await collabReportScopes({}, 456, 'submitted');
const orConditions = result.standardScopes[Op.or];
expect(orConditions[1]).toHaveProperty('id');
expect(orConditions[1].id).toHaveProperty([Op.in]);
// Check that it contains the user ID in the literal
expect(orConditions[1].id[Op.in].val).toContain('456');
});
it('includes approver subquery when userId is provided', async () => {
const result = await collabReportScopes({}, 789, 'approved');
const orConditions = result.standardScopes[Op.or];
expect(orConditions[2]).toHaveProperty('id');
expect(orConditions[2].id).toHaveProperty([Op.in]);
// Check that it contains the user ID in the literal
expect(orConditions[2].id[Op.in].val).toContain('789');
});
it('does not add userId filter when userId is null', async () => {
const result = await collabReportScopes({ region: [1, 2] }, null, 'needs_action');
expect(result).toEqual({
customScopes: [],
standardScopes: {
calculatedStatus: 'needs_action',
},
});
expect(result.standardScopes).not.toHaveProperty([Op.or]);
});
});
describe('getCSVReports', () => {
let csvReportIds = [];
beforeAll(async () => {
const [report1, report2] = await Promise.all([
CollabReport.create({
...reportObject,
name: 'CSV export test report 1',
calculatedStatus: REPORT_STATUSES.APPROVED,
}),
CollabReport.create({
...reportObject,
name: 'CSV export test report 2',
calculatedStatus: REPORT_STATUSES.APPROVED,
}),
]);
await CollabReportSpecialist.create({
collabReportId: report1.id,
specialistId: mockUserTwo.id,
});
await CollabReportApprover.create({
collabReportId: report1.id,
userId: mockUserTwo.id,
status: 'approved',
note: 'Test approval',
});
csvReportIds = [report1.id, report2.id];
});
afterAll(async () => {
await CollabReportSpecialist.destroy({
where: { collabReportId: csvReportIds },
force: true,
});
await CollabReportApprover.destroy({ where: { collabReportId: csvReportIds }, force: true });
await CollabReport.destroy({ where: { id: csvReportIds }, force: true });
});
it('returns all reports when no filters are provided', async () => {
const result = await getCSVReports({ 'id.in': csvReportIds });
expect(Array.isArray(result)).toBe(true);
expect(result.map(({ id }) => id)).toEqual(expect.arrayContaining(csvReportIds));
});
it('includes all required attributes for CSV export', async () => {
const result = await getCSVReports({ 'id.in': csvReportIds, limit: '1' });
expect(result.length).toBe(1);
const report = result[0];
expect(report).toHaveProperty('name');
expect(report).toHaveProperty('description');
expect(report).toHaveProperty('startDate');
expect(report).toHaveProperty('endDate');
expect(report).toHaveProperty('author');
expect(report).toHaveProperty('collaboratingSpecialists');
expect(report).toHaveProperty('approvers');
expect(report.get('status')).toBeTruthy();
});
it('includes author information with roles', async () => {
const result = await getCSVReports({ 'id.in': csvReportIds, limit: '1' });
const report = result[0];
expect(report.author).toHaveProperty('fullName');
expect(report.author).toHaveProperty('name');
expect(report.author).toHaveProperty('roles');
expect(Array.isArray(report.author.roles)).toBe(true);
});
it('includes collaborating specialists with roles', async () => {
const result = await getCSVReports({ 'id.in': csvReportIds });
const reportWithSpecialists = result.find(
(r) => r.collaboratingSpecialists && r.collaboratingSpecialists.length > 0
);
expect(reportWithSpecialists).toBeTruthy();
expect(Array.isArray(reportWithSpecialists.collaboratingSpecialists)).toBe(true);
const specialist = reportWithSpecialists.collaboratingSpecialists[0];
expect(specialist).toHaveProperty('id');
expect(specialist).toHaveProperty('name');
expect(specialist).toHaveProperty('fullName');
expect(specialist).toHaveProperty('roles');
expect(Array.isArray(specialist.roles)).toBe(true);
});
it('includes approvers with user information', async () => {
const result = await getCSVReports({ 'id.in': csvReportIds });
const reportWithApprovers = result.find((r) => r.approvers && r.approvers.length > 0);
expect(reportWithApprovers).toBeTruthy();
expect(Array.isArray(reportWithApprovers.approvers)).toBe(true);
const approver = reportWithApprovers.approvers[0];
expect(approver).toHaveProperty('id');
expect(approver).toHaveProperty('status');
expect(approver).toHaveProperty('note');
expect(approver).toHaveProperty('user');
expect(approver.user).toHaveProperty('id');
expect(approver.user).toHaveProperty('name');
expect(approver.user).toHaveProperty('fullName');
});
it('respects limit parameter', async () => {
const result = await getCSVReports({ 'id.in': csvReportIds, limit: '1' });
expect(result).toHaveLength(1);
});
it('handles "all" limit parameter', async () => {
const result = await getCSVReports({ 'id.in': csvReportIds, limit: 'all' });
expect(Array.isArray(result)).toBe(true);
expect(result.map(({ id }) => id)).toEqual(expect.arrayContaining(csvReportIds));
});
it('respects sortBy and sortDir parameters', async () => {
const resultAsc = await getCSVReports({
'id.in': csvReportIds,
sortBy: 'Activity_name',
sortDir: 'asc',
});
const resultDesc = await getCSVReports({
'id.in': csvReportIds,
sortBy: 'Activity_name',
sortDir: 'desc',
});
expect(resultAsc).toHaveLength(2);
expect(resultDesc).toHaveLength(2);
// Names should be in opposite order
expect(resultAsc[0].name).not.toBe(resultDesc[0].name);
});
it('includes steps data when available', async () => {
const result = await getCSVReports({ 'id.in': csvReportIds });
result.forEach((report) => {
expect(report).toHaveProperty('steps');
expect(Array.isArray(report.steps)).toBe(true);
});
});
it('uses default parameters when none provided, returning all matching records', async () => {
const result = await getCSVReports({ 'id.in': csvReportIds });
expect(Array.isArray(result)).toBe(true);
expect(result.map(({ id }) => id)).toEqual(expect.arrayContaining(csvReportIds));
});
});
describe('createOrUpdateReport with steps, dataUsed, and statesInvolved', () => {
let testReport;
afterEach(async () => {
if (testReport) {
// Clean up related data
await CollabReportStep.destroy({
where: { collabReportId: testReport.id },
force: true,
});
await CollabReportDataUsed.destroy({
where: { collabReportId: testReport.id },
force: true,
});
await CollabReportActivityState.destroy({
where: { collabReportId: testReport.id },
force: true,
});
await testReport.destroy({ force: true });
testReport = null;
}
});
describe('steps functionality', () => {
it('creates new steps when creating a report', async () => {
const reportWithSteps = {
...reportObject,
name: 'Test Report with Steps',
steps: [
{
collabStepDetail: 'First step completed',
collabStepCompleteDate: '2020-09-01',
toJSON() {
return {
collabStepDetail: 'First step completed',
collabStepCompleteDate: '2020-09-01',
};
},
},
{
collabStepDetail: 'Second step completed',
collabStepCompleteDate: '2020-09-02',
toJSON() {
return {
collabStepDetail: 'Second step completed',
collabStepCompleteDate: '2020-09-02',
};
},
},
],
};
const result = await createOrUpdateReport(reportWithSteps, null);
testReport = await CollabReport.findByPk(result.id);
const steps = await CollabReportStep.findAll({
where: { collabReportId: result.id },
order: [['collabStepDetail', 'ASC']],
});
expect(steps).toHaveLength(2);
expect(steps[0].collabStepDetail).toBe('First step completed');
expect(steps[1].collabStepDetail).toBe('Second step completed');
});
it('saves steps when the completion date is missing', async () => {
const reportWithSteps = {
...reportObject,
name: 'Test Report with Step Missing Date',
steps: [
{
collabStepDetail: 'Step without date',
collabStepCompleteDate: null,
toJSON() {
return { collabStepDetail: 'Step without date', collabStepCompleteDate: null };
},
},
],
};
const result = await createOrUpdateReport(reportWithSteps, null);
testReport = await CollabReport.findByPk(result.id);
const steps = await CollabReportStep.findAll({
where: { collabReportId: result.id },
});
expect(steps).toHaveLength(1);
expect(steps[0].collabStepDetail).toBe('Step without date');
expect(steps[0].collabStepCompleteDate).toBeNull();
});
it('updates existing steps when updating a report', async () => {
// Create initial report with steps
const initialReport = {
...reportObject,
name: 'Test Report for Step Updates',
steps: [
{
collabStepDetail: 'Original step',
collabStepCompleteDate: '2020-09-01',
toJSON() {
return { collabStepDetail: 'Original step', collabStepCompleteDate: '2020-09-01' };
},
},
],
};
const created = await createOrUpdateReport(initialReport, null);
testReport = await CollabReport.findByPk(created.id);
// Update with new steps
const updatedReport = {
...initialReport,
steps: [
{
collabStepDetail: 'Updated step',
collabStepCompleteDate: '2020-09-01',
toJSON() {
return {
collabStepDetail: this.collabStepDetail,
collabStepCompleteDate: this.collabStepCompleteDate,
};
},
},
{
collabStepDetail: 'New step',
collabStepCompleteDate: '2020-09-02',
toJSON() {
return {
collabStepDetail: this.collabStepDetail,
collabStepCompleteDate: this.collabStepCompleteDate,
};
},
},
],
};
await createOrUpdateReport(updatedReport, testReport);
const steps = await CollabReportStep.findAll({
where: { collabReportId: created.id },
order: [['collabStepDetail', 'ASC']],
});
expect(steps).toHaveLength(2);
expect(steps[0].collabStepDetail).toBe('New step');
expect(steps[1].collabStepDetail).toBe('Updated step');
});
it('removes steps when they are no longer included', async () => {
// Create initial report with steps
const initialReport = {
...reportObject,
name: 'Test Report for Step Removal',
steps: [
{
collabStepDetail: 'Step to keep',
collabStepCompleteDate: '2020-09-01',
toJSON() {
return {
collabStepDetail: this.collabStepDetail,
collabStepCompleteDate: this.collabStepCompleteDate,
};
},
},
{
collabStepDetail: 'Step to remove',
collabStepCompleteDate: '2020-09-02',
toJSON() {
return {
collabStepDetail: this.collabStepDetail,
collabStepCompleteDate: this.collabStepCompleteDate,
};
},
},
],
};
const created = await createOrUpdateReport(initialReport, null);
testReport = await CollabReport.findByPk(created.id);
// Update with fewer steps
const updatedReport = {
...initialReport,
steps: [
{
collabStepDetail: 'Step to keep',
collabStepCompleteDate: '2020-09-01',
toJSON() {
return {
collabStepDetail: this.collabStepDetail,
collabStepCompleteDate: this.collabStepCompleteDate,
};
},
},
],
};
await createOrUpdateReport(updatedReport, testReport);
const steps = await CollabReportStep.findAll({
where: { collabReportId: created.id },
});
expect(steps).toHaveLength(1);
expect(steps[0].collabStepDetail).toBe('Step to keep');
});
it('removes all steps when steps array is empty', async () => {
// Create initial report with steps
const initialReport = {
...reportObject,
name: 'Test Report for All Steps Removal',
steps: [
{
collabStepDetail: 'Step to remove',
collabStepCompleteDate: '2020-09-01',
toJSON() {
return {
collabStepDetail: this.collabStepDetail,
collabStepCompleteDate: this.collabStepCompleteDate,
};
},
},
],
};
const created = await createOrUpdateReport(initialReport, null);
testReport = await CollabReport.findByPk(created.id);
// Update with empty steps
const updatedReport = {
...initialReport,
steps: [],
};
await createOrUpdateReport(updatedReport, testReport);
const steps = await CollabReportStep.findAll({
where: { collabReportId: created.id },
});
expect(steps).toHaveLength(0);
});
});
describe('dataUsed functionality', () => {
it('creates new data used entries when creating a report', async () => {
const reportWithDataUsed = {
...reportObject,
name: 'Test Report with Data Used',
dataUsed: [
{
collabReportDatum: 'census_data',
},
{
collabReportDatum: 'other',
},
],
otherDataUsed: 'Custom data source',
};
const result = await createOrUpdateReport(reportWithDataUsed, null);
testReport = await CollabReport.findByPk(result.id);
const dataUsed = await CollabReportDataUsed.findAll({
where: { collabReportId: result.id },
});
expect(dataUsed).toHaveLength(2);
expect(dataUsed.find((d) => d.collabReportDatum === 'census_data')).toBeTruthy();
expect(dataUsed.find((d) => d.collabReportDatum === 'other')).toBeTruthy();
});
it('handles data used as simple strings', async () => {
const reportWithDataUsed = {
...reportObject,
name: 'Test Report with Simple Data Used',
dataUsed: ['census_data', 'pir'],
};
const result = await createOrUpdateReport(reportWithDataUsed, null);
testReport = await CollabReport.findByPk(result.id);
const dataUsed = await CollabReportDataUsed.findAll({
where: { collabReportId: result.id },
});
expect(dataUsed).toHaveLength(2);
expect(dataUsed.find((d) => d.collabReportDatum === 'census_data')).toBeTruthy();
expect(dataUsed.find((d) => d.collabReportDatum === 'pir')).toBeTruthy();
});
it('updates data used entries when updating a report', async () => {
// Create initial report
const initialReport = {
...reportObject,
name: 'Test Report for Data Used Updates',
dataUsed: [{ collabReportDatum: 'census_data' }],
};
const created = await createOrUpdateReport(initialReport, null);
testReport = await CollabReport.findByPk(created.id);
// Update with new data used
const updatedReport = {
...initialReport,
dataUsed: [{ collabReportDatum: 'pir' }, { collabReportDatum: 'other' }],
};
await createOrUpdateReport(updatedReport, testReport);
const dataUsed = await CollabReportDataUsed.findAll({
where: { collabReportId: created.id },
});
expect(dataUsed).toHaveLength(2);
expect(dataUsed.find((d) => d.collabReportDatum === 'census_data')).toBeFalsy();
expect(dataUsed.find((d) => d.collabReportDatum === 'pir')).toBeTruthy();
expect(dataUsed.find((d) => d.collabReportDatum === 'other')).toBeTruthy();
});
it('removes all data used when array is empty', async () => {
// Create initial report
const initialReport = {
...reportObject,
name: 'Test Report for Data Used Removal',
dataUsed: [{ collabReportDatum: 'census_data' }],
};
const created = await createOrUpdateReport(initialReport, null);
testReport = await CollabReport.findByPk(created.id);
// Update with empty data used
const updatedReport = {
...initialReport,
dataUsed: [],
};
await createOrUpdateReport(updatedReport, testReport);
const dataUsed = await CollabReportDataUsed.findAll({
where: { collabReportId: created.id },
});
expect(dataUsed).toHaveLength(0);
});
});
describe('statesInvolved functionality', () => {
it('creates new states involved when creating a report', async () => {
const reportWithStatesInvolved = {
...reportObject,
name: 'Test Report with States Involved',
statesInvolved: ['CA', 'NY'],
};
const result = await createOrUpdateReport(reportWithStatesInvolved, null);
testReport = await CollabReport.findByPk(result.id);
const statesInvolvedRecords = await CollabReportActivityState.findAll({
where: { collabReportId: result.id },
});
expect(statesInvolvedRecords).toHaveLength(2);
expect(statesInvolvedRecords.find((s) => s.activityStateCode === 'CA')).toBeTruthy();
expect(statesInvolvedRecords.find((s) => s.activityStateCode === 'NY')).toBeTruthy();
});
it('handles states involved as simple strings', async () => {
const reportWithStatesInvolved = {
...reportObject,
name: 'Test Report with Simple States Involved',
statesInvolved: ['TX', 'FL'],
};
const result = await createOrUpdateReport(reportWithStatesInvolved, null);
testReport = await CollabReport.findByPk(result.id);
const statesInvolvedRecords = await CollabReportActivityState.findAll({
where: { collabReportId: result.id },
});
expect(statesInvolvedRecords).toHaveLength(2);
expect(statesInvolvedRecords.find((s) => s.activityStateCode === 'TX')).toBeTruthy();
expect(statesInvolvedRecords.find((s) => s.activityStateCode === 'FL')).toBeTruthy();
});
it('updates states involved when updating a report', async () => {
// Create initial report
const initialReport = {
...reportObject,
name: 'Test Report for States Involved Updates',
statesInvolved: ['CA'],
};
const created = await createOrUpdateReport(initialReport, null);
testReport = await CollabReport.findByPk(created.id);