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