4 * Class CRM_Activity_BAO_ActivityTest
7 class CRM_Activity_BAO_ActivityTest
extends CiviUnitTestCase
{
8 public function setUp() {
10 $this->prepareForACLs();
11 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('view all contacts', 'access CiviCRM');
12 $this->setupForSmsTests();
16 * Clean up after tests.
18 public function tearDown() {
19 $tablesToTruncate = array(
21 'civicrm_activity_contact',
26 $this->quickCleanup($tablesToTruncate);
27 $this->cleanUpAfterACLs();
28 $this->setupForSmsTests(TRUE);
33 * Setup or clean up SMS tests
34 * @param bool $teardown
36 * @throws \CiviCRM_API3_Exception
38 public function setupForSmsTests($teardown = FALSE) {
39 require_once 'CiviTest/CiviTestSMSProvider.php';
41 // Option value params for CiviTestSMSProvider
42 $groupID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
44 'option_group_id' => $groupID,
45 'label' => 'unittestSMS',
46 'value' => 'unit.test.sms',
47 'name' => 'CiviTestSMSProvider',
54 // Test completed, delete provider
55 $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
56 civicrm_api3('option_value', 'delete', array('id' => $providerOptionValueResult['id']));
60 // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
61 // in CRM/Sms/Provider.php even though it is not an extension.
62 civicrm_api3('option_value', 'create', $params);
66 * Test case for create() method.
68 public function testCreate() {
69 $contactId = $this->individualCreate();
72 'source_contact_id' => $contactId,
73 'subject' => 'Scheduling Meeting',
74 'activity_type_id' => 2,
77 CRM_Activity_BAO_Activity
::create($params);
79 $activityId = $this->assertDBNotNull('CRM_Activity_DAO_Activity', 'Scheduling Meeting', 'id',
80 'subject', 'Database check for created activity.'
83 // Now call create() to modify an existing Activity.
86 'source_contact_id' => $contactId,
87 'subject' => 'Scheduling Interview',
88 'activity_type_id' => 3,
91 CRM_Activity_BAO_Activity
::create($params);
93 $activityTypeId = $this->assertDBNotNull('CRM_Activity_DAO_Activity', 'Scheduling Interview',
95 'subject', 'Database check on updated activity record.'
97 $this->assertEquals($activityTypeId, 3, 'Verify activity type id is 3.');
99 $this->contactDelete($contactId);
103 * Test case for getContactActivity() method.
105 * getContactActivity() method get activities detail for given target contact id.
107 public function testGetContactActivity() {
108 $contactId = $this->individualCreate();
110 'first_name' => 'liz',
111 'last_name' => 'hurleey',
113 $targetContactId = $this->individualCreate($params);
116 'source_contact_id' => $contactId,
117 'subject' => 'Scheduling Meeting',
118 'activity_type_id' => 2,
119 'target_contact_id' => array($targetContactId),
120 'activity_date_time' => date('Ymd'),
123 $this->callAPISuccess('Activity', 'create', $params);
125 $activityId = $this->assertDBNotNull('CRM_Activity_DAO_Activity', 'Scheduling Meeting',
127 'subject', 'Database check for created activity.'
130 // @todo - remove this deprecated functions
131 $activities = CRM_Activity_BAO_Activity
::getContactActivity($targetContactId);
133 $this->assertEquals($activities[$activityId]['subject'], 'Scheduling Meeting', 'Verify activity subject is correct.');
135 $this->contactDelete($contactId);
136 $this->contactDelete($targetContactId);
140 * Test case for retrieve() method.
142 * Retrieve($params, $defaults) method return activity detail for given params
145 public function testRetrieve() {
146 $contactId = $this->individualCreate();
148 'first_name' => 'liz',
149 'last_name' => 'hurleey',
151 $targetContactId = $this->individualCreate($params);
154 'source_contact_id' => $contactId,
155 'subject' => 'Scheduling Meeting',
156 'activity_type_id' => 2,
157 'target_contact_id' => array($targetContactId),
158 'activity_date_time' => date('Ymd'),
161 CRM_Activity_BAO_Activity
::create($params);
163 $this->assertDBNotNull('CRM_Activity_DAO_Activity', 'Scheduling Meeting', 'id',
164 'subject', 'Database check for created activity.'
167 $this->assertDBNotNull('CRM_Activity_DAO_ActivityContact', $targetContactId,
169 'Database check for created activity target.'
173 $activity = CRM_Activity_BAO_Activity
::retrieve($params, $defaults);
175 $this->assertEquals($activity->subject
, 'Scheduling Meeting', 'Verify activity subject is correct.');
176 $this->assertEquals($activity->activity_type_id
, 2, 'Verify activity type id is correct.');
177 $this->assertEquals($defaults['source_contact_id'], $contactId, 'Verify source contact id is correct.');
179 $this->assertEquals($defaults['subject'], 'Scheduling Meeting', 'Verify activity subject is correct.');
180 $this->assertEquals($defaults['activity_type_id'], 2, 'Verify activity type id is correct.');
182 $this->assertEquals($defaults['target_contact'][0], $targetContactId, 'Verify target contact id is correct.');
184 $this->contactDelete($contactId);
185 $this->contactDelete($targetContactId);
189 * Test case for deleteActivity() method.
191 * deleteActivity($params) method deletes activity for given params.
193 public function testDeleteActivity() {
194 $contactId = $this->individualCreate();
196 'first_name' => 'liz',
197 'last_name' => 'hurleey',
199 $targetContactId = $this->individualCreate($params);
202 'source_contact_id' => $contactId,
203 'source_record_id' => $contactId,
204 'subject' => 'Scheduling Meeting',
205 'activity_type_id' => 2,
206 'target_contact_id' => array($targetContactId),
207 'activity_date_time' => date('Ymd'),
210 CRM_Activity_BAO_Activity
::create($params);
212 $this->assertDBNotNull('CRM_Activity_DAO_Activity', 'Scheduling Meeting', 'id',
213 'subject', 'Database check for created activity.'
216 $this->assertDBNotNull('CRM_Activity_DAO_ActivityContact', $targetContactId,
218 'Database check for created activity target.'
221 'source_contact_id' => $contactId,
222 'source_record_id' => $contactId,
223 'subject' => 'Scheduling Meeting',
224 'activity_type_id' => 2,
227 CRM_Activity_BAO_Activity
::deleteActivity($params);
229 $this->assertDBNull('CRM_Activity_DAO_Activity', 'Scheduling Meeting', 'id',
230 'subject', 'Database check for deleted activity.'
232 $this->contactDelete($contactId);
233 $this->contactDelete($targetContactId);
237 * Test case for deleteActivityTarget() method.
239 * deleteActivityTarget($activityId) method deletes activity target for given activity id.
241 public function testDeleteActivityTarget() {
242 $contactId = $this->individualCreate();
244 'first_name' => 'liz',
245 'last_name' => 'hurleey',
247 $targetContactId = $this->individualCreate($params);
250 'source_contact_id' => $contactId,
251 'subject' => 'Scheduling Meeting',
252 'activity_type_id' => 2,
253 'target_contact_id' => array($targetContactId),
254 'activity_date_time' => date('Ymd'),
257 CRM_Activity_BAO_Activity
::create($params);
259 $activityId = $this->assertDBNotNull('CRM_Activity_DAO_Activity', 'Scheduling Meeting', 'id',
260 'subject', 'Database check for created activity.'
263 $this->assertDBNotNull('CRM_Activity_DAO_ActivityContact', $targetContactId,
265 'Database check for created activity target.'
268 CRM_Activity_BAO_Activity
::deleteActivityContact($activityId, 3);
270 $this->assertDBNull('CRM_Activity_DAO_ActivityContact', $targetContactId, 'id',
271 'contact_id', 'Database check for deleted activity target.'
274 $this->contactDelete($contactId);
275 $this->contactDelete($targetContactId);
279 * Test case for deleteActivityAssignment() method.
281 * deleteActivityAssignment($activityId) method deletes activity assignment for given activity id.
283 public function testDeleteActivityAssignment() {
284 $contactId = $this->individualCreate();
286 'first_name' => 'liz',
287 'last_name' => 'hurleey',
289 $assigneeContactId = $this->individualCreate($params);
292 'source_contact_id' => $contactId,
293 'subject' => 'Scheduling Meeting',
294 'activity_type_id' => 2,
295 'assignee_contact_id' => array($assigneeContactId),
296 'activity_date_time' => date('Ymd'),
299 CRM_Activity_BAO_Activity
::create($params);
301 $activityId = $this->assertDBNotNull('CRM_Activity_DAO_Activity', 'Scheduling Meeting', 'id',
302 'subject', 'Database check for created activity.'
305 $this->assertDBNotNull('CRM_Activity_DAO_ActivityContact',
306 $assigneeContactId, 'id', 'contact_id',
307 'Database check for created activity assignment.'
310 CRM_Activity_BAO_Activity
::deleteActivityContact($activityId, 1);
312 $this->assertDBNull('CRM_Activity_DAO_ActivityContact', $assigneeContactId, 'id',
313 'contact_id', 'Database check for deleted activity assignment.'
316 $this->contactDelete($contactId);
317 $this->contactDelete($assigneeContactId);
321 * Test getActivities BAO method for getting count.
323 public function testGetActivitiesCountForAdminDashboard() {
324 $this->setUpForActivityDashboardTests();
325 $activityCount = CRM_Activity_BAO_Activity
::getActivitiesCount($this->_params
);
326 $this->assertEquals(8, $activityCount);
330 * Test getActivities BAO method for getting count
332 public function testGetActivitiesCountforNonAdminDashboard() {
333 $op = new PHPUnit_Extensions_Database_Operation_Insert();
334 $op->execute($this->_dbconn
,
335 $this->createFlatXMLDataSet(
336 dirname(__FILE__
) . '/activities_for_dashboard_count.xml'
345 'activity_type_id' => NULL,
346 'activity_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled'), // for dashlet the Scheduled status is set by default
352 //since we are loading activities from dataset, we know total number of activities for this contact
353 // 5 activities ( 2 scheduled, 3 Completed ), note that dashboard shows only scheduled activities
354 $this->assertEquals(2, CRM_Activity_BAO_Activity
::getActivitiesCount($params));
358 * Test getActivities BAO method for getting count
360 public function testGetActivitiesCountforContactSummary() {
361 $op = new PHPUnit_Extensions_Database_Operation_Insert();
362 $op->execute($this->_dbconn
,
363 $this->createFlatXMLDataSet(
364 dirname(__FILE__
) . '/activities_for_dashboard_count.xml'
372 'context' => 'activity',
373 'activity_type_id' => NULL,
379 //since we are loading activities from dataset, we know total number of activities for this contact
380 // 5 activities, Contact Summary should show all activities
381 $this->assertEquals(5, CRM_Activity_BAO_Activity
::getActivitiesCount($params));
385 * CRM-18706 - Test Include/Exclude Activity Filters
387 public function testActivityFilters() {
388 $op = new PHPUnit_Extensions_Database_Operation_Insert();
389 $op->execute($this->_dbconn
,
390 $this->createFlatXMLDataSet(
391 dirname(__FILE__
) . '/activities_for_dashboard_count.xml'
394 Civi
::settings()->set('preserve_activity_tab_filter', 1);
395 $this->createLoggedInUser();
400 'context' => 'activity',
401 'activity_type_id' => 1,
404 $expectedFilters = array(
405 'activity_type_filter_id' => 1,
408 list($activities, $activityFilter) = CRM_Activity_Page_AJAX
::getContactActivity();
409 //Assert whether filters are correctly set.
410 $this->checkArrayEquals($expectedFilters, $activityFilter);
411 // This should include activities of type Meeting only.
412 foreach ($activities['data'] as $value) {
413 $this->assertContains('Meeting', $value['activity_type']);
415 unset($_GET['activity_type_id']);
417 $_GET['activity_type_exclude_id'] = $expectedFilters['activity_type_exclude_filter_id'] = 1;
418 list($activities, $activityFilter) = CRM_Activity_Page_AJAX
::getContactActivity();
419 $this->assertEquals(['activity_type_exclude_filter_id' => 1], $activityFilter);
420 // None of the activities should be of type Meeting.
421 foreach ($activities['data'] as $value) {
422 $this->assertNotContains('Meeting', $value['activity_type']);
427 * Test getActivities BAO method for getting count
429 public function testGetActivitiesCountforContactSummaryWithNoActivities() {
430 $op = new PHPUnit_Extensions_Database_Operation_Insert();
431 $op->execute($this->_dbconn
,
432 $this->createFlatXMLDataSet(
433 dirname(__FILE__
) . '/activities_for_dashboard_count.xml'
442 'activity_type_id' => NULL,
448 //since we are loading activities from dataset, we know total number of activities for this contact
449 // this contact does not have any activity
450 $this->assertEquals(0, CRM_Activity_BAO_Activity
::getActivitiesCount($params));
454 * Test getActivities BAO method.
456 public function testGetActivitiesForAdminDashboard() {
457 $this->setUpForActivityDashboardTests();
458 $activitiesNew = CRM_Activity_BAO_Activity
::getActivities($this->_params
);
459 // $this->assertEquals($activities, $activitiesDeprecatedFn);
461 //since we are loading activities from dataset, we know total number of activities
462 // with no contact ID and there should be 8 schedule activities shown on dashboard
464 foreach (array($activitiesNew) as $activities) {
465 $this->assertEquals($count, count($activities));
467 foreach ($activities as $key => $value) {
468 $this->assertEquals($value['subject'], "subject {$key}", 'Verify activity subject is correct.');
469 $this->assertEquals($value['activity_type_id'], 2, 'Verify activity type is correct.');
470 $this->assertEquals($value['status_id'], 1, 'Verify all activities are scheduled.');
476 * Test getActivities BAO method.
478 public function testGetActivitiesForAdminDashboardNoViewContacts() {
479 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
480 $this->setUpForActivityDashboardTests();
481 foreach (array(CRM_Activity_BAO_Activity
::getActivities($this->_params
)) as $activities) {
482 // Skipped until we get back to the upgraded version properly.
483 $this->assertEquals(0, count($activities));
488 * Test getActivities BAO method.
490 public function testGetActivitiesForAdminDashboardAclLimitedViewContacts() {
491 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
492 $this->allowedContacts
= array(1, 3, 4, 5);
493 $this->hookClass
->setHook('civicrm_aclWhereClause', array($this, 'aclWhereMultipleContacts'));
494 $this->setUpForActivityDashboardTests();
495 $this->assertEquals(7, count(CRM_Activity_BAO_Activity
::getActivities($this->_params
)));
499 * Test getActivities BAO method.
501 public function testGetActivitiesforNonAdminDashboard() {
502 $op = new PHPUnit_Extensions_Database_Operation_Insert();
503 $op->execute($this->_dbconn
,
504 $this->createFlatXMLDataSet(
505 dirname(__FILE__
) . '/activities_for_dashboard_count.xml'
511 'contact_id' => $contactID,
515 'activity_type_id' => NULL,
516 'activity_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled'), // for dashlet the Scheduled status is set by default
522 foreach (array(CRM_Activity_BAO_Activity
::getActivities($params)) as $activities) {
523 //since we are loading activities from dataset, we know total number of activities for this contact
524 // 5 activities ( 2 scheduled, 3 Completed ), note that dashboard shows only scheduled activities
526 $this->assertEquals($count, count($activities));
528 foreach ($activities as $key => $value) {
529 $this->assertEquals($value['subject'], "subject {$key}", 'Verify activity subject is correct.');
530 $this->assertEquals($value['activity_type_id'], 2, 'Verify activity type is correct.');
531 $this->assertEquals($value['status_id'], 1, 'Verify all activities are scheduled.');
534 $this->assertArrayHasKey($contactID, $value['target_contact_name']);
537 $this->assertArrayHasKey($contactID, $value['assignee_contact_name']);
544 * Test target contact count.
546 public function testTargetCountforContactSummary() {
548 $contactId = $this->individualCreate();
549 $targetContactIDs = array();
550 for ($i = 0; $i < $targetCount; $i++
) {
551 $targetContactIDs[] = $this->individualCreate(array(), $i);
553 // Create activities with 5 target contacts.
554 $activityParams = array(
555 'source_contact_id' => $contactId,
556 'target_contact_id' => $targetContactIDs,
558 $this->activityCreate($activityParams);
561 'contact_id' => $contactId,
562 'context' => 'activity',
564 foreach (array(CRM_Activity_BAO_Activity
::getActivities($params)) as $activities) {
565 //verify target count
566 $this->assertEquals($targetCount, $activities[1]['target_contact_counter']);
567 $this->assertEquals([$targetContactIDs[0] => 'Anderson, Anthony'], $activities[1]['target_contact_name']);
573 * Test getActivities BAO method.
575 public function testGetActivitiesforContactSummary() {
576 $op = new PHPUnit_Extensions_Database_Operation_Insert();
577 $op->execute($this->_dbconn
,
578 $this->createFlatXMLDataSet(
579 dirname(__FILE__
) . '/activities_for_dashboard_count.xml'
585 'contact_id' => $contactID,
588 'context' => 'activity',
589 'activity_type_id' => NULL,
595 //since we are loading activities from dataset, we know total number of activities for this contact
596 // 5 activities, Contact Summary should show all activities
598 foreach (array(CRM_Activity_BAO_Activity
::getActivities($params)) as $activities) {
600 $this->assertEquals($count, count($activities));
602 foreach ($activities as $key => $value) {
603 $this->assertEquals($value['subject'], "subject {$key}", 'Verify activity subject is correct.');
606 $this->assertEquals($value['status_id'], 2, 'Verify all activities are scheduled.');
609 $this->assertEquals($value['status_id'], 1, 'Verify all activities are scheduled.');
613 $this->assertEquals($value['activity_type_id'], 1, 'Verify activity type is correct.');
616 $this->assertEquals($value['activity_type_id'], 2, 'Verify activity type is correct.');
620 $this->assertArrayHasKey($contactID, $value['target_contact_name']);
623 $this->assertArrayHasKey($contactID, $value['assignee_contact_name']);
630 * Test getActivities BAO method.
632 public function testGetActivitiesforContactSummaryWithActivities() {
633 $op = new PHPUnit_Extensions_Database_Operation_Insert();
634 $op->execute($this->_dbconn
,
635 $this->createFlatXMLDataSet(
636 dirname(__FILE__
) . '/activities_for_dashboard_count.xml'
640 // parameters for different test cases, check each array key for the specific test-case
642 'with-no-activity' => array(
648 'activity_type_id' => NULL,
654 'with-activity' => array(
660 'activity_type_id' => NULL,
666 'with-activity_type' => array(
672 'activity_type_id' => 2,
678 'exclude-all-activity_type' => array(
684 'activity_type_exclude_id' => array(1, 2),
690 'sort-by-subject' => array(
696 'activity_type_id' => NULL,
699 'sort' => 'subject DESC',
704 foreach ($testCases as $caseName => $testCase) {
705 $activityCount = CRM_Activity_BAO_Activity
::getActivitiesCount($testCase['params']);
706 $activitiesNew = CRM_Activity_BAO_Activity
::getActivities($testCase['params']);
708 foreach (array($activitiesNew) as $activities) {
709 //$this->assertEquals($activityCount, CRM_Activity_BAO_Activity::getActivitiesCount($testCase['params']));
710 if ($caseName == 'with-no-activity') {
711 $this->assertEquals(0, count($activities));
712 $this->assertEquals(0, $activityCount);
714 elseif ($caseName == 'with-activity') {
715 // contact id 1 is assigned as source, target and assignee for activity id 1, 7 and 8 respectively
716 $this->assertEquals(3, count($activities));
717 $this->assertEquals(3, $activityCount);
718 $this->assertEquals(1, $activities[1]['source_contact_id']);
719 // @todo - this is a discrepancy between old & new - review.
720 //$this->assertEquals(TRUE, array_key_exists(1, $activities[7]['target_contact_name']));
721 $this->assertEquals(TRUE, array_key_exists(1, $activities[8]['assignee_contact_name']));
723 elseif ($caseName == 'with-activity_type') {
724 // contact id 3 for activity type 2 is assigned as assignee, source and target for
725 // activity id 1, 3 and 8 respectively
726 $this->assertEquals(3, count($activities));
727 $this->assertEquals(3, $activityCount);
728 // ensure activity type id is 2
729 $this->assertEquals(2, $activities[1]['activity_type_id']);
730 $this->assertEquals(3, $activities[3]['source_contact_id']);
731 // @todo review inconsistency between 2 versions.
732 // $this->assertEquals(TRUE, array_key_exists(3, $activities[8]['target_contact_name']));
733 $this->assertEquals(TRUE, array_key_exists(3, $activities[1]['assignee_contact_name']));
735 if ($caseName == 'exclude-all-activity_type') {
736 $this->assertEquals(0, count($activities));
737 $this->assertEquals(0, $activityCount);
739 if ($caseName == 'sort-by-subject') {
740 $this->assertEquals(3, count($activities));
741 $this->assertEquals(3, $activityCount);
742 // activities should be order by 'subject DESC'
743 $subjectOrder = array(
749 foreach ($activities as $activity) {
750 $this->assertEquals($subjectOrder[$count], $activity['subject']);
759 * CRM-20793 : Test getActivities by using activity date and status filter
761 public function testByActivityDateAndStatus() {
762 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= ['view all contacts', 'access CiviCRM'];
763 $op = new PHPUnit_Extensions_Database_Operation_Insert();
764 $op->execute($this->_dbconn
,
765 $this->createFlatXMLDataSet(
766 dirname(__FILE__
) . '/activities_for_dashboard_count.xml'
770 // activity IDs catagorised by date
771 $lastWeekActivities = array(1, 2, 3);
772 $todayActivities = array(4, 5, 6, 7);
773 $lastTwoMonthsActivities = array(8, 9, 10, 11);
774 $lastOrNextYearActivities = array(12, 13, 14, 15, 16);
776 // date values later used to set activity date value
777 $lastWeekDate = date('YmdHis', strtotime('1 week ago'));
778 $today = date('YmdHis');
779 $lastTwoMonthAgoDate = date('YmdHis', strtotime('2 months ago'));
780 // if current month is Jan then choose next year date otherwise the search result will include
781 // the previous week and last two months activities which are still in previous year and hence leads to improper result
782 $lastOrNextYearDate = (date('M') == 'Jan') ?
date('YmdHis', strtotime('+1 year')) : date('YmdHis', strtotime('1 year ago'));
783 for ($i = 1; $i <= 16; $i++
) {
784 if (in_array($i, $lastWeekActivities)) {
785 $date = $lastWeekDate;
787 elseif (in_array($i, $lastTwoMonthsActivities)) {
788 $date = $lastTwoMonthAgoDate;
790 elseif (in_array($i, $lastOrNextYearActivities)) {
791 $date = $lastOrNextYearDate;
793 elseif (in_array($i, $todayActivities)) {
796 $this->callAPISuccess('Activity', 'create', array(
798 'activity_date_time' => $date,
802 // parameters for different test cases, check each array key for the specific test-case
804 'todays-activity' => array(
809 'context' => 'activity',
810 'activity_date_time_relative' => 'this.day',
811 'activity_type_id' => NULL,
817 'todays-activity-filtered-by-range' => array(
822 'context' => 'activity',
823 'activity_date_time_low' => date('Y/m/d', strtotime('yesterday')),
824 'activity_date_time_high' => date('Y/m/d'),
825 'activity_type_id' => NULL,
831 'last-week-activity' => array(
836 'context' => 'activity',
837 'activity_date_time_relative' => 'previous.week',
838 'activity_type_id' => NULL,
844 'this-quarter-activity' => array(
849 'context' => 'activity',
850 'activity_date_time_relative' => 'this.quarter',
851 'activity_type_id' => NULL,
857 'activity-of-all-statuses' => array(
862 'context' => 'activity',
863 'activity_status_id' => '1,2',
864 'activity_type_id' => NULL,
872 foreach ($testCases as $caseName => $testCase) {
873 CRM_Utils_Date
::convertFormDateToApiFormat($testCase['params'], 'activity_date_time', FALSE);
874 $activities = CRM_Activity_BAO_Activity
::getActivities($testCase['params']);
875 $activityCount = CRM_Activity_BAO_Activity
::getActivitiesCount($testCase['params']);
877 $activityIDs = array_keys($activities);
879 if ($caseName == 'todays-activity' ||
$caseName == 'todays-activity-filtered-by-range') {
880 // Only one of the 4 activities today relates to contact id 1.
881 $this->assertEquals(1, $activityCount);
882 $this->assertEquals(1, count($activities));
883 $this->assertEquals([7], array_keys($activities));
885 elseif ($caseName == 'last-week-activity') {
886 // Only one of the 3 activities today relates to contact id 1.
887 $this->assertEquals(1, $activityCount);
888 $this->assertEquals(1, count($activities));
889 $this->assertEquals([1], $activityIDs);
891 elseif ($caseName == 'lhis-quarter-activity') {
892 $this->assertEquals(count($lastTwoMonthsActivities), $activityCount);
893 $this->assertEquals(count($lastTwoMonthsActivities), count($activities));
894 $this->checkArrayEquals($lastTwoMonthsActivities, $activityIDs);
896 elseif ($caseName == 'last-or-next-year-activity') {
897 $this->assertEquals(count($lastOrNextYearActivities), $activityCount);
898 $this->assertEquals(count($lastOrNextYearActivities), count($activities));
899 $this->checkArrayEquals($lastOrNextYearActivities, $activityIDs);
901 elseif ($caseName == 'activity-of-all-statuses') {
902 $this->assertEquals(3, $activityCount);
903 $this->assertEquals(3, count($activities));
909 * @dataProvider getActivityDateData
911 public function testActivityRelativeDateFilter($params, $expected) {
912 $thisYear = date('Y');
914 date('Y-m-d', strtotime(($thisYear - 1) . '-01-01')),
915 date('Y-m-d', strtotime(($thisYear - 1) . '-12-31')),
916 date('Y-m-d', strtotime($thisYear . '-01-01')),
917 date('Y-m-d', strtotime($thisYear . '-12-31')),
918 date('Y-m-d', strtotime(($thisYear +
1) . '-01-01')),
919 date('Y-m-d', strtotime(($thisYear +
1) . '-12-31')),
921 foreach ($dates as $date) {
922 $this->activityCreate(['activity_date_time' => $date]);
924 $activitiesDep = CRM_Activity_BAO_Activity
::getActivities($params);
925 $activityCount = CRM_Activity_BAO_Activity
::getActivitiesCount($params);
926 $this->assertEquals(count($activitiesDep), $activityCount);
927 foreach ($activitiesDep as $activity) {
928 $this->assertTrue(strtotime($activity['activity_date_time']) >= $expected['earliest'], $activity['activity_date_time'] . ' should be no earlier than ' . date('Y-m-d H:i:s', $expected['earliest']));
929 $this->assertTrue(strtotime($activity['activity_date_time']) < $expected['latest'], $activity['activity_date_time'] . ' should be before ' . date('Y-m-d H:i:s', $expected['latest']));
935 * Get activity date data.
937 * Later we might migrate rework the rest of
938 * testByActivityDateAndStatus
939 * to use data provider methodology as it's way complex!
943 public function getActivityDateData() {
945 'last-year-activity' => [
950 'context' => 'activity',
951 'activity_date_relative' => 'previous.year',
952 'activity_type_id' => NULL,
959 'earliest' => strtotime('first day of january last year'),
960 'latest' => strtotime('first day of january this year'),
967 * CRM-20308: Test from email address when a 'copy of Activity' event occur
969 public function testEmailAddressOfActivityCopy() {
970 // Case 1: assert the 'From' Email Address of source Actvity Contact ID
971 // create activity with source contact ID which has email address
972 $assigneeContactId = $this->individualCreate();
973 $sourceContactParams = array(
974 'first_name' => 'liz',
975 'last_name' => 'hurleey',
976 'email' => substr(sha1(rand()), 0, 7) . '@testemail.com',
978 $sourceContactID = $this->individualCreate($sourceContactParams);
979 $sourceDisplayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $sourceContactID, 'display_name');
981 // create an activity using API
983 'source_contact_id' => $sourceContactID,
984 'subject' => 'Scheduling Meeting ' . substr(sha1(rand()), 0, 4),
985 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Meeting'),
986 'assignee_contact_id' => array($assigneeContactId),
987 'activity_date_time' => date('Ymd'),
989 $activity = $this->callAPISuccess('Activity', 'create', $params);
991 // Check that from address is in "Source-Display-Name <source-email>"
992 $formAddress = CRM_Case_BAO_Case
::getReceiptFrom($activity['id']);
993 $expectedFromAddress = sprintf("%s <%s>", $sourceDisplayName, $sourceContactParams['email']);
994 $this->assertEquals($expectedFromAddress, $formAddress);
996 // Case 2: System Default From Address
997 // but first erase the email address of existing source contact ID
998 $withoutEmailParams = array(
1001 $sourceContactID = $this->individualCreate($withoutEmailParams);
1003 'source_contact_id' => $sourceContactID,
1004 'subject' => 'Scheduling Meeting ' . substr(sha1(rand()), 0, 4),
1005 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Meeting'),
1006 'activity_date_time' => date('Ymd'),
1008 $activity = $this->callAPISuccess('Activity', 'create', $params);
1009 // fetch domain info
1010 $domainInfo = $this->callAPISuccess('Domain', 'getsingle', array('id' => CRM_Core_Config
::domainID()));
1012 $formAddress = CRM_Case_BAO_Case
::getReceiptFrom($activity['id']);
1013 if (!empty($domainInfo['from_email'])) {
1014 $expectedFromAddress = sprintf("%s <%s>", $domainInfo['from_name'], $domainInfo['from_email']);
1016 // Case 3: fetch default Organization Contact email address
1017 elseif (!empty($domainInfo['domain_email'])) {
1018 $expectedFromAddress = sprintf("%s <%s>", $domainInfo['name'], $domainInfo['domain_email']);
1020 $this->assertEquals($expectedFromAddress, $formAddress);
1022 // TODO: Case 4 about checking the $formAddress on basis of logged contact ID respectively needs,
1023 // to change the domain setting, which isn't straight forward in test environment
1027 * Set up for testing activity queries.
1029 protected function setUpForActivityDashboardTests() {
1030 $op = new PHPUnit_Extensions_Database_Operation_Insert();
1031 $op->execute($this->_dbconn
,
1032 $this->createFlatXMLDataSet(
1033 dirname(__FILE__
) . '/activities_for_dashboard_count.xml'
1037 $this->_params
= array(
1038 'contact_id' => NULL,
1041 'context' => 'home',
1042 'activity_type_id' => NULL,
1043 'activity_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled'), // for dashlet the Scheduled status is set by default
1050 public function testSendEmailBasic() {
1051 $contactId = $this->individualCreate();
1053 // create a logged in USER since the code references it for sendEmail user.
1054 $this->createLoggedInUser();
1055 $session = CRM_Core_Session
::singleton();
1056 $loggedInUser = $session->get('userID');
1058 $contact = $this->civicrm_api('contact', 'getsingle', array('id' => $contactId, 'version' => $this->_apiversion
));
1059 $contactDetailsIntersectKeys = array(
1062 'display_name' => '',
1063 'do_not_email' => '',
1064 'preferred_mail_format' => '',
1065 'is_deceased' => '',
1069 $contactDetails = array(
1070 array_intersect_key($contact, $contactDetailsIntersectKeys),
1073 $subject = __FUNCTION__
. ' subject';
1074 $html = __FUNCTION__
. ' html';
1075 $text = __FUNCTION__
. ' text';
1076 $userID = $loggedInUser;
1078 list($sent, $activity_id) = $email_result = CRM_Activity_BAO_Activity
::sendEmail(
1085 $from = __FUNCTION__
. '@example.com'
1088 $activity = $this->civicrm_api('activity', 'getsingle', array('id' => $activity_id, 'version' => $this->_apiversion
));
1089 $details = "-ALTERNATIVE ITEM 0-
1091 -ALTERNATIVE ITEM 1-
1095 $this->assertEquals($activity['details'], $details, 'Activity details does not match.');
1096 $this->assertEquals($activity['subject'], $subject, 'Activity subject does not match.');
1099 public function testSendEmailWithCampaign() {
1100 // Create a contact and contactDetails array.
1101 $contactId = $this->individualCreate();
1103 // create a logged in USER since the code references it for sendEmail user.
1104 $this->createLoggedInUser();
1105 $session = CRM_Core_Session
::singleton();
1106 $loggedInUser = $session->get('userID');
1108 $contact = $this->civicrm_api('contact', 'getsingle', array('id' => $contactId, 'version' => $this->_apiversion
));
1109 $contactDetailsIntersectKeys = array(
1112 'display_name' => '',
1113 'do_not_email' => '',
1114 'preferred_mail_format' => '',
1115 'is_deceased' => '',
1119 $contactDetails = array(
1120 array_intersect_key($contact, $contactDetailsIntersectKeys),
1123 // Create a campaign.
1124 $result = $this->civicrm_api('Campaign', 'create', array(
1125 'version' => $this->_apiversion
,
1126 'title' => __FUNCTION__
. ' campaign',
1128 $campaign_id = $result['id'];
1130 $subject = __FUNCTION__
. ' subject';
1131 $html = __FUNCTION__
. ' html';
1132 $text = __FUNCTION__
. ' text';
1133 $userID = $loggedInUser;
1135 list($sent, $activity_id) = $email_result = CRM_Activity_BAO_Activity
::sendEmail(
1142 $from = __FUNCTION__
. '@example.com',
1143 $attachments = NULL,
1147 $additionalDetails = NULL,
1151 $activity = $this->civicrm_api('activity', 'getsingle', array('id' => $activity_id, 'version' => $this->_apiversion
));
1152 $this->assertEquals($activity['campaign_id'], $campaign_id, 'Activity campaign_id does not match.');
1156 * @expectedException CRM_Core_Exception
1157 * @expectedExceptionMessage You do not have the 'send SMS' permission
1159 public function testSendSMSWithoutPermission() {
1161 $session = CRM_Core_Session
::singleton();
1162 $config = &CRM_Core_Config
::singleton();
1163 $config->userPermissionClass
->permissions
= array('access CiviCRM');
1165 CRM_Activity_BAO_Activity
::sendSMS(
1170 $session->get('userID')
1174 public function testSendSmsNoPhoneNumber() {
1175 list($sent, $activityId, $success) = $this->createSendSmsTest(0);
1176 $activity = $this->civicrm_api('activity', 'getsingle', array('id' => $activityId, 'version' => $this->_apiversion
));
1178 $outBoundSmsActivityId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS');
1179 $activityStatusCompleted = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
1180 $details = 'createSendSmsTest text';
1181 $this->assertEquals($activity['activity_type_id'], $outBoundSmsActivityId, 'Wrong activity type is set.');
1182 $this->assertEquals($activity['status_id'], $activityStatusCompleted, 'Expected activity status Completed.');
1183 $this->assertEquals($activity['subject'], 'createSendSmsTest subject', 'Activity subject does not match.');
1184 $this->assertEquals($activity['details'], $details, 'Activity details does not match.');
1185 $this->assertEquals("Recipient phone number is invalid or recipient does not want to receive SMS", $sent[0]->message
, "Expected error doesn't match");
1186 $this->assertEquals(0, $success, "Expected success to be 0");
1189 public function testSendSmsFixedPhoneNumber() {
1190 list($sent, $activityId, $success) = $this->createSendSmsTest(1);
1191 $activity = $this->civicrm_api('activity', 'getsingle', array('id' => $activityId, 'version' => $this->_apiversion
));
1193 $outBoundSmsActivityId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS');
1194 $activityStatusCompleted = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
1195 $details = 'createSendSmsTest text';
1196 $this->assertEquals($activity['activity_type_id'], $outBoundSmsActivityId, 'Wrong activity type is set.');
1197 $this->assertEquals($activity['status_id'], $activityStatusCompleted, 'Expected activity status Completed.');
1198 $this->assertEquals($activity['subject'], 'createSendSmsTest subject', 'Activity subject does not match.');
1199 $this->assertEquals($activity['details'], $details, 'Activity details does not match.');
1200 $this->assertEquals("Recipient phone number is invalid or recipient does not want to receive SMS", $sent[0]->message
, "Expected error doesn't match");
1201 $this->assertEquals(0, $success, "Expected success to be 0");
1204 public function testSendSmsMobilePhoneNumber() {
1205 list($sent, $activityId, $success) = $this->createSendSmsTest(2);
1206 $activity = $this->civicrm_api('activity', 'getsingle', array('id' => $activityId, 'version' => $this->_apiversion
));
1208 $outBoundSmsActivityId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS');
1209 $activityStatusCompleted = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
1210 $details = 'createSendSmsTest text';
1211 $this->assertEquals($activity['activity_type_id'], $outBoundSmsActivityId, 'Wrong activity type is set.');
1212 $this->assertEquals($activity['status_id'], $activityStatusCompleted, 'Expected activity status Completed.');
1213 $this->assertEquals($activity['subject'], 'createSendSmsTest subject', 'Activity subject does not match.');
1214 $this->assertEquals($activity['details'], $details, 'Activity details does not match.');
1215 $this->assertEquals(TRUE, $sent, "Expected sent should be true");
1216 $this->assertEquals(1, $success, "Expected success to be 1");
1220 * Test that when a numbe ris specified in the To Param of the SMS provider parameters that an SMS is sent
1221 * @see dev/core/#273
1223 public function testSendSMSMobileInToProviderParam() {
1224 list($sent, $activityId, $success) = $this->createSendSmsTest(2, TRUE);
1225 $this->assertEquals(TRUE, $sent, "Expected sent should be true");
1226 $this->assertEquals(1, $success, "Expected success to be 1");
1230 * Test that when a numbe ris specified in the To Param of the SMS provider parameters that an SMS is sent
1231 * @see dev/core/#273
1233 public function testSendSMSMobileInToProviderParamWithDoNotSMS() {
1234 list($sent, $activityId, $success) = $this->createSendSmsTest(2, TRUE, ['do_not_sms' => 1]);
1235 foreach ($sent as $error) {
1236 $this->assertEquals('Contact Does not accept SMS', $error->getMessage());
1238 $this->assertEquals(1, count($sent), "Expected sent should a PEAR Error");
1239 $this->assertEquals(0, $success, "Expected success to be 0");
1244 * @param int $phoneType (0=no phone, phone_type option group (1=fixed, 2=mobile)
1245 * @param bool $passPhoneTypeInContactDetails
1246 * @param array $additionalContactParams additional contact creation params
1248 public function createSendSmsTest($phoneType = 0, $passPhoneTypeInContactDetails = FALSE, $additionalContactParams = []) {
1249 $provider = civicrm_api3('SmsProvider', 'create', array(
1250 'name' => "CiviTestSMSProvider",
1256 "api_params" => "a=1",
1257 "is_default" => "1",
1262 $smsProviderParams['provider_id'] = $provider['id'];
1265 $contactId = $this->individualCreate();
1266 if (!empty($additionalContactParams)) {
1267 $this->callAPISuccess('contact', 'create', ['id' => $contactId] +
$additionalContactParams);
1269 $contactsResult = $this->callApiSuccess('contact', 'get', ['id' => $contactId, 'version' => $this->_apiversion
]);
1270 $contactDetails = $contactsResult['values'];
1272 // Get contactIds from contact details
1273 foreach ($contactDetails as $contact) {
1274 $contactIds[] = $contact['contact_id'];
1277 $activityParams['sms_text_message'] = __FUNCTION__
. ' text';
1278 $activityParams['activity_subject'] = __FUNCTION__
. ' subject';
1280 // Get a "logged in" user to set as source of Sms.
1281 $session = CRM_Core_Session
::singleton();
1282 $sourceContactId = $session->get('userID');
1285 $this->_testSmsContactId
= $this->createLoggedInUser();
1287 // Give user permission to 'send SMS'
1288 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM', 'send SMS');
1290 // Create a phone number
1291 switch ($phoneType) {
1297 // Create a mobile phone number
1298 $phone = civicrm_api3('Phone', 'create', array(
1299 'contact_id' => $contactId,
1301 'phone_type_id' => "Mobile",
1303 if ($passPhoneTypeInContactDetails) {
1304 $contactDetails[$contactId]['phone'] = $phone['values'][$phone['id']]['phone'];
1305 $contactDetails[$contactId]['phone_type_id'] = $phone['values'][$phone['id']]['phone_type_id'];
1310 // Create a fixed phone number
1311 $phone = civicrm_api3('Phone', 'create', array(
1312 'contact_id' => $contactId,
1314 'phone_type_id' => "Phone",
1316 if ($passPhoneTypeInContactDetails) {
1317 $contactDetails[$contactId]['phone'] = $phone['values'][$phone['id']]['phone'];
1318 $contactDetails[$contactId]['phone_type_id'] = $phone['values'][$phone['id']]['phone_type_id'];
1323 // Now run the actual test
1324 list($sent, $activityId, $success) = CRM_Activity_BAO_Activity
::sendSms(
1332 return array($sent, $activityId, $success);