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