Merge pull request #5097 from PalanteJon/CRM-15917
[civicrm-core.git] / CRM / Report / Form / Contribute / Summary.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35 class CRM_Report_Form_Contribute_Summary extends CRM_Report_Form {
36 protected $_addressField = FALSE;
37
38 protected $_charts = array(
39 '' => 'Tabular',
40 'barChart' => 'Bar Chart',
41 'pieChart' => 'Pie Chart',
42 );
43 protected $_customGroupExtends = array('Contribution');
44 protected $_customGroupGroupBy = TRUE;
45
46 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
47
48 /**
49 */
50 public function __construct() {
51
52 // Check if CiviCampaign is a) enabled and b) has active campaigns
53 $config = CRM_Core_Config::singleton();
54 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
55 if ($campaignEnabled) {
56 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
57 $this->activeCampaigns = $getCampaigns['campaigns'];
58 asort($this->activeCampaigns);
59 }
60
61 $this->_columns = array(
62 'civicrm_contact' => array(
63 'dao' => 'CRM_Contact_DAO_Contact',
64 'fields' => array(
65 'sort_name' => array(
66 'title' => ts('Contact Name'),
67 'no_repeat' => TRUE,
68 ),
69 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
70 'id' => array(
71 'no_display' => TRUE,
72 'required' => TRUE,
73 ),
74 'contact_type' => array(
75 'title' => ts('Contact Type'),
76 ),
77 'contact_sub_type' => array(
78 'title' => ts('Contact Subtype'),
79 ),
80 ),
81 'grouping' => 'contact-fields',
82 'group_bys' => array(
83 'id' => array('title' => ts('Contact ID')),
84 'sort_name' => array(
85 'title' => ts('Contact Name'),
86 ),
87 ),
88 ),
89 'civicrm_email' => array(
90 'dao' => 'CRM_Core_DAO_Email',
91 'fields' => array(
92 'email' => array(
93 'title' => ts('Email'),
94 'no_repeat' => TRUE,
95 ),
96 ),
97 'grouping' => 'contact-fields',
98 ),
99 'civicrm_phone' => array(
100 'dao' => 'CRM_Core_DAO_Phone',
101 'fields' => array(
102 'phone' => array(
103 'title' => ts('Phone'),
104 'no_repeat' => TRUE,
105 ),
106 ),
107 'grouping' => 'contact-fields',
108 ),
109 'civicrm_financial_type' => array(
110 'dao' => 'CRM_Financial_DAO_FinancialType',
111 'fields' => array('financial_type' => NULL),
112 'grouping' => 'contri-fields',
113 'group_bys' => array(
114 'financial_type' => array('title' => ts('Financial Type')),
115 ),
116 ),
117 'civicrm_contribution' => array(
118 'dao' => 'CRM_Contribute_DAO_Contribution',
119 //'bao' => 'CRM_Contribute_BAO_Contribution',
120 'fields' => array(
121 'contribution_source' => array('title' => ts('Source')),
122 'currency' => array(
123 'required' => TRUE,
124 'no_display' => TRUE,
125 ),
126 'total_amount' => array(
127 'title' => ts('Contribution Amount Stats'),
128 'default' => TRUE,
129 'statistics' => array(
130 'sum' => ts('Contribution Aggregate'),
131 'count' => ts('Contributions'),
132 'avg' => ts('Contribution Avg'),
133 ),
134 ),
135 ),
136 'grouping' => 'contri-fields',
137 'filters' => array(
138 'receive_date' => array('operatorType' => CRM_Report_Form::OP_DATE),
139 'contribution_status_id' => array(
140 'title' => ts('Contribution Status'),
141 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
142 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
143 'default' => array(1),
144 'type' => CRM_Utils_Type::T_INT,
145 ),
146 'currency' => array(
147 'title' => 'Currency',
148 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
149 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
150 'default' => NULL,
151 'type' => CRM_Utils_Type::T_STRING,
152 ),
153 'financial_type_id' => array(
154 'title' => ts('Financial Type'),
155 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
156 'options' => CRM_Contribute_PseudoConstant::financialType(),
157 'type' => CRM_Utils_Type::T_INT,
158 ),
159 'contribution_page_id' => array(
160 'title' => ts('Contribution Page'),
161 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
162 'options' => CRM_Contribute_PseudoConstant::contributionPage(),
163 'type' => CRM_Utils_Type::T_INT,
164 ),
165 'total_amount' => array(
166 'title' => ts('Contribution Amount'),
167 ),
168 'total_sum' => array(
169 'title' => ts('Contribution Aggregate'),
170 'type' => CRM_Report_Form::OP_INT,
171 'dbAlias' => 'civicrm_contribution_total_amount_sum',
172 'having' => TRUE,
173 ),
174 'total_count' => array(
175 'title' => ts('Contribution Count'),
176 'type' => CRM_Report_Form::OP_INT,
177 'dbAlias' => 'civicrm_contribution_total_amount_count',
178 'having' => TRUE,
179 ),
180 'total_avg' => array(
181 'title' => ts('Contribution Avg'),
182 'type' => CRM_Report_Form::OP_INT,
183 'dbAlias' => 'civicrm_contribution_total_amount_avg',
184 'having' => TRUE,
185 ),
186 ),
187 'group_bys' => array(
188 'receive_date' => array(
189 'frequency' => TRUE,
190 'default' => TRUE,
191 'chart' => TRUE,
192 ),
193 'contribution_source' => NULL,
194 ),
195 ),
196 'civicrm_contribution_soft' => array(
197 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
198 'fields' => array(
199 'soft_amount' => array(
200 'title' => ts('Soft Credit Amount Stats'),
201 'name' => 'amount',
202 'statistics' => array(
203 'sum' => ts('Soft Credit Aggregate'),
204 'count' => ts('Soft Credits'),
205 'avg' => ts('Soft Credit Avg'),
206 ),
207 ),
208 ),
209 'grouping' => 'contri-fields',
210 'filters' => array(
211 'amount' => array(
212 'title' => ts('Soft Credit Amount'),
213 ),
214 'soft_credit_type_id' => array(
215 'title' => 'Soft Credit Type',
216 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
217 'options' => CRM_Core_OptionGroup::values('soft_credit_type'),
218 'default' => NULL,
219 'type' => CRM_Utils_Type::T_STRING,
220 ),
221 'soft_sum' => array(
222 'title' => ts('Soft Credit Aggregate'),
223 'type' => CRM_Report_Form::OP_INT,
224 'dbAlias' => 'civicrm_contribution_soft_soft_amount_sum',
225 'having' => TRUE,
226 ),
227 'soft_count' => array(
228 'title' => ts('Soft Credits Count'),
229 'type' => CRM_Report_Form::OP_INT,
230 'dbAlias' => 'civicrm_contribution_soft_soft_amount_count',
231 'having' => TRUE,
232 ),
233 'soft_avg' => array(
234 'title' => ts('Soft Credit Avg'),
235 'type' => CRM_Report_Form::OP_INT,
236 'dbAlias' => 'civicrm_contribution_soft_soft_amount_avg',
237 'having' => TRUE,
238 ),
239 ),
240 ),
241 ) + $this->addAddressFields();
242
243 // If we have a campaign, build out the relevant elements
244 if ($campaignEnabled && !empty($this->activeCampaigns)) {
245 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
246 'title' => 'Campaign',
247 'default' => 'false',
248 );
249 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
250 'title' => ts('Campaign'),
251 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
252 'options' => $this->activeCampaigns,
253 );
254 $this->_columns['civicrm_contribution']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
255 }
256
257 $this->_tagFilter = TRUE;
258 $this->_groupFilter = TRUE;
259 $this->_currencyColumn = 'civicrm_contribution_currency';
260 parent::__construct();
261 }
262
263 public function preProcess() {
264 parent::preProcess();
265 }
266
267 /**
268 * @param bool $freeze
269 *
270 * @return array
271 */
272 public function setDefaultValues($freeze = TRUE) {
273 return parent::setDefaultValues($freeze);
274 }
275
276 public function select() {
277 $select = array();
278 $this->_columnHeaders = array();
279 foreach ($this->_columns as $tableName => $table) {
280 if (array_key_exists('group_bys', $table)) {
281 foreach ($table['group_bys'] as $fieldName => $field) {
282 if ($tableName == 'civicrm_address') {
283 $this->_addressField = TRUE;
284 }
285 if (!empty($this->_params['group_bys'][$fieldName])) {
286 switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
287 case 'YEARWEEK':
288 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
289 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
290 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
291 $field['title'] = 'Week';
292 break;
293
294 case 'YEAR':
295 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
296 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
297 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
298 $field['title'] = 'Year';
299 break;
300
301 case 'MONTH':
302 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
303 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
304 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
305 $field['title'] = 'Month';
306 break;
307
308 case 'QUARTER':
309 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
310 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
311 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
312 $field['title'] = 'Quarter';
313 break;
314 }
315 if (!empty($this->_params['group_bys_freq'][$fieldName])) {
316 $this->_interval = $field['title'];
317 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
318 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
319 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName];
320
321 // just to make sure these values are transfered to rows.
322 // since we need that for calculation purpose,
323 // e.g making subtotals look nicer or graphs
324 $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
325 $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
326 }
327 }
328 }
329 }
330
331 if (array_key_exists('fields', $table)) {
332 foreach ($table['fields'] as $fieldName => $field) {
333 if ($tableName == 'civicrm_address') {
334 $this->_addressField = TRUE;
335 }
336 if (!empty($field['required']) ||
337 !empty($this->_params['fields'][$fieldName])
338 ) {
339
340 // only include statistics columns if set
341 if (!empty($field['statistics'])) {
342 foreach ($field['statistics'] as $stat => $label) {
343 switch (strtolower($stat)) {
344 case 'sum':
345 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
346 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
347 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
348 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
349 break;
350
351 case 'count':
352 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
353 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
354 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
355 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
356 break;
357
358 case 'avg':
359 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
360 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
361 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
362 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
363 break;
364 }
365 }
366 }
367 else {
368 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
369 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
370 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
371 }
372 }
373 }
374 }
375 }
376
377 $this->_select = "SELECT " . implode(', ', $select) . " ";
378 }
379
380 /**
381 * @param $fields
382 * @param $files
383 * @param $self
384 *
385 * @return array
386 */
387 public static function formRule($fields, $files, $self) {
388 $errors = $grouping = array();
389 //check for searching combination of dispaly columns and
390 //grouping criteria
391 $ignoreFields = array('total_amount', 'sort_name');
392 $errors = $self->customDataFormRule($fields, $ignoreFields);
393
394 if (empty($fields['group_bys']['receive_date'])) {
395 if (!empty($fields['receive_date_relative']) ||
396 CRM_Utils_Date::isDate($fields['receive_date_from']) ||
397 CRM_Utils_Date::isDate($fields['receive_date_to'])
398 ) {
399 $errors['receive_date_relative'] = ts("Do not use filter on Date if group by Receive Date is not used ");
400 }
401 }
402 if (empty($fields['fields']['total_amount'])) {
403 foreach (array(
404 'total_count_value',
405 'total_sum_value',
406 'total_avg_value',
407 ) as $val) {
408 if (!empty($fields[$val])) {
409 $errors[$val] = ts("Please select the Amount Statistics");
410 }
411 }
412 }
413
414 return $errors;
415 }
416
417 public function from() {
418 $softCreditJoin = "LEFT";
419 if (!empty($this->_params['fields']['soft_amount']) &&
420 empty($this->_params['fields']['total_amount'])
421 ) {
422 // if its only soft credit stats, use inner join
423 $softCreditJoin = "INNER";
424 }
425
426 $this->_from = "
427 FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
428 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
429 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
430 {$this->_aliases['civicrm_contribution']}.is_test = 0
431 {$softCreditJoin} JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
432 ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id = {$this->_aliases['civicrm_contribution']}.id
433 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
434 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
435 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
436 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
437 {$this->_aliases['civicrm_email']}.is_primary = 1)
438
439 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
440 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
441 {$this->_aliases['civicrm_phone']}.is_primary = 1)";
442
443 if ($this->_addressField) {
444 $this->_from .= "
445 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
446 ON {$this->_aliases['civicrm_contact']}.id =
447 {$this->_aliases['civicrm_address']}.contact_id AND
448 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
449 }
450 }
451
452 public function groupBy() {
453 $this->_groupBy = "";
454 $append = FALSE;
455 if (is_array($this->_params['group_bys']) &&
456 !empty($this->_params['group_bys'])
457 ) {
458 foreach ($this->_columns as $tableName => $table) {
459 if (array_key_exists('group_bys', $table)) {
460 foreach ($table['group_bys'] as $fieldName => $field) {
461 if (!empty($this->_params['group_bys'][$fieldName])) {
462 if (!empty($field['chart'])) {
463 $this->assign('chartSupported', TRUE);
464 }
465
466 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
467 !empty($this->_params['group_bys_freq'][$fieldName])
468 ) {
469
470 $append = "YEAR({$field['dbAlias']}),";
471 if (in_array(strtolower($this->_params['group_bys_freq'][$fieldName]),
472 array('year')
473 )) {
474 $append = '';
475 }
476 $this->_groupBy[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
477 $append = TRUE;
478 }
479 else {
480 $this->_groupBy[] = $field['dbAlias'];
481 }
482 }
483 }
484 }
485 }
486
487 if (!empty($this->_statFields) &&
488 (($append && count($this->_groupBy) <= 1) || (!$append)) &&
489 !$this->_having
490 ) {
491 $this->_rollup = " WITH ROLLUP";
492 }
493 $this->_groupBy = "GROUP BY " . implode(', ', $this->_groupBy) .
494 " {$this->_rollup} ";
495 }
496 else {
497 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_contact']}.id";
498 }
499 }
500
501 public function storeWhereHavingClauseArray() {
502 parent::storeWhereHavingClauseArray();
503 if (empty($this->_params['fields']['soft_amount']) &&
504 !empty($this->_havingClauses)
505 ) {
506 foreach ($this->_havingClauses as $key => $havingClause) {
507 if (stristr($havingClause, 'soft_soft')) {
508 unset($this->_havingClauses[$key]);
509 }
510 }
511 }
512 }
513
514 /**
515 * @param $rows
516 *
517 * @return array
518 */
519 public function statistics(&$rows) {
520 $statistics = parent::statistics($rows);
521
522 $softCredit = CRM_Utils_Array::value('soft_amount', $this->_params['fields']);
523 $onlySoftCredit = $softCredit &&
524 !CRM_Utils_Array::value('total_amount', $this->_params['fields']);
525 $totalAmount = $average = $softTotalAmount = $softAverage = array();
526
527 $select = "SELECT
528 COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_count,
529 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_sum,
530 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as civicrm_contribution_total_amount_avg,
531 {$this->_aliases['civicrm_contribution']}.currency as currency";
532
533 if ($softCredit) {
534 $select .= ",
535 COUNT({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_count,
536 SUM({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_sum,
537 ROUND(AVG({$this->_aliases['civicrm_contribution_soft']}.amount), 2) as civicrm_contribution_soft_soft_amount_avg";
538 }
539 $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
540 $sql = "{$select} {$this->_from} {$this->_where} {$group} {$this->_having}";
541
542 $dao = CRM_Core_DAO::executeQuery($sql);
543 $totalAmount = $average = $softTotalAmount = $softAverage = array();
544 $count = $softCount = 0;
545 while ($dao->fetch()) {
546 $totalAmount[]
547 = CRM_Utils_Money::format($dao->civicrm_contribution_total_amount_sum, $dao->currency) .
548 " (" . $dao->civicrm_contribution_total_amount_count . ")";
549 $average[] = CRM_Utils_Money::format($dao->civicrm_contribution_total_amount_avg, $dao->currency);
550 $count += $dao->civicrm_contribution_total_amount_count;
551
552 if ($softCredit) {
553 $softTotalAmount[]
554 = CRM_Utils_Money::format($dao->civicrm_contribution_soft_soft_amount_sum, $dao->currency) .
555 " (" . $dao->civicrm_contribution_soft_soft_amount_count . ")";
556 $softAverage[] = CRM_Utils_Money::format($dao->civicrm_contribution_soft_soft_amount_avg, $dao->currency);
557 $softCount += $dao->civicrm_contribution_soft_soft_amount_count;
558 }
559 }
560
561 if (!$onlySoftCredit) {
562 $statistics['counts']['amount'] = array(
563 'title' => ts('Total Amount'),
564 'value' => implode(', ', $totalAmount),
565 'type' => CRM_Utils_Type::T_STRING,
566 );
567 $statistics['counts']['count'] = array(
568 'title' => ts('Total Contributions'),
569 'value' => $count,
570 );
571 $statistics['counts']['avg'] = array(
572 'title' => ts('Average'),
573 'value' => implode(', ', $average),
574 'type' => CRM_Utils_Type::T_STRING,
575 );
576 }
577 if ($softCredit) {
578 $statistics['counts']['soft_amount'] = array(
579 'title' => ts('Total Soft Credit Amount'),
580 'value' => implode(', ', $softTotalAmount),
581 'type' => CRM_Utils_Type::T_STRING,
582 );
583 $statistics['counts']['soft_count'] = array(
584 'title' => ts('Total Soft Credits'),
585 'value' => $softCount,
586 );
587 $statistics['counts']['soft_avg'] = array(
588 'title' => ts('Average Soft Credit'),
589 'value' => implode(', ', $softAverage),
590 'type' => CRM_Utils_Type::T_STRING,
591 );
592 }
593 return $statistics;
594 }
595
596 public function postProcess() {
597 $this->buildACLClause($this->_aliases['civicrm_contact']);
598 parent::postProcess();
599 }
600
601 /**
602 * @param $rows
603 */
604 public function buildChart(&$rows) {
605 $graphRows = array();
606
607 if (!empty($this->_params['charts'])) {
608 if (!empty($this->_params['group_bys']['receive_date'])) {
609
610 $contrib = !empty($this->_params['fields']['total_amount']) ? TRUE : FALSE;
611 $softContrib = !empty($this->_params['fields']['soft_amount']) ? TRUE : FALSE;
612
613 foreach ($rows as $key => $row) {
614 if ($row['civicrm_contribution_receive_date_subtotal']) {
615 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
616 $graphRows[$this->_interval][] = $row['civicrm_contribution_receive_date_interval'];
617 if ($softContrib && $contrib) {
618 // both contri & soft contri stats are present
619 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
620 $graphRows['multiValue'][1][] = $row['civicrm_contribution_soft_soft_amount_sum'];
621 }
622 elseif ($softContrib) {
623 // only soft contributions
624 $graphRows['multiValue'][0][] = $row['civicrm_contribution_soft_soft_amount_sum'];
625 }
626 else {
627 // only contributions
628 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
629 }
630 }
631 }
632
633 if ($softContrib && $contrib) {
634 $graphRows['barKeys'][0] = ts('Contributions');
635 $graphRows['barKeys'][1] = ts('Soft Credits');
636 $graphRows['legend'] = ts('Contributions and Soft Credits');
637 }
638 elseif ($softContrib) {
639 $graphRows['legend'] = ts('Soft Credits');
640 }
641
642 // build the chart.
643 $config = CRM_Core_Config::Singleton();
644 $graphRows['xname'] = $this->_interval;
645 $graphRows['yname'] = "Amount ({$config->defaultCurrency})";
646 CRM_Utils_OpenFlashChart::chart($graphRows, $this->_params['charts'], $this->_interval);
647 $this->assign('chartType', $this->_params['charts']);
648 }
649 }
650 }
651
652 /**
653 * Alter display of rows.
654 *
655 * Iterate through the rows retrieved via SQL and make changes for display purposes,
656 * such as rendering contacts as links.
657 *
658 * @param array $rows
659 * Rows generated by SQL, with an array for each row.
660 */
661 public function alterDisplay(&$rows) {
662 $entryFound = FALSE;
663
664 foreach ($rows as $rowNum => $row) {
665 // make count columns point to detail report
666 if (!empty($this->_params['group_bys']['receive_date']) &&
667 !empty($row['civicrm_contribution_receive_date_start']) &&
668 CRM_Utils_Array::value('civicrm_contribution_receive_date_start', $row) &&
669 !empty($row['civicrm_contribution_receive_date_subtotal'])
670 ) {
671
672 $dateStart = CRM_Utils_Date::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
673 $endDate = new DateTime($dateStart);
674 $dateEnd = array();
675
676 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
677
678 switch (strtolower($this->_params['group_bys_freq']['receive_date'])) {
679 case 'month':
680 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] + 1,
681 $dateEnd['d'] - 1, $dateEnd['Y']
682 ));
683 break;
684
685 case 'year':
686 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
687 $dateEnd['d'] - 1, $dateEnd['Y'] + 1
688 ));
689 break;
690
691 case 'yearweek':
692 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
693 $dateEnd['d'] + 6, $dateEnd['Y']
694 ));
695 break;
696
697 case 'quarter':
698 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] + 3,
699 $dateEnd['d'] - 1, $dateEnd['Y']
700 ));
701 break;
702 }
703 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
704 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
705 $this->_absoluteUrl,
706 $this->_id,
707 $this->_drilldownReport
708 );
709 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
710 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
711 $entryFound = TRUE;
712 }
713
714 // make subtotals look nicer
715 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
716 !$row['civicrm_contribution_receive_date_subtotal']
717 ) {
718 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields);
719 $entryFound = TRUE;
720 }
721
722 // convert display name to links
723 if (array_key_exists('civicrm_contact_sort_name', $row) &&
724 array_key_exists('civicrm_contact_id', $row)
725 ) {
726 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
727 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
728 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
729 );
730 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
731 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
732 $entryFound = TRUE;
733 }
734
735 // If using campaigns, convert campaign_id to campaign title
736 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
737 if ($value = $row['civicrm_contribution_campaign_id']) {
738 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
739 }
740 $entryFound = TRUE;
741 }
742
743 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ? TRUE : $entryFound;
744
745 // skip looking further in rows, if first row itself doesn't
746 // have the column we need
747 if (!$entryFound) {
748 break;
749 }
750 }
751 }
752
753 }