Merge pull request #9363 from colemanw/CRM-19560
[civicrm-core.git] / CRM / Report / Form / Contribute / TopDonor.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
6a488035
TO
32 * $Id$
33 *
34 */
35class CRM_Report_Form_Contribute_TopDonor extends CRM_Report_Form {
36
37 protected $_summary = NULL;
70bea8e2 38 protected $_customGroupExtends = array(
39 'Contact',
40 'Individual',
7d793900 41 'Contribution',
70bea8e2 42 );
6a488035 43
1728e9a0 44 /**
45 * This report has not been optimised for group filtering.
46 *
47 * The functionality for group filtering has been improved but not
48 * all reports have been adjusted to take care of it. This report has not
49 * and will run an inefficient query until fixed.
50 *
51 * CRM-19170
52 *
53 * @var bool
54 */
55 protected $groupFilterNotOptimised = TRUE;
56
6a488035
TO
57 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
58
59 protected $_charts = array(
60 '' => 'Tabular',
61 'barChart' => 'Bar Chart',
62 'pieChart' => 'Pie Chart',
63 );
2f4c2f5d 64
74cf4551 65 /**
74cf4551 66 */
00be9182 67 public function __construct() {
70bea8e2 68 $this->_autoIncludeIndexedFieldsAsOrderBys = 1;
6a488035 69 $this->_columns = array(
ae5ffbb7
TO
70 'civicrm_contact' => array(
71 'dao' => 'CRM_Contact_DAO_Contact',
72 'fields' => array(
ae5ffbb7
TO
73 'display_name' => array(
74 'title' => ts('Contact Name'),
75 'required' => TRUE,
76 'no_repeat' => TRUE,
77 ),
78 'first_name' => array(
79 'title' => ts('First Name'),
80 ),
70bea8e2 81 'middle_name' => array(
82 'title' => ts('Middle Name'),
83 ),
ae5ffbb7
TO
84 'last_name' => array(
85 'title' => ts('Last Name'),
86 ),
70bea8e2 87 'id' => array(
88 'no_display' => TRUE,
89 'required' => TRUE,
90 ),
91 'gender_id' => array(
92 'title' => ts('Gender'),
93 ),
94 'birth_date' => array(
95 'title' => ts('Birth Date'),
96 ),
97 'age' => array(
98 'title' => ts('Age'),
99 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
100 ),
ae5ffbb7
TO
101 'contact_type' => array(
102 'title' => ts('Contact Type'),
103 ),
104 'contact_sub_type' => array(
105 'title' => ts('Contact Subtype'),
7a961f19 106 ),
6a488035 107 ),
49e1ea9f 108 'filters' => array(
109 'gender_id' => array(
110 'title' => ts('Gender'),
111 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
112 'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
113 ),
ee436328 114 'contact_type' => array(
115 'title' => ts('Contact Type'),
ae5ffbb7
TO
116 ),
117 'contact_sub_type' => array(
118 'title' => ts('Contact Subtype'),
7a961f19 119 ),
6a488035 120 ),
6e68fe2a 121 'filters' => array(
122 'gender_id' => array(
123 'title' => ts('Gender'),
124 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
125 'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
126 ),
127 ),
ae5ffbb7 128 ),
cbfbab2f
E
129 'civicrm_line_item' => array(
130 'dao' => 'CRM_Price_DAO_LineItem',
131 ),
ae5ffbb7
TO
132 );
133 $this->_columns += $this->getAddressColumns();
134 $this->_columns += array(
135 'civicrm_contribution' => array(
136 'dao' => 'CRM_Contribute_DAO_Contribution',
137 'fields' => array(
138 'total_amount' => array(
139 'title' => ts('Amount Statistics'),
140 'required' => TRUE,
141 'statistics' => array(
142 'sum' => ts('Aggregate Amount'),
143 'count' => ts('Donations'),
144 'avg' => ts('Average'),
f3bc9ff5 145 ),
6a488035 146 ),
ae5ffbb7
TO
147 'currency' => array(
148 'required' => TRUE,
149 'no_display' => TRUE,
6a488035
TO
150 ),
151 ),
ae5ffbb7 152 'filters' => array(
70bea8e2 153 'sort_name' => array(
154 'title' => ts('Participant Name'),
8ee006e7 155 'type' => CRM_Utils_Type::T_STRING,
70bea8e2 156 'operator' => 'like',
157 ),
158 'id' => array(
159 'title' => ts('Contact ID'),
8ee006e7 160 'type' => CRM_Utils_Type::T_INT,
70bea8e2 161 'no_display' => TRUE,
162 ),
70bea8e2 163 'birth_date' => array(
164 'title' => ts('Birth Date'),
165 'operatorType' => CRM_Report_Form::OP_DATE,
166 ),
167 'contact_type' => array(
168 'title' => ts('Contact Type'),
8ee006e7 169 'type' => CRM_Utils_Type::T_STRING,
70bea8e2 170 ),
171 'contact_sub_type' => array(
172 'title' => ts('Contact Subtype'),
8ee006e7 173 'type' => CRM_Utils_Type::T_STRING,
70bea8e2 174 ),
ae5ffbb7
TO
175 'receive_date' => array(
176 'default' => 'this.year',
177 'operatorType' => CRM_Report_Form::OP_DATE,
178 ),
179 'currency' => array(
ccc29f8e 180 'title' => ts('Currency'),
ae5ffbb7
TO
181 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
182 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
183 'default' => NULL,
184 'type' => CRM_Utils_Type::T_STRING,
185 ),
186 'total_range' => array(
187 'title' => ts('Show no. of Top Donors'),
188 'type' => CRM_Utils_Type::T_INT,
189 'default_op' => 'eq',
190 ),
191 'financial_type_id' => array(
192 'name' => 'financial_type_id',
193 'title' => ts('Financial Type'),
8ee006e7 194 'type' => CRM_Utils_Type::T_INT,
ae5ffbb7 195 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
cbfbab2f 196 'options' => CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes(),
ae5ffbb7
TO
197 ),
198 'contribution_status_id' => array(
199 'title' => ts('Contribution Status'),
200 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
201 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
202 'default' => array(1),
6a488035
TO
203 ),
204 ),
ae5ffbb7
TO
205 ),
206 'civicrm_email' => array(
207 'dao' => 'CRM_Core_DAO_Email',
208 'fields' => array(
209 'email' => array(
210 'title' => ts('Email'),
211 'default' => TRUE,
212 'no_repeat' => TRUE,
213 ),
214 ),
215 'grouping' => 'email-fields',
216 ),
217 'civicrm_phone' => array(
218 'dao' => 'CRM_Core_DAO_Phone',
219 'fields' => array(
220 'phone' => array(
221 'title' => ts('Phone'),
222 'default' => TRUE,
223 'no_repeat' => TRUE,
6a488035
TO
224 ),
225 ),
ae5ffbb7
TO
226 'grouping' => 'phone-fields',
227 ),
228 );
6a488035 229
16e2e80c 230 $this->_groupFilter = TRUE;
6a488035 231 $this->_tagFilter = TRUE;
7a961f19 232 $this->_currencyColumn = 'civicrm_contribution_currency';
6a488035
TO
233 parent::__construct();
234 }
235
00be9182 236 public function preProcess() {
6a488035
TO
237 parent::preProcess();
238 }
239
00be9182 240 public function select() {
6a488035
TO
241 $select = array();
242 $this->_columnHeaders = array();
243 //Headers for Rank column
244 $this->_columnHeaders["civicrm_donor_rank"]['title'] = ts('Rank');
245 $this->_columnHeaders["civicrm_donor_rank"]['type'] = 1;
246 //$select[] ="(@rank:=@rank+1) as civicrm_donor_rank ";
247
248 foreach ($this->_columns as $tableName => $table) {
249 if (array_key_exists('fields', $table)) {
250 foreach ($table['fields'] as $fieldName => $field) {
9d72cede
EM
251 if (!empty($field['required']) ||
252 !empty($this->_params['fields'][$fieldName])
253 ) {
6a488035 254 // only include statistics columns if set
a7488080 255 if (!empty($field['statistics'])) {
6a488035
TO
256 foreach ($field['statistics'] as $stat => $label) {
257 switch (strtolower($stat)) {
258 case 'sum':
259 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
260 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
261 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
262 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
263 break;
264
265 case 'count':
266 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
267 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
268 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
269 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
270 break;
271
272 case 'avg':
273 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
274 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
275 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
276 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
277 break;
278 }
279 }
280 }
281 else {
282 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
21d62de7
DG
283 // $field['type'] is not always set. Use string type as default if not set.
284 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = isset($field['type']) ? $field['type'] : 2;
6a488035
TO
285 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
286 }
287 }
288 }
289 }
290 }
d1641c51 291 $this->_selectClauses = $select;
65f9ed10 292
2c6b4783 293 $this->_select = " SELECT " . implode(', ', $select) . " ";
6a488035
TO
294 }
295
74cf4551
EM
296 /**
297 * @param $fields
298 * @param $files
299 * @param $self
300 *
301 * @return array
302 */
00be9182 303 public static function formRule($fields, $files, $self) {
6a488035
TO
304 $errors = array();
305
306 $op = CRM_Utils_Array::value('total_range_op', $fields);
307 $val = CRM_Utils_Array::value('total_range_value', $fields);
308
309 if (!in_array($op, array(
9d72cede 310 'eq',
21dfd5f5 311 'lte',
9d72cede
EM
312 ))
313 ) {
6a488035
TO
314 $errors['total_range_op'] = ts("Please select 'Is equal to' OR 'Is Less than or equal to' operator");
315 }
316
317 if ($val && !CRM_Utils_Rule::positiveInteger($val)) {
318 $errors['total_range_value'] = ts("Please enter positive number");
319 }
320 return $errors;
321 }
322
00be9182 323 public function from() {
6a488035
TO
324 $this->_from = "
325 FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
65f9ed10
E
326 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
327 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND {$this->_aliases['civicrm_contribution']}.is_test = 0
2f4c2f5d 328 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
329 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
6a488035 330 AND {$this->_aliases['civicrm_email']}.is_primary = 1
2f4c2f5d 331 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
6a488035 332 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
50757f01 333 {$this->_aliases['civicrm_phone']}.is_primary = 1";
21d62de7 334 $this->addAddressFromClause();
6a488035
TO
335 }
336
00be9182 337 public function where() {
6a488035 338 $clauses = array();
93406a82 339 $this->_tempClause = $this->_outerCluase = $this->_groupLimit = '';
6a488035
TO
340 foreach ($this->_columns as $tableName => $table) {
341 if (array_key_exists('filters', $table)) {
342 foreach ($table['filters'] as $fieldName => $field) {
343 $clause = NULL;
344 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
345 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
9d72cede
EM
346 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
347 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
6a488035
TO
348
349 if ($relative || $from || $to) {
350 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
351 }
352 }
353 else {
354 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
355 if ($op) {
356 $clause = $this->whereClause($field,
357 $op,
358 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
359 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
360 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
361 );
362 }
363 }
364
365 if (!empty($clause)) {
366 if ($fieldName == 'total_range') {
367 $value = CRM_Utils_Array::value("total_range_value", $this->_params);
368 $this->_outerCluase = " WHERE (( @rows := @rows + 1) <= {$value}) ";
93406a82 369 $this->_groupLimit = " LIMIT {$value}";
6a488035
TO
370 }
371 else {
372 $clauses[] = $clause;
373 }
374 }
375 }
376 }
377 }
378 if (empty($clauses)) {
379 $this->_where = "WHERE ( 1 ) ";
380 }
381 else {
382 $this->_where = "WHERE " . implode(' AND ', $clauses);
383 }
384
385 if ($this->_aclWhere) {
386 $this->_where .= " AND {$this->_aclWhere} ";
387 }
388 }
389
00be9182 390 public function groupBy() {
b708c08d 391 $this->_groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, array("{$this->_aliases['civicrm_contact']}.id", "{$this->_aliases['civicrm_contribution']}.currency"));
6a488035
TO
392 }
393
00be9182 394 public function postProcess() {
6a488035
TO
395
396 $this->beginPostProcess();
397
398 // get the acl clauses built before we assemble the query
399 $this->buildACLClause($this->_aliases['civicrm_contact']);
400
8ea1d58d 401 $this->buildQuery();
6a488035 402
6a488035
TO
403 //set the variable value rank, rows = 0
404 $setVariable = " SET @rows:=0, @rank=0 ";
405 CRM_Core_DAO::singleValueQuery($setVariable);
406
2c6b4783 407 $sql = "SELECT * FROM ( {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
6a488035
TO
408 ORDER BY civicrm_contribution_total_amount_sum DESC
409 ) as abc {$this->_outerCluase} $this->_limit
410 ";
411
412 $dao = CRM_Core_DAO::executeQuery($sql);
413
414 while ($dao->fetch()) {
415 $row = array();
416 foreach ($this->_columnHeaders as $key => $value) {
417 if (property_exists($dao, $key)) {
418 $row[$key] = $dao->$key;
419 }
420 }
421 $rows[] = $row;
422 }
423 $this->formatDisplay($rows);
424
425 $this->doTemplateAssignment($rows);
426
427 $this->endPostProcess($rows);
428 }
429
74cf4551 430 /**
100fef9d 431 * @param int $groupID
74cf4551 432 */
00be9182 433 public function add2group($groupID) {
6a488035
TO
434 if (is_numeric($groupID)) {
435
2f4c2f5d 436 $sql = "
437{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
6a488035 438ORDER BY civicrm_contribution_total_amount_sum DESC
93406a82 439) as abc {$this->_groupLimit}";
6a488035
TO
440 $dao = CRM_Core_DAO::executeQuery($sql);
441
442 $contact_ids = array();
443 // Add resulting contacts to group
444 while ($dao->fetch()) {
445 $contact_ids[$dao->civicrm_contact_id] = $dao->civicrm_contact_id;
446 }
447
448 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
449 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
450 }
451 }
452
74cf4551
EM
453 /**
454 * @param int $rowCount
455 */
00be9182 456 public function limit($rowCount = CRM_Report_Form::ROW_COUNT_LIMIT) {
6a488035
TO
457 // lets do the pager if in html mode
458 $this->_limit = NULL;
74cf4551 459
dbb4a0f9
PN
460 // CRM-14115, over-ride row count if rowCount is specified in URL
461 if ($this->_dashBoardRowCount) {
462 $rowCount = $this->_dashBoardRowCount;
463 }
6a488035 464 if ($this->_outputMode == 'html' || $this->_outputMode == 'group') {
ab432335 465 // Replace only first occurrence of SELECT.
6a488035
TO
466 $this->_select = preg_replace('/SELECT/', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select, 1);
467 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
468
469 if (!$pageId && !empty($_POST) && isset($_POST['crmPID_B'])) {
470 if (!isset($_POST['PagerBottomButton'])) {
471 unset($_POST['crmPID_B']);
472 }
473 else {
9d72cede 474 $pageId = max((int) @$_POST['crmPID_B'], 1);
6a488035
TO
475 }
476 }
477
478 $pageId = $pageId ? $pageId : 1;
479 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
480 $offset = ($pageId - 1) * $rowCount;
481
bf00d1b6
DL
482 $offset = CRM_Utils_Type::escape($offset, 'Int');
483 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
484
6a488035
TO
485 $this->_limit = " LIMIT $offset, " . $rowCount;
486 }
487 }
488
74cf4551 489 /**
ced9bfed
EM
490 * Alter display of rows.
491 *
492 * Iterate through the rows retrieved via SQL and make changes for display purposes,
493 * such as rendering contacts as links.
494 *
495 * @param array $rows
496 * Rows generated by SQL, with an array for each row.
74cf4551 497 */
00be9182 498 public function alterDisplay(&$rows) {
6a488035
TO
499 $entryFound = FALSE;
500 $rank = 1;
501 if (!empty($rows)) {
502 foreach ($rows as $rowNum => $row) {
503
504 $rows[$rowNum]['civicrm_donor_rank'] = $rank++;
505 // convert display name to links
506 if (array_key_exists('civicrm_contact_display_name', $row) &&
9d72cede
EM
507 array_key_exists('civicrm_contact_id', $row) &&
508 !empty($row['civicrm_contribution_currency'])
509 ) {
6a488035 510 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
9d72cede
EM
511 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'] .
512 "&currency_value=" . $row['civicrm_contribution_currency'],
6a488035
TO
513 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
514 );
515 $rows[$rowNum]['civicrm_contact_display_name_link'] = $url;
516 $entryFound = TRUE;
517 }
21d62de7 518 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ? TRUE : $entryFound;
6a488035 519
7d793900 520 //handle gender
521 if (array_key_exists('civicrm_contact_gender_id', $row)) {
522 if ($value = $row['civicrm_contact_gender_id']) {
523 $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
524 $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value];
525 }
526 $entryFound = TRUE;
70bea8e2 527 }
70bea8e2 528
7d793900 529 // display birthday in the configured custom format
530 if (array_key_exists('civicrm_contact_birth_date', $row)) {
531 $birthDate = $row['civicrm_contact_birth_date'];
532 if ($birthDate) {
533 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
534 }
535 $entryFound = TRUE;
70bea8e2 536 }
70bea8e2 537
6a488035
TO
538 // skip looking further in rows, if first row itself doesn't
539 // have the column we need
540 if (!$entryFound) {
541 break;
542 }
543 }
544 }
545 }
96025800 546
6a488035 547}