INFRA-132 - Misc
[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->_columns += $this->addAddressFields();
116 $this->_columns += 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 = "Group BY {$this->_aliases['civicrm_contribution']}.contact_id, " .
319 self::fiscalYearOffset($this->_aliases['civicrm_contribution'] .
320 '.receive_date') . " WITH ROLLUP ";
321 }
322
323 /**
324 * @param $rows
325 *
326 * @return array
327 */
328 public function statistics(&$rows) {
329 $statistics = parent::statistics($rows);
330
331 if (!empty($rows)) {
332 $select = "
333 SELECT
334 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount ";
335
336 $sql = "{$select} {$this->_from} {$this->_where}";
337 $dao = CRM_Core_DAO::executeQuery($sql);
338 if ($dao->fetch()) {
339 $statistics['counts']['amount'] = array(
340 'value' => $dao->amount,
341 'title' => 'Total LifeTime',
342 'type' => CRM_Utils_Type::T_MONEY,
343 );
344 }
345 }
346 return $statistics;
347 }
348
349 public function postProcess() {
350 // get ready with post process params
351 $this->beginPostProcess();
352
353 $this->buildACLClause($this->_aliases['civicrm_contact']);
354 $this->select();
355 $this->from();
356 $this->where();
357 $this->groupBy();
358
359 $rows = $contactIds = array();
360 if (empty($this->_params['charts'])) {
361 $this->limit();
362 $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}";
363
364 $dao = CRM_Core_DAO::executeQuery($getContacts);
365
366 while ($dao->fetch()) {
367 $contactIds[] = $dao->cid;
368 }
369 $dao->free();
370 $this->setPager();
371 }
372
373 if (!empty($contactIds) || !empty($this->_params['charts'])) {
374 if (!empty($this->_params['charts'])) {
375 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}";
376 }
377 else {
378 $sql = "" .
379 "{$this->_select} {$this->_from} WHERE {$this->_aliases['civicrm_contact']}.id IN (" .
380 implode(',', $contactIds) .
381 ") AND {$this->_aliases['civicrm_contribution']}.is_test = 0 {$this->_statusClause} {$this->_groupBy} ";
382 }
383
384 $current_year = $this->_params['yid_value'];
385 $previous_year = $current_year - 1;
386 $previous_pyear = $current_year - 2;
387 $previous_ppyear = $current_year - 3;
388 $upTo_year = $current_year - 4;
389
390 $rows = $row = array();
391 $dao = CRM_Core_DAO::executeQuery($sql);
392 $contributionSum = 0;
393 $yearcal = array();
394 while ($dao->fetch()) {
395 if (!$dao->civicrm_contribution_contact_id) {
396 continue;
397 }
398 $row = array();
399 foreach ($this->_columnHeaders as $key => $value) {
400 if (property_exists($dao, $key)) {
401 $rows[$dao->civicrm_contribution_contact_id][$key] = $dao->$key;
402 }
403 }
404 if ($dao->civicrm_contribution_receive_date) {
405 if ($dao->civicrm_contribution_receive_date > $upTo_year) {
406 $contributionSum += $dao->civicrm_contribution_total_amount;
407 $rows[$dao->civicrm_contribution_contact_id][$dao->civicrm_contribution_receive_date] = $dao->civicrm_contribution_total_amount;
408 }
409 }
410 else {
411 $rows[$dao->civicrm_contribution_contact_id]['civicrm_life_time_total'] = $dao->civicrm_contribution_total_amount;
412 if (($dao->civicrm_contribution_total_amount - $contributionSum) > 0
413 ) {
414 $rows[$dao->civicrm_contribution_contact_id]["civicrm_upto_{$upTo_year}"]
415 = $dao->civicrm_contribution_total_amount - $contributionSum;
416 }
417 $contributionSum = 0;
418 }
419 }
420 $dao->free();
421 }
422 // format result set.
423 $this->formatDisplay($rows, FALSE);
424
425 // assign variables to templates
426 $this->doTemplateAssignment($rows);
427
428 // do print / pdf / instance stuff if needed
429 $this->endPostProcess($rows);
430 }
431
432 /**
433 * @param $rows
434 */
435 public function buildChart(&$rows) {
436 $graphRows = array();
437 $count = 0;
438 $current_year = $this->_params['yid_value'];
439 $previous_year = $current_year - 1;
440 $previous_two_year = $current_year - 2;
441 $previous_three_year = $current_year - 3;
442 $upto = $current_year - 4;
443
444 $interval[$previous_year] = $previous_year;
445 $interval[$previous_two_year] = $previous_two_year;
446 $interval[$previous_three_year] = $previous_three_year;
447 $interval["upto_{$upto}"] = "Up To {$upto}";
448
449 foreach ($rows as $key => $row) {
450 $display["upto_{$upto}"]
451 = CRM_Utils_Array::value("upto_{$upto}", $display)
452 + CRM_Utils_Array::value("civicrm_upto_{$upto}", $row);
453 $display[$previous_year]
454 = CRM_Utils_Array::value($previous_year, $display)
455 + CRM_Utils_Array::value($previous_year, $row);
456 $display[$previous_two_year]
457 = CRM_Utils_Array::value($previous_two_year, $display)
458 + CRM_Utils_Array::value($previous_two_year, $row);
459 $display[$previous_three_year]
460 = CRM_Utils_Array::value($previous_three_year, $display)
461 + CRM_Utils_Array::value($previous_three_year, $row);
462 }
463
464 $graphRows['value'] = $display;
465 $config = CRM_Core_Config::Singleton();
466 $chartInfo = array(
467 'legend' => 'Sybunt Report',
468 'xname' => 'Year',
469 'yname' => "Amount ({$config->defaultCurrency})",
470 );
471 if ($this->_params['charts']) {
472 // build the chart.
473 CRM_Utils_OpenFlashChart::reportChart($graphRows, $this->_params['charts'], $interval, $chartInfo);
474 $this->assign('chartType', $this->_params['charts']);
475 }
476 }
477
478 /**
479 * @param $rows
480 */
481 public function alterDisplay(&$rows) {
482 // custom code to alter rows
483 $entryFound = FALSE;
484
485 foreach ($rows as $rowNum => $row) {
486 //Convert Display name into link
487 if (array_key_exists('civicrm_contact_sort_name', $row) &&
488 array_key_exists('civicrm_contribution_contact_id', $row)
489 ) {
490 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
491 'reset=1&force=1&id_op=eq&id_value=' .
492 $row['civicrm_contribution_contact_id'],
493 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
494 );
495 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
496 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
497 $entryFound = TRUE;
498 }
499
500 // convert campaign_id to campaign title
501 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
502 if ($value = $row['civicrm_contribution_campaign_id']) {
503 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
504 $entryFound = TRUE;
505 }
506 }
507
508 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ? TRUE : $entryFound;
509
510 // skip looking further in rows, if first row itself doesn't
511 // have the column we need
512 if (!$entryFound) {
513 break;
514 }
515 }
516 }
517
518 /**
519 * Override "This Year" $op options
520 * @param string $type
521 * @param null $fieldName
522 *
523 * @return array
524 */
525 public function getOperationPair($type = "string", $fieldName = NULL) {
526 if ($fieldName == 'yid') {
527 return array(
528 'calendar' => ts('Is Calendar Year'),
529 'fiscal' => ts('Fiscal Year Starting'),
530 );
531 }
532 return parent::getOperationPair($type, $fieldName);
533 }
534
535 }