3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
33 class CRM_Report_Form_Contribute_Summary
extends CRM_Report_Form
{
35 protected $_charts = array(
37 'barChart' => 'Bar Chart',
38 'pieChart' => 'Pie Chart',
40 protected $_customGroupExtends = array('Contribution', 'Contact', 'Individual');
41 protected $_customGroupGroupBy = TRUE;
43 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
46 * To what frequency group-by a date column
50 protected $_groupByDateFreq = array(
54 'QUARTER' => 'Quarter',
56 'FISCALYEAR' => 'Fiscal Year',
60 * This report has been optimised for group filtering.
66 protected $groupFilterNotOptimised = FALSE;
71 public function __construct() {
72 $this->_columns
= array(
73 'civicrm_contact' => array(
74 'dao' => 'CRM_Contact_DAO_Contact',
75 'fields' => array_merge(
76 $this->getBasicContactFields(),
79 'title' => ts('Contact Name'),
84 'filters' => $this->getBasicContactFilters(array('deceased' => NULL)),
85 'grouping' => 'contact-fields',
87 'id' => array('title' => ts('Contact ID')),
89 'title' => ts('Contact Name'),
93 'civicrm_email' => array(
94 'dao' => 'CRM_Core_DAO_Email',
97 'title' => ts('Email'),
101 'grouping' => 'contact-fields',
103 'civicrm_line_item' => array(
104 'dao' => 'CRM_Price_DAO_LineItem',
106 'civicrm_phone' => array(
107 'dao' => 'CRM_Core_DAO_Phone',
110 'title' => ts('Phone'),
114 'grouping' => 'contact-fields',
116 'civicrm_financial_type' => array(
117 'dao' => 'CRM_Financial_DAO_FinancialType',
118 'fields' => array('financial_type' => NULL),
119 'grouping' => 'contri-fields',
120 'group_bys' => array(
121 'financial_type' => array('title' => ts('Financial Type')),
124 'civicrm_contribution' => array(
125 'dao' => 'CRM_Contribute_DAO_Contribution',
126 //'bao' => 'CRM_Contribute_BAO_Contribution',
128 'contribution_status_id' => array(
129 'title' => ts('Contribution Status'),
131 'contribution_source' => array('title' => ts('Source')),
134 'no_display' => TRUE,
136 'contribution_page_id' => array(
137 'title' => ts('Contribution Page'),
139 'total_amount' => array(
140 'title' => ts('Contribution Amount Stats'),
142 'statistics' => array(
143 'count' => ts('Contributions'),
144 'sum' => ts('Contribution Aggregate'),
145 'avg' => ts('Contribution Avg'),
148 'non_deductible_amount' => array(
149 'title' => ts('Non-deductible Amount'),
152 'grouping' => 'contri-fields',
154 'receive_date' => array('operatorType' => CRM_Report_Form
::OP_DATE
),
155 'thankyou_date' => array('operatorType' => CRM_Report_Form
::OP_DATE
),
156 'contribution_status_id' => array(
157 'title' => ts('Contribution Status'),
158 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
159 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
160 'default' => array(1),
161 'type' => CRM_Utils_Type
::T_INT
,
163 'contribution_page_id' => array(
164 'title' => ts('Contribution Page'),
165 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
166 'options' => CRM_Contribute_PseudoConstant
::contributionPage(),
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
,
227 'contribution_page_id' => array(
228 'title' => ts('Contribution Page'),
229 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
230 'options' => CRM_Contribute_PseudoConstant
::contributionPage(),
231 'type' => CRM_Utils_Type
::T_INT
,
235 'civicrm_financial_trxn' => array(
236 'dao' => 'CRM_Financial_DAO_FinancialTrxn',
238 'card_type_id' => array(
239 'title' => ts('Credit Card Type'),
240 'dbAlias' => 'GROUP_CONCAT(financial_trxn_civireport.card_type_id SEPARATOR ",")',
244 'card_type_id' => array(
245 'title' => ts('Credit Card Type'),
246 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
247 'options' => CRM_Financial_DAO_FinancialTrxn
::buildOptions('card_type_id'),
249 'type' => CRM_Utils_Type
::T_STRING
,
253 'civicrm_batch' => array(
254 'dao' => 'CRM_Batch_DAO_EntityBatch',
255 'grouping' => 'contri-fields',
258 'name' => 'batch_id',
259 'title' => ts('Batch Title'),
260 'dbAlias' => 'GROUP_CONCAT(DISTINCT batch_civireport.batch_id
261 ORDER BY batch_civireport.batch_id SEPARATOR ",")',
266 'title' => ts('Batch Title'),
267 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
268 'options' => CRM_Batch_BAO_Batch
::getBatches(),
269 'type' => CRM_Utils_Type
::T_INT
,
272 'group_bys' => array(
273 'batch_id' => array('title' => ts('Batch Title')),
276 'civicrm_contribution_soft' => array(
277 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
279 'soft_amount' => array(
280 'title' => ts('Soft Credit Amount Stats'),
282 'statistics' => array(
283 'count' => ts('Soft Credits'),
284 'sum' => ts('Soft Credit Aggregate'),
285 'avg' => ts('Soft Credit Avg'),
289 'grouping' => 'contri-fields',
292 'title' => ts('Soft Credit Amount'),
294 'soft_credit_type_id' => array(
295 'title' => ts('Soft Credit Type'),
296 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
297 'options' => CRM_Core_OptionGroup
::values('soft_credit_type'),
299 'type' => CRM_Utils_Type
::T_STRING
,
302 'title' => ts('Soft Credit Aggregate'),
303 'type' => CRM_Report_Form
::OP_INT
,
304 'dbAlias' => 'civicrm_contribution_soft_soft_amount_sum',
307 'soft_count' => array(
308 'title' => ts('Soft Credits Count'),
309 'type' => CRM_Report_Form
::OP_INT
,
310 'dbAlias' => 'civicrm_contribution_soft_soft_amount_count',
314 'title' => ts('Soft Credit Avg'),
315 'type' => CRM_Report_Form
::OP_INT
,
316 'dbAlias' => 'civicrm_contribution_soft_soft_amount_avg',
321 ) +
$this->addAddressFields();
323 $this->addCampaignFields('civicrm_contribution', TRUE);
325 $this->_tagFilter
= TRUE;
326 $this->_groupFilter
= TRUE;
327 $this->_currencyColumn
= 'civicrm_contribution_currency';
328 parent
::__construct();
334 public function select() {
336 $this->_columnHeaders
= array();
337 foreach ($this->_columns
as $tableName => $table) {
338 if (array_key_exists('group_bys', $table)) {
339 foreach ($table['group_bys'] as $fieldName => $field) {
340 if (!empty($this->_params
['group_bys'][$fieldName])) {
341 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
343 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
344 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
345 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
346 $field['title'] = ts('Week Beginning');
350 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
351 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
352 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
353 $field['title'] = ts('Year Beginning');
357 $config = CRM_Core_Config
::singleton();
358 $fy = $config->fiscalYearStart
;
359 $fiscal = self
::fiscalYearOffset($field['dbAlias']);
361 $select[] = "DATE_ADD(MAKEDATE({$fiscal}, 1), INTERVAL ({$fy{'M'}})-1 MONTH) AS {$tableName}_{$fieldName}_start";
362 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_subtotal";
363 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_interval";
364 $field['title'] = ts('Fiscal Year Beginning');
368 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
369 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
370 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
371 $field['title'] = ts('Month Beginning');
375 $select[] = "DATE({$field['dbAlias']}) as {$tableName}_{$fieldName}_start";
376 $field['title'] = ts('Date');
380 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
381 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
382 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
383 $field['title'] = 'Quarter';
386 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
387 $this->_interval
= $this->_params
['group_bys_freq'][$fieldName];
388 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'];
389 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
390 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
392 // just to make sure these values are transferred to rows.
393 // since we need that for calculation purpose,
394 // e.g making subtotals look nicer or graphs
395 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
396 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
402 if (array_key_exists('fields', $table)) {
403 foreach ($table['fields'] as $fieldName => $field) {
404 if (!empty($field['required']) ||
405 !empty($this->_params
['fields'][$fieldName])
407 // only include statistics columns if set
408 if (!empty($field['statistics'])) {
409 foreach ($field['statistics'] as $stat => $label) {
410 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
411 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
412 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
413 switch (strtolower($stat)) {
415 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
419 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
420 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
424 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
430 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
431 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
432 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
439 $this->_selectClauses
= $select;
440 $this->_select
= "SELECT " . implode(', ', $select) . " ";
446 * @param array $fields
447 * @param array $files
448 * @param CRM_Report_Form_Contribute_Summary $self
452 public static function formRule($fields, $files, $self) {
453 // Check for searching combination of display columns and
455 $ignoreFields = array('total_amount', 'sort_name');
456 $errors = $self->customDataFormRule($fields, $ignoreFields);
458 if (empty($fields['fields']['total_amount'])) {
464 if (!empty($fields[$val])) {
465 $errors[$val] = ts("Please select the Amount Statistics");
476 * @param string $entity
478 * @todo fix function signature to match parent. Remove hacky passing of $entity
479 * to acheive unclear results.
481 public function from($entity = NULL) {
482 $softCreditJoinType = "LEFT";
483 if (!empty($this->_params
['fields']['soft_amount']) &&
484 empty($this->_params
['fields']['total_amount'])
486 // if its only soft credit stats, use inner join
487 $softCreditJoinType = "INNER";
490 $softCreditJoin = "{$softCreditJoinType} JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
491 ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
492 if ($entity == 'contribution' ||
empty($this->_params
['fields']['soft_amount'])) {
493 $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) ";
496 $this->setFromBase('civicrm_contact');
499 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
500 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
501 {$this->_aliases['civicrm_contribution']}.is_test = 0
503 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
504 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
507 $this->joinAddressFromContact();
508 $this->joinPhoneFromContact();
509 $this->joinEmailFromContact();
511 //for contribution batches
512 if ($this->isTableSelected('civicrm_batch')) {
514 LEFT JOIN civicrm_entity_financial_trxn eft
515 ON eft.entity_id = {$this->_aliases['civicrm_contribution']}.id AND
516 eft.entity_table = 'civicrm_contribution'
517 LEFT JOIN civicrm_entity_batch {$this->_aliases['civicrm_batch']}
518 ON ({$this->_aliases['civicrm_batch']}.entity_id = eft.financial_trxn_id
519 AND {$this->_aliases['civicrm_batch']}.entity_table = 'civicrm_financial_trxn')";
522 $this->addFinancialTrxnFromClause();
526 * Set group by clause.
528 public function groupBy() {
529 $this->_groupBy
= "";
530 $groupByColumns = array();
532 if (!empty($this->_params
['group_bys']) &&
533 is_array($this->_params
['group_bys'])
535 foreach ($this->_columns
as $tableName => $table) {
536 if (array_key_exists('group_bys', $table)) {
537 foreach ($table['group_bys'] as $fieldName => $field) {
538 if (!empty($this->_params
['group_bys'][$fieldName])) {
539 if (!empty($field['chart'])) {
540 $this->assign('chartSupported', TRUE);
543 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
544 !empty($this->_params
['group_bys_freq'][$fieldName])
547 $append = "YEAR({$field['dbAlias']});;";
548 if (in_array(strtolower($this->_params
['group_bys_freq'][$fieldName]),
553 if ($this->_params
['group_bys_freq'][$fieldName] == 'FISCALYEAR') {
554 $groupByColumns[] = self
::fiscalYearOffset($field['dbAlias']);
557 $groupByColumns[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
562 $groupByColumns[] = $field['dbAlias'];
569 if (!empty($this->_statFields
) &&
570 (($append && count($groupByColumns) <= 1) ||
(!$append)) &&
573 $this->_rollup
= " WITH ROLLUP";
576 foreach ($groupByColumns as $key => $val) {
577 if (strpos($val, ';;') !== FALSE) {
578 $groupBy = array_merge($groupBy, explode(';;', $val));
581 $groupBy[] = $groupByColumns[$key];
584 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBy);
587 $groupBy = "{$this->_aliases['civicrm_contact']}.id";
588 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contact']}.id";
590 $this->_groupBy
.= $this->_rollup
;
591 // append select with ANY_VALUE() keyword
592 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($this->_selectClauses
, $groupBy);
596 * Store having clauses as an array.
598 public function storeWhereHavingClauseArray() {
599 parent
::storeWhereHavingClauseArray();
600 if (empty($this->_params
['fields']['soft_amount']) &&
601 !empty($this->_havingClauses
)
603 foreach ($this->_havingClauses
as $key => $havingClause) {
604 if (stristr($havingClause, 'soft_soft')) {
605 unset($this->_havingClauses
[$key]);
618 public function statistics(&$rows) {
619 $statistics = parent
::statistics($rows);
621 $softCredit = CRM_Utils_Array
::value('soft_amount', $this->_params
['fields']);
622 $onlySoftCredit = $softCredit && !CRM_Utils_Array
::value('total_amount', $this->_params
['fields']);
623 $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
625 $this->from('contribution');
626 $this->customDataFrom();
629 COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_count,
630 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_sum,
631 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as civicrm_contribution_total_amount_avg,
632 {$this->_aliases['civicrm_contribution']}.currency as currency
633 {$this->_from} {$this->_where}";
637 $this->customDataFrom();
639 COUNT({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_count,
640 SUM({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_sum,
641 ROUND(AVG({$this->_aliases['civicrm_contribution_soft']}.amount), 2) as civicrm_contribution_soft_soft_amount_avg";
642 $contriQuery = "{$select}, {$contriQuery}";
643 $softSQL = "SELECT {$select}, {$this->_aliases['civicrm_contribution']}.currency as currency
644 {$this->_from} {$this->_where} {$group} {$this->_having}";
647 $contriSQL = "SELECT {$contriQuery} {$group} {$this->_having}";
648 $contriDAO = CRM_Core_DAO
::executeQuery($contriSQL);
650 $totalAmount = $average = $mode = $median = $softTotalAmount = $softAverage = array();
651 $count = $softCount = 0;
652 while ($contriDAO->fetch()) {
654 = CRM_Utils_Money
::format($contriDAO->civicrm_contribution_total_amount_sum
, $contriDAO->currency
) .
655 " (" . $contriDAO->civicrm_contribution_total_amount_count
. ")";
656 $average[] = CRM_Utils_Money
::format($contriDAO->civicrm_contribution_total_amount_avg
, $contriDAO->currency
);
657 $count +
= $contriDAO->civicrm_contribution_total_amount_count
;
660 $groupBy = "\n{$group}, {$this->_aliases['civicrm_contribution']}.total_amount";
661 $orderBy = "\nORDER BY civicrm_contribution_total_amount_count DESC";
662 $modeSQL = "SELECT MAX(civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count,
663 SUBSTRING_INDEX(GROUP_CONCAT(amount ORDER BY mode.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
665 FROM (SELECT {$this->_aliases['civicrm_contribution']}.total_amount as amount,
666 {$contriQuery} {$groupBy} {$orderBy}) as mode GROUP BY currency";
668 $mode = $this->calculateMode($modeSQL);
669 $median = $this->calculateMedian();
672 $softDAO = CRM_Core_DAO
::executeQuery($softSQL);
673 while ($softDAO->fetch()) {
675 = CRM_Utils_Money
::format($softDAO->civicrm_contribution_soft_soft_amount_sum
, $softDAO->currency
) .
676 " (" . $softDAO->civicrm_contribution_soft_soft_amount_count
. ")";
677 $softAverage[] = CRM_Utils_Money
::format($softDAO->civicrm_contribution_soft_soft_amount_avg
, $softDAO->currency
);
678 $softCount +
= $softDAO->civicrm_contribution_soft_soft_amount_count
;
682 if (!$onlySoftCredit) {
683 $statistics['counts']['amount'] = array(
684 'title' => ts('Total Amount'),
685 'value' => implode(', ', $totalAmount),
686 'type' => CRM_Utils_Type
::T_STRING
,
688 $statistics['counts']['count'] = array(
689 'title' => ts('Total Contributions'),
692 $statistics['counts']['avg'] = array(
693 'title' => ts('Average'),
694 'value' => implode(', ', $average),
695 'type' => CRM_Utils_Type
::T_STRING
,
697 $statistics['counts']['mode'] = array(
698 'title' => ts('Mode'),
699 'value' => implode(', ', $mode),
700 'type' => CRM_Utils_Type
::T_STRING
,
702 $statistics['counts']['median'] = array(
703 'title' => ts('Median'),
704 'value' => implode(', ', $median),
705 'type' => CRM_Utils_Type
::T_STRING
,
709 $statistics['counts']['soft_amount'] = array(
710 'title' => ts('Total Soft Credit Amount'),
711 'value' => implode(', ', $softTotalAmount),
712 'type' => CRM_Utils_Type
::T_STRING
,
714 $statistics['counts']['soft_count'] = array(
715 'title' => ts('Total Soft Credits'),
716 'value' => $softCount,
718 $statistics['counts']['soft_avg'] = array(
719 'title' => ts('Average Soft Credit'),
720 'value' => implode(', ', $softAverage),
721 'type' => CRM_Utils_Type
::T_STRING
,
728 * Post process function.
730 public function postProcess() {
731 $this->buildACLClause($this->_aliases
['civicrm_contact']);
732 parent
::postProcess();
736 * Build table rows for output.
741 public function buildRows($sql, &$rows) {
742 $dao = CRM_Core_DAO
::executeQuery($sql);
743 if (!is_array($rows)) {
747 // use this method to modify $this->_columnHeaders
748 $this->modifyColumnHeaders();
749 $contriRows = array();
750 $unselectedSectionColumns = $this->unselectedSectionColumns();
752 //CRM-16338 if both soft-credit and contribution are enabled then process the contribution's
753 //total amount's average, count and sum separately and add it to the respective result list
754 $softCredit = (!empty($this->_params
['fields']['soft_amount']) && !empty($this->_params
['fields']['total_amount'])) ?
TRUE : FALSE;
756 $this->from('contribution');
757 $this->customDataFrom();
758 $contriSQL = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
759 $contriDAO = CRM_Core_DAO
::executeQuery($contriSQL);
760 $contriFields = array(
761 'civicrm_contribution_total_amount_sum',
762 'civicrm_contribution_total_amount_avg',
763 'civicrm_contribution_total_amount_count',
765 $contriRows = array();
766 while ($contriDAO->fetch()) {
767 $contriRow = array();
768 foreach ($contriFields as $column) {
769 $contriRow[$column] = $contriDAO->$column;
771 $contriRows[] = $contriRow;
776 while ($dao->fetch()) {
778 foreach ($this->_columnHeaders
as $key => $value) {
779 if ($softCredit && array_key_exists($key, $contriRows[$count])) {
780 $row[$key] = $contriRows[$count][$key];
782 elseif (property_exists($dao, $key)) {
783 $row[$key] = $dao->$key;
787 // section headers not selected for display need to be added to row
788 foreach ($unselectedSectionColumns as $key => $values) {
789 if (property_exists($dao, $key)) {
790 $row[$key] = $dao->$key;
805 public function buildChart(&$rows) {
806 $graphRows = array();
808 if (!empty($this->_params
['charts'])) {
809 if (!empty($this->_params
['group_bys']['receive_date'])) {
811 $contrib = !empty($this->_params
['fields']['total_amount']) ?
TRUE : FALSE;
812 $softContrib = !empty($this->_params
['fields']['soft_amount']) ?
TRUE : FALSE;
814 foreach ($rows as $key => $row) {
815 if ($row['civicrm_contribution_receive_date_subtotal']) {
816 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
817 $graphRows[$this->_interval
][] = $row['civicrm_contribution_receive_date_interval'];
818 if ($softContrib && $contrib) {
819 // both contri & soft contri stats are present
820 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
821 $graphRows['multiValue'][1][] = $row['civicrm_contribution_soft_soft_amount_sum'];
823 elseif ($softContrib) {
824 // only soft contributions
825 $graphRows['multiValue'][0][] = $row['civicrm_contribution_soft_soft_amount_sum'];
828 // only contributions
829 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
834 if ($softContrib && $contrib) {
835 $graphRows['barKeys'][0] = ts('Contributions');
836 $graphRows['barKeys'][1] = ts('Soft Credits');
837 $graphRows['legend'] = ts('Contributions and Soft Credits');
839 elseif ($softContrib) {
840 $graphRows['legend'] = ts('Soft Credits');
844 $config = CRM_Core_Config
::Singleton();
845 $graphRows['xname'] = $this->_interval
;
846 $graphRows['yname'] = ts('Amount (%1)', array(1 => $config->defaultCurrency
));
847 CRM_Utils_OpenFlashChart
::chart($graphRows, $this->_params
['charts'], $this->_interval
);
848 $this->assign('chartType', $this->_params
['charts']);
854 * Alter display of rows.
856 * Iterate through the rows retrieved via SQL and make changes for display purposes,
857 * such as rendering contacts as links.
860 * Rows generated by SQL, with an array for each row.
862 public function alterDisplay(&$rows) {
864 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus();
865 $contributionPages = CRM_Contribute_PseudoConstant
::contributionPage();
867 foreach ($rows as $rowNum => $row) {
868 // make count columns point to detail report
869 if (!empty($this->_params
['group_bys']['receive_date']) &&
870 !empty($row['civicrm_contribution_receive_date_start']) &&
871 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
872 !empty($row['civicrm_contribution_receive_date_subtotal'])
875 $dateStart = CRM_Utils_Date
::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
876 $endDate = new DateTime($dateStart);
879 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
881 switch (strtolower($this->_params
['group_bys_freq']['receive_date'])) {
883 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
1,
884 $dateEnd['d'] - 1, $dateEnd['Y']
889 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
890 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
895 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
896 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
901 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
902 $dateEnd['d'] +
6, $dateEnd['Y']
907 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
3,
908 $dateEnd['d'] - 1, $dateEnd['Y']
912 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
913 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
916 $this->_drilldownReport
918 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
919 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
923 // make subtotals look nicer
924 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
925 !$row['civicrm_contribution_receive_date_subtotal']
927 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields
);
931 // convert display name to links
932 if (array_key_exists('civicrm_contact_sort_name', $row) &&
933 array_key_exists('civicrm_contact_id', $row)
935 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
936 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
937 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
939 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
940 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
944 // convert contribution status id to status name
945 if ($value = CRM_Utils_Array
::value('civicrm_contribution_contribution_status_id', $row)) {
946 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value];
950 if (!empty($row['civicrm_financial_trxn_card_type_id'])) {
951 $rows[$rowNum]['civicrm_financial_trxn_card_type_id'] = $this->getLabels($row['civicrm_financial_trxn_card_type_id'], 'CRM_Financial_DAO_FinancialTrxn', 'card_type_id');
955 if ($value = CRM_Utils_Array
::value('civicrm_contribution_contribution_page_id', $row)) {
956 $rows[$rowNum]['civicrm_contribution_contribution_page_id'] = $contributionPages[$value];
960 // If using campaigns, convert campaign_id to campaign title
961 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
962 if ($value = $row['civicrm_contribution_campaign_id']) {
963 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->campaigns
[$value];
968 // convert batch id to batch title
969 if (!empty($row['civicrm_batch_batch_id']) && !in_array('Subtotal', $rows[$rowNum])) {
970 $rows[$rowNum]['civicrm_batch_batch_id'] = $this->getLabels($row['civicrm_batch_batch_id'], 'CRM_Batch_BAO_EntityBatch', 'batch_id');
974 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
975 $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
977 // skip looking further in rows, if first row itself doesn't
978 // have the column we need
988 * Note this is a slow query. Alternative is extended reports.
993 protected function calculateMode($sql) {
995 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
996 while ($modeDAO->fetch()) {
997 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
998 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
1010 * Note this is a slow query. Alternative is extended reports.
1012 * @return array|null
1014 protected function calculateMedian() {
1015 $sql = "{$this->_from} {$this->_where}";
1016 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
1018 foreach ($currencies as $currency => $val) {
1020 $where = "AND {$this->_aliases['civicrm_contribution']}.currency = '{$currency}'";
1021 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
1025 $medianRow = floor($rowCount / 2);
1026 if ($rowCount %
2 == 0 && !empty($medianRow)) {
1032 $medianValue = "SELECT {$this->_aliases['civicrm_contribution']}.total_amount as median
1034 ORDER BY median LIMIT {$medianRow},{$offset}";
1035 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
1036 while ($medianValDAO->fetch()) {
1038 $midValue = $midValue +
$medianValDAO->median
;
1041 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
1045 $midValue = $midValue / 2;
1046 $median[] = CRM_Utils_Money
::format($midValue, $currency);