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