Merge pull request #4882 from colemanw/CRM-15789
[civicrm-core.git] / CRM / Report / Form / Contribute / Lybunt.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35 class 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;
47 protected $lifeTime_where = NULL;
48
49 /**
50 *
51 */
52 /**
53 *
54 */
55 public function __construct() {
56 $yearsInPast = 10;
57 $yearsInFuture = 1;
58 $date = CRM_Core_SelectValues::date('custom', NULL, $yearsInPast, $yearsInFuture);
59 $count = $date['maxYear'];
60 while ($date['minYear'] <= $count) {
61 $optionYear[$date['minYear']] = $date['minYear'];
62 $date['minYear']++;
63 }
64
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);
72 }
73
74 $this->_columns = array(
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 ),
96 ),
97 'filters' => array(
98 'sort_name' => array(
99 'title' => ts('Donor Name'),
100 'operator' => 'like',
101 ),
102 ),
103 ),
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 ),
112 ),
113 ),
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 ),
122 ),
123 ),
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 ),
148 ),
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 ),
168 ),
169 ),
170 );
171
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 );
178 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
179 'title' => ts('Campaign'),
180 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
181 'options' => $this->activeCampaigns,
182 );
183 }
184
185 $this->_groupFilter = TRUE;
186 $this->_tagFilter = TRUE;
187 parent::__construct();
188 }
189
190 public function preProcess() {
191 parent::preProcess();
192 }
193
194 public function select() {
195
196 $this->_columnHeaders = $select = array();
197 $current_year = $this->_params['yid_value'];
198 $previous_year = $current_year - 1;
199
200 foreach ($this->_columns as $tableName => $table) {
201
202 if (array_key_exists('fields', $table)) {
203 foreach ($table['fields'] as $fieldName => $field) {
204
205 if (!empty($field['required']) ||
206 !empty($this->_params['fields'][$fieldName])
207 ) {
208 if ($fieldName == 'total_amount') {
209 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}";
210
211 $this->_columnHeaders["{$previous_year}"]['type'] = $field['type'];
212 $this->_columnHeaders["{$previous_year}"]['title'] = $previous_year;
213
214 $this->_columnHeaders["civicrm_life_time_total"]['type'] = $field['type'];
215 $this->_columnHeaders["civicrm_life_time_total"]['title'] = 'LifeTime';;
216 }
217 elseif ($fieldName == 'receive_date') {
218 $select[] = self::fiscalYearOffset($field['dbAlias']) .
219 " as {$tableName}_{$fieldName} ";
220 }
221 else {
222 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName} ";
223 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
224 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
225 }
226
227 if (!empty($field['no_display'])) {
228 $this->_columnHeaders["{$tableName}_{$fieldName}"]['no_display'] = TRUE;
229 }
230 }
231 }
232 }
233 }
234
235 $this->_select = "SELECT " . implode(', ', $select) . " ";
236 }
237
238 public function from() {
239
240 $this->_from = "
241 FROM civicrm_contribution {$this->_aliases['civicrm_contribution']}
242 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
243 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id
244 {$this->_aclFrom}";
245
246 if ($this->isTableSelected('civicrm_email')) {
247 $this->_from .= "
248 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
249 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
250 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
251 }
252 if ($this->isTableSelected('civicrm_phone')) {
253 $this->_from .= "
254 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
255 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
256 {$this->_aliases['civicrm_phone']}.is_primary = 1";
257 }
258 $this->addAddressFromClause();
259 }
260
261 public function where() {
262 $this->_statusClause = "";
263 $clauses = array($this->_aliases['civicrm_contribution'] . '.is_test = 0');
264 $current_year = $this->_params['yid_value'];
265 $previous_year = $current_year - 1;
266
267 foreach ($this->_columns as $tableName => $table) {
268 if (array_key_exists('filters', $table)) {
269 foreach ($table['filters'] as $fieldName => $field) {
270 $clause = NULL;
271 if ($fieldName == 'yid') {
272 $clause = "contribution_civireport.contact_id NOT IN
273 (SELECT distinct contri.contact_id FROM civicrm_contribution contri
274 WHERE contri.is_test = 0 AND " .
275 self::fiscalYearOffset('contri.receive_date') . " = $current_year) AND contribution_civireport.contact_id IN (SELECT distinct contri.contact_id FROM civicrm_contribution contri
276 WHERE " . self::fiscalYearOffset('contri.receive_date') .
277 " = $previous_year AND contri.is_test = 0)";
278 }
279 elseif (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE
280 ) {
281 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
282 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
283 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
284
285 if ($relative || $from || $to) {
286 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
287 }
288 }
289 else {
290 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
291 if ($op) {
292 $clause = $this->whereClause($field,
293 $op,
294 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
295 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
296 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
297 );
298 if (($fieldName == 'contribution_status_id' ||
299 $fieldName == 'financial_type_id') && !empty($clause)
300 ) {
301 $this->_statusClause .= " AND " . $clause;
302 }
303 }
304 }
305
306 if (!empty($clause)) {
307 $clauses[] = $clause;
308 }
309 }
310 }
311 }
312
313 $this->_where = 'WHERE ' . implode(' AND ', $clauses);
314
315 if ($this->_aclWhere) {
316 $this->_where .= " AND {$this->_aclWhere} ";
317 }
318 }
319
320 public function groupBy() {
321 $this->_groupBy =
322 "GROUP BY {$this->_aliases['civicrm_contribution']}.contact_id, " .
323 self::fiscalYearOffset($this->_aliases['civicrm_contribution'] .
324 '.receive_date') . " WITH ROLLUP";
325 $this->assign('chartSupported', TRUE);
326 }
327
328 /**
329 * @param $rows
330 *
331 * @return array
332 */
333 public function statistics(&$rows) {
334 $statistics = parent::statistics($rows);
335 if (!empty($rows)) {
336 $select = "
337 SELECT
338 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount ";
339
340 $sql = "{$select} {$this->_from} {$this->_where}";
341 $dao = CRM_Core_DAO::executeQuery($sql);
342 if ($dao->fetch()) {
343 $statistics['counts']['amount'] = array(
344 'value' => $dao->amount,
345 'title' => 'Total LifeTime',
346 'type' => CRM_Utils_Type::T_MONEY,
347 );
348 }
349 }
350
351 return $statistics;
352 }
353
354 public function postProcess() {
355
356 // get ready with post process params
357 $this->beginPostProcess();
358
359 // get the acl clauses built before we assemble the query
360 $this->buildACLClause($this->_aliases['civicrm_contact']);
361 $this->select();
362 $this->from();
363 $this->where();
364 $this->groupBy();
365
366 $rows = $contactIds = array();
367 if (empty($this->_params['charts'])) {
368 $this->limit();
369 $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}";
370
371 $dao = CRM_Core_DAO::executeQuery($getContacts);
372
373 while ($dao->fetch()) {
374 $contactIds[] = $dao->cid;
375 }
376 $dao->free();
377 $this->setPager();
378 }
379
380 if (!empty($contactIds) || !empty($this->_params['charts'])) {
381 if (!empty($this->_params['charts'])) {
382 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}";
383 }
384 else {
385 $sql =
386 "{$this->_select} {$this->_from} WHERE {$this->_aliases['civicrm_contact']}.id IN (" .
387 implode(',', $contactIds) .
388 ") AND {$this->_aliases['civicrm_contribution']}.is_test = 0 {$this->_statusClause} {$this->_groupBy} ";
389 }
390
391 $dao = CRM_Core_DAO::executeQuery($sql);
392 $current_year = $this->_params['yid_value'];
393 $previous_year = $current_year - 1;
394
395 while ($dao->fetch()) {
396
397 if (!$dao->civicrm_contribution_contact_id) {
398 continue;
399 }
400
401 $row = array();
402 foreach ($this->_columnHeaders as $key => $value) {
403 if (property_exists($dao, $key)) {
404 $rows[$dao->civicrm_contribution_contact_id][$key] = $dao->$key;
405 }
406 }
407
408 if ($dao->civicrm_contribution_receive_date) {
409 if ($dao->civicrm_contribution_receive_date == $previous_year) {
410 $rows[$dao->civicrm_contribution_contact_id][$dao->civicrm_contribution_receive_date] = $dao->civicrm_contribution_total_amount;
411 }
412 }
413 else {
414 $rows[$dao->civicrm_contribution_contact_id]['civicrm_life_time_total'] = $dao->civicrm_contribution_total_amount;
415 }
416 }
417 $dao->free();
418 }
419
420 $this->formatDisplay($rows, FALSE);
421
422 // assign variables to templates
423 $this->doTemplateAssignment($rows);
424
425 // do print / pdf / instance stuff if needed
426 $this->endPostProcess($rows);
427 }
428
429 /**
430 * @param $rows
431 */
432 public function buildChart(&$rows) {
433
434 $graphRows = array();
435 $count = 0;
436 $display = array();
437
438 $current_year = $this->_params['yid_value'];
439 $previous_year = $current_year - 1;
440 $interval[$previous_year] = $previous_year;
441 $interval['life_time'] = 'Life Time';
442
443 foreach ($rows as $key => $row) {
444 $display['life_time'] = CRM_Utils_Array::value('life_time', $display) +
445 $row['civicrm_life_time_total'];
446 $display[$previous_year] =
447 CRM_Utils_Array::value($previous_year, $display) + $row[$previous_year];
448 }
449
450 $config = CRM_Core_Config::Singleton();
451 $graphRows['value'] = $display;
452 $chartInfo = array(
453 'legend' => ts('Lybunt Report'),
454 'xname' => ts('Year'),
455 'yname' => ts('Amount (%1)', array(1 => $config->defaultCurrency)),
456 );
457 if ($this->_params['charts']) {
458 // build chart.
459 CRM_Utils_OpenFlashChart::reportChart($graphRows, $this->_params['charts'], $interval, $chartInfo);
460 $this->assign('chartType', $this->_params['charts']);
461 }
462 }
463
464 /**
465 * @param $rows
466 */
467 public function alterDisplay(&$rows) {
468 // custom code to alter rows
469 $entryFound = FALSE;
470
471 foreach ($rows as $rowNum => $row) {
472 //Convert Display name into link
473 if (array_key_exists('civicrm_contact_sort_name', $row) &&
474 array_key_exists('civicrm_contribution_contact_id', $row)
475 ) {
476 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
477 'reset=1&force=1&id_op=eq&id_value=' .
478 $row['civicrm_contribution_contact_id'],
479 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
480 );
481 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
482 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
483 $entryFound = TRUE;
484 }
485
486 // convert campaign_id to campaign title
487 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
488 if ($value = $row['civicrm_contribution_campaign_id']) {
489 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
490 $entryFound = TRUE;
491 }
492 }
493
494 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ? TRUE : $entryFound;
495
496 // skip looking further in rows, if first row itself doesn't
497 // have the column we need
498 if (!$entryFound) {
499 break;
500 }
501 }
502 }
503
504 // Override "This Year" $op options
505 /**
506 * @param string $type
507 * @param null $fieldName
508 *
509 * @return array
510 */
511 public function getOperationPair($type = "string", $fieldName = NULL) {
512 if ($fieldName == 'yid') {
513 return array(
514 'calendar' => ts('Is Calendar Year'),
515 'fiscal' => ts('Fiscal Year Starting'),
516 );
517 }
518 return parent::getOperationPair($type, $fieldName);
519 }
520 }