3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
35 class CRM_Report_Form_Contribute_TopDonor
extends CRM_Report_Form
{
37 protected $_summary = NULL;
38 protected $_customGroupExtends = array(
44 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
46 protected $_charts = array(
48 'barChart' => 'Bar Chart',
49 'pieChart' => 'Pie Chart',
54 public function __construct() {
55 $this->_autoIncludeIndexedFieldsAsOrderBys
= 1;
56 $this->_columns
= array(
57 'civicrm_contact' => array(
58 'dao' => 'CRM_Contact_DAO_Contact',
60 'display_name' => array(
61 'title' => ts('Contact Name'),
65 'first_name' => array(
66 'title' => ts('First Name'),
68 'middle_name' => array(
69 'title' => ts('Middle Name'),
72 'title' => ts('Last Name'),
79 'title' => ts('Gender'),
81 'birth_date' => array(
82 'title' => ts('Birth Date'),
86 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
88 'contact_type' => array(
89 'title' => ts('Contact Type'),
91 'contact_sub_type' => array(
92 'title' => ts('Contact Subtype'),
97 'title' => ts('Gender'),
98 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
99 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
101 'contact_type' => array(
102 'title' => ts('Contact Type'),
104 'contact_sub_type' => array(
105 'title' => ts('Contact Subtype'),
110 $this->_columns +
= $this->getAddressColumns();
111 $this->_columns +
= array(
112 'civicrm_contribution' => array(
113 'dao' => 'CRM_Contribute_DAO_Contribution',
115 'total_amount' => array(
116 'title' => ts('Amount Statistics'),
118 'statistics' => array(
119 'sum' => ts('Aggregate Amount'),
120 'count' => ts('Donations'),
121 'avg' => ts('Average'),
126 'no_display' => TRUE,
130 'sort_name' => array(
131 'title' => ts('Participant Name'),
132 'operator' => 'like',
135 'title' => ts('Contact ID'),
136 'no_display' => TRUE,
138 'birth_date' => array(
139 'title' => ts('Birth Date'),
140 'operatorType' => CRM_Report_Form
::OP_DATE
,
142 'receive_date' => array(
143 'default' => 'this.year',
144 'operatorType' => CRM_Report_Form
::OP_DATE
,
147 'title' => 'Currency',
148 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
149 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
151 'type' => CRM_Utils_Type
::T_STRING
,
153 'total_range' => array(
154 'title' => ts('Show no. of Top Donors'),
155 'type' => CRM_Utils_Type
::T_INT
,
156 'default_op' => 'eq',
158 'financial_type_id' => array(
159 'name' => 'financial_type_id',
160 'title' => ts('Financial Type'),
161 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
162 'options' => CRM_Contribute_PseudoConstant
::financialType(),
164 'contribution_status_id' => array(
165 'title' => ts('Contribution Status'),
166 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
167 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
168 'default' => array(1),
172 'civicrm_email' => array(
173 'dao' => 'CRM_Core_DAO_Email',
176 'title' => ts('Email'),
181 'grouping' => 'email-fields',
183 'civicrm_phone' => array(
184 'dao' => 'CRM_Core_DAO_Phone',
187 'title' => ts('Phone'),
192 'grouping' => 'phone-fields',
196 $this->_groupFilter
= TRUE;
197 $this->_tagFilter
= TRUE;
198 $this->_currencyColumn
= 'civicrm_contribution_currency';
199 parent
::__construct();
202 public function preProcess() {
203 parent
::preProcess();
206 public function select() {
208 $this->_columnHeaders
= array();
209 //Headers for Rank column
210 $this->_columnHeaders
["civicrm_donor_rank"]['title'] = ts('Rank');
211 $this->_columnHeaders
["civicrm_donor_rank"]['type'] = 1;
212 //$select[] ="(@rank:=@rank+1) as civicrm_donor_rank ";
214 foreach ($this->_columns
as $tableName => $table) {
215 if (array_key_exists('fields', $table)) {
216 foreach ($table['fields'] as $fieldName => $field) {
217 if (!empty($field['required']) ||
218 !empty($this->_params
['fields'][$fieldName])
220 // only include statistics columns if set
221 if (!empty($field['statistics'])) {
222 foreach ($field['statistics'] as $stat => $label) {
223 switch (strtolower($stat)) {
225 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
226 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
227 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
228 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
232 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
233 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
234 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
235 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
239 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
240 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
241 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
242 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
248 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
249 // $field['type'] is not always set. Use string type as default if not set.
250 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = isset($field['type']) ?
$field['type'] : 2;
251 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'];
258 $this->_select
= " SELECT * FROM ( SELECT " . implode(', ', $select) . " ";
268 public static function formRule($fields, $files, $self) {
271 $op = CRM_Utils_Array
::value('total_range_op', $fields);
272 $val = CRM_Utils_Array
::value('total_range_value', $fields);
274 if (!in_array($op, array(
279 $errors['total_range_op'] = ts("Please select 'Is equal to' OR 'Is Less than or equal to' operator");
282 if ($val && !CRM_Utils_Rule
::positiveInteger($val)) {
283 $errors['total_range_value'] = ts("Please enter positive number");
288 public function from() {
290 FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
291 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
292 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND {$this->_aliases['civicrm_contribution']}.is_test = 0
293 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
294 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
295 AND {$this->_aliases['civicrm_email']}.is_primary = 1
296 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
297 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
298 {$this->_aliases['civicrm_phone']}.is_primary = 1
300 $this->addAddressFromClause();
303 public function where() {
305 $this->_tempClause
= $this->_outerCluase
= $this->_groupLimit
= '';
306 foreach ($this->_columns
as $tableName => $table) {
307 if (array_key_exists('filters', $table)) {
308 foreach ($table['filters'] as $fieldName => $field) {
310 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
311 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
312 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
313 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
315 if ($relative ||
$from ||
$to) {
316 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
320 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
322 $clause = $this->whereClause($field,
324 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
325 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
326 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
331 if (!empty($clause)) {
332 if ($fieldName == 'total_range') {
333 $value = CRM_Utils_Array
::value("total_range_value", $this->_params
);
334 $this->_outerCluase
= " WHERE (( @rows := @rows + 1) <= {$value}) ";
335 $this->_groupLimit
= " LIMIT {$value}";
338 $clauses[] = $clause;
344 if (empty($clauses)) {
345 $this->_where
= "WHERE ( 1 ) ";
348 $this->_where
= "WHERE " . implode(' AND ', $clauses);
351 if ($this->_aclWhere
) {
352 $this->_where
.= " AND {$this->_aclWhere} ";
356 public function groupBy() {
357 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contact']}.id, {$this->_aliases['civicrm_contribution']}.currency";
360 public function postProcess() {
362 $this->beginPostProcess();
364 // get the acl clauses built before we assemble the query
365 $this->buildACLClause($this->_aliases
['civicrm_contact']);
377 //set the variable value rank, rows = 0
378 $setVariable = " SET @rows:=0, @rank=0 ";
379 CRM_Core_DAO
::singleValueQuery($setVariable);
381 $sql = " {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
382 ORDER BY civicrm_contribution_total_amount_sum DESC
383 ) as abc {$this->_outerCluase} $this->_limit
386 $dao = CRM_Core_DAO
::executeQuery($sql);
388 while ($dao->fetch()) {
390 foreach ($this->_columnHeaders
as $key => $value) {
391 if (property_exists($dao, $key)) {
392 $row[$key] = $dao->$key;
397 $this->formatDisplay($rows);
399 $this->doTemplateAssignment($rows);
401 $this->endPostProcess($rows);
405 * @param int $groupID
407 public function add2group($groupID) {
408 if (is_numeric($groupID)) {
411 {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
412 ORDER BY civicrm_contribution_total_amount_sum DESC
413 ) as abc {$this->_groupLimit}";
414 $dao = CRM_Core_DAO
::executeQuery($sql);
416 $contact_ids = array();
417 // Add resulting contacts to group
418 while ($dao->fetch()) {
419 $contact_ids[$dao->civicrm_contact_id
] = $dao->civicrm_contact_id
;
422 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
423 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
428 * @param int $rowCount
430 public function limit($rowCount = CRM_Report_Form
::ROW_COUNT_LIMIT
) {
431 // lets do the pager if in html mode
432 $this->_limit
= NULL;
434 // CRM-14115, over-ride row count if rowCount is specified in URL
435 if ($this->_dashBoardRowCount
) {
436 $rowCount = $this->_dashBoardRowCount
;
438 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
439 // Replace only first occurrence of SELECT.
440 $this->_select
= preg_replace('/SELECT/', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
, 1);
441 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
443 if (!$pageId && !empty($_POST) && isset($_POST['crmPID_B'])) {
444 if (!isset($_POST['PagerBottomButton'])) {
445 unset($_POST['crmPID_B']);
448 $pageId = max((int) @$_POST['crmPID_B'], 1);
452 $pageId = $pageId ?
$pageId : 1;
453 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
454 $offset = ($pageId - 1) * $rowCount;
456 $offset = CRM_Utils_Type
::escape($offset, 'Int');
457 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
459 $this->_limit
= " LIMIT $offset, " . $rowCount;
464 * Alter display of rows.
466 * Iterate through the rows retrieved via SQL and make changes for display purposes,
467 * such as rendering contacts as links.
470 * Rows generated by SQL, with an array for each row.
472 public function alterDisplay(&$rows) {
476 foreach ($rows as $rowNum => $row) {
478 $rows[$rowNum]['civicrm_donor_rank'] = $rank++
;
479 // convert display name to links
480 if (array_key_exists('civicrm_contact_display_name', $row) &&
481 array_key_exists('civicrm_contact_id', $row) &&
482 !empty($row['civicrm_contribution_currency'])
484 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
485 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'] .
486 "¤cy_value=" . $row['civicrm_contribution_currency'],
487 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
489 $rows[$rowNum]['civicrm_contact_display_name_link'] = $url;
492 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ?
TRUE : $entryFound;
495 if (array_key_exists('civicrm_contact_gender_id', $row)) {
496 if ($value = $row['civicrm_contact_gender_id']) {
497 $gender = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id');
498 $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value];
503 // display birthday in the configured custom format
504 if (array_key_exists('civicrm_contact_birth_date', $row)) {
505 $birthDate = $row['civicrm_contact_birth_date'];
507 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date
::customFormat($birthDate, '%Y%m%d');
512 // skip looking further in rows, if first row itself doesn't
513 // have the column we need