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