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