Ensure reports use nested group selector and remove boilerplate
[civicrm-core.git] / CRM / Report / Form / Pledge / Detail.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 * !!!!!!!!!!!!!!!!!!!!
31 * NB: this is named detail but behaves like a summary report.
32 * It is also accessed through the Pledge Summary link in the UI
33 * This should presumably be changed.
34 * ~ Doten
35 * !!!!!!!!!!!!!!!!!!!!
36 *
37 */
38
39 /**
40 *
41 * @package CRM
42 * @copyright CiviCRM LLC (c) 2004-2014
43 * $Id$
44 *
45 */
46 class CRM_Report_Form_Pledge_Detail extends CRM_Report_Form {
47
48 protected $_summary = NULL;
49 protected $_totalPaid = FALSE;
50 protected $_pledgeStatuses = array();
51 protected $_customGroupExtends = array(
52 'Pledge',
53 'Individual'
54 );
55
56 /**
57 *
58 */
59 /**
60 *
61 */
62 function __construct() {
63 $this->_pledgeStatuses = CRM_Contribute_PseudoConstant::contributionStatus();
64 // Check if CiviCampaign is a) enabled and b) has active campaigns
65 $config = CRM_Core_Config::singleton();
66 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
67 if ($campaignEnabled) {
68 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
69 $this->activeCampaigns = $getCampaigns['campaigns'];
70 asort($this->activeCampaigns);
71 }
72
73 $this->_columns = array(
74 'civicrm_contact' =>
75 array(
76 'dao' => 'CRM_Contact_DAO_Contact',
77 'fields' =>
78 array(
79 'sort_name' =>
80 array('title' => ts('Contact Name'),
81 'required' => TRUE,
82 'no_repeat' => TRUE,
83 ),
84 ),
85 'filters' =>
86 array(
87 'sort_name' =>
88 array('title' => ts('Contact Name')),
89 'id' =>
90 array('no_display' => TRUE),
91 ),
92 'grouping' => 'contact-fields',
93 ),
94 'civicrm_email' =>
95 array(
96 'dao' => 'CRM_Core_DAO_Email',
97 'fields' =>
98 array(
99 'email' =>
100 array('no_repeat' => TRUE),
101 ),
102 'grouping' => 'contact-fields',
103 ),
104 'civicrm_pledge' =>
105 array(
106 'dao' => 'CRM_Pledge_DAO_Pledge',
107 'fields' =>
108 array(
109 'id' =>
110 array(
111 'no_display' => TRUE,
112 'required' => TRUE,
113 ),
114 'contact_id' =>
115 array(
116 'no_display' => TRUE,
117 'required' => TRUE,
118 ),
119 'amount' =>
120 array('title' => ts('Pledge Amount'),
121 'required' => TRUE,
122 'type' => CRM_Utils_Type::T_MONEY,
123 ),
124 'currency' =>
125 array(
126 'required' => TRUE,
127 'no_display' => TRUE,
128 ),
129 'frequency_unit' =>
130 array('title' => ts('Frequency Unit'),
131 ),
132 'installments' =>
133 array('title' => ts('Installments'),
134 ),
135 'pledge_create_date' =>
136 array('title' => ts('Pledge Made Date'),
137 ),
138 'start_date' =>
139 array('title' => ts('Pledge Start Date'),
140 'type' => CRM_Utils_Type::T_DATE,
141 ),
142 'end_date' =>
143 array('title' => ts('Pledge End Date'),
144 'type' => CRM_Utils_Type::T_DATE,
145 ),
146 'status_id' =>
147 array('title' => ts('Pledge Status'),
148 'required' => TRUE,
149 ),
150 ),
151 'filters' =>
152 array(
153 'pledge_create_date' =>
154 array(
155 'title' => 'Pledge Made Date',
156 'operatorType' => CRM_Report_Form::OP_DATE,
157 ),
158 'pledge_amount' =>
159 array('title' => ts('Pledged Amount'),
160 'operatorType' => CRM_Report_Form::OP_INT,
161 ),
162 'currency' =>
163 array('title' => 'Currency',
164 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
165 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
166 'default' => NULL,
167 'type' => CRM_Utils_Type::T_STRING,
168 ),
169 'sid' =>
170 array(
171 'name' => 'status_id',
172 'title' => ts('Pledge Status'),
173 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
174 'options' => CRM_Core_OptionGroup::values('contribution_status'),
175 ),
176
177 ),
178 ),
179 'civicrm_pledge_payment' =>
180 array(
181 'dao' => 'CRM_Pledge_DAO_PledgePayment',
182 'fields' =>
183 array(
184 'total_paid' =>
185 array(
186 'title' => ts('Total Amount Paid'),
187 'type' => CRM_Utils_Type::T_MONEY,
188 ),
189 'balance_due' =>
190 array(
191 'title' => ts('Balance Due'),
192 'default' => TRUE,
193 'type' => CRM_Utils_Type::T_MONEY,
194 ),
195
196 ),
197 ),
198 )
199 + $this->getAddressColumns(array('group_by' => FALSE))
200 + $this->getPhoneColumns();
201 // If we have a campaign, build out the relevant elements
202 $this->_tagFilter = TRUE;
203 if ($campaignEnabled && !empty($this->activeCampaigns)) {
204 $this->_columns['civicrm_pledge']['fields']['campaign_id'] = array(
205 'title' => 'Campaign',
206 'default' => 'false',
207 );
208 $this->_columns['civicrm_pledge']['filters']['campaign_id'] = array('title' => ts('Campaign'),
209 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
210 'options' => $this->activeCampaigns,
211 );
212 $this->_columns['civicrm_pledge']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
213
214 }
215
216 $this->_groupFilter = TRUE;
217 $this->_tagFilter = TRUE;
218 $this->_currencyColumn = 'civicrm_pledge_currency';
219 parent::__construct();
220 }
221
222 function preProcess() {
223 parent::preProcess();
224 }
225
226 function select() {
227 parent::select();
228 }
229 /*
230 * If we are retrieving total paid we need to define the inclusion of pledge_payment
231 */
232 /**
233 * @param $tableName
234 * @param $tableKey
235 * @param $fieldName
236 * @param $field
237 *
238 * @return bool|string
239 */
240 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
241 if($fieldName == 'total_paid'){
242 $this->_totalPaid = TRUE; // add pledge_payment join
243 $this->_columnHeaders["{$tableName}_{$fieldName}"] = array(
244 'title' => $field['title'],
245 'type' => $field['type']
246 );
247 return "COALESCE(sum({$this->_aliases[$tableName]}.actual_amount), 0) as {$tableName}_{$fieldName}";
248 }
249 if($fieldName == 'balance_due'){
250 $cancelledStatus = array_search('Cancelled', $this->_pledgeStatuses);
251 $completedStatus = array_search('Completed', $this->_pledgeStatuses);
252 $this->_totalPaid = TRUE; // add pledge_payment join
253 $this->_columnHeaders["{$tableName}_{$fieldName}"] = $field['title'];
254 $this->_columnHeaders["{$tableName}_{$fieldName}"] = array(
255 'title' => $field['title'],
256 'type' => $field['type']
257 );
258 return "IF({$this->_aliases['civicrm_pledge']}.status_id IN({$cancelledStatus}, $completedStatus), 0, COALESCE({$this->_aliases['civicrm_pledge']}.amount, 0) - COALESCE(sum({$this->_aliases[$tableName]}.actual_amount),0)) as {$tableName}_{$fieldName}";
259 }
260 return FALSE;
261 }
262
263 function groupBy() {
264 parent::groupBy();
265 if (empty($this->_groupBy) && $this->_totalPaid) {
266 $this->_groupBy = " GROUP BY {$this->_aliases['civicrm_pledge']}.id, {$this->_aliases['civicrm_pledge']}.currency" ;
267 }
268 }
269 function from() {
270 $this->_from = "
271 FROM civicrm_pledge {$this->_aliases['civicrm_pledge']}
272 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
273 ON ({$this->_aliases['civicrm_contact']}.id =
274 {$this->_aliases['civicrm_pledge']}.contact_id )
275 {$this->_aclFrom} ";
276
277 if($this->_totalPaid){
278 $this->_from .= "
279 LEFT JOIN civicrm_pledge_payment {$this->_aliases['civicrm_pledge_payment']} ON
280 {$this->_aliases['civicrm_pledge']}.id = {$this->_aliases['civicrm_pledge_payment']}.pledge_id
281 AND {$this->_aliases['civicrm_pledge_payment']}.status_id = 1
282 ";
283 }
284
285 $this->addPhoneFromClause();
286 $this->addAddressFromClause();
287 // include email field if email column is to be included
288 if ($this->_emailField) {
289 $this->_from .= "
290 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
291 ON ({$this->_aliases['civicrm_contact']}.id =
292 {$this->_aliases['civicrm_email']}.contact_id) AND
293 {$this->_aliases['civicrm_email']}.is_primary = 1\n";
294 }
295 }
296
297 /**
298 * @param $rows
299 *
300 * @return array
301 */
302 function statistics(&$rows) {
303 $statistics = parent::statistics($rows);
304 //regenerate the from field without extra left join on pledge payments
305 $this->_totalPaid = FALSE;
306 $this->from();
307 $this->customDataFrom();
308 if (!$this->_having) {
309 $totalAmount = $average = array();
310 $count = 0;
311 $select = "
312 SELECT COUNT({$this->_aliases['civicrm_pledge']}.amount ) as count,
313 SUM({$this->_aliases['civicrm_pledge']}.amount ) as amount,
314 ROUND(AVG({$this->_aliases['civicrm_pledge']}.amount), 2) as avg,
315 {$this->_aliases['civicrm_pledge']}.currency as currency
316 ";
317
318 $group = "GROUP BY {$this->_aliases['civicrm_pledge']}.currency";
319 $sql = "{$select} {$this->_from} {$this->_where} {$group}";
320 $dao = CRM_Core_DAO::executeQuery($sql);
321 $count = $index = $totalCount = 0;
322 // this will run once per currency
323 while($dao->fetch()) {
324 $totalAmount = CRM_Utils_Money::format($dao->amount, $dao->currency);
325 $average = CRM_Utils_Money::format($dao->avg, $dao->currency);
326 $count = $dao->count;
327 $totalCount .= $count;
328 $statistics['counts']['amount' . $index] = array(
329 'title' => ts('Total Amount Pledged (') . $dao->currency . ')',
330 'value' => $totalAmount,
331 'type' => CRM_Utils_Type::T_STRING,
332 );
333 $statistics['counts']['avg' . $index] = array(
334 'title' => ts('Average (') . $dao->currency . ')',
335 'value' => $average,
336 'type' => CRM_Utils_Type::T_STRING,
337 );
338 $statistics['counts']['count' . $index] = array(
339 'title' => ts('Total No Pledges (') . $dao->currency . ')',
340 'value' => $count,
341 'type' => CRM_Utils_Type::T_INT,
342 );
343 $index ++;
344 }
345 if($totalCount > $count) {
346 $statistics['counts']['count' . $index] = array(
347 'title' => ts('Total No Pledges'),
348 'value' => $totalCount,
349 'type' => CRM_Utils_Type::T_INT,
350 );
351 }
352 }
353 return $statistics;
354 }
355
356 function orderBy() {
357 $this->_orderBy = "ORDER BY {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_contact']}.id";
358 }
359
360 function where() {
361 $clauses = array();
362 foreach ($this->_columns as $tableName => $table) {
363 if (array_key_exists('filters', $table)) {
364 foreach ($table['filters'] as $fieldName => $field) {
365 $clause = NULL;
366 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
367 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
368 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
369 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
370
371 if ($relative || $from || $to) {
372 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
373 }
374 }
375 else {
376 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
377 if ($op) {
378 $clause = $this->whereClause($field,
379 $op,
380 CRM_Utils_Array::value("{$fieldName}_value",
381 $this->_params
382 ),
383 CRM_Utils_Array::value("{$fieldName}_min",
384 $this->_params
385 ),
386 CRM_Utils_Array::value("{$fieldName}_max",
387 $this->_params
388 )
389 );
390 }
391 }
392
393 if (!empty($clause)) {
394 $clauses[] = $clause;
395 }
396 }
397 }
398 }
399 if (empty($clauses)) {
400 $this->_where = "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) ";
401 }
402 else {
403 $this->_where = "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) AND
404 " . implode(' AND ', $clauses);
405 }
406
407 if ($this->_aclWhere) {
408 $this->_where .= " AND {$this->_aclWhere} ";
409 }
410 }
411
412 function postProcess() {
413
414 $this->beginPostProcess();
415
416 // get the acl clauses built before we assemble the query
417 $this->buildACLClause($this->_aliases['civicrm_contact']);
418 $sql = $this->buildQuery();
419 $rows = $payment = array();
420
421 $dao = CRM_Core_DAO::executeQuery($sql);
422
423 // Set pager for the Main Query only which displays basic information
424 $this->setPager();
425 $this->assign('columnHeaders', $this->_columnHeaders);
426
427 while ($dao->fetch()) {
428 $pledgeID = $dao->civicrm_pledge_id;
429 foreach ($this->_columnHeaders as $columnHeadersKey => $columnHeadersValue) {
430 $row = array();
431 if (property_exists($dao, $columnHeadersKey)) {
432 $display[$pledgeID][$columnHeadersKey] = $dao->$columnHeadersKey;
433 }
434 }
435 $pledgeIDArray[] = $pledgeID;
436 }
437
438 // Add Special headers
439 $this->_columnHeaders['scheduled_date'] = array(
440 'type' => CRM_Utils_Type::T_DATE,
441 'title' => 'Next Payment Due',
442 );
443 $this->_columnHeaders['scheduled_amount'] = array(
444 'type' => CRM_Utils_Type::T_MONEY,
445 'title' => 'Next Payment Amount',
446 );
447 $this->_columnHeaders['status_id'] = NULL;
448
449 /*
450 * this is purely about ordering the total paid & balance due fields off to the end
451 * of the table in case custom or address fields cause them to fall in the middle
452 * (arguably the pledge amount should be moved to after these fields too)
453 *
454 */
455 $tableHeaders = array(
456 'civicrm_pledge_payment_total_paid',
457 'civicrm_pledge_payment_balance_due'
458 );
459
460 foreach ($tableHeaders as $header) {
461 //per above, unset & reset them so they move to the end
462 if(isset($this->_columnHeaders[$header])){
463 $headervalue = $this->_columnHeaders[$header];
464 unset($this->_columnHeaders[$header]);
465 $this->_columnHeaders[$header] = $headervalue;
466 }
467 }
468
469 // To Display Payment Details of pledged amount
470 // for pledge payments In Progress
471 if (!empty($display)) {
472 $sqlPayment = "
473 SELECT min(payment.scheduled_date) as scheduled_date,
474 payment.pledge_id,
475 payment.scheduled_amount,
476 pledge.contact_id
477
478 FROM civicrm_pledge_payment payment
479 LEFT JOIN civicrm_pledge pledge
480 ON pledge.id = payment.pledge_id
481
482 WHERE payment.status_id = 2
483
484 GROUP BY payment.pledge_id";
485
486 $daoPayment = CRM_Core_DAO::executeQuery($sqlPayment);
487
488 while ($daoPayment->fetch()) {
489 foreach ($pledgeIDArray as $key => $val) {
490 if ($val == $daoPayment->pledge_id) {
491
492 $display[$daoPayment->pledge_id]['scheduled_date'] = $daoPayment->scheduled_date;
493
494 $display[$daoPayment->pledge_id]['scheduled_amount'] = $daoPayment->scheduled_amount;
495 }
496 }
497 }
498 }
499
500 // Displaying entire data on the form
501 if (!empty($display)) {
502 foreach ($display as $key => $value) {
503 $row = array();
504 foreach ($this->_columnHeaders as $columnKey => $columnValue) {
505 if (array_key_exists($columnKey, $value)) {
506 $row[$columnKey] = !empty($value[$columnKey]) ? $value[$columnKey] : '';
507 }
508 }
509 $rows[] = $row;
510 }
511 }
512
513 unset($this->_columnHeaders['status_id']);
514 unset($this->_columnHeaders['civicrm_pledge_id']);
515 unset($this->_columnHeaders['civicrm_pledge_contact_id']);
516
517 $this->formatDisplay($rows, FALSE);
518 $this->doTemplateAssignment($rows);
519 $this->endPostProcess($rows);
520 }
521
522 /**
523 * @param $rows
524 */
525 function alterDisplay(&$rows) {
526 // custom code to alter rows
527 $entryFound = FALSE;
528 $checkList = array();
529 $display_flag = $prev_cid = $cid = 0;
530
531 foreach ($rows as $rowNum => $row) {
532 if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') {
533 // don't repeat contact details if its same as the previous row
534 if (array_key_exists('civicrm_pledge_contact_id', $row)) {
535 if ($cid = $row['civicrm_pledge_contact_id']) {
536 if ($rowNum == 0) {
537 $prev_cid = $cid;
538 }
539 else {
540 if ($prev_cid == $cid) {
541 $display_flag = 1;
542 $prev_cid = $cid;
543 }
544 else {
545 $display_flag = 0;
546 $prev_cid = $cid;
547 }
548 }
549
550 if ($display_flag) {
551 foreach ($row as $colName => $colVal) {
552 if (in_array($colName, $this->_noRepeats)) {
553 unset($rows[$rowNum][$colName]);
554 }
555 }
556 }
557 $entryFound = TRUE;
558 }
559 }
560 }
561
562 // convert display name to links
563 if (array_key_exists('civicrm_contact_sort_name', $row) &&
564 array_key_exists('civicrm_pledge_contact_id', $row)
565 ) {
566 $url = CRM_Utils_System::url("civicrm/contact/view",
567 'reset=1&cid=' . $row['civicrm_pledge_contact_id'],
568 $this->_absoluteUrl
569 );
570 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
571 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
572 $entryFound = TRUE;
573 }
574
575 //handle status id
576 if (array_key_exists('civicrm_pledge_status_id', $row)) {
577 if ($value = $row['civicrm_pledge_status_id']) {
578 $rows[$rowNum]['civicrm_pledge_status_id'] = CRM_Contribute_PseudoConstant::contributionStatus($value);
579 }
580 $entryFound = TRUE;
581 }
582
583 // If using campaigns, convert campaign_id to campaign title
584 if (array_key_exists('civicrm_pledge_campaign_id', $row)) {
585 if ($value = $row['civicrm_pledge_campaign_id']) {
586 $rows[$rowNum]['civicrm_pledge_campaign_id'] = $this->activeCampaigns[$value];
587 }
588 $entryFound = TRUE;
589 }
590
591 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'pledge/detail', 'List all pledge(s) for this ') ? TRUE : $entryFound;
592
593 // skip looking further in rows, if first row itself doesn't
594 // have the column we need
595 if (!$entryFound) {
596 break;
597 }
598 }
599 }
600 }
601