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