Merge pull request #8466 from totten/master-path-warning
[civicrm-core.git] / CRM / Report / Form / Contribute / Summary.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2016
32 */
33 class CRM_Report_Form_Contribute_Summary extends CRM_Report_Form {
34 protected $_addressField = FALSE;
35
36 protected $_charts = array(
37 '' => 'Tabular',
38 'barChart' => 'Bar Chart',
39 'pieChart' => 'Pie Chart',
40 );
41 protected $_customGroupExtends = array('Contribution');
42 protected $_customGroupGroupBy = TRUE;
43
44 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
45
46 /**
47 * To what frequency group-by a date column
48 *
49 * @var array
50 */
51 protected $_groupByDateFreq = array(
52 'MONTH' => 'Month',
53 'YEARWEEK' => 'Week',
54 'DATE' => 'Day',
55 'QUARTER' => 'Quarter',
56 'YEAR' => 'Year',
57 'FISCALYEAR' => 'Fiscal Year',
58 );
59
60 /**
61 * This report has been optimised for group filtering.
62 *
63 * CRM-19170
64 *
65 * @var bool
66 */
67 protected $groupFilterNotOptimised = FALSE;
68
69 /**
70 * Class constructor.
71 */
72 public function __construct() {
73
74 // Check if CiviCampaign is a) enabled and b) has active campaigns
75 $config = CRM_Core_Config::singleton();
76 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
77 if ($campaignEnabled) {
78 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
79 $this->activeCampaigns = $getCampaigns['campaigns'];
80 asort($this->activeCampaigns);
81 }
82
83 $this->_columns = array(
84 'civicrm_contact' => array(
85 'dao' => 'CRM_Contact_DAO_Contact',
86 'fields' => array_merge(
87 $this->getBasicContactFields(),
88 array(
89 'sort_name' => array(
90 'title' => ts('Contact Name'),
91 'no_repeat' => TRUE,
92 ),
93 )
94 ),
95 'grouping' => 'contact-fields',
96 'group_bys' => array(
97 'id' => array('title' => ts('Contact ID')),
98 'sort_name' => array(
99 'title' => ts('Contact Name'),
100 ),
101 ),
102 ),
103 'civicrm_email' => array(
104 'dao' => 'CRM_Core_DAO_Email',
105 'fields' => array(
106 'email' => array(
107 'title' => ts('Email'),
108 'no_repeat' => TRUE,
109 ),
110 ),
111 'grouping' => 'contact-fields',
112 ),
113 'civicrm_line_item' => array(
114 'dao' => 'CRM_Price_DAO_LineItem',
115 ),
116 'civicrm_phone' => array(
117 'dao' => 'CRM_Core_DAO_Phone',
118 'fields' => array(
119 'phone' => array(
120 'title' => ts('Phone'),
121 'no_repeat' => TRUE,
122 ),
123 ),
124 'grouping' => 'contact-fields',
125 ),
126 'civicrm_financial_type' => array(
127 'dao' => 'CRM_Financial_DAO_FinancialType',
128 'fields' => array('financial_type' => NULL),
129 'grouping' => 'contri-fields',
130 'group_bys' => array(
131 'financial_type' => array('title' => ts('Financial Type')),
132 ),
133 ),
134 'civicrm_contribution' => array(
135 'dao' => 'CRM_Contribute_DAO_Contribution',
136 //'bao' => 'CRM_Contribute_BAO_Contribution',
137 'fields' => array(
138 'contribution_status_id' => array(
139 'title' => ts('Contribution Status'),
140 ),
141 'contribution_source' => array('title' => ts('Source')),
142 'currency' => array(
143 'required' => TRUE,
144 'no_display' => TRUE,
145 ),
146 'total_amount' => array(
147 'title' => ts('Contribution Amount Stats'),
148 'default' => TRUE,
149 'statistics' => array(
150 'count' => ts('Contributions'),
151 'sum' => ts('Contribution Aggregate'),
152 'avg' => ts('Contribution Avg'),
153 ),
154 ),
155 'non_deductible_amount' => array(
156 'title' => ts('Non-deductible Amount'),
157 ),
158 ),
159 'grouping' => 'contri-fields',
160 'filters' => array(
161 'receive_date' => array('operatorType' => CRM_Report_Form::OP_DATE),
162 'contribution_status_id' => array(
163 'title' => ts('Contribution Status'),
164 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
165 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
166 'default' => array(1),
167 'type' => CRM_Utils_Type::T_INT,
168 ),
169 'currency' => array(
170 'title' => ts('Currency'),
171 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
172 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
173 'default' => NULL,
174 'type' => CRM_Utils_Type::T_STRING,
175 ),
176 'financial_type_id' => array(
177 'title' => ts('Financial Type'),
178 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
179 'options' => CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes(),
180 'type' => CRM_Utils_Type::T_INT,
181 ),
182 'contribution_page_id' => array(
183 'title' => ts('Contribution Page'),
184 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
185 'options' => CRM_Contribute_PseudoConstant::contributionPage(),
186 'type' => CRM_Utils_Type::T_INT,
187 ),
188 'total_amount' => array(
189 'title' => ts('Contribution Amount'),
190 ),
191 'non_deductible_amount' => array(
192 'title' => ts('Non-deductible Amount'),
193 ),
194 'total_sum' => array(
195 'title' => ts('Contribution Aggregate'),
196 'type' => CRM_Report_Form::OP_INT,
197 'dbAlias' => 'civicrm_contribution_total_amount_sum',
198 'having' => TRUE,
199 ),
200 'total_count' => array(
201 'title' => ts('Contribution Count'),
202 'type' => CRM_Report_Form::OP_INT,
203 'dbAlias' => 'civicrm_contribution_total_amount_count',
204 'having' => TRUE,
205 ),
206 'total_avg' => array(
207 'title' => ts('Contribution Avg'),
208 'type' => CRM_Report_Form::OP_INT,
209 'dbAlias' => 'civicrm_contribution_total_amount_avg',
210 'having' => TRUE,
211 ),
212 ),
213 'group_bys' => array(
214 'receive_date' => array(
215 'frequency' => TRUE,
216 'default' => TRUE,
217 'chart' => TRUE,
218 ),
219 'contribution_source' => NULL,
220 'contribution_status_id' => array(
221 'title' => ts('Contribution Status'),
222 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
223 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
224 'default' => array(1),
225 'type' => CRM_Utils_Type::T_INT,
226 ),
227 ),
228 ),
229 'civicrm_batch' => array(
230 'dao' => 'CRM_Batch_DAO_EntityBatch',
231 'grouping' => 'contri-fields',
232 'filters' => array(
233 'batch_id' => array(
234 'title' => ts('Batch Title'),
235 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
236 'options' => CRM_Batch_BAO_Batch::getBatches(),
237 'type' => CRM_Utils_Type::T_INT,
238 ),
239 ),
240 ),
241 'civicrm_contribution_soft' => array(
242 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
243 'fields' => array(
244 'soft_amount' => array(
245 'title' => ts('Soft Credit Amount Stats'),
246 'name' => 'amount',
247 'statistics' => array(
248 'count' => ts('Soft Credits'),
249 'sum' => ts('Soft Credit Aggregate'),
250 'avg' => ts('Soft Credit Avg'),
251 ),
252 ),
253 ),
254 'grouping' => 'contri-fields',
255 'filters' => array(
256 'amount' => array(
257 'title' => ts('Soft Credit Amount'),
258 ),
259 'soft_credit_type_id' => array(
260 'title' => ts('Soft Credit Type'),
261 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
262 'options' => CRM_Core_OptionGroup::values('soft_credit_type'),
263 'default' => NULL,
264 'type' => CRM_Utils_Type::T_STRING,
265 ),
266 'soft_sum' => array(
267 'title' => ts('Soft Credit Aggregate'),
268 'type' => CRM_Report_Form::OP_INT,
269 'dbAlias' => 'civicrm_contribution_soft_soft_amount_sum',
270 'having' => TRUE,
271 ),
272 'soft_count' => array(
273 'title' => ts('Soft Credits Count'),
274 'type' => CRM_Report_Form::OP_INT,
275 'dbAlias' => 'civicrm_contribution_soft_soft_amount_count',
276 'having' => TRUE,
277 ),
278 'soft_avg' => array(
279 'title' => ts('Soft Credit Avg'),
280 'type' => CRM_Report_Form::OP_INT,
281 'dbAlias' => 'civicrm_contribution_soft_soft_amount_avg',
282 'having' => TRUE,
283 ),
284 ),
285 ),
286 ) + $this->addAddressFields();
287
288 // If we have a campaign, build out the relevant elements
289 if ($campaignEnabled && !empty($this->activeCampaigns)) {
290 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
291 'title' => ts('Campaign'),
292 'default' => 'false',
293 );
294 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
295 'title' => ts('Campaign'),
296 'type' => CRM_Utils_Type::T_INT,
297 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
298 'options' => $this->activeCampaigns,
299 );
300 $this->_columns['civicrm_contribution']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
301 }
302
303 $this->_tagFilter = TRUE;
304 $this->_groupFilter = TRUE;
305 $this->_currencyColumn = 'civicrm_contribution_currency';
306 parent::__construct();
307 }
308
309 /**
310 * Set select clause.
311 */
312 public function select() {
313 $select = array();
314 $this->_columnHeaders = array();
315 foreach ($this->_columns as $tableName => $table) {
316 if (array_key_exists('group_bys', $table)) {
317 foreach ($table['group_bys'] as $fieldName => $field) {
318 if ($tableName == 'civicrm_address') {
319 $this->_addressField = TRUE;
320 }
321 if (!empty($this->_params['group_bys'][$fieldName])) {
322 switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
323 case 'YEARWEEK':
324 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
325 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
326 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
327 $field['title'] = ts('Week Beginning');
328 break;
329
330 case 'YEAR':
331 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
332 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
333 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
334 $field['title'] = ts('Year Beginning');
335 break;
336
337 case 'FISCALYEAR':
338 $config = CRM_Core_Config::singleton();
339 $fy = $config->fiscalYearStart;
340 $fiscal = self::fiscalYearOffset($field['dbAlias']);
341
342 $select[] = "DATE_ADD(MAKEDATE({$fiscal}, 1), INTERVAL ({$fy{'M'}})-1 MONTH) AS {$tableName}_{$fieldName}_start";
343 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_subtotal";
344 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_interval";
345 $field['title'] = ts('Fiscal Year Beginning');
346 break;
347
348 case 'MONTH':
349 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
350 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
351 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
352 $field['title'] = ts('Month Beginning');
353 break;
354
355 case 'DATE':
356 $select[] = "DATE({$field['dbAlias']}) as {$tableName}_{$fieldName}_start";
357 $field['title'] = ts('Date');
358 break;
359
360 case 'QUARTER':
361 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
362 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
363 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
364 $field['title'] = 'Quarter';
365 break;
366 }
367 if (!empty($this->_params['group_bys_freq'][$fieldName])) {
368 $this->_interval = $this->_params['group_bys_freq'][$fieldName];
369 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['title'] = $field['title'];
370 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
371 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName];
372
373 // just to make sure these values are transferred to rows.
374 // since we need that for calculation purpose,
375 // e.g making subtotals look nicer or graphs
376 $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
377 $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
378 }
379 }
380 }
381 }
382
383 if (array_key_exists('fields', $table)) {
384 foreach ($table['fields'] as $fieldName => $field) {
385 if ($tableName == 'civicrm_address') {
386 $this->_addressField = TRUE;
387 }
388 if (!empty($field['required']) ||
389 !empty($this->_params['fields'][$fieldName])
390 ) {
391 // only include statistics columns if set
392 if (!empty($field['statistics'])) {
393 foreach ($field['statistics'] as $stat => $label) {
394 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
395 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
396 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
397 switch (strtolower($stat)) {
398 case 'sum':
399 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
400 break;
401
402 case 'count':
403 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
404 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
405 break;
406
407 case 'avg':
408 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
409 break;
410 }
411 }
412 }
413 else {
414 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
415 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
416 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
417 }
418 }
419 }
420 }
421 }
422
423 $this->_selectClauses = $select;
424 $this->_select = "SELECT " . implode(', ', $select) . " ";
425 }
426
427 /**
428 * Set form rules.
429 *
430 * @param array $fields
431 * @param array $files
432 * @param CRM_Report_Form_Contribute_Summary $self
433 *
434 * @return array
435 */
436 public static function formRule($fields, $files, $self) {
437 // Check for searching combination of display columns and
438 // grouping criteria
439 $ignoreFields = array('total_amount', 'sort_name');
440 $errors = $self->customDataFormRule($fields, $ignoreFields);
441
442 if (empty($fields['fields']['total_amount'])) {
443 foreach (array(
444 'total_count_value',
445 'total_sum_value',
446 'total_avg_value',
447 ) as $val) {
448 if (!empty($fields[$val])) {
449 $errors[$val] = ts("Please select the Amount Statistics");
450 }
451 }
452 }
453
454 return $errors;
455 }
456
457 /**
458 * Set from clause.
459 *
460 * @param string $entity
461 *
462 * @todo fix function signature to match parent. Remove hacky passing of $entity
463 * to acheive unclear results.
464 */
465 public function from($entity = NULL) {
466 $softCreditJoinType = "LEFT";
467 if (!empty($this->_params['fields']['soft_amount']) &&
468 empty($this->_params['fields']['total_amount'])
469 ) {
470 // if its only soft credit stats, use inner join
471 $softCreditJoinType = "INNER";
472 }
473
474 $softCreditJoin = "{$softCreditJoinType} JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
475 ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
476 if ($entity == 'contribution' || empty($this->_params['fields']['soft_amount'])) {
477 $softCreditJoin .= " AND {$this->_aliases['civicrm_contribution_soft']}.id = (SELECT MIN(id) FROM civicrm_contribution_soft cs WHERE cs.contribution_id = {$this->_aliases['civicrm_contribution']}.id) ";
478 }
479
480 $this->setFromBase('civicrm_contact');
481
482 $this->_from .= "
483 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
484 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
485 {$this->_aliases['civicrm_contribution']}.is_test = 0
486 {$softCreditJoin}
487 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
488 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
489 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
490 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
491 {$this->_aliases['civicrm_email']}.is_primary = 1)
492
493 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
494 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
495 {$this->_aliases['civicrm_phone']}.is_primary = 1)";
496
497 $this->addAddressFromClause();
498 if (!empty($this->_params['batch_id_value'])) {
499 $this->_from .= "
500 LEFT JOIN civicrm_entity_financial_trxn eft
501 ON eft.entity_id = {$this->_aliases['civicrm_contribution']}.id AND
502 eft.entity_table = 'civicrm_contribution'
503 LEFT JOIN civicrm_entity_batch {$this->_aliases['civicrm_batch']}
504 ON {$this->_aliases['civicrm_batch']}.entity_id = eft.financial_trxn_id AND
505 {$this->_aliases['civicrm_batch']}.entity_table = 'civicrm_financial_trxn'\n";
506 }
507 }
508
509 /**
510 * Set group by clause.
511 */
512 public function groupBy() {
513 $this->_groupBy = "";
514 $append = FALSE;
515 if (!empty($this->_params['group_bys']) &&
516 is_array($this->_params['group_bys'])
517 ) {
518 foreach ($this->_columns as $tableName => $table) {
519 if (array_key_exists('group_bys', $table)) {
520 foreach ($table['group_bys'] as $fieldName => $field) {
521 if (!empty($this->_params['group_bys'][$fieldName])) {
522 if (!empty($field['chart'])) {
523 $this->assign('chartSupported', TRUE);
524 }
525
526 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
527 !empty($this->_params['group_bys_freq'][$fieldName])
528 ) {
529
530 $append = "YEAR({$field['dbAlias']});;";
531 if (in_array(strtolower($this->_params['group_bys_freq'][$fieldName]),
532 array('year')
533 )) {
534 $append = '';
535 }
536 if ($this->_params['group_bys_freq'][$fieldName] == 'FISCALYEAR') {
537 $this->_groupBy[] = self::fiscalYearOffset($field['dbAlias']);
538 }
539 else {
540 $this->_groupBy[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
541 }
542 $append = TRUE;
543 }
544 else {
545 $this->_groupBy[] = $field['dbAlias'];
546 }
547 }
548 }
549 }
550 }
551
552 if (!empty($this->_statFields) &&
553 (($append && count($this->_groupBy) <= 1) || (!$append)) &&
554 !$this->_having
555 ) {
556 $this->_rollup = " WITH ROLLUP";
557 }
558 $groupBy = array();
559 foreach ($this->_groupBy as $key => $val) {
560 if (strpos($val, ';;') !== FALSE) {
561 $groupBy = array_merge($groupBy, explode(';;', $val));
562 }
563 else {
564 $groupBy[] = $this->_groupBy[$key];
565 }
566 }
567 $this->_groupBy = "GROUP BY " . implode(', ', $groupBy);
568 }
569 else {
570 $groupBy = "{$this->_aliases['civicrm_contact']}.id";
571 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_contact']}.id";
572 }
573 $this->_groupBy .= $this->_rollup;
574 // append select with ANY_VALUE() keyword
575 $this->_select = CRM_Contact_BAO_Query::appendAnyValueToSelect($this->_selectClauses, $groupBy);
576 }
577
578 /**
579 * Store having clauses as an array.
580 */
581 public function storeWhereHavingClauseArray() {
582 parent::storeWhereHavingClauseArray();
583 if (empty($this->_params['fields']['soft_amount']) &&
584 !empty($this->_havingClauses)
585 ) {
586 foreach ($this->_havingClauses as $key => $havingClause) {
587 if (stristr($havingClause, 'soft_soft')) {
588 unset($this->_havingClauses[$key]);
589 }
590 }
591 }
592 }
593
594 /**
595 * Set statistics.
596 *
597 * @param array $rows
598 *
599 * @return array
600 */
601 public function statistics(&$rows) {
602 $statistics = parent::statistics($rows);
603
604 $softCredit = CRM_Utils_Array::value('soft_amount', $this->_params['fields']);
605 $onlySoftCredit = $softCredit && !CRM_Utils_Array::value('total_amount', $this->_params['fields']);
606 $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
607
608 $this->from('contribution');
609 $this->customDataFrom();
610
611 $contriQuery = "
612 COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_count,
613 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_sum,
614 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as civicrm_contribution_total_amount_avg,
615 {$this->_aliases['civicrm_contribution']}.currency as currency
616 {$this->_from} {$this->_where}";
617
618 if ($softCredit) {
619 $this->from();
620 $select = "
621 COUNT({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_count,
622 SUM({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_sum,
623 ROUND(AVG({$this->_aliases['civicrm_contribution_soft']}.amount), 2) as civicrm_contribution_soft_soft_amount_avg";
624 $contriQuery = "{$select}, {$contriQuery}";
625 $softSQL = "SELECT {$select}, {$this->_aliases['civicrm_contribution']}.currency as currency
626 {$this->_from} {$this->_where} {$group} {$this->_having}";
627 }
628
629 $contriSQL = "SELECT {$contriQuery} {$group} {$this->_having}";
630 $contriDAO = CRM_Core_DAO::executeQuery($contriSQL);
631
632 $totalAmount = $average = $mode = $median = $softTotalAmount = $softAverage = array();
633 $count = $softCount = 0;
634 while ($contriDAO->fetch()) {
635 $totalAmount[]
636 = CRM_Utils_Money::format($contriDAO->civicrm_contribution_total_amount_sum, $contriDAO->currency) .
637 " (" . $contriDAO->civicrm_contribution_total_amount_count . ")";
638 $average[] = CRM_Utils_Money::format($contriDAO->civicrm_contribution_total_amount_avg, $contriDAO->currency);
639 $count += $contriDAO->civicrm_contribution_total_amount_count;
640 }
641
642 $groupBy = "\n{$group}, {$this->_aliases['civicrm_contribution']}.total_amount";
643 $orderBy = "\nORDER BY civicrm_contribution_total_amount_count DESC";
644 $modeSQL = "SELECT MAX(civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count,
645 SUBSTRING_INDEX(GROUP_CONCAT(amount ORDER BY mode.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
646 currency
647 FROM (SELECT {$this->_aliases['civicrm_contribution']}.total_amount as amount,
648 {$contriQuery} {$groupBy} {$orderBy}) as mode GROUP BY currency";
649
650 $mode = CRM_Contribute_BAO_Contribution::computeStats('mode', $modeSQL);
651
652 $medianSQL = "{$this->_from} {$this->_where}";
653 $median = CRM_Contribute_BAO_Contribution::computeStats('median', $medianSQL, $this->_aliases['civicrm_contribution']);
654
655 if ($softCredit) {
656 $softDAO = CRM_Core_DAO::executeQuery($softSQL);
657 while ($softDAO->fetch()) {
658 $softTotalAmount[]
659 = CRM_Utils_Money::format($softDAO->civicrm_contribution_soft_soft_amount_sum, $softDAO->currency) .
660 " (" . $softDAO->civicrm_contribution_soft_soft_amount_count . ")";
661 $softAverage[] = CRM_Utils_Money::format($softDAO->civicrm_contribution_soft_soft_amount_avg, $softDAO->currency);
662 $softCount += $softDAO->civicrm_contribution_soft_soft_amount_count;
663 }
664 }
665
666 if (!$onlySoftCredit) {
667 $statistics['counts']['amount'] = array(
668 'title' => ts('Total Amount'),
669 'value' => implode(', ', $totalAmount),
670 'type' => CRM_Utils_Type::T_STRING,
671 );
672 $statistics['counts']['count'] = array(
673 'title' => ts('Total Contributions'),
674 'value' => $count,
675 );
676 $statistics['counts']['avg'] = array(
677 'title' => ts('Average'),
678 'value' => implode(', ', $average),
679 'type' => CRM_Utils_Type::T_STRING,
680 );
681 $statistics['counts']['mode'] = array(
682 'title' => ts('Mode'),
683 'value' => implode(', ', $mode),
684 'type' => CRM_Utils_Type::T_STRING,
685 );
686 $statistics['counts']['median'] = array(
687 'title' => ts('Median'),
688 'value' => implode(', ', $median),
689 'type' => CRM_Utils_Type::T_STRING,
690 );
691 }
692 if ($softCredit) {
693 $statistics['counts']['soft_amount'] = array(
694 'title' => ts('Total Soft Credit Amount'),
695 'value' => implode(', ', $softTotalAmount),
696 'type' => CRM_Utils_Type::T_STRING,
697 );
698 $statistics['counts']['soft_count'] = array(
699 'title' => ts('Total Soft Credits'),
700 'value' => $softCount,
701 );
702 $statistics['counts']['soft_avg'] = array(
703 'title' => ts('Average Soft Credit'),
704 'value' => implode(', ', $softAverage),
705 'type' => CRM_Utils_Type::T_STRING,
706 );
707 }
708 return $statistics;
709 }
710
711 /**
712 * Post process function.
713 */
714 public function postProcess() {
715 $this->buildACLClause($this->_aliases['civicrm_contact']);
716 parent::postProcess();
717 }
718
719 /**
720 * Build table rows for output.
721 *
722 * @param string $sql
723 * @param array $rows
724 */
725 public function buildRows($sql, &$rows) {
726 $dao = CRM_Core_DAO::executeQuery($sql);
727 if (!is_array($rows)) {
728 $rows = array();
729 }
730
731 // use this method to modify $this->_columnHeaders
732 $this->modifyColumnHeaders();
733 $contriRows = array();
734 $unselectedSectionColumns = $this->unselectedSectionColumns();
735
736 //CRM-16338 if both soft-credit and contribution are enabled then process the contribution's
737 //total amount's average, count and sum separately and add it to the respective result list
738 $softCredit = (!empty($this->_params['fields']['soft_amount']) && !empty($this->_params['fields']['total_amount'])) ? TRUE : FALSE;
739 if ($softCredit) {
740 $this->from('contribution');
741 $contriSQL = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
742 $contriDAO = CRM_Core_DAO::executeQuery($contriSQL);
743 $contriFields = array(
744 'civicrm_contribution_total_amount_sum',
745 'civicrm_contribution_total_amount_avg',
746 'civicrm_contribution_total_amount_count');
747 $contriRows = array();
748 while ($contriDAO->fetch()) {
749 $contriRow = array();
750 foreach ($contriFields as $column) {
751 $contriRow[$column] = $contriDAO->$column;
752 }
753 $contriRows[] = $contriRow;
754 }
755 }
756
757 $count = 0;
758 while ($dao->fetch()) {
759 $row = array();
760 foreach ($this->_columnHeaders as $key => $value) {
761 if ($softCredit && array_key_exists($key, $contriRows[$count])) {
762 $row[$key] = $contriRows[$count][$key];
763 }
764 elseif (property_exists($dao, $key)) {
765 $row[$key] = $dao->$key;
766 }
767 }
768
769 // section headers not selected for display need to be added to row
770 foreach ($unselectedSectionColumns as $key => $values) {
771 if (property_exists($dao, $key)) {
772 $row[$key] = $dao->$key;
773 }
774 }
775
776 $count++;
777 $rows[] = $row;
778 }
779
780 }
781
782 /**
783 * Build chart.
784 *
785 * @param array $rows
786 */
787 public function buildChart(&$rows) {
788 $graphRows = array();
789
790 if (!empty($this->_params['charts'])) {
791 if (!empty($this->_params['group_bys']['receive_date'])) {
792
793 $contrib = !empty($this->_params['fields']['total_amount']) ? TRUE : FALSE;
794 $softContrib = !empty($this->_params['fields']['soft_amount']) ? TRUE : FALSE;
795
796 foreach ($rows as $key => $row) {
797 if ($row['civicrm_contribution_receive_date_subtotal']) {
798 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
799 $graphRows[$this->_interval][] = $row['civicrm_contribution_receive_date_interval'];
800 if ($softContrib && $contrib) {
801 // both contri & soft contri stats are present
802 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
803 $graphRows['multiValue'][1][] = $row['civicrm_contribution_soft_soft_amount_sum'];
804 }
805 elseif ($softContrib) {
806 // only soft contributions
807 $graphRows['multiValue'][0][] = $row['civicrm_contribution_soft_soft_amount_sum'];
808 }
809 else {
810 // only contributions
811 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
812 }
813 }
814 }
815
816 if ($softContrib && $contrib) {
817 $graphRows['barKeys'][0] = ts('Contributions');
818 $graphRows['barKeys'][1] = ts('Soft Credits');
819 $graphRows['legend'] = ts('Contributions and Soft Credits');
820 }
821 elseif ($softContrib) {
822 $graphRows['legend'] = ts('Soft Credits');
823 }
824
825 // build the chart.
826 $config = CRM_Core_Config::Singleton();
827 $graphRows['xname'] = $this->_interval;
828 $graphRows['yname'] = "Amount ({$config->defaultCurrency})";
829 CRM_Utils_OpenFlashChart::chart($graphRows, $this->_params['charts'], $this->_interval);
830 $this->assign('chartType', $this->_params['charts']);
831 }
832 }
833 }
834
835 /**
836 * Alter display of rows.
837 *
838 * Iterate through the rows retrieved via SQL and make changes for display purposes,
839 * such as rendering contacts as links.
840 *
841 * @param array $rows
842 * Rows generated by SQL, with an array for each row.
843 */
844 public function alterDisplay(&$rows) {
845 $entryFound = FALSE;
846 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
847
848 foreach ($rows as $rowNum => $row) {
849 // make count columns point to detail report
850 if (!empty($this->_params['group_bys']['receive_date']) &&
851 !empty($row['civicrm_contribution_receive_date_start']) &&
852 CRM_Utils_Array::value('civicrm_contribution_receive_date_start', $row) &&
853 !empty($row['civicrm_contribution_receive_date_subtotal'])
854 ) {
855
856 $dateStart = CRM_Utils_Date::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
857 $endDate = new DateTime($dateStart);
858 $dateEnd = array();
859
860 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
861
862 switch (strtolower($this->_params['group_bys_freq']['receive_date'])) {
863 case 'month':
864 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] + 1,
865 $dateEnd['d'] - 1, $dateEnd['Y']
866 ));
867 break;
868
869 case 'year':
870 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
871 $dateEnd['d'] - 1, $dateEnd['Y'] + 1
872 ));
873 break;
874
875 case 'fiscalyear':
876 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
877 $dateEnd['d'] - 1, $dateEnd['Y'] + 1
878 ));
879 break;
880
881 case 'yearweek':
882 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
883 $dateEnd['d'] + 6, $dateEnd['Y']
884 ));
885 break;
886
887 case 'quarter':
888 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] + 3,
889 $dateEnd['d'] - 1, $dateEnd['Y']
890 ));
891 break;
892 }
893 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
894 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
895 $this->_absoluteUrl,
896 $this->_id,
897 $this->_drilldownReport
898 );
899 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
900 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
901 $entryFound = TRUE;
902 }
903
904 // make subtotals look nicer
905 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
906 !$row['civicrm_contribution_receive_date_subtotal']
907 ) {
908 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields);
909 $entryFound = TRUE;
910 }
911
912 // convert display name to links
913 if (array_key_exists('civicrm_contact_sort_name', $row) &&
914 array_key_exists('civicrm_contact_id', $row)
915 ) {
916 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
917 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
918 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
919 );
920 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
921 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
922 $entryFound = TRUE;
923 }
924
925 // convert contribution status id to status name
926 if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_status_id', $row)) {
927 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value];
928 $entryFound = TRUE;
929 }
930
931 // If using campaigns, convert campaign_id to campaign title
932 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
933 if ($value = $row['civicrm_contribution_campaign_id']) {
934 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
935 }
936 $entryFound = TRUE;
937 }
938
939 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ? TRUE : $entryFound;
940 $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ? TRUE : $entryFound;
941
942 // skip looking further in rows, if first row itself doesn't
943 // have the column we need
944 if (!$entryFound) {
945 break;
946 }
947 }
948 }
949
950 }