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