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