Autoformat /tests directory with php short array syntax
[civicrm-core.git] / tests / phpunit / api / v3 / ReportTemplateTest.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Test APIv3 civicrm_report_instance_* functions
30 *
31 * @package CiviCRM_APIv3
32 * @subpackage API_Report
33 * @group headless
34 */
35 class api_v3_ReportTemplateTest extends CiviUnitTestCase {
36
37 use CRMTraits_ACL_PermissionTrait;
38 use CRMTraits_PCP_PCPTestTrait;
39 use CRMTraits_Custom_CustomDataTrait;
40
41 protected $contactIDs = [];
42
43 /**
44 * Our group reports use an alter so transaction cleanup won't work.
45 *
46 * @throws \Exception
47 */
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);
51 parent::tearDown();
52 }
53
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',
61 ]);
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"');
72
73 // change component to null
74 $result = $this->callAPISuccess('ReportTemplate', 'create', [
75 'id' => $entityId,
76 'component' => '',
77 ]);
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');
86
87 // deactivate
88 $result = $this->callAPISuccess('ReportTemplate', 'create', [
89 'id' => $entityId,
90 'is_active' => 0,
91 ]);
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"');
99
100 // activate
101 $result = $this->callAPISuccess('ReportTemplate', 'create', [
102 'id' => $entityId,
103 'is_active' => 1,
104 ]);
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"');
112
113 $result = $this->callAPISuccess('ReportTemplate', 'delete', [
114 'id' => $entityId,
115 ]);
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"
120 ');
121 }
122
123 /**
124 * Test api to get rows from reports.
125 *
126 * @dataProvider getReportTemplatesSupportingSelectWhere
127 *
128 * @param $reportID
129 *
130 * @throws \PHPUnit\Framework\IncompleteTestError
131 */
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']],
137 ]);
138 $found = FALSE;
139 foreach ($result['metadata']['sql'] as $sql) {
140 if (strstr($sql, " = 'Organization' ")) {
141 $found = TRUE;
142 }
143 }
144 $this->assertTrue($found, $reportID);
145 }
146
147 /**
148 * Get templates suitable for SelectWhere test.
149 *
150 * @return array
151 */
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 = [
156 'contribute/repeat',
157 'member/summary',
158 'event/summary',
159 'case/summary',
160 'case/timespent',
161 'case/demographics',
162 'contact/log',
163 'contribute/bookkeeping',
164 'grant/detail',
165 'event/incomesummary',
166 'case/detail',
167 'Mailing/bounce',
168 'Mailing/summary',
169 'grant/statistics',
170 'logging/contact/detail',
171 'logging/contact/summary',
172 ];
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]);
177 }
178 }
179 return $allTemplates;
180 }
181
182 /**
183 * @param \CRM_Core_DAO $entity
184 * @param array $clauses
185 */
186 public function hookSelectWhere($entity, &$clauses) {
187 // Restrict access to cases by type
188 if ($entity == 'Contact') {
189 $clauses['contact_type'][] = " = 'Organization' ";
190 }
191 }
192
193 /**
194 * Test getrows on contact summary report.
195 */
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']);
203
204 //the second part of this test has been commented out because it relied on the db being reset to
205 // it's base state
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
209 /*
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']);
214 */
215 }
216
217 /**
218 * Test getrows on Mailing Opened report.
219 */
220 public function testReportTemplateGetRowsMailingUniqueOpened() {
221 $description = "Retrieve rows from a mailing opened report template.";
222 $this->loadXMLDataSet(dirname(__FILE__) . '/../../CRM/Mailing/BAO/queryDataset.xml');
223
224 // Check total rows without distinct
225 global $_REQUEST;
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']);
232
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']);
240
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']);
248 }
249
250 /**
251 * Test api to get rows from reports.
252 *
253 * @dataProvider getReportTemplates
254 *
255 * @param $reportID
256 *
257 * @throws \PHPUnit\Framework\IncompleteTestError
258 */
259 public function testReportTemplateGetRowsAllReports($reportID) {
260 //$reportID = 'logging/contact/summary';
261 if (stristr($reportID, 'has existing issues')) {
262 $this->markTestIncomplete($reportID);
263 }
264 if (substr($reportID, 0, '7') === 'logging') {
265 Civi::settings()->set('logging', 1);
266 }
267
268 $this->callAPISuccess('report_template', 'getrows', [
269 'report_id' => $reportID,
270 ]);
271 if (substr($reportID, 0, '7') === 'logging') {
272 Civi::settings()->set('logging', 0);
273 }
274 }
275
276 /**
277 * Test logging report when a custom data table has a table removed by hook.
278 *
279 * Here we are checking that no fatal is triggered.
280 */
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']);
288
289 $this->callAPISuccess('report_template', 'getrows', [
290 'report_id' => 'logging/contact/summary',
291 ]);
292 Civi::settings()->set('logging', 0);
293 $this->customGroupDelete($group1['id']);
294 $this->customGroupDelete($group2['id']);
295 }
296
297 /**
298 * Remove one log table from the logging spec.
299 *
300 * @param array $logTableSpec
301 */
302 public function alterLogTablesRemoveCustom(&$logTableSpec) {
303 unset($logTableSpec['civicrm_value_second_one']);
304 }
305
306 /**
307 * Test api to get rows from reports with ACLs enabled.
308 *
309 * Checking for lack of fatal error at the moment.
310 *
311 * @dataProvider getReportTemplates
312 *
313 * @param $reportID
314 *
315 * @throws \PHPUnit\Framework\IncompleteTestError
316 */
317 public function testReportTemplateGetRowsAllReportsACL($reportID) {
318 if (stristr($reportID, 'has existing issues')) {
319 $this->markTestIncomplete($reportID);
320 }
321 $this->hookClass->setHook('civicrm_aclWhereClause', [$this, 'aclWhereHookNoResults']);
322 $this->callAPISuccess('report_template', 'getrows', [
323 'report_id' => $reportID,
324 ]);
325 }
326
327 /**
328 * Test get statistics.
329 *
330 * @dataProvider getReportTemplates
331 *
332 * @param $reportID
333 *
334 * @throws \PHPUnit\Framework\IncompleteTestError
335 */
336 public function testReportTemplateGetStatisticsAllReports($reportID) {
337 if (stristr($reportID, 'has existing issues')) {
338 $this->markTestIncomplete($reportID);
339 }
340 if (in_array($reportID, ['contribute/softcredit', 'contribute/bookkeeping'])) {
341 $this->markTestIncomplete($reportID . " has non enotices when calling statistics fn");
342 }
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');
347 }
348
349 /**
350 * Data provider function for getting all templates.
351 *
352 * Note that the function needs to
353 * be static so cannot use $this->callAPISuccess
354 */
355 public static function getReportTemplates() {
356 $reportsToSkip = [
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)',
359 ];
360
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']];
365 }
366 else {
367 $reportTemplates[] = [$report['value'] . " has existing issues : " . $reportsToSkip[$report['value']]];
368 }
369 }
370
371 return $reportTemplates;
372 }
373
374 /**
375 * Get contribution templates that work with basic filter tests.
376 *
377 * These templates require minimal data config.
378 */
379 public static function getContributionReportTemplates() {
380 return [['contribute/summary'], ['contribute/detail'], ['contribute/repeat'], ['topDonor' => 'contribute/topDonor']];
381 }
382
383 /**
384 * Get contribution templates that work with basic filter tests.
385 *
386 * These templates require minimal data config.
387 */
388 public static function getMembershipReportTemplates() {
389 return [['member/detail']];
390 }
391
392 /**
393 * Get the membership and contribution reports to test.
394 *
395 * @return array
396 */
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]);
403 }
404
405 }
406 return $templates;
407 }
408
409 /**
410 * Test Lybunt report to check basic inclusion of a contact who gave in the year before the chosen year.
411 */
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',
419 'yid_value' => 2015,
420 'yid_op' => 'calendar',
421 'options' => ['metadata' => ['sql']],
422 ]);
423 $this->assertEquals(1, $rows['count'], "Report failed - the sql used to generate the results was " . print_r($rows['metadata']['sql'], TRUE));
424 }
425
426 /**
427 * Test Lybunt report applies ACLs.
428 */
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']);
436 $params = [
437 'report_id' => 'contribute/lybunt',
438 'yid_value' => 2015,
439 'yid_op' => 'calendar',
440 'options' => ['metadata' => ['sql']],
441 'check_permissions' => 1,
442 ];
443
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));
446
447 CRM_Utils_Hook::singleton()->reset();
448 }
449
450 /**
451 * Test Lybunt report to check basic inclusion of a contact who gave in the year before the chosen year.
452 */
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',
461 'yid_value' => 2015,
462 'yid_op' => 'fiscal',
463 'options' => ['metadata' => ['sql']],
464 'order_bys' => [
465 [
466 'column' => 'first_name',
467 'order' => 'ASC',
468 ],
469 ],
470 ]);
471
472 $this->assertEquals(2, $rows['count'], "Report failed - the sql used to generate the results was " . print_r($rows['metadata']['sql'], TRUE));
473
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);
487 }
488
489 /**
490 * Test Lybunt report to check basic inclusion of a contact who gave in the year before the chosen year.
491 */
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',
500 'yid_value' => 2015,
501 'yid_op' => 'fiscal',
502 'options' => ['metadata' => ['sql']],
503 'fields' => ['first_name'],
504 'order_bys' => [
505 [
506 'column' => 'last_year_total_amount',
507 'order' => 'ASC',
508 ],
509 ],
510 ]);
511
512 $this->assertEquals(2, $rows['count'], "Report failed - the sql used to generate the results was " . print_r($rows['metadata']['sql'], TRUE));
513 }
514
515 /**
516 * Test the group filter works on the contribution summary (with a smart group).
517 *
518 * @dataProvider getMembershipAndContributionReportTemplatesForGroupTests
519 *
520 * @param string $template
521 * Name of the template to test.
522 */
523 public function testContributionSummaryWithSmartGroupFilter($template) {
524 $groupID = $this->setUpPopulatedSmartGroup();
525 $rows = $this->callAPISuccess('report_template', 'getrows', [
526 'report_id' => $template,
527 'gid_value' => $groupID,
528 'gid_op' => 'in',
529 'options' => ['metadata' => ['sql']],
530 ]);
531 $this->assertNumberOfContactsInResult(3, $rows, $template);
532 if ($template === 'contribute/summary') {
533 $this->assertEquals(3, $rows['values'][0]['civicrm_contribution_total_amount_count']);
534 }
535 }
536
537 /**
538 * Test the group filter works on the contribution summary.
539 *
540 * @dataProvider getMembershipAndContributionReportTemplatesForGroupTests
541 */
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,
547 'gid_op' => 'notin',
548 'options' => ['metadata' => ['sql']],
549 ]);
550 $this->assertEquals(2, $rows['values'][0]['civicrm_contribution_total_amount_count']);
551 }
552
553 /**
554 * Test no fatal on order by per https://lab.civicrm.org/dev/core/issues/739
555 */
556 public function testCaseDetailsCaseTypeHeader() {
557 $this->callAPISuccess('report_template', 'getrows', [
558 'report_id' => 'case/detail',
559 'fields' => ['subject' => 1, 'client_sort_name' => 1],
560 'order_bys' => [
561 1 => [
562 'column' => 'case_type_title',
563 'order' => 'ASC',
564 'section' => '1',
565 ],
566 ],
567 ]);
568 }
569
570 /**
571 * Test the group filter works on the contribution summary.
572 */
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']],
583 ]);
584 $this->assertEquals(
585 "<a href='/index.php?q=civicrm/contact/view&amp;reset=1&amp;cid=" . $contactID2 . "'>Anderson, Anthony</a> $ 5.00",
586 $rows['values'][0]['civicrm_contribution_soft_credits']
587 );
588 }
589
590 /**
591 * Test the amount column is populated on soft credit details.
592 */
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',
601 'fields' => [
602 'sort_name' => '1',
603 'email' => '1',
604 'financial_type_id' => '1',
605 'receive_date' => '1',
606 'total_amount' => '1',
607 ],
608 'options' => ['metadata' => ['sql', 'labels']],
609 ]);
610 foreach (array_keys($rows['metadata']['labels']) as $header) {
611 $this->assertTrue(!empty($rows['values'][0][$header]));
612 }
613 }
614
615 /**
616 * Test the group filter works on the various reports.
617 *
618 * @dataProvider getMembershipAndContributionReportTemplatesForGroupTests
619 *
620 * @param string $template
621 * Report template unique identifier.
622 */
623 public function testReportsWithNonSmartGroupFilter($template) {
624 $groupID = $this->setUpPopulatedGroup();
625 $rows = $this->callAPISuccess('report_template', 'getrows', [
626 'report_id' => $template,
627 'gid_value' => [$groupID],
628 'gid_op' => 'in',
629 'options' => ['metadata' => ['sql']],
630 ]);
631 $this->assertNumberOfContactsInResult(1, $rows, $template);
632 }
633
634 /**
635 * Assert the included results match the expected.
636 *
637 * There may or may not be a group by in play so the assertion varies a little.
638 *
639 * @param int $numberExpected
640 * @param array $rows
641 * Rows returned from the report.
642 * @param string $template
643 */
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);
647 }
648 else {
649 $this->assertEquals($numberExpected, count($rows['values']), 'wrong row count in ' . $template);
650 }
651 }
652
653 /**
654 * Test the group filter works on the contribution summary when 2 groups are involved.
655 */
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],
662 'gid_op' => 'in',
663 'options' => ['metadata' => ['sql']],
664 ]);
665 $this->assertEquals(4, $rows['values'][0]['civicrm_contribution_total_amount_count']);
666 }
667
668 /**
669 * CRM-20640: Test the group filter works on the contribution summary when a single contact in 2 groups.
670 */
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,
678 'status' => 'Added',
679 ]);
680
681 $rows = $this->callAPISuccess('report_template', 'getrows', [
682 'report_id' => 'contribute/summary',
683 'gid_value' => [$groupID1, $groupID2],
684 'gid_op' => 'in',
685 'options' => ['metadata' => ['sql']],
686 ]);
687 $this->assertEquals(1, $rows['count']);
688 }
689
690 /**
691 * Test the group filter works on the contribution summary when 2 groups are involved.
692 */
693 public function testContributionSummaryWithTwoGroupsWithIntersection() {
694 $groups = $this->setUpIntersectingGroups();
695
696 $rows = $this->callAPISuccess('report_template', 'getrows', [
697 'report_id' => 'contribute/summary',
698 'gid_value' => $groups,
699 'gid_op' => 'in',
700 'options' => ['metadata' => ['sql']],
701 ]);
702 $this->assertEquals(7, $rows['values'][0]['civicrm_contribution_total_amount_count']);
703 }
704
705 /**
706 * Set up a smart group for testing.
707 *
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.
710 *
711 * One household is hard-added as well as being in the filter.
712 *
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.
715 *
716 * @return int
717 */
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',
729 ]);
730 $this->callAPISuccess('GroupContact', 'create', [
731 'group_id' => $groupID,
732 'contact_id' => $individualID,
733 'status' => 'Added',
734 ]);
735 $this->callAPISuccess('GroupContact', 'create', [
736 'group_id' => $groupID,
737 'contact_id' => $householdID,
738 'status' => 'Added',
739 ]);
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]);
743 }
744
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);
747 return $groupID;
748 }
749
750 /**
751 * Set up a static group for testing.
752 *
753 * An individual is created and hard-added and an individual is created that is not added.
754 *
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.
757 *
758 * @param bool $returnAddedContact
759 *
760 * @return int
761 */
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',
771 ]);
772 $this->callAPISuccess('GroupContact', 'create', [
773 'group_id' => $groupID,
774 'contact_id' => $individualID,
775 'status' => 'Added',
776 ]);
777
778 foreach ([$individual1ID, $individualID, $individualIDRemoved] as $contactID) {
779 $this->contributionCreate(['contact_id' => $contactID, 'invoice_id' => '', 'trxn_id' => '']);
780 $this->contactMembershipCreate(['contact_id' => $contactID]);
781 }
782
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);
785
786 if ($returnAddedContact) {
787 return [$groupID, $individualID];
788 }
789
790 return $groupID;
791 }
792
793 /**
794 * @return array
795 */
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,
806 'status' => 'Added',
807 ]);
808 $this->callAPISuccess('GroupContact', 'create', [
809 'group_id' => $groupID2,
810 'contact_id' => $addedToBothIndividualID,
811 'status' => 'Added',
812 ]);
813 $this->callAPISuccess('GroupContact', 'create', [
814 'group_id' => $groupID,
815 'contact_id' => $removedFromBothIndividualID,
816 'status' => 'Removed',
817 ]);
818 $this->callAPISuccess('GroupContact', 'create', [
819 'group_id' => $groupID2,
820 'contact_id' => $removedFromBothIndividualID,
821 'status' => 'Removed',
822 ]);
823 $this->callAPISuccess('GroupContact', 'create', [
824 'group_id' => $groupID2,
825 'contact_id' => $addedToSmartGroupRemovedFromOtherIndividualID,
826 'status' => 'Added',
827 ]);
828 $this->callAPISuccess('GroupContact', 'create', [
829 'group_id' => $groupID,
830 'contact_id' => $addedToSmartGroupRemovedFromOtherIndividualID,
831 'status' => 'Removed',
832 ]);
833 $this->callAPISuccess('GroupContact', 'create', [
834 'group_id' => $groupID,
835 'contact_id' => $removedFromSmartGroupAddedToOtherIndividualID,
836 'status' => 'Added',
837 ]);
838 $this->callAPISuccess('GroupContact', 'create', [
839 'group_id' => $groupID2,
840 'contact_id' => $removedFromSmartGroupAddedToOtherIndividualID,
841 'status' => 'Removed',
842 ]);
843
844 foreach ([
845 $addedToBothIndividualID,
846 $removedFromBothIndividualID,
847 $addedToSmartGroupRemovedFromOtherIndividualID,
848 $removedFromSmartGroupAddedToOtherIndividualID,
849 ] as $contactID) {
850 $this->contributionCreate([
851 'contact_id' => $contactID,
852 'invoice_id' => '',
853 'trxn_id' => '',
854 ]);
855 }
856 return [$groupID, $groupID2];
857 }
858
859 /**
860 * Test Deferred Revenue Report.
861 */
862 public function testDeferredRevenueReport() {
863 $indv1 = $this->individualCreate();
864 $indv2 = $this->individualCreate();
865 $params = [
866 'contribution_invoice_settings' => [
867 'deferred_revenue_enabled' => '1',
868 ],
869 ];
870 $this->callAPISuccess('Setting', 'create', $params);
871 $this->contributionCreate(
872 [
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,
877 ]
878 );
879 $this->contributionCreate(
880 [
881 'contact_id' => $indv1,
882 'revenue_recognition_date' => date('Y-m-t', strtotime(date('ymd') . '+22 month')),
883 'financial_type_id' => 4,
884 'trxn_id' => NULL,
885 'invoice_id' => NULL,
886 ]
887 );
888 $this->contributionCreate(
889 [
890 'contact_id' => $indv2,
891 'revenue_recognition_date' => date('Y-m-t', strtotime(date('ymd') . '+1 month')),
892 'financial_type_id' => 4,
893 'trxn_id' => NULL,
894 'invoice_id' => NULL,
895 ]
896 );
897 $this->contributionCreate(
898 [
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,
903 'trxn_id' => NULL,
904 'invoice_id' => NULL,
905 ]
906 );
907 $rows = $this->callAPISuccess('report_template', 'getrows', [
908 'report_id' => 'contribute/deferredrevenue',
909 ]);
910 $this->assertEquals(2, $rows['count'], "Report failed to get row count");
911 $count = [2, 1];
912 foreach ($rows['values'] as $row) {
913 $this->assertEquals(array_pop($count), count($row['rows']), "Report failed to get row count");
914 }
915 }
916
917 /**
918 * Test the custom data order by works when not in select.
919 *
920 * @dataProvider getMembershipAndContributionReportTemplatesForGroupTests
921 *
922 * @param string $template
923 * Report template unique identifier.
924 *
925 * @throws \CRM_Core_Exception
926 */
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']],
934 ]);
935 }
936
937 /**
938 * Test the group filter works on the various reports.
939 *
940 * @dataProvider getMembershipAndContributionReportTemplatesForGroupTests
941 *
942 * @param string $template
943 * Report template unique identifier.
944 */
945 public function testReportsWithNoTInSmartGroupFilter($template) {
946 $groupID = $this->setUpPopulatedGroup();
947 $rows = $this->callAPISuccess('report_template', 'getrows', [
948 'report_id' => $template,
949 'gid_value' => [$groupID],
950 'gid_op' => 'notin',
951 'options' => ['metadata' => ['sql']],
952 ]);
953 $this->assertNumberOfContactsInResult(2, $rows, $template);
954 }
955
956 /**
957 * Test activity details report - requiring all current fields to be output.
958 */
959 public function testActivityDetails() {
960 $this->createContactsWithActivities();
961 $fields = [
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',
974 'status_id' => '1',
975 'duration' => '1',
976 'location' => '1',
977 'details' => '1',
978 'priority_id' => '1',
979 'result' => '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',
989 'city' => '1',
990 'postal_code' => '1',
991 'postal_code_suffix' => '1',
992 'country_id' => '1',
993 'state_province_id' => '1',
994 'county_id' => '1',
995 ];
996 $params = [
997 'fields' => $fields,
998 'current_user_op' => 'eq',
999 'current_user_value' => '0',
1000 'include_case_activities_op' => 'eq',
1001 'include_case_activities_value' => 0,
1002 'order_bys' => [
1003 1 => ['column' => 'activity_date_time', 'order' => 'ASC'],
1004 2 => ['column' => 'activity_type_id', 'order' => 'ASC'],
1005 ],
1006 ];
1007
1008 $params['report_id'] = 'Activity';
1009
1010 $rows = $this->callAPISuccess('report_template', 'getrows', $params)['values'];
1011 $expected = [
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&amp;reset=1&amp;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&amp;reset=1&amp;cid=3\'>Brzęczysław, Anthony</a>; <a title=\'View Contact Summary for this Contact\' href=\'/index.php?q=civicrm/contact/view&amp;reset=1&amp;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&amp;reset=1&amp;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',
1051 ];
1052 $row = $rows[0];
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';
1058 }
1059
1060 $this->assertEquals($expected, $row);
1061 }
1062
1063 /**
1064 * Set up some activity data..... use some chars that challenge our utf handling.
1065 */
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']);
1070
1071 $this->callAPISuccess('Activity', 'create', [
1072 'subject' => 'Very secret meeting',
1073 'activity_date_time' => date('Y-m-d 23:59:58', strtotime('now')),
1074 'duration' => 120,
1075 'location' => 'Pennsylvania',
1076 'details' => 'a test activity',
1077 'status_id' => 1,
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],
1082 ]);
1083 }
1084
1085 /**
1086 * Test the group filter works on the contribution summary.
1087 */
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',
1096 'fields' => [
1097 'sort_name' => '1',
1098 'age' => '1',
1099 'email' => '1',
1100 'phone' => '1',
1101 'financial_type_id' => '1',
1102 'receive_date' => '1',
1103 'total_amount' => '1',
1104 ],
1105 'order_bys' => [['column' => 'sort_name', 'order' => 'ASC', 'section' => '1']],
1106 'options' => ['metadata' => ['sql']],
1107 ]);
1108 }
1109
1110 /**
1111 * Test contact subtype filter on grant report.
1112 */
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'],
1122 ]);
1123 $this->assertEquals(1, $rows['count']);
1124 }
1125
1126 /**
1127 * Test contact subtype filter on summary report.
1128 *
1129 * @throws \CRM_Core_Exception
1130 */
1131 public function testContactSubtypeNotNull() {
1132 $this->individualCreate(['contact_sub_type' => ['Student', 'Parent']]);
1133 $this->individualCreate();
1134
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',
1141 ]);
1142 $this->assertEquals(1, $rows['count']);
1143 }
1144
1145 /**
1146 * Test contact subtype filter on summary report.
1147 *
1148 * @throws \CRM_Core_Exception
1149 */
1150 public function testContactSubtypeNull() {
1151 $this->individualCreate(['contact_sub_type' => ['Student', 'Parent']]);
1152 $this->individualCreate();
1153
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',
1160 ]);
1161 $this->assertEquals(1, $rows['count']);
1162 }
1163
1164 /**
1165 * Test PCP report to ensure total donors and total committed is accurate.
1166 */
1167 public function testPcpReportTotals() {
1168 $donor1ContactId = $this->individualCreate();
1169 $donor2ContactId = $this->individualCreate();
1170 $donor3ContactId = $this->individualCreate();
1171
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.
1174 //
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).
1177
1178 // A PCP page requires three components:
1179 // 1. A contribution page
1180 // 2. A PCP Block
1181 // 3. A PCP page
1182
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);
1187
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;
1191
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
1195 // soft credit.
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);
1201
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);
1211
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'];
1215
1216 // Create two contributions assigned to this contribution page and
1217 // assign soft credits appropriately.
1218 // FIRST...
1219 $contribution1params = [
1220 'contact_id' => $donor1ContactId,
1221 'contribution_page_id' => $contribution_page_id,
1222 'total_amount' => '75.00',
1223 ];
1224 $c1 = $this->contributionCreate($contribution1params);
1225 // Now the soft contribution.
1226 $p = [
1227 'contribution_id' => $c1,
1228 'pcp_id' => $pcp1->id,
1229 'contact_id' => $pcpOwnerContact1Id,
1230 'amount' => 75.00,
1231 'currency' => 'USD',
1232 'soft_credit_type_id' => $pcp_soft_credit_type_id,
1233 ];
1234 $this->callAPISuccess('contribution_soft', 'create', $p);
1235 // SECOND...
1236 $contribution2params = [
1237 'contact_id' => $donor2ContactId,
1238 'contribution_page_id' => $contribution_page_id,
1239 'total_amount' => '25.00',
1240 ];
1241 $c2 = $this->contributionCreate($contribution2params);
1242 // Now the soft contribution.
1243 $p = [
1244 'contribution_id' => $c2,
1245 'pcp_id' => $pcp1->id,
1246 'contact_id' => $pcpOwnerContact1Id,
1247 'amount' => 25.00,
1248 'currency' => 'USD',
1249 'soft_credit_type_id' => $pcp_soft_credit_type_id,
1250 ];
1251 $this->callAPISuccess('contribution_soft', 'create', $p);
1252
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',
1258 ];
1259 $c3 = $this->contributionCreate($contribution3params);
1260 // Now the soft contribution.
1261 $p = [
1262 'contribution_id' => $c3,
1263 'pcp_id' => $pcp2->id,
1264 'contact_id' => $pcpOwnerContact2Id,
1265 'amount' => 200.00,
1266 'currency' => 'USD',
1267 'soft_credit_type_id' => $pcp_soft_credit_type_id,
1268 ];
1269 $this->callAPISuccess('contribution_soft', 'create', $p);
1270
1271 $template = 'contribute/pcp';
1272 $rows = $this->callAPISuccess('report_template', 'getrows', [
1273 'report_id' => $template,
1274 'title' => 'My PCP',
1275 'fields' => [
1276 'amount_1' => '1',
1277 'soft_id' => '1',
1278 ],
1279 ]);
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");
1283 }
1284
1285 /**
1286 * Test a report that uses getAddressColumns();
1287 */
1288 public function testGetAddressColumns() {
1289 $template = 'event/participantlisting';
1290 $this->callAPISuccess('report_template', 'getrows', [
1291 'report_id' => $template,
1292 'fields' => [
1293 'sort_name' => '1',
1294 'street_address' => '1',
1295 ],
1296 ]);
1297 }
1298
1299 }