ecc162e99bba300c4da6fd37155d79a61af021e7
[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
314 if ($this->isTableSelected('civicrm_email')) {
315 $this->_from .= "
316 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
317 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
318 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
319 }
320 if ($this->isTableSelected('civicrm_phone')) {
321 $this->_from .= "
322 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
323 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
324 {$this->_aliases['civicrm_phone']}.is_primary = 1";
325 }
326 $this->addAddressFromClause();
327 }
328
329 public function where() {
330 $this->_statusClause = "";
331 $clauses = array($this->_aliases['civicrm_contribution'] . '.is_test = 0');
332 $current_year = $this->_params['yid_value'];
333 $previous_year = $current_year - 1;
334
335 foreach ($this->_columns as $tableName => $table) {
336 if (array_key_exists('filters', $table)) {
337 foreach ($table['filters'] as $fieldName => $field) {
338 $clause = NULL;
339 if ($fieldName == 'yid') {
340 $clause = "contribution_civireport.contact_id NOT IN
341 (SELECT distinct contri.contact_id FROM civicrm_contribution contri
342 WHERE contri.is_test = 0 AND " .
343 self::fiscalYearOffset('contri.receive_date') . " = $current_year) AND contribution_civireport.contact_id IN (SELECT distinct contri.contact_id FROM civicrm_contribution contri
344 WHERE " . self::fiscalYearOffset('contri.receive_date') .
345 " = $previous_year AND contri.is_test = 0) AND " . self::fiscalYearOffset('contribution_civireport.receive_date') . " = $previous_year";
346 }
347 elseif (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE
348 ) {
349 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
350 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
351 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
352
353 if ($relative || $from || $to) {
354 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
355 }
356 }
357 else {
358 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
359 if ($op) {
360 $clause = $this->whereClause($field,
361 $op,
362 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
363 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
364 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
365 );
366 if (($fieldName == 'contribution_status_id' ||
367 $fieldName == 'financial_type_id') && !empty($clause)
368 ) {
369 $this->_statusClause .= " AND " . $clause;
370 }
371 }
372 }
373
374 if (!empty($clause)) {
375 $clauses[] = $clause;
376 }
377 }
378 }
379 }
380
381 $this->_where = 'WHERE ' . implode(' AND ', $clauses);
382
383 if ($this->_aclWhere) {
384 $this->_where .= " AND {$this->_aclWhere} ";
385 }
386 }
387
388 public function groupBy() {
389 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_contribution']}.contact_id, " .
390 self::fiscalYearOffset($this->_aliases['civicrm_contribution'] .
391 '.receive_date') . " WITH ROLLUP";
392 $this->assign('chartSupported', TRUE);
393 }
394
395 /**
396 * @param $rows
397 *
398 * @return array
399 */
400 public function statistics(&$rows) {
401 $statistics = parent::statistics($rows);
402 if (!empty($rows)) {
403 $select = "SELECT SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount ";
404 $where = "WHERE {$this->_aliases['civicrm_contact']}.id IN (" . implode(',', $this->_contactIds) . ")
405 AND {$this->_aliases['civicrm_contribution']}.is_test = 0 {$this->_statusClause}";
406
407 $sql = "{$select} {$this->_from} {$where}";
408 $dao = CRM_Core_DAO::executeQuery($sql);
409 if ($dao->fetch()) {
410 $statistics['counts']['amount'] = array(
411 'value' => $dao->amount,
412 'title' => 'Total LifeTime',
413 'type' => CRM_Utils_Type::T_MONEY,
414 );
415 }
416 }
417
418 return $statistics;
419 }
420
421 public function postProcess() {
422
423 // get ready with post process params
424 $this->beginPostProcess();
425
426 // get the acl clauses built before we assemble the query
427 $this->buildACLClause($this->_aliases['civicrm_contact']);
428 $this->select();
429 $this->from();
430 $this->where();
431 $this->groupBy();
432 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
433
434 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp AS SELECT {$this->_aliases['civicrm_contribution']}.id {$this->_from}
435 INNER JOIN civicrm_line_item {$this->_aliases['civicrm_line_item']}
436 ON {$this->_aliases['civicrm_contribution']}.id = {$this->_aliases['civicrm_line_item']}.contribution_id AND
437 {$this->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
438 {$this->_where}
439 AND {$this->_aliases['civicrm_contribution']}.financial_type_id IN (" . implode(',' , array_keys($financialTypes)) . ")
440 AND {$this->_aliases['civicrm_line_item']}.financial_type_id IN (" . implode(',' , array_keys($financialTypes)) . ")
441 {$this->_groupBy}";
442 CRM_Core_DAO::executeQuery($sql);
443 $this->_from .= "
444 INNER JOIN civicrm_contribution_temp temp ON {$this->_aliases['civicrm_contribution']}.id = temp.id ";
445
446 $rows = $this->_contactIds = array();
447 $this->limit();
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}";
449
450 $dao = CRM_Core_DAO::executeQuery($getContacts);
451
452 while ($dao->fetch()) {
453 $this->_contactIds[] = $dao->cid;
454 }
455 $dao->free();
456 if (empty($this->_params['charts'])) {
457 $this->setPager();
458 }
459
460 if (!empty($this->_contactIds) || !empty($this->_params['charts'])) {
461 $sql = "{$this->_select} {$this->_from} WHERE {$this->_aliases['civicrm_contact']}.id IN (" . implode(',', $this->_contactIds) . ")
462 AND {$this->_aliases['civicrm_contribution']}.is_test = 0 {$this->_statusClause} {$this->_groupBy} ";
463
464 $dao = CRM_Core_DAO::executeQuery($sql);
465 $current_year = $this->_params['yid_value'];
466 $previous_year = $current_year - 1;
467
468 while ($dao->fetch()) {
469
470 if (!$dao->civicrm_contribution_contact_id) {
471 continue;
472 }
473
474 $row = array();
475 foreach ($this->_columnHeaders as $key => $value) {
476 if (property_exists($dao, $key)) {
477 $rows[$dao->civicrm_contribution_contact_id][$key] = $dao->$key;
478 }
479 }
480
481 if ($dao->civicrm_contribution_receive_date) {
482 if ($dao->civicrm_contribution_receive_date == $previous_year) {
483 $rows[$dao->civicrm_contribution_contact_id][$dao->civicrm_contribution_receive_date] = $dao->civicrm_contribution_total_amount;
484 }
485 }
486 else {
487 $rows[$dao->civicrm_contribution_contact_id]['civicrm_life_time_total'] = $dao->civicrm_contribution_total_amount;
488 }
489 }
490 $dao->free();
491 }
492
493 $this->formatDisplay($rows, FALSE);
494
495 // assign variables to templates
496 $this->doTemplateAssignment($rows);
497
498 // do print / pdf / instance stuff if needed
499 $this->endPostProcess($rows);
500 }
501
502 /**
503 * @param $rows
504 */
505 public function buildChart(&$rows) {
506
507 $graphRows = array();
508 $count = 0;
509 $display = array();
510
511 $current_year = $this->_params['yid_value'];
512 $previous_year = $current_year - 1;
513 $interval[$previous_year] = $previous_year;
514 $interval['life_time'] = 'Life Time';
515
516 foreach ($rows as $key => $row) {
517 $display['life_time'] = CRM_Utils_Array::value('life_time', $display) +
518 $row['civicrm_life_time_total'];
519 $display[$previous_year] = CRM_Utils_Array::value($previous_year, $display) + $row[$previous_year];
520 }
521
522 $config = CRM_Core_Config::Singleton();
523 $graphRows['value'] = $display;
524 $chartInfo = array(
525 'legend' => ts('Lybunt Report'),
526 'xname' => ts('Year'),
527 'yname' => ts('Amount (%1)', array(1 => $config->defaultCurrency)),
528 );
529 if ($this->_params['charts']) {
530 // build chart.
531 CRM_Utils_OpenFlashChart::reportChart($graphRows, $this->_params['charts'], $interval, $chartInfo);
532 $this->assign('chartType', $this->_params['charts']);
533 }
534 }
535
536 /**
537 * Alter display of rows.
538 *
539 * Iterate through the rows retrieved via SQL and make changes for display purposes,
540 * such as rendering contacts as links.
541 *
542 * @param array $rows
543 * Rows generated by SQL, with an array for each row.
544 */
545 public function alterDisplay(&$rows) {
546 $entryFound = FALSE;
547
548 foreach ($rows as $rowNum => $row) {
549 //Convert Display name into link
550 if (array_key_exists('civicrm_contact_sort_name', $row) &&
551 array_key_exists('civicrm_contribution_contact_id', $row)
552 ) {
553 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
554 'reset=1&force=1&id_op=eq&id_value=' .
555 $row['civicrm_contribution_contact_id'],
556 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
557 );
558 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
559 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
560 $entryFound = TRUE;
561 }
562
563 // convert campaign_id to campaign title
564 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
565 if ($value = $row['civicrm_contribution_campaign_id']) {
566 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
567 $entryFound = TRUE;
568 }
569 }
570
571 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ? TRUE : $entryFound;
572
573 //handle gender
574 if (array_key_exists('civicrm_contact_gender_id', $row)) {
575 if ($value = $row['civicrm_contact_gender_id']) {
576 $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
577 $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value];
578 }
579 $entryFound = TRUE;
580 }
581
582 // display birthday in the configured custom format
583 if (array_key_exists('civicrm_contact_birth_date', $row)) {
584 $birthDate = $row['civicrm_contact_birth_date'];
585 if ($birthDate) {
586 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
587 }
588 $entryFound = TRUE;
589 }
590
591 // skip looking further in rows, if first row itself doesn't
592 // have the column we need
593 if (!$entryFound) {
594 break;
595 }
596 }
597 }
598
599 /**
600 * Override "This Year" $op options
601 * @param string $type
602 * @param null $fieldName
603 *
604 * @return array
605 */
606 public function getOperationPair($type = "string", $fieldName = NULL) {
607 if ($fieldName == 'yid') {
608 return array(
609 'calendar' => ts('Is Calendar Year'),
610 'fiscal' => ts('Fiscal Year Starting'),
611 );
612 }
613 return parent::getOperationPair($type, $fieldName);
614 }
615
616 }