Merge pull request #4630 from atif-shaikh/CRM-15546
[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('Contribution 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 );
170
171 $this->_groupFilter = TRUE;
172 $this->_tagFilter = TRUE;
173 $this->_currencyColumn = 'civicrm_contribution_currency';
174 parent::__construct();
175 }
176
177 function preProcess() {
178 parent::preProcess();
179 }
180
181 function select() {
182 $select = array();
183 $this->_columnHeaders = array();
184 //Headers for Rank column
185 $this->_columnHeaders["civicrm_donor_rank"]['title'] = ts('Rank');
186 $this->_columnHeaders["civicrm_donor_rank"]['type'] = 1;
187 //$select[] ="(@rank:=@rank+1) as civicrm_donor_rank ";
188
189 foreach ($this->_columns as $tableName => $table) {
190 if (array_key_exists('fields', $table)) {
191 foreach ($table['fields'] as $fieldName => $field) {
192 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
193 // only include statistics columns if set
194 if (!empty($field['statistics'])) {
195 foreach ($field['statistics'] as $stat => $label) {
196 switch (strtolower($stat)) {
197 case 'sum':
198 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
199 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
200 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
201 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
202 break;
203
204 case 'count':
205 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
206 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
207 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
208 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
209 break;
210
211 case 'avg':
212 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
213 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
214 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
215 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
216 break;
217 }
218 }
219 }
220 else {
221 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
222 // $field['type'] is not always set. Use string type as default if not set.
223 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = isset($field['type']) ? $field['type'] : 2;
224 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
225 }
226 }
227 }
228 }
229 }
230
231 $this->_select = " SELECT * FROM ( SELECT " . implode(', ', $select) . " ";
232 }
233
234 /**
235 * @param $fields
236 * @param $files
237 * @param $self
238 *
239 * @return array
240 */
241 static function formRule($fields, $files, $self) {
242 $errors = array();
243
244 $op = CRM_Utils_Array::value('total_range_op', $fields);
245 $val = CRM_Utils_Array::value('total_range_value', $fields);
246
247 if (!in_array($op, array(
248 'eq', 'lte'))) {
249 $errors['total_range_op'] = ts("Please select 'Is equal to' OR 'Is Less than or equal to' operator");
250 }
251
252 if ($val && !CRM_Utils_Rule::positiveInteger($val)) {
253 $errors['total_range_value'] = ts("Please enter positive number");
254 }
255 return $errors;
256 }
257
258 function from() {
259 $this->_from = "
260 FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
261 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
262 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND {$this->_aliases['civicrm_contribution']}.is_test = 0
263 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
264 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
265 AND {$this->_aliases['civicrm_email']}.is_primary = 1
266 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
267 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
268 {$this->_aliases['civicrm_phone']}.is_primary = 1
269 ";
270 $this->addAddressFromClause();
271 }
272
273 function where() {
274 $clauses = array();
275 $this->_tempClause = $this->_outerCluase = $this->_groupLimit = '';
276 foreach ($this->_columns as $tableName => $table) {
277 if (array_key_exists('filters', $table)) {
278 foreach ($table['filters'] as $fieldName => $field) {
279 $clause = NULL;
280 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
281 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
282 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
283 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
284
285 if ($relative || $from || $to) {
286 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
287 }
288 }
289 else {
290 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
291 if ($op) {
292 $clause = $this->whereClause($field,
293 $op,
294 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
295 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
296 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
297 );
298 }
299 }
300
301 if (!empty($clause)) {
302 if ($fieldName == 'total_range') {
303 $value = CRM_Utils_Array::value("total_range_value", $this->_params);
304 $this->_outerCluase = " WHERE (( @rows := @rows + 1) <= {$value}) ";
305 $this->_groupLimit = " LIMIT {$value}";
306 }
307 else {
308 $clauses[] = $clause;
309 }
310 }
311 }
312 }
313 }
314 if (empty($clauses)) {
315 $this->_where = "WHERE ( 1 ) ";
316 }
317 else {
318 $this->_where = "WHERE " . implode(' AND ', $clauses);
319 }
320
321 if ($this->_aclWhere) {
322 $this->_where .= " AND {$this->_aclWhere} ";
323 }
324 }
325
326 function groupBy() {
327 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_contact']}.id, {$this->_aliases['civicrm_contribution']}.currency";
328 }
329
330 function postProcess() {
331
332 $this->beginPostProcess();
333
334 // get the acl clauses built before we assemble the query
335 $this->buildACLClause($this->_aliases['civicrm_contact']);
336
337 $this->select();
338
339 $this->from();
340
341 $this->where();
342
343 $this->groupBy();
344
345 $this->limit();
346
347
348 //set the variable value rank, rows = 0
349 $setVariable = " SET @rows:=0, @rank=0 ";
350 CRM_Core_DAO::singleValueQuery($setVariable);
351
352 $sql = " {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
353 ORDER BY civicrm_contribution_total_amount_sum DESC
354 ) as abc {$this->_outerCluase} $this->_limit
355 ";
356
357 $dao = CRM_Core_DAO::executeQuery($sql);
358
359 while ($dao->fetch()) {
360 $row = array();
361 foreach ($this->_columnHeaders as $key => $value) {
362 if (property_exists($dao, $key)) {
363 $row[$key] = $dao->$key;
364 }
365 }
366 $rows[] = $row;
367 }
368 $this->formatDisplay($rows);
369
370 $this->doTemplateAssignment($rows);
371
372 $this->endPostProcess($rows);
373 }
374
375 /**
376 * @param int $groupID
377 */
378 function add2group($groupID) {
379 if (is_numeric($groupID)) {
380
381 $sql = "
382 {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
383 ORDER BY civicrm_contribution_total_amount_sum DESC
384 ) as abc {$this->_groupLimit}";
385 $dao = CRM_Core_DAO::executeQuery($sql);
386
387 $contact_ids = array();
388 // Add resulting contacts to group
389 while ($dao->fetch()) {
390 $contact_ids[$dao->civicrm_contact_id] = $dao->civicrm_contact_id;
391 }
392
393 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
394 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
395 }
396 }
397
398 /**
399 * @param int $rowCount
400 */
401 function limit($rowCount = CRM_Report_Form::ROW_COUNT_LIMIT) {
402 // lets do the pager if in html mode
403 $this->_limit = NULL;
404
405 // CRM-14115, over-ride row count if rowCount is specified in URL
406 if ($this->_dashBoardRowCount) {
407 $rowCount = $this->_dashBoardRowCount;
408 }
409 if ($this->_outputMode == 'html' || $this->_outputMode == 'group') {
410 //replace only first occurence of SELECT
411 $this->_select = preg_replace('/SELECT/', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select, 1);
412 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
413
414 if (!$pageId && !empty($_POST) && isset($_POST['crmPID_B'])) {
415 if (!isset($_POST['PagerBottomButton'])) {
416 unset($_POST['crmPID_B']);
417 }
418 else {
419 $pageId = max((int)@$_POST['crmPID_B'], 1);
420 }
421 }
422
423 $pageId = $pageId ? $pageId : 1;
424 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
425 $offset = ($pageId - 1) * $rowCount;
426
427 $offset = CRM_Utils_Type::escape($offset, 'Int');
428 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
429
430 $this->_limit = " LIMIT $offset, " . $rowCount;
431 }
432 }
433
434 /**
435 * @param $rows
436 */
437 function alterDisplay(&$rows) {
438 // custom code to alter rows
439
440 $entryFound = FALSE;
441 $rank = 1;
442 if (!empty($rows)) {
443 foreach ($rows as $rowNum => $row) {
444
445 $rows[$rowNum]['civicrm_donor_rank'] = $rank++;
446 // convert display name to links
447 if (array_key_exists('civicrm_contact_display_name', $row) &&
448 array_key_exists('civicrm_contact_id', $row) && !empty($row['civicrm_contribution_currency'])) {
449 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
450 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'] . "&currency_value=" . $row['civicrm_contribution_currency'],
451 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
452 );
453 $rows[$rowNum]['civicrm_contact_display_name_link'] = $url;
454 $entryFound = TRUE;
455 }
456 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ? TRUE : $entryFound;
457
458 // skip looking further in rows, if first row itself doesn't
459 // have the column we need
460 if (!$entryFound) {
461 break;
462 }
463 }
464 }
465 }
466 }
467