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