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