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