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