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