Merge pull request #3880 from rohankatkar/webtestCRM-15108
[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 'civicrm_group' =>
199 array(
200 'dao' => 'CRM_Contact_DAO_Group',
201 'alias' => 'cgroup',
202 'filters' =>
203 array(
204 'gid' =>
205 array(
206 'name' => 'group_id',
207 'title' => ts(' Group'),
208 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
209 'group' => TRUE,
210 'options' => CRM_Core_PseudoConstant::group(),
211 ),
212 ),
213 )
214 )
215 + $this->getAddressColumns(array('group_by' => FALSE))
216 + $this->getPhoneColumns();
217 // If we have a campaign, build out the relevant elements
218 $this->_tagFilter = TRUE;
219 if ($campaignEnabled && !empty($this->activeCampaigns)) {
220 $this->_columns['civicrm_pledge']['fields']['campaign_id'] = array(
221 'title' => 'Campaign',
222 'default' => 'false',
223 );
224 $this->_columns['civicrm_pledge']['filters']['campaign_id'] = array('title' => ts('Campaign'),
225 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
226 'options' => $this->activeCampaigns,
227 );
228 $this->_columns['civicrm_pledge']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
229
230 }
231
232 $this->_tagFilter = TRUE;
233 $this->_currencyColumn = 'civicrm_pledge_currency';
234 parent::__construct();
235 }
236
237 function preProcess() {
238 parent::preProcess();
239 }
240
241 function select() {
242 parent::select();
243 }
244 /*
245 * If we are retrieving total paid we need to define the inclusion of pledge_payment
246 */
247 /**
248 * @param $tableName
249 * @param $tableKey
250 * @param $fieldName
251 * @param $field
252 *
253 * @return bool|string
254 */
255 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
256 if($fieldName == 'total_paid'){
257 $this->_totalPaid = TRUE; // add pledge_payment join
258 $this->_columnHeaders["{$tableName}_{$fieldName}"] = array(
259 'title' => $field['title'],
260 'type' => $field['type']
261 );
262 return "COALESCE(sum({$this->_aliases[$tableName]}.actual_amount), 0) as {$tableName}_{$fieldName}";
263 }
264 if($fieldName == 'balance_due'){
265 $cancelledStatus = array_search('Cancelled', $this->_pledgeStatuses);
266 $completedStatus = array_search('Completed', $this->_pledgeStatuses);
267 $this->_totalPaid = TRUE; // add pledge_payment join
268 $this->_columnHeaders["{$tableName}_{$fieldName}"] = $field['title'];
269 $this->_columnHeaders["{$tableName}_{$fieldName}"] = array(
270 'title' => $field['title'],
271 'type' => $field['type']
272 );
273 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}";
274 }
275 return FALSE;
276 }
277
278 function groupBy() {
279 parent::groupBy();
280 if (empty($this->_groupBy) && $this->_totalPaid) {
281 $this->_groupBy = " GROUP BY {$this->_aliases['civicrm_pledge']}.id, {$this->_aliases['civicrm_pledge']}.currency" ;
282 }
283 }
284 function from() {
285 $this->_from = "
286 FROM civicrm_pledge {$this->_aliases['civicrm_pledge']}
287 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
288 ON ({$this->_aliases['civicrm_contact']}.id =
289 {$this->_aliases['civicrm_pledge']}.contact_id )
290 {$this->_aclFrom} ";
291
292 if($this->_totalPaid){
293 $this->_from .= "
294 LEFT JOIN civicrm_pledge_payment {$this->_aliases['civicrm_pledge_payment']} ON
295 {$this->_aliases['civicrm_pledge']}.id = {$this->_aliases['civicrm_pledge_payment']}.pledge_id
296 AND {$this->_aliases['civicrm_pledge_payment']}.status_id = 1
297 ";
298 }
299
300 $this->addPhoneFromClause();
301 $this->addAddressFromClause();
302 // include email field if email column is to be included
303 if ($this->_emailField) {
304 $this->_from .= "
305 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
306 ON ({$this->_aliases['civicrm_contact']}.id =
307 {$this->_aliases['civicrm_email']}.contact_id) AND
308 {$this->_aliases['civicrm_email']}.is_primary = 1\n";
309 }
310 }
311
312 /**
313 * @param $rows
314 *
315 * @return array
316 */
317 function statistics(&$rows) {
318 $statistics = parent::statistics($rows);
319 //regenerate the from field without extra left join on pledge payments
320 $this->_totalPaid = FALSE;
321 $this->from();
322 $this->customDataFrom();
323 if (!$this->_having) {
324 $totalAmount = $average = array();
325 $count = 0;
326 $select = "
327 SELECT COUNT({$this->_aliases['civicrm_pledge']}.amount ) as count,
328 SUM({$this->_aliases['civicrm_pledge']}.amount ) as amount,
329 ROUND(AVG({$this->_aliases['civicrm_pledge']}.amount), 2) as avg,
330 {$this->_aliases['civicrm_pledge']}.currency as currency
331 ";
332
333 $group = "GROUP BY {$this->_aliases['civicrm_pledge']}.currency";
334 $sql = "{$select} {$this->_from} {$this->_where} {$group}";
335 $dao = CRM_Core_DAO::executeQuery($sql);
336 $count = $index = $totalCount = 0;
337 // this will run once per currency
338 while($dao->fetch()) {
339 $totalAmount = CRM_Utils_Money::format($dao->amount, $dao->currency);
340 $average = CRM_Utils_Money::format($dao->avg, $dao->currency);
341 $count = $dao->count;
342 $totalCount .= $count;
343 $statistics['counts']['amount' . $index] = array(
344 'title' => ts('Total Amount Pledged (') . $dao->currency . ')',
345 'value' => $totalAmount,
346 'type' => CRM_Utils_Type::T_STRING,
347 );
348 $statistics['counts']['avg' . $index] = array(
349 'title' => ts('Average (') . $dao->currency . ')',
350 'value' => $average,
351 'type' => CRM_Utils_Type::T_STRING,
352 );
353 $statistics['counts']['count' . $index] = array(
354 'title' => ts('Total No Pledges (') . $dao->currency . ')',
355 'value' => $count,
356 'type' => CRM_Utils_Type::T_INT,
357 );
358 $index ++;
359 }
360 if($totalCount > $count) {
361 $statistics['counts']['count' . $index] = array(
362 'title' => ts('Total No Pledges'),
363 'value' => $totalCount,
364 'type' => CRM_Utils_Type::T_INT,
365 );
366 }
367 }
368 return $statistics;
369 }
370
371 function orderBy() {
372 $this->_orderBy = "ORDER BY {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_contact']}.id";
373 }
374
375 function where() {
376 $clauses = array();
377 foreach ($this->_columns as $tableName => $table) {
378 if (array_key_exists('filters', $table)) {
379 foreach ($table['filters'] as $fieldName => $field) {
380 $clause = NULL;
381 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
382 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
383 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
384 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
385
386 if ($relative || $from || $to) {
387 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
388 }
389 }
390 else {
391 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
392 if ($op) {
393 $clause = $this->whereClause($field,
394 $op,
395 CRM_Utils_Array::value("{$fieldName}_value",
396 $this->_params
397 ),
398 CRM_Utils_Array::value("{$fieldName}_min",
399 $this->_params
400 ),
401 CRM_Utils_Array::value("{$fieldName}_max",
402 $this->_params
403 )
404 );
405 }
406 }
407
408 if (!empty($clause)) {
409 $clauses[] = $clause;
410 }
411 }
412 }
413 }
414 if (empty($clauses)) {
415 $this->_where = "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) ";
416 }
417 else {
418 $this->_where = "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) AND
419 " . implode(' AND ', $clauses);
420 }
421
422 if ($this->_aclWhere) {
423 $this->_where .= " AND {$this->_aclWhere} ";
424 }
425 }
426
427 function postProcess() {
428
429 $this->beginPostProcess();
430
431 // get the acl clauses built before we assemble the query
432 $this->buildACLClause($this->_aliases['civicrm_contact']);
433 $sql = $this->buildQuery();
434 $rows = $payment = array();
435
436 $dao = CRM_Core_DAO::executeQuery($sql);
437
438 // Set pager for the Main Query only which displays basic information
439 $this->setPager();
440 $this->assign('columnHeaders', $this->_columnHeaders);
441
442 while ($dao->fetch()) {
443 $pledgeID = $dao->civicrm_pledge_id;
444 foreach ($this->_columnHeaders as $columnHeadersKey => $columnHeadersValue) {
445 $row = array();
446 if (property_exists($dao, $columnHeadersKey)) {
447 $display[$pledgeID][$columnHeadersKey] = $dao->$columnHeadersKey;
448 }
449 }
450 $pledgeIDArray[] = $pledgeID;
451 }
452
453 // Add Special headers
454 $this->_columnHeaders['scheduled_date'] = array(
455 'type' => CRM_Utils_Type::T_DATE,
456 'title' => 'Next Payment Due',
457 );
458 $this->_columnHeaders['scheduled_amount'] = array(
459 'type' => CRM_Utils_Type::T_MONEY,
460 'title' => 'Next Payment Amount',
461 );
462 $this->_columnHeaders['status_id'] = NULL;
463
464 /*
465 * this is purely about ordering the total paid & balance due fields off to the end
466 * of the table in case custom or address fields cause them to fall in the middle
467 * (arguably the pledge amount should be moved to after these fields too)
468 *
469 */
470 $tableHeaders = array(
471 'civicrm_pledge_payment_total_paid',
472 'civicrm_pledge_payment_balance_due'
473 );
474
475 foreach ($tableHeaders as $header) {
476 //per above, unset & reset them so they move to the end
477 if(isset($this->_columnHeaders[$header])){
478 $headervalue = $this->_columnHeaders[$header];
479 unset($this->_columnHeaders[$header]);
480 $this->_columnHeaders[$header] = $headervalue;
481 }
482 }
483
484 // To Display Payment Details of pledged amount
485 // for pledge payments In Progress
486 if (!empty($display)) {
487 $sqlPayment = "
488 SELECT min(payment.scheduled_date) as scheduled_date,
489 payment.pledge_id,
490 payment.scheduled_amount,
491 pledge.contact_id
492
493 FROM civicrm_pledge_payment payment
494 LEFT JOIN civicrm_pledge pledge
495 ON pledge.id = payment.pledge_id
496
497 WHERE payment.status_id = 2
498
499 GROUP BY payment.pledge_id";
500
501 $daoPayment = CRM_Core_DAO::executeQuery($sqlPayment);
502
503 while ($daoPayment->fetch()) {
504 foreach ($pledgeIDArray as $key => $val) {
505 if ($val == $daoPayment->pledge_id) {
506
507 $display[$daoPayment->pledge_id]['scheduled_date'] = $daoPayment->scheduled_date;
508
509 $display[$daoPayment->pledge_id]['scheduled_amount'] = $daoPayment->scheduled_amount;
510 }
511 }
512 }
513 }
514
515 // Displaying entire data on the form
516 if (!empty($display)) {
517 foreach ($display as $key => $value) {
518 $row = array();
519 foreach ($this->_columnHeaders as $columnKey => $columnValue) {
520 if (array_key_exists($columnKey, $value)) {
521 $row[$columnKey] = !empty($value[$columnKey]) ? $value[$columnKey] : '';
522 }
523 }
524 $rows[] = $row;
525 }
526 }
527
528 unset($this->_columnHeaders['status_id']);
529 unset($this->_columnHeaders['civicrm_pledge_id']);
530 unset($this->_columnHeaders['civicrm_pledge_contact_id']);
531
532 $this->formatDisplay($rows, FALSE);
533 $this->doTemplateAssignment($rows);
534 $this->endPostProcess($rows);
535 }
536
537 /**
538 * @param $rows
539 */
540 function alterDisplay(&$rows) {
541 // custom code to alter rows
542 $entryFound = FALSE;
543 $checkList = array();
544 $display_flag = $prev_cid = $cid = 0;
545
546 foreach ($rows as $rowNum => $row) {
547 if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') {
548 // don't repeat contact details if its same as the previous row
549 if (array_key_exists('civicrm_pledge_contact_id', $row)) {
550 if ($cid = $row['civicrm_pledge_contact_id']) {
551 if ($rowNum == 0) {
552 $prev_cid = $cid;
553 }
554 else {
555 if ($prev_cid == $cid) {
556 $display_flag = 1;
557 $prev_cid = $cid;
558 }
559 else {
560 $display_flag = 0;
561 $prev_cid = $cid;
562 }
563 }
564
565 if ($display_flag) {
566 foreach ($row as $colName => $colVal) {
567 if (in_array($colName, $this->_noRepeats)) {
568 unset($rows[$rowNum][$colName]);
569 }
570 }
571 }
572 $entryFound = TRUE;
573 }
574 }
575 }
576
577 // convert display name to links
578 if (array_key_exists('civicrm_contact_sort_name', $row) &&
579 array_key_exists('civicrm_pledge_contact_id', $row)
580 ) {
581 $url = CRM_Utils_System::url("civicrm/contact/view",
582 'reset=1&cid=' . $row['civicrm_pledge_contact_id'],
583 $this->_absoluteUrl
584 );
585 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
586 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
587 $entryFound = TRUE;
588 }
589
590 //handle status id
591 if (array_key_exists('civicrm_pledge_status_id', $row)) {
592 if ($value = $row['civicrm_pledge_status_id']) {
593 $rows[$rowNum]['civicrm_pledge_status_id'] = CRM_Contribute_PseudoConstant::contributionStatus($value);
594 }
595 $entryFound = TRUE;
596 }
597
598 // If using campaigns, convert campaign_id to campaign title
599 if (array_key_exists('civicrm_pledge_campaign_id', $row)) {
600 if ($value = $row['civicrm_pledge_campaign_id']) {
601 $rows[$rowNum]['civicrm_pledge_campaign_id'] = $this->activeCampaigns[$value];
602 }
603 $entryFound = TRUE;
604 }
605
606 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'pledge/detail', 'List all pledge(s) for this ') ? TRUE : $entryFound;
607
608 // skip looking further in rows, if first row itself doesn't
609 // have the column we need
610 if (!$entryFound) {
611 break;
612 }
613 }
614 }
615 }
616