3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2016
33 class CRM_Report_Form_Contribute_Summary
extends CRM_Report_Form
{
34 protected $_addressField = FALSE;
36 protected $_charts = array(
38 'barChart' => 'Bar Chart',
39 'pieChart' => 'Pie Chart',
41 protected $_customGroupExtends = array('Contribution');
42 protected $_customGroupGroupBy = TRUE;
44 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
47 * To what frequency group-by a date column
51 protected $_groupByDateFreq = array(
55 'QUARTER' => 'Quarter',
57 'FISCALYEAR' => 'Fiscal Year',
61 * This report has been optimised for group filtering.
67 protected $groupFilterNotOptimised = FALSE;
72 public function __construct() {
74 // Check if CiviCampaign is a) enabled and b) has active campaigns
75 $config = CRM_Core_Config
::singleton();
76 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents
);
77 if ($campaignEnabled) {
78 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
79 $this->activeCampaigns
= $getCampaigns['campaigns'];
80 asort($this->activeCampaigns
);
83 $this->_columns
= array(
84 'civicrm_contact' => array(
85 'dao' => 'CRM_Contact_DAO_Contact',
86 'fields' => array_merge(
87 $this->getBasicContactFields(),
90 'title' => ts('Contact Name'),
95 'grouping' => 'contact-fields',
97 'id' => array('title' => ts('Contact ID')),
99 'title' => ts('Contact Name'),
103 'civicrm_email' => array(
104 'dao' => 'CRM_Core_DAO_Email',
107 'title' => ts('Email'),
111 'grouping' => 'contact-fields',
113 'civicrm_line_item' => array(
114 'dao' => 'CRM_Price_DAO_LineItem',
116 'civicrm_phone' => array(
117 'dao' => 'CRM_Core_DAO_Phone',
120 'title' => ts('Phone'),
124 'grouping' => 'contact-fields',
126 'civicrm_financial_type' => array(
127 'dao' => 'CRM_Financial_DAO_FinancialType',
128 'fields' => array('financial_type' => NULL),
129 'grouping' => 'contri-fields',
130 'group_bys' => array(
131 'financial_type' => array('title' => ts('Financial Type')),
134 'civicrm_contribution' => array(
135 'dao' => 'CRM_Contribute_DAO_Contribution',
136 //'bao' => 'CRM_Contribute_BAO_Contribution',
138 'contribution_status_id' => array(
139 'title' => ts('Contribution Status'),
141 'contribution_source' => array('title' => ts('Source')),
144 'no_display' => TRUE,
146 'total_amount' => array(
147 'title' => ts('Contribution Amount Stats'),
149 'statistics' => array(
150 'count' => ts('Contributions'),
151 'sum' => ts('Contribution Aggregate'),
152 'avg' => ts('Contribution Avg'),
155 'non_deductible_amount' => array(
156 'title' => ts('Non-deductible Amount'),
159 'grouping' => 'contri-fields',
161 'receive_date' => array('operatorType' => CRM_Report_Form
::OP_DATE
),
162 'contribution_status_id' => array(
163 'title' => ts('Contribution Status'),
164 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
165 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
166 'default' => array(1),
167 'type' => CRM_Utils_Type
::T_INT
,
170 'title' => ts('Currency'),
171 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
172 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
174 'type' => CRM_Utils_Type
::T_STRING
,
176 'financial_type_id' => array(
177 'title' => ts('Financial Type'),
178 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
179 'options' => CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes(),
180 'type' => CRM_Utils_Type
::T_INT
,
182 'contribution_page_id' => array(
183 'title' => ts('Contribution Page'),
184 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
185 'options' => CRM_Contribute_PseudoConstant
::contributionPage(),
186 'type' => CRM_Utils_Type
::T_INT
,
188 'total_amount' => array(
189 'title' => ts('Contribution Amount'),
191 'non_deductible_amount' => array(
192 'title' => ts('Non-deductible Amount'),
194 'total_sum' => array(
195 'title' => ts('Contribution Aggregate'),
196 'type' => CRM_Report_Form
::OP_INT
,
197 'dbAlias' => 'civicrm_contribution_total_amount_sum',
200 'total_count' => array(
201 'title' => ts('Contribution Count'),
202 'type' => CRM_Report_Form
::OP_INT
,
203 'dbAlias' => 'civicrm_contribution_total_amount_count',
206 'total_avg' => array(
207 'title' => ts('Contribution Avg'),
208 'type' => CRM_Report_Form
::OP_INT
,
209 'dbAlias' => 'civicrm_contribution_total_amount_avg',
213 'group_bys' => array(
214 'receive_date' => array(
219 'contribution_source' => NULL,
220 'contribution_status_id' => array(
221 'title' => ts('Contribution Status'),
222 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
223 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
224 'default' => array(1),
225 'type' => CRM_Utils_Type
::T_INT
,
229 'civicrm_batch' => array(
230 'dao' => 'CRM_Batch_DAO_EntityBatch',
231 'grouping' => 'contri-fields',
234 'title' => ts('Batch Title'),
235 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
236 'options' => CRM_Batch_BAO_Batch
::getBatches(),
237 'type' => CRM_Utils_Type
::T_INT
,
241 'civicrm_contribution_soft' => array(
242 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
244 'soft_amount' => array(
245 'title' => ts('Soft Credit Amount Stats'),
247 'statistics' => array(
248 'count' => ts('Soft Credits'),
249 'sum' => ts('Soft Credit Aggregate'),
250 'avg' => ts('Soft Credit Avg'),
254 'grouping' => 'contri-fields',
257 'title' => ts('Soft Credit Amount'),
259 'soft_credit_type_id' => array(
260 'title' => ts('Soft Credit Type'),
261 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
262 'options' => CRM_Core_OptionGroup
::values('soft_credit_type'),
264 'type' => CRM_Utils_Type
::T_STRING
,
267 'title' => ts('Soft Credit Aggregate'),
268 'type' => CRM_Report_Form
::OP_INT
,
269 'dbAlias' => 'civicrm_contribution_soft_soft_amount_sum',
272 'soft_count' => array(
273 'title' => ts('Soft Credits Count'),
274 'type' => CRM_Report_Form
::OP_INT
,
275 'dbAlias' => 'civicrm_contribution_soft_soft_amount_count',
279 'title' => ts('Soft Credit Avg'),
280 'type' => CRM_Report_Form
::OP_INT
,
281 'dbAlias' => 'civicrm_contribution_soft_soft_amount_avg',
286 ) +
$this->addAddressFields();
288 // If we have a campaign, build out the relevant elements
289 if ($campaignEnabled && !empty($this->activeCampaigns
)) {
290 $this->_columns
['civicrm_contribution']['fields']['campaign_id'] = array(
291 'title' => ts('Campaign'),
292 'default' => 'false',
294 $this->_columns
['civicrm_contribution']['filters']['campaign_id'] = array(
295 'title' => ts('Campaign'),
296 'type' => CRM_Utils_Type
::T_INT
,
297 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
298 'options' => $this->activeCampaigns
,
300 $this->_columns
['civicrm_contribution']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
303 $this->_tagFilter
= TRUE;
304 $this->_groupFilter
= TRUE;
305 $this->_currencyColumn
= 'civicrm_contribution_currency';
306 parent
::__construct();
312 public function select() {
314 $this->_columnHeaders
= array();
315 foreach ($this->_columns
as $tableName => $table) {
316 if (array_key_exists('group_bys', $table)) {
317 foreach ($table['group_bys'] as $fieldName => $field) {
318 if ($tableName == 'civicrm_address') {
319 $this->_addressField
= TRUE;
321 if (!empty($this->_params
['group_bys'][$fieldName])) {
322 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
324 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
325 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
326 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
327 $field['title'] = ts('Week Beginning');
331 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
332 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
333 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
334 $field['title'] = ts('Year Beginning');
338 $config = CRM_Core_Config
::singleton();
339 $fy = $config->fiscalYearStart
;
340 $fiscal = self
::fiscalYearOffset($field['dbAlias']);
342 $select[] = "DATE_ADD(MAKEDATE({$fiscal}, 1), INTERVAL ({$fy{'M'}})-1 MONTH) AS {$tableName}_{$fieldName}_start";
343 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_subtotal";
344 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_interval";
345 $field['title'] = ts('Fiscal Year Beginning');
349 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
350 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
351 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
352 $field['title'] = ts('Month Beginning');
356 $select[] = "DATE({$field['dbAlias']}) as {$tableName}_{$fieldName}_start";
357 $field['title'] = ts('Date');
361 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
362 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
363 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
364 $field['title'] = 'Quarter';
367 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
368 $this->_interval
= $this->_params
['group_bys_freq'][$fieldName];
369 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'];
370 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
371 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
373 // just to make sure these values are transferred to rows.
374 // since we need that for calculation purpose,
375 // e.g making subtotals look nicer or graphs
376 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
377 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
383 if (array_key_exists('fields', $table)) {
384 foreach ($table['fields'] as $fieldName => $field) {
385 if ($tableName == 'civicrm_address') {
386 $this->_addressField
= TRUE;
388 if (!empty($field['required']) ||
389 !empty($this->_params
['fields'][$fieldName])
391 // only include statistics columns if set
392 if (!empty($field['statistics'])) {
393 foreach ($field['statistics'] as $stat => $label) {
394 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
395 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
396 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
397 switch (strtolower($stat)) {
399 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
403 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
404 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
408 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
414 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
415 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
416 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
423 $this->_selectClauses
= $select;
424 $this->_select
= "SELECT " . implode(', ', $select) . " ";
430 * @param array $fields
431 * @param array $files
432 * @param CRM_Report_Form_Contribute_Summary $self
436 public static function formRule($fields, $files, $self) {
437 // Check for searching combination of display columns and
439 $ignoreFields = array('total_amount', 'sort_name');
440 $errors = $self->customDataFormRule($fields, $ignoreFields);
442 if (empty($fields['fields']['total_amount'])) {
448 if (!empty($fields[$val])) {
449 $errors[$val] = ts("Please select the Amount Statistics");
460 * @param string $entity
462 * @todo fix function signature to match parent. Remove hacky passing of $entity
463 * to acheive unclear results.
465 public function from($entity = NULL) {
466 $softCreditJoinType = "LEFT";
467 if (!empty($this->_params
['fields']['soft_amount']) &&
468 empty($this->_params
['fields']['total_amount'])
470 // if its only soft credit stats, use inner join
471 $softCreditJoinType = "INNER";
474 $softCreditJoin = "{$softCreditJoinType} JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
475 ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
476 if ($entity == 'contribution' ||
empty($this->_params
['fields']['soft_amount'])) {
477 $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) ";
480 $this->setFromBase('civicrm_contact');
483 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
484 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
485 {$this->_aliases['civicrm_contribution']}.is_test = 0
487 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
488 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
489 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
490 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
491 {$this->_aliases['civicrm_email']}.is_primary = 1)
493 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
494 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
495 {$this->_aliases['civicrm_phone']}.is_primary = 1)";
497 $this->addAddressFromClause();
498 if (!empty($this->_params
['batch_id_value'])) {
500 LEFT JOIN civicrm_entity_financial_trxn eft
501 ON eft.entity_id = {$this->_aliases['civicrm_contribution']}.id AND
502 eft.entity_table = 'civicrm_contribution'
503 LEFT JOIN civicrm_entity_batch {$this->_aliases['civicrm_batch']}
504 ON {$this->_aliases['civicrm_batch']}.entity_id = eft.financial_trxn_id AND
505 {$this->_aliases['civicrm_batch']}.entity_table = 'civicrm_financial_trxn'\n";
510 * Set group by clause.
512 public function groupBy() {
513 $this->_groupBy
= "";
515 if (!empty($this->_params
['group_bys']) &&
516 is_array($this->_params
['group_bys'])
518 foreach ($this->_columns
as $tableName => $table) {
519 if (array_key_exists('group_bys', $table)) {
520 foreach ($table['group_bys'] as $fieldName => $field) {
521 if (!empty($this->_params
['group_bys'][$fieldName])) {
522 if (!empty($field['chart'])) {
523 $this->assign('chartSupported', TRUE);
526 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
527 !empty($this->_params
['group_bys_freq'][$fieldName])
530 $append = "YEAR({$field['dbAlias']});;";
531 if (in_array(strtolower($this->_params
['group_bys_freq'][$fieldName]),
536 if ($this->_params
['group_bys_freq'][$fieldName] == 'FISCALYEAR') {
537 $this->_groupBy
[] = self
::fiscalYearOffset($field['dbAlias']);
540 $this->_groupBy
[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
545 $this->_groupBy
[] = $field['dbAlias'];
552 if (!empty($this->_statFields
) &&
553 (($append && count($this->_groupBy
) <= 1) ||
(!$append)) &&
556 $this->_rollup
= " WITH ROLLUP";
559 foreach ($this->_groupBy
as $key => $val) {
560 if (strpos($val, ';;') !== FALSE) {
561 $groupBy = array_merge($groupBy, explode(';;', $val));
564 $groupBy[] = $this->_groupBy
[$key];
567 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBy);
570 $groupBy = "{$this->_aliases['civicrm_contact']}.id";
571 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contact']}.id";
573 $this->_groupBy
.= $this->_rollup
;
574 // append select with ANY_VALUE() keyword
575 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($this->_selectClauses
, $groupBy);
579 * Store having clauses as an array.
581 public function storeWhereHavingClauseArray() {
582 parent
::storeWhereHavingClauseArray();
583 if (empty($this->_params
['fields']['soft_amount']) &&
584 !empty($this->_havingClauses
)
586 foreach ($this->_havingClauses
as $key => $havingClause) {
587 if (stristr($havingClause, 'soft_soft')) {
588 unset($this->_havingClauses
[$key]);
601 public function statistics(&$rows) {
602 $statistics = parent
::statistics($rows);
604 $softCredit = CRM_Utils_Array
::value('soft_amount', $this->_params
['fields']);
605 $onlySoftCredit = $softCredit && !CRM_Utils_Array
::value('total_amount', $this->_params
['fields']);
606 $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
608 $this->from('contribution');
609 $this->customDataFrom();
612 COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_count,
613 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_sum,
614 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as civicrm_contribution_total_amount_avg,
615 {$this->_aliases['civicrm_contribution']}.currency as currency
616 {$this->_from} {$this->_where}";
621 COUNT({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_count,
622 SUM({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_sum,
623 ROUND(AVG({$this->_aliases['civicrm_contribution_soft']}.amount), 2) as civicrm_contribution_soft_soft_amount_avg";
624 $contriQuery = "{$select}, {$contriQuery}";
625 $softSQL = "SELECT {$select}, {$this->_aliases['civicrm_contribution']}.currency as currency
626 {$this->_from} {$this->_where} {$group} {$this->_having}";
629 $contriSQL = "SELECT {$contriQuery} {$group} {$this->_having}";
630 $contriDAO = CRM_Core_DAO
::executeQuery($contriSQL);
632 $totalAmount = $average = $mode = $median = $softTotalAmount = $softAverage = array();
633 $count = $softCount = 0;
634 while ($contriDAO->fetch()) {
636 = CRM_Utils_Money
::format($contriDAO->civicrm_contribution_total_amount_sum
, $contriDAO->currency
) .
637 " (" . $contriDAO->civicrm_contribution_total_amount_count
. ")";
638 $average[] = CRM_Utils_Money
::format($contriDAO->civicrm_contribution_total_amount_avg
, $contriDAO->currency
);
639 $count +
= $contriDAO->civicrm_contribution_total_amount_count
;
642 $groupBy = "\n{$group}, {$this->_aliases['civicrm_contribution']}.total_amount";
643 $orderBy = "\nORDER BY civicrm_contribution_total_amount_count DESC";
644 $modeSQL = "SELECT MAX(civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count,
645 SUBSTRING_INDEX(GROUP_CONCAT(amount ORDER BY mode.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
647 FROM (SELECT {$this->_aliases['civicrm_contribution']}.total_amount as amount,
648 {$contriQuery} {$groupBy} {$orderBy}) as mode GROUP BY currency";
650 $mode = CRM_Contribute_BAO_Contribution
::computeStats('mode', $modeSQL);
652 $medianSQL = "{$this->_from} {$this->_where}";
653 $median = CRM_Contribute_BAO_Contribution
::computeStats('median', $medianSQL, $this->_aliases
['civicrm_contribution']);
656 $softDAO = CRM_Core_DAO
::executeQuery($softSQL);
657 while ($softDAO->fetch()) {
659 = CRM_Utils_Money
::format($softDAO->civicrm_contribution_soft_soft_amount_sum
, $softDAO->currency
) .
660 " (" . $softDAO->civicrm_contribution_soft_soft_amount_count
. ")";
661 $softAverage[] = CRM_Utils_Money
::format($softDAO->civicrm_contribution_soft_soft_amount_avg
, $softDAO->currency
);
662 $softCount +
= $softDAO->civicrm_contribution_soft_soft_amount_count
;
666 if (!$onlySoftCredit) {
667 $statistics['counts']['amount'] = array(
668 'title' => ts('Total Amount'),
669 'value' => implode(', ', $totalAmount),
670 'type' => CRM_Utils_Type
::T_STRING
,
672 $statistics['counts']['count'] = array(
673 'title' => ts('Total Contributions'),
676 $statistics['counts']['avg'] = array(
677 'title' => ts('Average'),
678 'value' => implode(', ', $average),
679 'type' => CRM_Utils_Type
::T_STRING
,
681 $statistics['counts']['mode'] = array(
682 'title' => ts('Mode'),
683 'value' => implode(', ', $mode),
684 'type' => CRM_Utils_Type
::T_STRING
,
686 $statistics['counts']['median'] = array(
687 'title' => ts('Median'),
688 'value' => implode(', ', $median),
689 'type' => CRM_Utils_Type
::T_STRING
,
693 $statistics['counts']['soft_amount'] = array(
694 'title' => ts('Total Soft Credit Amount'),
695 'value' => implode(', ', $softTotalAmount),
696 'type' => CRM_Utils_Type
::T_STRING
,
698 $statistics['counts']['soft_count'] = array(
699 'title' => ts('Total Soft Credits'),
700 'value' => $softCount,
702 $statistics['counts']['soft_avg'] = array(
703 'title' => ts('Average Soft Credit'),
704 'value' => implode(', ', $softAverage),
705 'type' => CRM_Utils_Type
::T_STRING
,
712 * Post process function.
714 public function postProcess() {
715 $this->buildACLClause($this->_aliases
['civicrm_contact']);
716 parent
::postProcess();
720 * Build table rows for output.
725 public function buildRows($sql, &$rows) {
726 $dao = CRM_Core_DAO
::executeQuery($sql);
727 if (!is_array($rows)) {
731 // use this method to modify $this->_columnHeaders
732 $this->modifyColumnHeaders();
733 $contriRows = array();
734 $unselectedSectionColumns = $this->unselectedSectionColumns();
736 //CRM-16338 if both soft-credit and contribution are enabled then process the contribution's
737 //total amount's average, count and sum separately and add it to the respective result list
738 $softCredit = (!empty($this->_params
['fields']['soft_amount']) && !empty($this->_params
['fields']['total_amount'])) ?
TRUE : FALSE;
740 $this->from('contribution');
741 $contriSQL = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
742 $contriDAO = CRM_Core_DAO
::executeQuery($contriSQL);
743 $contriFields = array(
744 'civicrm_contribution_total_amount_sum',
745 'civicrm_contribution_total_amount_avg',
746 'civicrm_contribution_total_amount_count');
747 $contriRows = array();
748 while ($contriDAO->fetch()) {
749 $contriRow = array();
750 foreach ($contriFields as $column) {
751 $contriRow[$column] = $contriDAO->$column;
753 $contriRows[] = $contriRow;
758 while ($dao->fetch()) {
760 foreach ($this->_columnHeaders
as $key => $value) {
761 if ($softCredit && array_key_exists($key, $contriRows[$count])) {
762 $row[$key] = $contriRows[$count][$key];
764 elseif (property_exists($dao, $key)) {
765 $row[$key] = $dao->$key;
769 // section headers not selected for display need to be added to row
770 foreach ($unselectedSectionColumns as $key => $values) {
771 if (property_exists($dao, $key)) {
772 $row[$key] = $dao->$key;
787 public function buildChart(&$rows) {
788 $graphRows = array();
790 if (!empty($this->_params
['charts'])) {
791 if (!empty($this->_params
['group_bys']['receive_date'])) {
793 $contrib = !empty($this->_params
['fields']['total_amount']) ?
TRUE : FALSE;
794 $softContrib = !empty($this->_params
['fields']['soft_amount']) ?
TRUE : FALSE;
796 foreach ($rows as $key => $row) {
797 if ($row['civicrm_contribution_receive_date_subtotal']) {
798 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
799 $graphRows[$this->_interval
][] = $row['civicrm_contribution_receive_date_interval'];
800 if ($softContrib && $contrib) {
801 // both contri & soft contri stats are present
802 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
803 $graphRows['multiValue'][1][] = $row['civicrm_contribution_soft_soft_amount_sum'];
805 elseif ($softContrib) {
806 // only soft contributions
807 $graphRows['multiValue'][0][] = $row['civicrm_contribution_soft_soft_amount_sum'];
810 // only contributions
811 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
816 if ($softContrib && $contrib) {
817 $graphRows['barKeys'][0] = ts('Contributions');
818 $graphRows['barKeys'][1] = ts('Soft Credits');
819 $graphRows['legend'] = ts('Contributions and Soft Credits');
821 elseif ($softContrib) {
822 $graphRows['legend'] = ts('Soft Credits');
826 $config = CRM_Core_Config
::Singleton();
827 $graphRows['xname'] = $this->_interval
;
828 $graphRows['yname'] = "Amount ({$config->defaultCurrency})";
829 CRM_Utils_OpenFlashChart
::chart($graphRows, $this->_params
['charts'], $this->_interval
);
830 $this->assign('chartType', $this->_params
['charts']);
836 * Alter display of rows.
838 * Iterate through the rows retrieved via SQL and make changes for display purposes,
839 * such as rendering contacts as links.
842 * Rows generated by SQL, with an array for each row.
844 public function alterDisplay(&$rows) {
846 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus();
848 foreach ($rows as $rowNum => $row) {
849 // make count columns point to detail report
850 if (!empty($this->_params
['group_bys']['receive_date']) &&
851 !empty($row['civicrm_contribution_receive_date_start']) &&
852 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
853 !empty($row['civicrm_contribution_receive_date_subtotal'])
856 $dateStart = CRM_Utils_Date
::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
857 $endDate = new DateTime($dateStart);
860 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
862 switch (strtolower($this->_params
['group_bys_freq']['receive_date'])) {
864 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
1,
865 $dateEnd['d'] - 1, $dateEnd['Y']
870 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
871 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
876 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
877 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
882 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
883 $dateEnd['d'] +
6, $dateEnd['Y']
888 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
3,
889 $dateEnd['d'] - 1, $dateEnd['Y']
893 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
894 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
897 $this->_drilldownReport
899 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
900 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
904 // make subtotals look nicer
905 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
906 !$row['civicrm_contribution_receive_date_subtotal']
908 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields
);
912 // convert display name to links
913 if (array_key_exists('civicrm_contact_sort_name', $row) &&
914 array_key_exists('civicrm_contact_id', $row)
916 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
917 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
918 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
920 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
921 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
925 // convert contribution status id to status name
926 if ($value = CRM_Utils_Array
::value('civicrm_contribution_contribution_status_id', $row)) {
927 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value];
931 // If using campaigns, convert campaign_id to campaign title
932 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
933 if ($value = $row['civicrm_contribution_campaign_id']) {
934 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns
[$value];
939 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
940 $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
942 // skip looking further in rows, if first row itself doesn't
943 // have the column we need