3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
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.
35 * !!!!!!!!!!!!!!!!!!!!
42 * @copyright CiviCRM LLC (c) 2004-2016
44 class CRM_Report_Form_Pledge_Detail
extends CRM_Report_Form
{
46 protected $_summary = NULL;
47 protected $_totalPaid = FALSE;
48 protected $_pledgeStatuses = array();
49 protected $_customGroupExtends = array(
55 * This report has not been optimised for group filtering.
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.
65 protected $groupFilterNotOptimised = TRUE;
70 public function __construct() {
71 $this->_pledgeStatuses
= CRM_Contribute_PseudoConstant
::contributionStatus();
72 // Check if CiviCampaign is a) enabled and b) has active campaigns
73 $config = CRM_Core_Config
::singleton();
74 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents
);
75 if ($campaignEnabled) {
76 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
77 $this->activeCampaigns
= $getCampaigns['campaigns'];
78 asort($this->activeCampaigns
);
81 $this->_columns
= array(
82 'civicrm_contact' => array(
83 'dao' => 'CRM_Contact_DAO_Contact',
86 'title' => ts('Contact Name'),
92 'sort_name' => array('title' => ts('Contact Name')),
93 'id' => array('no_display' => TRUE),
95 'grouping' => 'contact-fields',
97 'civicrm_email' => array(
98 'dao' => 'CRM_Core_DAO_Email',
100 'email' => array('no_repeat' => TRUE),
102 'grouping' => 'contact-fields',
104 'civicrm_pledge' => array(
105 'dao' => 'CRM_Pledge_DAO_Pledge',
108 'no_display' => TRUE,
111 'contact_id' => array(
112 'no_display' => TRUE,
115 'financial_type_id' => array(
116 'title' => ts('Financial Type'),
119 'title' => ts('Pledge Amount'),
121 'type' => CRM_Utils_Type
::T_MONEY
,
125 'no_display' => TRUE,
127 'frequency_unit' => array(
128 'title' => ts('Frequency Unit'),
130 'installments' => array(
131 'title' => ts('Installments'),
133 'pledge_create_date' => array(
134 'title' => ts('Pledge Made Date'),
136 'start_date' => array(
137 'title' => ts('Pledge Start Date'),
138 'type' => CRM_Utils_Type
::T_DATE
,
141 'title' => ts('Pledge End Date'),
142 'type' => CRM_Utils_Type
::T_DATE
,
144 'status_id' => array(
145 'title' => ts('Pledge Status'),
150 'pledge_create_date' => array(
151 'title' => ts('Pledge Made Date'),
152 'operatorType' => CRM_Report_Form
::OP_DATE
,
154 'pledge_amount' => array(
155 'title' => ts('Pledged Amount'),
156 'operatorType' => CRM_Report_Form
::OP_INT
,
159 'title' => ts('Currency'),
160 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
161 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
163 'type' => CRM_Utils_Type
::T_STRING
,
166 'name' => 'status_id',
167 'title' => ts('Pledge Status'),
168 'type' => CRM_Utils_Type
::T_INT
,
169 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
170 'options' => CRM_Core_OptionGroup
::values('contribution_status'),
172 'financial_type_id' => array(
173 'title' => ts('Financial Type'),
174 'type' => CRM_Utils_Type
::T_INT
,
175 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
176 'options' => CRM_Contribute_PseudoConstant
::financialType(),
181 'civicrm_pledge_payment' => array(
182 'dao' => 'CRM_Pledge_DAO_PledgePayment',
184 'total_paid' => array(
185 'title' => ts('Total Amount Paid'),
186 'type' => CRM_Utils_Type
::T_MONEY
,
188 'balance_due' => array(
189 'title' => ts('Balance Due'),
191 'type' => CRM_Utils_Type
::T_MONEY
,
197 $this->_columns +
= $this->getAddressColumns(array('group_by' => FALSE)) +
$this->getPhoneColumns();
199 // If we have a campaign, build out the relevant elements
200 $this->_tagFilter
= TRUE;
201 if ($campaignEnabled && !empty($this->activeCampaigns
)) {
202 $this->_columns
['civicrm_pledge']['fields']['campaign_id'] = array(
203 'title' => ts('Campaign'),
204 'default' => 'false',
206 $this->_columns
['civicrm_pledge']['filters']['campaign_id'] = array(
207 'title' => ts('Campaign'),
208 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
209 'options' => $this->activeCampaigns
,
210 'type' => CRM_Utils_Type
::T_INT
,
212 $this->_columns
['civicrm_pledge']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
216 $this->_groupFilter
= TRUE;
217 $this->_tagFilter
= TRUE;
218 $this->_currencyColumn
= 'civicrm_pledge_currency';
219 parent
::__construct();
222 public function preProcess() {
223 parent
::preProcess();
226 public function select() {
231 * If we are retrieving total paid we need to define the inclusion of pledge_payment.
233 * @param string $tableName
235 * @param string $fieldName
238 * @return bool|string
240 public 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'],
247 return "COALESCE(sum({$this->_aliases[$tableName]}.actual_amount), 0) as {$tableName}_{$fieldName}";
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'],
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}";
263 public function groupBy() {
265 if (empty($this->_groupBy
) && $this->_totalPaid
) {
266 $groupBy = array("{$this->_aliases['civicrm_pledge']}.id", "{$this->_aliases['civicrm_pledge']}.currency");
267 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $groupBy);
271 public function from() {
273 FROM civicrm_pledge {$this->_aliases['civicrm_pledge']}
274 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
275 ON ({$this->_aliases['civicrm_contact']}.id =
276 {$this->_aliases['civicrm_pledge']}.contact_id )
279 if ($this->_totalPaid
) {
281 LEFT JOIN civicrm_pledge_payment {$this->_aliases['civicrm_pledge_payment']} ON
282 {$this->_aliases['civicrm_pledge']}.id = {$this->_aliases['civicrm_pledge_payment']}.pledge_id
283 AND {$this->_aliases['civicrm_pledge_payment']}.status_id = 1
287 $this->addPhoneFromClause();
288 $this->addAddressFromClause();
289 // include email field if email column is to be included
290 if ($this->_emailField
) {
292 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
293 ON ({$this->_aliases['civicrm_contact']}.id =
294 {$this->_aliases['civicrm_email']}.contact_id) AND
295 {$this->_aliases['civicrm_email']}.is_primary = 1\n";
304 public function statistics(&$rows) {
305 $statistics = parent
::statistics($rows);
306 //regenerate the from field without extra left join on pledge payments
307 $totalPaid = $this->_totalPaid
;
308 $this->_totalPaid
= FALSE;
310 $this->customDataFrom();
311 if (!$this->_having
) {
312 $totalAmount = $average = array();
315 SELECT COUNT({$this->_aliases['civicrm_pledge']}.amount ) as count,
316 SUM({$this->_aliases['civicrm_pledge']}.amount ) as amount,
317 ROUND(AVG({$this->_aliases['civicrm_pledge']}.amount), 2) as avg,
318 {$this->_aliases['civicrm_pledge']}.currency as currency
321 $group = "GROUP BY {$this->_aliases['civicrm_pledge']}.currency";
322 $sql = "{$select} {$this->_from} {$this->_where} {$group}";
323 $dao = CRM_Core_DAO
::executeQuery($sql);
324 $count = $index = $totalCount = 0;
325 // this will run once per currency
326 while ($dao->fetch()) {
327 $totalAmount = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
328 $average = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
329 $count = $dao->count
;
330 $totalCount .= $count;
331 $statistics['counts']['amount' . $index] = array(
332 'title' => ts('Total Pledged') . ' (' . $dao->currency
. ')',
333 'value' => $totalAmount,
334 'type' => CRM_Utils_Type
::T_STRING
,
336 $statistics['counts']['avg' . $index] = array(
337 'title' => ts('Average') . ' (' . $dao->currency
. ')',
339 'type' => CRM_Utils_Type
::T_STRING
,
341 $statistics['counts']['count' . $index] = array(
342 'title' => ts('Total No Pledges') . ' (' . $dao->currency
. ')',
344 'type' => CRM_Utils_Type
::T_INT
,
348 if ($totalCount > $count) {
349 $statistics['counts']['count' . $index] = array(
350 'title' => ts('Total No Pledges'),
351 'value' => $totalCount,
352 'type' => CRM_Utils_Type
::T_INT
,
358 $this->_totalPaid
= TRUE;
364 public function orderBy() {
365 $this->_orderBy
= "ORDER BY {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_contact']}.id";
368 public function where() {
370 foreach ($this->_columns
as $tableName => $table) {
371 if (array_key_exists('filters', $table)) {
372 foreach ($table['filters'] as $fieldName => $field) {
374 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
375 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
376 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
377 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
379 if ($relative ||
$from ||
$to) {
380 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
384 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
386 $clause = $this->whereClause($field,
388 CRM_Utils_Array
::value("{$fieldName}_value",
391 CRM_Utils_Array
::value("{$fieldName}_min",
394 CRM_Utils_Array
::value("{$fieldName}_max",
401 if (!empty($clause)) {
402 $clauses[] = $clause;
407 if (empty($clauses)) {
408 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) ";
411 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) AND
412 " . implode(' AND ', $clauses);
415 if ($this->_aclWhere
) {
416 $this->_where
.= " AND {$this->_aclWhere} ";
420 public function postProcess() {
422 $this->beginPostProcess();
424 // get the acl clauses built before we assemble the query
425 $this->buildACLClause($this->_aliases
['civicrm_contact']);
426 $sql = $this->buildQuery();
427 $rows = $payment = array();
429 $dao = CRM_Core_DAO
::executeQuery($sql);
431 // Set pager for the Main Query only which displays basic information
433 $this->assign('columnHeaders', $this->_columnHeaders
);
435 while ($dao->fetch()) {
436 $pledgeID = $dao->civicrm_pledge_id
;
437 foreach ($this->_columnHeaders
as $columnHeadersKey => $columnHeadersValue) {
439 if (property_exists($dao, $columnHeadersKey)) {
440 $display[$pledgeID][$columnHeadersKey] = $dao->$columnHeadersKey;
443 $pledgeIDArray[] = $pledgeID;
446 // Add Special headers
447 $this->_columnHeaders
['scheduled_date'] = array(
448 'type' => CRM_Utils_Type
::T_DATE
,
449 'title' => ts('Next Payment Due'),
451 $this->_columnHeaders
['scheduled_amount'] = array(
452 'type' => CRM_Utils_Type
::T_MONEY
,
453 'title' => ts('Next Payment Amount'),
455 $this->_columnHeaders
['status_id'] = NULL;
458 * this is purely about ordering the total paid & balance due fields off to the end
459 * of the table in case custom or address fields cause them to fall in the middle
460 * (arguably the pledge amount should be moved to after these fields too)
463 $tableHeaders = array(
464 'civicrm_pledge_payment_total_paid',
465 'civicrm_pledge_payment_balance_due',
468 foreach ($tableHeaders as $header) {
469 //per above, unset & reset them so they move to the end
470 if (isset($this->_columnHeaders
[$header])) {
471 $headervalue = $this->_columnHeaders
[$header];
472 unset($this->_columnHeaders
[$header]);
473 $this->_columnHeaders
[$header] = $headervalue;
477 // To Display Payment Details of pledged amount
478 // for pledge payments In Progress
479 if (!empty($display)) {
480 $statusId = array_keys(CRM_Core_PseudoConstant
::accountOptionValues("contribution_status", NULL, " AND v.name IN ('Pending', 'Overdue')"));
481 $statusId = implode(',', $statusId);
482 $select = "payment.pledge_id, payment.scheduled_amount, pledge.contact_id";
484 SELECT min(payment.scheduled_date) as scheduled_date,
487 FROM civicrm_pledge_payment payment
488 LEFT JOIN civicrm_pledge pledge
489 ON pledge.id = payment.pledge_id
491 WHERE payment.status_id IN ({$statusId})
495 $daoPayment = CRM_Core_DAO
::executeQuery($sqlPayment);
497 while ($daoPayment->fetch()) {
498 foreach ($pledgeIDArray as $key => $val) {
499 if ($val == $daoPayment->pledge_id
) {
501 $display[$daoPayment->pledge_id
]['scheduled_date'] = $daoPayment->scheduled_date
;
503 $display[$daoPayment->pledge_id
]['scheduled_amount'] = $daoPayment->scheduled_amount
;
509 // Displaying entire data on the form
510 if (!empty($display)) {
511 foreach ($display as $key => $value) {
513 foreach ($this->_columnHeaders
as $columnKey => $columnValue) {
514 if (array_key_exists($columnKey, $value)) {
515 $row[$columnKey] = !empty($value[$columnKey]) ?
$value[$columnKey] : '';
522 unset($this->_columnHeaders
['status_id']);
523 unset($this->_columnHeaders
['civicrm_pledge_id']);
524 unset($this->_columnHeaders
['civicrm_pledge_contact_id']);
526 $this->formatDisplay($rows, FALSE);
527 $this->doTemplateAssignment($rows);
528 $this->endPostProcess($rows);
532 * Alter display of rows.
534 * Iterate through the rows retrieved via SQL and make changes for display purposes,
535 * such as rendering contacts as links.
538 * Rows generated by SQL, with an array for each row.
540 public function alterDisplay(&$rows) {
542 $checkList = array();
543 $display_flag = $prev_cid = $cid = 0;
545 foreach ($rows as $rowNum => $row) {
546 if (!empty($this->_noRepeats
) && $this->_outputMode
!= 'csv') {
547 // don't repeat contact details if its same as the previous row
548 if (array_key_exists('civicrm_pledge_contact_id', $row)) {
549 if ($cid = $row['civicrm_pledge_contact_id']) {
554 if ($prev_cid == $cid) {
565 foreach ($row as $colName => $colVal) {
566 if (in_array($colName, $this->_noRepeats
)) {
567 unset($rows[$rowNum][$colName]);
576 // convert display name to links
577 if (array_key_exists('civicrm_contact_sort_name', $row) &&
578 array_key_exists('civicrm_pledge_contact_id', $row)
580 $url = CRM_Utils_System
::url("civicrm/contact/view",
581 'reset=1&cid=' . $row['civicrm_pledge_contact_id'],
584 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
585 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
589 if (array_key_exists('civicrm_pledge_financial_type_id', $row)) {
590 if ($value = $row['civicrm_pledge_financial_type_id']) {
591 $rows[$rowNum]['civicrm_pledge_financial_type_id'] = CRM_Contribute_PseudoConstant
::financialType($value, FALSE);
597 if (array_key_exists('civicrm_pledge_status_id', $row)) {
598 if ($value = $row['civicrm_pledge_status_id']) {
599 $rows[$rowNum]['civicrm_pledge_status_id'] = CRM_Contribute_PseudoConstant
::contributionStatus($value);
604 // If using campaigns, convert campaign_id to campaign title
605 if (array_key_exists('civicrm_pledge_campaign_id', $row)) {
606 if ($value = $row['civicrm_pledge_campaign_id']) {
607 $rows[$rowNum]['civicrm_pledge_campaign_id'] = $this->activeCampaigns
[$value];
612 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'pledge/detail', 'List all pledge(s) for this ') ?
TRUE : $entryFound;
614 // skip looking further in rows, if first row itself doesn't
615 // have the column we need