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 $_charts = [
21 'barChart' => 'Bar Chart',
22 'pieChart' => 'Pie Chart',
24 protected $_customGroupExtends = ['Contribution', 'Contact', 'Individual'];
25 protected $_customGroupGroupBy = TRUE;
27 public $_drilldownReport = ['contribute/detail' => 'Link to Detail Report'];
30 * To what frequency group-by a date column
34 protected $_groupByDateFreq = [
38 'QUARTER' => 'Quarter',
40 'FISCALYEAR' => 'Fiscal Year',
44 * This report has been optimised for group filtering.
50 protected $groupFilterNotOptimised = FALSE;
53 * Use the generic (but flawed) handling to implement full group by.
55 * Note that because we are calling the parent group by function we set this to FALSE.
56 * The parent group by function adds things to the group by in order to make the mysql pass
57 * but can create incorrect results in the process.
61 public $optimisedForOnlyFullGroupBy = FALSE;
66 public function __construct() {
68 'civicrm_contact' => [
69 'dao' => 'CRM_Contact_DAO_Contact',
70 'fields' => array_merge(
71 $this->getBasicContactFields(),
74 'title' => ts('Contact Name'),
79 'filters' => $this->getBasicContactFilters(['deceased' => NULL]),
80 'grouping' => 'contact-fields',
82 'id' => ['title' => ts('Contact ID')],
84 'title' => ts('Contact Name'),
89 'dao' => 'CRM_Core_DAO_Email',
92 'title' => ts('Email'),
96 'grouping' => 'contact-fields',
98 'civicrm_line_item' => [
99 'dao' => 'CRM_Price_DAO_LineItem',
102 'dao' => 'CRM_Core_DAO_Phone',
105 'title' => ts('Phone'),
109 'grouping' => 'contact-fields',
111 'civicrm_financial_type' => [
112 'dao' => 'CRM_Financial_DAO_FinancialType',
113 'fields' => ['financial_type' => NULL],
114 'grouping' => 'contri-fields',
116 'financial_type' => ['title' => ts('Financial Type')],
119 'civicrm_contribution' => [
120 'dao' => 'CRM_Contribute_DAO_Contribution',
121 //'bao' => 'CRM_Contribute_BAO_Contribution',
123 'contribution_status_id' => [
124 'title' => ts('Contribution Status'),
126 'contribution_source' => ['title' => ts('Source')],
129 'no_display' => TRUE,
131 'contribution_page_id' => [
132 'title' => ts('Contribution Page'),
135 'title' => ts('Contribution Amount Stats'),
138 'count' => ts('Contributions'),
139 'sum' => ts('Contribution Aggregate'),
140 'avg' => ts('Contribution Avg'),
143 'non_deductible_amount' => [
144 'title' => ts('Non-deductible Amount'),
147 'grouping' => 'contri-fields',
149 'receive_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_Financial_BAO_FinancialType
::getAvailableFinancialTypes(),
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
,
184 'title' => ts('Contribution Amount'),
186 'non_deductible_amount' => [
187 'title' => ts('Non-deductible Amount'),
190 'title' => ts('Contribution Aggregate'),
191 'type' => CRM_Report_Form
::OP_INT
,
192 'dbAlias' => 'civicrm_contribution_total_amount_sum',
196 'title' => ts('Contribution Count'),
197 'type' => CRM_Report_Form
::OP_INT
,
198 'dbAlias' => 'civicrm_contribution_total_amount_count',
202 'title' => ts('Contribution Avg'),
203 'type' => CRM_Report_Form
::OP_INT
,
204 'dbAlias' => 'civicrm_contribution_total_amount_avg',
214 'contribution_source' => NULL,
215 'contribution_status_id' => [
216 'title' => ts('Contribution Status'),
217 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
218 'options' => CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'search'),
220 'type' => CRM_Utils_Type
::T_INT
,
222 'contribution_page_id' => [
223 'title' => ts('Contribution Page'),
224 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
225 'options' => CRM_Contribute_PseudoConstant
::contributionPage(),
226 'type' => CRM_Utils_Type
::T_INT
,
230 'civicrm_financial_trxn' => [
231 'dao' => 'CRM_Financial_DAO_FinancialTrxn',
234 'title' => ts('Credit Card Type'),
235 'dbAlias' => 'GROUP_CONCAT(financial_trxn_civireport.card_type_id SEPARATOR ",")',
240 'title' => ts('Credit Card Type'),
241 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
242 'options' => CRM_Financial_DAO_FinancialTrxn
::buildOptions('card_type_id'),
244 'type' => CRM_Utils_Type
::T_STRING
,
249 'dao' => 'CRM_Batch_DAO_EntityBatch',
250 'grouping' => 'contri-fields',
253 'name' => 'batch_id',
254 'title' => ts('Batch Title'),
255 'dbAlias' => 'GROUP_CONCAT(DISTINCT batch_civireport.batch_id
256 ORDER BY batch_civireport.batch_id SEPARATOR ",")',
261 'title' => ts('Batch Title'),
262 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
263 'options' => CRM_Batch_BAO_Batch
::getBatches(),
264 'type' => CRM_Utils_Type
::T_INT
,
268 'batch_id' => ['title' => ts('Batch Title')],
271 'civicrm_contribution_soft' => [
272 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
275 'title' => ts('Soft Credit Amount Stats'),
278 'count' => ts('Soft Credits'),
279 'sum' => ts('Soft Credit Aggregate'),
280 'avg' => ts('Soft Credit Avg'),
284 'grouping' => 'contri-fields',
287 'title' => ts('Soft Credit Amount'),
289 'soft_credit_type_id' => [
290 'title' => ts('Soft Credit Type'),
291 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
292 'options' => CRM_Core_OptionGroup
::values('soft_credit_type'),
294 'type' => CRM_Utils_Type
::T_STRING
,
297 'title' => ts('Soft Credit Aggregate'),
298 'type' => CRM_Report_Form
::OP_INT
,
299 'dbAlias' => 'civicrm_contribution_soft_soft_amount_sum',
303 'title' => ts('Soft Credits Count'),
304 'type' => CRM_Report_Form
::OP_INT
,
305 'dbAlias' => 'civicrm_contribution_soft_soft_amount_count',
309 'title' => ts('Soft Credit Avg'),
310 'type' => CRM_Report_Form
::OP_INT
,
311 'dbAlias' => 'civicrm_contribution_soft_soft_amount_avg',
316 ] +
$this->addAddressFields();
318 $this->addCampaignFields('civicrm_contribution', TRUE);
320 $this->_tagFilter
= TRUE;
321 $this->_groupFilter
= TRUE;
322 $this->_currencyColumn
= 'civicrm_contribution_currency';
323 parent
::__construct();
329 public function select() {
331 $this->_columnHeaders
= [];
332 foreach ($this->_columns
as $tableName => $table) {
333 if (array_key_exists('group_bys', $table)) {
334 foreach ($table['group_bys'] as $fieldName => $field) {
335 if (!empty($this->_params
['group_bys'][$fieldName])) {
336 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
338 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
339 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
340 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
341 $field['title'] = ts('Week Beginning');
345 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
346 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
347 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
348 $field['title'] = ts('Year Beginning');
352 $config = CRM_Core_Config
::singleton();
353 $fy = $config->fiscalYearStart
;
354 $fiscal = self
::fiscalYearOffset($field['dbAlias']);
356 $select[] = "DATE_ADD(MAKEDATE({$fiscal}, 1), INTERVAL ({$fy{'M'}})-1 MONTH) AS {$tableName}_{$fieldName}_start";
357 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_subtotal";
358 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_interval";
359 $field['title'] = ts('Fiscal Year Beginning');
363 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
364 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
365 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
366 $field['title'] = ts('Month Beginning');
370 $select[] = "DATE({$field['dbAlias']}) as {$tableName}_{$fieldName}_start";
371 $field['title'] = ts('Date');
375 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
376 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
377 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
378 $field['title'] = 'Quarter';
381 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
382 $this->_interval
= $this->_params
['group_bys_freq'][$fieldName];
383 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'];
384 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
385 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
387 // just to make sure these values are transferred to rows.
388 // since we need that for calculation purpose,
389 // e.g making subtotals look nicer or graphs
390 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = ['no_display' => TRUE];
391 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = ['no_display' => TRUE];
397 if (array_key_exists('fields', $table)) {
398 foreach ($table['fields'] as $fieldName => $field) {
399 if (!empty($field['required']) ||
400 !empty($this->_params
['fields'][$fieldName])
402 // only include statistics columns if set
403 if (!empty($field['statistics'])) {
404 foreach ($field['statistics'] as $stat => $label) {
405 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
406 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
407 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
408 switch (strtolower($stat)) {
410 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
414 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
415 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
419 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
425 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
426 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = $field['type'] ??
NULL;
427 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'] ??
NULL;
434 $this->_selectClauses
= $select;
435 $this->_select
= "SELECT " . implode(', ', $select) . " ";
441 * @param array $fields
442 * @param array $files
443 * @param CRM_Report_Form_Contribute_Summary $self
447 public static function formRule($fields, $files, $self) {
448 // Check for searching combination of display columns and
450 $ignoreFields = ['total_amount', 'sort_name'];
451 $errors = $self->customDataFormRule($fields, $ignoreFields);
453 if (empty($fields['fields']['total_amount'])) {
459 if (!empty($fields[$val])) {
460 $errors[$val] = ts("Please select the Amount Statistics");
471 * @param string $entity
473 * @todo fix function signature to match parent. Remove hacky passing of $entity
474 * to acheive unclear results.
476 public function from($entity = NULL) {
477 $softCreditJoinType = "LEFT";
478 if (!empty($this->_params
['fields']['soft_amount']) &&
479 empty($this->_params
['fields']['total_amount'])
481 // if its only soft credit stats, use inner join
482 $softCreditJoinType = "INNER";
485 $softCreditJoin = "{$softCreditJoinType} JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
486 ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
487 if ($entity == 'contribution' ||
empty($this->_params
['fields']['soft_amount'])) {
488 $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) ";
491 $this->setFromBase('civicrm_contact');
494 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
495 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
496 {$this->_aliases['civicrm_contribution']}.is_test = 0
498 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
499 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
502 $this->joinAddressFromContact();
503 $this->joinPhoneFromContact();
504 $this->joinEmailFromContact();
506 //for contribution batches
507 if ($this->isTableSelected('civicrm_batch')) {
509 LEFT JOIN civicrm_entity_financial_trxn eft
510 ON eft.entity_id = {$this->_aliases['civicrm_contribution']}.id AND
511 eft.entity_table = 'civicrm_contribution'
512 LEFT JOIN civicrm_entity_batch {$this->_aliases['civicrm_batch']}
513 ON ({$this->_aliases['civicrm_batch']}.entity_id = eft.financial_trxn_id
514 AND {$this->_aliases['civicrm_batch']}.entity_table = 'civicrm_financial_trxn')";
517 $this->addFinancialTrxnFromClause();
521 * Set group by clause.
523 public function groupBy() {
526 $isGroupByFrequency = !empty($this->_params
['group_bys_freq']);
528 if (!empty($this->_params
['group_bys']) &&
529 is_array($this->_params
['group_bys'])
532 if (!empty($this->_statFields
) &&
533 (($isGroupByFrequency && count($this->_groupByArray
) <= 1) ||
(!$isGroupByFrequency)) &&
536 $this->_rollup
= " WITH ROLLUP";
539 foreach ($this->_groupByArray
as $key => $val) {
540 if (strpos($val, ';;') !== FALSE) {
541 $groupBy = array_merge($groupBy, explode(';;', $val));
544 $groupBy[] = $this->_groupByArray
[$key];
547 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBy);
550 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contact']}.id";
552 $this->_groupBy
.= $this->_rollup
;
556 * Store having clauses as an array.
558 public function storeWhereHavingClauseArray() {
559 parent
::storeWhereHavingClauseArray();
560 if (empty($this->_params
['fields']['soft_amount']) &&
561 !empty($this->_havingClauses
)
563 foreach ($this->_havingClauses
as $key => $havingClause) {
564 if (stristr($havingClause, 'soft_soft')) {
565 unset($this->_havingClauses
[$key]);
578 * @throws \CRM_Core_Exception
580 public function statistics(&$rows) {
581 $statistics = parent
::statistics($rows);
583 $softCredit = $this->_params
['fields']['soft_amount'] ??
NULL;
584 $onlySoftCredit = $softCredit && !CRM_Utils_Array
::value('total_amount', $this->_params
['fields']);
585 if (!isset($this->_groupByArray
['civicrm_contribution_currency'])) {
586 $this->_groupByArray
['civicrm_contribution_currency'] = 'currency';
588 $group = ' GROUP BY ' . implode(', ', $this->_groupByArray
);
590 $this->from('contribution');
594 $this->customDataFrom();
596 // Ensure that Extensions that modify the from statement in the sql also modify it in the statistics.
597 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
600 COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_count,
601 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_sum,
602 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as civicrm_contribution_total_amount_avg,
603 {$this->_aliases['civicrm_contribution']}.currency as currency
604 {$this->_from} {$this->_where}
608 $selectOnlySoftCredit = "
609 COUNT({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_count,
610 SUM({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_sum,
611 ROUND(AVG({$this->_aliases['civicrm_contribution_soft']}.amount), 2) as civicrm_contribution_soft_soft_amount_avg,
614 $selectWithSoftCredit = "
615 COUNT({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_count,
616 SUM({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_sum,
617 ROUND(AVG({$this->_aliases['civicrm_contribution_soft']}.amount), 2) as civicrm_contribution_soft_soft_amount_avg,
618 COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_count,
619 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_sum,
620 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as civicrm_contribution_total_amount_avg,
623 if ($softCredit && $onlySoftCredit) {
624 $contriQuery = "{$selectOnlySoftCredit} {$contriQuery}";
625 $softSQL = "SELECT {$selectOnlySoftCredit} {$this->_aliases['civicrm_contribution']}.currency as currency
626 {$this->_from} {$this->_where} {$group} {$this->_having}";
628 elseif ($softCredit && !$onlySoftCredit) {
629 $contriQuery = "{$selectOnlySoftCredit} {$contriQuery}";
630 $softSQL = "SELECT {$selectWithSoftCredit} {$this->_aliases['civicrm_contribution']}.currency as currency
631 {$this->_from} {$this->_where} {$group} {$this->_having}";
635 $contriSQL = "SELECT {$contriQuery} {$group} {$this->_having}";
636 $contriDAO = CRM_Core_DAO
::executeQuery($contriSQL);
637 $this->addToDeveloperTab($contriSQL);
638 $currencies = $currAmount = $currAverage = $currCount = [];
639 $totalAmount = $average = $mode = $median = [];
640 $softTotalAmount = $softAverage = $averageCount = $averageSoftCount = [];
641 $softCount = $count = 0;
642 while ($contriDAO->fetch()) {
643 if (!isset($currAmount[$contriDAO->currency
])) {
644 $currAmount[$contriDAO->currency
] = 0;
646 if (!isset($currCount[$contriDAO->currency
])) {
647 $currCount[$contriDAO->currency
] = 0;
649 if (!isset($currAverage[$contriDAO->currency
])) {
650 $currAverage[$contriDAO->currency
] = 0;
652 if (!isset($averageCount[$contriDAO->currency
])) {
653 $averageCount[$contriDAO->currency
] = 0;
655 $currAmount[$contriDAO->currency
] +
= $contriDAO->civicrm_contribution_total_amount_sum
;
656 $currCount[$contriDAO->currency
] +
= $contriDAO->civicrm_contribution_total_amount_count
;
657 $currAverage[$contriDAO->currency
] +
= $contriDAO->civicrm_contribution_total_amount_avg
;
658 $averageCount[$contriDAO->currency
]++
;
659 $count +
= $contriDAO->civicrm_contribution_total_amount_count
;
661 if (!in_array($contriDAO->currency
, $currencies)) {
662 $currencies[] = $contriDAO->currency
;
666 foreach ($currencies as $currency) {
667 $totalAmount[] = CRM_Utils_Money
::format($currAmount[$currency], $currency) .
668 " (" . $currCount[$currency] . ")";
669 $average[] = CRM_Utils_Money
::format(($currAverage[$currency] / $averageCount[$currency]), $currency);
672 $groupBy = "\n{$group}, {$this->_aliases['civicrm_contribution']}.total_amount";
673 $orderBy = "\nORDER BY civicrm_contribution_total_amount_count DESC";
674 $modeSQL = "SELECT MAX(civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count,
675 SUBSTRING_INDEX(GROUP_CONCAT(amount ORDER BY mode.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
677 FROM (SELECT {$this->_aliases['civicrm_contribution']}.total_amount as amount,
678 {$contriQuery} {$groupBy} {$orderBy}) as mode GROUP BY currency";
680 $mode = $this->calculateMode($modeSQL);
681 $median = $this->calculateMedian();
683 $currencies = $currSoftAmount = $currSoftAverage = $currSoftCount = [];
685 $softDAO = CRM_Core_DAO
::executeQuery($softSQL);
686 $this->addToDeveloperTab($softSQL);
687 while ($softDAO->fetch()) {
688 if (!isset($currSoftAmount[$softDAO->currency
])) {
689 $currSoftAmount[$softDAO->currency
] = 0;
691 if (!isset($currSoftCount[$softDAO->currency
])) {
692 $currSoftCount[$softDAO->currency
] = 0;
694 if (!isset($currSoftAverage[$softDAO->currency
])) {
695 $currSoftAverage[$softDAO->currency
] = 0;
697 if (!isset($averageSoftCount[$softDAO->currency
])) {
698 $averageSoftCount[$softDAO->currency
] = 0;
700 $currSoftAmount[$softDAO->currency
] +
= $softDAO->civicrm_contribution_soft_soft_amount_sum
;
701 $currSoftCount[$softDAO->currency
] +
= $softDAO->civicrm_contribution_soft_soft_amount_count
;
702 $currSoftAverage[$softDAO->currency
] +
= $softDAO->civicrm_contribution_soft_soft_amount_avg
;
703 $averageSoftCount[$softDAO->currency
]++
;
704 $softCount +
= $softDAO->civicrm_contribution_soft_soft_amount_count
;
706 if (!in_array($softDAO->currency
, $currencies)) {
707 $currencies[] = $softDAO->currency
;
711 foreach ($currencies as $currency) {
712 $softTotalAmount[] = CRM_Utils_Money
::format($currSoftAmount[$currency], $currency) .
713 " (" . $currSoftCount[$currency] . ")";
714 $softAverage[] = CRM_Utils_Money
::format(($currSoftAverage[$currency] / $averageSoftCount[$currency]), $currency);
718 if (!$onlySoftCredit) {
719 $statistics['counts']['amount'] = [
720 'title' => ts('Total Amount'),
721 'value' => implode(', ', $totalAmount),
722 'type' => CRM_Utils_Type
::T_STRING
,
724 $statistics['counts']['count'] = [
725 'title' => ts('Total Contributions'),
728 $statistics['counts']['avg'] = [
729 'title' => ts('Average'),
730 'value' => implode(', ', $average),
731 'type' => CRM_Utils_Type
::T_STRING
,
733 $statistics['counts']['mode'] = [
734 'title' => ts('Mode'),
735 'value' => implode(', ', $mode),
736 'type' => CRM_Utils_Type
::T_STRING
,
738 $statistics['counts']['median'] = [
739 'title' => ts('Median'),
740 'value' => implode(', ', $median),
741 'type' => CRM_Utils_Type
::T_STRING
,
745 $statistics['counts']['soft_amount'] = [
746 'title' => ts('Total Soft Credit Amount'),
747 'value' => implode(', ', $softTotalAmount),
748 'type' => CRM_Utils_Type
::T_STRING
,
750 $statistics['counts']['soft_count'] = [
751 'title' => ts('Total Soft Credits'),
752 'value' => $softCount,
754 $statistics['counts']['soft_avg'] = [
755 'title' => ts('Average Soft Credit'),
756 'value' => implode(', ', $softAverage),
757 'type' => CRM_Utils_Type
::T_STRING
,
768 public function buildChart(&$rows) {
771 if (!empty($this->_params
['charts'])) {
772 if (!empty($this->_params
['group_bys']['receive_date'])) {
774 $contrib = !empty($this->_params
['fields']['total_amount']);
775 $softContrib = !empty($this->_params
['fields']['soft_amount']);
777 foreach ($rows as $key => $row) {
778 if ($row['civicrm_contribution_receive_date_subtotal']) {
779 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
780 $graphRows[$this->_interval
][] = $row['civicrm_contribution_receive_date_interval'];
781 if ($softContrib && $contrib) {
782 // both contri & soft contri stats are present
783 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
784 $graphRows['multiValue'][1][] = $row['civicrm_contribution_soft_soft_amount_sum'];
786 elseif ($softContrib) {
787 // only soft contributions
788 $graphRows['multiValue'][0][] = $row['civicrm_contribution_soft_soft_amount_sum'];
791 // only contributions
792 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
797 if ($softContrib && $contrib) {
798 $graphRows['barKeys'][0] = ts('Contributions');
799 $graphRows['barKeys'][1] = ts('Soft Credits');
800 $graphRows['legend'] = ts('Contributions and Soft Credits');
802 elseif ($softContrib) {
803 $graphRows['legend'] = ts('Soft Credits');
807 $config = CRM_Core_Config
::Singleton();
808 $graphRows['xname'] = $this->_interval
;
809 $graphRows['yname'] = ts('Amount (%1)', [1 => $config->defaultCurrency
]);
810 CRM_Utils_Chart
::chart($graphRows, $this->_params
['charts'], $this->_interval
);
811 $this->assign('chartType', $this->_params
['charts']);
817 * Alter display of rows.
819 * Iterate through the rows retrieved via SQL and make changes for display purposes,
820 * such as rendering contacts as links.
823 * Rows generated by SQL, with an array for each row.
825 public function alterDisplay(&$rows) {
827 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
828 $contributionPages = CRM_Contribute_PseudoConstant
::contributionPage();
829 //CRM-16338 if both soft-credit and contribution are enabled then process the contribution's
830 //total amount's average, count and sum separately and add it to the respective result list
831 $softCredit = (!empty($this->_params
['fields']['soft_amount']) && !empty($this->_params
['fields']['total_amount']));
833 $this->from('contribution');
834 $this->customDataFrom();
835 $contriSQL = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
836 CRM_Core_DAO
::disableFullGroupByMode();
837 $contriDAO = CRM_Core_DAO
::executeQuery($contriSQL);
838 CRM_Core_DAO
::reenableFullGroupByMode();
839 $this->addToDeveloperTab($contriSQL);
841 'civicrm_contribution_total_amount_sum',
842 'civicrm_contribution_total_amount_avg',
843 'civicrm_contribution_total_amount_count',
846 while ($contriDAO->fetch()) {
847 foreach ($contriFields as $column) {
848 $rows[$count][$column] = $contriDAO->$column;
853 foreach ($rows as $rowNum => $row) {
854 // make count columns point to detail report
855 if (!empty($this->_params
['group_bys']['receive_date']) &&
856 !empty($row['civicrm_contribution_receive_date_start']) &&
857 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
858 !empty($row['civicrm_contribution_receive_date_subtotal'])
861 $dateStart = CRM_Utils_Date
::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
862 $endDate = new DateTime($dateStart);
865 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
867 switch (strtolower($this->_params
['group_bys_freq']['receive_date'])) {
869 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
1,
870 $dateEnd['d'] - 1, $dateEnd['Y']
875 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
876 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
881 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
882 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
887 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
888 $dateEnd['d'] +
6, $dateEnd['Y']
893 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
3,
894 $dateEnd['d'] - 1, $dateEnd['Y']
898 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
899 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
902 $this->_drilldownReport
904 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
905 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
909 // make subtotals look nicer
910 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
911 !$row['civicrm_contribution_receive_date_subtotal']
913 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields
);
917 // convert display name to links
918 if (array_key_exists('civicrm_contact_sort_name', $row) &&
919 array_key_exists('civicrm_contact_id', $row)
921 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
922 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
923 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
925 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
926 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
930 // convert contribution status id to status name
931 if ($value = CRM_Utils_Array
::value('civicrm_contribution_contribution_status_id', $row)) {
932 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value];
936 if (!empty($row['civicrm_financial_trxn_card_type_id'])) {
937 $rows[$rowNum]['civicrm_financial_trxn_card_type_id'] = $this->getLabels($row['civicrm_financial_trxn_card_type_id'], 'CRM_Financial_DAO_FinancialTrxn', 'card_type_id');
941 if ($value = CRM_Utils_Array
::value('civicrm_contribution_contribution_page_id', $row)) {
942 $rows[$rowNum]['civicrm_contribution_contribution_page_id'] = $contributionPages[$value];
946 // If using campaigns, convert campaign_id to campaign title
947 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
948 if ($value = $row['civicrm_contribution_campaign_id']) {
949 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->campaigns
[$value];
954 // convert batch id to batch title
955 if (!empty($row['civicrm_batch_batch_id']) && !in_array('Subtotal', $rows[$rowNum])) {
956 $rows[$rowNum]['civicrm_batch_batch_id'] = $this->getLabels($row['civicrm_batch_batch_id'], 'CRM_Batch_BAO_EntityBatch', 'batch_id');
960 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
961 $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
963 // skip looking further in rows, if first row itself doesn't
964 // have the column we need
974 * Note this is a slow query. Alternative is extended reports.
979 protected function calculateMode($sql) {
981 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
982 while ($modeDAO->fetch()) {
983 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
984 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
996 * Note this is a slow query. Alternative is extended reports.
1000 protected function calculateMedian() {
1001 $sql = "{$this->_from} {$this->_where}";
1002 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
1004 foreach ($currencies as $currency => $val) {
1006 $where = "AND {$this->_aliases['civicrm_contribution']}.currency = '{$currency}'";
1007 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
1011 $medianRow = floor($rowCount / 2);
1012 if ($rowCount %
2 == 0 && !empty($medianRow)) {
1018 $medianValue = "SELECT {$this->_aliases['civicrm_contribution']}.total_amount as median
1020 ORDER BY median LIMIT {$medianRow},{$offset}";
1021 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
1022 while ($medianValDAO->fetch()) {
1024 $midValue = $midValue +
$medianValDAO->median
;
1027 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
1031 $midValue = $midValue / 2;
1032 $median[] = CRM_Utils_Money
::format($midValue, $currency);