/
JobTest.php
2539 lines (2401 loc) · 96.7 KB
/
JobTest.php
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
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* File for the CiviCRM APIv3 job functions
*
* @package CiviCRM_APIv3
* @subpackage API_Job
*
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
use Civi\Api4\Contact;
/**
* Class api_v3_JobTest
*
* @group headless
*/
class api_v3_JobTest extends CiviUnitTestCase {
/**
* Entities to return to their original values during tearDown.
*
* The array is keyed by EntityName.
*
* @var array
*/
private $originalValues = [];
/**
* Make sure triggers are rebuilt even if test fails. We don't need to do it
* for every test, so use this to signal tearDown.
* @var bool
*/
private $rebuildTriggers = FALSE;
/**
* Set up for tests.
*/
public function setUp(): void {
parent::setUp();
$this->_params = [
'sequential' => 1,
'name' => 'API_Test_Job',
'description' => 'A long description written by hand in cursive',
'run_frequency' => 'Daily',
'api_entity' => 'ApiTestEntity',
'api_action' => 'api_test_action',
'parameters' => 'Semi-formal explanation of runtime job parameters',
'is_active' => 1,
];
}
/**
* Cleanup after test.
*/
public function tearDown(): void {
$this->resetHooks();
if ($this->rebuildTriggers) {
\Civi::service('sql_triggers')->rebuild();
// not sure if this is necessary but clear it to be sure
CRM_Core_DAO::executeQuery('SET @CIVICRM_MERGE=NULL');
$this->rebuildTriggers = FALSE;
}
$this->quickCleanUpFinancialEntities();
$this->quickCleanup(['civicrm_contact', 'civicrm_address', 'civicrm_email', 'civicrm_relationship', 'civicrm_website', 'civicrm_phone', 'civicrm_job', 'civicrm_action_log', 'civicrm_action_schedule', 'civicrm_group', 'civicrm_group_contact'], TRUE);
foreach ($this->originalValues as $entity => $entities) {
foreach ($entities as $values) {
$this->callAPISuccess($entity, 'create', $values);
}
}
parent::tearDown();
}
/**
* Create job with an invalid "run_frequency" value.
*/
public function testCreateWithInvalidFrequency(): void {
$this->callAPIFailure('job', 'create', [
'sequential' => 1,
'name' => 'API_Test_Job',
'description' => 'A long description written by hand in cursive',
'run_frequency' => 'Fortnightly',
'api_entity' => 'ApiTestEntity',
'api_action' => 'api_test_action',
'parameters' => 'Semi-formal explanation of runtime job parameters',
'is_active' => 1,
]);
}
/**
* Create job.
*/
public function testCreate(): void {
$result = $this->callAPISuccess('Job', 'create', $this->_params);
$this->getAndCheck($this->_params, $result['id'], 'Job');
}
/**
* Clone job.
*/
public function testClone(): void {
$createResult = $this->callAPISuccess('Job', 'create', $this->_params);
$params = ['id' => $createResult['id']];
$cloneResult = $this->callAPISuccess('Job', 'clone', $params);
$clonedJob = $cloneResult['values'][$cloneResult['id']];
$this->assertEquals($this->_params['name'] . ' - Copy', $clonedJob['name']);
$this->assertEquals($this->_params['description'], $clonedJob['description']);
$this->assertEquals($this->_params['parameters'], $clonedJob['parameters']);
$this->assertEquals($this->_params['is_active'], $clonedJob['is_active']);
$this->assertArrayNotHasKey('last_run', $clonedJob);
$this->assertArrayNotHasKey('scheduled_run_date', $clonedJob);
}
/**
* Check job delete.
*/
public function testDelete(): void {
$createResult = $this->callAPISuccess('Job', 'create', $this->_params);
$params = ['id' => $createResult['id']];
$this->callAPISuccess('Job', 'delete', $params);
$this->assertAPIDeleted('Job', $createResult['id']);
}
/**
* Test processing strings with boolean's in them.
*
* e.g {if {contact.first_name|boolean}
*
* @dataProvider dataProviderNamesAndGreetings
* @throws \CRM_Core_Exception
*/
public function testUpdateGreetingBooleanToken($params, $expectedEmailGreeting): void {
$this->setEmailGreetingTemplateToConditional();
$contactID = $this->individualCreate($params);
$this->assertEquals($expectedEmailGreeting, Contact::get()->addSelect('email_greeting_display')->addWhere('id', '=', $contactID)->execute()->first()['email_greeting_display']);
}
/**
* Data provider for testing email greeting template.
*/
public function dataProviderNamesAndGreetings(): array {
return [
[
'params' => ['first_name' => 'Anthony'],
'expected' => 'Dear Anthony',
],
[
'params' => ['first_name' => ''],
'expected' => 'Dear Friend',
],
[
// This isn't really an issue with the |boolean provider
// but it would be without it - https://lab.civicrm.org/dev/core/-/issues/3962
'params' => ['first_name' => "O'Shea"],
'expected' => "Dear O'Shea",
],
];
}
/**
* Set the Individual email template to use {if {contact.first_name|boolean}.
*/
protected function setEmailGreetingTemplateToConditional(): void {
$this->originalValues['OptionValue']['email'] = reset($this->callAPISuccess('OptionValue', 'get', [
'option_group_id' => 'email_greeting',
'is_default' => TRUE,
'filter' => 1,
])['values']);
$this->callAPISuccess('OptionValue', 'create', [
'id' => $this->originalValues['OptionValue']['email']['id'],
'label' => '{if {contact.first_name|boolean}}Dear {contact.first_name}{else}Dear Friend{/if}',
]);
}
/**
* Test greeting update job.
*
* Note that this test is about testing the metadata / calling of the
* function & doesn't test the success of the called function
*
* @throws \CRM_Core_Exception
*/
public function testCallUpdateGreetingSuccess(): void {
$contactID = $this->individualCreate();
// Clear out the postal greeting
CRM_Core_DAO::executeQuery('UPDATE civicrm_contact SET postal_greeting_display = NULL WHERE id = ' . $contactID);
$this->callAPISuccess('Job', 'update_greeting', [
'gt' => 'postal_greeting',
'ct' => 'Individual',
]);
$this->assertEquals('Dear Anthony', Contact::get()
->addWhere('id', '=', $contactID)
->addSelect('postal_greeting_display')
->execute()->first()['postal_greeting_display']
);
}
/**
* Test greeting update handles comma separated params.
*/
public function testCallUpdateGreetingCommaSeparatedParamsSuccess(): void {
$gt = 'postal_greeting,email_greeting,addressee';
$ct = 'Individual,Household';
$this->callAPISuccess('Job', 'update_greeting', ['gt' => $gt, 'ct' => $ct]);
}
/**
* Test the call reminder success sends more than 25 reminders & is not
* incorrectly limited.
*
* Note that this particular test sends the reminders to the additional
* recipients only as no real reminder person is configured
*
* Also note that this is testing a 'job' api so is in this class rather than
* scheduled_reminder - which seems a cleaner place to build up a collection
* of scheduled reminder testing functions. However, it seems that the api
* itself would need to be moved to the scheduled_reminder fn to do that
* with the job wrapper being respected for legacy functions
*/
public function testCallSendReminderSuccessMoreThanDefaultLimit(): void {
$membershipTypeID = $this->membershipTypeCreate();
$this->membershipStatusCreate();
$createTotal = 30;
for ($i = 1; $i <= $createTotal; $i++) {
$contactID = $this->individualCreate();
$groupID = $this->groupCreate(['name' => $i, 'title' => $i]);
$this->callAPISuccess('action_schedule', 'create', [
'title' => " job $i",
'subject' => "job $i",
'entity_value' => $membershipTypeID,
'mapping_id' => 4,
'start_action_date' => 'membership_join_date',
'start_action_offset' => 0,
'start_action_condition' => 'before',
'start_action_unit' => 'hour',
'group_id' => $groupID,
'limit_to' => 2,
]);
$this->callAPISuccess('group_contact', 'create', [
'contact_id' => $contactID,
'status' => 'Added',
'group_id' => $groupID,
]);
}
$this->callAPISuccess('job', 'send_reminder', []);
$successfulCronCount = CRM_Core_DAO::singleValueQuery('SELECT count(*) FROM civicrm_action_log');
$this->assertEquals($successfulCronCount, $createTotal);
}
/**
* Test scheduled reminders respect limit to (since above identified addition_to handling issue).
*
* We create 3 contacts - 1 is in our group, 1 has our membership & the chosen one has both
* & check that only the chosen one got the reminder
*
* @throws \CRM_Core_Exception
*/
public function testCallSendReminderLimitToSMS(): void {
[$membershipTypeID, $groupID, $theChosenOneID, $provider] = $this->setUpMembershipSMSReminders();
$this->callAPISuccess('action_schedule', 'create', [
'title' => ' remind all Texans',
'subject' => 'drawling renewal',
'entity_value' => $membershipTypeID,
'mapping_id' => 4,
'start_action_date' => 'membership_start_date',
'start_action_offset' => 1,
'start_action_condition' => 'before',
'start_action_unit' => 'day',
'group_id' => $groupID,
'limit_to' => 1,
'sms_provider_id' => $provider['id'],
'mode' => 'User_Preference',
]);
$this->callAPISuccess('job', 'send_reminder', []);
$successfulCronCount = CRM_Core_DAO::singleValueQuery('SELECT count(*) FROM civicrm_action_log');
$this->assertEquals(1, $successfulCronCount);
$sentToID = CRM_Core_DAO::singleValueQuery('SELECT contact_id FROM civicrm_action_log');
$this->assertEquals($sentToID, $theChosenOneID);
$this->assertEquals(0, CRM_Core_DAO::singleValueQuery('SELECT is_error FROM civicrm_action_log'));
$this->setupForSmsTests(TRUE);
}
/**
* Test disabling expired relationships.
*/
public function testCallDisableExpiredRelationships(): void {
$individualID = $this->individualCreate();
$orgID = $this->organizationCreate();
CRM_Utils_Hook_UnitTests::singleton()->setHook('civicrm_pre', [$this, 'hookPreRelationship']);
$relationshipTypeID = $this->callAPISuccess('relationship_type', 'getvalue', [
'return' => 'id',
'name_a_b' => 'Employee of',
]);
$result = $this->callAPISuccess('Relationship', 'create', [
'relationship_type_id' => $relationshipTypeID,
'contact_id_a' => $individualID,
'contact_id_b' => $orgID,
'is_active' => 1,
'end_date' => 'yesterday',
]);
$relationshipID = $result['id'];
$this->assertEquals('Hooked', $result['values'][$relationshipID]['description']);
$this->callAPISuccess('Job', 'disable_expired_relationships', []);
$result = $this->callAPISuccess('relationship', 'get', []);
$this->assertEquals('Go Go you good thing', $result['values'][$relationshipID]['description']);
$this->contactDelete($individualID);
$this->contactDelete($orgID);
}
/**
* Event templates should not send reminders to additional contacts.
*
* @throws \CRM_Core_Exception
*/
public function testTemplateRemindAdditionalContacts(): void {
$contactId = $this->individualCreate();
$groupId = $this->groupCreate(['name' => 'Additional Contacts', 'title' => 'Additional Contacts']);
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contactId,
'group_id' => $groupId,
]);
$event = $this->eventCreateUnpaid(['is_template' => 1, 'template_title' => "I'm a template", 'title' => NULL]);
$eventId = $event['id'];
$this->callAPISuccess('action_schedule', 'create', [
'title' => 'Do not send me',
'subject' => 'I am a reminder attached to a template.',
'entity_value' => $eventId,
'mapping_id' => 5,
'start_action_date' => 'start_date',
'start_action_offset' => 1,
'start_action_condition' => 'before',
'start_action_unit' => 'day',
'group_id' => $groupId,
'limit_to' => 2,
'mode' => 'Email',
]);
$this->callAPISuccess('job', 'send_reminder', []);
$successfulCronCount = CRM_Core_DAO::singleValueQuery('SELECT count(*) FROM civicrm_action_log');
$this->assertEquals(0, $successfulCronCount);
}
/**
* Deleted events should not send reminders to additional contacts.
*/
public function testDeletedEventRemindAdditionalContacts(): void {
$contactId = $this->individualCreate();
$groupId = $this->groupCreate(['name' => 'Additional Contacts', 'title' => 'Additional Contacts']);
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contactId,
'group_id' => $groupId,
]);
$event = $this->eventCreateUnpaid(['title' => 'delete this event']);
$eventId = $event['id'];
$this->callAPISuccess('action_schedule', 'create', [
'title' => 'Do not send me',
'subject' => 'I am a reminder attached to a (soon to be) deleted event.',
'entity_value' => $eventId,
'mapping_id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
'start_action_date' => 'start_date',
'start_action_offset' => 1,
'start_action_condition' => 'before',
'start_action_unit' => 'day',
'group_id' => $groupId,
'limit_to' => 2,
'mode' => 'Email',
]);
$this->callAPISuccess('event', 'delete', ['id' => $eventId]);
$this->callAPISuccess('job', 'send_reminder', []);
$successfulCronCount = CRM_Core_DAO::singleValueQuery('SELECT count(*) FROM civicrm_action_log');
$this->assertEquals(0, $successfulCronCount);
}
/**
* Test scheduled reminders respect limit to (since above identified addition_to handling issue).
*
* We create 3 contacts - 1 is in our group, 1 has our membership & the chosen one has both
* & check that only the chosen one got the reminder
*
* Also check no hard fail on cron job with running a reminder that has a deleted SMS provider
*
* @throws \CRM_Core_Exception
*/
public function testCallSendReminderLimitToSMSWithDeletedProvider(): void {
[$membershipTypeID, $groupID, $theChosenOneID, $provider] = $this->setUpMembershipSMSReminders();
$this->callAPISuccess('action_schedule', 'create', [
'title' => ' remind all Texans',
'subject' => 'drawling renewal',
'entity_value' => $membershipTypeID,
'mapping_id' => 4,
'start_action_date' => 'membership_start_date',
'start_action_offset' => 1,
'start_action_condition' => 'before',
'start_action_unit' => 'day',
'group_id' => $groupID,
'limit_to' => 1,
'sms_provider_id' => $provider['id'],
'mode' => 'SMS',
]);
$this->callAPISuccess('SmsProvider', 'delete', ['id' => $provider['id']]);
$this->callAPISuccess('job', 'send_reminder', []);
$cronCount = CRM_Core_DAO::singleValueQuery('SELECT count(*) FROM civicrm_action_log');
$this->assertEquals(1, $cronCount);
$sentToID = CRM_Core_DAO::singleValueQuery('SELECT contact_id FROM civicrm_action_log');
$this->assertEquals($sentToID, $theChosenOneID);
$cronLog = CRM_Core_DAO::executeQuery('SELECT * FROM civicrm_action_log')->fetchAll()[0];
$this->assertEquals(1, $cronLog['is_error']);
$this->assertEquals('SMS reminder cannot be sent because the SMS provider has been deleted.', $cronLog['message']);
$this->setupForSmsTests(TRUE);
}
/**
* Test the batch merge function.
*
* We are just checking it returns without error here.
*/
public function testBatchMerge(): void {
$this->callAPISuccess('Job', 'process_batch_merge', []);
}
/**
* Test the batch merge function actually works!
*
* @dataProvider getMergeSets
*
* @param array $dataSet
*/
public function testBatchMergeWorks(array $dataSet): void {
foreach ($dataSet['contacts'] as $params) {
$this->callAPISuccess('Contact', 'create', $params);
}
$result = $this->callAPISuccess('Job', 'process_batch_merge', ['mode' => $dataSet['mode']]);
$this->assertCount($dataSet['skipped'], $result['values']['skipped'], 'Failed to skip the right number:' . $dataSet['skipped']);
$this->assertCount($dataSet['merged'], $result['values']['merged']);
$result = $this->callAPISuccess('Contact', 'get', [
'contact_sub_type' => 'Student',
'sequential' => 1,
'is_deceased' => ['IN' => [0, 1]],
'options' => ['sort' => 'id ASC'],
]);
$this->assertEquals(count($dataSet['expected']), $result['count']);
foreach ($dataSet['expected'] as $index => $contact) {
foreach ($contact as $key => $value) {
if ($key === 'gender_id') {
$key = 'gender';
}
$this->assertEquals($value, $result['values'][$index][$key]);
}
}
}
/**
* Check that the merge carries across various related entities.
*
* Note the group combinations & expected results:
*/
public function testBatchMergeWithAssets(): void {
$contactID = $this->individualCreate();
$contact2ID = $this->individualCreate();
$this->contributionCreate(['contact_id' => $contactID]);
$this->contributionCreate(['contact_id' => $contact2ID, 'invoice_id' => '2', 'trxn_id' => 2]);
$this->contactMembershipCreate(['contact_id' => $contactID]);
$this->contactMembershipCreate(['contact_id' => $contact2ID]);
$this->activityCreate(['source_contact_id' => $contactID, 'target_contact_id' => $contactID, 'assignee_contact_id' => $contactID]);
$this->activityCreate(['source_contact_id' => $contact2ID, 'target_contact_id' => $contact2ID, 'assignee_contact_id' => $contact2ID]);
$this->tagCreate(['name' => 'Tall']);
$this->tagCreate(['name' => 'Short']);
$this->entityTagAdd(['contact_id' => $contactID, 'tag_id' => 'Tall']);
$this->entityTagAdd(['contact_id' => $contact2ID, 'tag_id' => 'Short']);
$this->entityTagAdd(['contact_id' => $contact2ID, 'tag_id' => 'Tall']);
$result = $this->callAPISuccess('Job', 'process_batch_merge', ['mode' => 'safe']);
$this->assertCount(0, $result['values']['skipped']);
$this->assertCount(1, $result['values']['merged']);
$this->callAPISuccessGetCount('Contribution', ['contact_id' => $contactID], 2);
$this->callAPISuccessGetCount('Contribution', ['contact_id' => $contact2ID], 0);
$this->callAPISuccessGetCount('FinancialItem', ['contact_id' => $contactID], 2);
$this->callAPISuccessGetCount('FinancialItem', ['contact_id' => $contact2ID], 0);
$this->callAPISuccessGetCount('Membership', ['contact_id' => $contactID], 2);
$this->callAPISuccessGetCount('Membership', ['contact_id' => $contact2ID], 0);
$this->callAPISuccessGetCount('EntityTag', ['contact_id' => $contactID], 2);
$this->callAPISuccessGetCount('EntityTag', ['contact_id' => $contact2ID], 0);
// 14 activities is one for each contribution (2), two (source + target) for each membership (+(2x2) = 6)
// 3 for each of the added activities as there are 3 roles (+6 = 12
// 2 for the (source & target) contact merged activity (+2 = 14)
$this->callAPISuccessGetCount('ActivityContact', ['contact_id' => $contactID], 14);
// 2 for the connection to the deleted by merge activity (source & target)
$this->callAPISuccessGetCount('ActivityContact', ['contact_id' => $contact2ID], 2);
}
/**
* Test that non-contact entity tags are untouched in merge.
*/
public function testContributionEntityTag(): void {
$this->callAPISuccess('OptionValue', 'create', ['option_group_id' => 'tag_used_for', 'value' => 'civicrm_contribution', 'label' => 'Contribution']);
$tagID = $this->tagCreate(['name' => 'Big', 'used_for' => 'civicrm_contribution'])['id'];
$contact1 = $this->individualCreate();
$contact2 = $this->individualCreate();
$contributionID = NULL;
while ($contributionID !== $contact2) {
$contributionID = (int) $this->callAPISuccess('Contribution', 'create', ['contact_id' => $contact1, 'total_amount' => 5, 'financial_type_id' => 'Donation'])['id'];
}
$entityTagParams = ['entity_id' => $contributionID, 'entity_table' => 'civicrm_contribution', 'tag_id' => $tagID];
$this->callAPISuccess('EntityTag', 'create', $entityTagParams);
$this->callAPISuccessGetSingle('EntityTag', $entityTagParams);
$this->callAPISuccess('Job', 'process_batch_merge', ['mode' => 'safe']);
$this->callAPISuccessGetSingle('EntityTag', $entityTagParams);
}
/**
* Check that the merge carries across various related entities.
*
* Note the group combinations 'expected' results:
*
* Group 0 Added null Added
* Group 1 Added Added Added
* Group 2 Added Removed **** Added
* Group 3 Removed null **** null
* Group 4 Removed Added **** Added
* Group 5 Removed Removed **** null
* Group 6 null Added Added
* Group 7 null Removed **** null
*
* The ones with **** are the ones where I think a case could be made to change the behaviour.
*/
public function testBatchMergeMergesGroups(): void {
$contactID = $this->individualCreate();
$contact2ID = $this->individualCreate();
$groups = [];
for ($i = 0; $i < 8; $i++) {
$groups[] = $this->groupCreate([
'name' => 'mergeGroup' . $i,
'title' => 'merge group' . $i,
]);
}
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contactID,
'group_id' => $groups[0],
]);
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contactID,
'group_id' => $groups[1],
]);
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contactID,
'group_id' => $groups[2],
]);
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contactID,
'group_id' => $groups[3],
'status' => 'Removed',
]);
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contactID,
'group_id' => $groups[4],
'status' => 'Removed',
]);
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contactID,
'group_id' => $groups[5],
'status' => 'Removed',
]);
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contact2ID,
'group_id' => $groups[1],
]);
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contact2ID,
'group_id' => $groups[2],
'status' => 'Removed',
]);
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contact2ID,
'group_id' => $groups[4],
]);
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contact2ID,
'group_id' => $groups[5],
'status' => 'Removed',
]);
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contact2ID,
'group_id' => $groups[6],
]);
$this->callAPISuccess('GroupContact', 'create', [
'contact_id' => $contact2ID,
'group_id' => $groups[7],
'status' => 'Removed',
]);
$result = $this->callAPISuccess('Job', 'process_batch_merge', ['mode' => 'safe']);
$this->assertCount(0, $result['values']['skipped']);
$this->assertCount(1, $result['values']['merged']);
$groupResult = $this->callAPISuccess('GroupContact', 'get', []);
$this->assertEquals(5, $groupResult['count']);
$expectedGroups = [
$groups[0],
$groups[1],
$groups[2],
$groups[4],
$groups[6],
];
foreach ($groupResult['values'] as $groupValues) {
$this->assertEquals($contactID, $groupValues['contact_id']);
$this->assertEquals('Added', $groupValues['status']);
$this->assertContainsEquals($groupValues['group_id'], $expectedGroups);
}
}
/**
* Test that we handle cache entries without clashes.
*/
public function testMergeCaches(): void {
$contactID = $this->individualCreate();
$contact2ID = $this->individualCreate();
$groupID = $this->groupCreate();
$this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $contactID]);
$this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $contact2ID]);
CRM_Core_DAO::executeQuery("INSERT INTO civicrm_group_contact_cache(group_id, contact_id) VALUES
($groupID, $contactID),
($groupID, $contact2ID)
");
$this->callAPISuccess('Job', 'process_batch_merge', ['mode' => 'safe']);
}
/**
* Test that we handle cache entries without clashes.
*
* @throws \CRM_Core_Exception
*/
public function testMergeSharedActivity(): void {
$contactID = $this->individualCreate();
$contact2ID = $this->individualCreate();
$this->activityCreate(['target_contact_id' => [$contactID, $contact2ID]]);
$this->callAPISuccess('Job', 'process_batch_merge', ['mode' => 'safe']);
}
/**
* Test the decisions made for addresses when merging.
*
* @dataProvider getMergeLocationData
*
* Scenarios:
* (the ones with **** could be disputed as whether it is the best outcome).
* 'matching_primary' - Primary matches, including location_type_id. One contact has an additional address.
* - result - primary is the shared one. Additional address is retained.
* 'matching_primary_reverse' - Primary matches, including location_type_id. Keep both. (opposite order)
* - result - primary is the shared one. Additional address is retained.
* 'only_one_has_address' - Only one contact has addresses (retain)
* - the (only) address is retained
* 'only_one_has_address_reverse'
* - the (only) address is retained
* 'different_primaries_with_different_location_type' Primaries are different but do not clash due to diff type
* - result - both addresses kept. The one from the kept (lowest ID) contact is primary
* 'different_primaries_with_different_location_type_reverse' Primaries are different but do not clash due to diff type
* - result - both addresses kept. The one from the kept (lowest ID) contact is primary
* 'different_primaries_location_match_only_one_address' per previous but a second address matches the primary but is not primary
* - result - both addresses kept. The one from the kept (lowest ID) contact is primary
* 'different_primaries_location_match_only_one_address_reverse' per previous but a second address matches the primary but is not primary
* - result - both addresses kept. The one from the kept (lowest ID) contact is primary
* 'same_primaries_different_location' Primary addresses are the same but have different location type IDs
* - result primary kept with the lowest ID. Other address retained too (to preserve location type info).
* 'same_primaries_different_location_reverse' Primary addresses are the same but have different location type IDs
* - result primary kept with the lowest ID. Other address retained too (to preserve location type info).
*
* @param array $dataSet
*/
public function testBatchMergesAddresses(array $dataSet): void {
$contactID1 = $this->individualCreate();
$contactID2 = $this->individualCreate();
foreach ($dataSet['contact_1'] as $address) {
$this->callAPISuccess($dataSet['entity'], 'create', array_merge(['contact_id' => $contactID1], $address));
}
foreach ($dataSet['contact_2'] as $address) {
$this->callAPISuccess($dataSet['entity'], 'create', array_merge(['contact_id' => $contactID2], $address));
}
$result = $this->callAPISuccess('Job', 'process_batch_merge', ['mode' => 'safe']);
$this->assertCount(1, $result['values']['merged']);
$addresses = $this->callAPISuccess($dataSet['entity'], 'get', ['contact_id' => $contactID1, 'sequential' => 1]);
$this->assertEquals(count($dataSet['expected']), $addresses['count'], 'Did not get the expected result for ' . $dataSet['entity'] . (!empty($dataSet['description']) ? " on dataset {$dataSet['description']}" : ''));
$locationTypes = $this->callAPISuccess($dataSet['entity'], 'getoptions', ['field' => 'location_type_id']);
foreach ($dataSet['expected'] as $index => $expectedAddress) {
foreach ($expectedAddress as $key => $value) {
if ($key === 'location_type_id') {
$this->assertEquals($locationTypes['values'][$addresses['values'][$index][$key]], $value);
}
else {
$this->assertEquals($addresses['values'][$index][$key], $value, "mismatch on $key" . (!empty($dataSet['description']) ? " on dataset {$dataSet['description']}" : ''));
}
}
}
}
/**
* Test altering the address decision by hook.
*
* @dataProvider getMergeLocationData
*
* @param array $dataSet
*/
public function testBatchMergesAddressesHook(array $dataSet): void {
$contactID1 = $this->individualCreate();
$contactID2 = $this->individualCreate();
$this->contributionCreate(['contact_id' => $contactID1, 'receive_date' => '2010-01-01', 'invoice_id' => 1, 'trxn_id' => 1]);
$this->contributionCreate(['contact_id' => $contactID2, 'receive_date' => '2012-01-01', 'invoice_id' => 2, 'trxn_id' => 2]);
foreach ($dataSet['contact_1'] as $address) {
$this->callAPISuccess($dataSet['entity'], 'create', array_merge(['contact_id' => $contactID1], $address));
}
foreach ($dataSet['contact_2'] as $address) {
$this->callAPISuccess($dataSet['entity'], 'create', array_merge(['contact_id' => $contactID2], $address));
}
$this->hookClass->setHook('civicrm_alterLocationMergeData', [$this, 'hookMostRecentDonor']);
$result = $this->callAPISuccess('Job', 'process_batch_merge', ['mode' => 'safe']);
$this->assertCount(1, $result['values']['merged']);
$addresses = $this->callAPISuccess($dataSet['entity'], 'get', ['contact_id' => $contactID1, 'sequential' => 1]);
$this->assertEquals(count($dataSet['expected_hook']), $addresses['count']);
$locationTypes = $this->callAPISuccess($dataSet['entity'], 'getoptions', ['field' => 'location_type_id']);
foreach ($dataSet['expected_hook'] as $index => $expectedAddress) {
foreach ($expectedAddress as $key => $value) {
if ($key === 'location_type_id') {
$this->assertEquals($locationTypes['values'][$addresses['values'][$index][$key]], $value);
}
else {
$this->assertEquals($value, $addresses['values'][$index][$key], $dataSet['entity'] . ': Unexpected value for ' . $key . (!empty($dataSet['description']) ? " on dataset {$dataSet['description']}" : ''));
}
}
}
}
/**
* Test the organization will not be matched to an individual.
*/
public function testBatchMergeWillNotMergeOrganizationToIndividual(): void {
$individual = $this->callAPISuccess('Contact', 'create', [
'contact_type' => 'Individual',
'organization_name' => 'Anon',
'email' => 'anonymous@hacker.com',
]);
$organization = $this->callAPISuccess('Contact', 'create', [
'contact_type' => 'Organization',
'organization_name' => 'Anon',
'email' => 'anonymous@hacker.com',
]);
$result = $this->callAPISuccess('Job', 'process_batch_merge', ['mode' => 'aggressive']);
$this->assertCount(0, $result['values']['skipped']);
$this->assertCount(0, $result['values']['merged']);
$this->callAPISuccessGetSingle('Contact', ['id' => $individual['id']]);
$this->callAPISuccessGetSingle('Contact', ['id' => $organization['id']]);
}
/**
* Test hook allowing modification of the data calculated for merging locations.
*
* We are testing a nuanced real life situation where the address data of the
* most recent donor gets priority - resulting in the primary address being set
* to the primary address of the most recent donor and address data on a per
* location type basis also being set to the most recent donor. Hook also excludes
* a fully matching address with a different location.
*
* This has been added to the test suite to ensure the code supports more this
* type of intervention.
*
* @param array $blocksDAO
* Array of location DAO to be saved. These are arrays in 2 keys 'update' & 'delete'.
* @param int $mainId
* Contact_id of the contact that survives the merge.
* @param int $otherId
* Contact_id of the contact that will be absorbed and deleted.
* @param array $migrationInfo
* Calculated migration info, informational only.
*/
public function hookMostRecentDonor(array &$blocksDAO, int $mainId, int $otherId, array $migrationInfo): void {
$lastDonorID = $this->callAPISuccessGetValue('Contribution', [
'return' => 'contact_id',
'contact_id' => ['IN' => [$mainId, $otherId]],
'options' => ['sort' => 'receive_date DESC', 'limit' => 1],
]);
// Since the last donor is not the main ID we are prioritising info from the last donor.
// In the test this should always be true - but keep the check in case
// something changes that we need to detect.
if ($lastDonorID !== $mainId) {
foreach ($migrationInfo['other_details']['location_blocks'] as $blockType => $blocks) {
foreach ($blocks as $block) {
if ($block['is_primary']) {
$primaryAddressID = $block['id'];
if (!empty($migrationInfo['main_details']['location_blocks'][$blockType])) {
foreach ($migrationInfo['main_details']['location_blocks'][$blockType] as $mainBlock) {
if (empty($blocksDAO[$blockType]['update'][$block['id']]) && $mainBlock['location_type_id'] === $block['location_type_id']) {
// This was an address match - we just need to check the is_primary
// is true on the matching kept address.
$primaryAddressID = $mainBlock['id'];
$blocksDAO[$blockType]['update'][$primaryAddressID] = _civicrm_api3_load_DAO($blockType);
$blocksDAO[$blockType]['update'][$primaryAddressID]->id = $primaryAddressID;
}
$mainLocationTypeID = $mainBlock['location_type_id'];
// We also want to be more ruthless about removing matching addresses.
unset($mainBlock['location_type_id']);
if (CRM_Dedupe_Merger::locationIsSame($block, $mainBlock)
&& (!isset($blocksDAO[$blockType]['update'][$mainBlock['id']]))
&& (!isset($blocksDAO[$blockType]['delete'][$mainBlock['id']]))
) {
$blocksDAO[$blockType]['delete'][$mainBlock['id']] = _civicrm_api3_load_DAO($blockType);
$blocksDAO[$blockType]['delete'][$mainBlock['id']]->id = $mainBlock['id'];
}
// Arguably the right way to handle this is just to set is_primary for the primary
// and for the merge fn to call something like BAO::add & hooks to work etc.
// if that happens though this should keep working...
elseif ($mainBlock['is_primary'] && $mainLocationTypeID !== $block['location_type_id']) {
$blocksDAO['address']['update'][$mainBlock['id']] = _civicrm_api3_load_DAO($blockType);
$blocksDAO['address']['update'][$mainBlock['id']]->is_primary = 0;
$blocksDAO['address']['update'][$mainBlock['id']]->id = $mainBlock['id'];
}
}
$blocksDAO[$blockType]['update'][$primaryAddressID]->is_primary = 1;
}
}
}
}
}
}
/**
* Get address combinations for the merge test.
*
* @return array
*/
public function getMergeLocationData(): array {
$address1 = ['street_address' => 'Buckingham Palace', 'city' => 'London'];
$address2 = ['street_address' => 'The Doghouse', 'supplemental_address_1' => 'under the blanket'];
$data = $this->getMergeLocations($address1, $address2, 'Address');
$data = array_merge($data, $this->getMergeLocations(['phone' => '12345', 'phone_type_id' => 1], ['phone' => '678910', 'phone_type_id' => 1], 'Phone'));
$data = array_merge($data, $this->getMergeLocations(['phone' => '12345'], ['phone' => '678910'], 'Phone'));
return array_merge($data, $this->getMergeLocations(['email' => 'mini@me.com'], ['email' => 'mini@me.org'], 'Email', [
[
'email' => 'anthony_anderson@civicrm.org',
'location_type_id' => 'Home',
],
]));
}
/**
* Test weird characters don't mess with merge & cause a fatal.
*/
public function testNoErrorOnOdd(): void {
$this->individualCreate();
$this->individualCreate(['first_name' => 'Gerrit%0a%2e%0a']);
$this->callAPISuccess('Job', 'process_batch_merge', []);
$this->individualCreate();
$this->individualCreate(['first_name' => '[foo\\bar\'baz']);
$this->callAPISuccess('Job', 'process_batch_merge', []);
$this->callAPISuccessGetSingle('Contact', ['first_name' => '[foo\\bar\'baz']);
}
/**
* Test the batch merge does not create duplicate emails.
*
* Test CRM-18546, a 4.7 regression whereby a merged contact gets duplicate
* emails.
*/
public function testBatchMergeEmailHandling(): void {
for ($x = 0; $x <= 4; $x++) {
$this->individualCreate(['email' => 'batman@gotham.met']);
}
$result = $this->callAPISuccess('Job', 'process_batch_merge', []);
$this->assertCount(4, $result['values']['merged']);
$this->callAPISuccessGetCount('Contact', ['email' => 'batman@gotham.met'], 1);
$contacts = $this->callAPISuccess('Contact', 'get', ['is_deleted' => 0]);
$deletedContacts = $this->callAPISuccess('Contact', 'get', ['is_deleted' => 1]);
$this->callAPISuccessGetCount('Email', [
'email' => 'batman@gotham.met',
'contact_id' => ['IN' => array_keys($contacts['values'])],
], 1);
$this->callAPISuccessGetCount('Email', [
'email' => 'batman@gotham.met',
'contact_id' => ['IN' => array_keys($deletedContacts['values'])],
], 4);
}
/**
* Test the batch merge respects email "on hold".
*
* Test CRM-19148, Batch merge - Email on hold data lost when there is a conflict.
*
* @dataProvider getOnHoldSets
*
* @param bool $onHold1
* @param bool $onHold2
* @param bool $merge
* @param string|null $conflictText
*/
public function testBatchMergeEmailOnHold(bool $onHold1, bool $onHold2, bool $merge, ?string $conflictText): void {
$this->individualCreate([
'api.email.create' => [
'email' => 'batman@gotham.met',
'location_type_id' => 'Work',
'is_primary' => 1,
'on_hold' => (int) $onHold1,
],
]);
$this->individualCreate([
'api.email.create' => [
'email' => 'batman@gotham.met',
'location_type_id' => 'Work',
'is_primary' => 1,
'on_hold' => (int) $onHold2,
],
]);
$result = $this->callAPISuccess('Job', 'process_batch_merge', []);
$this->assertCount($merge, $result['values']['merged']);
if ($conflictText) {
$defaultRuleGroupID = $this->callAPISuccessGetValue('RuleGroup', [
'contact_type' => 'Individual',
'used' => 'Unsupervised',
'return' => 'id',
'options' => ['limit' => 1],
]);
$duplicates = $this->callAPISuccess('Dedupe', 'getduplicates', ['rule_group_id' => $defaultRuleGroupID]);
$this->assertEquals($conflictText, $duplicates['values'][0]['conflicts']);
}
}
/**
* Data provider for testBatchMergeEmailOnHold: combinations of on_hold & expected outcomes.
*/
public function getOnHoldSets(): array {
// Each row specifies: contact 1 on_hold, contact 2 on_hold, merge? (0 or 1),
return [
[FALSE, FALSE, TRUE, NULL],
[FALSE, TRUE, FALSE, "Email 2 (Work): 'batman@gotham.met' vs. 'batman@gotham.met\n(On Hold)'"],
[TRUE, FALSE, FALSE, "Email 2 (Work): 'batman@gotham.met\n(On Hold)' vs. 'batman@gotham.met'"],
[TRUE, TRUE, TRUE, NULL],
];
}
/**
* Test the batch merge does not fatal on an empty rule.
*
* @dataProvider getRuleSets
*
* @param string $contactType
* @param string $used
* @param string $name
* @param bool $isReserved
* @param int $threshold
*/
public function testBatchMergeEmptyRule(string $contactType, string $used, string $name, bool $isReserved, int $threshold): void {
$ruleGroup = $this->callAPISuccess('RuleGroup', 'create', [
'contact_type' => $contactType,
'threshold' => $threshold,
'used' => $used,
'title' => $name,
'is_reserved' => $isReserved,
]);
$this->callAPISuccess('Job', 'process_batch_merge', ['rule_group_id' => $ruleGroup['id']]);
$this->callAPISuccess('RuleGroup', 'delete', ['id' => $ruleGroup['id']]);
}
/**
* Get the various rule combinations.
*/
public function getRuleSets(): array {
$contactTypes = ['Individual', 'Organization', 'Household'];
$ruleTypes = ['Unsupervised', 'General', 'Supervised'];
$ruleGroups = [];
foreach ($contactTypes as $contactType) {
foreach ($ruleTypes as $used) {
$ruleGroups[] = [$contactType, $used, 'Bob', FALSE, 0];
$ruleGroups[] = [$contactType, $used, 'Bob', FALSE, 10];
$ruleGroups[] = [$contactType, $used, 'Bob', TRUE, 10];
$ruleGroups[] = [$contactType, $used, $contactType . $used, FALSE, 10];
$ruleGroups[] = [$contactType, $used, $contactType . $used, TRUE, 10];
}
}
return $ruleGroups;
}
/**
* Test the batch merge does not create duplicate emails.