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_Repeat
extends CRM_Report_Form
{
18 protected $_amountClauseWithAND = NULL;
20 protected $_customGroupExtends = array(
25 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
28 * Temp table for first time frame.
32 protected $tempTableRepeat1 = NULL;
35 * Temp table for second time frame.
39 protected $tempTableRepeat2 = NULL;
42 * The table the report is being grouped by.
46 protected $groupByTable;
49 * The field the report is being grouped by.
53 protected $groupByFieldName;
56 * The alias of the table the report is being grouped by.
60 protected $groupByTableAlias;
63 * The column in the contribution table that joins to the temp tables.
67 protected $contributionJoinTableColumn;
70 * This report has been optimised for group filtering.
73 * @see https://issues.civicrm.org/jira/browse/CRM-19170
75 protected $groupFilterNotOptimised = FALSE;
80 public function __construct() {
81 $this->_columns
= array(
82 'civicrm_contact' => array(
83 'dao' => 'CRM_Contact_DAO_Contact',
84 'grouping' => 'contact-fields',
85 'fields' => array_merge(
86 $this->getBasicContactFields(),
89 'title' => ts('Contact Name'),
95 'filters' => array_merge(
96 $this->getBasicContactFilters(array('deceased' => NULL)),
98 'percentage_change' => array(
99 'title' => ts('Percentage Change'),
100 'type' => CRM_Utils_Type
::T_INT
,
101 'operatorType' => CRM_Report_Form
::OP_INT
,
102 'name' => 'percentage_change',
103 'dbAlias' => '( ( contribution_civireport2.total_amount_sum - contribution_civireport1.total_amount_sum ) * 100 / contribution_civireport1.total_amount_sum )',
107 'group_bys' => array(
109 'title' => ts('Contact'),
113 'order_bys' => array(
114 'sort_name' => array(
115 'title' => ts('Last Name, First Name'),
117 'default_weight' => '0',
118 'default_order' => 'ASC',
120 'first_name' => array(
121 'title' => ts('First Name'),
123 'gender_id' => array(
124 'name' => 'gender_id',
125 'title' => ts('Gender'),
127 'birth_date' => array(
128 'name' => 'birth_date',
129 'title' => ts('Birth Date'),
131 'contact_type' => array(
132 'title' => ts('Contact Type'),
134 'contact_sub_type' => array(
135 'title' => ts('Contact Subtype'),
139 'civicrm_email' => array(
140 'dao' => 'CRM_Core_DAO_Email',
143 'title' => ts('Email'),
147 'grouping' => 'contact-fields',
149 'civicrm_phone' => array(
150 'dao' => 'CRM_Core_DAO_Phone',
153 'title' => ts('Phone'),
157 'grouping' => 'contact-fields',
159 'civicrm_financial_type' => array(
160 'dao' => 'CRM_Financial_DAO_FinancialType',
161 'fields' => array('financial_type' => array('title' => ts('Financial Type'))),
162 'grouping' => 'contri-fields',
163 'group_bys' => array(
164 'financial_type' => array(
166 'title' => ts('Financial Type'),
170 'civicrm_contribution' => array(
171 'dao' => 'CRM_Contribute_DAO_Contribution',
173 'contribution_source' => NULL,
174 'total_amount1' => array(
175 'name' => 'total_amount',
176 'alias' => 'contribution1',
177 'title' => ts('Range One Stat'),
178 'type' => CRM_Utils_Type
::T_MONEY
,
181 'clause' => 'contribution_civireport1.total_amount_count as contribution1_total_amount_count, contribution_civireport1.total_amount_sum as contribution1_total_amount_sum',
183 'total_amount2' => array(
184 'name' => 'total_amount',
185 'alias' => 'contribution2',
186 'title' => ts('Range Two Stat'),
187 'type' => CRM_Utils_Type
::T_MONEY
,
190 'clause' => 'contribution_civireport2.total_amount_count as contribution2_total_amount_count, contribution_civireport2.total_amount_sum as contribution2_total_amount_sum',
193 'grouping' => 'contri-fields',
195 'receive_date1' => array(
196 'title' => ts('Initial Date Range'),
197 'default' => 'previous.year',
198 'operatorType' => CRM_Report_Form
::OP_DATE
,
199 'name' => 'receive_date',
201 'receive_date2' => array(
202 'title' => ts('Second Date Range'),
203 'default' => 'this.year',
204 'operatorType' => CRM_Report_Form
::OP_DATE
,
205 'name' => 'receive_date',
207 'total_amount1' => array(
208 'title' => ts('Range One Amount'),
209 'type' => CRM_Utils_Type
::T_INT
,
210 'operatorType' => CRM_Report_Form
::OP_INT
,
211 'name' => 'total_amount',
213 'total_amount2' => array(
214 'title' => ts('Range Two Amount'),
215 'type' => CRM_Utils_Type
::T_INT
,
216 'operatorType' => CRM_Report_Form
::OP_INT
,
217 'name' => 'total_amount',
219 'financial_type_id' => array(
220 'title' => ts('Financial Type'),
221 'type' => CRM_Utils_Type
::T_INT
,
222 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
223 'options' => CRM_Contribute_BAO_Contribution
::buildOptions('financial_type_id', 'search'),
225 'contribution_status_id' => array(
226 'title' => ts('Contribution Status'),
227 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
228 'options' => CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'search'),
229 'default' => array('1'),
232 'group_bys' => array('contribution_source' => NULL),
234 ) +
$this->addAddressFields(TRUE, FALSE, TRUE, array('country_id' => FALSE));
236 $this->_groupFilter
= TRUE;
237 $this->_tagFilter
= TRUE;
239 parent
::__construct();
243 * Override parent select for reasons someone will someday make sense of & document.
245 public function select() {
248 // since contact fields not related to financial type
249 if (array_key_exists('financial_type', $this->_params
['group_bys']) ||
250 array_key_exists('contribution_source', $this->_params
['group_bys'])
252 unset($this->_columns
['civicrm_contact']['fields']['id']);
255 foreach ($this->_columns
as $tableName => $table) {
256 if (array_key_exists('fields', $table)) {
257 foreach ($table['fields'] as $fieldName => $field) {
258 if (!empty($field['required']) ||
259 !empty($this->_params
['fields'][$fieldName])
261 if (isset($field['clause'])) {
262 $select[] = $field['clause'];
264 // FIXME: dirty hack for setting columnHeaders
265 $this->_columnHeaders
["{$field['alias']}_{$field['name']}_sum"]['type'] = $field['type'] ??
NULL;
266 $this->_columnHeaders
["{$field['alias']}_{$field['name']}_sum"]['title'] = $field['title'];
267 $this->_columnHeaders
["{$field['alias']}_{$field['name']}_count"]['type'] = $field['type'] ??
NULL;
268 $this->_columnHeaders
["{$field['alias']}_{$field['name']}_count"]['title'] = $field['title'];
272 // only include statistics columns if set
273 $select[] = "{$field['dbAlias']} as {$field['alias']}_{$field['name']}";
274 $this->_columnHeaders
["{$field['alias']}_{$field['name']}"]['type'] = $field['type'] ??
NULL;
275 $this->_columnHeaders
["{$field['alias']}_{$field['name']}"]['title'] = $field['title'] ??
NULL;
276 if (!empty($field['no_display'])) {
277 $this->_columnHeaders
["{$field['alias']}_{$field['name']}"]['no_display'] = TRUE;
283 $this->_selectClauses
= $select;
284 $this->_select
= "SELECT " . implode(', ', $select) . " ";
288 * Inspect the group by params to determine group by information.
290 public function setGroupByInformation() {
291 if (!empty($this->_params
['group_bys']) &&
292 is_array($this->_params
['group_bys'])
294 foreach ($this->_columns
as $tableName => $table) {
295 if (array_key_exists('group_bys', $table)) {
296 foreach ($table['group_bys'] as $fieldName => $field) {
297 if (!empty($this->_params
['group_bys'][$fieldName])) {
298 $this->groupByTable
= $tableName;
299 $this->groupByTableAlias
= $field['alias'];
300 $this->groupByFieldName
= $field['name'];
301 if ($this->groupByTable
== 'civicrm_contact') {
302 $this->contributionJoinTableColumn
= "contact_id";
304 elseif ($this->groupByTable
== 'civicrm_contribution_type') {
305 $this->contributionJoinTableColumn
= "contribution_type_id";
307 elseif ($this->groupByTable
== 'civicrm_contribution') {
308 $this->contributionJoinTableColumn
= $this->groupByFieldName
;
310 elseif ($this->groupByTable
== 'civicrm_address') {
311 $this->contributionJoinTableColumn
= "contact_id";
313 elseif ($this->groupByTable
== 'civicrm_financial_type') {
314 $this->contributionJoinTableColumn
= 'financial_type_id';
325 public function from() {
326 $this->buildTempTables();
327 $fromCol = $this->groupByFieldName
;
329 $from = "$this->groupByTable $this->groupByTableAlias";
331 if ($this->groupByTable
== 'civicrm_contact') {
333 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']} ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id
334 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
335 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND {$this->_aliases['civicrm_email']}.is_primary = 1
336 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
337 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
340 elseif ($this->groupByTable
== 'civicrm_address') {
342 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']} ON {$this->_aliases['civicrm_address']}.contact_id = {$this->_aliases['civicrm_contact']}.id";
343 $this->groupByTableAlias
= $this->_aliases
['civicrm_contact'];
349 LEFT JOIN $this->tempTableRepeat1 {$this->_aliases['civicrm_contribution']}1
350 ON {$this->groupByTableAlias}.$fromCol = {$this->_aliases['civicrm_contribution']}1
351 .{$this->contributionJoinTableColumn}
352 LEFT JOIN $this->tempTableRepeat2 {$this->_aliases['civicrm_contribution']}2
353 ON {$this->groupByTableAlias}.$fromCol = {$this->_aliases['civicrm_contribution']}2.{$this->contributionJoinTableColumn}";
355 //Join temp table if report is filtered by group. This is specific to 'notin' operator and covered in unit test(ref dev/core#212)
356 if (!empty($this->_params
['gid_op']) && $this->_params
['gid_op'] == 'notin') {
357 $this->joinGroupTempTable('civicrm_contact', 'id', $this->_aliases
['civicrm_contact']);
362 * @param string $replaceAliasWith
364 * @return mixed|string
366 public function fromContribution($replaceAliasWith = 'contribution1') {
367 $this->setFromBase('civicrm_contribution', 'contact_id', $replaceAliasWith);
369 $temp = $this->_aliases
['civicrm_contribution'];
370 $this->_aliases
['civicrm_contribution'] = $replaceAliasWith;
371 $from = $this->_from
;
372 $this->_aliases
['civicrm_contribution'] = $temp;
378 * @param string $replaceAliasWith
380 * @return mixed|string
382 public function whereContribution($replaceAliasWith = 'contribution1') {
384 "is_test" => "{$this->_aliases['civicrm_contribution']}.is_test = 0",
385 "is_template" => "{$this->_aliases['civicrm_contribution']}.is_template = 0",
388 foreach ($this->_columns
['civicrm_contribution']['filters'] as $fieldName => $field) {
390 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
391 $relative = $this->_params
["{$fieldName}_relative"] ??
NULL;
392 $from = $this->_params
["{$fieldName}_from"] ??
NULL;
393 $to = $this->_params
["{$fieldName}_to"] ??
NULL;
395 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type']);
398 $op = $this->_params
["{$fieldName}_op"] ??
NULL;
400 $clause = $this->whereClause($field,
402 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
403 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
404 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
408 if (!empty($clause)) {
409 $clauses[$fieldName] = $clause;
413 if (!$this->_amountClauseWithAND
) {
414 $amountClauseWithAND = [];
415 if (!empty($clauses['total_amount1'])) {
416 $amountClauseWithAND[] = str_replace("{$this->_aliases['civicrm_contribution']}.total_amount",
417 "{$this->_aliases['civicrm_contribution']}1.total_amount_sum", $clauses['total_amount1']);
419 if (!empty($clauses['total_amount2'])) {
420 $amountClauseWithAND[] = str_replace("{$this->_aliases['civicrm_contribution']}.total_amount",
421 "{$this->_aliases['civicrm_contribution']}2.total_amount_sum", $clauses['total_amount2']);
423 $this->_amountClauseWithAND
= !empty($amountClauseWithAND) ?
implode(' AND ', $amountClauseWithAND) : NULL;
426 if ($replaceAliasWith == 'contribution1') {
427 unset($clauses['receive_date2'], $clauses['total_amount2']);
430 unset($clauses['receive_date1'], $clauses['total_amount1']);
433 $whereClause = !empty($clauses) ?
"WHERE " . implode(' AND ', $clauses) : '';
435 if ($replaceAliasWith) {
436 $whereClause = str_replace($this->_aliases
['civicrm_contribution'], $replaceAliasWith, $whereClause);
442 public function where() {
443 if (!$this->_amountClauseWithAND
) {
444 $this->_amountClauseWithAND
445 = "!({$this->_aliases['civicrm_contribution']}1.total_amount_count IS NULL AND {$this->_aliases['civicrm_contribution']}2.total_amount_count IS NULL)";
447 $clauses = array("atleast_one_amount" => $this->_amountClauseWithAND
);
449 foreach ($this->_columns
as $tableName => $table) {
450 if (array_key_exists('filters', $table) &&
451 $tableName != 'civicrm_contribution'
453 foreach ($table['filters'] as $fieldName => $field) {
455 $op = $this->_params
["{$fieldName}_op"] ??
NULL;
457 $clause = $this->whereClause($field,
459 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
460 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
461 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
464 if (!empty($clause)) {
465 $clauses[$fieldName] = $clause;
471 $this->_where
= !empty($clauses) ?
"WHERE " . implode(' AND ', $clauses) : '';
475 * @param array $fields
476 * @param array $files
477 * @param CRM_Core_Form $self
481 public static function formRule($fields, $files, $self) {
483 $errors = $checkDate = $errorCount = [];
500 'supplemental_address_1',
501 'supplemental_address_2',
502 'supplemental_address_3',
507 'postal_code_suffix',
514 'postal_greeting_display',
515 'email_greeting_display',
522 'external_identifier',
529 'preferred_language',
531 'country_id' => array('country_id'),
532 'state_province_id' => array('country_id', 'state_province_id'),
533 'contribution_source' => array('contribution_source'),
534 'financial_type' => array('financial_type'),
538 'id' => ts('Contact'),
539 'exposed_id' => ts('Contact'),
540 'country_id' => ts('Country'),
541 'state_province_id' => ts('State/Province'),
542 'contribution_source' => ts('Contribution Source'),
543 'financial_type' => ts('Financial Type'),
544 'sort_name' => ts('Contact Name'),
545 'email' => ts('Email'),
546 'phone' => ts('Phone'),
549 if (empty($fields['group_bys'])) {
550 $errors['fields'] = ts('Please select at least one Group by field.');
552 elseif ((array_key_exists('contribution_source', $fields['group_bys']) ||
553 array_key_exists('contribution_type', $fields['group_bys'])
555 (count($fields['group_bys']) > 1)
557 $errors['fields'] = ts('You can not use other Group by with Financial type or Contribution source.');
560 foreach ($fields['fields'] as $fld_id => $value) {
561 if (!($fld_id == 'total_amount1') && !($fld_id == 'total_amount2') && !(substr($fld_id, 0, 7) === "custom_")) {
564 foreach ($fields['group_bys'] as $grp_id => $val) {
565 $validFields = $rules[$grp_id];
566 if (in_array($fld_id, $validFields)) {
570 $invlidGroups[] = $idMapping[$grp_id];
574 $erorrGrps = implode(',', $invlidGroups);
575 $tempErrors[] = ts("Do not select field %1 with Group by %2.", array(
576 1 => $idMapping[$fld_id],
582 if (!empty($tempErrors)) {
583 $errors['fields'] = implode("<br/>", $tempErrors);
587 if (!empty($fields['gid_value']) && !empty($fields['group_bys'])) {
588 if (!array_key_exists('id', $fields['group_bys'])) {
589 $errors['gid_value'] = ts("Filter with Group only allow with group by Contact");
593 if ($fields['receive_date1_relative'] == '0') {
594 $checkDate['receive_date1']['receive_date1_from'] = $fields['receive_date1_from'];
595 $checkDate['receive_date1']['receive_date1_to'] = $fields['receive_date1_to'];
598 if ($fields['receive_date2_relative'] == '0') {
599 $checkDate['receive_date2']['receive_date2_from'] = $fields['receive_date2_from'];
600 $checkDate['receive_date2']['receive_date2_to'] = $fields['receive_date2_to'];
603 foreach ($checkDate as $date_range => $range_data) {
604 foreach ($range_data as $key => $value) {
605 if (CRM_Utils_Date
::isDate($value)) {
606 $errorCount[$date_range][$key]['valid'] = 'true';
607 $errorCount[$date_range][$key]['is_empty'] = 'false';
610 $errorCount[$date_range][$key]['valid'] = 'false';
611 $errorCount[$date_range][$key]['is_empty'] = 'true';
612 if (is_array($value)) {
613 foreach ($value as $v) {
615 $errorCount[$date_range][$key]['is_empty'] = 'false';
619 elseif (!isset($value)) {
620 $errorCount[$date_range][$key]['is_empty'] = 'false';
626 $errorText = ts("Select valid date range");
627 foreach ($errorCount as $date_range => $error_data) {
629 if (($error_data[$date_range . '_from']['valid'] == 'false') &&
630 ($error_data[$date_range . '_to']['valid'] == 'false')
633 if (($error_data[$date_range . '_from']['is_empty'] == 'true') &&
634 ($error_data[$date_range . '_to']['is_empty'] == 'true')
636 $errors[$date_range . '_relative'] = $errorText;
639 if ($error_data[$date_range . '_from']['is_empty'] == 'false') {
640 $errors[$date_range . '_from'] = $errorText;
643 if ($error_data[$date_range . '_to']['is_empty'] == 'false') {
644 $errors[$date_range . '_to'] = $errorText;
647 elseif (($error_data[$date_range . '_from']['valid'] == 'true') &&
648 ($error_data[$date_range . '_to']['valid'] == 'false')
650 if ($error_data[$date_range . '_to']['is_empty'] == 'false') {
651 $errors[$date_range . '_to'] = $errorText;
654 elseif (($error_data[$date_range . '_from']['valid'] == 'false') &&
655 ($error_data[$date_range . '_to']['valid'] == 'true')
657 if ($error_data[$date_range . '_from']['is_empty'] == 'false') {
658 $errors[$date_range . '_from'] = $errorText;
671 public function statistics(&$rows) {
672 $statistics = parent
::statistics($rows);
673 $sql = "{$this->_select} {$this->_from} {$this->_where}";
674 $dao = $this->executeReportQuery($sql);
675 //store contributions in array 'contact_sums' for comparison
677 while ($dao->fetch()) {
678 $contact_sums[$dao->contact_civireport_id
] = array(
679 'contribution1_total_amount_sum' => $dao->contribution1_total_amount_sum
,
680 'contribution2_total_amount_sum' => $dao->contribution2_total_amount_sum
,
684 $total_distinct_contacts = count($contact_sums);
691 foreach ($contact_sums as $uid => $row) {
692 if ($row['contribution1_total_amount_sum'] &&
693 $row['contribution2_total_amount_sum']
695 $change = ($row['contribution1_total_amount_sum'] -
696 $row['contribution2_total_amount_sum']);
700 elseif ($change > 0) {
703 elseif ($change < 0) {
707 elseif ($row['contribution1_total_amount_sum']) {
710 elseif ($row['contribution2_total_amount_sum']) {
715 //calculate percentages from numbers
716 if (!empty($total_distinct_contacts)) {
717 $maintained = ($maintained / $total_distinct_contacts) * 100;
718 $upgraded = ($upgraded / $total_distinct_contacts) * 100;
719 $downgraded = ($downgraded / $total_distinct_contacts) * 100;
720 $new = ($new / $total_distinct_contacts) * 100;
721 $lapsed = ($lapsed / $total_distinct_contacts) * 100;
723 //display percentages for new, lapsed, upgraded, downgraded, and maintained contributors
724 $statistics['counts']['count_new'] = array(
726 'title' => ts('% New Donors'),
728 $statistics['counts']['count_lapsed'] = array(
730 'title' => ts('% Lapsed Donors'),
732 $statistics['counts']['count_upgraded'] = array(
733 'value' => $upgraded,
734 'title' => ts('% Upgraded Donors'),
736 $statistics['counts']['count_downgraded'] = array(
737 'value' => $downgraded,
738 'title' => ts('% Downgraded Donors'),
740 $statistics['counts']['count_maintained'] = array(
741 'value' => $maintained,
742 'title' => ts('% Maintained Donors'),
746 SELECT COUNT({$this->_aliases['civicrm_contribution']}1.total_amount_count ) as count,
747 SUM({$this->_aliases['civicrm_contribution']}1.total_amount_sum ) as amount,
748 ROUND(AVG({$this->_aliases['civicrm_contribution']}1.total_amount_sum), 2) as avg,
749 COUNT({$this->_aliases['civicrm_contribution']}2.total_amount_count ) as count2,
750 SUM({$this->_aliases['civicrm_contribution']}2.total_amount_sum ) as amount2,
751 ROUND(AVG({$this->_aliases['civicrm_contribution']}2.total_amount_sum), 2) as avg2,
753 $sql = "{$select} {$this->_from} {$this->_where}
756 $dao = $this->executeReportQuery($sql);
758 $amount = $average = $amount2 = $average2 = [];
759 $count = $count2 = 0;
760 while ($dao->fetch()) {
763 = CRM_Utils_Money
::format($dao->amount
, $dao->currency
) . "(" .
765 $average[] = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
768 $count +
= $dao->count
;
771 = CRM_Utils_Money
::format($dao->amount2
, $dao->currency
) . "(" .
773 $average2[] = CRM_Utils_Money
::format($dao->avg2
, $dao->currency
);
775 $count2 +
= $dao->count2
;
778 $statistics['counts']['range_one_title'] = array('title' => ts('Initial Date Range:'));
779 $statistics['counts']['amount'] = array(
780 'value' => implode(', ', $amount),
781 'title' => ts('Total Amount'),
782 'type' => CRM_Utils_Type
::T_STRING
,
784 $statistics['counts']['count'] = array(
786 'title' => ts('Total Donations'),
788 $statistics['counts']['avg'] = array(
789 'value' => implode(', ', $average),
790 'title' => ts('Average'),
791 'type' => CRM_Utils_Type
::T_STRING
,
793 $statistics['counts']['range_two_title'] = array(
794 'title' => ts('Second Date Range:'),
796 $statistics['counts']['amount2'] = array(
797 'value' => implode(', ', $amount2),
798 'title' => ts('Total Amount'),
799 'type' => CRM_Utils_Type
::T_STRING
,
801 $statistics['counts']['count2'] = array(
803 'title' => ts('Total Donations'),
805 $statistics['counts']['avg2'] = array(
806 'value' => implode(', ', $average2),
807 'title' => ts('Average'),
808 'type' => CRM_Utils_Type
::T_STRING
,
814 public function postProcess() {
815 $this->beginPostProcess();
817 $this->buildGroupTempTable();
820 $this->customDataFrom();
827 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_orderBy} {$this->_limit}";
828 $dao = $this->executeReportQuery($sql);
830 while ($dao->fetch()) {
831 foreach ($this->_columnHeaders
as $key => $value) {
832 $rows[$count][$key] = $dao->$key;
837 // FIXME: calculate % using query
838 foreach ($rows as $uid => $row) {
839 if ($row['contribution1_total_amount_sum'] &&
840 $row['contribution2_total_amount_sum']
842 $rows[$uid]['change'] = number_format((($row['contribution2_total_amount_sum'] -
843 $row['contribution1_total_amount_sum']
845 ($row['contribution1_total_amount_sum']), 2
848 elseif ($row['contribution1_total_amount_sum']) {
849 $rows[$uid]['change'] = ts('Skipped Donation');
851 elseif ($row['contribution2_total_amount_sum']) {
852 $rows[$uid]['change'] = ts('New Donor');
854 if ($row['contribution1_total_amount_count']) {
855 $rows[$uid]['contribution1_total_amount_sum']
856 = $row['contribution1_total_amount_sum'] .
857 " ({$row['contribution1_total_amount_count']})";
859 if ($row['contribution2_total_amount_count']) {
860 $rows[$uid]['contribution2_total_amount_sum']
861 = $row['contribution2_total_amount_sum'] .
862 " ({$row['contribution2_total_amount_count']})";
865 $this->_columnHeaders
['change'] = array(
866 'title' => ts('% Change'),
867 'type' => CRM_Utils_Type
::T_INT
,
871 list($from1, $to1) = $this->getFromTo(CRM_Utils_Array
::value("receive_date1_relative", $this->_params
),
872 CRM_Utils_Array
::value("receive_date1_from", $this->_params
),
873 CRM_Utils_Array
::value("receive_date1_to", $this->_params
)
875 $from1 = CRM_Utils_Date
::customFormat($from1, NULL, array('d'));
876 $to1 = CRM_Utils_Date
::customFormat($to1, NULL, array('d'));
878 list($from2, $to2) = $this->getFromTo(CRM_Utils_Array
::value("receive_date2_relative", $this->_params
),
879 CRM_Utils_Array
::value("receive_date2_from", $this->_params
),
880 CRM_Utils_Array
::value("receive_date2_to", $this->_params
)
882 $from2 = CRM_Utils_Date
::customFormat($from2, NULL, array('d'));
883 $to2 = CRM_Utils_Date
::customFormat($to2, NULL, array('d'));
885 $this->_columnHeaders
['contribution1_total_amount_sum']['title'] = "$from1 - $to1";
886 $this->_columnHeaders
['contribution2_total_amount_sum']['title'] = "$from2 - $to2";
887 unset($this->_columnHeaders
['contribution1_total_amount_count'],
888 $this->_columnHeaders
['contribution2_total_amount_count']
891 $this->formatDisplay($rows);
893 // assign variables to templates
894 $this->doTemplateAssignment($rows);
896 $this->endPostProcess($rows);
900 * Alter display of rows.
902 * Iterate through the rows retrieved via SQL and make changes for display purposes,
903 * such as rendering contacts as links.
906 * Rows generated by SQL, with an array for each row.
908 public function alterDisplay(&$rows) {
909 list($from1, $to1) = $this->getFromTo(CRM_Utils_Array
::value("receive_date1_relative", $this->_params
),
910 CRM_Utils_Array
::value("receive_date1_from", $this->_params
),
911 CRM_Utils_Array
::value("receive_date1_to", $this->_params
)
913 list($from2, $to2) = $this->getFromTo(CRM_Utils_Array
::value("receive_date2_relative", $this->_params
),
914 CRM_Utils_Array
::value("receive_date2_from", $this->_params
),
915 CRM_Utils_Array
::value("receive_date2_to", $this->_params
)
920 $dateUrl .= "receive_date1_from={$from1}&";
923 $dateUrl .= "receive_date1_to={$to1}&";
926 $dateUrl .= "receive_date2_from={$from2}&";
929 $dateUrl .= "receive_date2_to={$to2}&";
932 foreach ($rows as $rowNum => $row) {
934 if (array_key_exists('address_civireport_country_id', $row)) {
935 if ($value = $row['address_civireport_country_id']) {
936 $rows[$rowNum]['address_civireport_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
938 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
940 "country_id_op=in&country_id_value={$value}&" .
942 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
945 $rows[$rowNum]['address_civireport_country_id_link'] = $url;
946 $rows[$rowNum]['address_civireport_country_id_hover'] = ts("View contributions for this Country.");
950 // handle state province
951 if (array_key_exists('address_civireport_state_province_id', $row)) {
952 if ($value = $row['address_civireport_state_province_id']) {
953 $rows[$rowNum]['address_civireport_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
955 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
957 "state_province_id_op=in&state_province_id_value={$value}&" .
959 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
962 $rows[$rowNum]['address_civireport_state_province_id_link'] = $url;
963 $rows[$rowNum]['address_civireport_state_province_id_hover'] = ts("View repeatDetails for this state.");
967 // convert display name to links
968 if (array_key_exists('contact_civireport_sort_name', $row) &&
969 array_key_exists('contact_civireport_id', $row)
971 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
972 'reset=1&force=1&id_op=eq&id_value=' . $row['contact_civireport_id'],
973 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
976 $rows[$rowNum]['contact_civireport_sort_name_link'] = $url;
977 $rows[$rowNum]['contact_civireport_sort_name_hover'] = ts("View Contribution details for this contact");
984 * Build the temp tables for comparison.
986 protected function buildTempTables() {
987 $this->setGroupByInformation();
988 $create = $subSelect1 = $subSelect2 = NULL;
989 if ($this->tempTableRepeat1
) {
993 if ($this->groupByTable
== 'civicrm_financial_type') {
994 $subSelect1 = 'contribution1.contact_id,';
995 $subSelect2 = 'contribution2.contact_id,';
996 $create = 'contact_id int unsigned,';
999 $subWhere = $this->whereContribution();
1000 $from = $this->fromContribution();
1001 $subContributionQuery1 = "
1002 SELECT {$subSelect1} contribution1.{$this->contributionJoinTableColumn},
1003 sum( contribution1.total_amount ) AS total_amount_sum,
1004 count( * ) AS total_amount_count
1007 GROUP BY contribution1.{$this->contributionJoinTableColumn}";
1009 $subWhere = $this->whereContribution('contribution2');
1010 $from = $this->fromContribution('contribution2');
1011 $subContributionQuery2 = "
1012 SELECT {$subSelect2} contribution2.{$this->contributionJoinTableColumn},
1013 sum( contribution2.total_amount ) AS total_amount_sum,
1014 count( * ) AS total_amount_count,
1018 GROUP BY contribution2.{$this->contributionJoinTableColumn}, currency";
1019 $this->tempTableRepeat1
= $this->createTemporaryTable('tempTableRepeat1', "
1021 {$this->contributionJoinTableColumn} int unsigned,
1022 total_amount_sum decimal(20,2),
1023 total_amount_count int
1025 $this->executeReportQuery("INSERT INTO $this->tempTableRepeat1 {$subContributionQuery1}");
1027 $this->executeReportQuery("
1028 ALTER TABLE $this->tempTableRepeat1 ADD INDEX ({$this->contributionJoinTableColumn})
1031 $this->tempTableRepeat2
= $this->createTemporaryTable('tempTableRepeat2', "
1033 {$this->contributionJoinTableColumn} int unsigned,
1034 total_amount_sum decimal(20,2),
1035 total_amount_count int,
1038 $sql = "INSERT INTO $this->tempTableRepeat2 {$subContributionQuery2}";
1039 $this->executeReportQuery($sql);
1041 $this->executeReportQuery("
1042 ALTER TABLE $this->tempTableRepeat2 ADD INDEX ({$this->contributionJoinTableColumn})