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