Merge pull request #9823 from JKingsnorth/CRM-19999
[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-2017 |
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-2017
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 'fields' => array(
233 'batch_id' => array(
234 'name' => 'batch_id',
235 'title' => ts('Batch Title'),
236 ),
237 ),
238 'filters' => array(
239 'batch_id' => array(
240 'title' => ts('Batch Title'),
241 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
242 'options' => CRM_Batch_BAO_Batch::getBatches(),
243 'type' => CRM_Utils_Type::T_INT,
244 ),
245 ),
246 'group_bys' => array(
247 'batch_id' => array('title' => ts('Batch ID')),
248 ),
249 ),
250 'civicrm_contribution_soft' => array(
251 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
252 'fields' => array(
253 'soft_amount' => array(
254 'title' => ts('Soft Credit Amount Stats'),
255 'name' => 'amount',
256 'statistics' => array(
257 'count' => ts('Soft Credits'),
258 'sum' => ts('Soft Credit Aggregate'),
259 'avg' => ts('Soft Credit Avg'),
260 ),
261 ),
262 ),
263 'grouping' => 'contri-fields',
264 'filters' => array(
265 'amount' => array(
266 'title' => ts('Soft Credit Amount'),
267 ),
268 'soft_credit_type_id' => array(
269 'title' => ts('Soft Credit Type'),
270 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
271 'options' => CRM_Core_OptionGroup::values('soft_credit_type'),
272 'default' => NULL,
273 'type' => CRM_Utils_Type::T_STRING,
274 ),
275 'soft_sum' => array(
276 'title' => ts('Soft Credit Aggregate'),
277 'type' => CRM_Report_Form::OP_INT,
278 'dbAlias' => 'civicrm_contribution_soft_soft_amount_sum',
279 'having' => TRUE,
280 ),
281 'soft_count' => array(
282 'title' => ts('Soft Credits Count'),
283 'type' => CRM_Report_Form::OP_INT,
284 'dbAlias' => 'civicrm_contribution_soft_soft_amount_count',
285 'having' => TRUE,
286 ),
287 'soft_avg' => array(
288 'title' => ts('Soft Credit Avg'),
289 'type' => CRM_Report_Form::OP_INT,
290 'dbAlias' => 'civicrm_contribution_soft_soft_amount_avg',
291 'having' => TRUE,
292 ),
293 ),
294 ),
295 ) + $this->addAddressFields();
296
297 // If we have a campaign, build out the relevant elements
298 if ($campaignEnabled && !empty($this->activeCampaigns)) {
299 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
300 'title' => ts('Campaign'),
301 'default' => 'false',
302 );
303 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
304 'title' => ts('Campaign'),
305 'type' => CRM_Utils_Type::T_INT,
306 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
307 'options' => $this->activeCampaigns,
308 );
309 $this->_columns['civicrm_contribution']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
310 }
311
312 $this->_tagFilter = TRUE;
313 $this->_groupFilter = TRUE;
314 $this->_currencyColumn = 'civicrm_contribution_currency';
315 parent::__construct();
316 }
317
318 /**
319 * Set select clause.
320 */
321 public function select() {
322 $select = array();
323 $this->_columnHeaders = array();
324 foreach ($this->_columns as $tableName => $table) {
325 if (array_key_exists('group_bys', $table)) {
326 foreach ($table['group_bys'] as $fieldName => $field) {
327 if ($tableName == 'civicrm_address') {
328 $this->_addressField = TRUE;
329 }
330 if (!empty($this->_params['group_bys'][$fieldName])) {
331 switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
332 case 'YEARWEEK':
333 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
334 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
335 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
336 $field['title'] = ts('Week Beginning');
337 break;
338
339 case 'YEAR':
340 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
341 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
342 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
343 $field['title'] = ts('Year Beginning');
344 break;
345
346 case 'FISCALYEAR':
347 $config = CRM_Core_Config::singleton();
348 $fy = $config->fiscalYearStart;
349 $fiscal = self::fiscalYearOffset($field['dbAlias']);
350
351 $select[] = "DATE_ADD(MAKEDATE({$fiscal}, 1), INTERVAL ({$fy{'M'}})-1 MONTH) AS {$tableName}_{$fieldName}_start";
352 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_subtotal";
353 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_interval";
354 $field['title'] = ts('Fiscal Year Beginning');
355 break;
356
357 case 'MONTH':
358 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
359 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
360 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
361 $field['title'] = ts('Month Beginning');
362 break;
363
364 case 'DATE':
365 $select[] = "DATE({$field['dbAlias']}) as {$tableName}_{$fieldName}_start";
366 $field['title'] = ts('Date');
367 break;
368
369 case 'QUARTER':
370 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
371 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
372 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
373 $field['title'] = 'Quarter';
374 break;
375 }
376 if (!empty($this->_params['group_bys_freq'][$fieldName])) {
377 $this->_interval = $this->_params['group_bys_freq'][$fieldName];
378 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['title'] = $field['title'];
379 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
380 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName];
381
382 // just to make sure these values are transferred to rows.
383 // since we need that for calculation purpose,
384 // e.g making subtotals look nicer or graphs
385 $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
386 $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
387 }
388 }
389 }
390 }
391
392 if (array_key_exists('fields', $table)) {
393 foreach ($table['fields'] as $fieldName => $field) {
394 if ($tableName == 'civicrm_address') {
395 $this->_addressField = TRUE;
396 }
397 if (!empty($field['required']) ||
398 !empty($this->_params['fields'][$fieldName])
399 ) {
400 // only include statistics columns if set
401 if (!empty($field['statistics'])) {
402 foreach ($field['statistics'] as $stat => $label) {
403 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
404 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
405 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
406 switch (strtolower($stat)) {
407 case 'sum':
408 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
409 break;
410
411 case 'count':
412 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
413 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
414 break;
415
416 case 'avg':
417 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
418 break;
419 }
420 }
421 }
422 else {
423 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
424 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
425 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
426 }
427 }
428 }
429 }
430 }
431
432 $this->_selectClauses = $select;
433 $this->_select = "SELECT " . implode(', ', $select) . " ";
434 }
435
436 /**
437 * Set form rules.
438 *
439 * @param array $fields
440 * @param array $files
441 * @param CRM_Report_Form_Contribute_Summary $self
442 *
443 * @return array
444 */
445 public static function formRule($fields, $files, $self) {
446 // Check for searching combination of display columns and
447 // grouping criteria
448 $ignoreFields = array('total_amount', 'sort_name');
449 $errors = $self->customDataFormRule($fields, $ignoreFields);
450
451 if (empty($fields['fields']['total_amount'])) {
452 foreach (array(
453 'total_count_value',
454 'total_sum_value',
455 'total_avg_value',
456 ) as $val) {
457 if (!empty($fields[$val])) {
458 $errors[$val] = ts("Please select the Amount Statistics");
459 }
460 }
461 }
462
463 return $errors;
464 }
465
466 /**
467 * Set from clause.
468 *
469 * @param string $entity
470 *
471 * @todo fix function signature to match parent. Remove hacky passing of $entity
472 * to acheive unclear results.
473 */
474 public function from($entity = NULL) {
475 $softCreditJoinType = "LEFT";
476 if (!empty($this->_params['fields']['soft_amount']) &&
477 empty($this->_params['fields']['total_amount'])
478 ) {
479 // if its only soft credit stats, use inner join
480 $softCreditJoinType = "INNER";
481 }
482
483 $softCreditJoin = "{$softCreditJoinType} JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
484 ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
485 if ($entity == 'contribution' || empty($this->_params['fields']['soft_amount'])) {
486 $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) ";
487 }
488
489 $this->setFromBase('civicrm_contact');
490
491 $this->_from .= "
492 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
493 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
494 {$this->_aliases['civicrm_contribution']}.is_test = 0
495 {$softCreditJoin}
496 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
497 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
498 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
499 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
500 {$this->_aliases['civicrm_email']}.is_primary = 1)
501
502 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
503 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
504 {$this->_aliases['civicrm_phone']}.is_primary = 1)";
505
506 $this->addAddressFromClause();
507 //for contribution batches
508 if ($this->isTableSelected('civicrm_batch')) {
509 $this->_from .= "
510 LEFT JOIN civicrm_entity_financial_trxn eft
511 ON eft.entity_id = {$this->_aliases['civicrm_contribution']}.id AND
512 eft.entity_table = 'civicrm_contribution'
513 LEFT JOIN civicrm_entity_batch {$this->_aliases['civicrm_batch']}
514 ON ({$this->_aliases['civicrm_batch']}.entity_id = eft.financial_trxn_id
515 AND {$this->_aliases['civicrm_batch']}.entity_table = 'civicrm_financial_trxn')";
516 }
517 }
518
519 /**
520 * Set group by clause.
521 */
522 public function groupBy() {
523 $this->_groupBy = "";
524 $append = FALSE;
525 if (!empty($this->_params['group_bys']) &&
526 is_array($this->_params['group_bys'])
527 ) {
528 foreach ($this->_columns as $tableName => $table) {
529 if (array_key_exists('group_bys', $table)) {
530 foreach ($table['group_bys'] as $fieldName => $field) {
531 if (!empty($this->_params['group_bys'][$fieldName])) {
532 if (!empty($field['chart'])) {
533 $this->assign('chartSupported', TRUE);
534 }
535
536 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
537 !empty($this->_params['group_bys_freq'][$fieldName])
538 ) {
539
540 $append = "YEAR({$field['dbAlias']});;";
541 if (in_array(strtolower($this->_params['group_bys_freq'][$fieldName]),
542 array('year')
543 )) {
544 $append = '';
545 }
546 if ($this->_params['group_bys_freq'][$fieldName] == 'FISCALYEAR') {
547 $this->_groupBy[] = self::fiscalYearOffset($field['dbAlias']);
548 }
549 else {
550 $this->_groupBy[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
551 }
552 $append = TRUE;
553 }
554 else {
555 $this->_groupBy[] = $field['dbAlias'];
556 }
557 }
558 }
559 }
560 }
561
562 if (!empty($this->_statFields) &&
563 (($append && count($this->_groupBy) <= 1) || (!$append)) &&
564 !$this->_having
565 ) {
566 $this->_rollup = " WITH ROLLUP";
567 }
568 $groupBy = array();
569 foreach ($this->_groupBy as $key => $val) {
570 if (strpos($val, ';;') !== FALSE) {
571 $groupBy = array_merge($groupBy, explode(';;', $val));
572 }
573 else {
574 $groupBy[] = $this->_groupBy[$key];
575 }
576 }
577 $this->_groupBy = "GROUP BY " . implode(', ', $groupBy);
578 }
579 else {
580 $groupBy = "{$this->_aliases['civicrm_contact']}.id";
581 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_contact']}.id";
582 }
583 $this->_groupBy .= $this->_rollup;
584 // append select with ANY_VALUE() keyword
585 $this->_select = CRM_Contact_BAO_Query::appendAnyValueToSelect($this->_selectClauses, $groupBy);
586 }
587
588 /**
589 * Store having clauses as an array.
590 */
591 public function storeWhereHavingClauseArray() {
592 parent::storeWhereHavingClauseArray();
593 if (empty($this->_params['fields']['soft_amount']) &&
594 !empty($this->_havingClauses)
595 ) {
596 foreach ($this->_havingClauses as $key => $havingClause) {
597 if (stristr($havingClause, 'soft_soft')) {
598 unset($this->_havingClauses[$key]);
599 }
600 }
601 }
602 }
603
604 /**
605 * Set statistics.
606 *
607 * @param array $rows
608 *
609 * @return array
610 */
611 public function statistics(&$rows) {
612 $statistics = parent::statistics($rows);
613
614 $softCredit = CRM_Utils_Array::value('soft_amount', $this->_params['fields']);
615 $onlySoftCredit = $softCredit && !CRM_Utils_Array::value('total_amount', $this->_params['fields']);
616 $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
617
618 $this->from('contribution');
619 $this->customDataFrom();
620
621 $contriQuery = "
622 COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_count,
623 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_sum,
624 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as civicrm_contribution_total_amount_avg,
625 {$this->_aliases['civicrm_contribution']}.currency as currency
626 {$this->_from} {$this->_where}";
627
628 if ($softCredit) {
629 $this->from();
630 $select = "
631 COUNT({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_count,
632 SUM({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_sum,
633 ROUND(AVG({$this->_aliases['civicrm_contribution_soft']}.amount), 2) as civicrm_contribution_soft_soft_amount_avg";
634 $contriQuery = "{$select}, {$contriQuery}";
635 $softSQL = "SELECT {$select}, {$this->_aliases['civicrm_contribution']}.currency as currency
636 {$this->_from} {$this->_where} {$group} {$this->_having}";
637 }
638
639 $contriSQL = "SELECT {$contriQuery} {$group} {$this->_having}";
640 $contriDAO = CRM_Core_DAO::executeQuery($contriSQL);
641
642 $totalAmount = $average = $mode = $median = $softTotalAmount = $softAverage = array();
643 $count = $softCount = 0;
644 while ($contriDAO->fetch()) {
645 $totalAmount[]
646 = CRM_Utils_Money::format($contriDAO->civicrm_contribution_total_amount_sum, $contriDAO->currency) .
647 " (" . $contriDAO->civicrm_contribution_total_amount_count . ")";
648 $average[] = CRM_Utils_Money::format($contriDAO->civicrm_contribution_total_amount_avg, $contriDAO->currency);
649 $count += $contriDAO->civicrm_contribution_total_amount_count;
650 }
651
652 $groupBy = "\n{$group}, {$this->_aliases['civicrm_contribution']}.total_amount";
653 $orderBy = "\nORDER BY civicrm_contribution_total_amount_count DESC";
654 $modeSQL = "SELECT MAX(civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count,
655 SUBSTRING_INDEX(GROUP_CONCAT(amount ORDER BY mode.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
656 currency
657 FROM (SELECT {$this->_aliases['civicrm_contribution']}.total_amount as amount,
658 {$contriQuery} {$groupBy} {$orderBy}) as mode GROUP BY currency";
659
660 $mode = CRM_Contribute_BAO_Contribution::computeStats('mode', $modeSQL);
661
662 $medianSQL = "{$this->_from} {$this->_where}";
663 $median = CRM_Contribute_BAO_Contribution::computeStats('median', $medianSQL, $this->_aliases['civicrm_contribution']);
664
665 if ($softCredit) {
666 $softDAO = CRM_Core_DAO::executeQuery($softSQL);
667 while ($softDAO->fetch()) {
668 $softTotalAmount[]
669 = CRM_Utils_Money::format($softDAO->civicrm_contribution_soft_soft_amount_sum, $softDAO->currency) .
670 " (" . $softDAO->civicrm_contribution_soft_soft_amount_count . ")";
671 $softAverage[] = CRM_Utils_Money::format($softDAO->civicrm_contribution_soft_soft_amount_avg, $softDAO->currency);
672 $softCount += $softDAO->civicrm_contribution_soft_soft_amount_count;
673 }
674 }
675
676 if (!$onlySoftCredit) {
677 $statistics['counts']['amount'] = array(
678 'title' => ts('Total Amount'),
679 'value' => implode(', ', $totalAmount),
680 'type' => CRM_Utils_Type::T_STRING,
681 );
682 $statistics['counts']['count'] = array(
683 'title' => ts('Total Contributions'),
684 'value' => $count,
685 );
686 $statistics['counts']['avg'] = array(
687 'title' => ts('Average'),
688 'value' => implode(', ', $average),
689 'type' => CRM_Utils_Type::T_STRING,
690 );
691 $statistics['counts']['mode'] = array(
692 'title' => ts('Mode'),
693 'value' => implode(', ', $mode),
694 'type' => CRM_Utils_Type::T_STRING,
695 );
696 $statistics['counts']['median'] = array(
697 'title' => ts('Median'),
698 'value' => implode(', ', $median),
699 'type' => CRM_Utils_Type::T_STRING,
700 );
701 }
702 if ($softCredit) {
703 $statistics['counts']['soft_amount'] = array(
704 'title' => ts('Total Soft Credit Amount'),
705 'value' => implode(', ', $softTotalAmount),
706 'type' => CRM_Utils_Type::T_STRING,
707 );
708 $statistics['counts']['soft_count'] = array(
709 'title' => ts('Total Soft Credits'),
710 'value' => $softCount,
711 );
712 $statistics['counts']['soft_avg'] = array(
713 'title' => ts('Average Soft Credit'),
714 'value' => implode(', ', $softAverage),
715 'type' => CRM_Utils_Type::T_STRING,
716 );
717 }
718 return $statistics;
719 }
720
721 /**
722 * Post process function.
723 */
724 public function postProcess() {
725 $this->buildACLClause($this->_aliases['civicrm_contact']);
726 parent::postProcess();
727 }
728
729 /**
730 * Build table rows for output.
731 *
732 * @param string $sql
733 * @param array $rows
734 */
735 public function buildRows($sql, &$rows) {
736 $dao = CRM_Core_DAO::executeQuery($sql);
737 if (!is_array($rows)) {
738 $rows = array();
739 }
740
741 // use this method to modify $this->_columnHeaders
742 $this->modifyColumnHeaders();
743 $contriRows = array();
744 $unselectedSectionColumns = $this->unselectedSectionColumns();
745
746 //CRM-16338 if both soft-credit and contribution are enabled then process the contribution's
747 //total amount's average, count and sum separately and add it to the respective result list
748 $softCredit = (!empty($this->_params['fields']['soft_amount']) && !empty($this->_params['fields']['total_amount'])) ? TRUE : FALSE;
749 if ($softCredit) {
750 $this->from('contribution');
751 $contriSQL = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
752 $contriDAO = CRM_Core_DAO::executeQuery($contriSQL);
753 $contriFields = array(
754 'civicrm_contribution_total_amount_sum',
755 'civicrm_contribution_total_amount_avg',
756 'civicrm_contribution_total_amount_count');
757 $contriRows = array();
758 while ($contriDAO->fetch()) {
759 $contriRow = array();
760 foreach ($contriFields as $column) {
761 $contriRow[$column] = $contriDAO->$column;
762 }
763 $contriRows[] = $contriRow;
764 }
765 }
766
767 $count = 0;
768 while ($dao->fetch()) {
769 $row = array();
770 foreach ($this->_columnHeaders as $key => $value) {
771 if ($softCredit && array_key_exists($key, $contriRows[$count])) {
772 $row[$key] = $contriRows[$count][$key];
773 }
774 elseif (property_exists($dao, $key)) {
775 $row[$key] = $dao->$key;
776 }
777 }
778
779 // section headers not selected for display need to be added to row
780 foreach ($unselectedSectionColumns as $key => $values) {
781 if (property_exists($dao, $key)) {
782 $row[$key] = $dao->$key;
783 }
784 }
785
786 $count++;
787 $rows[] = $row;
788 }
789
790 }
791
792 /**
793 * Build chart.
794 *
795 * @param array $rows
796 */
797 public function buildChart(&$rows) {
798 $graphRows = array();
799
800 if (!empty($this->_params['charts'])) {
801 if (!empty($this->_params['group_bys']['receive_date'])) {
802
803 $contrib = !empty($this->_params['fields']['total_amount']) ? TRUE : FALSE;
804 $softContrib = !empty($this->_params['fields']['soft_amount']) ? TRUE : FALSE;
805
806 foreach ($rows as $key => $row) {
807 if ($row['civicrm_contribution_receive_date_subtotal']) {
808 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
809 $graphRows[$this->_interval][] = $row['civicrm_contribution_receive_date_interval'];
810 if ($softContrib && $contrib) {
811 // both contri & soft contri stats are present
812 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
813 $graphRows['multiValue'][1][] = $row['civicrm_contribution_soft_soft_amount_sum'];
814 }
815 elseif ($softContrib) {
816 // only soft contributions
817 $graphRows['multiValue'][0][] = $row['civicrm_contribution_soft_soft_amount_sum'];
818 }
819 else {
820 // only contributions
821 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
822 }
823 }
824 }
825
826 if ($softContrib && $contrib) {
827 $graphRows['barKeys'][0] = ts('Contributions');
828 $graphRows['barKeys'][1] = ts('Soft Credits');
829 $graphRows['legend'] = ts('Contributions and Soft Credits');
830 }
831 elseif ($softContrib) {
832 $graphRows['legend'] = ts('Soft Credits');
833 }
834
835 // build the chart.
836 $config = CRM_Core_Config::Singleton();
837 $graphRows['xname'] = $this->_interval;
838 $graphRows['yname'] = "Amount ({$config->defaultCurrency})";
839 CRM_Utils_OpenFlashChart::chart($graphRows, $this->_params['charts'], $this->_interval);
840 $this->assign('chartType', $this->_params['charts']);
841 }
842 }
843 }
844
845 /**
846 * Alter display of rows.
847 *
848 * Iterate through the rows retrieved via SQL and make changes for display purposes,
849 * such as rendering contacts as links.
850 *
851 * @param array $rows
852 * Rows generated by SQL, with an array for each row.
853 */
854 public function alterDisplay(&$rows) {
855 $entryFound = FALSE;
856 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
857
858 foreach ($rows as $rowNum => $row) {
859 // make count columns point to detail report
860 if (!empty($this->_params['group_bys']['receive_date']) &&
861 !empty($row['civicrm_contribution_receive_date_start']) &&
862 CRM_Utils_Array::value('civicrm_contribution_receive_date_start', $row) &&
863 !empty($row['civicrm_contribution_receive_date_subtotal'])
864 ) {
865
866 $dateStart = CRM_Utils_Date::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
867 $endDate = new DateTime($dateStart);
868 $dateEnd = array();
869
870 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
871
872 switch (strtolower($this->_params['group_bys_freq']['receive_date'])) {
873 case 'month':
874 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] + 1,
875 $dateEnd['d'] - 1, $dateEnd['Y']
876 ));
877 break;
878
879 case 'year':
880 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
881 $dateEnd['d'] - 1, $dateEnd['Y'] + 1
882 ));
883 break;
884
885 case 'fiscalyear':
886 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
887 $dateEnd['d'] - 1, $dateEnd['Y'] + 1
888 ));
889 break;
890
891 case 'yearweek':
892 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
893 $dateEnd['d'] + 6, $dateEnd['Y']
894 ));
895 break;
896
897 case 'quarter':
898 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] + 3,
899 $dateEnd['d'] - 1, $dateEnd['Y']
900 ));
901 break;
902 }
903 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
904 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
905 $this->_absoluteUrl,
906 $this->_id,
907 $this->_drilldownReport
908 );
909 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
910 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
911 $entryFound = TRUE;
912 }
913
914 // make subtotals look nicer
915 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
916 !$row['civicrm_contribution_receive_date_subtotal']
917 ) {
918 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields);
919 $entryFound = TRUE;
920 }
921
922 // convert display name to links
923 if (array_key_exists('civicrm_contact_sort_name', $row) &&
924 array_key_exists('civicrm_contact_id', $row)
925 ) {
926 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
927 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
928 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
929 );
930 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
931 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
932 $entryFound = TRUE;
933 }
934
935 // convert contribution status id to status name
936 if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_status_id', $row)) {
937 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value];
938 $entryFound = TRUE;
939 }
940
941 // If using campaigns, convert campaign_id to campaign title
942 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
943 if ($value = $row['civicrm_contribution_campaign_id']) {
944 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
945 }
946 $entryFound = TRUE;
947 }
948
949 // convert batch id to batch title
950 if (!empty($row['civicrm_batch_batch_id'])) {
951 $rows[$rowNum]['civicrm_batch_batch_id'] = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', $row['civicrm_batch_batch_id'], 'title');
952 $entryFound = TRUE;
953 }
954
955 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ? TRUE : $entryFound;
956 $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ? TRUE : $entryFound;
957
958 // skip looking further in rows, if first row itself doesn't
959 // have the column we need
960 if (!$entryFound) {
961 break;
962 }
963 }
964 }
965
966 }