CRM-19184 - Activities target contact list does not truncate
[civicrm-core.git] / CRM / Report / Form / Contribute / Sybunt.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
32 */
33 class CRM_Report_Form_Contribute_Sybunt extends CRM_Report_Form {
34
35 protected $_charts = array(
36 '' => 'Tabular',
37 'barChart' => 'Bar Chart',
38 'pieChart' => 'Pie Chart',
39 );
40
41 protected $_customGroupExtends = array(
42 'Contact',
43 'Individual',
44 'Contribution',
45 );
46
47 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
48
49 /**
50 */
51 public function __construct() {
52 $this->_rollup = 'WITH ROLLUP';
53 $this->_autoIncludeIndexedFieldsAsOrderBys = 1;
54 $yearsInPast = 10;
55 $yearsInFuture = 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'];
60 $date['minYear']++;
61 }
62
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);
70 }
71
72 $this->_columns = array(
73 'civicrm_contact' => array(
74 'dao' => 'CRM_Contact_DAO_Contact',
75 'grouping' => 'contact-field',
76 'fields' => array(
77 'sort_name' => array(
78 'title' => ts('Donor Name'),
79 'required' => TRUE,
80 ),
81 'first_name' => array(
82 'title' => ts('First Name'),
83 ),
84 'middle_name' => array(
85 'title' => ts('Middle Name'),
86 ),
87 'last_name' => array(
88 'title' => ts('Last Name'),
89 ),
90 'id' => array(
91 'no_display' => TRUE,
92 'required' => TRUE,
93 ),
94 'gender_id' => array(
95 'title' => ts('Gender'),
96 ),
97 'birth_date' => array(
98 'title' => ts('Birth Date'),
99 ),
100 'age' => array(
101 'title' => ts('Age'),
102 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
103 ),
104 'contact_type' => array(
105 'title' => ts('Contact Type'),
106 ),
107 'contact_sub_type' => array(
108 'title' => ts('Contact Subtype'),
109 ),
110 ),
111 'grouping' => 'contact-fields',
112 'order_bys' => array(
113 'sort_name' => array(
114 'title' => ts('Last Name, First Name'),
115 'default' => '1',
116 'default_weight' => '0',
117 'default_order' => 'ASC',
118 ),
119 'first_name' => array(
120 'name' => 'first_name',
121 'title' => ts('First Name'),
122 ),
123 'gender_id' => array(
124 'name' => 'gender_id',
125 'title' => ts('Gender'),
126 ),
127 'birth_date' => array(
128 'name' => 'birth_date',
129 'title' => ts('Birth Date'),
130 ),
131 'age_at_event' => array(
132 'name' => 'age_at_event',
133 'title' => ts('Age at Event'),
134 ),
135 'contact_type' => array(
136 'title' => ts('Contact Type'),
137 ),
138 'contact_sub_type' => array(
139 'title' => ts('Contact Subtype'),
140 ),
141 ),
142 'filters' => array(
143 'sort_name' => array(
144 'title' => ts('Donor Name'),
145 'operator' => 'like',
146 ),
147 'id' => array(
148 'title' => ts('Contact ID'),
149 'no_display' => TRUE,
150 ),
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'),
155 ),
156 'birth_date' => array(
157 'title' => ts('Birth Date'),
158 'operatorType' => CRM_Report_Form::OP_DATE,
159 ),
160 'contact_type' => array(
161 'title' => ts('Contact Type'),
162 ),
163 'contact_sub_type' => array(
164 'title' => ts('Contact Subtype'),
165 ),
166 ),
167 ),
168 'civicrm_line_item' => array(
169 'dao' => 'CRM_Price_DAO_LineItem',
170 ),
171 'civicrm_email' => array(
172 'dao' => 'CRM_Core_DAO_Email',
173 'grouping' => 'contact-field',
174 'fields' => array(
175 'email' => array(
176 'title' => ts('Email'),
177 'default' => TRUE,
178 ),
179 ),
180 ),
181 'civicrm_phone' => array(
182 'dao' => 'CRM_Core_DAO_Phone',
183 'grouping' => 'contact-field',
184 'fields' => array(
185 'phone' => array(
186 'title' => ts('Phone'),
187 'default' => TRUE,
188 ),
189 ),
190 ),
191 );
192 $this->_columns += $this->addAddressFields();
193 $this->_columns += array(
194 'civicrm_contribution' => array(
195 'dao' => 'CRM_Contribute_DAO_Contribution',
196 'fields' => array(
197 'contact_id' => array(
198 'title' => ts('contactId'),
199 'no_display' => TRUE,
200 'required' => TRUE,
201 'no_repeat' => TRUE,
202 ),
203 'total_amount' => array(
204 'title' => ts('Total Amount'),
205 'no_display' => TRUE,
206 'required' => TRUE,
207 'no_repeat' => TRUE,
208 ),
209 'receive_date' => array(
210 'title' => ts('Year'),
211 'no_display' => TRUE,
212 'required' => TRUE,
213 'no_repeat' => TRUE,
214 ),
215 ),
216 'filters' => array(
217 'yid' => array(
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,
224 ),
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(),
230 ),
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'),
236 ),
237 ),
238 ),
239 );
240
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',
246 );
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,
252 );
253 }
254
255 $this->_groupFilter = TRUE;
256 $this->_tagFilter = TRUE;
257 parent::__construct();
258 }
259
260 public function preProcess() {
261 parent::preProcess();
262 }
263
264 public function select() {
265 $select = array();
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;
272
273 foreach ($this->_columns as $tableName => $table) {
274 if (array_key_exists('fields', $table)) {
275 foreach ($table['fields'] as $fieldName => $field) {
276
277 if (!empty($field['required']) ||
278 !empty($this->_params['fields'][$fieldName])
279 ) {
280 if ($fieldName == 'total_amount') {
281 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}";
282
283 $this->_columnHeaders["civicrm_upto_{$upTo_year}"]['type'] = $field['type'];
284 $this->_columnHeaders["civicrm_upto_{$upTo_year}"]['title'] = "Up To $upTo_year";
285
286 $this->_columnHeaders["year_{$previous_ppyear}"]['type'] = $field['type'];
287 $this->_columnHeaders["year_{$previous_ppyear}"]['title'] = $previous_ppyear;
288
289 $this->_columnHeaders["year_{$previous_pyear}"]['type'] = $field['type'];
290 $this->_columnHeaders["year_{$previous_pyear}"]['title'] = $previous_pyear;
291
292 $this->_columnHeaders["year_{$previous_year}"]['type'] = $field['type'];
293 $this->_columnHeaders["year_{$previous_year}"]['title'] = $previous_year;
294
295 $this->_columnHeaders["civicrm_life_time_total"]['type'] = $field['type'];
296 $this->_columnHeaders["civicrm_life_time_total"]['title'] = 'LifeTime';;
297 }
298 elseif ($fieldName == 'receive_date') {
299 $select[] = self::fiscalYearOffset($field['dbAlias']) .
300 " as {$tableName}_{$fieldName}";
301 }
302 else {
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'];
306 }
307 if (!empty($field['no_display'])) {
308 $this->_columnHeaders["{$tableName}_{$fieldName}"]['no_display'] = TRUE;
309 }
310 }
311 }
312 }
313 }
314 $this->_selectClauses = $select;
315
316 $this->_select = "SELECT " . implode(', ', $select) . " ";
317 }
318
319 public function from() {
320
321 $this->_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
325 {$this->_aclFrom}";
326
327 if ($this->isTableSelected('civicrm_email')) {
328 $this->_from .= "
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";
332 }
333 if ($this->isTableSelected('civicrm_phone')) {
334 $this->_from .= "
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";
338 }
339 $this->addAddressFromClause();
340 }
341
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) {
348 $clause = NULL;
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 )";
355 }
356 elseif (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE
357 ) {
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);
361
362 if ($relative || $from || $to) {
363 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
364 }
365 }
366 else {
367 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
368 if ($op) {
369 $clause = $this->whereClause($field,
370 $op,
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)
374 );
375 if (($fieldName == 'contribution_status_id' ||
376 $fieldName == 'financial_type_id') && !empty($clause)
377 ) {
378 $this->_statusClause .= " AND " . $clause;
379 }
380 }
381 }
382
383 if (!empty($clause)) {
384 $clauses[] = $clause;
385 }
386 }
387 }
388 }
389
390 $this->_where = "WHERE " . implode(' AND ', $clauses);
391
392 if ($this->_aclWhere) {
393 $this->_where .= " AND {$this->_aclWhere} ";
394 }
395 }
396
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}";
403 }
404
405 /**
406 * @param $rows
407 *
408 * @return array
409 */
410 public function statistics(&$rows) {
411 $statistics = parent::statistics($rows);
412
413 if (!empty($rows)) {
414 $select = "
415 SELECT
416 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount ";
417
418 $sql = "{$select} {$this->_from} {$this->_where}";
419 $dao = CRM_Core_DAO::executeQuery($sql);
420 if ($dao->fetch()) {
421 $statistics['counts']['amount'] = array(
422 'value' => $dao->amount,
423 'title' => 'Total LifeTime',
424 'type' => CRM_Utils_Type::T_MONEY,
425 );
426 }
427 }
428 return $statistics;
429 }
430
431 public function postProcess() {
432 // get ready with post process params
433 $this->beginPostProcess();
434 $this->buildACLClause($this->_aliases['civicrm_contact']);
435 $this->buildQuery();
436
437 $rows = $contactIds = array();
438 if (empty($this->_params['charts'])) {
439 $this->limit();
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}";
441
442 $dao = CRM_Core_DAO::executeQuery($getContacts);
443
444 while ($dao->fetch()) {
445 $contactIds[] = $dao->cid;
446 }
447 $dao->free();
448 $this->setPager();
449 }
450
451 if (!empty($contactIds) || !empty($this->_params['charts'])) {
452 if (!empty($this->_params['charts'])) {
453 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}";
454 }
455 else {
456 $sql = "" .
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} ";
460 }
461
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;
467
468 $rows = $row = array();
469 $dao = CRM_Core_DAO::executeQuery($sql);
470 $contributionSum = 0;
471 $yearcal = array();
472 while ($dao->fetch()) {
473 if (!$dao->civicrm_contribution_contact_id) {
474 continue;
475 }
476 $row = array();
477 foreach ($this->_columnHeaders as $key => $value) {
478 if (property_exists($dao, $key)) {
479 $rows[$dao->civicrm_contribution_contact_id][$key] = $dao->$key;
480 }
481 }
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;
486 }
487 }
488 else {
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
491 ) {
492 $rows[$dao->civicrm_contribution_contact_id]["civicrm_upto_{$upTo_year}"]
493 = $dao->civicrm_contribution_total_amount - $contributionSum;
494 }
495 $contributionSum = 0;
496 }
497 }
498 $dao->free();
499 }
500 // format result set.
501 $this->formatDisplay($rows, FALSE);
502
503 // assign variables to templates
504 $this->doTemplateAssignment($rows);
505
506 // do print / pdf / instance stuff if needed
507 $this->endPostProcess($rows);
508 }
509
510 /**
511 * @param $rows
512 */
513 public function buildChart(&$rows) {
514 $graphRows = array();
515 $count = 0;
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;
521
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}";
526
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);
540 }
541
542 $graphRows['value'] = $display;
543 $config = CRM_Core_Config::Singleton();
544 $chartInfo = array(
545 'legend' => 'Sybunt Report',
546 'xname' => 'Year',
547 'yname' => "Amount ({$config->defaultCurrency})",
548 );
549 if ($this->_params['charts']) {
550 // build the chart.
551 CRM_Utils_OpenFlashChart::reportChart($graphRows, $this->_params['charts'], $interval, $chartInfo);
552 $this->assign('chartType', $this->_params['charts']);
553 }
554 }
555
556 /**
557 * Alter display of rows.
558 *
559 * Iterate through the rows retrieved via SQL and make changes for display purposes,
560 * such as rendering contacts as links.
561 *
562 * @param array $rows
563 * Rows generated by SQL, with an array for each row.
564 */
565 public function alterDisplay(&$rows) {
566 $entryFound = FALSE;
567
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)
572 ) {
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
577 );
578 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
579 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
580 $entryFound = TRUE;
581 }
582
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];
587 $entryFound = TRUE;
588 }
589 }
590
591 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ? TRUE : $entryFound;
592
593 //handle gender
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];
598 }
599 $entryFound = TRUE;
600 }
601
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'];
605 if ($birthDate) {
606 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
607 }
608 $entryFound = TRUE;
609 }
610
611 // skip looking further in rows, if first row itself doesn't
612 // have the column we need
613 if (!$entryFound) {
614 break;
615 }
616 }
617 }
618
619 /**
620 * Override "This Year" $op options
621 * @param string $type
622 * @param null $fieldName
623 *
624 * @return array
625 */
626 public function getOperationPair($type = "string", $fieldName = NULL) {
627 if ($fieldName == 'yid') {
628 return array(
629 'calendar' => ts('Is Calendar Year'),
630 'fiscal' => ts('Fiscal Year Starting'),
631 );
632 }
633 return parent::getOperationPair($type, $fieldName);
634 }
635
636 }