Additional fixes in report and Search form
[civicrm-core.git] / CRM / Report / Form / Contribute / TopDonor.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2017
32 * $Id$
33 *
34 */
35 class CRM_Report_Form_Contribute_TopDonor extends CRM_Report_Form {
36
37 protected $_summary = NULL;
38 protected $_customGroupExtends = array(
39 'Contact',
40 'Individual',
41 'Contribution',
42 );
43
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
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 );
64
65 /**
66 */
67 public function __construct() {
68 $this->_autoIncludeIndexedFieldsAsOrderBys = 1;
69 $this->_columns = array(
70 'civicrm_contact' => array(
71 'dao' => 'CRM_Contact_DAO_Contact',
72 'fields' => array(
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 ),
81 'middle_name' => array(
82 'title' => ts('Middle Name'),
83 ),
84 'last_name' => array(
85 'title' => ts('Last Name'),
86 ),
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 ),
101 'contact_type' => array(
102 'title' => ts('Contact Type'),
103 ),
104 'contact_sub_type' => array(
105 'title' => ts('Contact Subtype'),
106 ),
107 ),
108 'filters' => $this->getBasicContactFilters(),
109 ),
110 'civicrm_line_item' => array(
111 'dao' => 'CRM_Price_DAO_LineItem',
112 ),
113 );
114 $this->_columns += $this->getAddressColumns();
115 $this->_columns += array(
116 'civicrm_contribution' => array(
117 'dao' => 'CRM_Contribute_DAO_Contribution',
118 'fields' => array(
119 'total_amount' => array(
120 'title' => ts('Amount Statistics'),
121 'required' => TRUE,
122 'statistics' => array(
123 'sum' => ts('Aggregate Amount'),
124 'count' => ts('Donations'),
125 'avg' => ts('Average'),
126 ),
127 ),
128 'currency' => array(
129 'required' => TRUE,
130 'no_display' => TRUE,
131 ),
132 ),
133 'filters' => array(
134 'receive_date' => array(
135 'default' => 'this.year',
136 'operatorType' => CRM_Report_Form::OP_DATE,
137 ),
138 'currency' => array(
139 'title' => ts('Currency'),
140 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
141 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
142 'default' => NULL,
143 'type' => CRM_Utils_Type::T_STRING,
144 ),
145 'total_range' => array(
146 'title' => ts('Show no. of Top Donors'),
147 'type' => CRM_Utils_Type::T_INT,
148 'default_op' => 'eq',
149 ),
150 'financial_type_id' => array(
151 'name' => 'financial_type_id',
152 'title' => ts('Financial Type'),
153 'type' => CRM_Utils_Type::T_INT,
154 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
155 'options' => CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes(),
156 ),
157 'contribution_status_id' => array(
158 'title' => ts('Contribution Status'),
159 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
160 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
161 'default' => array(1),
162 ),
163 ),
164 ),
165 'civicrm_financial_trxn' => array(
166 'dao' => 'CRM_Financial_DAO_FinancialTrxn',
167 'fields' => array(
168 'card_type_id' => array(
169 'title' => ts('Credit Card Type'),
170 'dbAlias' => 'GROUP_CONCAT(financial_trxn_civireport.card_type_id SEPARATOR ",")',
171 ),
172 ),
173 'filters' => array(
174 'card_type_id' => array(
175 'title' => ts('Credit Card Type'),
176 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
177 'options' => CRM_Financial_DAO_FinancialTrxn::buildOptions('card_type_id'),
178 'default' => NULL,
179 'type' => CRM_Utils_Type::T_STRING,
180 ),
181 ),
182 ),
183 'civicrm_email' => array(
184 'dao' => 'CRM_Core_DAO_Email',
185 'fields' => array(
186 'email' => array(
187 'title' => ts('Email'),
188 'default' => TRUE,
189 'no_repeat' => TRUE,
190 ),
191 ),
192 'grouping' => 'email-fields',
193 ),
194 'civicrm_phone' => array(
195 'dao' => 'CRM_Core_DAO_Phone',
196 'fields' => array(
197 'phone' => array(
198 'title' => ts('Phone'),
199 'default' => TRUE,
200 'no_repeat' => TRUE,
201 ),
202 ),
203 'grouping' => 'phone-fields',
204 ),
205 );
206
207 $this->_groupFilter = TRUE;
208 $this->_tagFilter = TRUE;
209 $this->_currencyColumn = 'civicrm_contribution_currency';
210 parent::__construct();
211 }
212
213 public function preProcess() {
214 parent::preProcess();
215 }
216
217 public function select() {
218 $select = array();
219 $this->_columnHeaders = array();
220 //Headers for Rank column
221 $this->_columnHeaders["civicrm_donor_rank"]['title'] = ts('Rank');
222 $this->_columnHeaders["civicrm_donor_rank"]['type'] = 1;
223 //$select[] ="(@rank:=@rank+1) as civicrm_donor_rank ";
224
225 foreach ($this->_columns as $tableName => $table) {
226 if (array_key_exists('fields', $table)) {
227 foreach ($table['fields'] as $fieldName => $field) {
228 if (!empty($field['required']) ||
229 !empty($this->_params['fields'][$fieldName])
230 ) {
231 // only include statistics columns if set
232 if (!empty($field['statistics'])) {
233 foreach ($field['statistics'] as $stat => $label) {
234 switch (strtolower($stat)) {
235 case 'sum':
236 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
237 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
238 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
239 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
240 break;
241
242 case 'count':
243 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
244 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
245 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
246 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
247 break;
248
249 case 'avg':
250 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
251 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
252 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
253 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
254 break;
255 }
256 }
257 }
258 else {
259 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
260 // $field['type'] is not always set. Use string type as default if not set.
261 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = isset($field['type']) ? $field['type'] : 2;
262 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
263 }
264 }
265 }
266 }
267 }
268 $this->_selectClauses = $select;
269
270 $this->_select = " SELECT " . implode(', ', $select) . " ";
271 }
272
273 /**
274 * @param $fields
275 * @param $files
276 * @param $self
277 *
278 * @return array
279 */
280 public static function formRule($fields, $files, $self) {
281 $errors = array();
282
283 $op = CRM_Utils_Array::value('total_range_op', $fields);
284 $val = CRM_Utils_Array::value('total_range_value', $fields);
285
286 if (!in_array($op, array(
287 'eq',
288 'lte',
289 ))
290 ) {
291 $errors['total_range_op'] = ts("Please select 'Is equal to' OR 'Is Less than or equal to' operator");
292 }
293
294 if ($val && !CRM_Utils_Rule::positiveInteger($val)) {
295 $errors['total_range_value'] = ts("Please enter positive number");
296 }
297 return $errors;
298 }
299
300 public function from() {
301 $this->_from = "
302 FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
303 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
304 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND {$this->_aliases['civicrm_contribution']}.is_test = 0
305 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
306 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
307 AND {$this->_aliases['civicrm_email']}.is_primary = 1
308 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
309 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
310 {$this->_aliases['civicrm_phone']}.is_primary = 1";
311
312 // for credit card type
313 $this->addFinancialTrxnFromClause();
314
315 $this->addAddressFromClause();
316 }
317
318 public function where() {
319 $clauses = array();
320 $this->_tempClause = $this->_outerCluase = $this->_groupLimit = '';
321 foreach ($this->_columns as $tableName => $table) {
322 if (array_key_exists('filters', $table)) {
323 foreach ($table['filters'] as $fieldName => $field) {
324 $clause = NULL;
325 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
326 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
327 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
328 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
329
330 if ($relative || $from || $to) {
331 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
332 }
333 }
334 else {
335 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
336 if ($op) {
337 $clause = $this->whereClause($field,
338 $op,
339 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
340 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
341 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
342 );
343 }
344 }
345
346 if (!empty($clause)) {
347 if ($fieldName == 'total_range') {
348 $value = CRM_Utils_Array::value("total_range_value", $this->_params);
349 $this->_outerCluase = " WHERE (( @rows := @rows + 1) <= {$value}) ";
350 $this->_groupLimit = " LIMIT {$value}";
351 }
352 else {
353 $clauses[] = $clause;
354 }
355 }
356 }
357 }
358 }
359 if (empty($clauses)) {
360 $this->_where = "WHERE ( 1 ) ";
361 }
362 else {
363 $this->_where = "WHERE " . implode(' AND ', $clauses);
364 }
365
366 if ($this->_aclWhere) {
367 $this->_where .= " AND {$this->_aclWhere} ";
368 }
369 }
370
371 public function groupBy() {
372 $this->_groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, array("{$this->_aliases['civicrm_contact']}.id", "{$this->_aliases['civicrm_contribution']}.currency"));
373 }
374
375 public function postProcess() {
376
377 $this->beginPostProcess();
378
379 // get the acl clauses built before we assemble the query
380 $this->buildACLClause($this->_aliases['civicrm_contact']);
381
382 $this->buildQuery();
383
384 //set the variable value rank, rows = 0
385 $setVariable = " SET @rows:=0, @rank=0 ";
386 CRM_Core_DAO::singleValueQuery($setVariable);
387
388 $sql = "SELECT * FROM ( {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
389 ORDER BY civicrm_contribution_total_amount_sum DESC
390 ) as abc {$this->_outerCluase} $this->_limit
391 ";
392
393 $dao = CRM_Core_DAO::executeQuery($sql);
394
395 while ($dao->fetch()) {
396 $row = array();
397 foreach ($this->_columnHeaders as $key => $value) {
398 if (property_exists($dao, $key)) {
399 $row[$key] = $dao->$key;
400 }
401 }
402 $rows[] = $row;
403 }
404 $this->formatDisplay($rows);
405
406 $this->doTemplateAssignment($rows);
407
408 $this->endPostProcess($rows);
409 }
410
411 /**
412 * @param int $groupID
413 */
414 public function add2group($groupID) {
415 if (is_numeric($groupID)) {
416
417 $sql = "
418 {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
419 ORDER BY civicrm_contribution_total_amount_sum DESC
420 ) as abc {$this->_groupLimit}";
421 $dao = CRM_Core_DAO::executeQuery($sql);
422
423 $contact_ids = array();
424 // Add resulting contacts to group
425 while ($dao->fetch()) {
426 $contact_ids[$dao->civicrm_contact_id] = $dao->civicrm_contact_id;
427 }
428
429 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
430 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
431 }
432 }
433
434 /**
435 * @param int $rowCount
436 */
437 public function limit($rowCount = CRM_Report_Form::ROW_COUNT_LIMIT) {
438 // lets do the pager if in html mode
439 $this->_limit = NULL;
440
441 // CRM-14115, over-ride row count if rowCount is specified in URL
442 if ($this->_dashBoardRowCount) {
443 $rowCount = $this->_dashBoardRowCount;
444 }
445 if ($this->_outputMode == 'html' || $this->_outputMode == 'group') {
446 // Replace only first occurrence of SELECT.
447 $this->_select = preg_replace('/SELECT/', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select, 1);
448 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer');
449
450 if (!$pageId && !empty($_POST) && isset($_POST['crmPID_B'])) {
451 if (!isset($_POST['PagerBottomButton'])) {
452 unset($_POST['crmPID_B']);
453 }
454 else {
455 $pageId = max((int) @$_POST['crmPID_B'], 1);
456 }
457 }
458
459 $pageId = $pageId ? $pageId : 1;
460 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
461 $offset = ($pageId - 1) * $rowCount;
462
463 $offset = CRM_Utils_Type::escape($offset, 'Int');
464 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
465
466 $this->_limit = " LIMIT $offset, " . $rowCount;
467 }
468 }
469
470 /**
471 * Alter display of rows.
472 *
473 * Iterate through the rows retrieved via SQL and make changes for display purposes,
474 * such as rendering contacts as links.
475 *
476 * @param array $rows
477 * Rows generated by SQL, with an array for each row.
478 */
479 public function alterDisplay(&$rows) {
480 $entryFound = FALSE;
481 $rank = 1;
482 if (!empty($rows)) {
483 foreach ($rows as $rowNum => $row) {
484
485 $rows[$rowNum]['civicrm_donor_rank'] = $rank++;
486 // convert display name to links
487 if (array_key_exists('civicrm_contact_display_name', $row) &&
488 array_key_exists('civicrm_contact_id', $row) &&
489 !empty($row['civicrm_contribution_currency'])
490 ) {
491 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
492 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'] .
493 "&currency_value=" . $row['civicrm_contribution_currency'],
494 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
495 );
496 $rows[$rowNum]['civicrm_contact_display_name_link'] = $url;
497 $entryFound = TRUE;
498 }
499 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ? TRUE : $entryFound;
500
501 //handle gender
502 if (array_key_exists('civicrm_contact_gender_id', $row)) {
503 if ($value = $row['civicrm_contact_gender_id']) {
504 $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
505 $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value];
506 }
507 $entryFound = TRUE;
508 }
509
510 // display birthday in the configured custom format
511 if (array_key_exists('civicrm_contact_birth_date', $row)) {
512 $birthDate = $row['civicrm_contact_birth_date'];
513 if ($birthDate) {
514 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
515 }
516 $entryFound = TRUE;
517 }
518
519 if (!empty($row['civicrm_financial_trxn_card_type_id'])) {
520 $rows[$rowNum]['civicrm_financial_trxn_card_type_id'] = $this->getLabels($row['civicrm_financial_trxn_card_type_id'], 'CRM_Financial_DAO_FinancialTrxn', 'card_type_id');
521 $entryFound = TRUE;
522 }
523
524 // skip looking further in rows, if first row itself doesn't
525 // have the column we need
526 if (!$entryFound) {
527 break;
528 }
529 }
530 }
531 }
532
533 }