3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
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-2020
33 class CRM_Report_Form_Contribute_Lybunt
extends CRM_Report_Form
{
35 protected $_charts = [
37 'barChart' => 'Bar Chart',
38 'pieChart' => 'Pie Chart',
42 * This is the report that links will lead to.
44 * It is a bit problematic to use contribute/detail for anything other than a single contact
45 * as the filtering from this report does not carry over to that report.
49 public $_drilldownReport = ['contribute/detail' => 'Link to Detail Report'];
51 protected $lifeTime_from = NULL;
52 protected $lifeTime_where = NULL;
53 protected $_customGroupExtends = [
61 * Table containing list of contact IDs.
65 protected $contactTempTable = '';
68 * This report has been optimised for group filtering.
74 protected $groupFilterNotOptimised = FALSE;
79 public function __construct() {
80 $this->optimisedForOnlyFullGroupBy
= FALSE;
81 $this->_rollup
= 'WITH ROLLUP';
82 $this->_autoIncludeIndexedFieldsAsOrderBys
= 1;
85 $date = CRM_Core_SelectValues
::date('custom', NULL, $yearsInPast, $yearsInFuture);
86 $count = $date['maxYear'];
87 while ($date['minYear'] <= $count) {
88 $optionYear[$date['minYear']] = $date['minYear'];
93 'civicrm_contact' => [
94 'dao' => 'CRM_Contact_DAO_Contact',
95 'grouping' => 'contact-field',
96 'fields' => $this->getBasicContactFields(),
99 'title' => ts('Last Name, First Name'),
101 'default_order' => 'ASC',
104 'name' => 'first_name',
105 'title' => ts('First Name'),
108 'name' => 'gender_id',
109 'title' => ts('Gender'),
112 'name' => 'birth_date',
113 'title' => ts('Birth Date'),
116 'title' => ts('Contact Type'),
118 'contact_sub_type' => [
119 'title' => ts('Contact Subtype'),
124 'title' => ts('Donor Name'),
125 'operator' => 'like',
128 'title' => ts('Contact ID'),
129 'no_display' => TRUE,
132 'title' => ts('Gender'),
133 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
134 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
137 'title' => ts('Birth Date'),
138 'operatorType' => CRM_Report_Form
::OP_DATE
,
141 'title' => ts('Contact Type'),
143 'contact_sub_type' => [
144 'title' => ts('Contact Subtype'),
147 'do_not_phone' => [],
148 'do_not_email' => [],
154 'civicrm_line_item' => [
155 'dao' => 'CRM_Price_DAO_LineItem',
158 'dao' => 'CRM_Core_DAO_Email',
159 'grouping' => 'contact-field',
162 'title' => ts('Email'),
166 'title' => ts('Email on hold'),
171 'dao' => 'CRM_Core_DAO_Phone',
172 'grouping' => 'contact-field',
175 'title' => ts('Phone'),
181 $this->_columns +
= $this->addAddressFields(FALSE);
183 'civicrm_contribution' => [
184 'dao' => 'CRM_Contribute_DAO_Contribution',
187 'title' => ts('contactId'),
188 'no_display' => TRUE,
193 'title' => ts('Year'),
194 'no_display' => TRUE,
198 'last_year_total_amount' => [
199 'title' => ts('Last Year Total'),
201 'type' => CRM_Utils_Type
::T_MONEY
,
204 'civicrm_life_time_total' => [
205 'title' => ts('Lifetime Total'),
207 'type' => CRM_Utils_Type
::T_MONEY
,
208 'statistics' => ['sum' => ts('Lifetime total')],
213 'name' => 'receive_date',
214 'title' => ts('This Year'),
215 'operatorType' => CRM_Report_Form
::OP_SELECT
,
216 'options' => $optionYear,
217 'default' => date('Y'),
218 'type' => CRM_Utils_Type
::T_INT
,
220 'financial_type_id' => [
221 'title' => ts('Financial Type'),
222 'type' => CRM_Utils_Type
::T_INT
,
223 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
224 'options' => CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes(),
226 'contribution_status_id' => [
227 'title' => ts('Contribution Status'),
228 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
229 'options' => CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'search'),
234 'last_year_total_amount' => [
235 'title' => ts('Total amount last year'),
237 'default_weight' => '0',
238 'default_order' => 'DESC',
244 'civicrm_financial_trxn' => [
245 'dao' => 'CRM_Financial_DAO_FinancialTrxn',
248 'title' => ts('Credit Card Type'),
249 'dbAlias' => 'GROUP_CONCAT(financial_trxn_civireport.card_type_id SEPARATOR ",")',
254 'title' => ts('Credit Card Type'),
255 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
256 'options' => CRM_Financial_DAO_FinancialTrxn
::buildOptions('card_type_id'),
258 'type' => CRM_Utils_Type
::T_STRING
,
264 // If we have a campaign, build out the relevant elements
265 $this->addCampaignFields('civicrm_contribution');
267 $this->_groupFilter
= TRUE;
268 $this->_tagFilter
= TRUE;
269 parent
::__construct();
273 * Build select clause for a single field.
275 * @param string $tableName
276 * @param string $tableKey
277 * @param string $fieldName
278 * @param string $field
282 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
283 if ($fieldName == 'last_year_total_amount') {
284 $this->_columnHeaders
["{$tableName}_{$fieldName}"] = $field;
285 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $this->getLastYearColumnTitle();
286 $this->_statFields
[$this->getLastYearColumnTitle()] = "{$tableName}_{$fieldName}";
287 return "SUM(IF(" . $this->whereClauseLastYear('contribution_civireport.receive_date') . ", contribution_civireport.total_amount, 0)) as {$tableName}_{$fieldName}";
289 if ($fieldName == 'civicrm_life_time_total') {
290 $this->_columnHeaders
["{$tableName}_{$fieldName}"] = $field;
291 $this->_statFields
[$field['title']] = "{$tableName}_{$fieldName}";
292 return "SUM({$this->_aliases[$tableName]}.total_amount) as {$tableName}_{$fieldName}";
294 if ($fieldName == 'receive_date') {
295 return self
::fiscalYearOffset($field['dbAlias']) .
296 " as {$tableName}_{$fieldName} ";
302 * Get the title for the last year column.
304 public function getLastYearColumnTitle() {
305 if ($this->getYearFilterType() == 'calendar') {
306 return ts('Total for ') . ($this->getCurrentYear() - 1);
308 return ts('Total for Fiscal Year ') . ($this->getCurrentYear() - 1) . '-' . ($this->getCurrentYear());
312 * Construct from clause.
314 * On the first run we are creating a table of contacts to include in the report.
316 * Once contactTempTable is populated we should avoid using any further filters that affect
317 * the contacts that should be visible.
319 public function from() {
320 if (!empty($this->contactTempTable
)) {
322 FROM civicrm_contribution {$this->_aliases['civicrm_contribution']}
323 INNER JOIN $this->contactTempTable restricted_contacts
324 ON restricted_contacts.cid = {$this->_aliases['civicrm_contribution']}.contact_id
325 AND {$this->_aliases['civicrm_contribution']}.is_test = 0
326 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
327 ON restricted_contacts.cid = {$this->_aliases['civicrm_contact']}.id";
329 $this->joinAddressFromContact();
330 $this->joinPhoneFromContact();
331 $this->joinEmailFromContact();
334 $this->setFromBase('civicrm_contact');
336 $this->_from
.= " INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']} ";
337 if (!$this->groupTempTable
) {
338 // The received_date index is better than the contribution_status_id index (fairly substantially).
339 // But if we have already pre-filtered down to a group of contacts then we want that to be the
340 // primary filter and the index hint will block that.
341 $this->_from
.= "USE index (received_date)";
343 $this->_from
.= " ON {$this->_aliases['civicrm_contribution']}.contact_id = {$this->_aliases['civicrm_contact']}.id
344 AND {$this->_aliases['civicrm_contribution']}.is_test = 0
345 AND " . $this->whereClauseLastYear("{$this->_aliases['civicrm_contribution']}.receive_date") . "
347 $this->selectivelyAddLocationTablesJoinsToFilterQuery();
350 // for credit card type
351 $this->addFinancialTrxnFromClause();
355 * Generate where clause.
357 * We are overriding this primarily for 'before-after' handling of the receive_date placeholder field.
359 * We call this twice. The first time we are generating a temp table and we want to do an IS NULL on the
360 * join that draws in contributions from this year. The second time we are filtering elsewhere (contacts via
361 * the temp table & contributions via selective addition of contributions in the select function).
363 * If lifetime total is NOT selected we can add a further filter here to possibly improve performance
364 * but the benefit if unproven as yet.
365 * $clause = $this->whereClauseLastYear("{$this->_aliases['civicrm_contribution']}.receive_date");
367 * @param array $field Field specifications
368 * @param string $op Query operator (not an exact match to sql)
369 * @param mixed $value
373 * @return null|string
375 public function whereClause(&$field, $op, $value, $min, $max) {
376 if ($field['name'] == 'receive_date') {
378 if (empty($this->contactTempTable
)) {
379 $clause = "{$this->_aliases['civicrm_contact']}.id NOT IN (
380 SELECT cont_exclude.contact_id
381 FROM civicrm_contribution cont_exclude
382 WHERE " . $this->whereClauseThisYear('cont_exclude.receive_date')
386 // Group filtering is already done so skip.
387 elseif (!empty($field['group']) && $this->contactTempTable
) {
391 $clause = parent
::whereClause($field, $op, $value, $min, $max);
397 * Generate where clause for last calendar year or fiscal year.
399 * @todo must be possible to re-use relative dates stuff.
401 * @param string $fieldName
405 public function whereClauseLastYear($fieldName) {
406 return "$fieldName BETWEEN '" . $this->getFirstDateOfPriorRange() . "' AND '" . $this->getLastDateOfPriorRange() . "'";
410 * Generate where clause for last calendar year or fiscal year.
412 * @todo must be possible to re-use relative dates stuff.
414 * @param string $fieldName
416 * @param int $current_year
417 * @return null|string
419 public function whereClauseThisYear($fieldName, $current_year = NULL) {
420 return "$fieldName BETWEEN '" . $this->getFirstDateOfCurrentRange() . "' AND '" . $this->getLastDateOfCurrentRange() . "'";
424 * Get the year value for the current year.
428 public function getCurrentYear() {
429 return $this->_params
['yid_value'];
433 * Get the date time of the first date in the 'this year' range.
437 public function getFirstDateOfCurrentRange() {
438 $current_year = $this->getCurrentYear();
439 if ($this->getYearFilterType() == 'calendar') {
440 return "{$current_year }-01-01";
443 $fiscalYear = CRM_Core_Config
::singleton()->fiscalYearStart
;
444 return "{$current_year}-{$fiscalYear['M']}-{$fiscalYear['d']}";
449 * Get the year value for the current year.
453 public function getYearFilterType() {
454 return CRM_Utils_Array
::value('yid_op', $this->_params
, 'calendar');
458 * Get the date time of the last date in the 'this year' range.
462 public function getLastDateOfCurrentRange() {
463 return date('YmdHis', strtotime('+ 1 year - 1 second', strtotime($this->getFirstDateOfCurrentRange())));
467 * Get the date time of the first date in the 'last year' range.
471 public function getFirstDateOfPriorRange() {
472 return date('YmdHis', strtotime('- 1 year', strtotime($this->getFirstDateOfCurrentRange())));
476 * Get the date time of the last date in the 'last year' range.
480 public function getLastDateOfPriorRange() {
481 return date('YmdHis', strtotime('+ 1 year - 1 second', strtotime($this->getFirstDateOfPriorRange())));
484 public function groupBy() {
485 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contribution']}.contact_id ";
486 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($this->_selectClauses
, "{$this->_aliases['civicrm_contribution']}.contact_id");
487 $this->assign('chartSupported', TRUE);
495 public function statistics(&$rows) {
497 $statistics = parent
::statistics($rows);
498 // The parent class does something odd where it adds an extra row to the count for the grand total.
499 // Perhaps that works on some other report? But here it just seems odd.
500 $this->countStat($statistics, count($rows));
502 if (!empty($this->rollupRow
) && !empty($this->rollupRow
['civicrm_contribution_last_year_total_amount'])) {
503 $statistics['counts']['civicrm_contribution_last_year_total_amount'] = [
504 'value' => $this->rollupRow
['civicrm_contribution_last_year_total_amount'],
505 'title' => $this->getLastYearColumnTitle(),
506 'type' => CRM_Utils_Type
::T_MONEY
,
510 if (!empty($this->rollupRow
) && !empty($this->rollupRow
['civicrm_contribution_civicrm_life_time_total'])) {
511 $statistics['counts']['civicrm_contribution_civicrm_life_time_total'] = [
512 'value' => $this->rollupRow
['civicrm_contribution_civicrm_life_time_total'],
513 'title' => ts('Total LifeTime'),
514 'type' => CRM_Utils_Type
::T_MONEY
,
518 $select = "SELECT SUM({$this->_aliases['civicrm_contribution']}.total_amount) as amount,
519 SUM(IF( " . $this->whereClauseLastYear('contribution_civireport.receive_date') . ", contribution_civireport.total_amount, 0)) as last_year
521 $sql = "{$select} {$this->_from} {$this->_where}";
522 $dao = CRM_Core_DAO
::executeQuery($sql);
524 $statistics['counts']['amount'] = [
525 'value' => $dao->amount
,
526 'title' => ts('Total LifeTime'),
527 'type' => CRM_Utils_Type
::T_MONEY
,
529 $statistics['counts']['last_year'] = [
530 'value' => $dao->last_year
,
531 'title' => $this->getLastYearColumnTitle(),
532 'type' => CRM_Utils_Type
::T_MONEY
,
542 * This function is called by both the api (tests) and the UI.
544 public function beginPostProcessCommon() {
546 // @todo this acl has no test coverage and is very hard to test manually so could be fragile.
547 $this->resetFormSqlAndWhereHavingClauses();
549 $this->contactTempTable
= $this->createTemporaryTable('rptlybunt', "
550 SELECT SQL_CALC_FOUND_ROWS {$this->_aliases['civicrm_contact']}.id as cid {$this->_from}
552 GROUP BY {$this->_aliases['civicrm_contact']}.id"
555 if (empty($this->_params
['charts'])) {
559 // Reset where clauses to be regenerated in postProcess.
560 $this->_whereClauses
= [];
564 * Build the report query.
566 * The issue we are hitting is that if we want to do group by & then ORDER BY we have to
567 * wrap the query in an outer query with the order by - otherwise the group by takes precedent.
568 * This is an issue when we want to group by contact but order by the maximum aggregate donation.
570 * @param bool $applyLimit
574 public function buildQuery($applyLimit = TRUE) {
575 $this->buildGroupTempTable();
576 $this->buildPermissionClause();
577 // Calling where & select before FROM allows us to build temp tables to use in from.
581 $this->customDataFrom(empty($this->contactTempTable
));
587 // order_by columns not selected for display need to be included in SELECT
588 // This differs from parent in that we are getting those not in order by rather than not in
589 // sections, as we need to adapt to our contact group by.
590 $unselectedSectionColumns = array_diff_key($this->_orderByFields
, $this->getSelectColumns());
591 foreach ($unselectedSectionColumns as $alias => $section) {
592 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
595 if ($applyLimit && empty($this->_params
['charts'])) {
599 $sql = "{$this->_select} {$this->_from} {$this->_where} {$limitFilter} {$this->_groupBy} {$this->_having} {$this->_rollup}";
601 if (!empty($this->_orderByArray
)) {
602 $this->_orderBy
= str_replace('contact_civireport.', 'civicrm_contact_', "ORDER BY ISNULL(civicrm_contribution_contact_id), " . implode(', ', $this->_orderByArray
));
603 $this->_orderBy
= str_replace('contribution_civireport.', 'civicrm_contribution_', $this->_orderBy
);
604 foreach ($this->_orderByFields
as $field) {
605 $this->_orderBy
= str_replace($field['dbAlias'], $field['tplField'], $this->_orderBy
);
607 $sql = str_replace('SQL_CALC_FOUND_ROWS', '', $sql);
608 $sql = "SELECT SQL_CALC_FOUND_ROWS * FROM ( $sql ) as inner_query {$this->_orderBy} $this->_limit";
611 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
612 $this->addToDeveloperTab($sql);
618 * Reset the form sql and where / having clause arrays.
620 * We do an early iteration of the report queries to generate the temp table.
622 * However, that iteration populates the sql for the developer tab,
623 * the whereClauses & the havingClauses and they are populated again in the normal
624 * report flow. This is harmless but confusing - ie. the where clause winds up repeating
625 * the same filters and the dev tab shows the query twice, so we rest them.
627 protected function resetFormSqlAndWhereHavingClauses() {
629 $this->_havingClauses
= [];
630 $this->_whereClauses
= [];
631 $this->sqlArray
= [];
637 public function buildChart(&$rows) {
643 $current_year = $this->_params
['yid_value'];
644 $previous_year = $current_year - 1;
645 $interval[$previous_year] = $previous_year;
646 $interval['life_time'] = 'Life Time';
648 foreach ($rows as $key => $row) {
649 $display['life_time'] = CRM_Utils_Array
::value('life_time', $display) +
650 $row['civicrm_life_time_total'];
651 $display[$previous_year] = CRM_Utils_Array
::value($previous_year, $display) +
$row[$previous_year];
654 $config = CRM_Core_Config
::Singleton();
655 $graphRows['value'] = $display;
657 'legend' => ts('Lybunt Report'),
658 'xname' => ts('Year'),
659 'yname' => ts('Amount (%1)', [1 => $config->defaultCurrency
]),
661 if ($this->_params
['charts']) {
663 CRM_Utils_Chart
::reportChart($graphRows, $this->_params
['charts'], $interval, $chartInfo);
664 $this->assign('chartType', $this->_params
['charts']);
669 * Alter display of rows.
671 * Iterate through the rows retrieved via SQL and make changes for display purposes,
672 * such as rendering contacts as links.
675 * Rows generated by SQL, with an array for each row.
677 public function alterDisplay(&$rows) {
680 foreach ($rows as $rowNum => $row) {
681 //Convert Display name into link
682 if (array_key_exists('civicrm_contact_sort_name', $row) &&
683 array_key_exists('civicrm_contribution_contact_id', $row)
685 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
686 'reset=1&force=1&id_op=eq&id_value=' .
687 $row['civicrm_contribution_contact_id'],
688 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
690 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
691 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
695 // convert campaign_id to campaign title
696 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
697 if ($value = $row['civicrm_contribution_campaign_id']) {
698 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->campaigns
[$value];
702 // Display 'Yes' if the email is on hold (leave blank for no so it stands out better).
703 if (array_key_exists('civicrm_email_on_hold', $row)) {
704 $rows[$rowNum]['civicrm_email_on_hold'] = $row['civicrm_email_on_hold'] ?
ts('Yes') : '';
708 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, NULL, 'List all contribution(s)') ?
TRUE : $entryFound;
709 $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, NULL, 'List all contribution(s)') ?
TRUE : $entryFound;
711 if (!empty($row['civicrm_financial_trxn_card_type_id'])) {
712 $rows[$rowNum]['civicrm_financial_trxn_card_type_id'] = $this->getLabels($row['civicrm_financial_trxn_card_type_id'], 'CRM_Financial_DAO_FinancialTrxn', 'card_type_id');
716 // skip looking further in rows, if first row itself doesn't
717 // have the column we need
725 * Override "This Year" $op options
726 * @param string $type
727 * @param null $fieldName
731 public function getOperationPair($type = "string", $fieldName = NULL) {
732 if ($fieldName == 'yid') {
734 'calendar' => ts('Is Calendar Year'),
735 'fiscal' => ts('Fiscal Year Starting'),
738 return parent
::getOperationPair($type, $fieldName);