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',
113 array( 'financial_type' => null, ),
114 'grouping' => 'contri-fields',
116 array( 'financial_type' => array('title' => ts('Financial Type')), ), ),
117 'civicrm_contribution' =>
119 'dao' => 'CRM_Contribute_DAO_Contribution',
120 //'bao' => 'CRM_Contribute_BAO_Contribution',
123 'contribution_source' => array('title' => ts('Source'),
126 array('title' => ts('Amount Statistics'),
130 array('sum' => ts('Aggregate Amount'),
131 'count' => ts('Donations'),
132 'avg' => ts('Average'),
136 'grouping' => 'contri-fields',
140 array('operatorType' => CRM_Report_Form
::OP_DATE
),
141 'contribution_status_id' =>
142 array('title' => ts('Donation Status'),
143 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
144 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
145 'default' => array(1),
146 'type' => CRM_Utils_Type
::T_INT
,
148 'financial_type_id' =>
149 array( 'title' => ts( 'Financial Type' ),
150 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
151 'options' => CRM_Contribute_PseudoConstant
::financialType( ),
152 'type' => CRM_Utils_Type
::T_INT
,
155 array('title' => ts('Donation Amount'),
158 array('title' => ts('Aggregate Amount'),
159 'type' => CRM_Report_Form
::OP_INT
,
160 'dbAlias' => 'civicrm_contribution_total_amount_sum',
164 array('title' => ts('Donation Count'),
165 'type' => CRM_Report_Form
::OP_INT
,
166 'dbAlias' => 'civicrm_contribution_total_amount_count',
170 array('title' => ts('Average'),
171 'type' => CRM_Report_Form
::OP_INT
,
172 'dbAlias' => 'civicrm_contribution_total_amount_avg',
184 'contribution_source' => NULL,
189 'dao' => 'CRM_Contact_DAO_GroupContact',
195 'name' => 'group_id',
196 'title' => ts('Group'),
197 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
199 'options' => CRM_Core_PseudoConstant
::group(),
200 'type' => CRM_Utils_Type
::T_INT
,
204 ) +
$this->addAddressFields();
206 $this->_tagFilter
= TRUE;
207 if ($campaignEnabled && !empty($this->activeCampaigns
)) {
208 $this->_columns
['civicrm_contribution']['fields']['campaign_id'] = array(
209 'title' => 'Campaign',
210 'default' => 'false',
212 $this->_columns
['civicrm_contribution']['filters']['campaign_id'] = array('title' => ts('Campaign'),
213 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
214 'options' => $this->activeCampaigns
,
216 $this->_columns
['civicrm_contribution']['grouping']['campaign_id'] = 'contri-fields';
217 $this->_columns
['civicrm_contribution']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
219 parent
::__construct();
222 function preProcess() {
223 parent
::preProcess();
226 function setDefaultValues($freeze = TRUE) {
227 return parent
::setDefaultValues($freeze);
232 $this->_columnHeaders
= array();
233 foreach ($this->_columns
as $tableName => $table) {
234 if (array_key_exists('group_bys', $table)) {
235 foreach ($table['group_bys'] as $fieldName => $field) {
236 if ($tableName == 'civicrm_address') {
237 $this->_addressField
= TRUE;
239 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
240 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
242 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
243 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
244 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
245 $field['title'] = 'Week';
249 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
250 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
251 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
252 $field['title'] = 'Year';
256 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
257 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
258 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
259 $field['title'] = 'Month';
263 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
264 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
265 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
266 $field['title'] = 'Quarter';
269 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
270 $this->_interval
= $field['title'];
271 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
272 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
273 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
275 // just to make sure these values are transfered to rows.
276 // since we need that for calculation purpose,
277 // e.g making subtotals look nicer or graphs
278 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
279 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
285 if (array_key_exists('fields', $table)) {
286 foreach ($table['fields'] as $fieldName => $field) {
287 if ($tableName == 'civicrm_address') {
288 $this->_addressField
= TRUE;
290 if (CRM_Utils_Array
::value('required', $field) ||
291 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
294 // only include statistics columns if set
295 if (CRM_Utils_Array
::value('statistics', $field)) {
296 foreach ($field['statistics'] as $stat => $label) {
297 switch (strtolower($stat)) {
299 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
300 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
301 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
302 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
306 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
307 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
308 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
309 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
313 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
314 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
315 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
316 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
322 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
323 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
324 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
331 $this->_select
= "SELECT " . implode(', ', $select) . " ";
334 static function formRule($fields, $files, $self) {
335 $errors = $grouping = array();
336 //check for searching combination of dispaly columns and
338 $ignoreFields = array('total_amount', 'sort_name');
339 $errors = $self->customDataFormRule($fields, $ignoreFields);
341 if (CRM_Utils_Array
::value('receive_date', $fields['group_bys'])) {
342 foreach ($self->_columns
as $tableName => $table) {
343 if (array_key_exists('fields', $table)) {
344 foreach ($table['fields'] as $fieldName => $field) {
345 if (CRM_Utils_Array
::value($field['name'], $fields['fields']) &&
346 $fields['fields'][$field['name']] &&
347 in_array( $field['name'], array( 'sort_name', 'postal_greeting_display', 'contribution_source', 'financial_type' ) ) ) {
348 $grouping[] = $field['title'];
353 if (!empty($grouping)) {
354 $temp = 'and ' . implode(', ', $grouping);
355 $errors['fields'] = ts("Please do not use combination of Receive Date %1", array(1 => $temp));
359 if (!CRM_Utils_Array
::value('receive_date', $fields['group_bys'])) {
360 if (CRM_Utils_Array
::value('receive_date_relative', $fields) ||
361 CRM_Utils_Date
::isDate($fields['receive_date_from']) ||
362 CRM_Utils_Date
::isDate($fields['receive_date_to'])
364 $errors['receive_date_relative'] = ts("Do not use filter on Date if group by Receive Date is not used ");
367 if (!CRM_Utils_Array
::value('total_amount', $fields['fields'])) {
369 'total_count_value', 'total_sum_value', 'total_avg_value') as $val) {
370 if (CRM_Utils_Array
::value($val, $fields)) {
371 $errors[$val] = ts("Please select the Amount Statistics");
381 FROM civicrm_contact {$this->_aliases['civicrm_contact']}
382 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
383 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
384 {$this->_aliases['civicrm_contribution']}.is_test = 0
385 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
386 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
387 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
388 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
389 {$this->_aliases['civicrm_email']}.is_primary = 1)
391 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
392 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
393 {$this->_aliases['civicrm_phone']}.is_primary = 1)";
395 if ($this->_addressField
) {
397 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
398 ON {$this->_aliases['civicrm_contact']}.id =
399 {$this->_aliases['civicrm_address']}.contact_id AND
400 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
405 $this->_groupBy
= "";
407 if (is_array($this->_params
['group_bys']) &&
408 !empty($this->_params
['group_bys'])
410 foreach ($this->_columns
as $tableName => $table) {
411 if (array_key_exists('group_bys', $table)) {
412 foreach ($table['group_bys'] as $fieldName => $field) {
413 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
414 if (CRM_Utils_Array
::value('chart', $field)) {
415 $this->assign('chartSupported', TRUE);
418 if (CRM_Utils_Array
::value('frequency', $table['group_bys'][$fieldName]) &&
419 CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])
422 $append = "YEAR({$field['dbAlias']}),";
423 if (in_array(strtolower($this->_params
['group_bys_freq'][$fieldName]),
428 $this->_groupBy
[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
432 $this->_groupBy
[] = $field['dbAlias'];
439 if (!empty($this->_statFields
) &&
440 (($append && count($this->_groupBy
) <= 1) ||
(!$append)) && !$this->_having
442 $this->_rollup
= " WITH ROLLUP";
444 $this->_groupBy
= "GROUP BY " . implode(', ', $this->_groupBy
) . " {$this->_rollup} ";
447 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contact']}.id";
451 function statistics(&$rows) {
452 $statistics = parent
::statistics($rows);
454 if (!$this->_having
) {
456 SELECT COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as count,
457 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount,
458 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as avg
461 $sql = "{$select} {$this->_from} {$this->_where}";
462 $dao = CRM_Core_DAO
::executeQuery($sql);
465 $statistics['counts']['amount'] = array(
466 'value' => $dao->amount
,
467 'title' => 'Total Amount',
468 'type' => CRM_Utils_Type
::T_MONEY
,
470 $statistics['counts']['count '] = array(
471 'value' => $dao->count
,
472 'title' => 'Total Donations',
474 $statistics['counts']['avg '] = array(
475 'value' => $dao->avg
,
476 'title' => 'Average',
477 'type' => CRM_Utils_Type
::T_MONEY
,
484 function postProcess() {
485 parent
::postProcess();
488 function buildChart(&$rows) {
489 $graphRows = array();
492 if (CRM_Utils_Array
::value('charts', $this->_params
)) {
493 foreach ($rows as $key => $row) {
494 if ($row['civicrm_contribution_receive_date_subtotal']) {
495 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
496 $graphRows[$this->_interval
][] = $row['civicrm_contribution_receive_date_interval'];
497 $graphRows['value'][] = $row['civicrm_contribution_total_amount_sum'];
502 if (CRM_Utils_Array
::value('receive_date', $this->_params
['group_bys'])) {
505 $config = CRM_Core_Config
::Singleton();
506 $graphRows['xname'] = $this->_interval
;
507 $graphRows['yname'] = "Amount ({$config->defaultCurrency})";
508 CRM_Utils_OpenFlashChart
::chart($graphRows, $this->_params
['charts'], $this->_interval
);
509 $this->assign('chartType', $this->_params
['charts']);
514 function alterDisplay(&$rows) {
515 // custom code to alter rows
518 foreach ($rows as $rowNum => $row) {
519 // make count columns point to detail report
520 if (CRM_Utils_Array
::value('receive_date', $this->_params
['group_bys']) &&
521 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
522 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
523 CRM_Utils_Array
::value('civicrm_contribution_receive_date_subtotal', $row)
526 $dateStart = CRM_Utils_Date
::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
527 $endDate = new DateTime($dateStart);
530 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
532 switch (strtolower($this->_params
['group_bys_freq']['receive_date'])) {
534 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
1,
535 $dateEnd['d'] - 1, $dateEnd['Y']
540 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
541 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
546 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
547 $dateEnd['d'] +
6, $dateEnd['Y']
552 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
3,
553 $dateEnd['d'] - 1, $dateEnd['Y']
557 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
558 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
561 $this->_drilldownReport
563 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
564 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
568 // make subtotals look nicer
569 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
570 !$row['civicrm_contribution_receive_date_subtotal']
572 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields
);
576 // convert display name to links
577 if (array_key_exists('civicrm_contact_sort_name', $row) &&
578 array_key_exists('civicrm_contact_id', $row)
580 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
581 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
582 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
584 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
585 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
589 // convert campaign_id to campaign title
590 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
591 if ($value = $row['civicrm_contribution_campaign_id']) {
592 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns
[$value];
596 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
599 // skip looking further in rows, if first row itself doesn't
600 // have the column we need