c819ed9bfe023e55d2eb3d323d70da5cb6ac9e0d
[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 $this->_columns = array(
60 'civicrm_contact' =>
61 array(
62 'dao' => 'CRM_Contact_DAO_Contact',
63 'grouping' => 'contact-field',
64 'fields' =>
65 array(
66 'sort_name' =>
67 array('title' => ts('Donor Name'),
68 'default' => TRUE,
69 'required' => TRUE,
70 ),
71 'first_name' => array('title' => ts('First Name'),
72 ),
73 'last_name' => array('title' => ts('Last Name'),
74 ),
75 ),
76 'filters' =>
77 array(
78 'sort_name' =>
79 array('title' => ts('Donor Name'),
80 'operator' => 'like',
81 ),
82 ),
83 ),
84 'civicrm_email' =>
85 array(
86 'dao' => 'CRM_Core_DAO_Email',
87 'grouping' => 'contact-field',
88 'fields' =>
89 array(
90 'email' =>
91 array('title' => ts('Email'),
92 'default' => TRUE,
93 ),
94 ),
95 ),
96 'civicrm_phone' =>
97 array(
98 'dao' => 'CRM_Core_DAO_Phone',
99 'grouping' => 'contact-field',
100 'fields' =>
101 array(
102 'phone' =>
103 array('title' => ts('Phone'),
104 'default' => TRUE,
105 ),
106 ),
107 ),
108 'civicrm_contribution' =>
109 array(
110 'dao' => 'CRM_Contribute_DAO_Contribution',
111 'fields' =>
112 array(
113 'contact_id' =>
114 array('title' => ts('contactId'),
115 'no_display' => TRUE,
116 'required' => TRUE,
117 'no_repeat' => TRUE,
118 ),
119 'total_amount' =>
120 array('title' => ts('Total Amount'),
121 'no_display' => TRUE,
122 'required' => TRUE,
123 'no_repeat' => TRUE,
124 ),
125 'receive_date' =>
126 array('title' => ts('Year'),
127 'no_display' => TRUE,
128 'required' => TRUE,
129 'no_repeat' => TRUE,
130 ),
131 ),
132 'filters' =>
133 array(
134 'yid' =>
135 array(
136 'name' => 'receive_date',
137 'title' => ts('This Year'),
138 'operatorType' => CRM_Report_Form::OP_SELECT,
139 'options' => $optionYear,
140 'default' => date('Y'),
141 ),
142 'financial_type_id' => array(
143 'title' => ts('Financial Type'),
144 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
145 'options' => CRM_Contribute_PseudoConstant::financialType(),
146 ),
147 'contribution_status_id' =>
148 array('title' => ts('Contribution Status'),
149 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
150 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
151 'default' => array('1'),
152 ),
153 ),
154 ),
155 'civicrm_group' =>
156 array(
157 'dao' => 'CRM_Contact_DAO_GroupContact',
158 'alias' => 'cgroup',
159 'filters' =>
160 array(
161 'gid' =>
162 array(
163 'name' => 'group_id',
164 'title' => ts('Group'),
165 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
166 'group' => TRUE,
167 'options' => CRM_Core_PseudoConstant::group(),
168 ),
169 ),
170 ),
171 );
172
173 $this->_tagFilter = TRUE;
174 parent::__construct();
175 }
176
177 function preProcess() {
178 parent::preProcess();
179 }
180
181 function select() {
182
183 $this->_columnHeaders = $select = array();
184 $current_year = $this->_params['yid_value'];
185 $previous_year = $current_year - 1;
186
187
188 foreach ($this->_columns as $tableName => $table) {
189
190 if (array_key_exists('fields', $table)) {
191 foreach ($table['fields'] as $fieldName => $field) {
192
193 if (CRM_Utils_Array::value('required', $field) ||
194 CRM_Utils_Array::value($fieldName, $this->_params['fields'])
195 ) {
196 if ($fieldName == 'total_amount') {
197 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}";
198
199 $this->_columnHeaders["{$previous_year}"]['type'] = $field['type'];
200 $this->_columnHeaders["{$previous_year}"]['title'] = $previous_year;
201
202 $this->_columnHeaders["civicrm_life_time_total"]['type'] = $field['type'];
203 $this->_columnHeaders["civicrm_life_time_total"]['title'] = 'LifeTime';;
204 }
205 elseif ($fieldName == 'receive_date') {
206 $select[] = self::fiscalYearOffset($field['dbAlias']) . " as {$tableName}_{$fieldName} ";
207 }
208 else {
209 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName} ";
210 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
211 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
212 }
213
214 if (CRM_Utils_Array::value('no_display', $field)) {
215 $this->_columnHeaders["{$tableName}_{$fieldName}"]['no_display'] = TRUE;
216 }
217 }
218 }
219 }
220 }
221
222 $this->_select = "SELECT " . implode(', ', $select) . " ";
223 }
224
225 function from() {
226
227 $this->_from = "
228 FROM civicrm_contribution {$this->_aliases['civicrm_contribution']}
229 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
230 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id
231 {$this->_aclFrom}
232 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
233 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
234 {$this->_aliases['civicrm_email']}.is_primary = 1
235 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
236 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
237 {$this->_aliases['civicrm_phone']}.is_primary = 1 ";
238 }
239
240 function where() {
241 $this->_statusClause = "";
242 $clauses = array($this->_aliases['civicrm_contribution'] . '.is_test = 0');
243 $current_year = $this->_params['yid_value'];
244 $previous_year = $current_year - 1;
245
246 foreach ($this->_columns as $tableName => $table) {
247 if (array_key_exists('filters', $table)) {
248 foreach ($table['filters'] as $fieldName => $field) {
249 $clause = NULL;
250 if ($fieldName == 'yid') {
251 $clause = "contribution_civireport.contact_id NOT IN
252 (SELECT distinct contri.contact_id FROM civicrm_contribution contri
253 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
254 WHERE " . self::fiscalYearOffset('contri.receive_date') . " = $previous_year AND contri.is_test = 0)";
255 }
256 elseif (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
257 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
258 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
259 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
260
261 if ($relative || $from || $to) {
262 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
263 }
264 }
265 else {
266 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
267 if ($op) {
268 $clause = $this->whereClause($field,
269 $op,
270 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
271 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
272 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
273 );
274 if (($fieldName == 'contribution_status_id' || $fieldName == 'financial_type_id') && !empty($clause)) {
275 $this->_statusClause .= " AND " . $clause;
276 }
277 }
278 }
279
280 if (!empty($clause)) {
281 $clauses[] = $clause;
282 }
283 }
284 }
285 }
286
287 $this->_where = 'WHERE ' . implode(' AND ', $clauses);
288
289 if ($this->_aclWhere) {
290 $this->_where .= " AND {$this->_aclWhere} ";
291 }
292 }
293
294 function groupBy() {
295 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_contribution']}.contact_id, " . self::fiscalYearOffset($this->_aliases['civicrm_contribution'] . '.receive_date') . " WITH ROLLUP";
296 $this->assign('chartSupported', TRUE);
297 }
298
299 function statistics(&$rows) {
300 $statistics = parent::statistics($rows);
301 if (!empty($rows)) {
302 $select = "
303 SELECT
304 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount ";
305
306 $sql = "{$select} {$this->_from} {$this->_where}";
307 $dao = CRM_Core_DAO::executeQuery($sql);
308 if ($dao->fetch()) {
309 $statistics['counts']['amount'] = array(
310 'value' => $dao->amount,
311 'title' => 'Total LifeTime',
312 'type' => CRM_Utils_Type::T_MONEY,
313 );
314 }
315 }
316
317 return $statistics;
318 }
319
320 function postProcess() {
321
322 // get ready with post process params
323 $this->beginPostProcess();
324
325 // get the acl clauses built before we assemble the query
326 $this->buildACLClause($this->_aliases['civicrm_contact']);
327 $this->select();
328 $this->from();
329 $this->where();
330 $this->groupBy();
331
332 $rows = $contactIds = array();
333 if (!CRM_Utils_Array::value('charts', $this->_params)) {
334 $this->limit();
335 $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}";
336
337 $dao = CRM_Core_DAO::executeQuery($getContacts);
338
339 while ($dao->fetch()) {
340 $contactIds[] = $dao->cid;
341 }
342 $dao->free();
343 $this->setPager();
344 }
345
346 if (!empty($contactIds) || CRM_Utils_Array::value('charts', $this->_params)) {
347 if (CRM_Utils_Array::value('charts', $this->_params)) {
348 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}";
349 }
350 else {
351 $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} ";
352 }
353
354 $dao = CRM_Core_DAO::executeQuery($sql);
355 $current_year = $this->_params['yid_value'];
356 $previous_year = $current_year - 1;
357
358 while ($dao->fetch()) {
359
360 if (!$dao->civicrm_contribution_contact_id) {
361 continue;
362 }
363
364 $row = array();
365 foreach ($this->_columnHeaders as $key => $value) {
366 if (property_exists($dao, $key)) {
367 $rows[$dao->civicrm_contribution_contact_id][$key] = $dao->$key;
368 }
369 }
370
371 if ($dao->civicrm_contribution_receive_date) {
372 if ($dao->civicrm_contribution_receive_date == $previous_year) {
373 $rows[$dao->civicrm_contribution_contact_id][$dao->civicrm_contribution_receive_date] = $dao->civicrm_contribution_total_amount;
374 }
375 }
376 else {
377 $rows[$dao->civicrm_contribution_contact_id]['civicrm_life_time_total'] = $dao->civicrm_contribution_total_amount;
378 }
379 }
380 $dao->free();
381 }
382
383 $this->formatDisplay($rows, FALSE);
384
385 // assign variables to templates
386 $this->doTemplateAssignment($rows);
387
388 // do print / pdf / instance stuff if needed
389 $this->endPostProcess($rows);
390 }
391
392 function buildChart(&$rows) {
393
394 $graphRows = array();
395 $count = 0;
396 $display = array();
397
398 $current_year = $this->_params['yid_value'];
399 $previous_year = $current_year - 1;
400 $interval[$previous_year] = $previous_year;
401 $interval['life_time'] = 'Life Time';
402
403 foreach ($rows as $key => $row) {
404 $display['life_time'] = CRM_Utils_Array::value('life_time', $display) + $row['civicrm_life_time_total'];
405 $display[$previous_year] = CRM_Utils_Array::value($previous_year, $display) + $row[$previous_year];
406 }
407
408 $config = CRM_Core_Config::Singleton();
409 $graphRows['value'] = $display;
410 $chartInfo = array('legend' => ts('Lybunt Report'),
411 'xname' => ts('Year'),
412 'yname' => ts('Amount (%1)', array(1 => $config->defaultCurrency)),
413 );
414 if ($this->_params['charts']) {
415 // build chart.
416 CRM_Utils_OpenFlashChart::reportChart($graphRows, $this->_params['charts'], $interval, $chartInfo);
417 $this->assign('chartType', $this->_params['charts']);
418 }
419 }
420
421 function alterDisplay(&$rows) {
422 foreach ($rows as $rowNum => $row) {
423 //Convert Display name into link
424 if (array_key_exists('civicrm_contact_sort_name', $row) &&
425 array_key_exists('civicrm_contribution_contact_id', $row)
426 ) {
427 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
428 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contribution_contact_id'],
429 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
430 );
431 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
432 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
433 }
434 }
435 }
436
437 // Override "This Year" $op options
438 static function getOperationPair($type = "string", $fieldName = NULL) {
439 if ($fieldName == 'yid') {
440 return array('calendar' => ts('Is Calendar Year'), 'fiscal' => ts('Fiscal Year Starting'));
441 }
442 return parent::getOperationPair($type, $fieldName);
443 }
444 }
445