3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
35 class CRM_Report_Form_Contribute_TopDonor
extends CRM_Report_Form
{
37 protected $_summary = NULL;
38 protected $_customGroupExtends = array(
45 * This report has not been optimised for group filtering.
47 * The functionality for group filtering has been improved but not
48 * all reports have been adjusted to take care of it. This report has not
49 * and will run an inefficient query until fixed.
55 protected $groupFilterNotOptimised = TRUE;
57 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
59 protected $_charts = array(
61 'barChart' => 'Bar Chart',
62 'pieChart' => 'Pie Chart',
67 public function __construct() {
68 $this->_autoIncludeIndexedFieldsAsOrderBys
= 1;
69 $this->_columns
= array(
70 'civicrm_contact' => array(
71 'dao' => 'CRM_Contact_DAO_Contact',
73 'display_name' => array(
74 'title' => ts('Contact Name'),
78 'first_name' => array(
79 'title' => ts('First Name'),
81 'middle_name' => array(
82 'title' => ts('Middle Name'),
85 'title' => ts('Last Name'),
92 'title' => ts('Gender'),
94 'birth_date' => array(
95 'title' => ts('Birth Date'),
99 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
101 'contact_type' => array(
102 'title' => ts('Contact Type'),
104 'contact_sub_type' => array(
105 'title' => ts('Contact Subtype'),
108 'filters' => $this->getBasicContactFilters(),
110 'civicrm_line_item' => array(
111 'dao' => 'CRM_Price_DAO_LineItem',
114 $this->_columns +
= $this->getAddressColumns();
115 $this->_columns +
= array(
116 'civicrm_contribution' => array(
117 'dao' => 'CRM_Contribute_DAO_Contribution',
119 'total_amount' => array(
120 'title' => ts('Amount Statistics'),
122 'statistics' => array(
123 'sum' => ts('Aggregate Amount'),
124 'count' => ts('Donations'),
125 'avg' => ts('Average'),
130 'no_display' => TRUE,
134 'receive_date' => array(
135 'default' => 'this.year',
136 'operatorType' => CRM_Report_Form
::OP_DATE
,
139 'title' => ts('Currency'),
140 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
141 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
143 'type' => CRM_Utils_Type
::T_STRING
,
145 'total_range' => array(
146 'title' => ts('Show no. of Top Donors'),
147 'type' => CRM_Utils_Type
::T_INT
,
148 'default_op' => 'eq',
150 'financial_type_id' => array(
151 'name' => 'financial_type_id',
152 'title' => ts('Financial Type'),
153 'type' => CRM_Utils_Type
::T_INT
,
154 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
155 'options' => CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes(),
157 'contribution_status_id' => array(
158 'title' => ts('Contribution Status'),
159 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
160 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
161 'default' => array(1),
165 'civicrm_financial_trxn' => array(
166 'dao' => 'CRM_Financial_DAO_FinancialTrxn',
168 'card_type' => array(
169 'title' => ts('Credit Card Type'),
170 'dbAlias' => 'GROUP_CONCAT(financial_trxn_civireport.card_type SEPARATOR ",")',
174 'card_type' => array(
175 'title' => ts('Credit Card Type'),
176 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
177 'options' => CRM_Financial_DAO_FinancialTrxn
::buildOptions('card_type'),
179 'type' => CRM_Utils_Type
::T_STRING
,
183 'civicrm_email' => array(
184 'dao' => 'CRM_Core_DAO_Email',
187 'title' => ts('Email'),
192 'grouping' => 'email-fields',
194 'civicrm_phone' => array(
195 'dao' => 'CRM_Core_DAO_Phone',
198 'title' => ts('Phone'),
203 'grouping' => 'phone-fields',
207 $this->_groupFilter
= TRUE;
208 $this->_tagFilter
= TRUE;
209 $this->_currencyColumn
= 'civicrm_contribution_currency';
210 parent
::__construct();
213 public function preProcess() {
214 parent
::preProcess();
217 public function select() {
219 $this->_columnHeaders
= array();
220 //Headers for Rank column
221 $this->_columnHeaders
["civicrm_donor_rank"]['title'] = ts('Rank');
222 $this->_columnHeaders
["civicrm_donor_rank"]['type'] = 1;
223 //$select[] ="(@rank:=@rank+1) as civicrm_donor_rank ";
225 foreach ($this->_columns
as $tableName => $table) {
226 if (array_key_exists('fields', $table)) {
227 foreach ($table['fields'] as $fieldName => $field) {
228 if (!empty($field['required']) ||
229 !empty($this->_params
['fields'][$fieldName])
231 // only include statistics columns if set
232 if (!empty($field['statistics'])) {
233 foreach ($field['statistics'] as $stat => $label) {
234 switch (strtolower($stat)) {
236 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
237 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
238 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
239 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
243 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
244 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
245 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
246 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
250 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
251 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
252 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
253 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
259 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
260 // $field['type'] is not always set. Use string type as default if not set.
261 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = isset($field['type']) ?
$field['type'] : 2;
262 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'];
268 $this->_selectClauses
= $select;
270 $this->_select
= " SELECT " . implode(', ', $select) . " ";
280 public static function formRule($fields, $files, $self) {
283 $op = CRM_Utils_Array
::value('total_range_op', $fields);
284 $val = CRM_Utils_Array
::value('total_range_value', $fields);
286 if (!in_array($op, array(
291 $errors['total_range_op'] = ts("Please select 'Is equal to' OR 'Is Less than or equal to' operator");
294 if ($val && !CRM_Utils_Rule
::positiveInteger($val)) {
295 $errors['total_range_value'] = ts("Please enter positive number");
300 public function from() {
302 FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
303 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
304 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND {$this->_aliases['civicrm_contribution']}.is_test = 0
305 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
306 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
307 AND {$this->_aliases['civicrm_email']}.is_primary = 1
308 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
309 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
310 {$this->_aliases['civicrm_phone']}.is_primary = 1";
312 // for credit card type
313 $this->addFinancialTrxnFromClause();
315 $this->addAddressFromClause();
318 public function where() {
320 $this->_tempClause
= $this->_outerCluase
= $this->_groupLimit
= '';
321 foreach ($this->_columns
as $tableName => $table) {
322 if (array_key_exists('filters', $table)) {
323 foreach ($table['filters'] as $fieldName => $field) {
325 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
326 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
327 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
328 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
330 if ($relative ||
$from ||
$to) {
331 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
335 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
337 $clause = $this->whereClause($field,
339 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
340 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
341 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
346 if (!empty($clause)) {
347 if ($fieldName == 'total_range') {
348 $value = CRM_Utils_Array
::value("total_range_value", $this->_params
);
349 $this->_outerCluase
= " WHERE (( @rows := @rows + 1) <= {$value}) ";
350 $this->_groupLimit
= " LIMIT {$value}";
353 $clauses[] = $clause;
359 if (empty($clauses)) {
360 $this->_where
= "WHERE ( 1 ) ";
363 $this->_where
= "WHERE " . implode(' AND ', $clauses);
366 if ($this->_aclWhere
) {
367 $this->_where
.= " AND {$this->_aclWhere} ";
371 public function groupBy() {
372 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, array("{$this->_aliases['civicrm_contact']}.id", "{$this->_aliases['civicrm_contribution']}.currency"));
375 public function postProcess() {
377 $this->beginPostProcess();
379 // get the acl clauses built before we assemble the query
380 $this->buildACLClause($this->_aliases
['civicrm_contact']);
384 //set the variable value rank, rows = 0
385 $setVariable = " SET @rows:=0, @rank=0 ";
386 CRM_Core_DAO
::singleValueQuery($setVariable);
388 $sql = "SELECT * FROM ( {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
389 ORDER BY civicrm_contribution_total_amount_sum DESC
390 ) as abc {$this->_outerCluase} $this->_limit
393 $dao = CRM_Core_DAO
::executeQuery($sql);
395 while ($dao->fetch()) {
397 foreach ($this->_columnHeaders
as $key => $value) {
398 if (property_exists($dao, $key)) {
399 $row[$key] = $dao->$key;
404 $this->formatDisplay($rows);
406 $this->doTemplateAssignment($rows);
408 $this->endPostProcess($rows);
412 * @param int $groupID
414 public function add2group($groupID) {
415 if (is_numeric($groupID)) {
418 {$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}
419 ORDER BY civicrm_contribution_total_amount_sum DESC
420 ) as abc {$this->_groupLimit}";
421 $dao = CRM_Core_DAO
::executeQuery($sql);
423 $contact_ids = array();
424 // Add resulting contacts to group
425 while ($dao->fetch()) {
426 $contact_ids[$dao->civicrm_contact_id
] = $dao->civicrm_contact_id
;
429 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
430 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
435 * @param int $rowCount
437 public function limit($rowCount = CRM_Report_Form
::ROW_COUNT_LIMIT
) {
438 // lets do the pager if in html mode
439 $this->_limit
= NULL;
441 // CRM-14115, over-ride row count if rowCount is specified in URL
442 if ($this->_dashBoardRowCount
) {
443 $rowCount = $this->_dashBoardRowCount
;
445 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
446 // Replace only first occurrence of SELECT.
447 $this->_select
= preg_replace('/SELECT/', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
, 1);
448 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
450 if (!$pageId && !empty($_POST) && isset($_POST['crmPID_B'])) {
451 if (!isset($_POST['PagerBottomButton'])) {
452 unset($_POST['crmPID_B']);
455 $pageId = max((int) @$_POST['crmPID_B'], 1);
459 $pageId = $pageId ?
$pageId : 1;
460 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
461 $offset = ($pageId - 1) * $rowCount;
463 $offset = CRM_Utils_Type
::escape($offset, 'Int');
464 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
466 $this->_limit
= " LIMIT $offset, " . $rowCount;
471 * Alter display of rows.
473 * Iterate through the rows retrieved via SQL and make changes for display purposes,
474 * such as rendering contacts as links.
477 * Rows generated by SQL, with an array for each row.
479 public function alterDisplay(&$rows) {
483 foreach ($rows as $rowNum => $row) {
485 $rows[$rowNum]['civicrm_donor_rank'] = $rank++
;
486 // convert display name to links
487 if (array_key_exists('civicrm_contact_display_name', $row) &&
488 array_key_exists('civicrm_contact_id', $row) &&
489 !empty($row['civicrm_contribution_currency'])
491 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
492 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'] .
493 "¤cy_value=" . $row['civicrm_contribution_currency'],
494 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
496 $rows[$rowNum]['civicrm_contact_display_name_link'] = $url;
499 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ?
TRUE : $entryFound;
502 if (array_key_exists('civicrm_contact_gender_id', $row)) {
503 if ($value = $row['civicrm_contact_gender_id']) {
504 $gender = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id');
505 $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value];
510 // display birthday in the configured custom format
511 if (array_key_exists('civicrm_contact_birth_date', $row)) {
512 $birthDate = $row['civicrm_contact_birth_date'];
514 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date
::customFormat($birthDate, '%Y%m%d');
519 if (!empty($row['civicrm_financial_trxn_card_type'])) {
520 $rows[$rowNum]['civicrm_financial_trxn_card_type'] = $this->getLabels($row['civicrm_financial_trxn_card_type'], 'CRM_Financial_DAO_FinancialTrxn', 'card_type');
524 // skip looking further in rows, if first row itself doesn't
525 // have the column we need