Merge pull request #4875 from civicrm/minor-fix
[civicrm-core.git] / CRM / Report / Form / Contribute / TopDonor.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.6 |
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_TopDonor extends CRM_Report_Form {
37
38 protected $_summary = NULL;
39
40 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
41
42 protected $_charts = array(
43 '' => 'Tabular',
44 'barChart' => 'Bar Chart',
45 'pieChart' => 'Pie Chart',
46 );
47
48 /**
49 */
50 /**
51 */
52 public function __construct() {
53 $this->_columns = array(
54 'civicrm_contact' => array(
55 'dao' => 'CRM_Contact_DAO_Contact',
56 'fields' => array(
57 'id' => array(
58 'no_display' => TRUE,
59 'required' => TRUE,
60 ),
61 'display_name' => array(
62 'title' => ts('Contact Name'),
63 'required' => TRUE,
64 'no_repeat' => TRUE,
65 ),
66 'first_name' => array(
67 'title' => ts('First Name'),
68 ),
69 'last_name' => array(
70 'title' => ts('Last Name'),
71 ),
72 'contact_type' => array(
73 'title' => ts('Contact Type'),
74 ),
75 'contact_sub_type' => array(
76 'title' => ts('Contact Subtype'),
77 ),
78 ),
79 ),
80 )
81 + $this->getAddressColumns()
82 + array(
83 'civicrm_contribution' => array(
84 'dao' => 'CRM_Contribute_DAO_Contribution',
85 'fields' => array(
86 'total_amount' => array(
87 'title' => ts('Amount Statistics'),
88 'required' => TRUE,
89 'statistics' => array(
90 'sum' => ts('Aggregate Amount'),
91 'count' => ts('Donations'),
92 'avg' => ts('Average'),
93 ),
94 ),
95 'currency' => array(
96 'required' => TRUE,
97 'no_display' => TRUE,
98 ),
99 ),
100 'filters' => array(
101 'receive_date' => array(
102 'default' => 'this.year',
103 'operatorType' => CRM_Report_Form::OP_DATE,
104 ),
105 'currency' => array(
106 'title' => 'Currency',
107 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
108 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
109 'default' => NULL,
110 'type' => CRM_Utils_Type::T_STRING,
111 ),
112 'total_range' => array(
113 'title' => ts('Show no. of Top Donors'),
114 'type' => CRM_Utils_Type::T_INT,
115 'default_op' => 'eq',
116 ),
117 'financial_type_id' => array(
118 'name' => 'financial_type_id',
119 'title' => ts('Financial Type'),
120 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
121 'options' => CRM_Contribute_PseudoConstant::financialType(),
122 ),
123 'contribution_status_id' => array(
124 'title' => ts('Contribution Status'),
125 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
126 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
127 'default' => array(1),
128 ),
129 ),
130 ),
131 'civicrm_email' => array(
132 'dao' => 'CRM_Core_DAO_Email',
133 'fields' => array(
134 'email' => array(
135 'title' => ts('Email'),
136 'default' => TRUE,
137 'no_repeat' => TRUE,
138 ),
139 ),
140 'grouping' => 'email-fields',
141 ),
142 'civicrm_phone' => array(
143 'dao' => 'CRM_Core_DAO_Phone',
144 'fields' => array(
145 'phone' => array(
146 'title' => ts('Phone'),
147 'default' => TRUE,
148 'no_repeat' => TRUE,
149 ),
150 ),
151 'grouping' => 'phone-fields',
152 ),
153 );
154
155 $this->_groupFilter = TRUE;
156 $this->_tagFilter = TRUE;
157 $this->_currencyColumn = 'civicrm_contribution_currency';
158 parent::__construct();
159 }
160
161 public function preProcess() {
162 parent::preProcess();
163 }
164
165 public function select() {
166 $select = array();
167 $this->_columnHeaders = array();
168 //Headers for Rank column
169 $this->_columnHeaders["civicrm_donor_rank"]['title'] = ts('Rank');
170 $this->_columnHeaders["civicrm_donor_rank"]['type'] = 1;
171 //$select[] ="(@rank:=@rank+1) as civicrm_donor_rank ";
172
173 foreach ($this->_columns as $tableName => $table) {
174 if (array_key_exists('fields', $table)) {
175 foreach ($table['fields'] as $fieldName => $field) {
176 if (!empty($field['required']) ||
177 !empty($this->_params['fields'][$fieldName])
178 ) {
179 // only include statistics columns if set
180 if (!empty($field['statistics'])) {
181 foreach ($field['statistics'] as $stat => $label) {
182 switch (strtolower($stat)) {
183 case 'sum':
184 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
185 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
186 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
187 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
188 break;
189
190 case 'count':
191 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
192 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
193 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
194 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
195 break;
196
197 case 'avg':
198 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
199 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
200 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
201 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
202 break;
203 }
204 }
205 }
206 else {
207 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
208 // $field['type'] is not always set. Use string type as default if not set.
209 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = isset($field['type']) ? $field['type'] : 2;
210 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
211 }
212 }
213 }
214 }
215 }
216
217 $this->_select = " SELECT * FROM ( SELECT " . implode(', ', $select) . " ";
218 }
219
220 /**
221 * @param $fields
222 * @param $files
223 * @param $self
224 *
225 * @return array
226 */
227 public static function formRule($fields, $files, $self) {
228 $errors = array();
229
230 $op = CRM_Utils_Array::value('total_range_op', $fields);
231 $val = CRM_Utils_Array::value('total_range_value', $fields);
232
233 if (!in_array($op, array(
234 'eq',
235 'lte',
236 ))
237 ) {
238 $errors['total_range_op'] = ts("Please select 'Is equal to' OR 'Is Less than or equal to' operator");
239 }
240
241 if ($val && !CRM_Utils_Rule::positiveInteger($val)) {
242 $errors['total_range_value'] = ts("Please enter positive number");
243 }
244 return $errors;
245 }
246
247 public function from() {
248 $this->_from = "
249 FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
250 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
251 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND {$this->_aliases['civicrm_contribution']}.is_test = 0
252 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
253 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
254 AND {$this->_aliases['civicrm_email']}.is_primary = 1
255 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
256 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
257 {$this->_aliases['civicrm_phone']}.is_primary = 1
258 ";
259 $this->addAddressFromClause();
260 }
261
262 public function where() {
263 $clauses = array();
264 $this->_tempClause = $this->_outerCluase = $this->_groupLimit = '';
265 foreach ($this->_columns as $tableName => $table) {
266 if (array_key_exists('filters', $table)) {
267 foreach ($table['filters'] as $fieldName => $field) {
268 $clause = NULL;
269 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
270 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
271 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
272 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
273
274 if ($relative || $from || $to) {
275 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
276 }
277 }
278 else {
279 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
280 if ($op) {
281 $clause = $this->whereClause($field,
282 $op,
283 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
284 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
285 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
286 );
287 }
288 }
289
290 if (!empty($clause)) {
291 if ($fieldName == 'total_range') {
292 $value = CRM_Utils_Array::value("total_range_value", $this->_params);
293 $this->_outerCluase = " WHERE (( @rows := @rows + 1) <= {$value}) ";
294 $this->_groupLimit = " LIMIT {$value}";
295 }
296 else {
297 $clauses[] = $clause;
298 }
299 }
300 }
301 }
302 }
303 if (empty($clauses)) {
304 $this->_where = "WHERE ( 1 ) ";
305 }
306 else {
307 $this->_where = "WHERE " . implode(' AND ', $clauses);
308 }
309
310 if ($this->_aclWhere) {
311 $this->_where .= " AND {$this->_aclWhere} ";
312 }
313 }
314
315 public function groupBy() {
316 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_contact']}.id, {$this->_aliases['civicrm_contribution']}.currency";
317 }
318
319 public function postProcess() {
320
321 $this->beginPostProcess();
322
323 // get the acl clauses built before we assemble the query
324 $this->buildACLClause($this->_aliases['civicrm_contact']);
325
326 $this->select();
327
328 $this->from();
329
330 $this->where();
331
332 $this->groupBy();
333
334 $this->limit();
335
336 //set the variable value rank, rows = 0
337 $setVariable = " SET @rows:=0, @rank=0 ";
338 CRM_Core_DAO::singleValueQuery($setVariable);
339
340 $sql = " {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
341 ORDER BY civicrm_contribution_total_amount_sum DESC
342 ) as abc {$this->_outerCluase} $this->_limit
343 ";
344
345 $dao = CRM_Core_DAO::executeQuery($sql);
346
347 while ($dao->fetch()) {
348 $row = array();
349 foreach ($this->_columnHeaders as $key => $value) {
350 if (property_exists($dao, $key)) {
351 $row[$key] = $dao->$key;
352 }
353 }
354 $rows[] = $row;
355 }
356 $this->formatDisplay($rows);
357
358 $this->doTemplateAssignment($rows);
359
360 $this->endPostProcess($rows);
361 }
362
363 /**
364 * @param int $groupID
365 */
366 public function add2group($groupID) {
367 if (is_numeric($groupID)) {
368
369 $sql = "
370 {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
371 ORDER BY civicrm_contribution_total_amount_sum DESC
372 ) as abc {$this->_groupLimit}";
373 $dao = CRM_Core_DAO::executeQuery($sql);
374
375 $contact_ids = array();
376 // Add resulting contacts to group
377 while ($dao->fetch()) {
378 $contact_ids[$dao->civicrm_contact_id] = $dao->civicrm_contact_id;
379 }
380
381 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
382 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
383 }
384 }
385
386 /**
387 * @param int $rowCount
388 */
389 public function limit($rowCount = CRM_Report_Form::ROW_COUNT_LIMIT) {
390 // lets do the pager if in html mode
391 $this->_limit = NULL;
392
393 // CRM-14115, over-ride row count if rowCount is specified in URL
394 if ($this->_dashBoardRowCount) {
395 $rowCount = $this->_dashBoardRowCount;
396 }
397 if ($this->_outputMode == 'html' || $this->_outputMode == 'group') {
398 //replace only first occurence of SELECT
399 $this->_select = preg_replace('/SELECT/', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select, 1);
400 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
401
402 if (!$pageId && !empty($_POST) && isset($_POST['crmPID_B'])) {
403 if (!isset($_POST['PagerBottomButton'])) {
404 unset($_POST['crmPID_B']);
405 }
406 else {
407 $pageId = max((int) @$_POST['crmPID_B'], 1);
408 }
409 }
410
411 $pageId = $pageId ? $pageId : 1;
412 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
413 $offset = ($pageId - 1) * $rowCount;
414
415 $offset = CRM_Utils_Type::escape($offset, 'Int');
416 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
417
418 $this->_limit = " LIMIT $offset, " . $rowCount;
419 }
420 }
421
422 /**
423 * @param $rows
424 */
425 public function alterDisplay(&$rows) {
426 // custom code to alter rows
427
428 $entryFound = FALSE;
429 $rank = 1;
430 if (!empty($rows)) {
431 foreach ($rows as $rowNum => $row) {
432
433 $rows[$rowNum]['civicrm_donor_rank'] = $rank++;
434 // convert display name to links
435 if (array_key_exists('civicrm_contact_display_name', $row) &&
436 array_key_exists('civicrm_contact_id', $row) &&
437 !empty($row['civicrm_contribution_currency'])
438 ) {
439 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
440 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'] .
441 "&currency_value=" . $row['civicrm_contribution_currency'],
442 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
443 );
444 $rows[$rowNum]['civicrm_contact_display_name_link'] = $url;
445 $entryFound = TRUE;
446 }
447 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ? TRUE : $entryFound;
448
449 // skip looking further in rows, if first row itself doesn't
450 // have the column we need
451 if (!$entryFound) {
452 break;
453 }
454 }
455 }
456 }
457 }