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