CRM-9394
[civicrm-core.git] / CRM / Report / Form / Contribute / TopDonor.php
CommitLineData
6a488035
TO
1<?php
2// $Id$
3
4/*
5 +--------------------------------------------------------------------+
6 | CiviCRM version 4.3 |
7 +--------------------------------------------------------------------+
8 | Copyright CiviCRM LLC (c) 2004-2013 |
9 +--------------------------------------------------------------------+
10 | This file is a part of CiviCRM. |
11 | |
12 | CiviCRM is free software; you can copy, modify, and distribute it |
13 | under the terms of the GNU Affero General Public License |
14 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
15 | |
16 | CiviCRM is distributed in the hope that it will be useful, but |
17 | WITHOUT ANY WARRANTY; without even the implied warranty of |
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
19 | See the GNU Affero General Public License for more details. |
20 | |
21 | You should have received a copy of the GNU Affero General Public |
22 | License and the CiviCRM Licensing Exception along |
23 | with this program; if not, contact CiviCRM LLC |
24 | at info[AT]civicrm[DOT]org. If you have questions about the |
25 | GNU Affero General Public License or the licensing of CiviCRM, |
26 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
27 +--------------------------------------------------------------------+
28*/
29
30/**
31 *
32 * @package CRM
33 * @copyright CiviCRM LLC (c) 2004-2013
34 * $Id$
35 *
36 */
37class CRM_Report_Form_Contribute_TopDonor extends CRM_Report_Form {
38
39 protected $_summary = NULL;
40
41 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
42
43 protected $_charts = array(
44 '' => 'Tabular',
45 'barChart' => 'Bar Chart',
46 'pieChart' => 'Pie Chart',
47 );
48
49 function __construct() {
50 $this->_columns = array(
51 'civicrm_contact' =>
52 array(
53 'dao' => 'CRM_Contact_DAO_Contact',
54 'fields' =>
55 array(
56 'id' =>
57 array(
58 'no_display' => TRUE,
59 'required' => TRUE,
60 ),
61 'display_name' =>
62 array('title' => ts('Contact Name'),
63 'required' => TRUE,
64 'no_repeat' => TRUE,
65 ),
66 'first_name' => array('title' => ts('First Name'),
67 ),
68 'last_name' => array('title' => ts('Last Name'),
69 ),
70 ),
71 ),
72 'civicrm_contribution' =>
73 array(
74 'dao' => 'CRM_Contribute_DAO_Contribution',
75 'fields' =>
76 array(
77 'total_amount' =>
78 array('title' => ts('Amount Statistics'),
79 'required' => TRUE,
80 'statistics' =>
81 array('sum' => ts('Aggregate Amount'),
82 'count' => ts('Donations'),
83 'avg' => ts('Average'),
84 ),
85 ),
7a961f19 86 'currency' =>
87 array('required' => TRUE,
88 'no_display' => TRUE,
89 ),
6a488035
TO
90 ),
91 'filters' =>
92 array(
93 'receive_date' =>
94 array(
95 'default' => 'this.year',
96 'operatorType' => CRM_Report_Form::OP_DATE,
97 ),
7a961f19 98 'currency' =>
f3bc9ff5 99 array('title' => 'Currency',
100 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
0637f1c4 101 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
d1b0931b 102 'default' => NULL,
7a961f19 103 'type' => CRM_Utils_Type::T_STRING,
f3bc9ff5 104 ),
6a488035
TO
105 'total_range' =>
106 array('title' => ts('Show no. of Top Donors'),
107 'type' => CRM_Utils_Type::T_INT,
108 'default_op' => 'eq',
109 ),
f3bc9ff5 110 'financial_type_id' =>
b914f4e8
PN
111 array('name' => 'financial_type_id',
112 'title' => ts('Financial Type'),
6a488035 113 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
b914f4e8 114 'options' => CRM_Contribute_PseudoConstant::financialType() ,
6a488035
TO
115 ),
116 'contribution_status_id' =>
117 array('title' => ts('Donation Status'),
118 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
119 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
120 'default' => array(1),
121 ),
122 ),
123 ),
124 'civicrm_email' =>
125 array(
126 'dao' => 'CRM_Core_DAO_Email',
127 'fields' =>
128 array(
129 'email' =>
130 array('title' => ts('Email'),
131 'default' => TRUE,
132 'no_repeat' => TRUE,
133 ),
134 ),
135 'grouping' => 'email-fields',
136 ),
137
138 'civicrm_phone' =>
139 array(
140 'dao' => 'CRM_Core_DAO_Phone',
141 'fields' =>
142 array(
143 'phone' =>
144 array('title' => ts('Phone'),
145 'default' => TRUE,
146 'no_repeat' => TRUE,
147 ),
148 ),
149 'grouping' => 'phone-fields',
150 ),
151 'civicrm_group' =>
152 array(
153 'dao' => 'CRM_Contact_DAO_GroupContact',
154 'alias' => 'cgroup',
155 'filters' =>
156 array(
157 'gid' =>
158 array(
159 'name' => 'group_id',
160 'title' => ts('Group'),
161 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
162 'group' => TRUE,
163 'options' => CRM_Core_PseudoConstant::group(),
164 ),
165 ),
166 ),
167 );
168
169 $this->_tagFilter = TRUE;
7a961f19 170 $this->_currencyColumn = 'civicrm_contribution_currency';
6a488035
TO
171 parent::__construct();
172 }
173
174 function preProcess() {
175 parent::preProcess();
176 }
177
178 function select() {
179 $select = array();
180 $this->_columnHeaders = array();
181 //Headers for Rank column
182 $this->_columnHeaders["civicrm_donor_rank"]['title'] = ts('Rank');
183 $this->_columnHeaders["civicrm_donor_rank"]['type'] = 1;
184 //$select[] ="(@rank:=@rank+1) as civicrm_donor_rank ";
185
186 foreach ($this->_columns as $tableName => $table) {
187 if (array_key_exists('fields', $table)) {
188 foreach ($table['fields'] as $fieldName => $field) {
189 if (CRM_Utils_Array::value('required', $field) ||
190 CRM_Utils_Array::value($fieldName, $this->_params['fields'])
191 ) {
192 // only include statistics columns if set
193 if (CRM_Utils_Array::value('statistics', $field)) {
194 foreach ($field['statistics'] as $stat => $label) {
195 switch (strtolower($stat)) {
196 case 'sum':
197 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
198 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
199 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
200 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
201 break;
202
203 case 'count':
204 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
205 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
206 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
207 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
208 break;
209
210 case 'avg':
211 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
212 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
213 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
214 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
215 break;
216 }
217 }
218 }
219 else {
220 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
221 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = $field['type'];
222 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
223 }
224 }
225 }
226 }
227 }
228 $this->_select = " SELECT * FROM ( SELECT " . implode(', ', $select) . " ";
229 }
230
231 static function formRule($fields, $files, $self) {
232 $errors = array();
233
234 $op = CRM_Utils_Array::value('total_range_op', $fields);
235 $val = CRM_Utils_Array::value('total_range_value', $fields);
236
237 if (!in_array($op, array(
238 'eq', 'lte'))) {
239 $errors['total_range_op'] = ts("Please select 'Is equal to' OR 'Is Less than or equal to' operator");
240 }
241
242 if ($val && !CRM_Utils_Rule::positiveInteger($val)) {
243 $errors['total_range_value'] = ts("Please enter positive number");
244 }
245 return $errors;
246 }
247
248 function from() {
249 $this->_from = "
250 FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
251 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
252 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND {$this->_aliases['civicrm_contribution']}.is_test = 0
253 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
254 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
255 AND {$this->_aliases['civicrm_email']}.is_primary = 1
256 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
257 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
258 {$this->_aliases['civicrm_phone']}.is_primary = 1
259 ";
260 }
261
262 function where() {
263 $clauses = array();
264 $this->_tempClause = $this->_outerCluase = '';
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 }
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 function groupBy() {
7a961f19 315 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_contact']}.id, {$this->_aliases['civicrm_contribution']}.currency";
6a488035
TO
316 }
317
318 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
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 function add2group($groupID) {
364 if (is_numeric($groupID)) {
365
366 $sql = "
367{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
368ORDER BY civicrm_contribution_total_amount_sum DESC
369) as abc {$this->_outerCluase}";
370 $dao = CRM_Core_DAO::executeQuery($sql);
371
372 $contact_ids = array();
373 // Add resulting contacts to group
374 while ($dao->fetch()) {
375 $contact_ids[$dao->civicrm_contact_id] = $dao->civicrm_contact_id;
376 }
377
378 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
379 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
380 }
381 }
382
383 function limit($rowCount = CRM_Report_Form::ROW_COUNT_LIMIT) {
384 // lets do the pager if in html mode
385 $this->_limit = NULL;
386 if ($this->_outputMode == 'html' || $this->_outputMode == 'group') {
387 //replace only first occurence of SELECT
388 $this->_select = preg_replace('/SELECT/', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select, 1);
389 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
390
391 if (!$pageId && !empty($_POST) && isset($_POST['crmPID_B'])) {
392 if (!isset($_POST['PagerBottomButton'])) {
393 unset($_POST['crmPID_B']);
394 }
395 else {
396 $pageId = max((int)@$_POST['crmPID_B'], 1);
397 }
398 }
399
400 $pageId = $pageId ? $pageId : 1;
401 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
402 $offset = ($pageId - 1) * $rowCount;
403
404 $this->_limit = " LIMIT $offset, " . $rowCount;
405 }
406 }
407
408 function alterDisplay(&$rows) {
409 // custom code to alter rows
410
411 $entryFound = FALSE;
412 $rank = 1;
413 if (!empty($rows)) {
414 foreach ($rows as $rowNum => $row) {
415
416 $rows[$rowNum]['civicrm_donor_rank'] = $rank++;
417 // convert display name to links
418 if (array_key_exists('civicrm_contact_display_name', $row) &&
7a961f19 419 array_key_exists('civicrm_contact_id', $row) &&
420 CRM_Utils_Array::value('civicrm_contribution_currency', $row)
6a488035
TO
421 ) {
422 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
7a961f19 423 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'] . "&currency_value=" . $row['civicrm_contribution_currency'],
6a488035
TO
424 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
425 );
426 $rows[$rowNum]['civicrm_contact_display_name_link'] = $url;
427 $entryFound = TRUE;
428 }
429
430 // skip looking further in rows, if first row itself doesn't
431 // have the column we need
432 if (!$entryFound) {
433 break;
434 }
435 }
436 }
437 }
438}
439