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