phpcs - Fix error, "CONST keyword must be lowercase; expected const but found CONST"
[civicrm-core.git] / CRM / Report / Form / Contribute / Lybunt.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35class CRM_Report_Form_Contribute_Lybunt extends CRM_Report_Form {
36
37
38 protected $_charts = array(
39 '' => 'Tabular',
40 'barChart' => 'Bar Chart',
41 'pieChart' => 'Pie Chart',
42 );
43
44 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
45
46 protected $lifeTime_from = NULL;
430ae6dd
TO
47 protected $lifeTime_where = NULL;
48
74cf4551
EM
49 /**
50 *
51 */
52 /**
53 *
54 */
430ae6dd 55 function __construct() {
9d72cede 56 $yearsInPast = 10;
6a488035 57 $yearsInFuture = 1;
9d72cede
EM
58 $date = CRM_Core_SelectValues::date('custom', NULL, $yearsInPast, $yearsInFuture);
59 $count = $date['maxYear'];
6a488035
TO
60 while ($date['minYear'] <= $count) {
61 $optionYear[$date['minYear']] = $date['minYear'];
62 $date['minYear']++;
63 }
64
d62fab33
RN
65 // Check if CiviCampaign is a) enabled and b) has active campaigns
66 $config = CRM_Core_Config::singleton();
67 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
68 if ($campaignEnabled) {
69 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
70 $this->activeCampaigns = $getCampaigns['campaigns'];
71 asort($this->activeCampaigns);
f813f78e 72 }
d62fab33 73
6a488035 74 $this->_columns = array(
9d72cede
EM
75 'civicrm_contact' => array(
76 'dao' => 'CRM_Contact_DAO_Contact',
77 'grouping' => 'contact-field',
78 'fields' => array(
79 'sort_name' => array(
80 'title' => ts('Donor Name'),
81 'default' => TRUE,
82 'required' => TRUE,
83 ),
84 'first_name' => array(
85 'title' => ts('First Name'),
86 ),
87 'last_name' => array(
88 'title' => ts('Last Name'),
89 ),
90 'contact_type' => array(
91 'title' => ts('Contact Type'),
92 ),
93 'contact_sub_type' => array(
94 'title' => ts('Contact Subtype'),
95 ),
6a488035 96 ),
9d72cede
EM
97 'filters' => array(
98 'sort_name' => array(
99 'title' => ts('Donor Name'),
100 'operator' => 'like',
101 ),
6a488035
TO
102 ),
103 ),
9d72cede
EM
104 'civicrm_email' => array(
105 'dao' => 'CRM_Core_DAO_Email',
106 'grouping' => 'contact-field',
107 'fields' => array(
108 'email' => array(
109 'title' => ts('Email'),
110 'default' => TRUE,
111 ),
6a488035
TO
112 ),
113 ),
9d72cede
EM
114 'civicrm_phone' => array(
115 'dao' => 'CRM_Core_DAO_Phone',
116 'grouping' => 'contact-field',
117 'fields' => array(
118 'phone' => array(
119 'title' => ts('Phone'),
120 'default' => TRUE,
121 ),
6a488035
TO
122 ),
123 ),
9d72cede
EM
124 )
125 + $this->addAddressFields()
126 + array(
127 'civicrm_contribution' => array(
128 'dao' => 'CRM_Contribute_DAO_Contribution',
129 'fields' => array(
130 'contact_id' => array(
131 'title' => ts('contactId'),
132 'no_display' => TRUE,
133 'required' => TRUE,
134 'no_repeat' => TRUE,
135 ),
136 'total_amount' => array(
137 'title' => ts('Total Amount'),
138 'no_display' => TRUE,
139 'required' => TRUE,
140 'no_repeat' => TRUE,
141 ),
142 'receive_date' => array(
143 'title' => ts('Year'),
144 'no_display' => TRUE,
145 'required' => TRUE,
146 'no_repeat' => TRUE,
147 ),
6a488035 148 ),
9d72cede
EM
149 'filters' => array(
150 'yid' => array(
151 'name' => 'receive_date',
152 'title' => ts('This Year'),
153 'operatorType' => CRM_Report_Form::OP_SELECT,
154 'options' => $optionYear,
155 'default' => date('Y'),
156 ),
157 'financial_type_id' => array(
158 'title' => ts('Financial Type'),
159 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
160 'options' => CRM_Contribute_PseudoConstant::financialType(),
161 ),
162 'contribution_status_id' => array(
163 'title' => ts('Contribution Status'),
164 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
165 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
166 'default' => array('1'),
167 ),
6a488035
TO
168 ),
169 ),
9d72cede 170 );
6a488035 171
d62fab33
RN
172 // If we have a campaign, build out the relevant elements
173 if ($campaignEnabled && !empty($this->activeCampaigns)) {
174 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
175 'title' => ts('Campaign'),
176 'default' => 'false',
177 );
9d72cede
EM
178 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
179 'title' => ts('Campaign'),
d62fab33
RN
180 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
181 'options' => $this->activeCampaigns,
182 );
183 }
184
16e2e80c 185 $this->_groupFilter = TRUE;
6a488035
TO
186 $this->_tagFilter = TRUE;
187 parent::__construct();
188 }
189
190 function preProcess() {
191 parent::preProcess();
192 }
193
194 function select() {
195
196 $this->_columnHeaders = $select = array();
197 $current_year = $this->_params['yid_value'];
198 $previous_year = $current_year - 1;
199
200
201 foreach ($this->_columns as $tableName => $table) {
202
203 if (array_key_exists('fields', $table)) {
204 foreach ($table['fields'] as $fieldName => $field) {
205
9d72cede
EM
206 if (!empty($field['required']) ||
207 !empty($this->_params['fields'][$fieldName])
208 ) {
6a488035
TO
209 if ($fieldName == 'total_amount') {
210 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}";
211
212 $this->_columnHeaders["{$previous_year}"]['type'] = $field['type'];
213 $this->_columnHeaders["{$previous_year}"]['title'] = $previous_year;
214
215 $this->_columnHeaders["civicrm_life_time_total"]['type'] = $field['type'];
216 $this->_columnHeaders["civicrm_life_time_total"]['title'] = 'LifeTime';;
217 }
218 elseif ($fieldName == 'receive_date') {
9d72cede
EM
219 $select[] = self::fiscalYearOffset($field['dbAlias']) .
220 " as {$tableName}_{$fieldName} ";
6a488035
TO
221 }
222 else {
223 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName} ";
224 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
225 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
226 }
227
a7488080 228 if (!empty($field['no_display'])) {
6a488035
TO
229 $this->_columnHeaders["{$tableName}_{$fieldName}"]['no_display'] = TRUE;
230 }
231 }
232 }
233 }
234 }
235
236 $this->_select = "SELECT " . implode(', ', $select) . " ";
237 }
238
239 function from() {
240
241 $this->_from = "
242 FROM civicrm_contribution {$this->_aliases['civicrm_contribution']}
1c44e08e 243 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
6a488035 244 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id
a27c90f2
NG
245 {$this->_aclFrom}";
246
247 if ($this->isTableSelected('civicrm_email')) {
248 $this->_from .= "
1c44e08e 249 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
a27c90f2
NG
250 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
251 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
252 }
253 if ($this->isTableSelected('civicrm_phone')) {
254 $this->_from .= "
1c44e08e 255 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
6a488035 256 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
a27c90f2
NG
257 {$this->_aliases['civicrm_phone']}.is_primary = 1";
258 }
72a9af52 259 $this->addAddressFromClause();
6a488035
TO
260 }
261
262 function where() {
263 $this->_statusClause = "";
9d72cede
EM
264 $clauses = array($this->_aliases['civicrm_contribution'] . '.is_test = 0');
265 $current_year = $this->_params['yid_value'];
266 $previous_year = $current_year - 1;
6a488035
TO
267
268 foreach ($this->_columns as $tableName => $table) {
269 if (array_key_exists('filters', $table)) {
270 foreach ($table['filters'] as $fieldName => $field) {
271 $clause = NULL;
272 if ($fieldName == 'yid') {
273 $clause = "contribution_civireport.contact_id NOT IN
1c44e08e 274(SELECT distinct contri.contact_id FROM civicrm_contribution contri
9d72cede
EM
275 WHERE contri.is_test = 0 AND " .
276 self::fiscalYearOffset('contri.receive_date') . " = $current_year) AND contribution_civireport.contact_id IN (SELECT distinct contri.contact_id FROM civicrm_contribution contri
277 WHERE " . self::fiscalYearOffset('contri.receive_date') .
278 " = $previous_year AND contri.is_test = 0)";
6a488035 279 }
9d72cede
EM
280 elseif (CRM_Utils_Array::value('type', $field) &
281 CRM_Utils_Type::T_DATE
282 ) {
6a488035 283 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
9d72cede
EM
284 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
285 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
6a488035
TO
286
287 if ($relative || $from || $to) {
288 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
289 }
290 }
291 else {
292 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
293 if ($op) {
294 $clause = $this->whereClause($field,
295 $op,
296 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
297 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
298 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
299 );
9d72cede
EM
300 if (($fieldName == 'contribution_status_id' ||
301 $fieldName == 'financial_type_id') && !empty($clause)
302 ) {
6a488035
TO
303 $this->_statusClause .= " AND " . $clause;
304 }
305 }
306 }
307
308 if (!empty($clause)) {
309 $clauses[] = $clause;
310 }
311 }
312 }
313 }
314
315 $this->_where = 'WHERE ' . implode(' AND ', $clauses);
316
317 if ($this->_aclWhere) {
318 $this->_where .= " AND {$this->_aclWhere} ";
319 }
320 }
321
322 function groupBy() {
9d72cede
EM
323 $this->_groupBy =
324 "GROUP BY {$this->_aliases['civicrm_contribution']}.contact_id, " .
325 self::fiscalYearOffset($this->_aliases['civicrm_contribution'] .
326 '.receive_date') . " WITH ROLLUP";
6a488035
TO
327 $this->assign('chartSupported', TRUE);
328 }
329
74cf4551
EM
330 /**
331 * @param $rows
332 *
333 * @return array
334 */
6a488035
TO
335 function statistics(&$rows) {
336 $statistics = parent::statistics($rows);
337 if (!empty($rows)) {
338 $select = "
1c44e08e 339 SELECT
6a488035
TO
340 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount ";
341
342 $sql = "{$select} {$this->_from} {$this->_where}";
343 $dao = CRM_Core_DAO::executeQuery($sql);
344 if ($dao->fetch()) {
345 $statistics['counts']['amount'] = array(
346 'value' => $dao->amount,
347 'title' => 'Total LifeTime',
348 'type' => CRM_Utils_Type::T_MONEY,
349 );
350 }
351 }
352
353 return $statistics;
354 }
355
356 function postProcess() {
357
358 // get ready with post process params
359 $this->beginPostProcess();
360
361 // get the acl clauses built before we assemble the query
362 $this->buildACLClause($this->_aliases['civicrm_contact']);
363 $this->select();
364 $this->from();
365 $this->where();
366 $this->groupBy();
367
368 $rows = $contactIds = array();
a7488080 369 if (empty($this->_params['charts'])) {
6a488035
TO
370 $this->limit();
371 $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}";
372
373 $dao = CRM_Core_DAO::executeQuery($getContacts);
374
375 while ($dao->fetch()) {
376 $contactIds[] = $dao->cid;
377 }
378 $dao->free();
379 $this->setPager();
380 }
381
8cc574cf 382 if (!empty($contactIds) || !empty($this->_params['charts'])) {
a7488080 383 if (!empty($this->_params['charts'])) {
6a488035
TO
384 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}";
385 }
386 else {
9d72cede
EM
387 $sql =
388 "{$this->_select} {$this->_from} WHERE {$this->_aliases['civicrm_contact']}.id IN (" .
389 implode(',', $contactIds) .
390 ") AND {$this->_aliases['civicrm_contribution']}.is_test = 0 {$this->_statusClause} {$this->_groupBy} ";
6a488035
TO
391 }
392
9d72cede
EM
393 $dao = CRM_Core_DAO::executeQuery($sql);
394 $current_year = $this->_params['yid_value'];
6a488035
TO
395 $previous_year = $current_year - 1;
396
397 while ($dao->fetch()) {
398
399 if (!$dao->civicrm_contribution_contact_id) {
400 continue;
401 }
402
403 $row = array();
404 foreach ($this->_columnHeaders as $key => $value) {
405 if (property_exists($dao, $key)) {
406 $rows[$dao->civicrm_contribution_contact_id][$key] = $dao->$key;
407 }
408 }
409
410 if ($dao->civicrm_contribution_receive_date) {
411 if ($dao->civicrm_contribution_receive_date == $previous_year) {
412 $rows[$dao->civicrm_contribution_contact_id][$dao->civicrm_contribution_receive_date] = $dao->civicrm_contribution_total_amount;
413 }
414 }
415 else {
416 $rows[$dao->civicrm_contribution_contact_id]['civicrm_life_time_total'] = $dao->civicrm_contribution_total_amount;
417 }
418 }
419 $dao->free();
420 }
421
422 $this->formatDisplay($rows, FALSE);
423
424 // assign variables to templates
425 $this->doTemplateAssignment($rows);
426
427 // do print / pdf / instance stuff if needed
428 $this->endPostProcess($rows);
429 }
430
74cf4551
EM
431 /**
432 * @param $rows
433 */
6a488035
TO
434 function buildChart(&$rows) {
435
436 $graphRows = array();
9d72cede
EM
437 $count = 0;
438 $display = array();
6a488035
TO
439
440 $current_year = $this->_params['yid_value'];
441 $previous_year = $current_year - 1;
442 $interval[$previous_year] = $previous_year;
443 $interval['life_time'] = 'Life Time';
444
445 foreach ($rows as $key => $row) {
9d72cede
EM
446 $display['life_time'] = CRM_Utils_Array::value('life_time', $display) +
447 $row['civicrm_life_time_total'];
448 $display[$previous_year] =
449 CRM_Utils_Array::value($previous_year, $display) + $row[$previous_year];
6a488035
TO
450 }
451
9d72cede 452 $config = CRM_Core_Config::Singleton();
6a488035 453 $graphRows['value'] = $display;
9d72cede
EM
454 $chartInfo = array(
455 'legend' => ts('Lybunt Report'),
6a488035
TO
456 'xname' => ts('Year'),
457 'yname' => ts('Amount (%1)', array(1 => $config->defaultCurrency)),
458 );
459 if ($this->_params['charts']) {
460 // build chart.
461 CRM_Utils_OpenFlashChart::reportChart($graphRows, $this->_params['charts'], $interval, $chartInfo);
462 $this->assign('chartType', $this->_params['charts']);
463 }
464 }
465
74cf4551
EM
466 /**
467 * @param $rows
468 */
6a488035 469 function alterDisplay(&$rows) {
72a9af52
NG
470 // custom code to alter rows
471 $entryFound = FALSE;
472
6a488035
TO
473 foreach ($rows as $rowNum => $row) {
474 //Convert Display name into link
475 if (array_key_exists('civicrm_contact_sort_name', $row) &&
476 array_key_exists('civicrm_contribution_contact_id', $row)
477 ) {
478 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
9d72cede
EM
479 'reset=1&force=1&id_op=eq&id_value=' .
480 $row['civicrm_contribution_contact_id'],
6a488035
TO
481 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
482 );
483 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
484 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
72a9af52 485 $entryFound = TRUE;
6a488035 486 }
d62fab33
RN
487
488 // convert campaign_id to campaign title
489 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
490 if ($value = $row['civicrm_contribution_campaign_id']) {
491 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
492 $entryFound = TRUE;
493 }
494 }
a27c90f2 495
72a9af52
NG
496 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ? TRUE : $entryFound;
497
498 // skip looking further in rows, if first row itself doesn't
499 // have the column we need
500 if (!$entryFound) {
501 break;
a27c90f2 502 }
6a488035
TO
503 }
504 }
505
506 // Override "This Year" $op options
74cf4551
EM
507 /**
508 * @param string $type
509 * @param null $fieldName
510 *
511 * @return array
512 */
1b36206c 513 function getOperationPair($type = "string", $fieldName = NULL) {
6a488035 514 if ($fieldName == 'yid') {
9d72cede
EM
515 return array(
516 'calendar' => ts('Is Calendar Year'),
517 'fiscal' => ts('Fiscal Year Starting')
518 );
6a488035
TO
519 }
520 return parent::getOperationPair($type, $fieldName);
521 }
522}
523