3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Report_Form_Contribute_Summary
extends CRM_Report_Form
{
19 protected $_customGroupExtends = ['Contribution', 'Contact', 'Individual'];
20 protected $_customGroupGroupBy = TRUE;
22 public $_drilldownReport = ['contribute/detail' => 'Link to Detail Report'];
25 * To what frequency group-by a date column
29 protected $_groupByDateFreq = [
33 'QUARTER' => 'Quarter',
35 'FISCALYEAR' => 'Fiscal Year',
39 * This report has been optimised for group filtering.
42 * @see https://issues.civicrm.org/jira/browse/CRM-19170
44 protected $groupFilterNotOptimised = FALSE;
47 * Use the generic (but flawed) handling to implement full group by.
49 * Note that because we are calling the parent group by function we set this to FALSE.
50 * The parent group by function adds things to the group by in order to make the mysql pass
51 * but can create incorrect results in the process.
55 public $optimisedForOnlyFullGroupBy = FALSE;
60 public function __construct() {
62 'civicrm_contact' => [
63 'dao' => 'CRM_Contact_DAO_Contact',
64 'fields' => array_merge(
65 $this->getBasicContactFields(),
68 'title' => ts('Contact Name'),
73 'filters' => $this->getBasicContactFilters(['deceased' => NULL]),
74 'grouping' => 'contact-fields',
76 'id' => ['title' => ts('Contact ID')],
78 'title' => ts('Contact Name'),
83 'dao' => 'CRM_Core_DAO_Email',
86 'title' => ts('Email'),
90 'grouping' => 'contact-fields',
92 'civicrm_line_item' => [
93 'dao' => 'CRM_Price_DAO_LineItem',
96 'dao' => 'CRM_Core_DAO_Phone',
99 'title' => ts('Phone'),
103 'grouping' => 'contact-fields',
105 'civicrm_financial_type' => [
106 'dao' => 'CRM_Financial_DAO_FinancialType',
107 'fields' => ['financial_type' => NULL],
108 'grouping' => 'contri-fields',
110 'financial_type' => ['title' => ts('Financial Type')],
113 'civicrm_contribution' => [
114 'dao' => 'CRM_Contribute_DAO_Contribution',
115 //'bao' => 'CRM_Contribute_BAO_Contribution',
117 'contribution_status_id' => [
118 'title' => ts('Contribution Status'),
120 'contribution_source' => ['title' => ts('Source')],
123 'no_display' => TRUE,
125 'contribution_page_id' => [
126 'title' => ts('Contribution Page'),
129 'title' => ts('Contribution Amount Stats'),
132 'count' => ts('Contributions'),
133 'sum' => ts('Contribution Aggregate'),
134 'avg' => ts('Contribution Avg'),
137 'non_deductible_amount' => [
138 'title' => ts('Non-deductible Amount'),
140 'contribution_recur_id' => [
141 'title' => ts('Contribution Recurring'),
142 'dbAlias' => '!ISNULL(contribution_civireport.contribution_recur_id)',
143 'type' => CRM_Utils_Type
::T_BOOLEAN
,
146 'grouping' => 'contri-fields',
148 'receive_date' => ['operatorType' => CRM_Report_Form
::OP_DATE
],
149 'receipt_date' => ['operatorType' => CRM_Report_Form
::OP_DATE
],
150 'thankyou_date' => ['operatorType' => CRM_Report_Form
::OP_DATE
],
151 'contribution_status_id' => [
152 'title' => ts('Contribution Status'),
153 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
154 'options' => CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'search'),
156 'type' => CRM_Utils_Type
::T_INT
,
158 'contribution_page_id' => [
159 'title' => ts('Contribution Page'),
160 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
161 'options' => CRM_Contribute_PseudoConstant
::contributionPage(),
162 'type' => CRM_Utils_Type
::T_INT
,
165 'title' => ts('Currency'),
166 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
167 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
169 'type' => CRM_Utils_Type
::T_STRING
,
171 'financial_type_id' => [
172 'title' => ts('Financial Type'),
173 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
174 'options' => CRM_Contribute_BAO_Contribution
::buildOptions('financial_type_id', 'search'),
175 'type' => CRM_Utils_Type
::T_INT
,
177 'contribution_page_id' => [
178 'title' => ts('Contribution Page'),
179 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
180 'options' => CRM_Contribute_PseudoConstant
::contributionPage(),
181 'type' => CRM_Utils_Type
::T_INT
,
183 'contribution_recur_id' => [
184 'title' => ts('Contribution Recurring'),
185 'operatorType' => CRM_Report_Form
::OP_SELECT
,
186 'type' => CRM_Utils_Type
::T_BOOLEAN
,
192 'dbAlias' => '!ISNULL(contribution_civireport.contribution_recur_id)',
195 'title' => ts('Contribution Amount'),
197 'non_deductible_amount' => [
198 'title' => ts('Non-deductible Amount'),
201 'title' => ts('Contribution Aggregate'),
202 'type' => CRM_Report_Form
::OP_INT
,
203 'dbAlias' => 'civicrm_contribution_total_amount_sum',
207 'title' => ts('Contribution Count'),
208 'type' => CRM_Report_Form
::OP_INT
,
209 'dbAlias' => 'civicrm_contribution_total_amount_count',
213 'title' => ts('Contribution Avg'),
214 'type' => CRM_Report_Form
::OP_INT
,
215 'dbAlias' => 'civicrm_contribution_total_amount_avg',
225 'contribution_source' => NULL,
226 'contribution_status_id' => [
227 'title' => ts('Contribution Status'),
228 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
229 'options' => CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'search'),
231 'type' => CRM_Utils_Type
::T_INT
,
233 'contribution_page_id' => [
234 'title' => ts('Contribution Page'),
235 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
236 'options' => CRM_Contribute_PseudoConstant
::contributionPage(),
237 'type' => CRM_Utils_Type
::T_INT
,
239 'contribution_recur_id' => [
240 'title' => ts('Contribution Recurring'),
241 'type' => CRM_Utils_Type
::T_BOOLEAN
,
242 'dbAlias' => '!ISNULL(contribution_civireport.contribution_recur_id)',
246 'civicrm_financial_trxn' => [
247 'dao' => 'CRM_Financial_DAO_FinancialTrxn',
250 'title' => ts('Credit Card Type'),
251 'dbAlias' => 'GROUP_CONCAT(financial_trxn_civireport.card_type_id SEPARATOR ",")',
256 'title' => ts('Credit Card Type'),
257 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
258 'options' => CRM_Financial_DAO_FinancialTrxn
::buildOptions('card_type_id'),
260 'type' => CRM_Utils_Type
::T_STRING
,
265 'dao' => 'CRM_Batch_DAO_EntityBatch',
266 'grouping' => 'contri-fields',
269 'name' => 'batch_id',
270 'title' => ts('Batch Title'),
271 'dbAlias' => 'GROUP_CONCAT(DISTINCT batch_civireport.batch_id
272 ORDER BY batch_civireport.batch_id SEPARATOR ",")',
277 'title' => ts('Batch Title'),
278 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
279 'options' => CRM_Batch_BAO_Batch
::getBatches(),
280 'type' => CRM_Utils_Type
::T_INT
,
284 'batch_id' => ['title' => ts('Batch Title')],
287 'civicrm_contribution_soft' => [
288 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
291 'title' => ts('Soft Credit Amount Stats'),
294 'count' => ts('Soft Credits'),
295 'sum' => ts('Soft Credit Aggregate'),
296 'avg' => ts('Soft Credit Avg'),
300 'grouping' => 'contri-fields',
303 'title' => ts('Soft Credit Amount'),
305 'soft_credit_type_id' => [
306 'title' => ts('Soft Credit Type'),
307 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
308 'options' => CRM_Core_OptionGroup
::values('soft_credit_type'),
310 'type' => CRM_Utils_Type
::T_STRING
,
313 'title' => ts('Soft Credit Aggregate'),
314 'type' => CRM_Report_Form
::OP_INT
,
315 'dbAlias' => 'civicrm_contribution_soft_soft_amount_sum',
319 'title' => ts('Soft Credits Count'),
320 'type' => CRM_Report_Form
::OP_INT
,
321 'dbAlias' => 'civicrm_contribution_soft_soft_amount_count',
325 'title' => ts('Soft Credit Avg'),
326 'type' => CRM_Report_Form
::OP_INT
,
327 'dbAlias' => 'civicrm_contribution_soft_soft_amount_avg',
332 ] +
$this->addAddressFields();
334 $this->addCampaignFields('civicrm_contribution', TRUE);
336 // Add charts support
339 'barChart' => ts('Bar Chart'),
340 'pieChart' => ts('Pie Chart'),
343 $this->_tagFilter
= TRUE;
344 $this->_groupFilter
= TRUE;
345 $this->_currencyColumn
= 'civicrm_contribution_currency';
346 parent
::__construct();
352 public function select() {
354 $this->_columnHeaders
= [];
355 foreach ($this->_columns
as $tableName => $table) {
356 if (array_key_exists('group_bys', $table)) {
357 foreach ($table['group_bys'] as $fieldName => $field) {
358 if (!empty($this->_params
['group_bys'][$fieldName])) {
359 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
361 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
362 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
363 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
364 $field['title'] = ts('Week Beginning');
368 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
369 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
370 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
371 $field['title'] = ts('Year Beginning');
375 $config = CRM_Core_Config
::singleton();
376 $fy = $config->fiscalYearStart
;
377 $fiscal = self
::fiscalYearOffset($field['dbAlias']);
379 $select[] = "DATE_ADD(MAKEDATE({$fiscal}, 1), INTERVAL ({$fy['M']})-1 MONTH) AS {$tableName}_{$fieldName}_start";
380 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_subtotal";
381 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_interval";
382 $field['title'] = ts('Fiscal Year Beginning');
386 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
387 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
388 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
389 $field['title'] = ts('Month Beginning');
393 $select[] = "DATE({$field['dbAlias']}) as {$tableName}_{$fieldName}_start";
394 $field['title'] = ts('Date');
398 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
399 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
400 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
401 $field['title'] = 'Quarter';
404 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
405 $this->_interval
= $this->_params
['group_bys_freq'][$fieldName];
406 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'];
407 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
408 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
410 // just to make sure these values are transferred to rows.
411 // since we need that for calculation purpose,
412 // e.g making subtotals look nicer or graphs
413 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = ['no_display' => TRUE];
414 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = ['no_display' => TRUE];
420 if (array_key_exists('fields', $table)) {
421 foreach ($table['fields'] as $fieldName => $field) {
422 if (!empty($field['required']) ||
423 !empty($this->_params
['fields'][$fieldName])
425 // only include statistics columns if set
426 if (!empty($field['statistics'])) {
427 foreach ($field['statistics'] as $stat => $label) {
428 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
429 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
430 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
431 switch (strtolower($stat)) {
433 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
437 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
438 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
442 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
448 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
449 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = $field['type'] ??
NULL;
450 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'] ??
NULL;
457 $this->_selectClauses
= $select;
458 $this->_select
= "SELECT " . implode(', ', $select) . " ";
464 * @param array $fields
465 * @param array $files
466 * @param CRM_Report_Form_Contribute_Summary $self
470 public static function formRule($fields, $files, $self) {
471 // Check for searching combination of display columns and
473 $ignoreFields = ['total_amount', 'sort_name'];
474 $errors = $self->customDataFormRule($fields, $ignoreFields);
476 if (empty($fields['fields']['total_amount'])) {
482 if (!empty($fields[$val])) {
483 $errors[$val] = ts("Please select the Amount Statistics");
494 * @param string $entity
496 * @todo fix function signature to match parent. Remove hacky passing of $entity
497 * to acheive unclear results.
499 public function from($entity = NULL) {
500 $softCreditJoinType = "LEFT";
501 if (!empty($this->_params
['fields']['soft_amount']) &&
502 empty($this->_params
['fields']['total_amount'])
504 // if its only soft credit stats, use inner join
505 $softCreditJoinType = "INNER";
508 $softCreditJoin = "{$softCreditJoinType} JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
509 ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
510 if ($entity == 'contribution' ||
empty($this->_params
['fields']['soft_amount'])) {
511 $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) ";
514 $this->setFromBase('civicrm_contact');
517 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
518 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
519 {$this->_aliases['civicrm_contribution']}.is_test = 0 AND
520 {$this->_aliases['civicrm_contribution']}.is_template = 0
522 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
523 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
526 $this->joinAddressFromContact();
527 $this->joinPhoneFromContact();
528 $this->joinEmailFromContact();
530 //for contribution batches
531 if ($this->isTableSelected('civicrm_batch')) {
533 LEFT JOIN civicrm_entity_financial_trxn eft
534 ON eft.entity_id = {$this->_aliases['civicrm_contribution']}.id AND
535 eft.entity_table = 'civicrm_contribution'
536 LEFT JOIN civicrm_entity_batch {$this->_aliases['civicrm_batch']}
537 ON ({$this->_aliases['civicrm_batch']}.entity_id = eft.financial_trxn_id
538 AND {$this->_aliases['civicrm_batch']}.entity_table = 'civicrm_financial_trxn')";
541 $this->addFinancialTrxnFromClause();
545 * Set group by clause.
547 public function groupBy() {
550 $isGroupByFrequency = !empty($this->_params
['group_bys_freq']);
552 if (!empty($this->_params
['group_bys']) &&
553 is_array($this->_params
['group_bys'])
556 if (!empty($this->_statFields
) &&
557 (($isGroupByFrequency && count($this->_groupByArray
) <= 1) ||
(!$isGroupByFrequency)) &&
560 $this->_rollup
= " WITH ROLLUP";
563 foreach ($this->_groupByArray
as $key => $val) {
564 if (strpos($val, ';;') !== FALSE) {
565 $groupBy = array_merge($groupBy, explode(';;', $val));
568 $groupBy[] = $this->_groupByArray
[$key];
571 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBy);
574 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contact']}.id";
576 $this->_groupBy
.= $this->_rollup
;
580 * Store having clauses as an array.
582 public function storeWhereHavingClauseArray() {
583 parent
::storeWhereHavingClauseArray();
584 if (empty($this->_params
['fields']['soft_amount']) &&
585 !empty($this->_havingClauses
)
587 foreach ($this->_havingClauses
as $key => $havingClause) {
588 if (stristr($havingClause, 'soft_soft')) {
589 unset($this->_havingClauses
[$key]);
602 * @throws \CRM_Core_Exception
604 public function statistics(&$rows) {
605 $statistics = parent
::statistics($rows);
607 $softCredit = $this->_params
['fields']['soft_amount'] ??
NULL;
608 $onlySoftCredit = $softCredit && !CRM_Utils_Array
::value('total_amount', $this->_params
['fields']);
609 if (!isset($this->_groupByArray
['civicrm_contribution_currency'])) {
610 $this->_groupByArray
['civicrm_contribution_currency'] = 'currency';
612 $group = ' GROUP BY ' . implode(', ', $this->_groupByArray
);
614 $this->from('contribution');
618 $this->customDataFrom();
620 // Ensure that Extensions that modify the from statement in the sql also modify it in the statistics.
621 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
624 COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_count,
625 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_sum,
626 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as civicrm_contribution_total_amount_avg,
627 {$this->_aliases['civicrm_contribution']}.currency as currency
628 {$this->_from} {$this->_where}
632 $selectOnlySoftCredit = "
633 COUNT({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_count,
634 SUM({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_sum,
635 ROUND(AVG({$this->_aliases['civicrm_contribution_soft']}.amount), 2) as civicrm_contribution_soft_soft_amount_avg,
638 $selectWithSoftCredit = "
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 COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_count,
643 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_sum,
644 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as civicrm_contribution_total_amount_avg,
647 if ($softCredit && $onlySoftCredit) {
648 $contriQuery = "{$selectOnlySoftCredit} {$contriQuery}";
649 $softSQL = "SELECT {$selectOnlySoftCredit} {$this->_aliases['civicrm_contribution']}.currency as currency
650 {$this->_from} {$this->_where} {$group} {$this->_having}";
652 elseif ($softCredit && !$onlySoftCredit) {
653 $contriQuery = "{$selectOnlySoftCredit} {$contriQuery}";
654 $softSQL = "SELECT {$selectWithSoftCredit} {$this->_aliases['civicrm_contribution']}.currency as currency
655 {$this->_from} {$this->_where} {$group} {$this->_having}";
659 $contriSQL = "SELECT {$contriQuery} {$group} {$this->_having}";
660 $contriDAO = CRM_Core_DAO
::executeQuery($contriSQL);
661 $this->addToDeveloperTab($contriSQL);
662 $currencies = $currAmount = $currAverage = $currCount = [];
663 $totalAmount = $average = $mode = $median = [];
664 $softTotalAmount = $softAverage = $averageCount = $averageSoftCount = [];
665 $softCount = $count = 0;
666 while ($contriDAO->fetch()) {
667 if (!isset($currAmount[$contriDAO->currency
])) {
668 $currAmount[$contriDAO->currency
] = 0;
670 if (!isset($currCount[$contriDAO->currency
])) {
671 $currCount[$contriDAO->currency
] = 0;
673 if (!isset($currAverage[$contriDAO->currency
])) {
674 $currAverage[$contriDAO->currency
] = 0;
676 if (!isset($averageCount[$contriDAO->currency
])) {
677 $averageCount[$contriDAO->currency
] = 0;
679 $currAmount[$contriDAO->currency
] +
= $contriDAO->civicrm_contribution_total_amount_sum
;
680 $currCount[$contriDAO->currency
] +
= $contriDAO->civicrm_contribution_total_amount_count
;
681 $currAverage[$contriDAO->currency
] +
= $contriDAO->civicrm_contribution_total_amount_avg
;
682 $averageCount[$contriDAO->currency
]++
;
683 $count +
= $contriDAO->civicrm_contribution_total_amount_count
;
685 if (!in_array($contriDAO->currency
, $currencies)) {
686 $currencies[] = $contriDAO->currency
;
690 foreach ($currencies as $currency) {
691 $totalAmount[] = CRM_Utils_Money
::format($currAmount[$currency], $currency) .
692 " (" . $currCount[$currency] . ")";
693 $average[] = CRM_Utils_Money
::format(($currAverage[$currency] / $averageCount[$currency]), $currency);
696 $groupBy = "\n{$group}, {$this->_aliases['civicrm_contribution']}.total_amount";
697 $orderBy = "\nORDER BY civicrm_contribution_total_amount_count DESC";
698 $modeSQL = "SELECT MAX(civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count,
699 SUBSTRING_INDEX(GROUP_CONCAT(amount ORDER BY mode.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
701 FROM (SELECT {$this->_aliases['civicrm_contribution']}.total_amount as amount,
702 {$contriQuery} {$groupBy} {$orderBy}) as mode GROUP BY currency";
704 $mode = $this->calculateMode($modeSQL);
705 $median = $this->calculateMedian();
707 $currencies = $currSoftAmount = $currSoftAverage = $currSoftCount = [];
709 $softDAO = CRM_Core_DAO
::executeQuery($softSQL);
710 $this->addToDeveloperTab($softSQL);
711 while ($softDAO->fetch()) {
712 if (!isset($currSoftAmount[$softDAO->currency
])) {
713 $currSoftAmount[$softDAO->currency
] = 0;
715 if (!isset($currSoftCount[$softDAO->currency
])) {
716 $currSoftCount[$softDAO->currency
] = 0;
718 if (!isset($currSoftAverage[$softDAO->currency
])) {
719 $currSoftAverage[$softDAO->currency
] = 0;
721 if (!isset($averageSoftCount[$softDAO->currency
])) {
722 $averageSoftCount[$softDAO->currency
] = 0;
724 $currSoftAmount[$softDAO->currency
] +
= $softDAO->civicrm_contribution_soft_soft_amount_sum
;
725 $currSoftCount[$softDAO->currency
] +
= $softDAO->civicrm_contribution_soft_soft_amount_count
;
726 $currSoftAverage[$softDAO->currency
] +
= $softDAO->civicrm_contribution_soft_soft_amount_avg
;
727 $averageSoftCount[$softDAO->currency
]++
;
728 $softCount +
= $softDAO->civicrm_contribution_soft_soft_amount_count
;
730 if (!in_array($softDAO->currency
, $currencies)) {
731 $currencies[] = $softDAO->currency
;
735 foreach ($currencies as $currency) {
736 $softTotalAmount[] = CRM_Utils_Money
::format($currSoftAmount[$currency], $currency) .
737 " (" . $currSoftCount[$currency] . ")";
738 $softAverage[] = CRM_Utils_Money
::format(($currSoftAverage[$currency] / $averageSoftCount[$currency]), $currency);
742 if (!$onlySoftCredit) {
743 $statistics['counts']['amount'] = [
744 'title' => ts('Total Amount'),
745 'value' => implode(', ', $totalAmount),
746 'type' => CRM_Utils_Type
::T_STRING
,
748 $statistics['counts']['count'] = [
749 'title' => ts('Total Contributions'),
752 $statistics['counts']['avg'] = [
753 'title' => ts('Average'),
754 'value' => implode(', ', $average),
755 'type' => CRM_Utils_Type
::T_STRING
,
757 $statistics['counts']['mode'] = [
758 'title' => ts('Mode'),
759 'value' => implode(', ', $mode),
760 'type' => CRM_Utils_Type
::T_STRING
,
762 $statistics['counts']['median'] = [
763 'title' => ts('Median'),
764 'value' => implode(', ', $median),
765 'type' => CRM_Utils_Type
::T_STRING
,
769 $statistics['counts']['soft_amount'] = [
770 'title' => ts('Total Soft Credit Amount'),
771 'value' => implode(', ', $softTotalAmount),
772 'type' => CRM_Utils_Type
::T_STRING
,
774 $statistics['counts']['soft_count'] = [
775 'title' => ts('Total Soft Credits'),
776 'value' => $softCount,
778 $statistics['counts']['soft_avg'] = [
779 'title' => ts('Average Soft Credit'),
780 'value' => implode(', ', $softAverage),
781 'type' => CRM_Utils_Type
::T_STRING
,
790 * @param array $original_rows
792 public function buildChart(&$original_rows) {
795 if (!empty($this->_params
['charts'])) {
796 if (!empty($this->_params
['group_bys']['receive_date'])) {
798 $contrib = !empty($this->_params
['fields']['total_amount']);
799 $softContrib = !empty($this->_params
['fields']['soft_amount']);
801 // Make a copy so that we don't affect what gets passed later to hooks etc.
802 $rows = $original_rows;
803 if ($this->_rollup
) {
804 // Remove the total row otherwise it overwrites the real last month's data since it has the
809 foreach ($rows as $key => $row) {
810 if ($row['civicrm_contribution_receive_date_subtotal']) {
811 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
812 $graphRows[$this->_interval
][] = $row['civicrm_contribution_receive_date_interval'];
813 if ($softContrib && $contrib) {
814 // both contri & soft contri stats are present
815 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
816 $graphRows['multiValue'][1][] = $row['civicrm_contribution_soft_soft_amount_sum'];
818 elseif ($softContrib) {
819 // only soft contributions
820 $graphRows['multiValue'][0][] = $row['civicrm_contribution_soft_soft_amount_sum'];
823 // only contributions
824 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
829 if ($softContrib && $contrib) {
830 $graphRows['barKeys'][0] = ts('Contributions');
831 $graphRows['barKeys'][1] = ts('Soft Credits');
832 $graphRows['legend'] = ts('Contributions and Soft Credits');
834 elseif ($softContrib) {
835 $graphRows['legend'] = ts('Soft Credits');
839 $config = CRM_Core_Config
::Singleton();
840 $graphRows['xname'] = $this->_interval
;
841 $graphRows['yname'] = ts('Amount (%1)', [1 => $config->defaultCurrency
]);
842 CRM_Utils_Chart
::chart($graphRows, $this->_params
['charts'], $this->_interval
);
843 $this->assign('chartType', $this->_params
['charts']);
849 * Alter display of rows.
851 * Iterate through the rows retrieved via SQL and make changes for display purposes,
852 * such as rendering contacts as links.
855 * Rows generated by SQL, with an array for each row.
857 public function alterDisplay(&$rows) {
859 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
860 $contributionPages = CRM_Contribute_PseudoConstant
::contributionPage();
861 //CRM-16338 if both soft-credit and contribution are enabled then process the contribution's
862 //total amount's average, count and sum separately and add it to the respective result list
863 $softCredit = (!empty($this->_params
['fields']['soft_amount']) && !empty($this->_params
['fields']['total_amount']));
865 $this->from('contribution');
866 $this->customDataFrom();
867 $contriSQL = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
868 CRM_Core_DAO
::disableFullGroupByMode();
869 $contriDAO = CRM_Core_DAO
::executeQuery($contriSQL);
870 CRM_Core_DAO
::reenableFullGroupByMode();
871 $this->addToDeveloperTab($contriSQL);
873 'civicrm_contribution_total_amount_sum',
874 'civicrm_contribution_total_amount_avg',
875 'civicrm_contribution_total_amount_count',
878 while ($contriDAO->fetch()) {
879 foreach ($contriFields as $column) {
880 $rows[$count][$column] = $contriDAO->$column;
885 foreach ($rows as $rowNum => $row) {
886 // make count columns point to detail report
887 if (!empty($this->_params
['group_bys']['receive_date']) &&
888 !empty($row['civicrm_contribution_receive_date_start']) &&
889 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
890 !empty($row['civicrm_contribution_receive_date_subtotal'])
893 $dateStart = CRM_Utils_Date
::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
894 $endDate = new DateTime($dateStart);
897 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
899 switch (strtolower($this->_params
['group_bys_freq']['receive_date'])) {
901 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
1,
902 $dateEnd['d'] - 1, $dateEnd['Y']
907 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
908 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
913 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
914 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
919 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
920 $dateEnd['d'] +
6, $dateEnd['Y']
925 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
3,
926 $dateEnd['d'] - 1, $dateEnd['Y']
930 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
931 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
934 $this->_drilldownReport
936 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
937 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
941 // make subtotals look nicer
942 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
943 !$row['civicrm_contribution_receive_date_subtotal']
945 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields
);
949 // convert display name to links
950 if (array_key_exists('civicrm_contact_sort_name', $row) &&
951 array_key_exists('civicrm_contact_id', $row)
953 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
954 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
955 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
957 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
958 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
962 // convert contribution status id to status name
963 if ($value = CRM_Utils_Array
::value('civicrm_contribution_contribution_status_id', $row)) {
964 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value];
968 if (!empty($row['civicrm_financial_trxn_card_type_id'])) {
969 $rows[$rowNum]['civicrm_financial_trxn_card_type_id'] = $this->getLabels($row['civicrm_financial_trxn_card_type_id'], 'CRM_Financial_DAO_FinancialTrxn', 'card_type_id');
973 if ($value = CRM_Utils_Array
::value('civicrm_contribution_contribution_page_id', $row)) {
974 $rows[$rowNum]['civicrm_contribution_contribution_page_id'] = $contributionPages[$value];
978 // If using campaigns, convert campaign_id to campaign title
979 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
980 if ($value = $row['civicrm_contribution_campaign_id']) {
981 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->campaigns
[$value];
986 // convert batch id to batch title
987 if (!empty($row['civicrm_batch_batch_id']) && !in_array('Subtotal', $rows[$rowNum])) {
988 $rows[$rowNum]['civicrm_batch_batch_id'] = $this->getLabels($row['civicrm_batch_batch_id'], 'CRM_Batch_BAO_EntityBatch', 'batch_id');
992 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
993 $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
995 // skip looking further in rows, if first row itself doesn't
996 // have the column we need
1006 * Note this is a slow query. Alternative is extended reports.
1008 * @param string $sql
1009 * @return array|null
1011 protected function calculateMode($sql) {
1013 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
1014 while ($modeDAO->fetch()) {
1015 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
1016 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
1019 $mode[] = ts('N/A');
1028 * Note this is a slow query. Alternative is extended reports.
1030 * @return array|null
1032 protected function calculateMedian() {
1033 $sql = "{$this->_from} {$this->_where}";
1034 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
1036 foreach ($currencies as $currency => $val) {
1038 $where = "AND {$this->_aliases['civicrm_contribution']}.currency = '{$currency}'";
1039 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
1043 $medianRow = floor($rowCount / 2);
1044 if ($rowCount %
2 == 0 && !empty($medianRow)) {
1050 $medianValue = "SELECT {$this->_aliases['civicrm_contribution']}.total_amount as median
1052 ORDER BY median LIMIT {$medianRow},{$offset}";
1053 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
1054 while ($medianValDAO->fetch()) {
1056 $midValue = $midValue +
$medianValDAO->median
;
1059 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
1063 $midValue = $midValue / 2;
1064 $median[] = CRM_Utils_Money
::format($midValue, $currency);