Enable 'add new' by default on merge screen
[civicrm-core.git] / tests / phpunit / CRM / Dedupe / MergerTest.php
CommitLineData
0622d221 1<?php
0622d221 2
3/**
4 * Class CRM_Dedupe_DedupeMergerTest
acb109b7 5 * @group headless
0622d221 6 */
7class CRM_Dedupe_MergerTest extends CiviUnitTestCase {
8
9 protected $_groupId;
10 protected $_contactIds = array();
11
3308aac0 12 public function tearDown() {
13 $this->quickCleanup(array('civicrm_contact', 'civicrm_group_contact', 'civicrm_group'));
14 parent::tearDown();
15 }
16
0622d221 17 public function createDupeContacts() {
18 // create a group to hold contacts, so that dupe checks don't consider any other contacts in the DB
19 $params = array(
20 'name' => 'Test Dupe Merger Group',
21 'title' => 'Test Dupe Merger Group',
22 'domain_id' => 1,
23 'is_active' => 1,
24 'visibility' => 'Public Pages',
0622d221 25 );
87a56b12 26
27 $result = $this->callAPISuccess('group', 'create', $params);
0622d221 28 $this->_groupId = $result['id'];
29
30 // contact data set
31
32 // make dupe checks based on based on following contact sets:
33 // FIRST - LAST - EMAIL
34 // ---------------------------------
35 // robin - hood - robin@example.com
36 // robin - hood - robin@example.com
37 // robin - hood - hood@example.com
38 // robin - dale - robin@example.com
39 // little - dale - dale@example.com
40 // little - dale - dale@example.com
41 // will - dale - dale@example.com
42 // will - dale - will@example.com
43 // will - dale - will@example.com
44 $params = array(
45 array(
46 'first_name' => 'robin',
47 'last_name' => 'hood',
48 'email' => 'robin@example.com',
49 'contact_type' => 'Individual',
50 ),
51 array(
52 'first_name' => 'robin',
53 'last_name' => 'hood',
54 'email' => 'robin@example.com',
55 'contact_type' => 'Individual',
56 ),
57 array(
58 'first_name' => 'robin',
59 'last_name' => 'hood',
60 'email' => 'hood@example.com',
61 'contact_type' => 'Individual',
62 ),
63 array(
64 'first_name' => 'robin',
65 'last_name' => 'dale',
66 'email' => 'robin@example.com',
67 'contact_type' => 'Individual',
68 ),
69 array(
70 'first_name' => 'little',
71 'last_name' => 'dale',
72 'email' => 'dale@example.com',
73 'contact_type' => 'Individual',
74 ),
75 array(
76 'first_name' => 'little',
77 'last_name' => 'dale',
78 'email' => 'dale@example.com',
79 'contact_type' => 'Individual',
80 ),
81 array(
82 'first_name' => 'will',
83 'last_name' => 'dale',
84 'email' => 'dale@example.com',
85 'contact_type' => 'Individual',
86 ),
87 array(
88 'first_name' => 'will',
89 'last_name' => 'dale',
90 'email' => 'will@example.com',
91 'contact_type' => 'Individual',
92 ),
93 array(
94 'first_name' => 'will',
95 'last_name' => 'dale',
96 'email' => 'will@example.com',
97 'contact_type' => 'Individual',
98 ),
99 );
100
101 $count = 1;
102 foreach ($params as $param) {
103 $param['version'] = 3;
104 $contact = civicrm_api('contact', 'create', $param);
105 $this->_contactIds[$count++] = $contact['id'];
106
107 $grpParams = array(
108 'contact_id' => $contact['id'],
109 'group_id' => $this->_groupId,
110 'version' => 3,
111 );
87a56b12 112 $this->callAPISuccess('group_contact', 'create', $grpParams);
0622d221 113 }
114 }
115
93ac19cd 116 /**
117 * Delete all created contacts.
118 */
0622d221 119 public function deleteDupeContacts() {
0622d221 120 foreach ($this->_contactIds as $contactId) {
93ac19cd 121 $this->contactDelete($contactId);
0622d221 122 }
87a56b12 123 $this->groupDelete($this->_groupId);
0622d221 124 }
125
c8ec0753 126 /**
a354251e 127 * Test the batch merge.
c8ec0753 128 */
0622d221 129 public function testBatchMergeSelectedDuplicates() {
130 $this->createDupeContacts();
131
132 // verify that all contacts have been created separately
133 $this->assertEquals(count($this->_contactIds), 9, 'Check for number of contacts.');
134
135 $dao = new CRM_Dedupe_DAO_RuleGroup();
136 $dao->contact_type = 'Individual';
137 $dao->name = 'IndividualSupervised';
138 $dao->is_default = 1;
139 $dao->find(TRUE);
140
141 $foundDupes = CRM_Dedupe_Finder::dupesInGroup($dao->id, $this->_groupId);
142
143 // -------------------------------------------------------------------------
144 // Name and Email (reserved) Matches ( 3 pairs )
145 // --------------------------------------------------------------------------
146 // robin - hood - robin@example.com
147 // robin - hood - robin@example.com
148 // little - dale - dale@example.com
149 // little - dale - dale@example.com
150 // will - dale - will@example.com
151 // will - dale - will@example.com
152 // so 3 pairs for - first + last + mail
153 $this->assertEquals(count($foundDupes), 3, 'Check Individual-Supervised dupe rule for dupesInGroup().');
154
155 // Run dedupe finder as the browser would
156 $_SERVER['REQUEST_METHOD'] = 'GET'; //avoid invalid key error
157 $object = new CRM_Contact_Page_DedupeFind();
158 $object->set('gid', $this->_groupId);
159 $object->set('rgid', $dao->id);
160 $object->set('action', CRM_Core_Action::UPDATE);
64fe2fe0 161 $object->setEmbedded(TRUE);
0622d221 162 @$object->run();
163
164 // Retrieve pairs from prev next cache table
165 $select = array('pn.is_selected' => 'is_selected');
b1679439 166 $cacheKeyString = CRM_Dedupe_Merger::getMergeCacheKeyString($dao->id, $this->_groupId);
0622d221 167 $pnDupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, NULL, NULL, 0, 0, $select);
168
169 $this->assertEquals(count($foundDupes), count($pnDupePairs), 'Check number of dupe pairs in prev next cache.');
170
171 // mark first two pairs as selected
172 CRM_Core_DAO::singleValueQuery("UPDATE civicrm_prevnext_cache SET is_selected = 1 WHERE id IN ({$pnDupePairs[0]['prevnext_id']}, {$pnDupePairs[1]['prevnext_id']})");
173
174 $pnDupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, NULL, NULL, 0, 0, $select);
175 $this->assertEquals($pnDupePairs[0]['is_selected'], 1, 'Check if first record in dupe pairs is marked as selected.');
176 $this->assertEquals($pnDupePairs[0]['is_selected'], 1, 'Check if second record in dupe pairs is marked as selected.');
177
178 // batch merge selected dupes
d13a105a 179 $result = CRM_Dedupe_Merger::batchMerge($dao->id, $this->_groupId, 'safe', 5, 1);
0622d221 180 $this->assertEquals(count($result['merged']), 2, 'Check number of merged pairs.');
181
182 // retrieve pairs from prev next cache table
183 $pnDupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, NULL, NULL, 0, 0, $select);
184 $this->assertEquals(count($pnDupePairs), 1, 'Check number of remaining dupe pairs in prev next cache.');
185
186 $this->deleteDupeContacts();
187 }
188
c8ec0753 189 /**
a354251e 190 * Test the batch merge.
c8ec0753 191 */
0622d221 192 public function testBatchMergeAllDuplicates() {
193 $this->createDupeContacts();
194
195 // verify that all contacts have been created separately
196 $this->assertEquals(count($this->_contactIds), 9, 'Check for number of contacts.');
197
198 $dao = new CRM_Dedupe_DAO_RuleGroup();
199 $dao->contact_type = 'Individual';
200 $dao->name = 'IndividualSupervised';
201 $dao->is_default = 1;
202 $dao->find(TRUE);
203
204 $foundDupes = CRM_Dedupe_Finder::dupesInGroup($dao->id, $this->_groupId);
205
206 // -------------------------------------------------------------------------
207 // Name and Email (reserved) Matches ( 3 pairs )
208 // --------------------------------------------------------------------------
209 // robin - hood - robin@example.com
210 // robin - hood - robin@example.com
211 // little - dale - dale@example.com
212 // little - dale - dale@example.com
213 // will - dale - will@example.com
214 // will - dale - will@example.com
215 // so 3 pairs for - first + last + mail
216 $this->assertEquals(count($foundDupes), 3, 'Check Individual-Supervised dupe rule for dupesInGroup().');
217
218 // Run dedupe finder as the browser would
219 $_SERVER['REQUEST_METHOD'] = 'GET'; //avoid invalid key error
220 $object = new CRM_Contact_Page_DedupeFind();
221 $object->set('gid', $this->_groupId);
222 $object->set('rgid', $dao->id);
223 $object->set('action', CRM_Core_Action::UPDATE);
64fe2fe0 224 $object->setEmbedded(TRUE);
0622d221 225 @$object->run();
226
227 // Retrieve pairs from prev next cache table
228 $select = array('pn.is_selected' => 'is_selected');
b1679439 229 $cacheKeyString = CRM_Dedupe_Merger::getMergeCacheKeyString($dao->id, $this->_groupId);
0622d221 230 $pnDupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, NULL, NULL, 0, 0, $select);
231
232 $this->assertEquals(count($foundDupes), count($pnDupePairs), 'Check number of dupe pairs in prev next cache.');
233
234 // batch merge all dupes
d13a105a 235 $result = CRM_Dedupe_Merger::batchMerge($dao->id, $this->_groupId, 'safe', 5, 2);
0622d221 236 $this->assertEquals(count($result['merged']), 3, 'Check number of merged pairs.');
237
238 // retrieve pairs from prev next cache table
239 $pnDupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, NULL, NULL, 0, 0, $select);
240 $this->assertEquals(count($pnDupePairs), 0, 'Check number of remaining dupe pairs in prev next cache.');
241
242 $this->deleteDupeContacts();
243 }
244
bf17fa88 245 /**
246 * The goal of this function is to test that all required tables are returned.
247 */
248 public function testGetCidRefs() {
249 $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__, 'Contacts');
250 $this->assertEquals(array_merge($this->getStaticCIDRefs(), $this->getHackedInCIDRef()), CRM_Dedupe_Merger::cidRefs());
251 $this->assertEquals(array_merge($this->getCalculatedCIDRefs(), $this->getHackedInCIDRef()), CRM_Dedupe_Merger::cidRefs());
252 }
253
254 /**
255 * Get the list of not-really-cid-refs that are currently hacked in.
256 *
257 * This is hacked into getCIDs function.
258 *
259 * @return array
260 */
261 public function getHackedInCIDRef() {
262 return array(
263 'civicrm_entity_tag' => array(
264 0 => 'entity_id',
265 ),
266 );
267 }
268
2988f5c7 269 /**
270 * Test function that gets duplicate pairs.
271 *
272 * It turns out there are 2 code paths retrieving this data so my initial focus is on ensuring
273 * they match.
274 */
275 public function testGetMatches() {
276 $this->setupMatchData();
277 $pairs = CRM_Dedupe_Merger::getDuplicatePairs(
278 1,
279 NULL,
280 TRUE,
281 25,
282 FALSE
283 );
284
285 $this->assertEquals(array(
286 0 => array(
08cde01f 287 'srcID' => $this->contacts[1]['id'],
2988f5c7 288 'srcName' => 'Mr. Mickey Mouse II',
08cde01f 289 'dstID' => $this->contacts[0]['id'],
2988f5c7 290 'dstName' => 'Mr. Mickey Mouse II',
291 'weight' => 20,
292 'canMerge' => TRUE,
293 ),
3308aac0 294 1 => array(
08cde01f 295 'srcID' => $this->contacts[3]['id'],
3308aac0 296 'srcName' => 'Mr. Minnie Mouse II',
08cde01f 297 'dstID' => $this->contacts[2]['id'],
3308aac0 298 'dstName' => 'Mr. Minnie Mouse II',
299 'weight' => 20,
300 'canMerge' => TRUE,
301 ),
2988f5c7 302 ), $pairs);
303 }
304
bc0f3965 305 /**
306 * Test function that gets organization pairs.
307 *
308 * Note the rule will match on organization_name OR email - hence lots of matches.
309 */
310 public function testGetOrganizationMatches() {
311 $this->setupMatchData();
312 $ruleGroups = $this->callAPISuccessGetSingle('RuleGroup', array('contact_type' => 'Organization', 'used' => 'Supervised'));
313
314 $pairs = CRM_Dedupe_Merger::getDuplicatePairs(
315 $ruleGroups['id'],
316 NULL,
317 TRUE,
318 25,
319 FALSE
320 );
321
72475b30 322 $expectedPairs = array(
bc0f3965 323 0 => array(
324 'srcID' => $this->contacts[5]['id'],
325 'srcName' => 'Walt Disney Ltd',
326 'dstID' => $this->contacts[4]['id'],
327 'dstName' => 'Walt Disney Ltd',
328 'weight' => 20,
329 'canMerge' => TRUE,
330 ),
331 1 => array(
332 'srcID' => $this->contacts[7]['id'],
333 'srcName' => 'Walt Disney',
334 'dstID' => $this->contacts[6]['id'],
335 'dstName' => 'Walt Disney',
336 'weight' => 10,
337 'canMerge' => TRUE,
338 ),
339 2 => array(
340 'srcID' => $this->contacts[6]['id'],
341 'srcName' => 'Walt Disney',
342 'dstID' => $this->contacts[4]['id'],
343 'dstName' => 'Walt Disney Ltd',
344 'weight' => 10,
345 'canMerge' => TRUE,
346 ),
347 3 => array(
348 'srcID' => $this->contacts[6]['id'],
349 'srcName' => 'Walt Disney',
350 'dstID' => $this->contacts[5]['id'],
351 'dstName' => 'Walt Disney Ltd',
352 'weight' => 10,
353 'canMerge' => TRUE,
354 ),
72475b30
TO
355 );
356 usort($pairs, array(__CLASS__, 'compareDupes'));
357 usort($expectedPairs, array(__CLASS__, 'compareDupes'));
358 $this->assertEquals($expectedPairs, $pairs);
359 }
360
361 /**
362 * Function to sort $duplicate records in a stable way.
363 *
364 * @param array $a
365 * @param array $b
366 * @return int
367 */
368 public static function compareDupes($a, $b) {
369 foreach (array('srcName', 'dstName', 'srcID', 'dstID') as $field) {
370 if ($a[$field] != $b[$field]) {
371 return ($a[$field] < $b[$field]) ? 1 : -1;
372 }
373 }
374 return 0;
bc0f3965 375 }
376
377 /**
378 * Test function that gets organization duplicate pairs.
379 */
380 public function testGetOrganizationMatchesInGroup() {
381 $this->setupMatchData();
382 $ruleGroups = $this->callAPISuccessGetSingle('RuleGroup', array('contact_type' => 'Organization', 'used' => 'Supervised'));
383
384 $groupID = $this->groupCreate(array('title' => 'she-mice'));
385
386 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupID, 'contact_id' => $this->contacts[4]['id']));
387
388 $pairs = CRM_Dedupe_Merger::getDuplicatePairs(
389 $ruleGroups['id'],
390 $groupID,
391 TRUE,
392 25,
393 FALSE
394 );
395
396 $this->assertEquals(array(
397 0 => array(
398 'srcID' => $this->contacts[5]['id'],
399 'srcName' => 'Walt Disney Ltd',
400 'dstID' => $this->contacts[4]['id'],
401 'dstName' => 'Walt Disney Ltd',
402 'weight' => 20,
403 'canMerge' => TRUE,
404 ),
405 1 => array(
406 'srcID' => $this->contacts[6]['id'],
407 'srcName' => 'Walt Disney',
408 'dstID' => $this->contacts[4]['id'],
409 'dstName' => 'Walt Disney Ltd',
410 'weight' => 10,
411 'canMerge' => TRUE,
412 ),
413 ), $pairs);
be61083d 414
415 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupID, 'contact_id' => $this->contacts[5]['id']));
416 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_prevnext_cache");
417 $pairs = CRM_Dedupe_Merger::getDuplicatePairs(
418 $ruleGroups['id'],
419 $groupID,
420 TRUE,
421 25,
422 FALSE
423 );
424
425 $this->assertEquals(array(
426 0 => array(
427 'srcID' => $this->contacts[5]['id'],
428 'srcName' => 'Walt Disney Ltd',
429 'dstID' => $this->contacts[4]['id'],
430 'dstName' => 'Walt Disney Ltd',
431 'weight' => 20,
432 'canMerge' => TRUE,
433 ),
434 1 => array(
435 'srcID' => $this->contacts[6]['id'],
436 'srcName' => 'Walt Disney',
437 'dstID' => $this->contacts[4]['id'],
438 'dstName' => 'Walt Disney Ltd',
439 'weight' => 10,
440 'canMerge' => TRUE,
441 ),
442 2 => array(
443 'srcID' => $this->contacts[6]['id'],
444 'srcName' => 'Walt Disney',
445 'dstID' => $this->contacts[5]['id'],
446 'dstName' => 'Walt Disney Ltd',
447 'weight' => 10,
448 'canMerge' => TRUE,
449 ),
450 ), $pairs);
bc0f3965 451 }
452
3308aac0 453 /**
454 * Test function that gets duplicate pairs.
455 *
456 * It turns out there are 2 code paths retrieving this data so my initial focus is on ensuring
457 * they match.
458 */
459 public function testGetMatchesInGroup() {
460 $this->setupMatchData();
461
462 $groupID = $this->groupCreate(array('title' => 'she-mice'));
463
464 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupID, 'contact_id' => $this->contacts[3]['id']));
465
466 $pairs = CRM_Dedupe_Merger::getDuplicatePairs(
467 1,
468 $groupID,
469 TRUE,
470 25,
471 FALSE
472 );
473
474 $this->assertEquals(array(
475 0 => array(
476 'srcID' => $this->contacts[3]['id'],
477 'srcName' => 'Mr. Minnie Mouse II',
478 'dstID' => $this->contacts[2]['id'],
479 'dstName' => 'Mr. Minnie Mouse II',
480 'weight' => 20,
481 'canMerge' => TRUE,
482 ),
483 ), $pairs);
484 }
485
0946ab3f 486 /**
487 * CRM-19653 : Test that custom field data should/shouldn't be overriden on
488 * selecting/not selecting option to migrate data respectively
489 */
490 public function testCustomDataOverwrite() {
dba77ae8
CR
491 // Create Custom Field
492 $createGroup = $this->setupCustomGroupForIndividual();
493 $createField = $this->setupCustomField('Graduation', $createGroup);
494 $customFieldName = "custom_" . $createField['id'];
495
496 // Contacts setup
0946ab3f 497 $this->setupMatchData();
498
499 $originalContactID = $this->contacts[0]['id'];
500 $duplicateContactID1 = $this->contacts[1]['id']; // used as duplicate contact in 1st use-case
501 $duplicateContactID2 = $this->contacts[2]['id']; // used as duplicate contact in 2nd use-case
502
0946ab3f 503 // update the text custom field for original contact with value 'abc'
504 $this->callAPISuccess('Contact', 'create', array(
505 'id' => $originalContactID,
dba77ae8 506 "{$customFieldName}" => 'abc',
0946ab3f 507 ));
dba77ae8
CR
508 $this->assertCustomFieldValue($originalContactID, 'abc', $customFieldName);
509
0946ab3f 510 // update the text custom field for duplicate contact 1 with value 'def'
511 $this->callAPISuccess('Contact', 'create', array(
512 'id' => $duplicateContactID1,
dba77ae8 513 "{$customFieldName}" => 'def',
0946ab3f 514 ));
dba77ae8
CR
515 $this->assertCustomFieldValue($duplicateContactID1, 'def', $customFieldName);
516
0946ab3f 517 // update the text custom field for duplicate contact 2 with value 'ghi'
518 $this->callAPISuccess('Contact', 'create', array(
519 'id' => $duplicateContactID2,
dba77ae8 520 "{$customFieldName}" => 'ghi',
0946ab3f 521 ));
dba77ae8 522 $this->assertCustomFieldValue($duplicateContactID2, 'ghi', $customFieldName);
0946ab3f 523
524 /*** USE-CASE 1: DO NOT OVERWRITE CUSTOM FIELD VALUE **/
dba77ae8 525 $this->mergeContacts($originalContactID, $duplicateContactID1, array(
ee3b1d86 526 "move_{$customFieldName}" => NULL,
0946ab3f 527 ));
dba77ae8 528 $this->assertCustomFieldValue($originalContactID, 'abc', $customFieldName);
0946ab3f 529
530 /*** USE-CASE 2: OVERWRITE CUSTOM FIELD VALUE **/
dba77ae8
CR
531 $this->mergeContacts($originalContactID, $duplicateContactID2, array(
532 "move_{$customFieldName}" => 'ghi',
533 ));
534 $this->assertCustomFieldValue($originalContactID, 'ghi', $customFieldName);
535
536 // cleanup created custom set
537 $this->callAPISuccess('CustomField', 'delete', array('id' => $createField['id']));
538 $this->callAPISuccess('CustomGroup', 'delete', array('id' => $createGroup['id']));
539 }
540
541 /**
542 * Verifies that when a contact with a custom field value is merged into a
543 * contact without a record int its corresponding custom group table, and none
544 * of the custom fields of that custom table are selected, the value is not
545 * merged in.
546 */
547 public function testMigrationOfUnselectedCustomDataOnEmptyCustomRecord() {
548 // Create Custom Fields
549 $createGroup = $this->setupCustomGroupForIndividual();
550 $customField1 = $this->setupCustomField('TestField', $createGroup);
551
c1955865
J
552 // Create multi-value custom field
553 $multiGroup = $this->CustomGroupMultipleCreateByParams();
554 $multiField = $this->customFieldCreate(array(
555 'custom_group_id' => $multiGroup['id'],
556 'label' => 'field_1' . $multiGroup['id'],
557 'in_selector' => 1,
558 ));
559
dba77ae8
CR
560 // Contacts setup
561 $this->setupMatchData();
562 $originalContactID = $this->contacts[0]['id'];
563 $duplicateContactID = $this->contacts[1]['id'];
564
565 // Update the text custom fields for duplicate contact
566 $this->callAPISuccess('Contact', 'create', array(
567 'id' => $duplicateContactID,
568 "custom_{$customField1['id']}" => 'abc',
c1955865 569 "custom_{$multiField['id']}" => 'def',
dba77ae8
CR
570 ));
571 $this->assertCustomFieldValue($duplicateContactID, 'abc', "custom_{$customField1['id']}");
c1955865 572 $this->assertCustomFieldValue($duplicateContactID, 'def', "custom_{$multiField['id']}");
dba77ae8 573
c1955865 574 // Merge, and ensure that no value was migrated
dba77ae8 575 $this->mergeContacts($originalContactID, $duplicateContactID, array(
ee3b1d86 576 "move_custom_{$customField1['id']}" => NULL,
c1955865 577 "move_rel_table_custom_{$multiGroup['id']}" => NULL,
dba77ae8
CR
578 ));
579 $this->assertCustomFieldValue($originalContactID, '', "custom_{$customField1['id']}");
c1955865 580 $this->assertCustomFieldValue($originalContactID, '', "custom_{$multiField['id']}");
dba77ae8
CR
581
582 // cleanup created custom set
583 $this->callAPISuccess('CustomField', 'delete', array('id' => $customField1['id']));
584 $this->callAPISuccess('CustomGroup', 'delete', array('id' => $createGroup['id']));
c1955865
J
585 $this->callAPISuccess('CustomField', 'delete', array('id' => $multiField['id']));
586 $this->callAPISuccess('CustomGroup', 'delete', array('id' => $multiGroup['id']));
dba77ae8
CR
587 }
588
589 /**
590 * Tests that if only part of the custom fields of a custom group are selected
591 * for a merge, only those values are merged, while all other fields of the
592 * custom group retain their original value, specifically for a contact with
593 * no records on the custom group table.
594 */
595 public function testMigrationOfSomeCustomDataOnEmptyCustomRecord() {
596 // Create Custom Fields
597 $createGroup = $this->setupCustomGroupForIndividual();
598 $customField1 = $this->setupCustomField('Test1', $createGroup);
599 $customField2 = $this->setupCustomField('Test2', $createGroup);
600
c1955865
J
601 // Create multi-value custom field
602 $multiGroup = $this->CustomGroupMultipleCreateByParams();
603 $multiField = $this->customFieldCreate(array(
604 'custom_group_id' => $multiGroup['id'],
605 'label' => 'field_1' . $multiGroup['id'],
606 'in_selector' => 1,
607 ));
608
dba77ae8
CR
609 // Contacts setup
610 $this->setupMatchData();
611 $originalContactID = $this->contacts[0]['id'];
612 $duplicateContactID = $this->contacts[1]['id'];
613
614 // Update the text custom fields for duplicate contact
615 $this->callAPISuccess('Contact', 'create', array(
616 'id' => $duplicateContactID,
617 "custom_{$customField1['id']}" => 'abc',
618 "custom_{$customField2['id']}" => 'def',
c1955865 619 "custom_{$multiField['id']}" => 'ghi',
dba77ae8
CR
620 ));
621 $this->assertCustomFieldValue($duplicateContactID, 'abc', "custom_{$customField1['id']}");
622 $this->assertCustomFieldValue($duplicateContactID, 'def', "custom_{$customField2['id']}");
c1955865 623 $this->assertCustomFieldValue($duplicateContactID, 'ghi', "custom_{$multiField['id']}");
dba77ae8
CR
624
625 // Perform merge
626 $this->mergeContacts($originalContactID, $duplicateContactID, array(
ee3b1d86 627 "move_custom_{$customField1['id']}" => NULL,
dba77ae8 628 "move_custom_{$customField2['id']}" => 'def',
c1955865 629 "move_rel_table_custom_{$multiGroup['id']}" => '1',
dba77ae8
CR
630 ));
631 $this->assertCustomFieldValue($originalContactID, '', "custom_{$customField1['id']}");
632 $this->assertCustomFieldValue($originalContactID, 'def', "custom_{$customField2['id']}");
c1955865 633 $this->assertCustomFieldValue($originalContactID, 'ghi', "custom_{$multiField['id']}");
dba77ae8
CR
634
635 // cleanup created custom set
636 $this->callAPISuccess('CustomField', 'delete', array('id' => $customField1['id']));
637 $this->callAPISuccess('CustomField', 'delete', array('id' => $customField2['id']));
638 $this->callAPISuccess('CustomGroup', 'delete', array('id' => $createGroup['id']));
c1955865
J
639 $this->callAPISuccess('CustomField', 'delete', array('id' => $multiField['id']));
640 $this->callAPISuccess('CustomGroup', 'delete', array('id' => $multiGroup['id']));
dba77ae8
CR
641 }
642
643 /**
644 * Calls merge method on given contacts, with values given in $params array.
645 *
646 * @param $originalContactID
647 * ID of target contact
648 * @param $duplicateContactID
649 * ID of contact to be merged
650 * @param $params
651 * Array of fields to be merged from source into target contact, of the form
652 * ['move_<fieldName>' => <fieldValue>]
653 */
654 private function mergeContacts($originalContactID, $duplicateContactID, $params) {
655 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($originalContactID, $duplicateContactID);
656
0946ab3f 657 $migrationData = array(
658 'main_details' => $rowsElementsAndInfo['main_details'],
659 'other_details' => $rowsElementsAndInfo['other_details'],
0946ab3f 660 );
dba77ae8
CR
661
662 // Migrate data of duplicate contact
663 CRM_Dedupe_Merger::moveAllBelongings($originalContactID, $duplicateContactID, array_merge($migrationData, $params));
664 }
665
666 /**
667 * Checks if the expected value for the given field corresponds to what is
668 * stored in the database for the given contact ID.
669 *
670 * @param $contactID
671 * @param $expectedValue
672 * @param $customFieldName
673 */
674 private function assertCustomFieldValue($contactID, $expectedValue, $customFieldName) {
0946ab3f 675 $data = $this->callAPISuccess('Contact', 'getsingle', array(
dba77ae8 676 'id' => $contactID,
0946ab3f 677 'return' => array($customFieldName),
678 ));
0946ab3f 679
dba77ae8
CR
680 $this->assertEquals($expectedValue, $data[$customFieldName], "Custom field value was supposed to be '{$expectedValue}', '{$data[$customFieldName]}' found.");
681 }
682
683 /**
684 * Creates a custom group to run tests on contacts that are individuals.
685 *
686 * @return array
687 * Data for the created custom group record
688 */
689 private function setupCustomGroupForIndividual() {
690 $customGroup = $this->callAPISuccess('custom_group', 'get', array(
691 'name' => 'test_group',
692 ));
693
694 if ($customGroup['count'] > 0) {
695 $this->callAPISuccess('CustomGroup', 'delete', array('id' => $customGroup['id']));
696 }
697
698 $customGroup = $this->callAPISuccess('custom_group', 'create', array(
699 'title' => 'Test_Group',
700 'name' => 'test_group',
701 'extends' => array('Individual'),
702 'style' => 'Inline',
703 'is_multiple' => FALSE,
704 'is_active' => 1,
705 ));
706
707 return $customGroup;
708 }
709
710 /**
711 * Creates a custom field on the provided custom group with the given field
712 * label.
713 *
714 * @param $fieldLabel
715 * @param $createGroup
716 *
717 * @return array
718 * Data for the created custom field record
719 */
720 private function setupCustomField($fieldLabel, $createGroup) {
721 return $this->callAPISuccess('custom_field', 'create', array(
722 'label' => $fieldLabel,
723 'data_type' => 'Alphanumeric',
724 'html_type' => 'Text',
725 'custom_group_id' => $createGroup['id'],
726 ));
0946ab3f 727 }
728
3308aac0 729 /**
730 * Set up some contacts for our matching.
731 */
2988f5c7 732 public function setupMatchData() {
733 $fixtures = array(
734 array(
735 'first_name' => 'Mickey',
736 'last_name' => 'Mouse',
737 'email' => 'mickey@mouse.com',
738 ),
739 array(
740 'first_name' => 'Mickey',
741 'last_name' => 'Mouse',
742 'email' => 'mickey@mouse.com',
743 ),
744 array(
745 'first_name' => 'Minnie',
746 'last_name' => 'Mouse',
747 'email' => 'mickey@mouse.com',
748 ),
3308aac0 749 array(
750 'first_name' => 'Minnie',
751 'last_name' => 'Mouse',
752 'email' => 'mickey@mouse.com',
753 ),
2988f5c7 754 );
755 foreach ($fixtures as $fixture) {
756 $contactID = $this->individualCreate($fixture);
757 $this->contacts[] = array_merge($fixture, array('id' => $contactID));
bc0f3965 758 }
759 $organizationFixtures = array(
760 array(
761 'organization_name' => 'Walt Disney Ltd',
762 'email' => 'walt@disney.com',
763 ),
764 array(
765 'organization_name' => 'Walt Disney Ltd',
766 'email' => 'walt@disney.com',
767 ),
768 array(
769 'organization_name' => 'Walt Disney',
770 'email' => 'walt@disney.com',
771 ),
772 array(
773 'organization_name' => 'Walt Disney',
774 'email' => 'walter@disney.com',
775 ),
776 );
777 foreach ($organizationFixtures as $fixture) {
778 $contactID = $this->organizationCreate($fixture);
779 $this->contacts[] = array_merge($fixture, array('id' => $contactID));
2988f5c7 780 }
781 }
782
783
bf17fa88 784 /**
785 * Get the list of tables that refer to the CID.
786 *
787 * This is a statically maintained (in this test list).
788 *
789 * There is also a check against an automated list but having both seems to add extra stability to me. They do
790 * not change often.
791 */
792 public function getStaticCIDRefs() {
793 return array(
794 'civicrm_acl_cache' => array(
795 0 => 'contact_id',
796 ),
797 'civicrm_acl_contact_cache' => array(
dbb4e4f9 798 0 => 'contact_id',
bf17fa88 799 ),
800 'civicrm_action_log' => array(
801 0 => 'contact_id',
802 ),
803 'civicrm_activity_contact' => array(
804 0 => 'contact_id',
805 ),
806 'civicrm_address' => array(
807 0 => 'contact_id',
808 ),
809 'civicrm_batch' => array(
810 0 => 'created_id',
811 1 => 'modified_id',
812 ),
813 'civicrm_campaign' => array(
814 0 => 'created_id',
815 1 => 'last_modified_id',
816 ),
817 'civicrm_case_contact' => array(
818 0 => 'contact_id',
819 ),
820 'civicrm_contact' => array(
821 0 => 'primary_contact_id',
822 1 => 'employer_id',
823 ),
824 'civicrm_contribution' => array(
825 0 => 'contact_id',
826 ),
827 'civicrm_contribution_page' => array(
828 0 => 'created_id',
829 ),
830 'civicrm_contribution_recur' => array(
831 0 => 'contact_id',
832 ),
833 'civicrm_contribution_soft' => array(
834 0 => 'contact_id',
835 ),
836 'civicrm_custom_group' => array(
837 0 => 'created_id',
838 ),
839 'civicrm_dashboard_contact' => array(
840 0 => 'contact_id',
841 ),
842 'civicrm_dedupe_exception' => array(
843 0 => 'contact_id1',
844 1 => 'contact_id2',
845 ),
846 'civicrm_domain' => array(
847 0 => 'contact_id',
848 ),
849 'civicrm_email' => array(
850 0 => 'contact_id',
851 ),
852 'civicrm_event' => array(
853 0 => 'created_id',
854 ),
855 'civicrm_event_carts' => array(
856 0 => 'user_id',
857 ),
858 'civicrm_financial_account' => array(
859 0 => 'contact_id',
860 ),
861 'civicrm_financial_item' => array(
862 0 => 'contact_id',
863 ),
864 'civicrm_grant' => array(
865 0 => 'contact_id',
866 ),
867 'civicrm_group' => array(
868 0 => 'created_id',
869 1 => 'modified_id',
870 ),
871 'civicrm_group_contact' => array(
872 0 => 'contact_id',
873 ),
874 'civicrm_group_contact_cache' => array(
875 0 => 'contact_id',
876 ),
877 'civicrm_group_organization' => array(
878 0 => 'organization_id',
879 ),
880 'civicrm_im' => array(
881 0 => 'contact_id',
882 ),
883 'civicrm_log' => array(
884 0 => 'modified_id',
885 ),
886 'civicrm_mailing' => array(
887 0 => 'created_id',
888 1 => 'scheduled_id',
889 2 => 'approver_id',
890 ),
ae2c7e00 891 'civicrm_file' => array(
892 'created_id',
893 ),
bf17fa88 894 'civicrm_mailing_abtest' => array(
895 0 => 'created_id',
896 ),
897 'civicrm_mailing_event_queue' => array(
898 0 => 'contact_id',
899 ),
900 'civicrm_mailing_event_subscribe' => array(
901 0 => 'contact_id',
902 ),
903 'civicrm_mailing_recipients' => array(
904 0 => 'contact_id',
905 ),
906 'civicrm_membership' => array(
907 0 => 'contact_id',
908 ),
909 'civicrm_membership_log' => array(
910 0 => 'modified_id',
911 ),
912 'civicrm_membership_type' => array(
913 0 => 'member_of_contact_id',
914 ),
915 'civicrm_note' => array(
916 0 => 'contact_id',
917 ),
918 'civicrm_openid' => array(
919 0 => 'contact_id',
920 ),
921 'civicrm_participant' => array(
922 0 => 'contact_id',
101d0fef 923 1 => 'transferred_to_contact_id', //CRM-16761
bf17fa88 924 ),
925 'civicrm_payment_token' => array(
926 0 => 'contact_id',
927 1 => 'created_id',
928 ),
929 'civicrm_pcp' => array(
930 0 => 'contact_id',
931 ),
932 'civicrm_phone' => array(
933 0 => 'contact_id',
934 ),
935 'civicrm_pledge' => array(
936 0 => 'contact_id',
937 ),
938 'civicrm_print_label' => array(
939 0 => 'created_id',
940 ),
941 'civicrm_relationship' => array(
942 0 => 'contact_id_a',
943 1 => 'contact_id_b',
944 ),
945 'civicrm_report_instance' => array(
946 0 => 'created_id',
947 1 => 'owner_id',
948 ),
949 'civicrm_setting' => array(
950 0 => 'contact_id',
951 1 => 'created_id',
952 ),
953 'civicrm_subscription_history' => array(
954 0 => 'contact_id',
955 ),
956 'civicrm_survey' => array(
957 0 => 'created_id',
958 1 => 'last_modified_id',
959 ),
960 'civicrm_tag' => array(
961 0 => 'created_id',
962 ),
963 'civicrm_uf_group' => array(
964 0 => 'created_id',
965 ),
966 'civicrm_uf_match' => array(
967 0 => 'contact_id',
968 ),
969 'civicrm_value_testgetcidref_1' => array(
970 0 => 'entity_id',
971 ),
972 'civicrm_website' => array(
973 0 => 'contact_id',
974 ),
975 );
976 }
977
978 /**
979 * Get a list of CIDs that is calculated off the schema.
980 *
981 * Note this is an expensive and table locking query. Should be safe in tests though.
982 */
983 public function getCalculatedCIDRefs() {
984 $cidRefs = array();
985 $sql = "
986SELECT
987 table_name,
988 column_name
989FROM information_schema.key_column_usage
990WHERE
991 referenced_table_schema = database() AND
992 referenced_table_name = 'civicrm_contact' AND
993 referenced_column_name = 'id';
994 ";
995 $dao = CRM_Core_DAO::executeQuery($sql);
996 while ($dao->fetch()) {
997 $cidRefs[$dao->table_name][] = $dao->column_name;
998 }
999 // Do specific re-ordering changes to make this the same as the ref validated one.
1000 // The above query orders by FK alphabetically.
1001 // There might be cleverer ways to do this but it shouldn't change much.
1002 $cidRefs['civicrm_contact'][0] = 'primary_contact_id';
1003 $cidRefs['civicrm_contact'][1] = 'employer_id';
dbb4e4f9 1004 $cidRefs['civicrm_acl_contact_cache'][0] = 'contact_id';
bf17fa88 1005 $cidRefs['civicrm_mailing'][0] = 'created_id';
1006 $cidRefs['civicrm_mailing'][1] = 'scheduled_id';
1007 $cidRefs['civicrm_mailing'][2] = 'approver_id';
1008 return $cidRefs;
1009 }
1010
0622d221 1011}