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