3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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'),
250 // If we have a campaign, build out the relevant elements
251 if ($campaignEnabled && !empty($this->activeCampaigns
)) {
252 $this->_columns
['civicrm_contribution']['fields']['campaign_id'] = array(
253 'title' => ts('Campaign'),
254 'default' => 'false',
256 $this->_columns
['civicrm_contribution']['filters']['campaign_id'] = array(
257 'title' => ts('Campaign'),
258 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
259 'options' => $this->activeCampaigns
,
260 'type' => CRM_Utils_Type
::T_INT
,
264 $this->_groupFilter
= TRUE;
265 $this->_tagFilter
= TRUE;
266 parent
::__construct();
269 public function preProcess() {
270 parent
::preProcess();
273 public function select() {
275 $this->_columnHeaders
= array();
276 $current_year = $this->_params
['yid_value'];
277 $previous_year = $current_year - 1;
278 $previous_pyear = $current_year - 2;
279 $previous_ppyear = $current_year - 3;
280 $upTo_year = $current_year - 4;
282 foreach ($this->_columns
as $tableName => $table) {
283 if (array_key_exists('fields', $table)) {
284 foreach ($table['fields'] as $fieldName => $field) {
286 if (!empty($field['required']) ||
287 !empty($this->_params
['fields'][$fieldName])
289 if ($fieldName == 'total_amount') {
290 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}";
292 $this->_columnHeaders
["civicrm_upto_{$upTo_year}"]['type'] = $field['type'];
293 $this->_columnHeaders
["civicrm_upto_{$upTo_year}"]['title'] = ts("Up To %1", array(1 => $upTo_year));
295 $this->_columnHeaders
["year_{$previous_ppyear}"]['type'] = $field['type'];
296 $this->_columnHeaders
["year_{$previous_ppyear}"]['title'] = $previous_ppyear;
298 $this->_columnHeaders
["year_{$previous_pyear}"]['type'] = $field['type'];
299 $this->_columnHeaders
["year_{$previous_pyear}"]['title'] = $previous_pyear;
301 $this->_columnHeaders
["year_{$previous_year}"]['type'] = $field['type'];
302 $this->_columnHeaders
["year_{$previous_year}"]['title'] = $previous_year;
304 $this->_columnHeaders
["civicrm_life_time_total"]['type'] = $field['type'];
305 $this->_columnHeaders
["civicrm_life_time_total"]['title'] = ts('LifeTime');
307 elseif ($fieldName == 'receive_date') {
308 $select[] = self
::fiscalYearOffset($field['dbAlias']) .
309 " as {$tableName}_{$fieldName}";
312 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
313 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
314 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'];
316 if (!empty($field['no_display'])) {
317 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['no_display'] = TRUE;
323 $this->_selectClauses
= $select;
325 $this->_select
= "SELECT " . implode(', ', $select) . " ";
328 public function from() {
329 $this->setFromBase('civicrm_contribution', 'contact_id');
331 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
332 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id
335 if ($this->isTableSelected('civicrm_email')) {
337 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
338 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
339 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
341 if ($this->isTableSelected('civicrm_phone')) {
343 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
344 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
345 {$this->_aliases['civicrm_phone']}.is_primary = 1";
347 $this->addAddressFromClause();
350 public function where() {
351 $this->_statusClause
= "";
352 $clauses = array($this->_aliases
['civicrm_contribution'] . '.is_test = 0');
353 foreach ($this->_columns
as $tableName => $table) {
354 if (array_key_exists('filters', $table)) {
355 foreach ($table['filters'] as $fieldName => $field) {
357 if ($fieldName == 'yid') {
358 $clause = "contribution_civireport.contact_id NOT IN
359 (SELECT distinct cont.id FROM civicrm_contact cont, civicrm_contribution contri
360 WHERE cont.id = contri.contact_id AND " .
361 self
::fiscalYearOffset('contri.receive_date') .
362 " = {$this->_params['yid_value']} AND contri.is_test = 0 )";
364 elseif (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
366 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
367 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
368 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
370 if ($relative ||
$from ||
$to) {
371 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
375 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
377 $clause = $this->whereClause($field,
379 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
380 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
381 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
383 if (($fieldName == 'contribution_status_id' ||
384 $fieldName == 'financial_type_id') && !empty($clause)
386 $this->_statusClause
.= " AND " . $clause;
391 if (!empty($clause)) {
392 $clauses[] = $clause;
398 $this->_where
= "WHERE " . implode(' AND ', $clauses);
400 if ($this->_aclWhere
) {
401 $this->_where
.= " AND {$this->_aclWhere} ";
405 public function groupBy() {
406 $this->assign('chartSupported', TRUE);
407 $fiscalYearOffset = self
::fiscalYearOffset("{$this->_aliases['civicrm_contribution']}.receive_date");
408 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contribution']}.contact_id, {$fiscalYearOffset}";
409 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($this->_selectClauses
, array("{$this->_aliases['civicrm_contribution']}.contact_id", $fiscalYearOffset));
410 $this->_groupBy
.= " {$this->_rollup}";
418 public function statistics(&$rows) {
419 $statistics = parent
::statistics($rows);
424 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount ";
426 $sql = "{$select} {$this->_from} {$this->_where}";
427 $dao = CRM_Core_DAO
::executeQuery($sql);
429 $statistics['counts']['amount'] = array(
430 'value' => $dao->amount
,
431 'title' => ts('Total LifeTime'),
432 'type' => CRM_Utils_Type
::T_MONEY
,
439 public function postProcess() {
440 // get ready with post process params
441 $this->beginPostProcess();
442 $this->buildACLClause($this->_aliases
['civicrm_contact']);
445 $rows = $contactIds = array();
446 if (empty($this->_params
['charts'])) {
448 $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}";
450 $dao = CRM_Core_DAO
::executeQuery($getContacts);
452 while ($dao->fetch()) {
453 $contactIds[] = $dao->cid
;
459 if (!empty($contactIds) ||
!empty($this->_params
['charts'])) {
460 if (!empty($this->_params
['charts'])) {
461 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}";
465 "{$this->_select} {$this->_from} WHERE {$this->_aliases['civicrm_contact']}.id IN (" .
466 implode(',', $contactIds) .
467 ") AND {$this->_aliases['civicrm_contribution']}.is_test = 0 {$this->_statusClause} {$this->_groupBy} ";
470 $current_year = $this->_params
['yid_value'];
471 $previous_year = $current_year - 1;
472 $previous_pyear = $current_year - 2;
473 $previous_ppyear = $current_year - 3;
474 $upTo_year = $current_year - 4;
476 $rows = $row = array();
477 $dao = CRM_Core_DAO
::executeQuery($sql);
478 $contributionSum = 0;
480 while ($dao->fetch()) {
481 if (!$dao->civicrm_contribution_contact_id
) {
485 foreach ($this->_columnHeaders
as $key => $value) {
486 if (property_exists($dao, $key)) {
487 $rows[$dao->civicrm_contribution_contact_id
][$key] = $dao->$key;
490 if ($dao->civicrm_contribution_receive_date
) {
491 if ($dao->civicrm_contribution_receive_date
> $upTo_year) {
492 $contributionSum +
= $dao->civicrm_contribution_total_amount
;
493 $rows[$dao->civicrm_contribution_contact_id
]['year_' . $dao->civicrm_contribution_receive_date
] = $dao->civicrm_contribution_total_amount
;
497 $rows[$dao->civicrm_contribution_contact_id
]['civicrm_life_time_total'] = $dao->civicrm_contribution_total_amount
;
498 if (($dao->civicrm_contribution_total_amount
- $contributionSum) > 0
500 $rows[$dao->civicrm_contribution_contact_id
]["civicrm_upto_{$upTo_year}"]
501 = $dao->civicrm_contribution_total_amount
- $contributionSum;
503 $contributionSum = 0;
508 // format result set.
509 $this->formatDisplay($rows, FALSE);
511 // assign variables to templates
512 $this->doTemplateAssignment($rows);
514 // do print / pdf / instance stuff if needed
515 $this->endPostProcess($rows);
521 public function buildChart(&$rows) {
522 $graphRows = array();
524 $current_year = $this->_params
['yid_value'];
525 $previous_year = $current_year - 1;
526 $previous_two_year = $current_year - 2;
527 $previous_three_year = $current_year - 3;
528 $upto = $current_year - 4;
530 $interval[$previous_year] = $previous_year;
531 $interval[$previous_two_year] = $previous_two_year;
532 $interval[$previous_three_year] = $previous_three_year;
533 $interval["upto_{$upto}"] = "Up To {$upto}";
535 foreach ($rows as $key => $row) {
536 $display["upto_{$upto}"]
537 = CRM_Utils_Array
::value("upto_{$upto}", $display) + CRM_Utils_Array
::value("civicrm_upto_{$upto}", $row);
538 $display[$previous_year]
539 = CRM_Utils_Array
::value($previous_year, $display) + CRM_Utils_Array
::value($previous_year, $row);
540 $display[$previous_two_year]
541 = CRM_Utils_Array
::value($previous_two_year, $display) + CRM_Utils_Array
::value($previous_two_year, $row);
542 $display[$previous_three_year]
543 = CRM_Utils_Array
::value($previous_three_year, $display) + CRM_Utils_Array
::value($previous_three_year, $row);
546 $graphRows['value'] = $display;
547 $config = CRM_Core_Config
::Singleton();
549 'legend' => 'Sybunt Report',
551 'yname' => "Amount ({$config->defaultCurrency})",
553 if ($this->_params
['charts']) {
555 CRM_Utils_OpenFlashChart
::reportChart($graphRows, $this->_params
['charts'], $interval, $chartInfo);
556 $this->assign('chartType', $this->_params
['charts']);
561 * Alter display of rows.
563 * Iterate through the rows retrieved via SQL and make changes for display purposes,
564 * such as rendering contacts as links.
567 * Rows generated by SQL, with an array for each row.
569 public function alterDisplay(&$rows) {
572 foreach ($rows as $rowNum => $row) {
573 //Convert Display name into link
574 if (array_key_exists('civicrm_contact_sort_name', $row) &&
575 array_key_exists('civicrm_contribution_contact_id', $row)
577 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
578 'reset=1&force=1&id_op=eq&id_value=' .
579 $row['civicrm_contribution_contact_id'],
580 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
582 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
583 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
587 // convert campaign_id to campaign title
588 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
589 if ($value = $row['civicrm_contribution_campaign_id']) {
590 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns
[$value];
595 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ?
TRUE : $entryFound;
598 if (array_key_exists('civicrm_contact_gender_id', $row)) {
599 if ($value = $row['civicrm_contact_gender_id']) {
600 $gender = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id');
601 $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value];
606 // display birthday in the configured custom format
607 if (array_key_exists('civicrm_contact_birth_date', $row)) {
608 $birthDate = $row['civicrm_contact_birth_date'];
610 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date
::customFormat($birthDate, '%Y%m%d');
615 // skip looking further in rows, if first row itself doesn't
616 // have the column we need
624 * Override "This Year" $op options
625 * @param string $type
626 * @param null $fieldName
630 public function getOperationPair($type = "string", $fieldName = NULL) {
631 if ($fieldName == 'yid') {
633 'calendar' => ts('Is Calendar Year'),
634 'fiscal' => ts('Fiscal Year Starting'),
637 return parent
::getOperationPair($type, $fieldName);