3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
33 class CRM_Report_Form_Contribute_Sybunt
extends CRM_Report_Form
{
35 protected $_charts = array(
37 'barChart' => 'Bar Chart',
38 'pieChart' => 'Pie Chart',
41 protected $_customGroupExtends = array(
47 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
50 * This report has been optimised for group filtering.
56 protected $groupFilterNotOptimised = FALSE;
61 public function __construct() {
62 $this->_rollup
= 'WITH ROLLUP';
63 $this->_autoIncludeIndexedFieldsAsOrderBys
= 1;
66 $date = CRM_Core_SelectValues
::date('custom', NULL, $yearsInPast, $yearsInFuture);
67 $count = $date['maxYear'];
68 while ($date['minYear'] <= $count) {
69 $optionYear[$date['minYear']] = $date['minYear'];
73 // Check if CiviCampaign is a) enabled and b) has active campaigns
74 $config = CRM_Core_Config
::singleton();
75 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents
);
76 if ($campaignEnabled) {
77 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
78 $this->activeCampaigns
= $getCampaigns['campaigns'];
79 asort($this->activeCampaigns
);
82 $this->_columns
= array(
83 'civicrm_contact' => array(
84 'dao' => 'CRM_Contact_DAO_Contact',
85 'grouping' => 'contact-field',
88 'title' => ts('Donor Name'),
91 'first_name' => array(
92 'title' => ts('First Name'),
94 'middle_name' => array(
95 'title' => ts('Middle Name'),
98 'title' => ts('Last Name'),
101 'no_display' => TRUE,
104 'gender_id' => array(
105 'title' => ts('Gender'),
107 'birth_date' => array(
108 'title' => ts('Birth Date'),
111 'title' => ts('Age'),
112 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
114 'contact_type' => array(
115 'title' => ts('Contact Type'),
117 'contact_sub_type' => array(
118 'title' => ts('Contact Subtype'),
121 'order_bys' => array(
122 'sort_name' => array(
123 'title' => ts('Last Name, First Name'),
125 'default_weight' => '0',
126 'default_order' => 'ASC',
128 'first_name' => array(
129 'name' => 'first_name',
130 'title' => ts('First Name'),
132 'gender_id' => array(
133 'name' => 'gender_id',
134 'title' => ts('Gender'),
136 'birth_date' => array(
137 'name' => 'birth_date',
138 'title' => ts('Birth Date'),
140 'age_at_event' => array(
141 'name' => 'age_at_event',
142 'title' => ts('Age at Event'),
144 'contact_type' => array(
145 'title' => ts('Contact Type'),
147 'contact_sub_type' => array(
148 'title' => ts('Contact Subtype'),
152 'sort_name' => array(
153 'title' => ts('Donor Name'),
154 'operator' => 'like',
157 'title' => ts('Contact ID'),
158 'no_display' => TRUE,
160 'gender_id' => array(
161 'title' => ts('Gender'),
162 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
163 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
165 'birth_date' => array(
166 'title' => ts('Birth Date'),
167 'operatorType' => CRM_Report_Form
::OP_DATE
,
169 'contact_type' => array(
170 'title' => ts('Contact Type'),
172 'contact_sub_type' => array(
173 'title' => ts('Contact Subtype'),
177 'civicrm_line_item' => array(
178 'dao' => 'CRM_Price_DAO_LineItem',
180 'civicrm_email' => array(
181 'dao' => 'CRM_Core_DAO_Email',
182 'grouping' => 'contact-field',
185 'title' => ts('Email'),
190 'civicrm_phone' => array(
191 'dao' => 'CRM_Core_DAO_Phone',
192 'grouping' => 'contact-field',
195 'title' => ts('Phone'),
201 $this->_columns +
= $this->addAddressFields();
202 $this->_columns +
= array(
203 'civicrm_contribution' => array(
204 'dao' => 'CRM_Contribute_DAO_Contribution',
206 'contact_id' => array(
207 'title' => ts('contactId'),
208 'no_display' => TRUE,
212 'total_amount' => array(
213 'title' => ts('Total Amount'),
214 'no_display' => TRUE,
218 'receive_date' => array(
219 'title' => ts('Year'),
220 'no_display' => TRUE,
227 'name' => 'receive_date',
228 'title' => ts('This Year'),
229 'operatorType' => CRM_Report_Form
::OP_SELECT
,
230 'options' => $optionYear,
231 'default' => date('Y'),
232 'type' => CRM_Utils_Type
::T_INT
,
234 'financial_type_id' => array(
235 'title' => ts('Financial Type'),
236 'type' => CRM_Utils_Type
::T_INT
,
237 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
238 'options' => CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes(),
240 'contribution_status_id' => array(
241 'title' => ts('Contribution Status'),
242 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
243 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
244 'default' => array('1'),
249 $this->_columns +
= array(
250 'civicrm_financial_trxn' => array(
251 'dao' => 'CRM_Financial_DAO_FinancialTrxn',
253 'card_type_id' => array(
254 'title' => ts('Credit Card Type'),
255 'dbAlias' => 'GROUP_CONCAT(financial_trxn_civireport.card_type_id SEPARATOR ",")',
259 'card_type_id' => array(
260 'title' => ts('Credit Card Type'),
261 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
263 'options' => CRM_Financial_DAO_FinancialTrxn
::buildOptions('card_type_id'),
264 'type' => CRM_Utils_Type
::T_STRING
,
270 // If we have a campaign, build out the relevant elements
271 if ($campaignEnabled && !empty($this->activeCampaigns
)) {
272 $this->_columns
['civicrm_contribution']['fields']['campaign_id'] = array(
273 'title' => ts('Campaign'),
274 'default' => 'false',
276 $this->_columns
['civicrm_contribution']['filters']['campaign_id'] = array(
277 'title' => ts('Campaign'),
278 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
279 'options' => $this->activeCampaigns
,
280 'type' => CRM_Utils_Type
::T_INT
,
284 $this->_groupFilter
= TRUE;
285 $this->_tagFilter
= TRUE;
286 parent
::__construct();
289 public function preProcess() {
290 parent
::preProcess();
293 public function select() {
295 $this->_columnHeaders
= array();
296 $current_year = $this->_params
['yid_value'];
297 $previous_year = $current_year - 1;
298 $previous_pyear = $current_year - 2;
299 $previous_ppyear = $current_year - 3;
300 $upTo_year = $current_year - 4;
302 foreach ($this->_columns
as $tableName => $table) {
303 if (array_key_exists('fields', $table)) {
304 foreach ($table['fields'] as $fieldName => $field) {
306 if (!empty($field['required']) ||
307 !empty($this->_params
['fields'][$fieldName])
309 if ($fieldName == 'total_amount') {
310 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}";
312 $this->_columnHeaders
["civicrm_upto_{$upTo_year}"]['type'] = $field['type'];
313 $this->_columnHeaders
["civicrm_upto_{$upTo_year}"]['title'] = ts("Up To %1", array(1 => $upTo_year));
315 $this->_columnHeaders
["year_{$previous_ppyear}"]['type'] = $field['type'];
316 $this->_columnHeaders
["year_{$previous_ppyear}"]['title'] = $previous_ppyear;
318 $this->_columnHeaders
["year_{$previous_pyear}"]['type'] = $field['type'];
319 $this->_columnHeaders
["year_{$previous_pyear}"]['title'] = $previous_pyear;
321 $this->_columnHeaders
["year_{$previous_year}"]['type'] = $field['type'];
322 $this->_columnHeaders
["year_{$previous_year}"]['title'] = $previous_year;
324 $this->_columnHeaders
["civicrm_life_time_total"]['type'] = $field['type'];
325 $this->_columnHeaders
["civicrm_life_time_total"]['title'] = ts('LifeTime');
327 elseif ($fieldName == 'receive_date') {
328 $select[] = self
::fiscalYearOffset($field['dbAlias']) .
329 " as {$tableName}_{$fieldName}";
332 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
333 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
334 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'];
336 if (!empty($field['no_display'])) {
337 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['no_display'] = TRUE;
343 $this->_selectClauses
= $select;
345 $this->_select
= "SELECT " . implode(', ', $select) . " ";
348 public function from() {
349 $this->setFromBase('civicrm_contribution', 'contact_id');
351 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
352 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id
355 $this->joinPhoneFromContact();
356 $this->joinEmailFromContact();
358 // for credit card type
359 $this->addFinancialTrxnFromClause();
361 $this->joinAddressFromContact();
364 public function where() {
365 $this->_statusClause
= "";
366 $clauses = array($this->_aliases
['civicrm_contribution'] . '.is_test = 0');
367 foreach ($this->_columns
as $tableName => $table) {
368 if (array_key_exists('filters', $table)) {
369 foreach ($table['filters'] as $fieldName => $field) {
371 if ($fieldName == 'yid') {
372 $clause = "contribution_civireport.contact_id NOT IN
373 (SELECT distinct cont.id FROM civicrm_contact cont, civicrm_contribution contri
374 WHERE cont.id = contri.contact_id AND " .
375 self
::fiscalYearOffset('contri.receive_date') .
376 " = {$this->_params['yid_value']} AND contri.is_test = 0 )";
378 elseif (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
380 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
381 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
382 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
384 if ($relative ||
$from ||
$to) {
385 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
389 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
391 $clause = $this->whereClause($field,
393 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
394 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
395 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
397 if (($fieldName == 'contribution_status_id' ||
398 $fieldName == 'financial_type_id') && !empty($clause)
400 $this->_statusClause
.= " AND " . $clause;
405 if (!empty($clause)) {
406 $clauses[] = $clause;
412 $this->_where
= "WHERE " . implode(' AND ', $clauses);
414 if ($this->_aclWhere
) {
415 $this->_where
.= " AND {$this->_aclWhere} ";
419 public function groupBy() {
420 $this->assign('chartSupported', TRUE);
421 $fiscalYearOffset = self
::fiscalYearOffset("{$this->_aliases['civicrm_contribution']}.receive_date");
422 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contribution']}.contact_id, {$fiscalYearOffset}";
423 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($this->_selectClauses
, array("{$this->_aliases['civicrm_contribution']}.contact_id", $fiscalYearOffset));
424 $this->_groupBy
.= " {$this->_rollup}";
432 public function statistics(&$rows) {
433 $statistics = parent
::statistics($rows);
438 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount ";
440 $sql = "{$select} {$this->_from} {$this->_where}";
441 $dao = CRM_Core_DAO
::executeQuery($sql);
443 $statistics['counts']['amount'] = array(
444 'value' => $dao->amount
,
445 'title' => ts('Total LifeTime'),
446 'type' => CRM_Utils_Type
::T_MONEY
,
453 public function postProcess() {
454 // get ready with post process params
455 $this->beginPostProcess();
456 $this->buildACLClause($this->_aliases
['civicrm_contact']);
459 $rows = $contactIds = array();
460 if (empty($this->_params
['charts'])) {
462 $getContacts = "SELECT SQL_CALC_FOUND_ROWS {$this->_aliases['civicrm_contact']}.id as cid {$this->_from} {$this->_where} GROUP BY {$this->_aliases['civicrm_contact']}.id {$this->_limit}";
464 $dao = CRM_Core_DAO
::executeQuery($getContacts);
466 while ($dao->fetch()) {
467 $contactIds[] = $dao->cid
;
473 if (!empty($contactIds) ||
!empty($this->_params
['charts'])) {
474 if (!empty($this->_params
['charts'])) {
475 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}";
479 "{$this->_select} {$this->_from} WHERE {$this->_aliases['civicrm_contact']}.id IN (" .
480 implode(',', $contactIds) .
481 ") AND {$this->_aliases['civicrm_contribution']}.is_test = 0 {$this->_statusClause} {$this->_groupBy} ";
484 $current_year = $this->_params
['yid_value'];
485 $previous_year = $current_year - 1;
486 $previous_pyear = $current_year - 2;
487 $previous_ppyear = $current_year - 3;
488 $upTo_year = $current_year - 4;
490 $rows = $row = array();
491 $dao = CRM_Core_DAO
::executeQuery($sql);
492 $contributionSum = 0;
494 while ($dao->fetch()) {
495 if (!$dao->civicrm_contribution_contact_id
) {
499 foreach ($this->_columnHeaders
as $key => $value) {
500 if (property_exists($dao, $key)) {
501 $rows[$dao->civicrm_contribution_contact_id
][$key] = $dao->$key;
504 if ($dao->civicrm_contribution_receive_date
) {
505 if ($dao->civicrm_contribution_receive_date
> $upTo_year) {
506 $contributionSum +
= $dao->civicrm_contribution_total_amount
;
507 $rows[$dao->civicrm_contribution_contact_id
]['year_' . $dao->civicrm_contribution_receive_date
] = $dao->civicrm_contribution_total_amount
;
511 $rows[$dao->civicrm_contribution_contact_id
]['civicrm_life_time_total'] = $dao->civicrm_contribution_total_amount
;
512 if (($dao->civicrm_contribution_total_amount
- $contributionSum) > 0
514 $rows[$dao->civicrm_contribution_contact_id
]["civicrm_upto_{$upTo_year}"]
515 = $dao->civicrm_contribution_total_amount
- $contributionSum;
517 $contributionSum = 0;
522 // format result set.
523 $this->formatDisplay($rows, FALSE);
525 // assign variables to templates
526 $this->doTemplateAssignment($rows);
528 // do print / pdf / instance stuff if needed
529 $this->endPostProcess($rows);
535 public function buildChart(&$rows) {
536 $graphRows = array();
538 $current_year = $this->_params
['yid_value'];
539 $previous_year = $current_year - 1;
540 $previous_two_year = $current_year - 2;
541 $previous_three_year = $current_year - 3;
542 $upto = $current_year - 4;
544 $interval[$previous_year] = $previous_year;
545 $interval[$previous_two_year] = $previous_two_year;
546 $interval[$previous_three_year] = $previous_three_year;
547 $interval["upto_{$upto}"] = "Up To {$upto}";
549 foreach ($rows as $key => $row) {
550 $display["upto_{$upto}"]
551 = CRM_Utils_Array
::value("upto_{$upto}", $display) + CRM_Utils_Array
::value("civicrm_upto_{$upto}", $row);
552 $display[$previous_year]
553 = CRM_Utils_Array
::value($previous_year, $display) + CRM_Utils_Array
::value($previous_year, $row);
554 $display[$previous_two_year]
555 = CRM_Utils_Array
::value($previous_two_year, $display) + CRM_Utils_Array
::value($previous_two_year, $row);
556 $display[$previous_three_year]
557 = CRM_Utils_Array
::value($previous_three_year, $display) + CRM_Utils_Array
::value($previous_three_year, $row);
560 $graphRows['value'] = $display;
561 $config = CRM_Core_Config
::Singleton();
563 'legend' => 'Sybunt Report',
565 'yname' => "Amount ({$config->defaultCurrency})",
567 if ($this->_params
['charts']) {
569 CRM_Utils_OpenFlashChart
::reportChart($graphRows, $this->_params
['charts'], $interval, $chartInfo);
570 $this->assign('chartType', $this->_params
['charts']);
575 * Alter display of rows.
577 * Iterate through the rows retrieved via SQL and make changes for display purposes,
578 * such as rendering contacts as links.
581 * Rows generated by SQL, with an array for each row.
583 public function alterDisplay(&$rows) {
586 foreach ($rows as $rowNum => $row) {
587 //Convert Display name into link
588 if (array_key_exists('civicrm_contact_sort_name', $row) &&
589 array_key_exists('civicrm_contribution_contact_id', $row)
591 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
592 'reset=1&force=1&id_op=eq&id_value=' .
593 $row['civicrm_contribution_contact_id'],
594 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
596 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
597 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
601 // convert campaign_id to campaign title
602 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
603 if ($value = $row['civicrm_contribution_campaign_id']) {
604 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns
[$value];
609 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ?
TRUE : $entryFound;
612 if (array_key_exists('civicrm_contact_gender_id', $row)) {
613 if ($value = $row['civicrm_contact_gender_id']) {
614 $gender = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id');
615 $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value];
620 // display birthday in the configured custom format
621 if (array_key_exists('civicrm_contact_birth_date', $row)) {
622 $birthDate = $row['civicrm_contact_birth_date'];
624 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date
::customFormat($birthDate, '%Y%m%d');
629 if (!empty($row['civicrm_financial_trxn_card_type_id'])) {
630 $rows[$rowNum]['civicrm_financial_trxn_card_type_id'] = $this->getLabels($row['civicrm_financial_trxn_card_type_id'], 'CRM_Financial_DAO_FinancialTrxn', 'card_type_id');
634 // skip looking further in rows, if first row itself doesn't
635 // have the column we need
643 * Override "This Year" $op options
644 * @param string $type
645 * @param null $fieldName
649 public function getOperationPair($type = "string", $fieldName = NULL) {
650 if ($fieldName == 'yid') {
652 'calendar' => ts('Is Calendar Year'),
653 'fiscal' => ts('Fiscal Year Starting'),
656 return parent
::getOperationPair($type, $fieldName);