INFRA-132 - Misc
[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'] =
318 $field['title'] . ' Beginning';
319 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
320 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName];
321
322 // just to make sure these values are transfered to rows.
323 // since we need that for calculation purpose,
324 // e.g making subtotals look nicer or graphs
325 $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
326 $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
327 }
328 }
329 }
330 }
331
332 if (array_key_exists('fields', $table)) {
333 foreach ($table['fields'] as $fieldName => $field) {
334 if ($tableName == 'civicrm_address') {
335 $this->_addressField = TRUE;
336 }
337 if (!empty($field['required']) ||
338 !empty($this->_params['fields'][$fieldName])
339 ) {
340
341 // only include statistics columns if set
342 if (!empty($field['statistics'])) {
343 foreach ($field['statistics'] as $stat => $label) {
344 switch (strtolower($stat)) {
345 case 'sum':
346 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
347 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
348 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
349 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
350 break;
351
352 case 'count':
353 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
354 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
355 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
356 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
357 break;
358
359 case 'avg':
360 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
361 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
362 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
363 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
364 break;
365 }
366 }
367 }
368 else {
369 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
370 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
371 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
372 }
373 }
374 }
375 }
376 }
377
378 $this->_select = "SELECT " . implode(', ', $select) . " ";
379 }
380
381 /**
382 * @param $fields
383 * @param $files
384 * @param $self
385 *
386 * @return array
387 */
388 public static function formRule($fields, $files, $self) {
389 $errors = $grouping = array();
390 //check for searching combination of dispaly columns and
391 //grouping criteria
392 $ignoreFields = array('total_amount', 'sort_name');
393 $errors = $self->customDataFormRule($fields, $ignoreFields);
394
395 if (empty($fields['group_bys']['receive_date'])) {
396 if (!empty($fields['receive_date_relative']) ||
397 CRM_Utils_Date::isDate($fields['receive_date_from']) ||
398 CRM_Utils_Date::isDate($fields['receive_date_to'])
399 ) {
400 $errors['receive_date_relative'] = ts("Do not use filter on Date if group by Receive Date is not used ");
401 }
402 }
403 if (empty($fields['fields']['total_amount'])) {
404 foreach (array(
405 'total_count_value',
406 'total_sum_value',
407 'total_avg_value',
408 ) as $val) {
409 if (!empty($fields[$val])) {
410 $errors[$val] = ts("Please select the Amount Statistics");
411 }
412 }
413 }
414
415 return $errors;
416 }
417
418 public function from() {
419 $softCreditJoin = "LEFT";
420 if (!empty($this->_params['fields']['soft_amount']) &&
421 empty($this->_params['fields']['total_amount'])
422 ) {
423 // if its only soft credit stats, use inner join
424 $softCreditJoin = "INNER";
425 }
426
427 $this->_from = "
428 FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
429 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
430 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
431 {$this->_aliases['civicrm_contribution']}.is_test = 0
432 {$softCreditJoin} JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
433 ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id = {$this->_aliases['civicrm_contribution']}.id
434 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
435 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
436 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
437 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
438 {$this->_aliases['civicrm_email']}.is_primary = 1)
439
440 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
441 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
442 {$this->_aliases['civicrm_phone']}.is_primary = 1)";
443
444 if ($this->_addressField) {
445 $this->_from .= "
446 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
447 ON {$this->_aliases['civicrm_contact']}.id =
448 {$this->_aliases['civicrm_address']}.contact_id AND
449 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
450 }
451 }
452
453 public function groupBy() {
454 $this->_groupBy = "";
455 $append = FALSE;
456 if (is_array($this->_params['group_bys']) &&
457 !empty($this->_params['group_bys'])
458 ) {
459 foreach ($this->_columns as $tableName => $table) {
460 if (array_key_exists('group_bys', $table)) {
461 foreach ($table['group_bys'] as $fieldName => $field) {
462 if (!empty($this->_params['group_bys'][$fieldName])) {
463 if (!empty($field['chart'])) {
464 $this->assign('chartSupported', TRUE);
465 }
466
467 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
468 !empty($this->_params['group_bys_freq'][$fieldName])
469 ) {
470
471 $append = "YEAR({$field['dbAlias']}),";
472 if (in_array(strtolower($this->_params['group_bys_freq'][$fieldName]),
473 array('year')
474 )) {
475 $append = '';
476 }
477 $this->_groupBy[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
478 $append = TRUE;
479 }
480 else {
481 $this->_groupBy[] = $field['dbAlias'];
482 }
483 }
484 }
485 }
486 }
487
488 if (!empty($this->_statFields) &&
489 (($append && count($this->_groupBy) <= 1) || (!$append)) &&
490 !$this->_having
491 ) {
492 $this->_rollup = " WITH ROLLUP";
493 }
494 $this->_groupBy = "GROUP BY " . implode(', ', $this->_groupBy) .
495 " {$this->_rollup} ";
496 }
497 else {
498 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_contact']}.id";
499 }
500 }
501
502 public function storeWhereHavingClauseArray() {
503 parent::storeWhereHavingClauseArray();
504 if (empty($this->_params['fields']['soft_amount']) &&
505 !empty($this->_havingClauses)
506 ) {
507 foreach ($this->_havingClauses as $key => $havingClause) {
508 if (stristr($havingClause, 'soft_soft')) {
509 unset($this->_havingClauses[$key]);
510 }
511 }
512 }
513 }
514
515 /**
516 * @param $rows
517 *
518 * @return array
519 */
520 public function statistics(&$rows) {
521 $statistics = parent::statistics($rows);
522
523 $softCredit = CRM_Utils_Array::value('soft_amount', $this->_params['fields']);
524 $onlySoftCredit = $softCredit &&
525 !CRM_Utils_Array::value('total_amount', $this->_params['fields']);
526 $totalAmount = $average = $softTotalAmount = $softAverage = array();
527
528 $select = "SELECT
529 COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_count,
530 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_sum,
531 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as civicrm_contribution_total_amount_avg,
532 {$this->_aliases['civicrm_contribution']}.currency as currency";
533
534 if ($softCredit) {
535 $select .= ",
536 COUNT({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_count,
537 SUM({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_sum,
538 ROUND(AVG({$this->_aliases['civicrm_contribution_soft']}.amount), 2) as civicrm_contribution_soft_soft_amount_avg";
539 }
540 $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
541 $sql = "{$select} {$this->_from} {$this->_where} {$group} {$this->_having}";
542
543 $dao = CRM_Core_DAO::executeQuery($sql);
544 $totalAmount = $average = $softTotalAmount = $softAverage = array();
545 $count = $softCount = 0;
546 while ($dao->fetch()) {
547 $totalAmount[] =
548 CRM_Utils_Money::format($dao->civicrm_contribution_total_amount_sum, $dao->currency) .
549 " (" . $dao->civicrm_contribution_total_amount_count . ")";
550 $average[] = CRM_Utils_Money::format($dao->civicrm_contribution_total_amount_avg, $dao->currency);
551 $count += $dao->civicrm_contribution_total_amount_count;
552
553 if ($softCredit) {
554 $softTotalAmount[] =
555 CRM_Utils_Money::format($dao->civicrm_contribution_soft_soft_amount_sum, $dao->currency) .
556 " (" . $dao->civicrm_contribution_soft_soft_amount_count . ")";
557 $softAverage[] = CRM_Utils_Money::format($dao->civicrm_contribution_soft_soft_amount_avg, $dao->currency);
558 $softCount += $dao->civicrm_contribution_soft_soft_amount_count;
559 }
560 }
561
562 if (!$onlySoftCredit) {
563 $statistics['counts']['amount'] = array(
564 'title' => ts('Total Amount'),
565 'value' => implode(', ', $totalAmount),
566 'type' => CRM_Utils_Type::T_STRING,
567 );
568 $statistics['counts']['count'] = array(
569 'title' => ts('Total Contributions'),
570 'value' => $count,
571 );
572 $statistics['counts']['avg'] = array(
573 'title' => ts('Average'),
574 'value' => implode(', ', $average),
575 'type' => CRM_Utils_Type::T_STRING,
576 );
577 }
578 if ($softCredit) {
579 $statistics['counts']['soft_amount'] = array(
580 'title' => ts('Total Soft Credit Amount'),
581 'value' => implode(', ', $softTotalAmount),
582 'type' => CRM_Utils_Type::T_STRING,
583 );
584 $statistics['counts']['soft_count'] = array(
585 'title' => ts('Total Soft Credits'),
586 'value' => $softCount,
587 );
588 $statistics['counts']['soft_avg'] = array(
589 'title' => ts('Average Soft Credit'),
590 'value' => implode(', ', $softAverage),
591 'type' => CRM_Utils_Type::T_STRING,
592 );
593 }
594 return $statistics;
595 }
596
597 public function postProcess() {
598 $this->buildACLClause($this->_aliases['civicrm_contact']);
599 parent::postProcess();
600 }
601
602 /**
603 * @param $rows
604 */
605 public function buildChart(&$rows) {
606 $graphRows = array();
607
608 if (!empty($this->_params['charts'])) {
609 if (!empty($this->_params['group_bys']['receive_date'])) {
610
611 $contrib = !empty($this->_params['fields']['total_amount']) ? TRUE : FALSE;
612 $softContrib = !empty($this->_params['fields']['soft_amount']) ? TRUE : FALSE;
613
614 foreach ($rows as $key => $row) {
615 if ($row['civicrm_contribution_receive_date_subtotal']) {
616 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
617 $graphRows[$this->_interval][] = $row['civicrm_contribution_receive_date_interval'];
618 if ($softContrib && $contrib) {
619 // both contri & soft contri stats are present
620 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
621 $graphRows['multiValue'][1][] = $row['civicrm_contribution_soft_soft_amount_sum'];
622 }
623 elseif ($softContrib) {
624 // only soft contributions
625 $graphRows['multiValue'][0][] = $row['civicrm_contribution_soft_soft_amount_sum'];
626 }
627 else {
628 // only contributions
629 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
630 }
631 }
632 }
633
634 if ($softContrib && $contrib) {
635 $graphRows['barKeys'][0] = ts('Contributions');
636 $graphRows['barKeys'][1] = ts('Soft Credits');
637 $graphRows['legend'] = ts('Contributions and Soft Credits');
638 }
639 elseif ($softContrib) {
640 $graphRows['legend'] = ts('Soft Credits');
641 }
642
643 // build the chart.
644 $config = CRM_Core_Config::Singleton();
645 $graphRows['xname'] = $this->_interval;
646 $graphRows['yname'] = "Amount ({$config->defaultCurrency})";
647 CRM_Utils_OpenFlashChart::chart($graphRows, $this->_params['charts'], $this->_interval);
648 $this->assign('chartType', $this->_params['charts']);
649 }
650 }
651 }
652
653 /**
654 * @param $rows
655 */
656 public function alterDisplay(&$rows) {
657 // custom code to alter rows
658 $entryFound = FALSE;
659
660 foreach ($rows as $rowNum => $row) {
661 // make count columns point to detail report
662 if (!empty($this->_params['group_bys']['receive_date']) &&
663 !empty($row['civicrm_contribution_receive_date_start']) &&
664 CRM_Utils_Array::value('civicrm_contribution_receive_date_start', $row) &&
665 !empty($row['civicrm_contribution_receive_date_subtotal'])
666 ) {
667
668 $dateStart = CRM_Utils_Date::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
669 $endDate = new DateTime($dateStart);
670 $dateEnd = array();
671
672 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
673
674 switch (strtolower($this->_params['group_bys_freq']['receive_date'])) {
675 case 'month':
676 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] + 1,
677 $dateEnd['d'] - 1, $dateEnd['Y']
678 ));
679 break;
680
681 case 'year':
682 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
683 $dateEnd['d'] - 1, $dateEnd['Y'] + 1
684 ));
685 break;
686
687 case 'yearweek':
688 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
689 $dateEnd['d'] + 6, $dateEnd['Y']
690 ));
691 break;
692
693 case 'quarter':
694 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] + 3,
695 $dateEnd['d'] - 1, $dateEnd['Y']
696 ));
697 break;
698 }
699 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
700 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
701 $this->_absoluteUrl,
702 $this->_id,
703 $this->_drilldownReport
704 );
705 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
706 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
707 $entryFound = TRUE;
708 }
709
710 // make subtotals look nicer
711 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
712 !$row['civicrm_contribution_receive_date_subtotal']
713 ) {
714 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields);
715 $entryFound = TRUE;
716 }
717
718 // convert display name to links
719 if (array_key_exists('civicrm_contact_sort_name', $row) &&
720 array_key_exists('civicrm_contact_id', $row)
721 ) {
722 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
723 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
724 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
725 );
726 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
727 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
728 $entryFound = TRUE;
729 }
730
731 // If using campaigns, convert campaign_id to campaign title
732 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
733 if ($value = $row['civicrm_contribution_campaign_id']) {
734 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
735 }
736 $entryFound = TRUE;
737 }
738
739 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ? TRUE : $entryFound;
740
741 // skip looking further in rows, if first row itself doesn't
742 // have the column we need
743 if (!$entryFound) {
744 break;
745 }
746 }
747 }
748
749 }