4 * Class CRM_Dedupe_DedupeMergerTest
8 class CRM_Dedupe_MergerTest
extends CiviUnitTestCase
{
12 protected $_contactIds = [];
19 public function tearDown() {
22 'civicrm_group_contact',
28 public function createDupeContacts() {
29 // create a group to hold contacts, so that dupe checks don't consider any other contacts in the DB
31 'name' => 'Test Dupe Merger Group',
32 'title' => 'Test Dupe Merger Group',
35 'visibility' => 'Public Pages',
38 $result = $this->callAPISuccess('group', 'create', $params);
39 $this->_groupId
= $result['id'];
43 // make dupe checks based on based on following contact sets:
44 // FIRST - LAST - EMAIL
45 // ---------------------------------
46 // robin - hood - robin@example.com
47 // robin - hood - robin@example.com
48 // robin - hood - hood@example.com
49 // robin - dale - robin@example.com
50 // little - dale - dale@example.com
51 // little - dale - dale@example.com
52 // will - dale - dale@example.com
53 // will - dale - will@example.com
54 // will - dale - will@example.com
57 'first_name' => 'robin',
58 'last_name' => 'hood',
59 'email' => 'robin@example.com',
60 'contact_type' => 'Individual',
63 'first_name' => 'robin',
64 'last_name' => 'hood',
65 'email' => 'robin@example.com',
66 'contact_type' => 'Individual',
69 'first_name' => 'robin',
70 'last_name' => 'hood',
71 'email' => 'hood@example.com',
72 'contact_type' => 'Individual',
75 'first_name' => 'robin',
76 'last_name' => 'dale',
77 'email' => 'robin@example.com',
78 'contact_type' => 'Individual',
81 'first_name' => 'little',
82 'last_name' => 'dale',
83 'email' => 'dale@example.com',
84 'contact_type' => 'Individual',
87 'first_name' => 'little',
88 'last_name' => 'dale',
89 'email' => 'dale@example.com',
90 'contact_type' => 'Individual',
93 'first_name' => 'will',
94 'last_name' => 'dale',
95 'email' => 'dale@example.com',
96 'contact_type' => 'Individual',
99 'first_name' => 'will',
100 'last_name' => 'dale',
101 'email' => 'will@example.com',
102 'contact_type' => 'Individual',
105 'first_name' => 'will',
106 'last_name' => 'dale',
107 'email' => 'will@example.com',
108 'contact_type' => 'Individual',
113 foreach ($params as $param) {
114 $param['version'] = 3;
115 $contact = civicrm_api('contact', 'create', $param);
116 $this->_contactIds
[$count++
] = $contact['id'];
119 'contact_id' => $contact['id'],
120 'group_id' => $this->_groupId
,
123 $this->callAPISuccess('group_contact', 'create', $grpParams);
128 * Delete all created contacts.
130 public function deleteDupeContacts() {
131 foreach ($this->_contactIds
as $contactId) {
132 $this->contactDelete($contactId);
134 $this->groupDelete($this->_groupId
);
138 * Test the batch merge.
140 public function testBatchMergeSelectedDuplicates() {
141 $this->createDupeContacts();
143 // verify that all contacts have been created separately
144 $this->assertEquals(count($this->_contactIds
), 9, 'Check for number of contacts.');
146 $dao = new CRM_Dedupe_DAO_RuleGroup();
147 $dao->contact_type
= 'Individual';
148 $dao->name
= 'IndividualSupervised';
149 $dao->is_default
= 1;
152 $foundDupes = CRM_Dedupe_Finder
::dupesInGroup($dao->id
, $this->_groupId
);
154 // -------------------------------------------------------------------------
155 // Name and Email (reserved) Matches ( 3 pairs )
156 // --------------------------------------------------------------------------
157 // robin - hood - robin@example.com
158 // robin - hood - robin@example.com
159 // little - dale - dale@example.com
160 // little - dale - dale@example.com
161 // will - dale - will@example.com
162 // will - dale - will@example.com
163 // so 3 pairs for - first + last + mail
164 $this->assertEquals(count($foundDupes), 3, 'Check Individual-Supervised dupe rule for dupesInGroup().');
166 // Run dedupe finder as the browser would
167 //avoid invalid key error
168 $_SERVER['REQUEST_METHOD'] = 'GET';
169 $object = new CRM_Contact_Page_DedupeFind();
170 $object->set('gid', $this->_groupId
);
171 $object->set('rgid', $dao->id
);
172 $object->set('action', CRM_Core_Action
::UPDATE
);
173 $object->setEmbedded(TRUE);
176 // Retrieve pairs from prev next cache table
177 $select = ['pn.is_selected' => 'is_selected'];
178 $cacheKeyString = CRM_Dedupe_Merger
::getMergeCacheKeyString($dao->id
, $this->_groupId
);
179 $pnDupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, NULL, NULL, 0, 0, $select);
180 $this->assertEquals(count($foundDupes), count($pnDupePairs), 'Check number of dupe pairs in prev next cache.');
182 // mark first two pairs as selected
183 CRM_Core_DAO
::singleValueQuery("UPDATE civicrm_prevnext_cache SET is_selected = 1 WHERE id IN ({$pnDupePairs[0]['prevnext_id']}, {$pnDupePairs[1]['prevnext_id']})");
185 $pnDupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, NULL, NULL, 0, 0, $select);
186 $this->assertEquals($pnDupePairs[0]['is_selected'], 1, 'Check if first record in dupe pairs is marked as selected.');
187 $this->assertEquals($pnDupePairs[0]['is_selected'], 1, 'Check if second record in dupe pairs is marked as selected.');
189 // batch merge selected dupes
190 $result = CRM_Dedupe_Merger
::batchMerge($dao->id
, $this->_groupId
, 'safe', 5, 1);
191 $this->assertEquals(count($result['merged']), 2, 'Check number of merged pairs.');
193 $stats = $this->callAPISuccess('Dedupe', 'getstatistics', [
194 'group_id' => $this->_groupId
,
195 'rule_group_id' => $dao->id
,
196 'check_permissions' => TRUE,
198 $this->assertEquals(['merged' => 2, 'skipped' => 0], $stats);
200 // retrieve pairs from prev next cache table
201 $pnDupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, NULL, NULL, 0, 0, $select);
202 $this->assertEquals(count($pnDupePairs), 1, 'Check number of remaining dupe pairs in prev next cache.');
204 $this->deleteDupeContacts();
208 * Test the batch merge.
210 public function testBatchMergeAllDuplicates() {
211 $this->createDupeContacts();
213 // verify that all contacts have been created separately
214 $this->assertEquals(count($this->_contactIds
), 9, 'Check for number of contacts.');
216 $dao = new CRM_Dedupe_DAO_RuleGroup();
217 $dao->contact_type
= 'Individual';
218 $dao->name
= 'IndividualSupervised';
219 $dao->is_default
= 1;
222 $foundDupes = CRM_Dedupe_Finder
::dupesInGroup($dao->id
, $this->_groupId
);
224 // -------------------------------------------------------------------------
225 // Name and Email (reserved) Matches ( 3 pairs )
226 // --------------------------------------------------------------------------
227 // robin - hood - robin@example.com
228 // robin - hood - robin@example.com
229 // little - dale - dale@example.com
230 // little - dale - dale@example.com
231 // will - dale - will@example.com
232 // will - dale - will@example.com
233 // so 3 pairs for - first + last + mail
234 $this->assertEquals(count($foundDupes), 3, 'Check Individual-Supervised dupe rule for dupesInGroup().');
236 // Run dedupe finder as the browser would
237 //avoid invalid key error
238 $_SERVER['REQUEST_METHOD'] = 'GET';
239 $object = new CRM_Contact_Page_DedupeFind();
240 $object->set('gid', $this->_groupId
);
241 $object->set('rgid', $dao->id
);
242 $object->set('action', CRM_Core_Action
::UPDATE
);
243 $object->setEmbedded(TRUE);
246 // Retrieve pairs from prev next cache table
247 $select = ['pn.is_selected' => 'is_selected'];
248 $cacheKeyString = CRM_Dedupe_Merger
::getMergeCacheKeyString($dao->id
, $this->_groupId
);
249 $pnDupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, NULL, NULL, 0, 0, $select);
251 $this->assertEquals(count($foundDupes), count($pnDupePairs), 'Check number of dupe pairs in prev next cache.');
253 // batch merge all dupes
254 $result = CRM_Dedupe_Merger
::batchMerge($dao->id
, $this->_groupId
, 'safe', 5, 2);
255 $this->assertEquals(count($result['merged']), 3, 'Check number of merged pairs.');
257 $stats = $this->callAPISuccess('Dedupe', 'getstatistics', [
258 'rule_group_id' => $dao->id
,
259 'group_id' => $this->_groupId
,
261 // retrieve pairs from prev next cache table
262 $pnDupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, NULL, NULL, 0, 0, $select);
263 $this->assertEquals(count($pnDupePairs), 0, 'Check number of remaining dupe pairs in prev next cache.');
265 $this->deleteDupeContacts();
269 * The goal of this function is to test that all required tables are returned.
271 public function testGetCidRefs() {
272 $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, 'Contacts');
273 $this->assertEquals(array_merge($this->getStaticCIDRefs(), $this->getHackedInCIDRef()), CRM_Dedupe_Merger
::cidRefs());
274 $this->assertEquals(array_merge($this->getCalculatedCIDRefs(), $this->getHackedInCIDRef()), CRM_Dedupe_Merger
::cidRefs());
278 * Get the list of not-really-cid-refs that are currently hacked in.
280 * This is hacked into getCIDs function.
284 public function getHackedInCIDRef() {
286 'civicrm_entity_tag' => [
293 * Test function that gets duplicate pairs.
295 * It turns out there are 2 code paths retrieving this data so my initial
296 * focus is on ensuring they match.
298 public function testGetMatches() {
299 $this->setupMatchData();
301 $pairs = $this->callAPISuccess('Dedupe', 'getduplicates', [
302 'rule_group_id' => 1,
304 $this->assertEquals([
306 'srcID' => $this->contacts
[1]['id'],
307 'srcName' => 'Mr. Mickey Mouse II',
308 'dstID' => $this->contacts
[0]['id'],
309 'dstName' => 'Mr. Mickey Mouse II',
314 'srcID' => $this->contacts
[3]['id'],
315 'srcName' => 'Mr. Minnie Mouse II',
316 'dstID' => $this->contacts
[2]['id'],
317 'dstName' => 'Mr. Minnie Mouse II',
325 * Test function that gets organization pairs.
327 * Note the rule will match on organization_name OR email - hence lots of
332 public function testGetOrganizationMatches() {
333 $this->setupMatchData();
334 $ruleGroups = $this->callAPISuccessGetSingle('RuleGroup', [
335 'contact_type' => 'Organization',
336 'used' => 'Supervised',
339 $pairs = CRM_Dedupe_Merger
::getDuplicatePairs(
349 'srcID' => $this->contacts
[5]['id'],
350 'srcName' => 'Walt Disney Ltd',
351 'dstID' => $this->contacts
[4]['id'],
352 'dstName' => 'Walt Disney Ltd',
357 'srcID' => $this->contacts
[7]['id'],
358 'srcName' => 'Walt Disney',
359 'dstID' => $this->contacts
[6]['id'],
360 'dstName' => 'Walt Disney',
365 'srcID' => $this->contacts
[6]['id'],
366 'srcName' => 'Walt Disney',
367 'dstID' => $this->contacts
[4]['id'],
368 'dstName' => 'Walt Disney Ltd',
373 'srcID' => $this->contacts
[6]['id'],
374 'srcName' => 'Walt Disney',
375 'dstID' => $this->contacts
[5]['id'],
376 'dstName' => 'Walt Disney Ltd',
381 usort($pairs, [__CLASS__
, 'compareDupes']);
382 usort($expectedPairs, [__CLASS__
, 'compareDupes']);
383 $this->assertEquals($expectedPairs, $pairs);
387 * Function to sort $duplicate records in a stable way.
394 public static function compareDupes($a, $b) {
395 foreach (['srcName', 'dstName', 'srcID', 'dstID'] as $field) {
396 if ($a[$field] != $b[$field]) {
397 return ($a[$field] < $b[$field]) ?
1 : -1;
404 * Test function that gets organization duplicate pairs.
408 public function testGetOrganizationMatchesInGroup() {
409 $this->setupMatchData();
410 $ruleGroups = $this->callAPISuccessGetSingle('RuleGroup', [
411 'contact_type' => 'Organization',
412 'used' => 'Supervised',
415 $groupID = $this->groupCreate(['title' => 'she-mice']);
417 $this->callAPISuccess('GroupContact', 'create', [
418 'group_id' => $groupID,
419 'contact_id' => $this->contacts
[4]['id'],
422 $pairs = CRM_Dedupe_Merger
::getDuplicatePairs(
430 $this->assertEquals([
432 'srcID' => $this->contacts
[5]['id'],
433 'srcName' => 'Walt Disney Ltd',
434 'dstID' => $this->contacts
[4]['id'],
435 'dstName' => 'Walt Disney Ltd',
440 'srcID' => $this->contacts
[6]['id'],
441 'srcName' => 'Walt Disney',
442 'dstID' => $this->contacts
[4]['id'],
443 'dstName' => 'Walt Disney Ltd',
449 $this->callAPISuccess('GroupContact', 'create', [
450 'group_id' => $groupID,
451 'contact_id' => $this->contacts
[5]['id'],
453 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_prevnext_cache");
454 $pairs = CRM_Dedupe_Merger
::getDuplicatePairs(
462 $this->assertEquals([
464 'srcID' => $this->contacts
[5]['id'],
465 'srcName' => 'Walt Disney Ltd',
466 'dstID' => $this->contacts
[4]['id'],
467 'dstName' => 'Walt Disney Ltd',
472 'srcID' => $this->contacts
[6]['id'],
473 'srcName' => 'Walt Disney',
474 'dstID' => $this->contacts
[4]['id'],
475 'dstName' => 'Walt Disney Ltd',
480 'srcID' => $this->contacts
[6]['id'],
481 'srcName' => 'Walt Disney',
482 'dstID' => $this->contacts
[5]['id'],
483 'dstName' => 'Walt Disney Ltd',
491 * Test function that gets duplicate pairs.
493 * It turns out there are 2 code paths retrieving this data so my initial
494 * focus is on ensuring they match.
496 public function testGetMatchesInGroup() {
497 $this->setupMatchData();
499 $groupID = $this->groupCreate(['title' => 'she-mice']);
501 $this->callAPISuccess('GroupContact', 'create', [
502 'group_id' => $groupID,
503 'contact_id' => $this->contacts
[3]['id'],
506 $pairs = CRM_Dedupe_Merger
::getDuplicatePairs(
514 $this->assertEquals([
516 'srcID' => $this->contacts
[3]['id'],
517 'srcName' => 'Mr. Minnie Mouse II',
518 'dstID' => $this->contacts
[2]['id'],
519 'dstName' => 'Mr. Minnie Mouse II',
527 * Test the special info handling is unchanged after cleanup.
529 * Note the handling is silly - we are testing to lock in over short term
530 * changes not to imply any contract on the function.
532 public function testGetRowsElementsAndInfoSpecialInfo() {
533 $contact1 = $this->individualCreate([
534 'preferred_communication_method' => [],
535 'communication_style_id' => 'Familiar',
536 'prefix_id' => 'Mrs.',
537 'suffix_id' => 'III',
539 $contact2 = $this->individualCreate([
540 'preferred_communication_method' => [
544 'communication_style_id' => 'Formal',
545 'gender_id' => 'Female',
547 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($contact1, $contact2);
548 $rows = $rowsElementsAndInfo['rows'];
549 $this->assertEquals([
552 'title' => 'Individual Prefix',
553 ], $rows['move_prefix_id']);
554 $this->assertEquals([
557 'title' => 'Individual Suffix',
558 ], $rows['move_suffix_id']);
559 $this->assertEquals([
563 ], $rows['move_gender_id']);
564 $this->assertEquals([
565 'main' => 'Familiar',
567 'title' => 'Communication Style',
568 ], $rows['move_communication_style_id']);
569 $this->assertEquals(1, $rowsElementsAndInfo['migration_info']['move_communication_style_id']);
570 $this->assertEquals([
572 'other' => 'SMS, Fax',
573 'title' => 'Preferred Communication Method',
574 ], $rows['move_preferred_communication_method']);
575 $this->assertEquals('\ 14\ 15\ 1', $rowsElementsAndInfo['migration_info']['move_preferred_communication_method']);
579 * Test migration of Membership.
581 public function testMergeMembership() {
583 $this->setupMatchData();
584 $originalContactID = $this->contacts
[0]['id'];
585 $duplicateContactID = $this->contacts
[1]['id'];
587 //Add Membership for the duplicate contact.
588 $memTypeId = $this->membershipTypeCreate();
589 $this->callAPISuccess('Membership', 'create', [
590 'membership_type_id' => $memTypeId,
591 'contact_id' => $duplicateContactID,
593 //Assert if 'add new' checkbox is enabled on the merge form.
594 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($originalContactID, $duplicateContactID);
595 foreach ($rowsElementsAndInfo['elements'] as $element) {
596 if (!empty($element[3]) && $element[3] == 'add new') {
597 $checkedAttr = ['checked' => 'checked'];
598 $this->checkArrayEquals($element[4], $checkedAttr);
602 //Merge and move the mem to the main contact.
603 $this->mergeContacts($originalContactID, $duplicateContactID, [
604 'move_rel_table_memberships' => 1,
605 'operation' => ['move_rel_table_memberships' => ['add' => 1]],
608 //Check if membership is correctly transferred to original contact.
609 $originalContactMembership = $this->callAPISuccess('Membership', 'get', [
610 'membership_type_id' => $memTypeId,
611 'contact_id' => $originalContactID,
613 $this->assertEquals(1, $originalContactMembership['count']);
617 * CRM-19653 : Test that custom field data should/shouldn't be overriden on
618 * selecting/not selecting option to migrate data respectively
620 public function testCustomDataOverwrite() {
621 // Create Custom Field
622 $createGroup = $this->setupCustomGroupForIndividual();
623 $createField = $this->setupCustomField('Graduation', $createGroup);
624 $customFieldName = "custom_" . $createField['id'];
627 $this->setupMatchData();
629 $originalContactID = $this->contacts
[0]['id'];
630 // used as duplicate contact in 1st use-case
631 $duplicateContactID1 = $this->contacts
[1]['id'];
632 // used as duplicate contact in 2nd use-case
633 $duplicateContactID2 = $this->contacts
[2]['id'];
635 // update the text custom field for original contact with value 'abc'
636 $this->callAPISuccess('Contact', 'create', [
637 'id' => $originalContactID,
638 "{$customFieldName}" => 'abc',
640 $this->assertCustomFieldValue($originalContactID, 'abc', $customFieldName);
642 // update the text custom field for duplicate contact 1 with value 'def'
643 $this->callAPISuccess('Contact', 'create', [
644 'id' => $duplicateContactID1,
645 "{$customFieldName}" => 'def',
647 $this->assertCustomFieldValue($duplicateContactID1, 'def', $customFieldName);
649 // update the text custom field for duplicate contact 2 with value 'ghi'
650 $this->callAPISuccess('Contact', 'create', [
651 'id' => $duplicateContactID2,
652 "{$customFieldName}" => 'ghi',
654 $this->assertCustomFieldValue($duplicateContactID2, 'ghi', $customFieldName);
656 /*** USE-CASE 1: DO NOT OVERWRITE CUSTOM FIELD VALUE **/
657 $this->mergeContacts($originalContactID, $duplicateContactID1, [
658 "move_{$customFieldName}" => NULL,
660 $this->assertCustomFieldValue($originalContactID, 'abc', $customFieldName);
662 /*** USE-CASE 2: OVERWRITE CUSTOM FIELD VALUE **/
663 $this->mergeContacts($originalContactID, $duplicateContactID2, [
664 "move_{$customFieldName}" => 'ghi',
666 $this->assertCustomFieldValue($originalContactID, 'ghi', $customFieldName);
668 // cleanup created custom set
669 $this->callAPISuccess('CustomField', 'delete', ['id' => $createField['id']]);
670 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $createGroup['id']]);
674 * Creatd Date merge cases
677 public function createdDateMergeCases() {
679 // Normal pattern merge into the lower id
681 // Check if we flipped the contacts that it still does right thing
687 * dev/core#996 Ensure that the oldest created date is retained even if duplicates have been flipped
688 * @dataProvider createdDateMergeCases
690 public function testCreatedDatePostMerge($keepContactKey, $duplicateContactKey) {
691 $this->setupMatchData();
692 $lowerContactCreatedDate = $this->callAPISuccess('Contact', 'getsingle', [
693 'id' => $this->contacts
[0]['id'],
694 'return' => ['created_date'],
696 // Assume contats have been flipped in the UL so merging into the higher id
697 $this->mergeContacts($this->contacts
[$keepContactKey]['id'], $this->contacts
[$duplicateContactKey]['id'], []);
698 $this->assertEquals($lowerContactCreatedDate, $this->callAPISuccess('Contact', 'getsingle', ['id' => $this->contacts
[$keepContactKey]['id'], 'return' => ['created_date']])['created_date']);
702 * Verifies that when a contact with a custom field value is merged into a
703 * contact without a record int its corresponding custom group table, and none
704 * of the custom fields of that custom table are selected, the value is not
707 public function testMigrationOfUnselectedCustomDataOnEmptyCustomRecord() {
708 // Create Custom Fields
709 $createGroup = $this->setupCustomGroupForIndividual();
710 $customField1 = $this->setupCustomField('TestField', $createGroup);
712 // Create multi-value custom field
713 $multiGroup = $this->CustomGroupMultipleCreateByParams();
714 $multiField = $this->customFieldCreate([
715 'custom_group_id' => $multiGroup['id'],
716 'label' => 'field_1' . $multiGroup['id'],
721 $this->setupMatchData();
722 $originalContactID = $this->contacts
[0]['id'];
723 $duplicateContactID = $this->contacts
[1]['id'];
725 // Update the text custom fields for duplicate contact
726 $this->callAPISuccess('Contact', 'create', [
727 'id' => $duplicateContactID,
728 "custom_{$customField1['id']}" => 'abc',
729 "custom_{$multiField['id']}" => 'def',
731 $this->assertCustomFieldValue($duplicateContactID, 'abc', "custom_{$customField1['id']}");
732 $this->assertCustomFieldValue($duplicateContactID, 'def', "custom_{$multiField['id']}");
734 // Merge, and ensure that no value was migrated
735 $this->mergeContacts($originalContactID, $duplicateContactID, [
736 "move_custom_{$customField1['id']}" => NULL,
737 "move_rel_table_custom_{$multiGroup['id']}" => NULL,
739 $this->assertCustomFieldValue($originalContactID, '', "custom_{$customField1['id']}");
740 $this->assertCustomFieldValue($originalContactID, '', "custom_{$multiField['id']}");
742 // cleanup created custom set
743 $this->callAPISuccess('CustomField', 'delete', ['id' => $customField1['id']]);
744 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $createGroup['id']]);
745 $this->callAPISuccess('CustomField', 'delete', ['id' => $multiField['id']]);
746 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $multiGroup['id']]);
750 * Tests that if only part of the custom fields of a custom group are selected
751 * for a merge, only those values are merged, while all other fields of the
752 * custom group retain their original value, specifically for a contact with
753 * no records on the custom group table.
755 public function testMigrationOfSomeCustomDataOnEmptyCustomRecord() {
756 // Create Custom Fields
757 $createGroup = $this->setupCustomGroupForIndividual();
758 $customField1 = $this->setupCustomField('Test1', $createGroup);
759 $customField2 = $this->setupCustomField('Test2', $createGroup);
761 // Create multi-value custom field
762 $multiGroup = $this->CustomGroupMultipleCreateByParams();
763 $multiField = $this->customFieldCreate([
764 'custom_group_id' => $multiGroup['id'],
765 'label' => 'field_1' . $multiGroup['id'],
770 $this->setupMatchData();
771 $originalContactID = $this->contacts
[0]['id'];
772 $duplicateContactID = $this->contacts
[1]['id'];
774 // Update the text custom fields for duplicate contact
775 $this->callAPISuccess('Contact', 'create', [
776 'id' => $duplicateContactID,
777 "custom_{$customField1['id']}" => 'abc',
778 "custom_{$customField2['id']}" => 'def',
779 "custom_{$multiField['id']}" => 'ghi',
781 $this->assertCustomFieldValue($duplicateContactID, 'abc', "custom_{$customField1['id']}");
782 $this->assertCustomFieldValue($duplicateContactID, 'def', "custom_{$customField2['id']}");
783 $this->assertCustomFieldValue($duplicateContactID, 'ghi', "custom_{$multiField['id']}");
786 $this->mergeContacts($originalContactID, $duplicateContactID, [
787 "move_custom_{$customField1['id']}" => NULL,
788 "move_custom_{$customField2['id']}" => 'def',
789 "move_rel_table_custom_{$multiGroup['id']}" => '1',
791 $this->assertCustomFieldValue($originalContactID, '', "custom_{$customField1['id']}");
792 $this->assertCustomFieldValue($originalContactID, 'def', "custom_{$customField2['id']}");
793 $this->assertCustomFieldValue($originalContactID, 'ghi', "custom_{$multiField['id']}");
795 // cleanup created custom set
796 $this->callAPISuccess('CustomField', 'delete', ['id' => $customField1['id']]);
797 $this->callAPISuccess('CustomField', 'delete', ['id' => $customField2['id']]);
798 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $createGroup['id']]);
799 $this->callAPISuccess('CustomField', 'delete', ['id' => $multiField['id']]);
800 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $multiGroup['id']]);
804 * Test that ContactReference fields are updated to point to the main contact
805 * after a merge is performed and the duplicate contact is deleted.
807 public function testMigrationOfContactReferenceCustomField() {
808 // Create Custom Fields
809 $contactGroup = $this->setupCustomGroupForIndividual();
810 $activityGroup = $this->customGroupCreate([
811 'name' => 'test_group_activity',
812 'extends' => 'Activity',
814 $refFieldContact = $this->customFieldCreate([
815 'custom_group_id' => $contactGroup['id'],
816 'label' => 'field_1' . $contactGroup['id'],
817 'data_type' => 'ContactReference',
818 'default_value' => NULL,
820 $refFieldActivity = $this->customFieldCreate([
821 'custom_group_id' => $activityGroup['id'],
822 'label' => 'field_1' . $activityGroup['id'],
823 'data_type' => 'ContactReference',
824 'default_value' => NULL,
828 $this->setupMatchData();
829 $originalContactID = $this->contacts
[0]['id'];
830 $duplicateContactID = $this->contacts
[1]['id'];
832 // create a contact that won't be merged but has a ContactReference field
833 // pointing to the duplicate (to be deleted) contact
834 $unrelatedContact = $this->individualCreate([
835 'first_name' => 'Unrelated',
836 'first_name' => 'Contact',
837 'email' => 'unrelated@example.com',
838 "custom_{$refFieldContact['id']}" => $duplicateContactID,
840 // also create an activity with a ContactReference custom field
841 $activity = $this->activityCreate([
842 'target_contact_id' => $unrelatedContact,
843 "custom_{$refFieldActivity['id']}" => $duplicateContactID,
846 // verify that the fields were set
847 $this->assertCustomFieldValue($unrelatedContact, $duplicateContactID, "custom_{$refFieldContact['id']}");
848 $this->assertEntityCustomFieldValue('Activity', $activity['id'], $duplicateContactID, "custom_{$refFieldActivity['id']}_id");
851 $this->mergeContacts($originalContactID, $duplicateContactID, []);
853 // verify that the ContactReference fields were updated to point to the surviving contact post-merge
854 $this->assertCustomFieldValue($unrelatedContact, $originalContactID, "custom_{$refFieldContact['id']}");
855 $this->assertEntityCustomFieldValue('Activity', $activity['id'], $originalContactID, "custom_{$refFieldActivity['id']}_id");
857 // cleanup created custom set
858 $this->callAPISuccess('CustomField', 'delete', ['id' => $refFieldContact['id']]);
859 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $contactGroup['id']]);
860 $this->callAPISuccess('CustomField', 'delete', ['id' => $refFieldActivity['id']]);
861 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $activityGroup['id']]);
865 * Calls merge method on given contacts, with values given in $params array.
867 * @param $originalContactID
868 * ID of target contact
869 * @param $duplicateContactID
870 * ID of contact to be merged
872 * Array of fields to be merged from source into target contact, of the form
873 * ['move_<fieldName>' => <fieldValue>]
875 * @throws \CRM_Core_Exception
876 * @throws \CiviCRM_API3_Exception
878 private function mergeContacts($originalContactID, $duplicateContactID, $params) {
879 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($originalContactID, $duplicateContactID);
882 'main_details' => $rowsElementsAndInfo['main_details'],
883 'other_details' => $rowsElementsAndInfo['other_details'],
886 // Migrate data of duplicate contact
887 CRM_Dedupe_Merger
::moveAllBelongings($originalContactID, $duplicateContactID, array_merge($migrationData, $params));
891 * Checks if the expected value for the given field corresponds to what is
892 * stored in the database for the given contact ID.
895 * @param $expectedValue
896 * @param $customFieldName
898 private function assertCustomFieldValue($contactID, $expectedValue, $customFieldName) {
899 $this->assertEntityCustomFieldValue('Contact', $contactID, $expectedValue, $customFieldName);
903 * Check if the custom field of the given field and entity id matches the
908 * @param $expectedValue
909 * @param $customFieldName
911 private function assertEntityCustomFieldValue($entity, $id, $expectedValue, $customFieldName) {
912 $data = $this->callAPISuccess($entity, 'getsingle', [
914 'return' => [$customFieldName],
917 $this->assertEquals($expectedValue, $data[$customFieldName], "Custom field value was supposed to be '{$expectedValue}', '{$data[$customFieldName]}' found.");
921 * Creates a custom group to run tests on contacts that are individuals.
924 * Data for the created custom group record
926 private function setupCustomGroupForIndividual() {
927 $customGroup = $this->callAPISuccess('custom_group', 'get', [
928 'name' => 'test_group',
931 if ($customGroup['count'] > 0) {
932 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $customGroup['id']]);
935 $customGroup = $this->callAPISuccess('custom_group', 'create', [
936 'title' => 'Test_Group',
937 'name' => 'test_group',
938 'extends' => ['Individual'],
940 'is_multiple' => FALSE,
948 * Creates a custom field on the provided custom group with the given field
952 * @param $createGroup
955 * Data for the created custom field record
957 private function setupCustomField($fieldLabel, $createGroup) {
958 return $this->callAPISuccess('custom_field', 'create', [
959 'label' => $fieldLabel,
960 'data_type' => 'Alphanumeric',
961 'html_type' => 'Text',
962 'custom_group_id' => $createGroup['id'],
967 * Set up some contacts for our matching.
969 public function setupMatchData() {
972 'first_name' => 'Mickey',
973 'last_name' => 'Mouse',
974 'email' => 'mickey@mouse.com',
977 'first_name' => 'Mickey',
978 'last_name' => 'Mouse',
979 'email' => 'mickey@mouse.com',
982 'first_name' => 'Minnie',
983 'last_name' => 'Mouse',
984 'email' => 'mickey@mouse.com',
987 'first_name' => 'Minnie',
988 'last_name' => 'Mouse',
989 'email' => 'mickey@mouse.com',
992 foreach ($fixtures as $fixture) {
993 $contactID = $this->individualCreate($fixture);
994 $this->contacts
[] = array_merge($fixture, ['id' => $contactID]);
997 $organizationFixtures = [
999 'organization_name' => 'Walt Disney Ltd',
1000 'email' => 'walt@disney.com',
1003 'organization_name' => 'Walt Disney Ltd',
1004 'email' => 'walt@disney.com',
1007 'organization_name' => 'Walt Disney',
1008 'email' => 'walt@disney.com',
1011 'organization_name' => 'Walt Disney',
1012 'email' => 'walter@disney.com',
1015 foreach ($organizationFixtures as $fixture) {
1016 $contactID = $this->organizationCreate($fixture);
1017 $this->contacts
[] = array_merge($fixture, ['id' => $contactID]);
1022 * Get the list of tables that refer to the CID.
1024 * This is a statically maintained (in this test list).
1026 * There is also a check against an automated list but having both seems to
1027 * add extra stability to me. They do not change often.
1029 public function getStaticCIDRefs() {
1031 'civicrm_acl_cache' => [
1034 'civicrm_acl_contact_cache' => [
1037 'civicrm_action_log' => [
1040 'civicrm_activity_contact' => [
1043 'civicrm_address' => [
1046 'civicrm_batch' => [
1050 'civicrm_campaign' => [
1052 1 => 'last_modified_id',
1054 'civicrm_case_contact' => [
1057 'civicrm_contact' => [
1058 0 => 'primary_contact_id',
1061 'civicrm_contribution' => [
1064 'civicrm_contribution_page' => [
1067 'civicrm_contribution_recur' => [
1070 'civicrm_contribution_soft' => [
1073 'civicrm_custom_group' => [
1076 'civicrm_dashboard_contact' => [
1079 'civicrm_dedupe_exception' => [
1083 'civicrm_domain' => [
1086 'civicrm_email' => [
1089 'civicrm_event' => [
1092 'civicrm_event_carts' => [
1095 'civicrm_financial_account' => [
1098 'civicrm_financial_item' => [
1101 'civicrm_grant' => [
1104 'civicrm_group' => [
1108 'civicrm_group_contact' => [
1111 'civicrm_group_contact_cache' => [
1114 'civicrm_group_organization' => [
1115 0 => 'organization_id',
1123 'civicrm_mailing' => [
1125 1 => 'scheduled_id',
1131 'civicrm_mailing_abtest' => [
1134 'civicrm_mailing_event_queue' => [
1137 'civicrm_mailing_event_subscribe' => [
1140 'civicrm_mailing_recipients' => [
1143 'civicrm_membership' => [
1146 'civicrm_membership_log' => [
1149 'civicrm_membership_type' => [
1150 0 => 'member_of_contact_id',
1155 'civicrm_openid' => [
1158 'civicrm_participant' => [
1161 1 => 'transferred_to_contact_id',
1163 'civicrm_payment_token' => [
1170 'civicrm_phone' => [
1173 'civicrm_pledge' => [
1176 'civicrm_print_label' => [
1179 'civicrm_relationship' => [
1180 0 => 'contact_id_a',
1181 1 => 'contact_id_b',
1183 'civicrm_report_instance' => [
1187 'civicrm_setting' => [
1191 'civicrm_subscription_history' => [
1194 'civicrm_survey' => [
1196 1 => 'last_modified_id',
1201 'civicrm_uf_group' => [
1204 'civicrm_uf_match' => [
1207 'civicrm_value_testgetcidref_1' => [
1210 'civicrm_website' => [
1217 * Get a list of CIDs that is calculated off the schema.
1219 * Note this is an expensive and table locking query. Should be safe in tests
1222 public function getCalculatedCIDRefs() {
1228 FROM information_schema.key_column_usage
1230 referenced_table_schema = database() AND
1231 referenced_table_name = 'civicrm_contact' AND
1232 referenced_column_name = 'id';
1234 $dao = CRM_Core_DAO
::executeQuery($sql);
1235 while ($dao->fetch()) {
1236 $cidRefs[$dao->table_name
][] = $dao->column_name
;
1238 // Do specific re-ordering changes to make this the same as the ref validated one.
1239 // The above query orders by FK alphabetically.
1240 // There might be cleverer ways to do this but it shouldn't change much.
1241 $cidRefs['civicrm_contact'][0] = 'primary_contact_id';
1242 $cidRefs['civicrm_contact'][1] = 'employer_id';
1243 $cidRefs['civicrm_acl_contact_cache'][0] = 'contact_id';
1244 $cidRefs['civicrm_mailing'][0] = 'created_id';
1245 $cidRefs['civicrm_mailing'][1] = 'scheduled_id';
1246 $cidRefs['civicrm_mailing'][2] = 'approver_id';