3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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(
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
);
73 $this->_columns
= array(
76 'dao' => 'CRM_Contact_DAO_Contact',
80 array('title' => ts('Contact Name'),
88 array('title' => ts('Contact Name')),
90 array('no_display' => TRUE),
92 'grouping' => 'contact-fields',
96 'dao' => 'CRM_Core_DAO_Email',
100 array('no_repeat' => TRUE),
102 'grouping' => 'contact-fields',
106 'dao' => 'CRM_Pledge_DAO_Pledge',
111 'no_display' => TRUE,
116 'no_display' => TRUE,
120 array('title' => ts('Pledge Amount'),
122 'type' => CRM_Utils_Type
::T_MONEY
,
127 'no_display' => TRUE,
130 array('title' => ts('Frequency Unit'),
133 array('title' => ts('Installments'),
135 'pledge_create_date' =>
136 array('title' => ts('Pledge Made Date'),
139 array('title' => ts('Pledge Start Date'),
140 'type' => CRM_Utils_Type
::T_DATE
,
143 array('title' => ts('Pledge End Date'),
144 'type' => CRM_Utils_Type
::T_DATE
,
147 array('title' => ts('Pledge Status'),
153 'pledge_create_date' =>
155 'title' => 'Pledge Made Date',
156 'operatorType' => CRM_Report_Form
::OP_DATE
,
159 array('title' => ts('Pledged Amount'),
160 'operatorType' => CRM_Report_Form
::OP_INT
,
163 array('title' => 'Currency',
164 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
165 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
167 'type' => CRM_Utils_Type
::T_STRING
,
171 'name' => 'status_id',
172 'title' => ts('Pledge Status'),
173 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
174 'options' => CRM_Core_OptionGroup
::values('contribution_status'),
179 'civicrm_pledge_payment' =>
181 'dao' => 'CRM_Pledge_DAO_PledgePayment',
186 'title' => ts('Total Amount Paid'),
187 'type' => CRM_Utils_Type
::T_MONEY
,
191 'title' => ts('Balance Due'),
193 'type' => CRM_Utils_Type
::T_MONEY
,
199 +
$this->getAddressColumns(array('group_by' => FALSE))
200 +
$this->getPhoneColumns();
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' => 'Campaign',
206 'default' => 'false',
208 $this->_columns
['civicrm_pledge']['filters']['campaign_id'] = array('title' => ts('Campaign'),
209 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
210 'options' => $this->activeCampaigns
,
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 function preProcess() {
223 parent
::preProcess();
230 * If we are retrieving total paid we need to define the inclusion of pledge_payment
238 * @return bool|string
240 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}";
265 if (empty($this->_groupBy
) && $this->_totalPaid
) {
266 $this->_groupBy
= " GROUP BY {$this->_aliases['civicrm_pledge']}.id, {$this->_aliases['civicrm_pledge']}.currency" ;
271 FROM civicrm_pledge {$this->_aliases['civicrm_pledge']}
272 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
273 ON ({$this->_aliases['civicrm_contact']}.id =
274 {$this->_aliases['civicrm_pledge']}.contact_id )
277 if($this->_totalPaid
){
279 LEFT JOIN civicrm_pledge_payment {$this->_aliases['civicrm_pledge_payment']} ON
280 {$this->_aliases['civicrm_pledge']}.id = {$this->_aliases['civicrm_pledge_payment']}.pledge_id
281 AND {$this->_aliases['civicrm_pledge_payment']}.status_id = 1
285 $this->addPhoneFromClause();
286 $this->addAddressFromClause();
287 // include email field if email column is to be included
288 if ($this->_emailField
) {
290 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
291 ON ({$this->_aliases['civicrm_contact']}.id =
292 {$this->_aliases['civicrm_email']}.contact_id) AND
293 {$this->_aliases['civicrm_email']}.is_primary = 1\n";
302 function statistics(&$rows) {
303 $statistics = parent
::statistics($rows);
304 //regenerate the from field without extra left join on pledge payments
305 $this->_totalPaid
= FALSE;
307 $this->customDataFrom();
308 if (!$this->_having
) {
309 $totalAmount = $average = array();
312 SELECT COUNT({$this->_aliases['civicrm_pledge']}.amount ) as count,
313 SUM({$this->_aliases['civicrm_pledge']}.amount ) as amount,
314 ROUND(AVG({$this->_aliases['civicrm_pledge']}.amount), 2) as avg,
315 {$this->_aliases['civicrm_pledge']}.currency as currency
318 $group = "GROUP BY {$this->_aliases['civicrm_pledge']}.currency";
319 $sql = "{$select} {$this->_from} {$this->_where} {$group}";
320 $dao = CRM_Core_DAO
::executeQuery($sql);
321 $count = $index = $totalCount = 0;
322 // this will run once per currency
323 while($dao->fetch()) {
324 $totalAmount = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
325 $average = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
326 $count = $dao->count
;
327 $totalCount .= $count;
328 $statistics['counts']['amount' . $index] = array(
329 'title' => ts('Total Amount Pledged (') . $dao->currency
. ')',
330 'value' => $totalAmount,
331 'type' => CRM_Utils_Type
::T_STRING
,
333 $statistics['counts']['avg' . $index] = array(
334 'title' => ts('Average (') . $dao->currency
. ')',
336 'type' => CRM_Utils_Type
::T_STRING
,
338 $statistics['counts']['count' . $index] = array(
339 'title' => ts('Total No Pledges (') . $dao->currency
. ')',
341 'type' => CRM_Utils_Type
::T_INT
,
345 if($totalCount > $count) {
346 $statistics['counts']['count' . $index] = array(
347 'title' => ts('Total No Pledges'),
348 'value' => $totalCount,
349 'type' => CRM_Utils_Type
::T_INT
,
357 $this->_orderBy
= "ORDER BY {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_contact']}.id";
362 foreach ($this->_columns
as $tableName => $table) {
363 if (array_key_exists('filters', $table)) {
364 foreach ($table['filters'] as $fieldName => $field) {
366 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
367 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
368 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
369 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
371 if ($relative ||
$from ||
$to) {
372 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
376 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
378 $clause = $this->whereClause($field,
380 CRM_Utils_Array
::value("{$fieldName}_value",
383 CRM_Utils_Array
::value("{$fieldName}_min",
386 CRM_Utils_Array
::value("{$fieldName}_max",
393 if (!empty($clause)) {
394 $clauses[] = $clause;
399 if (empty($clauses)) {
400 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) ";
403 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) AND
404 " . implode(' AND ', $clauses);
407 if ($this->_aclWhere
) {
408 $this->_where
.= " AND {$this->_aclWhere} ";
412 function postProcess() {
414 $this->beginPostProcess();
416 // get the acl clauses built before we assemble the query
417 $this->buildACLClause($this->_aliases
['civicrm_contact']);
418 $sql = $this->buildQuery();
419 $rows = $payment = array();
421 $dao = CRM_Core_DAO
::executeQuery($sql);
423 // Set pager for the Main Query only which displays basic information
425 $this->assign('columnHeaders', $this->_columnHeaders
);
427 while ($dao->fetch()) {
428 $pledgeID = $dao->civicrm_pledge_id
;
429 foreach ($this->_columnHeaders
as $columnHeadersKey => $columnHeadersValue) {
431 if (property_exists($dao, $columnHeadersKey)) {
432 $display[$pledgeID][$columnHeadersKey] = $dao->$columnHeadersKey;
435 $pledgeIDArray[] = $pledgeID;
438 // Add Special headers
439 $this->_columnHeaders
['scheduled_date'] = array(
440 'type' => CRM_Utils_Type
::T_DATE
,
441 'title' => 'Next Payment Due',
443 $this->_columnHeaders
['scheduled_amount'] = array(
444 'type' => CRM_Utils_Type
::T_MONEY
,
445 'title' => 'Next Payment Amount',
447 $this->_columnHeaders
['status_id'] = NULL;
450 * this is purely about ordering the total paid & balance due fields off to the end
451 * of the table in case custom or address fields cause them to fall in the middle
452 * (arguably the pledge amount should be moved to after these fields too)
455 $tableHeaders = array(
456 'civicrm_pledge_payment_total_paid',
457 'civicrm_pledge_payment_balance_due'
460 foreach ($tableHeaders as $header) {
461 //per above, unset & reset them so they move to the end
462 if(isset($this->_columnHeaders
[$header])){
463 $headervalue = $this->_columnHeaders
[$header];
464 unset($this->_columnHeaders
[$header]);
465 $this->_columnHeaders
[$header] = $headervalue;
469 // To Display Payment Details of pledged amount
470 // for pledge payments In Progress
471 if (!empty($display)) {
473 SELECT min(payment.scheduled_date) as scheduled_date,
475 payment.scheduled_amount,
478 FROM civicrm_pledge_payment payment
479 LEFT JOIN civicrm_pledge pledge
480 ON pledge.id = payment.pledge_id
482 WHERE payment.status_id = 2
484 GROUP BY payment.pledge_id";
486 $daoPayment = CRM_Core_DAO
::executeQuery($sqlPayment);
488 while ($daoPayment->fetch()) {
489 foreach ($pledgeIDArray as $key => $val) {
490 if ($val == $daoPayment->pledge_id
) {
492 $display[$daoPayment->pledge_id
]['scheduled_date'] = $daoPayment->scheduled_date
;
494 $display[$daoPayment->pledge_id
]['scheduled_amount'] = $daoPayment->scheduled_amount
;
500 // Displaying entire data on the form
501 if (!empty($display)) {
502 foreach ($display as $key => $value) {
504 foreach ($this->_columnHeaders
as $columnKey => $columnValue) {
505 if (array_key_exists($columnKey, $value)) {
506 $row[$columnKey] = !empty($value[$columnKey]) ?
$value[$columnKey] : '';
513 unset($this->_columnHeaders
['status_id']);
514 unset($this->_columnHeaders
['civicrm_pledge_id']);
515 unset($this->_columnHeaders
['civicrm_pledge_contact_id']);
517 $this->formatDisplay($rows, FALSE);
518 $this->doTemplateAssignment($rows);
519 $this->endPostProcess($rows);
525 function alterDisplay(&$rows) {
526 // custom code to alter rows
528 $checkList = array();
529 $display_flag = $prev_cid = $cid = 0;
531 foreach ($rows as $rowNum => $row) {
532 if (!empty($this->_noRepeats
) && $this->_outputMode
!= 'csv') {
533 // don't repeat contact details if its same as the previous row
534 if (array_key_exists('civicrm_pledge_contact_id', $row)) {
535 if ($cid = $row['civicrm_pledge_contact_id']) {
540 if ($prev_cid == $cid) {
551 foreach ($row as $colName => $colVal) {
552 if (in_array($colName, $this->_noRepeats
)) {
553 unset($rows[$rowNum][$colName]);
562 // convert display name to links
563 if (array_key_exists('civicrm_contact_sort_name', $row) &&
564 array_key_exists('civicrm_pledge_contact_id', $row)
566 $url = CRM_Utils_System
::url("civicrm/contact/view",
567 'reset=1&cid=' . $row['civicrm_pledge_contact_id'],
570 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
571 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
576 if (array_key_exists('civicrm_pledge_status_id', $row)) {
577 if ($value = $row['civicrm_pledge_status_id']) {
578 $rows[$rowNum]['civicrm_pledge_status_id'] = CRM_Contribute_PseudoConstant
::contributionStatus($value);
583 // If using campaigns, convert campaign_id to campaign title
584 if (array_key_exists('civicrm_pledge_campaign_id', $row)) {
585 if ($value = $row['civicrm_pledge_campaign_id']) {
586 $rows[$rowNum]['civicrm_pledge_campaign_id'] = $this->activeCampaigns
[$value];
591 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'pledge/detail', 'List all pledge(s) for this ') ?
TRUE : $entryFound;
593 // skip looking further in rows, if first row itself doesn't
594 // have the column we need