forked from medic/cht-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegration.spec.js
More file actions
784 lines (675 loc) · 28 KB
/
integration.spec.js
File metadata and controls
784 lines (675 loc) · 28 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
const chai = require('chai');
const moment = require('moment');
const chaiExclude = require('chai-exclude');
const { MS_IN_DAY, engineSettings, defaultConfigSettingsDoc } = require('./mocks');
const memdownMedic = require('@medic/memdown');
const sinon = require('sinon');
const RulesEngine = require('../src');
const rulesEmitter = require('../src/rules-emitter');
const { expect } = chai;
chai.use(chaiExclude);
let db;
let rulesEngine;
const TEST_START = 1500000000000;
const TARGET_INTERVAL = moment(TEST_START).startOf('month').format('YYYY-MM');
const TASK_ID_PREFIX = (taskId) => `task~org.couchdb.user:username~${taskId}`;
const FACILITY_REMINDER_TASK_ID = 'report~pregnancy-facility-visit-reminder~anc.facility_reminder';
const PREGNANCY_REMINDER_12_TASK_ID = 'pregReg~pregnancy-home-visit-week12~anc.pregnancy_home_visit.known_lmp';
const PREGNANCY_REMINDER_20_TASK_ID = 'pregReg~pregnancy-home-visit-week20~anc.pregnancy_home_visit.known_lmp';
const PREGNANCY_REMINDER_26_TASK_ID = 'pregReg~pregnancy-home-visit-week26~anc.pregnancy_home_visit.known_lmp';
const EXPECTED_TASK_ID_PREFIX = TASK_ID_PREFIX(FACILITY_REMINDER_TASK_ID);
const patientContact = {
_id: 'patient',
name: 'chw',
type: 'contact',
contact_type: 'person',
patient_id: 'patient_id',
};
const pregnancyFollowupReport = {
_id: 'report',
type: 'data_record',
form: 'pregnancy',
fields: {
t_pregnancy_follow_up_date: new Date(TEST_START).toISOString(),
patient_uuid: 'patient'
},
reported_date: 0,
};
const pregnancyRegistrationReport = {
_id: 'pregReg',
type: 'data_record',
form: 'pregnancy',
fields: {
lmp_date_8601: TEST_START,
patient_id: patientContact._id,
},
reported_date: TEST_START,
};
const reportByPatientIdOnly = {
_id: 'report',
type: 'data_record',
form: 'pregnancy',
fields: {
t_pregnancy_follow_up_date: new Date(TEST_START).toISOString(),
},
patient_id: patientContact.patient_id,
reported_date: 0,
};
const expectedQueriesForAllFreshData = [
'medic-client/contacts_by_type',
'medic-client/reports_by_subject',
'medic-offline-tasks/tasks_by_contact'
];
const expectedQueriesForFreshData = [
'medic-client/reports_by_subject',
'medic-offline-tasks/tasks_by_contact',
'medic-offline-tasks/tasks_by_contact',
];
const fetchTargets = async (interval) => {
const targets = await rulesEngine.fetchTargets(interval);
return targets.reduce((agg, target) => {
agg[target.id] = target;
return agg;
}, {});
};
let clock;
describe(`Rules Engine Integration Tests`, () => {
before(async () => {
db = await memdownMedic('../..');
rulesEngine = RulesEngine(db);
await rulesEngine.initialize(engineSettings());
});
after(() => {
rulesEmitter.shutdown();
});
let configHashSalt = 0;
beforeEach(() => {
clock = sinon.useFakeTimers({ now: TEST_START, toFake: ['Date'] });
});
afterEach(() => {
sinon.restore();
clock.restore();
});
describe('rulesAreDeclarative: false', () => {
it('should throw an error when rules are not declarative', async () => {
db = await memdownMedic('../..');
rulesEngine = RulesEngine(db);
configHashSalt++;
const rulesSettings = engineSettings({ rulesAreDeclarative: false, configHashSalt });
await rulesEngine.rulesConfigChange(rulesSettings);
});
});
describe(`rulesAreDeclarative: true`, () => {
beforeEach(async () => {
db = await memdownMedic('../..');
rulesEngine = RulesEngine(db);
configHashSalt++;
const rulesSettings = engineSettings({ rulesAreDeclarative: true, configHashSalt });
await rulesEngine.rulesConfigChange(rulesSettings);
});
it('should refresh emissions for all contacts', async () => {
await db.bulkDocs([patientContact, pregnancyFollowupReport, pregnancyRegistrationReport]);
sinon.spy(db, 'bulkDocs');
sinon.spy(db, 'query');
await rulesEngine.refreshEmissionsFor();
expect(db.bulkDocs.callCount).to.equal(2);
const tasks = db.bulkDocs.args[0][0];
expect(tasks.length).to.equal(4);
const taskReminder12 = tasks.find(task => task.emission._id === PREGNANCY_REMINDER_12_TASK_ID);
expect(taskReminder12).to.deep.include({
_id: `${TASK_ID_PREFIX(PREGNANCY_REMINDER_12_TASK_ID)}~${TEST_START}`,
requester: patientContact._id,
owner: patientContact._id,
state: 'Draft',
});
const taskReminder20 = tasks.find(task => task.emission._id === PREGNANCY_REMINDER_20_TASK_ID);
expect(taskReminder20).to.deep.include({
_id: `${TASK_ID_PREFIX(PREGNANCY_REMINDER_20_TASK_ID)}~${TEST_START}`,
requester: patientContact._id,
owner: patientContact._id,
state: 'Draft',
});
const taskReminder26 = tasks.find(task => task.emission._id === PREGNANCY_REMINDER_26_TASK_ID);
expect(taskReminder26).to.deep.include({
_id: `${TASK_ID_PREFIX(PREGNANCY_REMINDER_26_TASK_ID)}~${TEST_START}`,
requester: patientContact._id,
owner: patientContact._id,
state: 'Draft',
});
const taskFacilityReminder = tasks.find(task => task.emission._id === FACILITY_REMINDER_TASK_ID);
expect(taskFacilityReminder).to.deep.include({
_id: `${TASK_ID_PREFIX(FACILITY_REMINDER_TASK_ID)}~${TEST_START}`,
requester: patientContact._id,
owner: patientContact._id,
state: 'Ready',
});
const targetDoc = db.bulkDocs.args[1][0].docs[0];
expect(targetDoc).to.deep.include({
_id: `target~${TARGET_INTERVAL}~user~org.couchdb.user:username`,
reporting_period: TARGET_INTERVAL,
});
expect(targetDoc.targets).to.deep.include({
id: 'pregnancy-registrations-this-month',
value: { pass: 1, total: 1 },
});
expect(targetDoc.targets).to.deep.include( {
id: 'active-pregnancies',
value: { pass: 1, total: 1 },
},);
expect(targetDoc.targets).to.deep.include( {
id: 'births-this-month',
value: { pass: 0, total: 0 },
});
});
it('unknown contact yields zero tasks and empty targets', async () => {
await db.bulkDocs([patientContact, pregnancyFollowupReport]);
sinon.spy(db, 'query');
expect(await rulesEngine.fetchTasksFor(['abc'])).to.deep.eq([]);
// First call fetches fresh data
expect(db.query.callCount).to.eq(expectedQueriesForFreshData.length);
expect(await rulesEngine.fetchTasksFor(['abc'])).to.deep.eq([]);
// Additional calls only fetch the calculated tasks
expect(db.query.callCount).to.eq(expectedQueriesForFreshData.length + 1);
const targets = await rulesEngine.fetchTargets();
expect(targets.length).to.eq(defaultConfigSettingsDoc.tasks.targets.items.length);
expect(targets.some(t => t.total > 0)).to.be.false;
});
it('fail facility_reminder due to time window', async () => {
// the task is 5 days old when it is discovered
const NOW = moment(TEST_START).add('5', 'days').valueOf();
clock.setSystemTime(NOW);
await triggerFacilityReminderInReadyState(['patient']);
// the task expires four days later, but the contact is not dirty. so no recalculation, just decay
clock.setSystemTime(TEST_START + MS_IN_DAY * 9);
const noTasks = await rulesEngine.fetchTasksFor(['patient']);
expect(db.query.callCount).to.eq(expectedQueriesForFreshData.length + 1);
expect(noTasks).to.have.property('length', 0);
expect(db.bulkDocs.callCount).to.eq(3);
expect(db.bulkDocs.args[1][0].docs.length).to.eq(1);
expect(db.bulkDocs.args[1][0].docs[0]).to.deep.include({
type: 'target',
user: 'org.couchdb.user:username',
owner: 'user',
reporting_period: TARGET_INTERVAL,
});
expect(db.bulkDocs.args[2][0].length).to.eq(1);
expect(db.bulkDocs.args[2][0][0]).to.deep.include({
_id: `task~org.couchdb.user:username~report~pregnancy-facility-visit-reminder~anc.facility_reminder~${NOW}`,
requester: 'patient',
owner: 'patient',
state: 'Failed',
stateHistory: [
{
state: 'Ready',
timestamp: NOW,
},
{
state: 'Failed',
timestamp: Date.now(),
},
]
});
// a month later, no new doc will be created
clock.setSystemTime(TEST_START + MS_IN_DAY * 39);
const monthLater = await rulesEngine.fetchTasksFor(['patient']);
expect(monthLater).to.have.property('length', 0);
expect(db.bulkDocs.callCount).to.eq(4);
const dateNext = moment(TEST_START + MS_IN_DAY * 39).format('YYYY-MM');
expect(db.bulkDocs.args[3][0].docs[0]).to.deep.include({
_id: `target~${dateNext}~user~org.couchdb.user:username`,
type: 'target',
owner: 'user',
reporting_period: dateNext,
});
});
it('fail facility_reminder because of fresh doc merge', async () => {
await triggerFacilityReminderInReadyState(['patient']);
// move forward 9 days, the contact is dirty, the task is recalculated
clock.setSystemTime(TEST_START + MS_IN_DAY * 9);
const noTasks = await rulesEngine.fetchTasksFor(['patient']);
expect(db.query.args.map(args => args[0]))
.to.deep.eq([...expectedQueriesForFreshData, ...expectedQueriesForFreshData]);
expect(noTasks).to.have.property('length', 0);
expect(db.bulkDocs.callCount).to.eq(3);
expect(db.bulkDocs.args[1][0].docs.length).to.eq(1);
expect(db.bulkDocs.args[1][0].docs[0]).to.deep.include({
type: 'target',
user: 'org.couchdb.user:username',
owner: 'user',
});
expect(db.bulkDocs.args[2][0]).to.have.property('length', 1);
expect(db.bulkDocs.args[2][0][0]).to.deep.include({
_id: `${EXPECTED_TASK_ID_PREFIX}~${TEST_START}`,
state: 'Failed',
stateHistory: [
{
state: 'Ready',
timestamp: TEST_START,
},
{
state: 'Failed',
timestamp: Date.now(),
},
]
});
});
it('complete task.anc.facility_reminder', async () => {
await triggerFacilityReminderInReadyState(['patient']);
await db.put({
_id: 'reminder',
type: 'data_record',
form: 'pregnancy_facility_visit_reminder',
fields: [],
patient_id: 'patient',
reported_date: Date.now(),
});
// changes feed marks contact for updates
await rulesEngine.updateEmissionsFor('patient');
expect(db.bulkDocs.callCount).to.eq(4);
// requery via 'tasks tab' interface instead of 'contacts tab' interface
const completedTask = await rulesEngine.fetchTasksFor();
expect(completedTask).to.have.property('length', 0);
expect(db.query.callCount).to.eq(
expectedQueriesForFreshData.length + 2 /* update emissions for*/ +
expectedQueriesForAllFreshData.length + 2 /* tasks */
);
expect(db.bulkDocs.callCount).to.eq(4);
expect(db.bulkDocs.args[3][0]).to.have.property('length', 1);
expect(db.bulkDocs.args[3][0][0]).to.deep.include({
_id: `${EXPECTED_TASK_ID_PREFIX}~${TEST_START}`,
state: 'Completed',
stateHistory: [
{
state: 'Ready',
timestamp: TEST_START,
},
{
state: 'Completed',
timestamp: TEST_START,
},
]
});
await rulesEngine.fetchTargets();
expect(db.query.callCount).to.eq(
expectedQueriesForFreshData.length + 2 /* update emissions for*/ +
expectedQueriesForAllFreshData.length + 2 /* tasks */
);
});
it('cancel facility_reminder due to "purged" report', async () => {
await triggerFacilityReminderInReadyState(['patient']);
const existingPregnancy = await db.get(pregnancyFollowupReport._id);
await db.put({
_id: existingPregnancy._id,
_rev: existingPregnancy._rev,
deleted: true,
});
// changes feed marks contact for updates
await rulesEngine.updateEmissionsFor('patient');
expect(db.bulkDocs.callCount).to.eq(4);
const completedTask = await rulesEngine.fetchTasksFor(['patient']);
expect(completedTask).to.have.property('length', 0);
expect(db.query.callCount).to.eq(expectedQueriesForFreshData.length * 2 + 1);
expect(db.bulkDocs.callCount).to.eq(4);
expect(db.bulkDocs.args[3][0]).to.have.property('length', 1);
const [taskDoc] = db.bulkDocs.args[3][0];
expect(taskDoc).to.deep.include({
_id: `${EXPECTED_TASK_ID_PREFIX}~${TEST_START}`,
state: 'Cancelled',
stateHistory: [
{
state: 'Ready',
timestamp: TEST_START,
},
{
state: 'Cancelled',
timestamp: TEST_START,
},
]
});
// new pregnancy report causes new task
const secondPregnancyReport = Object.assign({}, pregnancyFollowupReport, { _id: 'newPregnancy' });
await db.put(secondPregnancyReport);
await rulesEngine.updateEmissionsFor('patient');
const secondReadyTasks = await rulesEngine.fetchTasksFor(['patient']);
expect(secondReadyTasks).to.have.property('length', 1);
expect(secondReadyTasks[0].state).to.eq('Ready');
expect(secondReadyTasks[0]._id).to.not.eq(taskDoc._id);
});
it('config change causes reload with no cancellations or errors', async () => {
await triggerFacilityReminderInReadyState(['patient']);
const settings = { rulesAreDeclarative: true, rules: 'const nothing = [];' };
const updatedSettings = engineSettings(settings);
await rulesEngine.rulesConfigChange(updatedSettings);
expect(db.bulkDocs.callCount).to.eq(2);
const completedTask = await rulesEngine.fetchTasksFor(['patient']);
expect(completedTask).to.have.property('length', 0);
expect(db.query.callCount).to.eq(expectedQueriesForFreshData.length * 2);
});
it('settings update to invalid config yields no tasks displayed or updated', async () => {
await triggerFacilityReminderInReadyState(['patient']);
try {
const settings = { rules: 'not javascript' };
const updatedSettings = engineSettings(settings);
await rulesEngine.rulesConfigChange(updatedSettings);
expect('throw').to.throw;
} catch (err) {
expect(err.message).to.include('Unexpected identifier');
}
const successfulRecompile = rulesEmitter.isEnabled();
expect(successfulRecompile).to.be.false;
expect(rulesEngine.isEnabled()).to.be.false;
const tasks = await rulesEngine.fetchTasksFor(['patient']);
expect(tasks).to.be.empty;
});
it('reloading same config does not bust cache', async () => {
await triggerFacilityReminderInReadyState(['patient']);
await rulesEngine.rulesConfigChange(engineSettings({ rulesAreDeclarative: true, configHashSalt }));
const successfulRecompile = rulesEmitter.isEnabled();
expect(successfulRecompile).to.be.true;
expect(rulesEngine.isEnabled()).to.be.true;
const readyTasks = await rulesEngine.fetchTasksFor(['patient']);
expect(readyTasks.length).to.eq(1);
expect(db.query.callCount).to.eq(expectedQueriesForFreshData.length + 1);
});
it('purged doc will not be recreated due to isTimely window', async () => {
await db.bulkDocs([patientContact, pregnancyFollowupReport]);
const tasks = await rulesEngine.fetchTasksFor();
expect(tasks).to.have.property('length', 1);
clock.setSystemTime(moment().add(90, 'days').valueOf());
const purgedTask = {
_id: tasks[0]._id,
_rev: tasks[0]._rev,
purged: true,
};
await db.bulkDocs([purgedTask]);
const tasksAfterPurge = await rulesEngine.fetchTasksFor();
expect(tasksAfterPurge).to.have.property('length', 0);
const allTasks = await db.query('medic-offline-tasks/tasks_by_contact');
expect(allTasks.total_rows).to.eq(0);
});
it('mark dirty by subject id (tasks tab scenario)', async () => {
sinon.spy(rulesEmitter, 'getEmissionsFor');
const firstTasks = await triggerFacilityReminderInReadyState(
undefined,
[patientContact, reportByPatientIdOnly],
);
expect(rulesEmitter.getEmissionsFor.callCount).to.eq(1);
expect(rulesEmitter.getEmissionsFor.args[0]).excludingEvery('_rev').to.deep.eq([
[patientContact],
[reportByPatientIdOnly],
[]
]);
await rulesEngine.updateEmissionsFor(reportByPatientIdOnly.patient_id);
const secondTasks = await rulesEngine.fetchTasksFor();
expect(rulesEmitter.getEmissionsFor.callCount).to.eq(3);
expect(rulesEmitter.getEmissionsFor.args[1]).excludingEvery('_rev').to.deep.eq([
[patientContact],
[reportByPatientIdOnly],
firstTasks
]);
expect(secondTasks).to.deep.eq(firstTasks);
expect(db.query.args.map(args => args[0])).to.deep.eq([
...expectedQueriesForAllFreshData,
'medic-offline-tasks/tasks_by_contact',
'medic-client/contacts_by_reference',
...expectedQueriesForFreshData
]);
});
it('mark dirty by subject id (contacts tab scenario)', async () => {
sinon.spy(rulesEmitter, 'getEmissionsFor');
const firstTasks = await triggerFacilityReminderInReadyState(
['patient'],
[patientContact, reportByPatientIdOnly],
);
expect(rulesEmitter.getEmissionsFor.callCount).to.eq(1);
expect(rulesEmitter.getEmissionsFor.args[0]).excludingEvery('_rev').to.deep.eq([
[patientContact],
[reportByPatientIdOnly],
[]
]);
await rulesEngine.updateEmissionsFor(reportByPatientIdOnly.patient_id);
const secondTasks = await rulesEngine.fetchTasksFor([patientContact._id]);
expect(rulesEmitter.getEmissionsFor.callCount).to.eq(3);
expect(rulesEmitter.getEmissionsFor.args[1]).excludingEvery('_rev').to.deep.eq([
[patientContact],
[reportByPatientIdOnly],
firstTasks
]);
expect(secondTasks).to.deep.eq(firstTasks);
expect(db.query.args.map(args => args[0])).to.deep.eq([
...expectedQueriesForFreshData,
'medic-client/contacts_by_reference',
...expectedQueriesForFreshData
]);
});
it('headless scenario (tasks tab)', async () => {
const headlessReport = { _id: 'report', type: 'data_record', form: 'form', patient_id: 'headless' };
const headlessReport2 = { _id: 'report2', type: 'data_record', form: 'form', patient_id: 'headless2' };
const taskOwnedByHeadless = {
_id: 'task', type: 'task', state: 'Ready', owner: 'headless', emission: {
_id: 'emitted', dueDate: Date.now(), startDate: Date.now(), endDate: Date.now(),
}
};
const taskEmittedByHeadless2 = {
_id: 'task2', type: 'task', state: 'Ready', requester: 'headless2', emission: {
_id: 'emitted', dueDate: Date.now(), startDate: Date.now(), endDate: Date.now(),
}
};
await db.bulkDocs([headlessReport, headlessReport2, taskOwnedByHeadless, taskEmittedByHeadless2]);
sinon.spy(db, 'bulkDocs');
sinon.spy(db, 'query');
sinon.spy(rulesEmitter, 'getEmissionsFor');
const firstResult = await rulesEngine.fetchTasksFor();
expect(rulesEmitter.getEmissionsFor.args).excludingEvery(['_rev', 'state', 'stateHistory'])
.to.deep.eq([[[], [headlessReport, headlessReport2], [taskEmittedByHeadless2]]]);
expect(db.query.args.map(args => args[0]))
.to.deep.eq([...expectedQueriesForAllFreshData, 'medic-offline-tasks/tasks_by_contact']);
expect(firstResult).excludingEvery('_rev').to.deep.eq([taskOwnedByHeadless]);
expect(db.bulkDocs.callCount).to.eq(2); // taskEmittedByHeadless2 gets cancelled
await rulesEngine.updateEmissionsFor('headless');
const secondResult = await rulesEngine.fetchTasksFor();
expect(secondResult).to.deep.eq(firstResult);
expect(db.query.args.map(args => args[0]).length).to.deep.eq(
expectedQueriesForAllFreshData.length + 2 /* tasks, updateFor */ +
expectedQueriesForFreshData.length
);
await rulesEngine.fetchTasksFor();
expect(db.query.args.map(args => args[0]).length).to.deep.eq(
expectedQueriesForAllFreshData.length + 2 /* tasks, updateFor */ +
expectedQueriesForFreshData.length + 1 /* tasks */
);
});
it('targets for two pregnancy registrations', async () => {
const patientContact2 = Object.assign({}, patientContact, { _id: 'patient2', patient_id: 'patient_id2', });
const pregnancyRegistrationReport2 = Object.assign(
{},
pregnancyRegistrationReport,
{
_id: 'pregReg2',
fields: {
lmp_date_8601: TEST_START, patient_id: patientContact2.patient_id
}, reported_date: TEST_START+2
}
);
await db.bulkDocs([patientContact, patientContact2, pregnancyRegistrationReport, pregnancyRegistrationReport2]);
sinon.spy(db, 'bulkDocs');
sinon.spy(db, 'query');
const targets = await fetchTargets();
expect(db.query.callCount).to.eq(expectedQueriesForAllFreshData.length);
expect(targets[['pregnancy-registrations-this-month']].value).to.deep.eq({
total: 2,
pass: 2,
});
const sameTargets = await fetchTargets();
expect(db.query.callCount).to.eq(expectedQueriesForAllFreshData.length);
expect(sameTargets).to.deep.eq(targets);
const interval = { start: TEST_START - 1, end: TEST_START + 1 };
const filteredTargets = await fetchTargets(interval);
expect(db.query.callCount).to.eq(expectedQueriesForAllFreshData.length);
expect(filteredTargets['pregnancy-registrations-this-month'].value).to.deep.eq({
total: 1,
pass: 1,
});
});
it('targets for three pregnancy registrations for the same patient', async () => {
const pregnancyRegistrationReport2 = Object.assign(
{},
pregnancyRegistrationReport,
{
_id: '2nd-pregReg',
fields: { lmp_date_8601: TEST_START, patient_id: patientContact._id, },
reported_date: TEST_START + 2
}
);
const pregnancyRegistrationReport3 = Object.assign(
{},
pregnancyRegistrationReport,
{
_id: '3rd-pregReg',
fields: { lmp_date_8601: TEST_START - 3, patient_id: patientContact.patient_id, },
reported_date: TEST_START - 3
}
);
await db.bulkDocs([
patientContact,
pregnancyRegistrationReport,
pregnancyRegistrationReport2,
pregnancyRegistrationReport3,
]);
sinon.spy(db, 'bulkDocs');
sinon.spy(db, 'query');
const targets = await fetchTargets();
expect(db.query.callCount).to.eq(expectedQueriesForAllFreshData.length);
expect(targets[['pregnancy-registrations-this-month']].value).to.deep.eq({
total: 1,
pass: 1,
});
const sameTargets = await fetchTargets();
expect(db.query.callCount).to.eq(expectedQueriesForAllFreshData.length);
expect(sameTargets).to.deep.eq(targets);
// the latest report, 2nd-pregReg is in this interval
let interval = { start: TEST_START + 1, end: TEST_START + 2 };
let filteredTargets = await fetchTargets(interval);
expect(db.query.callCount).to.eq(expectedQueriesForAllFreshData.length);
expect(filteredTargets['pregnancy-registrations-this-month'].value).to.deep.eq({
total: 1,
pass: 1,
});
// pregReg is in this interval
interval = { start: TEST_START - 1, end: TEST_START };
filteredTargets = await fetchTargets(interval);
expect(db.query.callCount).to.eq(expectedQueriesForAllFreshData.length);
expect(filteredTargets['pregnancy-registrations-this-month'].value).to.deep.eq({
total: 0,
pass: 0,
});
// 3rd-pregReg is in this interval
interval = { start: TEST_START - 3, end: TEST_START - 2 };
filteredTargets = await fetchTargets(interval);
expect(db.query.callCount).to.eq(expectedQueriesForAllFreshData.length);
expect(filteredTargets['pregnancy-registrations-this-month'].value).to.deep.eq({
total: 0,
pass: 0,
});
// delete the "latest" report
const report = await db.get('2nd-pregReg');
await db.remove(report);
await rulesEngine.updateEmissionsFor([patientContact._id]);
// the latest report, 2nd-pregReg was in this interval
interval = { start: TEST_START + 1, end: TEST_START + 2 };
filteredTargets = await fetchTargets(interval);
expect(filteredTargets['pregnancy-registrations-this-month'].value).to.deep.eq({
total: 0,
pass: 0,
});
// pregReg is in this interval and is now the latest report
interval = { start: TEST_START - 1, end: TEST_START };
filteredTargets = await fetchTargets(interval);
expect(filteredTargets['pregnancy-registrations-this-month'].value).to.deep.eq({
total: 1,
pass: 1,
});
});
});
describe('showTask', () => {
it('should return true for tasks in Ready state', () => {
const taskDoc = { state: 'Ready' };
expect(rulesEngine.showTask(taskDoc)).to.be.true;
});
it('should return false for tasks in Draft state', () => {
const taskDoc = { state: 'Draft' };
expect(rulesEngine.showTask(taskDoc)).to.be.false;
});
it('should return false for tasks in Completed state', () => {
const taskDoc = { state: 'Completed' };
expect(rulesEngine.showTask(taskDoc)).to.be.false;
});
it('should return false for tasks in Failed state', () => {
const taskDoc = { state: 'Failed' };
expect(rulesEngine.showTask(taskDoc)).to.be.false;
});
it('should return false for tasks in Cancelled state', () => {
const taskDoc = { state: 'Cancelled' };
expect(rulesEngine.showTask(taskDoc)).to.be.false;
});
it('should return false for tasks with no state', () => {
const taskDoc = {};
expect(rulesEngine.showTask(taskDoc)).to.be.false;
});
it('should return false for tasks with undefined state', () => {
const taskDoc = { state: undefined };
expect(rulesEngine.showTask(taskDoc)).to.be.false;
});
});
// interface is not used within cht-core but is used by cht-conf-test-harness
it('custom emitter', async () => {
const expectedEmission = {
_id: 'emitted',
contact: patientContact,
date: new Date().toISOString(),
};
const customEmitter = {
getContact: () => class {
constructor() {
this.reports = [];
}
},
initialize: () => {},
startSession: () => ({
processDocsByContact: () => {},
dispose: () => {},
result: () => Promise.resolve({ tasks: [expectedEmission], targets: [] }),
}),
shutdown: () => {},
};
configHashSalt++;
const rulesSettings = engineSettings({ customEmitter, configHashSalt, rulesAreDeclarative: true });
await db.bulkDocs([patientContact]);
rulesEngine = RulesEngine(db);
await rulesEngine.rulesConfigChange(rulesSettings);
const taskEmissions = await rulesEngine.fetchTasksFor(['patient']);
expect(taskEmissions).to.have.property('length', 1);
expect(taskEmissions[0]).to.include({
_id: `task~org.couchdb.user:username~${expectedEmission._id}~${TEST_START}`,
});
});
});
const triggerFacilityReminderInReadyState = async (selectBy, docs = [patientContact, pregnancyFollowupReport]) => {
await db.bulkDocs(docs);
sinon.spy(db, 'bulkDocs');
sinon.spy(db, 'query');
const tasks = await rulesEngine.fetchTasksFor(selectBy);
expect(tasks).to.have.property('length', 1);
expect(db.query.args.map(args => args[0])).to.deep.eq(
selectBy ? expectedQueriesForFreshData : [...expectedQueriesForAllFreshData, 'medic-offline-tasks/tasks_by_contact']
);
expect(db.bulkDocs.callCount).to.eq(2);
expect(tasks[0]).to.deep.include({
_id: `task~org.couchdb.user:username~report~pregnancy-facility-visit-reminder~anc.facility_reminder~${Date.now()}`,
state: 'Ready',
requester: 'patient',
owner: 'patient',
});
expect(tasks).excluding('_rev').to.deep.eq(db.bulkDocs.args[0][0]);
return tasks;
};