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