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
46 class CRM_Report_Form_Pledge_Detail
extends CRM_Report_Form
{
48 protected $_summary = NULL;
49 protected $_totalPaid = FALSE;
50 protected $_pledgeStatuses = array();
51 protected $_customGroupExtends = array(
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
);
70 $this->_columns
= array(
71 'civicrm_contact' => array(
72 'dao' => 'CRM_Contact_DAO_Contact',
75 'title' => ts('Contact Name'),
81 'sort_name' => array('title' => ts('Contact Name')),
82 'id' => array('no_display' => TRUE),
84 'grouping' => 'contact-fields',
86 'civicrm_email' => array(
87 'dao' => 'CRM_Core_DAO_Email',
89 'email' => array('no_repeat' => TRUE),
91 'grouping' => 'contact-fields',
93 'civicrm_pledge' => array(
94 'dao' => 'CRM_Pledge_DAO_Pledge',
100 'contact_id' => array(
101 'no_display' => TRUE,
104 'financial_type_id' => array(
105 'title' => ts('Financial Type'),
108 'title' => ts('Pledge Amount'),
110 'type' => CRM_Utils_Type
::T_MONEY
,
114 'no_display' => TRUE,
116 'frequency_unit' => array(
117 'title' => ts('Frequency Unit'),
119 'installments' => array(
120 'title' => ts('Installments'),
122 'pledge_create_date' => array(
123 'title' => ts('Pledge Made Date'),
125 'start_date' => array(
126 'title' => ts('Pledge Start Date'),
127 'type' => CRM_Utils_Type
::T_DATE
,
130 'title' => ts('Pledge End Date'),
131 'type' => CRM_Utils_Type
::T_DATE
,
133 'status_id' => array(
134 'title' => ts('Pledge Status'),
139 'pledge_create_date' => array(
140 'title' => 'Pledge Made Date',
141 'operatorType' => CRM_Report_Form
::OP_DATE
,
143 'pledge_amount' => array(
144 'title' => ts('Pledged Amount'),
145 'operatorType' => CRM_Report_Form
::OP_INT
,
148 'title' => 'Currency',
149 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
150 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
152 'type' => CRM_Utils_Type
::T_STRING
,
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'),
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(),
170 'civicrm_pledge_payment' => array(
171 'dao' => 'CRM_Pledge_DAO_PledgePayment',
173 'total_paid' => array(
174 'title' => ts('Total Amount Paid'),
175 'type' => CRM_Utils_Type
::T_MONEY
,
177 'balance_due' => array(
178 'title' => ts('Balance Due'),
180 'type' => CRM_Utils_Type
::T_MONEY
,
186 $this->_columns +
= $this->getAddressColumns(array('group_by' => FALSE)) +
$this->getPhoneColumns();
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',
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
,
201 $this->_columns
['civicrm_pledge']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
205 $this->_groupFilter
= TRUE;
206 $this->_tagFilter
= TRUE;
207 $this->_currencyColumn
= 'civicrm_pledge_currency';
208 parent
::__construct();
211 public function preProcess() {
212 parent
::preProcess();
215 public function select() {
220 * If we are retrieving total paid we need to define the inclusion of pledge_payment.
222 * @param string $tableName
224 * @param string $fieldName
227 * @return bool|string
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'],
236 return "COALESCE(sum({$this->_aliases[$tableName]}.actual_amount), 0) as {$tableName}_{$fieldName}";
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'],
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}";
252 public function groupBy() {
254 if (empty($this->_groupBy
) && $this->_totalPaid
) {
255 $groupBy = array("{$this->_aliases['civicrm_pledge']}.id", "{$this->_aliases['civicrm_pledge']}.currency");
256 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $groupBy);
260 public function from() {
262 FROM civicrm_pledge {$this->_aliases['civicrm_pledge']}
263 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
264 ON ({$this->_aliases['civicrm_contact']}.id =
265 {$this->_aliases['civicrm_pledge']}.contact_id )
268 if ($this->_totalPaid
) {
270 LEFT JOIN civicrm_pledge_payment {$this->_aliases['civicrm_pledge_payment']} ON
271 {$this->_aliases['civicrm_pledge']}.id = {$this->_aliases['civicrm_pledge_payment']}.pledge_id
272 AND {$this->_aliases['civicrm_pledge_payment']}.status_id = 1
276 $this->addPhoneFromClause();
277 $this->addAddressFromClause();
278 // include email field if email column is to be included
279 if ($this->_emailField
) {
281 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
282 ON ({$this->_aliases['civicrm_contact']}.id =
283 {$this->_aliases['civicrm_email']}.contact_id) AND
284 {$this->_aliases['civicrm_email']}.is_primary = 1\n";
293 public function statistics(&$rows) {
294 $statistics = parent
::statistics($rows);
295 //regenerate the from field without extra left join on pledge payments
296 $totalPaid = $this->_totalPaid
;
297 $this->_totalPaid
= FALSE;
299 $this->customDataFrom();
300 if (!$this->_having
) {
301 $totalAmount = $average = array();
304 SELECT COUNT({$this->_aliases['civicrm_pledge']}.amount ) as count,
305 SUM({$this->_aliases['civicrm_pledge']}.amount ) as amount,
306 ROUND(AVG({$this->_aliases['civicrm_pledge']}.amount), 2) as avg,
307 {$this->_aliases['civicrm_pledge']}.currency as currency
310 $group = "GROUP BY {$this->_aliases['civicrm_pledge']}.currency";
311 $sql = "{$select} {$this->_from} {$this->_where} {$group}";
312 $dao = CRM_Core_DAO
::executeQuery($sql);
313 $count = $index = $totalCount = 0;
314 // this will run once per currency
315 while ($dao->fetch()) {
316 $totalAmount = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
317 $average = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
318 $count = $dao->count
;
319 $totalCount .= $count;
320 $statistics['counts']['amount' . $index] = array(
321 'title' => ts('Total Pledged') . ' (' . $dao->currency
. ')',
322 'value' => $totalAmount,
323 'type' => CRM_Utils_Type
::T_STRING
,
325 $statistics['counts']['avg' . $index] = array(
326 'title' => ts('Average') . ' (' . $dao->currency
. ')',
328 'type' => CRM_Utils_Type
::T_STRING
,
330 $statistics['counts']['count' . $index] = array(
331 'title' => ts('Total No Pledges') . ' (' . $dao->currency
. ')',
333 'type' => CRM_Utils_Type
::T_INT
,
337 if ($totalCount > $count) {
338 $statistics['counts']['count' . $index] = array(
339 'title' => ts('Total No Pledges'),
340 'value' => $totalCount,
341 'type' => CRM_Utils_Type
::T_INT
,
347 $this->_totalPaid
= TRUE;
353 public function orderBy() {
354 $this->_orderBy
= "ORDER BY {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_contact']}.id";
357 public function where() {
359 foreach ($this->_columns
as $tableName => $table) {
360 if (array_key_exists('filters', $table)) {
361 foreach ($table['filters'] as $fieldName => $field) {
363 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
364 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
365 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
366 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
368 if ($relative ||
$from ||
$to) {
369 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
373 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
375 $clause = $this->whereClause($field,
377 CRM_Utils_Array
::value("{$fieldName}_value",
380 CRM_Utils_Array
::value("{$fieldName}_min",
383 CRM_Utils_Array
::value("{$fieldName}_max",
390 if (!empty($clause)) {
391 $clauses[] = $clause;
396 if (empty($clauses)) {
397 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) ";
400 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) AND
401 " . implode(' AND ', $clauses);
404 if ($this->_aclWhere
) {
405 $this->_where
.= " AND {$this->_aclWhere} ";
409 public function postProcess() {
411 $this->beginPostProcess();
413 // get the acl clauses built before we assemble the query
414 $this->buildACLClause($this->_aliases
['civicrm_contact']);
415 $sql = $this->buildQuery();
416 $rows = $payment = array();
418 $dao = CRM_Core_DAO
::executeQuery($sql);
420 // Set pager for the Main Query only which displays basic information
422 $this->assign('columnHeaders', $this->_columnHeaders
);
424 while ($dao->fetch()) {
425 $pledgeID = $dao->civicrm_pledge_id
;
426 foreach ($this->_columnHeaders
as $columnHeadersKey => $columnHeadersValue) {
428 if (property_exists($dao, $columnHeadersKey)) {
429 $display[$pledgeID][$columnHeadersKey] = $dao->$columnHeadersKey;
432 $pledgeIDArray[] = $pledgeID;
435 // Add Special headers
436 $this->_columnHeaders
['scheduled_date'] = array(
437 'type' => CRM_Utils_Type
::T_DATE
,
438 'title' => 'Next Payment Due',
440 $this->_columnHeaders
['scheduled_amount'] = array(
441 'type' => CRM_Utils_Type
::T_MONEY
,
442 'title' => 'Next Payment Amount',
444 $this->_columnHeaders
['status_id'] = NULL;
447 * this is purely about ordering the total paid & balance due fields off to the end
448 * of the table in case custom or address fields cause them to fall in the middle
449 * (arguably the pledge amount should be moved to after these fields too)
452 $tableHeaders = array(
453 'civicrm_pledge_payment_total_paid',
454 'civicrm_pledge_payment_balance_due',
457 foreach ($tableHeaders as $header) {
458 //per above, unset & reset them so they move to the end
459 if (isset($this->_columnHeaders
[$header])) {
460 $headervalue = $this->_columnHeaders
[$header];
461 unset($this->_columnHeaders
[$header]);
462 $this->_columnHeaders
[$header] = $headervalue;
466 // To Display Payment Details of pledged amount
467 // for pledge payments In Progress
468 if (!empty($display)) {
469 $statusId = array_keys(CRM_Core_PseudoConstant
::accountOptionValues("contribution_status", NULL, " AND v.name IN ('Pending', 'Overdue')"));
470 $statusId = implode(',', $statusId);
471 $select = "payment.pledge_id, payment.scheduled_amount, pledge.contact_id";
473 SELECT min(payment.scheduled_date) as scheduled_date,
476 FROM civicrm_pledge_payment payment
477 LEFT JOIN civicrm_pledge pledge
478 ON pledge.id = payment.pledge_id
480 WHERE payment.status_id IN ({$statusId})
484 $daoPayment = CRM_Core_DAO
::executeQuery($sqlPayment);
486 while ($daoPayment->fetch()) {
487 foreach ($pledgeIDArray as $key => $val) {
488 if ($val == $daoPayment->pledge_id
) {
490 $display[$daoPayment->pledge_id
]['scheduled_date'] = $daoPayment->scheduled_date
;
492 $display[$daoPayment->pledge_id
]['scheduled_amount'] = $daoPayment->scheduled_amount
;
498 // Displaying entire data on the form
499 if (!empty($display)) {
500 foreach ($display as $key => $value) {
502 foreach ($this->_columnHeaders
as $columnKey => $columnValue) {
503 if (array_key_exists($columnKey, $value)) {
504 $row[$columnKey] = !empty($value[$columnKey]) ?
$value[$columnKey] : '';
511 unset($this->_columnHeaders
['status_id']);
512 unset($this->_columnHeaders
['civicrm_pledge_id']);
513 unset($this->_columnHeaders
['civicrm_pledge_contact_id']);
515 $this->formatDisplay($rows, FALSE);
516 $this->doTemplateAssignment($rows);
517 $this->endPostProcess($rows);
521 * Alter display of rows.
523 * Iterate through the rows retrieved via SQL and make changes for display purposes,
524 * such as rendering contacts as links.
527 * Rows generated by SQL, with an array for each row.
529 public function alterDisplay(&$rows) {
531 $checkList = array();
532 $display_flag = $prev_cid = $cid = 0;
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']) {
543 if ($prev_cid == $cid) {
554 foreach ($row as $colName => $colVal) {
555 if (in_array($colName, $this->_noRepeats
)) {
556 unset($rows[$rowNum][$colName]);
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)
569 $url = CRM_Utils_System
::url("civicrm/contact/view",
570 'reset=1&cid=' . $row['civicrm_pledge_contact_id'],
573 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
574 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
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);
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);
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];
601 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'pledge/detail', 'List all pledge(s) for this ') ?
TRUE : $entryFound;
603 // skip looking further in rows, if first row itself doesn't
604 // have the column we need