Merge pull request #3925 from eileenmcnaughton/CRM-15168
[civicrm-core.git] / CRM / Report / Form / Contribute / Repeat.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.5 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27 */
28
29 /**
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2014
33 * $Id$
34 *
35 */
36 class CRM_Report_Form_Contribute_Repeat extends CRM_Report_Form {
37 protected $_amountClauseWithAND = NULL;
38
39 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
40
41 /**
42 *
43 */
44 /**
45 *
46 */
47 function __construct() {
48 $this->_columns = array(
49 'civicrm_contact' =>
50 array(
51 'dao' => 'CRM_Contact_DAO_Contact',
52 'grouping' => 'contact-fields',
53 'fields' =>
54 array(
55 'sort_name' =>
56 array(
57 'title' => ts('Contact Name'),
58 'no_repeat' => TRUE,
59 'default' => TRUE,
60 ),
61 'display_name' =>
62 array(
63 'title' => ts('Display Name'),
64 'no_repeat' => TRUE,
65 ),
66 'addressee_display' =>
67 array(
68 'title' => ts('Addressee Name'),
69 'no_repeat' => TRUE,
70 ),
71 'id' =>
72 array(
73 'no_display' => TRUE,
74 'required' => TRUE,
75 ),
76 'contact_type' =>
77 array(
78 'title' => ts('Contact Type'),
79 'no_repeat' => TRUE,
80 ),
81 'contact_sub_type' =>
82 array(
83 'title' => ts('Contact SubType'),
84 'no_repeat' => TRUE,
85 ),
86 ),
87 'filters' =>
88 array(
89 'percentage_change' =>
90 array(
91 'title' => ts('Percentage Change'),
92 'type' => CRM_Utils_Type::T_INT,
93 'operatorType' => CRM_Report_Form::OP_INT,
94 'name' => 'percentage_change',
95 'dbAlias' => '( ( contribution_civireport2.total_amount_sum - contribution_civireport1.total_amount_sum ) * 100 / contribution_civireport1.total_amount_sum )',
96 ),
97 ),
98 'group_bys' =>
99 array(
100 'id' =>
101 array(
102 'title' => ts('Contact'),
103 'default' => TRUE,
104 ),
105 ),
106 ),
107 'civicrm_email' =>
108 array(
109 'dao' => 'CRM_Core_DAO_Email',
110 'fields' =>
111 array(
112 'email' =>
113 array(
114 'title' => ts('Email'),
115 'no_repeat' => TRUE,
116 ),
117 ),
118 'grouping' => 'contact-fields',
119 ),
120 'civicrm_phone' =>
121 array(
122 'dao' => 'CRM_Core_DAO_Phone',
123 'fields' =>
124 array(
125 'phone' =>
126 array(
127 'title' => ts('Phone'),
128 'no_repeat' => TRUE,
129 ),
130 ),
131 'grouping' => 'contact-fields',
132 ),
133 'civicrm_address' =>
134 array(
135 'dao' => 'CRM_Core_DAO_Address',
136 'grouping' => 'contact-fields',
137 'fields' =>
138 array(
139 'street_address' => array('title' => ts('Street Address')),
140 'supplemental_address_1' => array('title' => ts('Supplemental Address 1')),
141 'city' => array('title' => ts('City')),
142 'country_id' => array('title' => ts('Country')),
143 'state_province_id' => array('title' => ts('State/Province')),
144 'postal_code' => array('title' => ts('Postal Code')),
145 ),
146 'group_bys' =>
147 array(
148 'country_id' => array('title' => ts('Country')),
149 'state_province_id' => array('title' => ts('State/Province'),
150 ),
151 ),
152 ),
153 'civicrm_financial_type' =>
154 array(
155 'dao' => 'CRM_Financial_DAO_FinancialType',
156 'fields' => array('financial_type' => array('title' => ts('Financial Type'))),
157 'grouping' => 'contri-fields',
158 'group_bys' =>
159 array('financial_type' =>
160 array(
161 'name' => 'id',
162 'title' => ts('Financial Type'),
163 ),
164 ),
165 ),
166 'civicrm_contribution' =>
167 array(
168 'dao' => 'CRM_Contribute_DAO_Contribution',
169 'fields' =>
170 array(
171 'contribution_source' => NULL,
172 'total_amount1' =>
173 array(
174 'name' => 'total_amount',
175 'alias' => 'contribution1',
176 'title' => ts('Range One Stat'),
177 'type' => CRM_Utils_Type::T_MONEY,
178 'default' => TRUE,
179 'required' => TRUE,
180 'clause' => '
181 contribution_civireport1.total_amount_count as contribution1_total_amount_count,
182 contribution_civireport1.total_amount_sum as contribution1_total_amount_sum',
183 ),
184 'total_amount2' =>
185 array(
186 'name' => 'total_amount',
187 'alias' => 'contribution2',
188 'title' => ts('Range Two Stat'),
189 'type' => CRM_Utils_Type::T_MONEY,
190 'default' => TRUE,
191 'required' => TRUE,
192 'clause' => '
193 contribution_civireport2.total_amount_count as contribution2_total_amount_count,
194 contribution_civireport2.total_amount_sum as contribution2_total_amount_sum',
195 ),
196 ),
197 'grouping' => 'contri-fields',
198 'filters' =>
199 array(
200 'receive_date1' =>
201 array(
202 'title' => ts('Initial Date Range'),
203 'default' => 'previous.year',
204 'type' => CRM_Utils_Type::T_DATE,
205 'operatorType' => CRM_Report_Form::OP_DATE,
206 'name' => 'receive_date',
207 ),
208 'receive_date2' =>
209 array(
210 'title' => ts('Second Date Range'),
211 'default' => 'this.year',
212 'type' => CRM_Utils_Type::T_DATE,
213 'operatorType' => CRM_Report_Form::OP_DATE,
214 'name' => 'receive_date',
215 ),
216 'total_amount1' =>
217 array(
218 'title' => ts('Range One Amount'),
219 'type' => CRM_Utils_Type::T_INT,
220 'operatorType' => CRM_Report_Form::OP_INT,
221 'name' => 'total_amount',
222 ),
223 'total_amount2' =>
224 array(
225 'title' => ts('Range Two Amount'),
226 'type' => CRM_Utils_Type::T_INT,
227 'operatorType' => CRM_Report_Form::OP_INT,
228 'name' => 'total_amount',
229 ),
230 'financial_type_id' =>
231 array(
232 'title' => ts('Financial Type'),
233 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
234 'options' => CRM_Contribute_PseudoConstant::financialType(),
235 ),
236 'contribution_status_id' =>
237 array(
238 'title' => ts('Contribution Status'),
239 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
240 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
241 'default' => array('1'),
242 ),
243 ),
244 'group_bys' => array('contribution_source' => NULL),
245 ),
246 );
247
248 $this->_groupFilter = TRUE;
249 $this->_tagFilter = TRUE;
250
251 parent::__construct();
252 }
253
254 function preProcess() {
255 parent::preProcess();
256 }
257
258 /**
259 * @param bool $freeze
260 *
261 * @return array
262 */
263 function setDefaultValues($freeze = TRUE) {
264 return parent::setDefaultValues($freeze);
265 }
266
267 function select() {
268 $select = array();
269 $append = NULL;
270 // since contact fields not related to financial type
271 if (array_key_exists('financial_type', $this->_params['group_bys']) ||
272 array_key_exists('contribution_source', $this->_params['group_bys'])
273 ) {
274 unset($this->_columns['civicrm_contact']['fields']['id']);
275 }
276
277 foreach ($this->_columns as $tableName => $table) {
278 if (array_key_exists('fields', $table)) {
279 foreach ($table['fields'] as $fieldName => $field) {
280 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
281 if (isset($field['clause'])) {
282 $select[] = $field['clause'];
283
284 // FIXME: dirty hack for setting columnHeaders
285 $this->_columnHeaders["{$field['alias']}_{$field['name']}_sum"]['type'] = CRM_Utils_Array::value('type', $field);
286 $this->_columnHeaders["{$field['alias']}_{$field['name']}_sum"]['title'] = $field['title'];
287 $this->_columnHeaders["{$field['alias']}_{$field['name']}_count"]['type'] = CRM_Utils_Array::value('type', $field);
288 $this->_columnHeaders["{$field['alias']}_{$field['name']}_count"]['title'] = $field['title'];
289 continue;
290 }
291
292 // only include statistics columns if set
293 $select[] = "{$field['dbAlias']} as {$field['alias']}_{$field['name']}";
294 $this->_columnHeaders["{$field['alias']}_{$field['name']}"]['type'] = CRM_Utils_Array::value('type', $field);
295 $this->_columnHeaders["{$field['alias']}_{$field['name']}"]['title'] = CRM_Utils_Array::value('title', $field);
296 if (!empty($field['no_display'])) {
297 $this->_columnHeaders["{$field['alias']}_{$field['name']}"]['no_display'] = TRUE;
298 }
299 }
300 }
301 }
302 }
303
304 $this->_select = "SELECT " . implode(', ', $select) . " ";
305 }
306
307 /**
308 * @param bool $tableCol
309 */
310 function groupBy($tableCol = FALSE) {
311 $this->_groupBy = "";
312 if (!empty($this->_params['group_bys']) && is_array($this->_params['group_bys'])) {
313 foreach ($this->_columns as $tableName => $table) {
314 if (array_key_exists('group_bys', $table)) {
315 foreach ($table['group_bys'] as $fieldName => $field) {
316 if (!empty($this->_params['group_bys'][$fieldName])) {
317 if ($tableCol) {
318 return array($tableName, $field['alias'], $field['name']);
319 }
320 else {
321 $this->_groupBy[] = "{$field['dbAlias']}";
322 }
323 }
324 }
325 }
326 }
327
328 $this->_groupBy = "GROUP BY " . implode(', ', $this->_groupBy);
329 }
330 }
331
332 function from() {
333 list($fromTable, $fromAlias, $fromCol) = $this->groupBy(TRUE);
334 $from = "$fromTable $fromAlias";
335
336 if ($fromTable == 'civicrm_contact') {
337 $contriCol = "contact_id";
338 $from .= "
339 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']} ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id
340 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
341 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND {$this->_aliases['civicrm_email']}.is_primary = 1
342 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
343 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
344
345 }
346 else if ($fromTable == 'civicrm_financial_type') {
347 $contriCol = "financial_type_id";
348 }
349 elseif ($fromTable == 'civicrm_contribution') {
350 $contriCol = $fromCol;
351 }
352 elseif ($fromTable == 'civicrm_address') {
353 $from .= "
354 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']} ON {$this->_aliases['civicrm_address']}.contact_id = {$this->_aliases['civicrm_contact']}.id";
355 $fromAlias = $this->_aliases['civicrm_contact'];
356 $fromCol = "id";
357 $contriCol = "contact_id";
358 }
359
360 $this->_from = "
361 FROM $from
362 LEFT JOIN civicrm_temp_civireport_repeat1 {$this->_aliases['civicrm_contribution']}1
363 ON $fromAlias.$fromCol = {$this->_aliases['civicrm_contribution']}1.$contriCol
364 LEFT JOIN civicrm_temp_civireport_repeat2 {$this->_aliases['civicrm_contribution']}2
365 ON $fromAlias.$fromCol = {$this->_aliases['civicrm_contribution']}2.$contriCol";
366 }
367
368 /**
369 * @param string $replaceAliasWith
370 *
371 * @return mixed|string
372 */
373 function whereContribution($replaceAliasWith = 'contribution1') {
374 $clauses = array("is_test" => "{$this->_aliases['civicrm_contribution']}.is_test = 0");
375
376 foreach ($this->_columns['civicrm_contribution']['filters'] as $fieldName => $field) {
377 $clause = NULL;
378 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
379 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
380 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
381 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
382
383 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type']);
384 }
385 else {
386 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
387 if ($op) {
388 $clause = $this->whereClause($field,
389 $op,
390 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
391 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
392 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
393 );
394 }
395 }
396 if (!empty($clause)) {
397 $clauses[$fieldName] = $clause;
398 }
399 }
400
401 if (!$this->_amountClauseWithAND) {
402 $amountClauseWithAND = array();
403 if (!empty($clauses['total_amount1'])) {
404 $amountClauseWithAND[] = str_replace("{$this->_aliases['civicrm_contribution']}.total_amount",
405 "{$this->_aliases['civicrm_contribution']}1.total_amount_sum", $clauses['total_amount1']);
406 }
407 if (!empty($clauses['total_amount2'])) {
408 $amountClauseWithAND[] = str_replace("{$this->_aliases['civicrm_contribution']}.total_amount",
409 "{$this->_aliases['civicrm_contribution']}2.total_amount_sum", $clauses['total_amount2']);
410 }
411 $this->_amountClauseWithAND = !empty($amountClauseWithAND) ? implode(' AND ', $amountClauseWithAND) : NULL;
412 }
413
414 if ($replaceAliasWith == 'contribution1') {
415 unset($clauses['receive_date2'], $clauses['total_amount2']);
416 }
417 else {
418 unset($clauses['receive_date1'], $clauses['total_amount1']);
419 }
420
421 $whereClause = !empty($clauses) ? "WHERE " . implode(' AND ', $clauses) : '';
422
423 if ($replaceAliasWith) {
424 $whereClause = str_replace($this->_aliases['civicrm_contribution'], $replaceAliasWith, $whereClause);
425 }
426
427 return $whereClause;
428 }
429
430 function where() {
431 if (!$this->_amountClauseWithAND) {
432 $this->_amountClauseWithAND =
433 "!({$this->_aliases['civicrm_contribution']}1.total_amount_count IS NULL AND {$this->_aliases['civicrm_contribution']}2.total_amount_count IS NULL)";
434 }
435 $clauses = array("atleast_one_amount" => $this->_amountClauseWithAND);
436
437 foreach ($this->_columns as $tableName => $table) {
438 if (array_key_exists('filters', $table) && $tableName != 'civicrm_contribution') {
439 foreach ($table['filters'] as $fieldName => $field) {
440 $clause = NULL;
441 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
442 if ($op) {
443 $clause = $this->whereClause($field,
444 $op,
445 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
446 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
447 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
448 );
449 }
450 if (!empty($clause)) {
451 $clauses[$fieldName] = $clause;
452 }
453 }
454 }
455 }
456
457 $this->_where = !empty($clauses) ? "WHERE " . implode(' AND ', $clauses) : '';
458 }
459
460 /**
461 * @param $fields
462 * @param $files
463 * @param $self
464 *
465 * @return array
466 */
467 function formRule($fields, $files, $self) {
468
469 $errors = $checkDate = $errorCount = array();
470
471 $rules = array(
472 'id' => array(
473 'sort_name',
474 'display_name',
475 'addressee_display',
476 'contact_type',
477 'contact_sub_type',
478 'email',
479 'phone',
480 'state_province_id',
481 'country_id',
482 'city',
483 'street_address',
484 'supplemental_address_1',
485 'postal_code',
486 ),
487 'country_id' => array('country_id'),
488 'state_province_id' => array('country_id', 'state_province_id'),
489 'contribution_source' => array('contribution_source'),
490 'financial_type' => array('financial_type'),
491 );
492
493 $idMapping = array(
494 'id' => ts('Contact'),
495 'country_id' => ts('Country'),
496 'state_province_id' => ts('State/Province'),
497 'contribution_source' => ts('Contribution Source'),
498 'financial_type' => ts('Financial Type'),
499 'sort_name' => ts('Contact Name'),
500 'email' => ts('Email'),
501 'phone' => ts('Phone'),
502 );
503
504 if (empty($fields['group_bys'])) {
505 $errors['fields'] = ts('Please select at least one Group by field.');
506 }
507 elseif ((array_key_exists('contribution_source', $fields['group_bys']) ||
508 array_key_exists('contribution_type', $fields['group_bys'])
509 ) &&
510 (count($fields['group_bys']) > 1)
511 ) {
512 $errors['fields'] = ts('You can not use other Group by with Financial type or Contribution source.');
513 }
514 else {
515 foreach ($fields['fields'] as $fld_id => $value) {
516 if (!($fld_id == 'total_amount1') && !($fld_id == 'total_amount2')) {
517 $found = FALSE;
518 $invlidGroups = array();
519 foreach ($fields['group_bys'] as $grp_id => $val) {
520 $validFields = $rules[$grp_id];
521 if (in_array($fld_id, $validFields)) {
522 $found = TRUE;
523 }
524 else {
525 $invlidGroups[] = $idMapping[$grp_id];
526 }
527 }
528 if (!$found) {
529 $erorrGrps = implode(',', $invlidGroups);
530 $tempErrors[] = ts("Do not select field %1 with Group by %2.", array(1 => $idMapping[$fld_id], 2 => $erorrGrps));
531 }
532 }
533 }
534 if (!empty($tempErrors)) {
535 $errors['fields'] = implode("<br>", $tempErrors);
536 }
537 }
538
539 if (!empty($fields['gid_value']) && !empty($fields['group_bys'])) {
540 if (!array_key_exists('id', $fields['group_bys'])) {
541 $errors['gid_value'] = ts("Filter with Group only allow with group by Contact");
542 }
543 }
544
545 if ($fields['receive_date1_relative'] == '0') {
546 $checkDate['receive_date1']['receive_date1_from'] = $fields['receive_date1_from'];
547 $checkDate['receive_date1']['receive_date1_to'] = $fields['receive_date1_to'];
548 }
549
550 if ($fields['receive_date2_relative'] == '0') {
551 $checkDate['receive_date2']['receive_date2_from'] = $fields['receive_date2_from'];
552 $checkDate['receive_date2']['receive_date2_to'] = $fields['receive_date2_to'];
553 }
554
555 foreach ($checkDate as $date_range => $range_data) {
556 foreach ($range_data as $key => $value) {
557 if (CRM_Utils_Date::isDate($value)) {
558 $errorCount[$date_range][$key]['valid'] = 'true';
559 $errorCount[$date_range][$key]['is_empty'] = 'false';
560 }
561 else {
562 $errorCount[$date_range][$key]['valid'] = 'false';
563 $errorCount[$date_range][$key]['is_empty'] = 'true';
564 if (is_array($value)) {
565 foreach ($value as $v) {
566 if ($v) {
567 $errorCount[$date_range][$key]['is_empty'] = 'false';
568 }
569 }
570 }
571 elseif (!isset($value)) {
572 $errorCount[$date_range][$key]['is_empty'] = 'false';
573 }
574 }
575 }
576 }
577
578 $errorText = ts("Select valid date range");
579 foreach ($errorCount as $date_range => $error_data) {
580
581 if (($error_data[$date_range . '_from']['valid'] == 'false') &&
582 ($error_data[$date_range . '_to']['valid'] == 'false')
583 ) {
584
585 if (($error_data[$date_range . '_from']['is_empty'] == 'true') &&
586 ($error_data[$date_range . '_to']['is_empty'] == 'true')
587 ) {
588 $errors[$date_range . '_relative'] = $errorText;
589 }
590
591 if ($error_data[$date_range . '_from']['is_empty'] == 'false') {
592 $errors[$date_range . '_from'] = $errorText;
593 }
594
595 if ($error_data[$date_range . '_to']['is_empty'] == 'false') {
596 $errors[$date_range . '_to'] = $errorText;
597 }
598 }
599 elseif (($error_data[$date_range . '_from']['valid'] == 'true') &&
600 ($error_data[$date_range . '_to']['valid'] == 'false')
601 ) {
602 if ($error_data[$date_range . '_to']['is_empty'] == 'false') {
603 $errors[$date_range . '_to'] = $errorText;
604 }
605 }
606 elseif (($error_data[$date_range . '_from']['valid'] == 'false') &&
607 ($error_data[$date_range . '_to']['valid'] == 'true')
608 ) {
609 if ($error_data[$date_range . '_from']['is_empty'] == 'false') {
610 $errors[$date_range . '_from'] = $errorText;
611 }
612 }
613 }
614
615 return $errors;
616 }
617
618 /**
619 * @param $rows
620 *
621 * @return array
622 */
623 function statistics(&$rows) {
624 $statistics = parent::statistics($rows);
625
626 //fetch contributions for both date ranges from pre-existing temp tables
627 $sql = "
628 CREATE TEMPORARY TABLE civicrm_temp_civireport_repeat3
629 SELECT contact_id FROM civicrm_temp_civireport_repeat1 UNION SELECT contact_id FROM civicrm_temp_civireport_repeat2;";
630 $dao = CRM_Core_DAO::executeQuery($sql);
631
632 $sql = "
633 SELECT civicrm_temp_civireport_repeat3.contact_id,
634 civicrm_temp_civireport_repeat1.total_amount_sum as contribution1_total_amount_sum,
635 civicrm_temp_civireport_repeat2.total_amount_sum as contribution2_total_amount_sum
636 FROM civicrm_temp_civireport_repeat3
637 LEFT JOIN civicrm_temp_civireport_repeat1
638 ON civicrm_temp_civireport_repeat3.contact_id = civicrm_temp_civireport_repeat1.contact_id
639 LEFT JOIN civicrm_temp_civireport_repeat2
640 ON civicrm_temp_civireport_repeat3.contact_id = civicrm_temp_civireport_repeat2.contact_id";
641 $dao = CRM_Core_DAO::executeQuery($sql);
642
643 //store contributions in array 'contact_sums' for comparison
644 $contact_sums = array();
645 while ($dao->fetch()) {
646 $contact_sums[$dao->contact_id] =
647 array(
648 'contribution1_total_amount_sum' => $dao->contribution1_total_amount_sum,
649 'contribution2_total_amount_sum' => $dao->contribution2_total_amount_sum
650 );
651 }
652
653 $total_distinct_contacts = count($contact_sums);
654 $number_maintained = 0;
655 $number_upgraded = 0;
656 $number_downgraded = 0;
657 $number_new = 0;
658 $number_lapsed = 0;
659
660 foreach ($contact_sums as $uid => $row) {
661 if ($row['contribution1_total_amount_sum'] && $row['contribution2_total_amount_sum']) {
662 $change = ($row['contribution1_total_amount_sum'] - $row['contribution2_total_amount_sum']);
663 if($change == 0)
664 $number_maintained += 1;
665 elseif($change > 0)
666 $number_upgraded += 1;
667 elseif($change < 0)
668 $number_downgraded += 1;
669 }
670 elseif ($row['contribution1_total_amount_sum']) {
671 $number_new +=1;
672 }
673 elseif ($row['contribution2_total_amount_sum']) {
674 $number_lapsed +=1;
675 }
676 }
677
678 //calculate percentages from numbers
679 $percent_maintained = ($number_maintained / $total_distinct_contacts) * 100;
680 $percent_upgraded = ($number_upgraded / $total_distinct_contacts) * 100;
681 $percent_downgraded = ($number_downgraded / $total_distinct_contacts) * 100;
682 $percent_new = ($number_new / $total_distinct_contacts) * 100;
683 $percent_lapsed = ($number_lapsed / $total_distinct_contacts) * 100;
684
685 //display percentages for new, lapsed, upgraded, downgraded, and maintained contributors
686 $statistics['counts']['count_new'] = array(
687 'value' => $percent_new,
688 'title' => '% New Donors',
689 );
690 $statistics['counts']['count_lapsed'] = array(
691 'value' => $percent_lapsed,
692 'title' => '% Lapsed Donors',
693 );
694 $statistics['counts']['count_upgraded'] = array(
695 'value' => $percent_upgraded,
696 'title' => '% Upgraded Donors',
697 );
698 $statistics['counts']['count_downgraded'] = array(
699 'value' => $percent_downgraded,
700 'title' => '% Downgraded Donors',
701 );
702 $statistics['counts']['count_maintained'] = array(
703 'value' => $percent_maintained,
704 'title' => '% Maintained Donors',
705 );
706
707 $select = "
708 SELECT COUNT({$this->_aliases['civicrm_contribution']}1.total_amount_count ) as count,
709 SUM({$this->_aliases['civicrm_contribution']}1.total_amount_sum ) as amount,
710 ROUND(AVG({$this->_aliases['civicrm_contribution']}1.total_amount_sum), 2) as avg,
711 COUNT({$this->_aliases['civicrm_contribution']}2.total_amount_count ) as count2,
712 SUM({$this->_aliases['civicrm_contribution']}2.total_amount_sum ) as amount2,
713 ROUND(AVG({$this->_aliases['civicrm_contribution']}2.total_amount_sum), 2) as avg2,
714 currency";
715 $sql = "{$select} {$this->_from} {$this->_where}
716 GROUP BY currency
717 ";
718 $dao = CRM_Core_DAO::executeQuery($sql);
719
720 $amount = $average = $amount2 = $average2 = array();
721 $count = $count2 = 0;
722 while ($dao->fetch()) {
723 if ($dao->amount) {
724 $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency)."(".$dao->count.")";
725 $average[] = CRM_Utils_Money::format($dao->avg, $dao->currency);
726 }
727
728 $count += $dao->count;
729 if ($dao->amount2) {
730 $amount2[] = CRM_Utils_Money::format($dao->amount2, $dao->currency)."(".$dao->count.")";
731 $average2[] = CRM_Utils_Money::format($dao->avg2, $dao->currency);
732 }
733 $count2 += $dao->count2;
734 }
735
736 $statistics['counts']['range_one_title'] = array('title' => 'Initial Date Range:');
737 $statistics['counts']['amount'] = array(
738 'value' => implode(', ', $amount),
739 'title' => 'Total Amount',
740 'type' => CRM_Utils_Type::T_STRING,
741 );
742 $statistics['counts']['count'] = array(
743 'value' => $count,
744 'title' => 'Total Donations',
745 );
746 $statistics['counts']['avg'] = array(
747 'value' => implode(', ', $average),
748 'title' => 'Average',
749 'type' => CRM_Utils_Type::T_STRING,
750 );
751 $statistics['counts']['range_two_title'] = array(
752 'title' => 'Second Date Range:',
753 );
754 $statistics['counts']['amount2'] = array(
755 'value' => implode(', ', $amount2),
756 'title' => 'Total Amount',
757 'type' => CRM_Utils_Type::T_STRING,
758 );
759 $statistics['counts']['count2'] = array(
760 'value' => $count2,
761 'title' => 'Total Donations',
762 );
763 $statistics['counts']['avg2'] = array(
764 'value' => implode(', ', $average2),
765 'title' => 'Average',
766 'type' => CRM_Utils_Type::T_STRING,
767 );
768
769 return $statistics;
770 }
771
772 function postProcess() {
773 $this->beginPostProcess();
774 $create = $subSelect1 = $subSelect2 = NULL;
775 list($fromTable, $fromAlias, $fromCol) = $this->groupBy(TRUE);
776 if ($fromTable == 'civicrm_contact') {
777 $contriCol = "contact_id";
778 }
779 elseif ($fromTable == 'civicrm_contribution_type') {
780 $contriCol = "contribution_type_id";
781 }
782 elseif ($fromTable == 'civicrm_contribution') {
783 $contriCol = $fromCol;
784 }
785 elseif ($fromTable == 'civicrm_address') {
786 $contriCol = "contact_id";
787 }
788 elseif ($fromTable == 'civicrm_financial_type') {
789 $contriCol = 'financial_type_id';
790 $subSelect1 = 'contribution1.contact_id,';
791 $subSelect2 = 'contribution2.contact_id,';
792 $create = 'contact_id int unsigned,';
793 }
794
795 $subWhere = $this->whereContribution();
796 $subContributionQuery1 = "
797 SELECT {$subSelect1} contribution1.{$contriCol},
798 sum( contribution1.total_amount ) AS total_amount_sum,
799 count( * ) AS total_amount_count
800 FROM civicrm_contribution contribution1
801 {$subWhere}
802 GROUP BY contribution1.{$contriCol}";
803
804 $subWhere = $this->whereContribution('contribution2');
805 $subContributionQuery2 = "
806 SELECT {$subSelect2} contribution2.{$contriCol},
807 sum( contribution2.total_amount ) AS total_amount_sum,
808 count( * ) AS total_amount_count,
809 currency
810 FROM civicrm_contribution contribution2
811 {$subWhere}
812 GROUP BY contribution2.{$contriCol}";
813
814 $sql = "
815 CREATE TEMPORARY TABLE civicrm_temp_civireport_repeat1 (
816 {$create}
817 {$contriCol} int unsigned,
818 total_amount_sum int,
819 total_amount_count int
820 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
821 CRM_Core_DAO::executeQuery($sql);
822 $sql = "INSERT INTO civicrm_temp_civireport_repeat1 {$subContributionQuery1}";
823 CRM_Core_DAO::executeQuery($sql);
824
825 $sql = "
826 CREATE TEMPORARY TABLE civicrm_temp_civireport_repeat2 (
827 {$create}
828 {$contriCol} int unsigned,
829 total_amount_sum int,
830 total_amount_count int,
831 currency varchar(3)
832 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
833 CRM_Core_DAO::executeQuery($sql);
834 $sql = "INSERT INTO civicrm_temp_civireport_repeat2 {$subContributionQuery2}";
835 CRM_Core_DAO::executeQuery($sql);
836
837 $this->select();
838 $this->from();
839 $this->where();
840 $this->groupBy();
841 $this->limit();
842
843 $count = 0;
844 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_limit}";
845 $dao = CRM_Core_DAO::executeQuery($sql);
846 $rows = array();
847 while ($dao->fetch()) {
848 foreach ($this->_columnHeaders as $key => $value) {
849 $rows[$count][$key] = $dao->$key;
850 }
851 $count++;
852 }
853
854 // FIXME: calculate % using query
855 foreach ($rows as $uid => $row) {
856 if ($row['contribution1_total_amount_sum'] && $row['contribution2_total_amount_sum']) {
857 $rows[$uid]['change'] = number_format((($row['contribution2_total_amount_sum'] -
858 $row['contribution1_total_amount_sum']
859 ) * 100) /
860 ($row['contribution1_total_amount_sum']), 2
861 );
862 }
863 elseif ($row['contribution1_total_amount_sum']) {
864 $rows[$uid]['change'] = ts('Skipped Donation');
865 }
866 elseif ($row['contribution2_total_amount_sum']) {
867 $rows[$uid]['change'] = ts('New Donor');
868 }
869 if ($row['contribution1_total_amount_count']) {
870 $rows[$uid]['contribution1_total_amount_sum'] = $row['contribution1_total_amount_sum'] . " ({$row['contribution1_total_amount_count']})";
871 }
872 if ($row['contribution2_total_amount_count']) {
873 $rows[$uid]['contribution2_total_amount_sum'] = $row['contribution2_total_amount_sum'] . " ({$row['contribution2_total_amount_count']})";
874 }
875 }
876 $this->_columnHeaders['change'] = array(
877 'title' => '% Change',
878 'type' => CRM_Utils_Type::T_INT,
879 );
880
881 // hack to fix title
882 list($from1, $to1) = $this->getFromTo(CRM_Utils_Array::value("receive_date1_relative", $this->_params),
883 CRM_Utils_Array::value("receive_date1_from", $this->_params),
884 CRM_Utils_Array::value("receive_date1_to", $this->_params)
885 );
886 $from1 = CRM_Utils_Date::customFormat($from1, NULL, array('d'));
887 $to1 = CRM_Utils_Date::customFormat($to1, NULL, array('d'));
888
889 list($from2, $to2) = $this->getFromTo(CRM_Utils_Array::value("receive_date2_relative", $this->_params),
890 CRM_Utils_Array::value("receive_date2_from", $this->_params),
891 CRM_Utils_Array::value("receive_date2_to", $this->_params)
892 );
893 $from2 = CRM_Utils_Date::customFormat($from2, NULL, array('d'));
894 $to2 = CRM_Utils_Date::customFormat($to2, NULL, array('d'));
895
896 $this->_columnHeaders['contribution1_total_amount_sum']['title'] = "$from1 -<br/> $to1";
897 $this->_columnHeaders['contribution2_total_amount_sum']['title'] = "$from2 -<br/> $to2";
898 unset($this->_columnHeaders['contribution1_total_amount_count'],
899 $this->_columnHeaders['contribution2_total_amount_count']
900 );
901
902 $this->formatDisplay($rows);
903
904 // assign variables to templates
905 $this->doTemplateAssignment($rows);
906
907 $this->endPostProcess($rows);
908 }
909
910 /**
911 * @param $rows
912 */
913 function alterDisplay(&$rows) {
914 // custom code to alter rows
915 list($from1, $to1) = $this->getFromTo(CRM_Utils_Array::value("receive_date1_relative", $this->_params),
916 CRM_Utils_Array::value("receive_date1_from", $this->_params),
917 CRM_Utils_Array::value("receive_date1_to", $this->_params)
918 );
919 list($from2, $to2) = $this->getFromTo(CRM_Utils_Array::value("receive_date2_relative", $this->_params),
920 CRM_Utils_Array::value("receive_date2_from", $this->_params),
921 CRM_Utils_Array::value("receive_date2_to", $this->_params)
922 );
923
924 $dateUrl = "";
925 if ($from1) {
926 $dateUrl .= "receive_date1_from={$from1}&";
927 }
928 if ($to1) {
929 $dateUrl .= "receive_date1_to={$to1}&";
930 }
931 if ($from2) {
932 $dateUrl .= "receive_date2_from={$from2}&";
933 }
934 if ($to2) {
935 $dateUrl .= "receive_date2_to={$to2}&";
936 }
937
938 foreach ($rows as $rowNum => $row) {
939 // handle country
940 if (array_key_exists('address_civireport_country_id', $row)) {
941 if ($value = $row['address_civireport_country_id']) {
942 $rows[$rowNum]['address_civireport_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
943
944 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
945 "reset=1&force=1&" .
946 "country_id_op=in&country_id_value={$value}&" .
947 "$dateUrl",
948 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
949 );
950
951 $rows[$rowNum]['address_civireport_country_id_link'] = $url;
952 $rows[$rowNum]['address_civireport_country_id_hover'] = ts("View contributions for this Country.");
953 }
954 }
955
956 // handle state province
957 if (array_key_exists('address_civireport_state_province_id', $row)) {
958 if ($value = $row['address_civireport_state_province_id']) {
959 $rows[$rowNum]['address_civireport_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
960
961 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
962 "reset=1&force=1&" .
963 "state_province_id_op=in&state_province_id_value={$value}&" .
964 "$dateUrl",
965 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
966 );
967
968 $rows[$rowNum]['address_civireport_state_province_id_link'] = $url;
969 $rows[$rowNum]['address_civireport_state_province_id_hover'] = ts("View repeatDetails for this state.");
970 }
971 }
972
973 // convert display name to links
974 if (array_key_exists('contact_civireport_sort_name', $row) &&
975 array_key_exists('contact_civireport_id', $row)
976 ) {
977 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
978 'reset=1&force=1&id_op=eq&id_value=' . $row['contact_civireport_id'],
979 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
980 );
981
982 $rows[$rowNum]['contact_civireport_sort_name_link'] = $url;
983 $rows[$rowNum]['contact_civireport_sort_name_hover'] = ts("View Contribution details for this contact");
984 }
985 }
986 // foreach ends
987 }
988 }
989