5 +--------------------------------------------------------------------+
6 | CiviCRM version 4.3 |
7 +--------------------------------------------------------------------+
8 | Copyright CiviCRM LLC (c) 2004-2013 |
9 +--------------------------------------------------------------------+
10 | This file is a part of CiviCRM. |
12 | CiviCRM is free software; you can copy, modify, and distribute it |
13 | under the terms of the GNU Affero General Public License |
14 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
16 | CiviCRM is distributed in the hope that it will be useful, but |
17 | WITHOUT ANY WARRANTY; without even the implied warranty of |
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
19 | See the GNU Affero General Public License for more details. |
21 | You should have received a copy of the GNU Affero General Public |
22 | License and the CiviCRM Licensing Exception along |
23 | with this program; if not, contact CiviCRM LLC |
24 | at info[AT]civicrm[DOT]org. If you have questions about the |
25 | GNU Affero General Public License or the licensing of CiviCRM, |
26 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
27 +--------------------------------------------------------------------+
33 * @copyright CiviCRM LLC (c) 2004-2013
37 class CRM_Report_Form_Contribute_Summary
extends CRM_Report_Form
{
38 protected $_addressField = FALSE;
40 protected $_charts = array(
42 'barChart' => 'Bar Chart',
43 'pieChart' => 'Pie Chart',
45 protected $_customGroupExtends = array('Contribution');
46 protected $_customGroupGroupBy = TRUE;
48 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
50 function __construct() {
51 $config = CRM_Core_Config
::singleton();
52 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents
);
53 if ($campaignEnabled) {
54 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
55 $this->activeCampaigns
= $getCampaigns['campaigns'];
56 asort($this->activeCampaigns
);
58 $this->_columns
= array(
61 'dao' => 'CRM_Contact_DAO_Contact',
65 array('title' => ts('Contact Name'),
68 'postal_greeting_display' =>
69 array('title' => ts('Postal Greeting')),
76 'grouping' => 'contact-fields',
80 array('title' => ts('Contact ID')),
82 array('title' => ts('Contact Name'),
88 'dao' => 'CRM_Core_DAO_Email',
92 array('title' => ts('Email'),
96 'grouping' => 'contact-fields',
100 'dao' => 'CRM_Core_DAO_Phone',
104 array('title' => ts('Phone'),
108 'grouping' => 'contact-fields',
110 'civicrm_financial_type' =>
111 array('dao' => 'CRM_Financial_DAO_FinancialType',
112 'fields' => array('financial_type' => null,),
113 'grouping' => 'contri-fields',
114 'group_bys' => array(
115 'financial_type' => array('title' => ts('Financial Type')),
118 'civicrm_contribution' =>
120 'dao' => 'CRM_Contribute_DAO_Contribution',
121 //'bao' => 'CRM_Contribute_BAO_Contribution',
124 'contribution_source' => array('title' => ts('Source'),
127 array('title' => ts('Amount Statistics'),
131 array('sum' => ts('Aggregate Amount'),
132 'count' => ts('Donations'),
133 'avg' => ts('Average'),
137 'grouping' => 'contri-fields',
141 array('operatorType' => CRM_Report_Form
::OP_DATE
),
142 'contribution_status_id' =>
143 array('title' => ts('Donation Status'),
144 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
145 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
146 'default' => array(1),
147 'type' => CRM_Utils_Type
::T_INT
,
149 'financial_type_id' =>
150 array('title' => ts('Financial Type'),
151 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
152 'options' => CRM_Contribute_PseudoConstant
::financialType(),
153 'type' => CRM_Utils_Type
::T_INT
,
156 array('title' => ts('Donation Amount'),
159 array('title' => ts('Aggregate Amount'),
160 'type' => CRM_Report_Form
::OP_INT
,
161 'dbAlias' => 'civicrm_contribution_total_amount_sum',
165 array('title' => ts('Donation Count'),
166 'type' => CRM_Report_Form
::OP_INT
,
167 'dbAlias' => 'civicrm_contribution_total_amount_count',
171 array('title' => ts('Average'),
172 'type' => CRM_Report_Form
::OP_INT
,
173 'dbAlias' => 'civicrm_contribution_total_amount_avg',
185 'contribution_source' => NULL,
190 'dao' => 'CRM_Contact_DAO_GroupContact',
196 'name' => 'group_id',
197 'title' => ts('Group'),
198 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
200 'options' => CRM_Core_PseudoConstant
::group(),
201 'type' => CRM_Utils_Type
::T_INT
,
205 ) +
$this->addAddressFields();
207 $this->_tagFilter
= TRUE;
208 if ($campaignEnabled && !empty($this->activeCampaigns
)) {
209 $this->_columns
['civicrm_contribution']['fields']['campaign_id'] = array(
210 'title' => 'Campaign',
211 'default' => 'false',
213 $this->_columns
['civicrm_contribution']['filters']['campaign_id'] = array('title' => ts('Campaign'),
214 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
215 'options' => $this->activeCampaigns
,
217 $this->_columns
['civicrm_contribution']['grouping']['campaign_id'] = 'contri-fields';
218 $this->_columns
['civicrm_contribution']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
220 parent
::__construct();
223 function preProcess() {
224 parent
::preProcess();
227 function setDefaultValues($freeze = TRUE) {
228 return parent
::setDefaultValues($freeze);
233 $this->_columnHeaders
= array();
234 foreach ($this->_columns
as $tableName => $table) {
235 if (array_key_exists('group_bys', $table)) {
236 foreach ($table['group_bys'] as $fieldName => $field) {
237 if ($tableName == 'civicrm_address') {
238 $this->_addressField
= TRUE;
240 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
241 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
243 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
244 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
245 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
246 $field['title'] = 'Week';
250 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
251 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
252 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
253 $field['title'] = 'Year';
257 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
258 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
259 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
260 $field['title'] = 'Month';
264 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
265 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
266 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
267 $field['title'] = 'Quarter';
270 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
271 $this->_interval
= $field['title'];
272 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
273 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
274 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
276 // just to make sure these values are transfered to rows.
277 // since we need that for calculation purpose,
278 // e.g making subtotals look nicer or graphs
279 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
280 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
286 if (array_key_exists('fields', $table)) {
287 foreach ($table['fields'] as $fieldName => $field) {
288 if ($tableName == 'civicrm_address') {
289 $this->_addressField
= TRUE;
291 if (CRM_Utils_Array
::value('required', $field) ||
292 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
295 // only include statistics columns if set
296 if (CRM_Utils_Array
::value('statistics', $field)) {
297 foreach ($field['statistics'] as $stat => $label) {
298 switch (strtolower($stat)) {
300 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
301 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
302 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
303 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
307 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
308 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
309 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
310 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
314 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
315 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
316 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
317 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
323 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
324 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
325 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
332 $this->_select
= "SELECT " . implode(', ', $select) . " ";
335 static function formRule($fields, $files, $self) {
336 $errors = $grouping = array();
337 //check for searching combination of dispaly columns and
339 $ignoreFields = array('total_amount', 'sort_name');
340 $errors = $self->customDataFormRule($fields, $ignoreFields);
342 if (CRM_Utils_Array
::value('receive_date', $fields['group_bys'])) {
343 foreach ($self->_columns
as $tableName => $table) {
344 if (array_key_exists('fields', $table)) {
345 foreach ($table['fields'] as $fieldName => $field) {
346 if (CRM_Utils_Array
::value($field['name'], $fields['fields']) &&
347 $fields['fields'][$field['name']] &&
348 in_array( $field['name'], array('sort_name', 'postal_greeting_display', 'contribution_source', 'financial_type'))) {
349 $grouping[] = $field['title'];
354 if (!empty($grouping)) {
355 $temp = 'and ' . implode(', ', $grouping);
356 $errors['fields'] = ts("Please do not use combination of Receive Date %1", array(1 => $temp));
360 if (!CRM_Utils_Array
::value('receive_date', $fields['group_bys'])) {
361 if (CRM_Utils_Array
::value('receive_date_relative', $fields) ||
362 CRM_Utils_Date
::isDate($fields['receive_date_from']) ||
363 CRM_Utils_Date
::isDate($fields['receive_date_to'])
365 $errors['receive_date_relative'] = ts("Do not use filter on Date if group by Receive Date is not used ");
368 if (!CRM_Utils_Array
::value('total_amount', $fields['fields'])) {
370 'total_count_value', 'total_sum_value', 'total_avg_value') as $val) {
371 if (CRM_Utils_Array
::value($val, $fields)) {
372 $errors[$val] = ts("Please select the Amount Statistics");
382 FROM civicrm_contact {$this->_aliases['civicrm_contact']}
383 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
384 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
385 {$this->_aliases['civicrm_contribution']}.is_test = 0
386 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
387 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
388 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
389 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
390 {$this->_aliases['civicrm_email']}.is_primary = 1)
392 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
393 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
394 {$this->_aliases['civicrm_phone']}.is_primary = 1)";
396 if ($this->_addressField
) {
398 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
399 ON {$this->_aliases['civicrm_contact']}.id =
400 {$this->_aliases['civicrm_address']}.contact_id AND
401 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
406 $this->_groupBy
= "";
408 if (is_array($this->_params
['group_bys']) &&
409 !empty($this->_params
['group_bys'])
411 foreach ($this->_columns
as $tableName => $table) {
412 if (array_key_exists('group_bys', $table)) {
413 foreach ($table['group_bys'] as $fieldName => $field) {
414 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
415 if (CRM_Utils_Array
::value('chart', $field)) {
416 $this->assign('chartSupported', TRUE);
419 if (CRM_Utils_Array
::value('frequency', $table['group_bys'][$fieldName]) &&
420 CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])
423 $append = "YEAR({$field['dbAlias']}),";
424 if (in_array(strtolower($this->_params
['group_bys_freq'][$fieldName]),
429 $this->_groupBy
[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
433 $this->_groupBy
[] = $field['dbAlias'];
440 if (!empty($this->_statFields
) &&
441 (($append && count($this->_groupBy
) <= 1) ||
(!$append)) && !$this->_having
443 $this->_rollup
= " WITH ROLLUP";
445 $this->_groupBy
= "GROUP BY " . implode(', ', $this->_groupBy
) . " {$this->_rollup} ";
448 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contact']}.id";
452 function statistics(&$rows) {
453 $statistics = parent
::statistics($rows);
455 if (!$this->_having
) {
457 SELECT COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as count,
458 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount,
459 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as avg
462 $sql = "{$select} {$this->_from} {$this->_where}";
463 $dao = CRM_Core_DAO
::executeQuery($sql);
466 $statistics['counts']['amount'] = array(
467 'value' => $dao->amount
,
468 'title' => 'Total Amount',
469 'type' => CRM_Utils_Type
::T_MONEY
,
471 $statistics['counts']['count '] = array(
472 'value' => $dao->count
,
473 'title' => 'Total Donations',
475 $statistics['counts']['avg '] = array(
476 'value' => $dao->avg
,
477 'title' => 'Average',
478 'type' => CRM_Utils_Type
::T_MONEY
,
485 function postProcess() {
486 parent
::postProcess();
489 function buildChart(&$rows) {
490 $graphRows = array();
493 if (CRM_Utils_Array
::value('charts', $this->_params
)) {
494 foreach ($rows as $key => $row) {
495 if ($row['civicrm_contribution_receive_date_subtotal']) {
496 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
497 $graphRows[$this->_interval
][] = $row['civicrm_contribution_receive_date_interval'];
498 $graphRows['value'][] = $row['civicrm_contribution_total_amount_sum'];
503 if (CRM_Utils_Array
::value('receive_date', $this->_params
['group_bys'])) {
506 $config = CRM_Core_Config
::Singleton();
507 $graphRows['xname'] = $this->_interval
;
508 $graphRows['yname'] = "Amount ({$config->defaultCurrency})";
509 CRM_Utils_OpenFlashChart
::chart($graphRows, $this->_params
['charts'], $this->_interval
);
510 $this->assign('chartType', $this->_params
['charts']);
515 function alterDisplay(&$rows) {
516 // custom code to alter rows
519 foreach ($rows as $rowNum => $row) {
520 // make count columns point to detail report
521 if (CRM_Utils_Array
::value('receive_date', $this->_params
['group_bys']) &&
522 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
523 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
524 CRM_Utils_Array
::value('civicrm_contribution_receive_date_subtotal', $row)
527 $dateStart = CRM_Utils_Date
::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
528 $endDate = new DateTime($dateStart);
531 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
533 switch (strtolower($this->_params
['group_bys_freq']['receive_date'])) {
535 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
1,
536 $dateEnd['d'] - 1, $dateEnd['Y']
541 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
542 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
547 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
548 $dateEnd['d'] +
6, $dateEnd['Y']
553 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
3,
554 $dateEnd['d'] - 1, $dateEnd['Y']
558 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
559 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
562 $this->_drilldownReport
564 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
565 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
569 // make subtotals look nicer
570 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
571 !$row['civicrm_contribution_receive_date_subtotal']
573 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields
);
577 // convert display name to links
578 if (array_key_exists('civicrm_contact_sort_name', $row) &&
579 array_key_exists('civicrm_contact_id', $row)
581 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
582 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
583 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
585 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
586 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
590 // convert campaign_id to campaign title
591 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
592 if ($value = $row['civicrm_contribution_campaign_id']) {
593 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns
[$value];
597 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
600 // skip looking further in rows, if first row itself doesn't
601 // have the column we need