a few comment fixes
[civicrm-core.git] / CRM / Report / Form / Contribute / Sybunt.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35class 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
74cf4551 44 /**
74cf4551 45 */
00be9182 46 public function __construct() {
9d72cede 47 $yearsInPast = 10;
6a488035 48 $yearsInFuture = 1;
9d72cede
EM
49 $date = CRM_Core_SelectValues::date('custom', NULL, $yearsInPast, $yearsInFuture);
50 $count = $date['maxYear'];
6a488035
TO
51 while ($date['minYear'] <= $count) {
52 $optionYear[$date['minYear']] = $date['minYear'];
53 $date['minYear']++;
54 }
55
d62fab33
RN
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);
f813f78e 63 }
d62fab33 64
6a488035 65 $this->_columns = array(
a1a2a83d
TO
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,
6a488035 73 ),
a1a2a83d
TO
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'),
6a488035
TO
85 ),
86 ),
a1a2a83d
TO
87 'filters' => array(
88 'sort_name' => array(
89 'title' => ts('Donor Name'),
90 'operator' => 'like',
6a488035
TO
91 ),
92 ),
a1a2a83d
TO
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,
6a488035
TO
101 ),
102 ),
a1a2a83d
TO
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,
6a488035 131 ),
a1a2a83d
TO
132 'receive_date' => array(
133 'title' => ts('Year'),
134 'no_display' => TRUE,
135 'required' => TRUE,
136 'no_repeat' => TRUE,
6a488035
TO
137 ),
138 ),
a1a2a83d
TO
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 );
6a488035 161
d62fab33
RN
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 );
9d72cede
EM
168 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
169 'title' => ts('Campaign'),
d62fab33
RN
170 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
171 'options' => $this->activeCampaigns,
172 );
173 }
174
16e2e80c 175 $this->_groupFilter = TRUE;
6a488035
TO
176 $this->_tagFilter = TRUE;
177 parent::__construct();
178 }
179
00be9182 180 public function preProcess() {
6a488035
TO
181 parent::preProcess();
182 }
183
00be9182 184 public function select() {
6a488035
TO
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
9d72cede
EM
197 if (!empty($field['required']) ||
198 !empty($this->_params['fields'][$fieldName])
199 ) {
6a488035
TO
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') {
9d72cede
EM
219 $select[] = self::fiscalYearOffset($field['dbAlias']) .
220 " as {$tableName}_{$fieldName}";
6a488035
TO
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 }
a7488080 227 if (!empty($field['no_display'])) {
6a488035
TO
228 $this->_columnHeaders["{$tableName}_{$fieldName}"]['no_display'] = TRUE;
229 }
230 }
231 }
232 }
233 }
234
235 $this->_select = "SELECT " . implode(', ', $select) . " ";
236 }
237
00be9182 238 public function from() {
6a488035 239
74cf4551 240 $this->_from = "
6a488035 241 FROM civicrm_contribution {$this->_aliases['civicrm_contribution']}
a27c90f2
NG
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 }
72a9af52 258 $this->addAddressFromClause();
6a488035
TO
259 }
260
00be9182 261 public function where() {
6a488035
TO
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
9d72cede
EM
271 WHERE cont.id = contri.contact_id AND " .
272 self::fiscalYearOffset('contri.receive_date') .
273 " = {$this->_params['yid_value']} AND contri.is_test = 0 )";
6a488035 274 }
84178120 275 elseif (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE
9d72cede 276 ) {
6a488035 277 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
9d72cede
EM
278 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
279 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
6a488035
TO
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 );
9d72cede
EM
294 if (($fieldName == 'contribution_status_id' ||
295 $fieldName == 'financial_type_id') && !empty($clause)
296 ) {
6a488035
TO
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
00be9182 316 public function groupBy() {
6a488035 317 $this->assign('chartSupported', TRUE);
6c552737 318 $this->_groupBy = "Group BY {$this->_aliases['civicrm_contribution']}.contact_id, " .
9d72cede
EM
319 self::fiscalYearOffset($this->_aliases['civicrm_contribution'] .
320 '.receive_date') . " WITH ROLLUP ";
6a488035
TO
321 }
322
74cf4551
EM
323 /**
324 * @param $rows
325 *
326 * @return array
327 */
00be9182 328 public function statistics(&$rows) {
6a488035
TO
329 $statistics = parent::statistics($rows);
330
331 if (!empty($rows)) {
332 $select = "
39eb89f4 333 SELECT
6a488035
TO
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
00be9182 349 public function postProcess() {
6a488035
TO
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();
a7488080 360 if (empty($this->_params['charts'])) {
6a488035
TO
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
8cc574cf 373 if (!empty($contactIds) || !empty($this->_params['charts'])) {
a7488080 374 if (!empty($this->_params['charts'])) {
6a488035
TO
375 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}";
376 }
377 else {
6c552737 378 $sql = "" .
9d72cede
EM
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} ";
6a488035
TO
382 }
383
9d72cede
EM
384 $current_year = $this->_params['yid_value'];
385 $previous_year = $current_year - 1;
386 $previous_pyear = $current_year - 2;
6a488035 387 $previous_ppyear = $current_year - 3;
9d72cede 388 $upTo_year = $current_year - 4;
6a488035 389
9d72cede
EM
390 $rows = $row = array();
391 $dao = CRM_Core_DAO::executeQuery($sql);
6a488035 392 $contributionSum = 0;
9d72cede 393 $yearcal = array();
6a488035
TO
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;
9d72cede
EM
412 if (($dao->civicrm_contribution_total_amount - $contributionSum) > 0
413 ) {
6c552737
TO
414 $rows[$dao->civicrm_contribution_contact_id]["civicrm_upto_{$upTo_year}"]
415 = $dao->civicrm_contribution_total_amount - $contributionSum;
6a488035
TO
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
74cf4551
EM
432 /**
433 * @param $rows
434 */
00be9182 435 public function buildChart(&$rows) {
9d72cede
EM
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;
6a488035 441 $previous_three_year = $current_year - 3;
9d72cede 442 $upto = $current_year - 4;
6a488035
TO
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) {
6c552737
TO
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);
6a488035
TO
462 }
463
464 $graphRows['value'] = $display;
9d72cede
EM
465 $config = CRM_Core_Config::Singleton();
466 $chartInfo = array(
6a488035
TO
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
74cf4551 478 /**
ced9bfed
EM
479 * Alter display of rows.
480 *
481 * Iterate through the rows retrieved via SQL and make changes for display purposes,
482 * such as rendering contacts as links.
483 *
484 * @param array $rows
485 * Rows generated by SQL, with an array for each row.
74cf4551 486 */
00be9182 487 public function alterDisplay(&$rows) {
72a9af52 488 $entryFound = FALSE;
6a488035
TO
489
490 foreach ($rows as $rowNum => $row) {
491 //Convert Display name into link
492 if (array_key_exists('civicrm_contact_sort_name', $row) &&
493 array_key_exists('civicrm_contribution_contact_id', $row)
494 ) {
495 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
9d72cede
EM
496 'reset=1&force=1&id_op=eq&id_value=' .
497 $row['civicrm_contribution_contact_id'],
6a488035
TO
498 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
499 );
500 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
501 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
72a9af52 502 $entryFound = TRUE;
6a488035 503 }
f813f78e 504
d62fab33
RN
505 // convert campaign_id to campaign title
506 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
507 if ($value = $row['civicrm_contribution_campaign_id']) {
508 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
509 $entryFound = TRUE;
510 }
511 }
a27c90f2 512
72a9af52
NG
513 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ? TRUE : $entryFound;
514
515 // skip looking further in rows, if first row itself doesn't
516 // have the column we need
517 if (!$entryFound) {
518 break;
a27c90f2 519 }
6a488035
TO
520 }
521 }
522
74cf4551 523 /**
4f1f1f2a 524 * Override "This Year" $op options
74cf4551
EM
525 * @param string $type
526 * @param null $fieldName
527 *
528 * @return array
529 */
00be9182 530 public function getOperationPair($type = "string", $fieldName = NULL) {
6a488035 531 if ($fieldName == 'yid') {
9d72cede
EM
532 return array(
533 'calendar' => ts('Is Calendar Year'),
21dfd5f5 534 'fiscal' => ts('Fiscal Year Starting'),
9d72cede 535 );
6a488035
TO
536 }
537 return parent::getOperationPair($type, $fieldName);
538 }
96025800 539
6a488035 540}