3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Test APIv3 civicrm_report_instance_* functions
31 * @package CiviCRM_APIv3
32 * @subpackage API_Report
35 class api_v3_ReportTemplateTest
extends CiviUnitTestCase
{
37 use CRMTraits_ACL_PermissionTrait
;
38 use CRMTraits_PCP_PCPTestTrait
;
39 use CRMTraits_Custom_CustomDataTrait
;
41 protected $contactIDs = [];
44 * Our group reports use an alter so transaction cleanup won't work.
48 public function tearDown() {
49 $this->quickCleanUpFinancialEntities();
50 $this->quickCleanup(['civicrm_group', 'civicrm_saved_search', 'civicrm_group_contact', 'civicrm_group_contact_cache', 'civicrm_group'], TRUE);
54 public function testReportTemplate() {
55 $result = $this->callAPISuccess('ReportTemplate', 'create', [
56 'label' => 'Example Form',
57 'description' => 'Longish description of the example form',
58 'class_name' => 'CRM_Report_Form_Examplez',
59 'report_url' => 'example/path',
60 'component' => 'CiviCase',
62 $this->assertAPISuccess($result);
63 $this->assertEquals(1, $result['count']);
64 $entityId = $result['id'];
65 $this->assertTrue(is_numeric($entityId));
66 $this->assertEquals(7, $result['values'][$entityId]['component_id']);
67 $this->assertDBQuery(1, 'SELECT count(*) FROM civicrm_option_value
68 WHERE name = "CRM_Report_Form_Examplez"
69 AND option_group_id IN (SELECT id from civicrm_option_group WHERE name = "report_template") ');
70 $this->assertDBQuery(1, 'SELECT is_active FROM civicrm_option_value
71 WHERE name = "CRM_Report_Form_Examplez"');
73 // change component to null
74 $result = $this->callAPISuccess('ReportTemplate', 'create', [
78 $this->assertAPISuccess($result);
79 $this->assertEquals(1, $result['count']);
80 $this->assertDBQuery(1, 'SELECT count(*) FROM civicrm_option_value
81 WHERE name = "CRM_Report_Form_Examplez"
82 AND option_group_id IN (SELECT id from civicrm_option_group WHERE name = "report_template") ');
83 $this->assertDBQuery(1, 'SELECT count(*) FROM civicrm_option_value
84 WHERE name = "CRM_Report_Form_Examplez"
85 AND component_id IS NULL');
88 $result = $this->callAPISuccess('ReportTemplate', 'create', [
92 $this->assertAPISuccess($result);
93 $this->assertEquals(1, $result['count']);
94 $this->assertDBQuery(1, 'SELECT count(*) FROM civicrm_option_value
95 WHERE name = "CRM_Report_Form_Examplez"
96 AND option_group_id IN (SELECT id from civicrm_option_group WHERE name = "report_template") ');
97 $this->assertDBQuery(0, 'SELECT is_active FROM civicrm_option_value
98 WHERE name = "CRM_Report_Form_Examplez"');
101 $result = $this->callAPISuccess('ReportTemplate', 'create', [
105 $this->assertAPISuccess($result);
106 $this->assertEquals(1, $result['count']);
107 $this->assertDBQuery(1, 'SELECT count(*) FROM civicrm_option_value
108 WHERE name = "CRM_Report_Form_Examplez"
109 AND option_group_id IN (SELECT id from civicrm_option_group WHERE name = "report_template") ');
110 $this->assertDBQuery(1, 'SELECT is_active FROM civicrm_option_value
111 WHERE name = "CRM_Report_Form_Examplez"');
113 $result = $this->callAPISuccess('ReportTemplate', 'delete', [
116 $this->assertAPISuccess($result);
117 $this->assertEquals(1, $result['count']);
118 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_option_value
119 WHERE name = "CRM_Report_Form_Examplez"
124 * Test api to get rows from reports.
126 * @dataProvider getReportTemplatesSupportingSelectWhere
130 * @throws \PHPUnit\Framework\IncompleteTestError
132 public function testReportTemplateSelectWhere($reportID) {
133 $this->hookClass
->setHook('civicrm_selectWhereClause', [$this, 'hookSelectWhere']);
134 $result = $this->callAPISuccess('report_template', 'getrows', [
135 'report_id' => $reportID,
136 'options' => ['metadata' => ['sql']],
139 foreach ($result['metadata']['sql'] as $sql) {
140 if (strstr($sql, " = 'Organization' ")) {
144 $this->assertTrue($found, $reportID);
148 * Get templates suitable for SelectWhere test.
152 public function getReportTemplatesSupportingSelectWhere() {
153 $allTemplates = $this->getReportTemplates();
154 // Exclude all that do not work as of test being written. I have not dug into why not.
155 $currentlyExcluded = [
163 'contribute/bookkeeping',
165 'event/incomesummary',
170 'logging/contact/detail',
171 'logging/contact/summary',
173 foreach ($allTemplates as $index => $template) {
174 $reportID = $template[0];
175 if (in_array($reportID, $currentlyExcluded) ||
stristr($reportID, 'has existing issues')) {
176 unset($allTemplates[$index]);
179 return $allTemplates;
183 * @param \CRM_Core_DAO $entity
184 * @param array $clauses
186 public function hookSelectWhere($entity, &$clauses) {
187 // Restrict access to cases by type
188 if ($entity == 'Contact') {
189 $clauses['contact_type'][] = " = 'Organization' ";
194 * Test getrows on contact summary report.
196 public function testReportTemplateGetRowsContactSummary() {
197 $description = "Retrieve rows from a report template (optionally providing the instance_id).";
198 $result = $this->callAPISuccess('report_template', 'getrows', [
199 'report_id' => 'contact/summary',
200 'options' => ['metadata' => ['labels', 'title']],
201 ], __FUNCTION__
, __FILE__
, $description, 'Getrows');
202 $this->assertEquals('Contact Name', $result['metadata']['labels']['civicrm_contact_sort_name']);
204 //the second part of this test has been commented out because it relied on the db being reset to
206 //wasn't able to get that to work consistently
207 // however, when the db is in the base state the tests do pass
208 // and because the test covers 'all' contacts we can't create our own & assume the others don't exist
210 $this->assertEquals(2, $result['count']);
211 $this->assertEquals('Default Organization', $result[0]['civicrm_contact_sort_name']);
212 $this->assertEquals('Second Domain', $result[1]['civicrm_contact_sort_name']);
213 $this->assertEquals('15 Main St', $result[1]['civicrm_address_street_address']);
218 * Test getrows on Mailing Opened report.
220 public function testReportTemplateGetRowsMailingUniqueOpened() {
221 $description = "Retrieve rows from a mailing opened report template.";
222 $this->loadXMLDataSet(dirname(__FILE__
) . '/../../CRM/Mailing/BAO/queryDataset.xml');
224 // Check total rows without distinct
226 $_REQUEST['distinct'] = 0;
227 $result = $this->callAPIAndDocument('report_template', 'getrows', [
228 'report_id' => 'Mailing/opened',
229 'options' => ['metadata' => ['labels', 'title']],
230 ], __FUNCTION__
, __FILE__
, $description, 'Getrows');
231 $this->assertEquals(14, $result['count']);
233 // Check total rows with distinct
234 $_REQUEST['distinct'] = 1;
235 $result = $this->callAPIAndDocument('report_template', 'getrows', [
236 'report_id' => 'Mailing/opened',
237 'options' => ['metadata' => ['labels', 'title']],
238 ], __FUNCTION__
, __FILE__
, $description, 'Getrows');
239 $this->assertEquals(5, $result['count']);
241 // Check total rows with distinct by passing NULL value to distinct parameter
242 $_REQUEST['distinct'] = NULL;
243 $result = $this->callAPIAndDocument('report_template', 'getrows', [
244 'report_id' => 'Mailing/opened',
245 'options' => ['metadata' => ['labels', 'title']],
246 ], __FUNCTION__
, __FILE__
, $description, 'Getrows');
247 $this->assertEquals(5, $result['count']);
251 * Test api to get rows from reports.
253 * @dataProvider getReportTemplates
257 * @throws \PHPUnit\Framework\IncompleteTestError
259 public function testReportTemplateGetRowsAllReports($reportID) {
260 //$reportID = 'logging/contact/summary';
261 if (stristr($reportID, 'has existing issues')) {
262 $this->markTestIncomplete($reportID);
264 if (substr($reportID, 0, '7') === 'logging') {
265 Civi
::settings()->set('logging', 1);
268 $this->callAPISuccess('report_template', 'getrows', [
269 'report_id' => $reportID,
271 if (substr($reportID, 0, '7') === 'logging') {
272 Civi
::settings()->set('logging', 0);
277 * Test logging report when a custom data table has a table removed by hook.
279 * Here we are checking that no fatal is triggered.
281 public function testLoggingReportWithHookRemovalOfCustomDataTable() {
282 Civi
::settings()->set('logging', 1);
283 $group1 = $this->customGroupCreate();
284 $group2 = $this->customGroupCreate(['name' => 'second_one', 'title' => 'second one', 'table_name' => 'civicrm_value_second_one']);
285 $this->customFieldCreate(['custom_group_id' => $group1['id'], 'label' => 'field one']);
286 $this->customFieldCreate(['custom_group_id' => $group2['id'], 'label' => 'field two']);
287 $this->hookClass
->setHook('civicrm_alterLogTables', [$this, 'alterLogTablesRemoveCustom']);
289 $this->callAPISuccess('report_template', 'getrows', [
290 'report_id' => 'logging/contact/summary',
292 Civi
::settings()->set('logging', 0);
293 $this->customGroupDelete($group1['id']);
294 $this->customGroupDelete($group2['id']);
298 * Remove one log table from the logging spec.
300 * @param array $logTableSpec
302 public function alterLogTablesRemoveCustom(&$logTableSpec) {
303 unset($logTableSpec['civicrm_value_second_one']);
307 * Test api to get rows from reports with ACLs enabled.
309 * Checking for lack of fatal error at the moment.
311 * @dataProvider getReportTemplates
315 * @throws \PHPUnit\Framework\IncompleteTestError
317 public function testReportTemplateGetRowsAllReportsACL($reportID) {
318 if (stristr($reportID, 'has existing issues')) {
319 $this->markTestIncomplete($reportID);
321 $this->hookClass
->setHook('civicrm_aclWhereClause', [$this, 'aclWhereHookNoResults']);
322 $this->callAPISuccess('report_template', 'getrows', [
323 'report_id' => $reportID,
328 * Test get statistics.
330 * @dataProvider getReportTemplates
334 * @throws \PHPUnit\Framework\IncompleteTestError
336 public function testReportTemplateGetStatisticsAllReports($reportID) {
337 if (stristr($reportID, 'has existing issues')) {
338 $this->markTestIncomplete($reportID);
340 if (in_array($reportID, ['contribute/softcredit', 'contribute/bookkeeping'])) {
341 $this->markTestIncomplete($reportID . " has non enotices when calling statistics fn");
343 $description = "Get Statistics from a report (note there isn't much data to get in the test DB).";
344 $result = $this->callAPIAndDocument('report_template', 'getstatistics', [
345 'report_id' => $reportID,
346 ], __FUNCTION__
, __FILE__
, $description, 'Getstatistics', 'getstatistics');
350 * Data provider function for getting all templates.
352 * Note that the function needs to
353 * be static so cannot use $this->callAPISuccess
355 public static function getReportTemplates() {
357 'event/income' => 'I do no understand why but error is Call to undefined method CRM_Report_Form_Event_Income::from() in CRM/Report/Form.php on line 2120',
358 'contribute/history' => 'Declaration of CRM_Report_Form_Contribute_History::buildRows() should be compatible with CRM_Report_Form::buildRows($sql, &$rows)',
361 $reports = civicrm_api3('report_template', 'get', ['return' => 'value', 'options' => ['limit' => 500]]);
362 foreach ($reports['values'] as $report) {
363 if (empty($reportsToSkip[$report['value']])) {
364 $reportTemplates[] = [$report['value']];
367 $reportTemplates[] = [$report['value'] . " has existing issues : " . $reportsToSkip[$report['value']]];
371 return $reportTemplates;
375 * Get contribution templates that work with basic filter tests.
377 * These templates require minimal data config.
379 public static function getContributionReportTemplates() {
380 return [['contribute/summary'], ['contribute/detail'], ['contribute/repeat'], ['topDonor' => 'contribute/topDonor']];
384 * Get contribution templates that work with basic filter tests.
386 * These templates require minimal data config.
388 public static function getMembershipReportTemplates() {
389 return [['member/detail']];
393 * Get the membership and contribution reports to test.
397 public static function getMembershipAndContributionReportTemplatesForGroupTests() {
398 $templates = array_merge(self
::getContributionReportTemplates(), self
::getMembershipReportTemplates());
399 foreach ($templates as $key => $value) {
400 if (array_key_exists('topDonor', $value)) {
401 // Report is not standard enough to test here.
402 unset($templates[$key]);
410 * Test Lybunt report to check basic inclusion of a contact who gave in the year before the chosen year.
412 public function testLybuntReportWithData() {
413 $inInd = $this->individualCreate();
414 $outInd = $this->individualCreate();
415 $this->contributionCreate(['contact_id' => $inInd, 'receive_date' => '2014-03-01']);
416 $this->contributionCreate(['contact_id' => $outInd, 'receive_date' => '2015-03-01', 'trxn_id' => NULL, 'invoice_id' => NULL]);
417 $rows = $this->callAPISuccess('report_template', 'getrows', [
418 'report_id' => 'contribute/lybunt',
420 'yid_op' => 'calendar',
421 'options' => ['metadata' => ['sql']],
423 $this->assertEquals(1, $rows['count'], "Report failed - the sql used to generate the results was " . print_r($rows['metadata']['sql'], TRUE));
427 * Test Lybunt report applies ACLs.
429 public function testLybuntReportWithDataAndACLFilter() {
430 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= ['administer CiviCRM'];
431 $inInd = $this->individualCreate();
432 $outInd = $this->individualCreate();
433 $this->contributionCreate(['contact_id' => $inInd, 'receive_date' => '2014-03-01']);
434 $this->contributionCreate(['contact_id' => $outInd, 'receive_date' => '2015-03-01', 'trxn_id' => NULL, 'invoice_id' => NULL]);
435 $this->hookClass
->setHook('civicrm_aclWhereClause', [$this, 'aclWhereHookNoResults']);
437 'report_id' => 'contribute/lybunt',
439 'yid_op' => 'calendar',
440 'options' => ['metadata' => ['sql']],
441 'check_permissions' => 1,
444 $rows = $this->callAPISuccess('report_template', 'getrows', $params);
445 $this->assertEquals(0, $rows['count'], "Report failed - the sql used to generate the results was " . print_r($rows['metadata']['sql'], TRUE));
447 CRM_Utils_Hook
::singleton()->reset();
451 * Test Lybunt report to check basic inclusion of a contact who gave in the year before the chosen year.
453 public function testLybuntReportWithFYData() {
454 $inInd = $this->individualCreate();
455 $outInd = $this->individualCreate();
456 $this->contributionCreate(['contact_id' => $inInd, 'receive_date' => '2014-10-01']);
457 $this->contributionCreate(['contact_id' => $outInd, 'receive_date' => '2015-03-01', 'trxn_id' => NULL, 'invoice_id' => NULL]);
458 $this->callAPISuccess('Setting', 'create', ['fiscalYearStart' => ['M' => 7, 'd' => 1]]);
459 $rows = $this->callAPISuccess('report_template', 'getrows', [
460 'report_id' => 'contribute/lybunt',
462 'yid_op' => 'fiscal',
463 'options' => ['metadata' => ['sql']],
466 'column' => 'first_name',
472 $this->assertEquals(2, $rows['count'], "Report failed - the sql used to generate the results was " . print_r($rows['metadata']['sql'], TRUE));
474 $expected = preg_replace('/\s+/', ' ', 'DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci AS
475 SELECT SQL_CALC_FOUND_ROWS contact_civireport.id as cid FROM civicrm_contact contact_civireport INNER JOIN civicrm_contribution contribution_civireport USE index (received_date) ON contribution_civireport.contact_id = contact_civireport.id
476 AND contribution_civireport.is_test = 0
477 AND contribution_civireport.receive_date BETWEEN \'20140701000000\' AND \'20150630235959\'
478 WHERE contact_civireport.id NOT IN (
479 SELECT cont_exclude.contact_id
480 FROM civicrm_contribution cont_exclude
481 WHERE cont_exclude.receive_date BETWEEN \'2015-7-1\' AND \'20160630235959\')
482 AND ( contribution_civireport.contribution_status_id IN (1) )
483 GROUP BY contact_civireport.id');
484 // Exclude whitespace in comparison as we don't care if it changes & this allows us to make the above readable.
485 $whitespacelessSql = preg_replace('/\s+/', ' ', $rows['metadata']['sql'][0]);
486 $this->assertContains($expected, $whitespacelessSql);
490 * Test Lybunt report to check basic inclusion of a contact who gave in the year before the chosen year.
492 public function testLybuntReportWithFYDataOrderByLastYearAmount() {
493 $inInd = $this->individualCreate();
494 $outInd = $this->individualCreate();
495 $this->contributionCreate(['contact_id' => $inInd, 'receive_date' => '2014-10-01']);
496 $this->contributionCreate(['contact_id' => $outInd, 'receive_date' => '2015-03-01', 'trxn_id' => NULL, 'invoice_id' => NULL]);
497 $this->callAPISuccess('Setting', 'create', ['fiscalYearStart' => ['M' => 7, 'd' => 1]]);
498 $rows = $this->callAPISuccess('report_template', 'getrows', [
499 'report_id' => 'contribute/lybunt',
501 'yid_op' => 'fiscal',
502 'options' => ['metadata' => ['sql']],
503 'fields' => ['first_name'],
506 'column' => 'last_year_total_amount',
512 $this->assertEquals(2, $rows['count'], "Report failed - the sql used to generate the results was " . print_r($rows['metadata']['sql'], TRUE));
516 * Test the group filter works on the contribution summary (with a smart group).
518 * @dataProvider getMembershipAndContributionReportTemplatesForGroupTests
520 * @param string $template
521 * Name of the template to test.
523 public function testContributionSummaryWithSmartGroupFilter($template) {
524 $groupID = $this->setUpPopulatedSmartGroup();
525 $rows = $this->callAPISuccess('report_template', 'getrows', [
526 'report_id' => $template,
527 'gid_value' => $groupID,
529 'options' => ['metadata' => ['sql']],
531 $this->assertNumberOfContactsInResult(3, $rows, $template);
532 if ($template === 'contribute/summary') {
533 $this->assertEquals(3, $rows['values'][0]['civicrm_contribution_total_amount_count']);
538 * Test the group filter works on the contribution summary.
540 * @dataProvider getMembershipAndContributionReportTemplatesForGroupTests
542 public function testContributionSummaryWithNotINSmartGroupFilter($template) {
543 $groupID = $this->setUpPopulatedSmartGroup();
544 $rows = $this->callAPISuccess('report_template', 'getrows', [
545 'report_id' => 'contribute/summary',
546 'gid_value' => $groupID,
548 'options' => ['metadata' => ['sql']],
550 $this->assertEquals(2, $rows['values'][0]['civicrm_contribution_total_amount_count']);
554 * Test no fatal on order by per https://lab.civicrm.org/dev/core/issues/739
556 public function testCaseDetailsCaseTypeHeader() {
557 $this->callAPISuccess('report_template', 'getrows', [
558 'report_id' => 'case/detail',
559 'fields' => ['subject' => 1, 'client_sort_name' => 1],
562 'column' => 'case_type_title',
571 * Test the group filter works on the contribution summary.
573 public function testContributionDetailSoftCredits() {
574 $contactID = $this->individualCreate();
575 $contactID2 = $this->individualCreate();
576 $this->contributionCreate(['contact_id' => $contactID, 'api.ContributionSoft.create' => ['amount' => 5, 'contact_id' => $contactID2]]);
577 $template = 'contribute/detail';
578 $rows = $this->callAPISuccess('report_template', 'getrows', [
579 'report_id' => $template,
580 'contribution_or_soft_value' => 'contributions_only',
581 'fields' => ['soft_credits' => 1, 'contribution_or_soft' => 1, 'sort_name' => 1],
582 'options' => ['metadata' => ['sql']],
585 "<a href='/index.php?q=civicrm/contact/view&reset=1&cid=" . $contactID2 . "'>Anderson, Anthony</a> $ 5.00",
586 $rows['values'][0]['civicrm_contribution_soft_credits']
591 * Test the amount column is populated on soft credit details.
593 public function testContributionDetailSoftCreditsOnly() {
594 $contactID = $this->individualCreate();
595 $contactID2 = $this->individualCreate();
596 $this->contributionCreate(['contact_id' => $contactID, 'api.ContributionSoft.create' => ['amount' => 5, 'contact_id' => $contactID2]]);
597 $template = 'contribute/detail';
598 $rows = $this->callAPISuccess('report_template', 'getrows', [
599 'report_id' => $template,
600 'contribution_or_soft_value' => 'soft_credits_only',
604 'financial_type_id' => '1',
605 'receive_date' => '1',
606 'total_amount' => '1',
608 'options' => ['metadata' => ['sql', 'labels']],
610 foreach (array_keys($rows['metadata']['labels']) as $header) {
611 $this->assertTrue(!empty($rows['values'][0][$header]));
616 * Test the group filter works on the various reports.
618 * @dataProvider getMembershipAndContributionReportTemplatesForGroupTests
620 * @param string $template
621 * Report template unique identifier.
623 public function testReportsWithNonSmartGroupFilter($template) {
624 $groupID = $this->setUpPopulatedGroup();
625 $rows = $this->callAPISuccess('report_template', 'getrows', [
626 'report_id' => $template,
627 'gid_value' => [$groupID],
629 'options' => ['metadata' => ['sql']],
631 $this->assertNumberOfContactsInResult(1, $rows, $template);
635 * Assert the included results match the expected.
637 * There may or may not be a group by in play so the assertion varies a little.
639 * @param int $numberExpected
641 * Rows returned from the report.
642 * @param string $template
644 protected function assertNumberOfContactsInResult($numberExpected, $rows, $template) {
645 if (isset($rows['values'][0]['civicrm_contribution_total_amount_count'])) {
646 $this->assertEquals($numberExpected, $rows['values'][0]['civicrm_contribution_total_amount_count'], 'wrong row count in ' . $template);
649 $this->assertEquals($numberExpected, count($rows['values']), 'wrong row count in ' . $template);
654 * Test the group filter works on the contribution summary when 2 groups are involved.
656 public function testContributionSummaryWithTwoGroups() {
657 $groupID = $this->setUpPopulatedGroup();
658 $groupID2 = $this->setUpPopulatedSmartGroup();
659 $rows = $this->callAPISuccess('report_template', 'getrows', [
660 'report_id' => 'contribute/summary',
661 'gid_value' => [$groupID, $groupID2],
663 'options' => ['metadata' => ['sql']],
665 $this->assertEquals(4, $rows['values'][0]['civicrm_contribution_total_amount_count']);
669 * CRM-20640: Test the group filter works on the contribution summary when a single contact in 2 groups.
671 public function testContributionSummaryWithSingleContactsInTwoGroups() {
672 list($groupID1, $individualID) = $this->setUpPopulatedGroup(TRUE);
673 // create second group and add the individual to it.
674 $groupID2 = $this->groupCreate(['name' => uniqid(), 'title' => uniqid()]);
675 $this->callAPISuccess('GroupContact', 'create', [
676 'group_id' => $groupID2,
677 'contact_id' => $individualID,
681 $rows = $this->callAPISuccess('report_template', 'getrows', [
682 'report_id' => 'contribute/summary',
683 'gid_value' => [$groupID1, $groupID2],
685 'options' => ['metadata' => ['sql']],
687 $this->assertEquals(1, $rows['count']);
691 * Test the group filter works on the contribution summary when 2 groups are involved.
693 public function testContributionSummaryWithTwoGroupsWithIntersection() {
694 $groups = $this->setUpIntersectingGroups();
696 $rows = $this->callAPISuccess('report_template', 'getrows', [
697 'report_id' => 'contribute/summary',
698 'gid_value' => $groups,
700 'options' => ['metadata' => ['sql']],
702 $this->assertEquals(7, $rows['values'][0]['civicrm_contribution_total_amount_count']);
706 * Set up a smart group for testing.
708 * The smart group includes all Households by filter. In addition an individual
709 * is created and hard-added and an individual is created that is not added.
711 * One household is hard-added as well as being in the filter.
713 * This gives us a range of scenarios for testing contacts are included only once
714 * whenever they are hard-added or in the criteria.
718 public function setUpPopulatedSmartGroup() {
719 $household1ID = $this->householdCreate();
720 $individual1ID = $this->individualCreate();
721 $householdID = $this->householdCreate();
722 $individualID = $this->individualCreate();
723 $individualIDRemoved = $this->individualCreate();
724 $groupID = $this->smartGroupCreate([], ['name' => uniqid(), 'title' => uniqid()]);
725 $this->callAPISuccess('GroupContact', 'create', [
726 'group_id' => $groupID,
727 'contact_id' => $individualIDRemoved,
728 'status' => 'Removed',
730 $this->callAPISuccess('GroupContact', 'create', [
731 'group_id' => $groupID,
732 'contact_id' => $individualID,
735 $this->callAPISuccess('GroupContact', 'create', [
736 'group_id' => $groupID,
737 'contact_id' => $householdID,
740 foreach ([$household1ID, $individual1ID, $householdID, $individualID, $individualIDRemoved] as $contactID) {
741 $this->contributionCreate(['contact_id' => $contactID, 'invoice_id' => '', 'trxn_id' => '']);
742 $this->contactMembershipCreate(['contact_id' => $contactID]);
745 // Refresh the cache for test purposes. It would be better to alter to alter the GroupContact add function to add contacts to the cache.
746 CRM_Contact_BAO_GroupContactCache
::clearGroupContactCache($groupID);
751 * Set up a static group for testing.
753 * An individual is created and hard-added and an individual is created that is not added.
755 * This gives us a range of scenarios for testing contacts are included only once
756 * whenever they are hard-added or in the criteria.
758 * @param bool $returnAddedContact
762 public function setUpPopulatedGroup($returnAddedContact = FALSE) {
763 $individual1ID = $this->individualCreate();
764 $individualID = $this->individualCreate();
765 $individualIDRemoved = $this->individualCreate();
766 $groupID = $this->groupCreate(['name' => uniqid(), 'title' => uniqid()]);
767 $this->callAPISuccess('GroupContact', 'create', [
768 'group_id' => $groupID,
769 'contact_id' => $individualIDRemoved,
770 'status' => 'Removed',
772 $this->callAPISuccess('GroupContact', 'create', [
773 'group_id' => $groupID,
774 'contact_id' => $individualID,
778 foreach ([$individual1ID, $individualID, $individualIDRemoved] as $contactID) {
779 $this->contributionCreate(['contact_id' => $contactID, 'invoice_id' => '', 'trxn_id' => '']);
780 $this->contactMembershipCreate(['contact_id' => $contactID]);
783 // Refresh the cache for test purposes. It would be better to alter to alter the GroupContact add function to add contacts to the cache.
784 CRM_Contact_BAO_GroupContactCache
::clearGroupContactCache($groupID);
786 if ($returnAddedContact) {
787 return [$groupID, $individualID];
796 public function setUpIntersectingGroups() {
797 $groupID = $this->setUpPopulatedGroup();
798 $groupID2 = $this->setUpPopulatedSmartGroup();
799 $addedToBothIndividualID = $this->individualCreate();
800 $removedFromBothIndividualID = $this->individualCreate();
801 $addedToSmartGroupRemovedFromOtherIndividualID = $this->individualCreate();
802 $removedFromSmartGroupAddedToOtherIndividualID = $this->individualCreate();
803 $this->callAPISuccess('GroupContact', 'create', [
804 'group_id' => $groupID,
805 'contact_id' => $addedToBothIndividualID,
808 $this->callAPISuccess('GroupContact', 'create', [
809 'group_id' => $groupID2,
810 'contact_id' => $addedToBothIndividualID,
813 $this->callAPISuccess('GroupContact', 'create', [
814 'group_id' => $groupID,
815 'contact_id' => $removedFromBothIndividualID,
816 'status' => 'Removed',
818 $this->callAPISuccess('GroupContact', 'create', [
819 'group_id' => $groupID2,
820 'contact_id' => $removedFromBothIndividualID,
821 'status' => 'Removed',
823 $this->callAPISuccess('GroupContact', 'create', [
824 'group_id' => $groupID2,
825 'contact_id' => $addedToSmartGroupRemovedFromOtherIndividualID,
828 $this->callAPISuccess('GroupContact', 'create', [
829 'group_id' => $groupID,
830 'contact_id' => $addedToSmartGroupRemovedFromOtherIndividualID,
831 'status' => 'Removed',
833 $this->callAPISuccess('GroupContact', 'create', [
834 'group_id' => $groupID,
835 'contact_id' => $removedFromSmartGroupAddedToOtherIndividualID,
838 $this->callAPISuccess('GroupContact', 'create', [
839 'group_id' => $groupID2,
840 'contact_id' => $removedFromSmartGroupAddedToOtherIndividualID,
841 'status' => 'Removed',
845 $addedToBothIndividualID,
846 $removedFromBothIndividualID,
847 $addedToSmartGroupRemovedFromOtherIndividualID,
848 $removedFromSmartGroupAddedToOtherIndividualID,
850 $this->contributionCreate([
851 'contact_id' => $contactID,
856 return [$groupID, $groupID2];
860 * Test Deferred Revenue Report.
862 public function testDeferredRevenueReport() {
863 $indv1 = $this->individualCreate();
864 $indv2 = $this->individualCreate();
866 'contribution_invoice_settings' => [
867 'deferred_revenue_enabled' => '1',
870 $this->callAPISuccess('Setting', 'create', $params);
871 $this->contributionCreate(
873 'contact_id' => $indv1,
874 'receive_date' => '2016-10-01',
875 'revenue_recognition_date' => date('Y-m-t', strtotime(date('ymd') . '+3 month')),
876 'financial_type_id' => 2,
879 $this->contributionCreate(
881 'contact_id' => $indv1,
882 'revenue_recognition_date' => date('Y-m-t', strtotime(date('ymd') . '+22 month')),
883 'financial_type_id' => 4,
885 'invoice_id' => NULL,
888 $this->contributionCreate(
890 'contact_id' => $indv2,
891 'revenue_recognition_date' => date('Y-m-t', strtotime(date('ymd') . '+1 month')),
892 'financial_type_id' => 4,
894 'invoice_id' => NULL,
897 $this->contributionCreate(
899 'contact_id' => $indv2,
900 'receive_date' => '2016-03-01',
901 'revenue_recognition_date' => date('Y-m-t', strtotime(date('ymd') . '+4 month')),
902 'financial_type_id' => 2,
904 'invoice_id' => NULL,
907 $rows = $this->callAPISuccess('report_template', 'getrows', [
908 'report_id' => 'contribute/deferredrevenue',
910 $this->assertEquals(2, $rows['count'], "Report failed to get row count");
912 foreach ($rows['values'] as $row) {
913 $this->assertEquals(array_pop($count), count($row['rows']), "Report failed to get row count");
918 * Test the custom data order by works when not in select.
920 * @dataProvider getMembershipAndContributionReportTemplatesForGroupTests
922 * @param string $template
923 * Report template unique identifier.
925 * @throws \CRM_Core_Exception
927 public function testReportsCustomDataOrderBy($template) {
928 $this->entity
= 'Contact';
929 $this->createCustomGroupWithFieldOfType();
930 $this->callAPISuccess('report_template', 'getrows', [
931 'report_id' => $template,
932 'contribution_or_soft_value' => 'contributions_only',
933 'order_bys' => [['column' => 'custom_' . $this->ids
['CustomField']['text'], 'order' => 'ASC']],
938 * Test the group filter works on the various reports.
940 * @dataProvider getMembershipAndContributionReportTemplatesForGroupTests
942 * @param string $template
943 * Report template unique identifier.
945 public function testReportsWithNoTInSmartGroupFilter($template) {
946 $groupID = $this->setUpPopulatedGroup();
947 $rows = $this->callAPISuccess('report_template', 'getrows', [
948 'report_id' => $template,
949 'gid_value' => [$groupID],
951 'options' => ['metadata' => ['sql']],
953 $this->assertNumberOfContactsInResult(2, $rows, $template);
957 * Test activity details report - requiring all current fields to be output.
959 public function testActivityDetails() {
960 $this->createContactsWithActivities();
962 'contact_source' => '1',
963 'contact_assignee' => '1',
964 'contact_target' => '1',
965 'contact_source_email' => '1',
966 'contact_assignee_email' => '1',
967 'contact_target_email' => '1',
968 'contact_source_phone' => '1',
969 'contact_assignee_phone' => '1',
970 'contact_target_phone' => '1',
971 'activity_type_id' => '1',
972 'activity_subject' => '1',
973 'activity_date_time' => '1',
978 'priority_id' => '1',
980 'engagement_level' => '1',
981 'address_name' => '1',
982 'street_address' => '1',
983 'supplemental_address_1' => '1',
984 'supplemental_address_2' => '1',
985 'supplemental_address_3' => '1',
986 'street_number' => '1',
987 'street_name' => '1',
988 'street_unit' => '1',
990 'postal_code' => '1',
991 'postal_code_suffix' => '1',
993 'state_province_id' => '1',
998 'current_user_op' => 'eq',
999 'current_user_value' => '0',
1000 'include_case_activities_op' => 'eq',
1001 'include_case_activities_value' => 0,
1003 1 => ['column' => 'activity_date_time', 'order' => 'ASC'],
1004 2 => ['column' => 'activity_type_id', 'order' => 'ASC'],
1008 $params['report_id'] = 'Activity';
1010 $rows = $this->callAPISuccess('report_template', 'getrows', $params)['values'];
1012 'civicrm_contact_contact_source' => 'Łąchowski-Roberts, Anthony',
1013 'civicrm_contact_contact_assignee' => '<a title=\'View Contact Summary for this Contact\' href=\'/index.php?q=civicrm/contact/view&reset=1&cid=4\'>Łąchowski-Roberts, Anthony</a>',
1014 'civicrm_contact_contact_target' => '<a title=\'View Contact Summary for this Contact\' href=\'/index.php?q=civicrm/contact/view&reset=1&cid=3\'>Brzęczysław, Anthony</a>; <a title=\'View Contact Summary for this Contact\' href=\'/index.php?q=civicrm/contact/view&reset=1&cid=4\'>Łąchowski-Roberts, Anthony</a>',
1015 'civicrm_contact_contact_source_id' => $this->contactIDs
[2],
1016 'civicrm_contact_contact_assignee_id' => $this->contactIDs
[1],
1017 'civicrm_contact_contact_target_id' => $this->contactIDs
[0] . ';' . $this->contactIDs
[1],
1018 'civicrm_email_contact_source_email' => 'anthony_anderson@civicrm.org',
1019 'civicrm_email_contact_assignee_email' => 'anthony_anderson@civicrm.org',
1020 'civicrm_email_contact_target_email' => 'techo@spying.com;anthony_anderson@civicrm.org',
1021 'civicrm_phone_contact_source_phone' => NULL,
1022 'civicrm_phone_contact_assignee_phone' => NULL,
1023 'civicrm_phone_contact_target_phone' => NULL,
1024 'civicrm_activity_id' => '1',
1025 'civicrm_activity_source_record_id' => NULL,
1026 'civicrm_activity_activity_type_id' => 'Meeting',
1027 'civicrm_activity_activity_subject' => 'Very secret meeting',
1028 'civicrm_activity_activity_date_time' => date('Y-m-d 23:59:58', strtotime('now')),
1029 'civicrm_activity_status_id' => 'Scheduled',
1030 'civicrm_activity_duration' => '120',
1031 'civicrm_activity_location' => 'Pennsylvania',
1032 'civicrm_activity_details' => 'a test activity',
1033 'civicrm_activity_priority_id' => 'Normal',
1034 'civicrm_address_address_name' => NULL,
1035 'civicrm_address_street_address' => NULL,
1036 'civicrm_address_supplemental_address_1' => NULL,
1037 'civicrm_address_supplemental_address_2' => NULL,
1038 'civicrm_address_supplemental_address_3' => NULL,
1039 'civicrm_address_street_number' => NULL,
1040 'civicrm_address_street_name' => NULL,
1041 'civicrm_address_street_unit' => NULL,
1042 'civicrm_address_city' => NULL,
1043 'civicrm_address_postal_code' => NULL,
1044 'civicrm_address_postal_code_suffix' => NULL,
1045 'civicrm_address_country_id' => NULL,
1046 'civicrm_address_state_province_id' => NULL,
1047 'civicrm_address_county_id' => NULL,
1048 'civicrm_contact_contact_source_link' => '/index.php?q=civicrm/contact/view&reset=1&cid=' . $this->contactIDs
[2],
1049 'civicrm_contact_contact_source_hover' => 'View Contact Summary for this Contact',
1050 'civicrm_activity_activity_type_id_hover' => 'View Activity Record',
1053 // This link is not relative - skip for now
1054 unset($row['civicrm_activity_activity_type_id_link']);
1055 if ($row['civicrm_email_contact_target_email'] === 'anthony_anderson@civicrm.org;techo@spying.com') {
1056 // order is unpredictable
1057 $expected['civicrm_email_contact_target_email'] = 'anthony_anderson@civicrm.org;techo@spying.com';
1060 $this->assertEquals($expected, $row);
1064 * Set up some activity data..... use some chars that challenge our utf handling.
1066 public function createContactsWithActivities() {
1067 $this->contactIDs
[] = $this->individualCreate(['last_name' => 'Brzęczysław', 'email' => 'techo@spying.com']);
1068 $this->contactIDs
[] = $this->individualCreate(['last_name' => 'Łąchowski-Roberts']);
1069 $this->contactIDs
[] = $this->individualCreate(['last_name' => 'Łąchowski-Roberts']);
1071 $this->callAPISuccess('Activity', 'create', [
1072 'subject' => 'Very secret meeting',
1073 'activity_date_time' => date('Y-m-d 23:59:58', strtotime('now')),
1075 'location' => 'Pennsylvania',
1076 'details' => 'a test activity',
1078 'activity_type_id' => 'Meeting',
1079 'source_contact_id' => $this->contactIDs
[2],
1080 'target_contact_id' => [$this->contactIDs
[0], $this->contactIDs
[1]],
1081 'assignee_contact_id' => $this->contactIDs
[1],
1086 * Test the group filter works on the contribution summary.
1088 public function testContributionDetailTotalHeader() {
1089 $contactID = $this->individualCreate();
1090 $contactID2 = $this->individualCreate();
1091 $this->contributionCreate(['contact_id' => $contactID, 'api.ContributionSoft.create' => ['amount' => 5, 'contact_id' => $contactID2]]);
1092 $template = 'contribute/detail';
1093 $rows = $this->callAPISuccess('report_template', 'getrows', [
1094 'report_id' => $template,
1095 'contribution_or_soft_value' => 'contributions_only',
1101 'financial_type_id' => '1',
1102 'receive_date' => '1',
1103 'total_amount' => '1',
1105 'order_bys' => [['column' => 'sort_name', 'order' => 'ASC', 'section' => '1']],
1106 'options' => ['metadata' => ['sql']],
1111 * Test contact subtype filter on grant report.
1113 public function testGrantReportSeparatedFilter() {
1114 $contactID = $this->individualCreate(['contact_sub_type' => ['Student', 'Parent']]);
1115 $contactID2 = $this->individualCreate();
1116 $this->callAPISuccess('Grant', 'create', ['contact_id' => $contactID, 'status_id' => 1, 'grant_type_id' => 1, 'amount_total' => 1]);
1117 $this->callAPISuccess('Grant', 'create', ['contact_id' => $contactID2, 'status_id' => 1, 'grant_type_id' => 1, 'amount_total' => 1]);
1118 $rows = $this->callAPISuccess('report_template', 'getrows', [
1119 'report_id' => 'grant/detail',
1120 'contact_sub_type_op' => 'in',
1121 'contact_sub_type_value' => ['Student'],
1123 $this->assertEquals(1, $rows['count']);
1127 * Test contact subtype filter on summary report.
1129 * @throws \CRM_Core_Exception
1131 public function testContactSubtypeNotNull() {
1132 $this->individualCreate(['contact_sub_type' => ['Student', 'Parent']]);
1133 $this->individualCreate();
1135 $rows = $this->callAPISuccess('report_template', 'getrows', [
1136 'report_id' => 'contact/summary',
1137 'contact_sub_type_op' => 'nnll',
1138 'contact_sub_type_value' => [],
1139 'contact_type_op' => 'eq',
1140 'contact_type_value' => 'Individual',
1142 $this->assertEquals(1, $rows['count']);
1146 * Test contact subtype filter on summary report.
1148 * @throws \CRM_Core_Exception
1150 public function testContactSubtypeNull() {
1151 $this->individualCreate(['contact_sub_type' => ['Student', 'Parent']]);
1152 $this->individualCreate();
1154 $rows = $this->callAPISuccess('report_template', 'getrows', [
1155 'report_id' => 'contact/summary',
1156 'contact_sub_type_op' => 'nll',
1157 'contact_sub_type_value' => [],
1158 'contact_type_op' => 'eq',
1159 'contact_type_value' => 'Individual',
1161 $this->assertEquals(1, $rows['count']);
1165 * Test PCP report to ensure total donors and total committed is accurate.
1167 public function testPcpReportTotals() {
1168 $donor1ContactId = $this->individualCreate();
1169 $donor2ContactId = $this->individualCreate();
1170 $donor3ContactId = $this->individualCreate();
1172 // We are going to create two PCP pages. We will create two contributions
1173 // on the first PCP page and one contribution on the second PCP page.
1175 // Then, we will ensure that the first PCP page reports a total of both
1176 // contributions (but not the contribution made on the second PCP page).
1178 // A PCP page requires three components:
1179 // 1. A contribution page
1183 // pcpBLockParams creates a contribution page and returns the parameters
1184 // necessary to create a PBP Block.
1185 $blockParams = $this->pcpBlockParams();
1186 $pcpBlock = CRM_PCP_BAO_PCPBlock
::create($blockParams);
1188 // Keep track of the contribution page id created. We will use this
1189 // contribution page id for all the PCP pages.
1190 $contribution_page_id = $pcpBlock->entity_id
;
1192 // pcpParams returns the parameters needed to create a PCP page.
1193 $pcpParams = $this->pcpParams();
1194 // Keep track of the owner of the page so we can properly apply the
1196 $pcpOwnerContact1Id = $pcpParams['contact_id'];
1197 $pcpParams['pcp_block_id'] = $pcpBlock->id
;
1198 $pcpParams['page_id'] = $contribution_page_id;
1199 $pcpParams['page_type'] = 'contribute';
1200 $pcp1 = CRM_PCP_BAO_PCP
::create($pcpParams);
1202 // Nice work. Now, let's create a second PCP page.
1203 $pcpParams = $this->pcpParams();
1204 // Keep track of the owner of the page.
1205 $pcpOwnerContact2Id = $pcpParams['contact_id'];
1206 // We're using the same pcpBlock id and contribution page that we created above.
1207 $pcpParams['pcp_block_id'] = $pcpBlock->id
;
1208 $pcpParams['page_id'] = $contribution_page_id;
1209 $pcpParams['page_type'] = 'contribute';
1210 $pcp2 = CRM_PCP_BAO_PCP
::create($pcpParams);
1212 // Get soft credit types, with the name column as the key.
1213 $soft_credit_types = CRM_Contribute_BAO_ContributionSoft
::buildOptions("soft_credit_type_id", NULL, ["flip" => TRUE, 'labelColumn' => 'name']);
1214 $pcp_soft_credit_type_id = $soft_credit_types['pcp'];
1216 // Create two contributions assigned to this contribution page and
1217 // assign soft credits appropriately.
1219 $contribution1params = [
1220 'contact_id' => $donor1ContactId,
1221 'contribution_page_id' => $contribution_page_id,
1222 'total_amount' => '75.00',
1224 $c1 = $this->contributionCreate($contribution1params);
1225 // Now the soft contribution.
1227 'contribution_id' => $c1,
1228 'pcp_id' => $pcp1->id
,
1229 'contact_id' => $pcpOwnerContact1Id,
1231 'currency' => 'USD',
1232 'soft_credit_type_id' => $pcp_soft_credit_type_id,
1234 $this->callAPISuccess('contribution_soft', 'create', $p);
1236 $contribution2params = [
1237 'contact_id' => $donor2ContactId,
1238 'contribution_page_id' => $contribution_page_id,
1239 'total_amount' => '25.00',
1241 $c2 = $this->contributionCreate($contribution2params);
1242 // Now the soft contribution.
1244 'contribution_id' => $c2,
1245 'pcp_id' => $pcp1->id
,
1246 'contact_id' => $pcpOwnerContact1Id,
1248 'currency' => 'USD',
1249 'soft_credit_type_id' => $pcp_soft_credit_type_id,
1251 $this->callAPISuccess('contribution_soft', 'create', $p);
1253 // Create one contributions assigned to the second PCP page
1254 $contribution3params = [
1255 'contact_id' => $donor3ContactId,
1256 'contribution_page_id' => $contribution_page_id,
1257 'total_amount' => '200.00',
1259 $c3 = $this->contributionCreate($contribution3params);
1260 // Now the soft contribution.
1262 'contribution_id' => $c3,
1263 'pcp_id' => $pcp2->id
,
1264 'contact_id' => $pcpOwnerContact2Id,
1266 'currency' => 'USD',
1267 'soft_credit_type_id' => $pcp_soft_credit_type_id,
1269 $this->callAPISuccess('contribution_soft', 'create', $p);
1271 $template = 'contribute/pcp';
1272 $rows = $this->callAPISuccess('report_template', 'getrows', [
1273 'report_id' => $template,
1274 'title' => 'My PCP',
1280 $values = $rows['values'][0];
1281 $this->assertEquals(100.00, $values['civicrm_contribution_soft_amount_1_sum'], "Total commited should be $100");
1282 $this->assertEquals(2, $values['civicrm_contribution_soft_soft_id_count'], "Total donors should be 2");
1286 * Test a report that uses getAddressColumns();
1288 public function testGetAddressColumns() {
1289 $template = 'event/participantlisting';
1290 $this->callAPISuccess('report_template', 'getrows', [
1291 'report_id' => $template,
1294 'street_address' => '1',