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');
51 public function __construct() {
52 $this->_rollup
= 'WITH ROLLUP';
53 $this->_autoIncludeIndexedFieldsAsOrderBys
= 1;
56 $date = CRM_Core_SelectValues
::date('custom', NULL, $yearsInPast, $yearsInFuture);
57 $count = $date['maxYear'];
58 while ($date['minYear'] <= $count) {
59 $optionYear[$date['minYear']] = $date['minYear'];
63 // Check if CiviCampaign is a) enabled and b) has active campaigns
64 $config = CRM_Core_Config
::singleton();
65 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents
);
66 if ($campaignEnabled) {
67 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
68 $this->activeCampaigns
= $getCampaigns['campaigns'];
69 asort($this->activeCampaigns
);
72 $this->_columns
= array(
73 'civicrm_contact' => array(
74 'dao' => 'CRM_Contact_DAO_Contact',
75 'grouping' => 'contact-field',
78 'title' => ts('Donor Name'),
81 'first_name' => array(
82 'title' => ts('First Name'),
84 'middle_name' => array(
85 'title' => ts('Middle Name'),
88 'title' => ts('Last Name'),
95 'title' => ts('Gender'),
97 'birth_date' => array(
98 'title' => ts('Birth Date'),
101 'title' => ts('Age'),
102 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
104 'contact_type' => array(
105 'title' => ts('Contact Type'),
107 'contact_sub_type' => array(
108 'title' => ts('Contact Subtype'),
111 'grouping' => 'contact-fields',
112 'order_bys' => array(
113 'sort_name' => array(
114 'title' => ts('Last Name, First Name'),
116 'default_weight' => '0',
117 'default_order' => 'ASC',
119 'first_name' => array(
120 'name' => 'first_name',
121 'title' => ts('First Name'),
123 'gender_id' => array(
124 'name' => 'gender_id',
125 'title' => ts('Gender'),
127 'birth_date' => array(
128 'name' => 'birth_date',
129 'title' => ts('Birth Date'),
131 'age_at_event' => array(
132 'name' => 'age_at_event',
133 'title' => ts('Age at Event'),
135 'contact_type' => array(
136 'title' => ts('Contact Type'),
138 'contact_sub_type' => array(
139 'title' => ts('Contact Subtype'),
143 'sort_name' => array(
144 'title' => ts('Donor Name'),
145 'operator' => 'like',
148 'title' => ts('Contact ID'),
149 'no_display' => TRUE,
151 'gender_id' => array(
152 'title' => ts('Gender'),
153 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
154 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
156 'birth_date' => array(
157 'title' => ts('Birth Date'),
158 'operatorType' => CRM_Report_Form
::OP_DATE
,
160 'contact_type' => array(
161 'title' => ts('Contact Type'),
163 'contact_sub_type' => array(
164 'title' => ts('Contact Subtype'),
168 'civicrm_line_item' => array(
169 'dao' => 'CRM_Price_DAO_LineItem',
171 'civicrm_email' => array(
172 'dao' => 'CRM_Core_DAO_Email',
173 'grouping' => 'contact-field',
176 'title' => ts('Email'),
181 'civicrm_phone' => array(
182 'dao' => 'CRM_Core_DAO_Phone',
183 'grouping' => 'contact-field',
186 'title' => ts('Phone'),
192 $this->_columns +
= $this->addAddressFields();
193 $this->_columns +
= array(
194 'civicrm_contribution' => array(
195 'dao' => 'CRM_Contribute_DAO_Contribution',
197 'contact_id' => array(
198 'title' => ts('contactId'),
199 'no_display' => TRUE,
203 'total_amount' => array(
204 'title' => ts('Total Amount'),
205 'no_display' => TRUE,
209 'receive_date' => array(
210 'title' => ts('Year'),
211 'no_display' => TRUE,
218 'name' => 'receive_date',
219 'title' => ts('This Year'),
220 'operatorType' => CRM_Report_Form
::OP_SELECT
,
221 'options' => $optionYear,
222 'default' => date('Y'),
223 'type' => CRM_Utils_Type
::T_INT
,
225 'financial_type_id' => array(
226 'title' => ts('Financial Type'),
227 'type' => CRM_Utils_Type
::T_INT
,
228 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
229 'options' => CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes(),
231 'contribution_status_id' => array(
232 'title' => ts('Contribution Status'),
233 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
234 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
235 'default' => array('1'),
241 // If we have a campaign, build out the relevant elements
242 if ($campaignEnabled && !empty($this->activeCampaigns
)) {
243 $this->_columns
['civicrm_contribution']['fields']['campaign_id'] = array(
244 'title' => ts('Campaign'),
245 'default' => 'false',
247 $this->_columns
['civicrm_contribution']['filters']['campaign_id'] = array(
248 'title' => ts('Campaign'),
249 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
250 'options' => $this->activeCampaigns
,
251 'type' => CRM_Utils_Type
::T_INT
,
255 $this->_groupFilter
= TRUE;
256 $this->_tagFilter
= TRUE;
257 parent
::__construct();
260 public function preProcess() {
261 parent
::preProcess();
264 public function select() {
266 $this->_columnHeaders
= array();
267 $current_year = $this->_params
['yid_value'];
268 $previous_year = $current_year - 1;
269 $previous_pyear = $current_year - 2;
270 $previous_ppyear = $current_year - 3;
271 $upTo_year = $current_year - 4;
273 foreach ($this->_columns
as $tableName => $table) {
274 if (array_key_exists('fields', $table)) {
275 foreach ($table['fields'] as $fieldName => $field) {
277 if (!empty($field['required']) ||
278 !empty($this->_params
['fields'][$fieldName])
280 if ($fieldName == 'total_amount') {
281 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}";
283 $this->_columnHeaders
["civicrm_upto_{$upTo_year}"]['type'] = $field['type'];
284 $this->_columnHeaders
["civicrm_upto_{$upTo_year}"]['title'] = "Up To $upTo_year";
286 $this->_columnHeaders
["year_{$previous_ppyear}"]['type'] = $field['type'];
287 $this->_columnHeaders
["year_{$previous_ppyear}"]['title'] = $previous_ppyear;
289 $this->_columnHeaders
["year_{$previous_pyear}"]['type'] = $field['type'];
290 $this->_columnHeaders
["year_{$previous_pyear}"]['title'] = $previous_pyear;
292 $this->_columnHeaders
["year_{$previous_year}"]['type'] = $field['type'];
293 $this->_columnHeaders
["year_{$previous_year}"]['title'] = $previous_year;
295 $this->_columnHeaders
["civicrm_life_time_total"]['type'] = $field['type'];
296 $this->_columnHeaders
["civicrm_life_time_total"]['title'] = 'LifeTime';;
298 elseif ($fieldName == 'receive_date') {
299 $select[] = self
::fiscalYearOffset($field['dbAlias']) .
300 " as {$tableName}_{$fieldName}";
303 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
304 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
305 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'];
307 if (!empty($field['no_display'])) {
308 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['no_display'] = TRUE;
314 $this->_selectClauses
= $select;
316 $this->_select
= "SELECT " . implode(', ', $select) . " ";
319 public function from() {
322 FROM civicrm_contribution {$this->_aliases['civicrm_contribution']}
323 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
324 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id
327 if ($this->isTableSelected('civicrm_email')) {
329 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
330 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
331 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
333 if ($this->isTableSelected('civicrm_phone')) {
335 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
336 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
337 {$this->_aliases['civicrm_phone']}.is_primary = 1";
339 $this->addAddressFromClause();
342 public function where() {
343 $this->_statusClause
= "";
344 $clauses = array($this->_aliases
['civicrm_contribution'] . '.is_test = 0');
345 foreach ($this->_columns
as $tableName => $table) {
346 if (array_key_exists('filters', $table)) {
347 foreach ($table['filters'] as $fieldName => $field) {
349 if ($fieldName == 'yid') {
350 $clause = "contribution_civireport.contact_id NOT IN
351 (SELECT distinct cont.id FROM civicrm_contact cont, civicrm_contribution contri
352 WHERE cont.id = contri.contact_id AND " .
353 self
::fiscalYearOffset('contri.receive_date') .
354 " = {$this->_params['yid_value']} AND contri.is_test = 0 )";
356 elseif (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
358 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
359 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
360 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
362 if ($relative ||
$from ||
$to) {
363 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
367 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
369 $clause = $this->whereClause($field,
371 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
372 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
373 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
375 if (($fieldName == 'contribution_status_id' ||
376 $fieldName == 'financial_type_id') && !empty($clause)
378 $this->_statusClause
.= " AND " . $clause;
383 if (!empty($clause)) {
384 $clauses[] = $clause;
390 $this->_where
= "WHERE " . implode(' AND ', $clauses);
392 if ($this->_aclWhere
) {
393 $this->_where
.= " AND {$this->_aclWhere} ";
397 public function groupBy() {
398 $this->assign('chartSupported', TRUE);
399 $fiscalYearOffset = self
::fiscalYearOffset("{$this->_aliases['civicrm_contribution']}.receive_date");
400 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contribution']}.contact_id, {$fiscalYearOffset}";
401 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($this->_selectClauses
, array("{$this->_aliases['civicrm_contribution']}.contact_id", $fiscalYearOffset));
402 $this->_groupBy
.= " {$this->_rollup}";
410 public function statistics(&$rows) {
411 $statistics = parent
::statistics($rows);
416 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount ";
418 $sql = "{$select} {$this->_from} {$this->_where}";
419 $dao = CRM_Core_DAO
::executeQuery($sql);
421 $statistics['counts']['amount'] = array(
422 'value' => $dao->amount
,
423 'title' => 'Total LifeTime',
424 'type' => CRM_Utils_Type
::T_MONEY
,
431 public function postProcess() {
432 // get ready with post process params
433 $this->beginPostProcess();
434 $this->buildACLClause($this->_aliases
['civicrm_contact']);
437 $rows = $contactIds = array();
438 if (empty($this->_params
['charts'])) {
440 $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}";
442 $dao = CRM_Core_DAO
::executeQuery($getContacts);
444 while ($dao->fetch()) {
445 $contactIds[] = $dao->cid
;
451 if (!empty($contactIds) ||
!empty($this->_params
['charts'])) {
452 if (!empty($this->_params
['charts'])) {
453 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}";
457 "{$this->_select} {$this->_from} WHERE {$this->_aliases['civicrm_contact']}.id IN (" .
458 implode(',', $contactIds) .
459 ") AND {$this->_aliases['civicrm_contribution']}.is_test = 0 {$this->_statusClause} {$this->_groupBy} ";
462 $current_year = $this->_params
['yid_value'];
463 $previous_year = $current_year - 1;
464 $previous_pyear = $current_year - 2;
465 $previous_ppyear = $current_year - 3;
466 $upTo_year = $current_year - 4;
468 $rows = $row = array();
469 $dao = CRM_Core_DAO
::executeQuery($sql);
470 $contributionSum = 0;
472 while ($dao->fetch()) {
473 if (!$dao->civicrm_contribution_contact_id
) {
477 foreach ($this->_columnHeaders
as $key => $value) {
478 if (property_exists($dao, $key)) {
479 $rows[$dao->civicrm_contribution_contact_id
][$key] = $dao->$key;
482 if ($dao->civicrm_contribution_receive_date
) {
483 if ($dao->civicrm_contribution_receive_date
> $upTo_year) {
484 $contributionSum +
= $dao->civicrm_contribution_total_amount
;
485 $rows[$dao->civicrm_contribution_contact_id
]['year_' . $dao->civicrm_contribution_receive_date
] = $dao->civicrm_contribution_total_amount
;
489 $rows[$dao->civicrm_contribution_contact_id
]['civicrm_life_time_total'] = $dao->civicrm_contribution_total_amount
;
490 if (($dao->civicrm_contribution_total_amount
- $contributionSum) > 0
492 $rows[$dao->civicrm_contribution_contact_id
]["civicrm_upto_{$upTo_year}"]
493 = $dao->civicrm_contribution_total_amount
- $contributionSum;
495 $contributionSum = 0;
500 // format result set.
501 $this->formatDisplay($rows, FALSE);
503 // assign variables to templates
504 $this->doTemplateAssignment($rows);
506 // do print / pdf / instance stuff if needed
507 $this->endPostProcess($rows);
513 public function buildChart(&$rows) {
514 $graphRows = array();
516 $current_year = $this->_params
['yid_value'];
517 $previous_year = $current_year - 1;
518 $previous_two_year = $current_year - 2;
519 $previous_three_year = $current_year - 3;
520 $upto = $current_year - 4;
522 $interval[$previous_year] = $previous_year;
523 $interval[$previous_two_year] = $previous_two_year;
524 $interval[$previous_three_year] = $previous_three_year;
525 $interval["upto_{$upto}"] = "Up To {$upto}";
527 foreach ($rows as $key => $row) {
528 $display["upto_{$upto}"]
529 = CRM_Utils_Array
::value("upto_{$upto}", $display)
530 + CRM_Utils_Array
::value("civicrm_upto_{$upto}", $row);
531 $display[$previous_year]
532 = CRM_Utils_Array
::value($previous_year, $display)
533 + CRM_Utils_Array
::value($previous_year, $row);
534 $display[$previous_two_year]
535 = CRM_Utils_Array
::value($previous_two_year, $display)
536 + CRM_Utils_Array
::value($previous_two_year, $row);
537 $display[$previous_three_year]
538 = CRM_Utils_Array
::value($previous_three_year, $display)
539 + CRM_Utils_Array
::value($previous_three_year, $row);
542 $graphRows['value'] = $display;
543 $config = CRM_Core_Config
::Singleton();
545 'legend' => 'Sybunt Report',
547 'yname' => "Amount ({$config->defaultCurrency})",
549 if ($this->_params
['charts']) {
551 CRM_Utils_OpenFlashChart
::reportChart($graphRows, $this->_params
['charts'], $interval, $chartInfo);
552 $this->assign('chartType', $this->_params
['charts']);
557 * Alter display of rows.
559 * Iterate through the rows retrieved via SQL and make changes for display purposes,
560 * such as rendering contacts as links.
563 * Rows generated by SQL, with an array for each row.
565 public function alterDisplay(&$rows) {
568 foreach ($rows as $rowNum => $row) {
569 //Convert Display name into link
570 if (array_key_exists('civicrm_contact_sort_name', $row) &&
571 array_key_exists('civicrm_contribution_contact_id', $row)
573 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
574 'reset=1&force=1&id_op=eq&id_value=' .
575 $row['civicrm_contribution_contact_id'],
576 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
578 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
579 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
583 // convert campaign_id to campaign title
584 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
585 if ($value = $row['civicrm_contribution_campaign_id']) {
586 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns
[$value];
591 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ?
TRUE : $entryFound;
594 if (array_key_exists('civicrm_contact_gender_id', $row)) {
595 if ($value = $row['civicrm_contact_gender_id']) {
596 $gender = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id');
597 $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value];
602 // display birthday in the configured custom format
603 if (array_key_exists('civicrm_contact_birth_date', $row)) {
604 $birthDate = $row['civicrm_contact_birth_date'];
606 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date
::customFormat($birthDate, '%Y%m%d');
611 // skip looking further in rows, if first row itself doesn't
612 // have the column we need
620 * Override "This Year" $op options
621 * @param string $type
622 * @param null $fieldName
626 public function getOperationPair($type = "string", $fieldName = NULL) {
627 if ($fieldName == 'yid') {
629 'calendar' => ts('Is Calendar Year'),
630 'fiscal' => ts('Fiscal Year Starting'),
633 return parent
::getOperationPair($type, $fieldName);