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