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