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