CRM-12595 fix formatting in CRM/Report files
[civicrm-core.git] / CRM / Report / Form / Contribute / TopDonor.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.3 |
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('title' => ts('First Name'),
66 ),
67 'last_name' => array('title' => ts('Last Name'),
68 ),
69 ),
70 ),
71 'civicrm_contribution' =>
72 array(
73 'dao' => 'CRM_Contribute_DAO_Contribution',
74 'fields' =>
75 array(
76 'total_amount' =>
77 array('title' => ts('Amount Statistics'),
78 'required' => TRUE,
79 'statistics' =>
80 array('sum' => ts('Aggregate Amount'),
81 'count' => ts('Donations'),
82 'avg' => ts('Average'),
83 ),
84 ),
85 'currency' =>
86 array('required' => TRUE,
87 'no_display' => TRUE,
88 ),
89 ),
90 'filters' =>
91 array(
92 'receive_date' =>
93 array(
94 'default' => 'this.year',
95 'operatorType' => CRM_Report_Form::OP_DATE,
96 ),
97 'currency' =>
98 array('title' => 'Currency',
99 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
100 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
101 'default' => NULL,
102 'type' => CRM_Utils_Type::T_STRING,
103 ),
104 'total_range' =>
105 array('title' => ts('Show no. of Top Donors'),
106 'type' => CRM_Utils_Type::T_INT,
107 'default_op' => 'eq',
108 ),
109 'financial_type_id' =>
110 array('name' => 'financial_type_id',
111 'title' => ts('Financial Type'),
112 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
113 'options' => CRM_Contribute_PseudoConstant::financialType() ,
114 ),
115 'contribution_status_id' =>
116 array('title' => ts('Donation Status'),
117 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
118 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
119 'default' => array(1),
120 ),
121 ),
122 ),
123 'civicrm_email' =>
124 array(
125 'dao' => 'CRM_Core_DAO_Email',
126 'fields' =>
127 array(
128 'email' =>
129 array('title' => ts('Email'),
130 'default' => TRUE,
131 'no_repeat' => TRUE,
132 ),
133 ),
134 'grouping' => 'email-fields',
135 ),
136
137 'civicrm_phone' =>
138 array(
139 'dao' => 'CRM_Core_DAO_Phone',
140 'fields' =>
141 array(
142 'phone' =>
143 array('title' => ts('Phone'),
144 'default' => TRUE,
145 'no_repeat' => TRUE,
146 ),
147 ),
148 'grouping' => 'phone-fields',
149 ),
150 'civicrm_group' =>
151 array(
152 'dao' => 'CRM_Contact_DAO_GroupContact',
153 'alias' => 'cgroup',
154 'filters' =>
155 array(
156 'gid' =>
157 array(
158 'name' => 'group_id',
159 'title' => ts('Group'),
160 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
161 'group' => TRUE,
162 'options' => CRM_Core_PseudoConstant::group(),
163 ),
164 ),
165 ),
166 );
167
168 $this->_tagFilter = TRUE;
169 $this->_currencyColumn = 'civicrm_contribution_currency';
170 parent::__construct();
171 }
172
173 function preProcess() {
174 parent::preProcess();
175 }
176
177 function select() {
178 $select = array();
179 $this->_columnHeaders = array();
180 //Headers for Rank column
181 $this->_columnHeaders["civicrm_donor_rank"]['title'] = ts('Rank');
182 $this->_columnHeaders["civicrm_donor_rank"]['type'] = 1;
183 //$select[] ="(@rank:=@rank+1) as civicrm_donor_rank ";
184
185 foreach ($this->_columns as $tableName => $table) {
186 if (array_key_exists('fields', $table)) {
187 foreach ($table['fields'] as $fieldName => $field) {
188 if (CRM_Utils_Array::value('required', $field) ||
189 CRM_Utils_Array::value($fieldName, $this->_params['fields'])
190 ) {
191 // only include statistics columns if set
192 if (CRM_Utils_Array::value('statistics', $field)) {
193 foreach ($field['statistics'] as $stat => $label) {
194 switch (strtolower($stat)) {
195 case 'sum':
196 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
197 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
198 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
199 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
200 break;
201
202 case 'count':
203 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
204 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
205 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
206 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
207 break;
208
209 case 'avg':
210 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
211 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
212 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
213 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
214 break;
215 }
216 }
217 }
218 else {
219 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
220 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = $field['type'];
221 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
222 }
223 }
224 }
225 }
226 }
227 $this->_select = " SELECT * FROM ( SELECT " . implode(', ', $select) . " ";
228 }
229
230 static function formRule($fields, $files, $self) {
231 $errors = array();
232
233 $op = CRM_Utils_Array::value('total_range_op', $fields);
234 $val = CRM_Utils_Array::value('total_range_value', $fields);
235
236 if (!in_array($op, array(
237 'eq', 'lte'))) {
238 $errors['total_range_op'] = ts("Please select 'Is equal to' OR 'Is Less than or equal to' operator");
239 }
240
241 if ($val && !CRM_Utils_Rule::positiveInteger($val)) {
242 $errors['total_range_value'] = ts("Please enter positive number");
243 }
244 return $errors;
245 }
246
247 function from() {
248 $this->_from = "
249 FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
250 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
251 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND {$this->_aliases['civicrm_contribution']}.is_test = 0
252 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
253 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
254 AND {$this->_aliases['civicrm_email']}.is_primary = 1
255 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
256 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
257 {$this->_aliases['civicrm_phone']}.is_primary = 1
258 ";
259 }
260
261 function where() {
262 $clauses = array();
263 $this->_tempClause = $this->_outerCluase = '';
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 }
294 else {
295 $clauses[] = $clause;
296 }
297 }
298 }
299 }
300 }
301 if (empty($clauses)) {
302 $this->_where = "WHERE ( 1 ) ";
303 }
304 else {
305 $this->_where = "WHERE " . implode(' AND ', $clauses);
306 }
307
308 if ($this->_aclWhere) {
309 $this->_where .= " AND {$this->_aclWhere} ";
310 }
311 }
312
313 function groupBy() {
314 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_contact']}.id, {$this->_aliases['civicrm_contribution']}.currency";
315 }
316
317 function postProcess() {
318
319 $this->beginPostProcess();
320
321 // get the acl clauses built before we assemble the query
322 $this->buildACLClause($this->_aliases['civicrm_contact']);
323
324 $this->select();
325
326 $this->from();
327
328 $this->where();
329
330 $this->groupBy();
331
332 $this->limit();
333
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 function add2group($groupID) {
363 if (is_numeric($groupID)) {
364
365 $sql = "
366 {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
367 ORDER BY civicrm_contribution_total_amount_sum DESC
368 ) as abc {$this->_outerCluase}";
369 $dao = CRM_Core_DAO::executeQuery($sql);
370
371 $contact_ids = array();
372 // Add resulting contacts to group
373 while ($dao->fetch()) {
374 $contact_ids[$dao->civicrm_contact_id] = $dao->civicrm_contact_id;
375 }
376
377 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
378 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
379 }
380 }
381
382 function limit($rowCount = CRM_Report_Form::ROW_COUNT_LIMIT) {
383 // lets do the pager if in html mode
384 $this->_limit = NULL;
385 if ($this->_outputMode == 'html' || $this->_outputMode == 'group') {
386 //replace only first occurence of SELECT
387 $this->_select = preg_replace('/SELECT/', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select, 1);
388 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
389
390 if (!$pageId && !empty($_POST) && isset($_POST['crmPID_B'])) {
391 if (!isset($_POST['PagerBottomButton'])) {
392 unset($_POST['crmPID_B']);
393 }
394 else {
395 $pageId = max((int)@$_POST['crmPID_B'], 1);
396 }
397 }
398
399 $pageId = $pageId ? $pageId : 1;
400 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
401 $offset = ($pageId - 1) * $rowCount;
402
403 $this->_limit = " LIMIT $offset, " . $rowCount;
404 }
405 }
406
407 function alterDisplay(&$rows) {
408 // custom code to alter rows
409
410 $entryFound = FALSE;
411 $rank = 1;
412 if (!empty($rows)) {
413 foreach ($rows as $rowNum => $row) {
414
415 $rows[$rowNum]['civicrm_donor_rank'] = $rank++;
416 // convert display name to links
417 if (array_key_exists('civicrm_contact_display_name', $row) &&
418 array_key_exists('civicrm_contact_id', $row) &&
419 CRM_Utils_Array::value('civicrm_contribution_currency', $row)
420 ) {
421 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
422 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'] . "&currency_value=" . $row['civicrm_contribution_currency'],
423 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
424 );
425 $rows[$rowNum]['civicrm_contact_display_name_link'] = $url;
426 $entryFound = TRUE;
427 }
428
429 // skip looking further in rows, if first row itself doesn't
430 // have the column we need
431 if (!$entryFound) {
432 break;
433 }
434 }
435 }
436 }
437 }
438