3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
35 class CRM_Report_Form_Contribute_Summary
extends CRM_Report_Form
{
36 protected $_addressField = FALSE;
38 protected $_charts = array(
40 'barChart' => 'Bar Chart',
41 'pieChart' => 'Pie Chart',
43 protected $_customGroupExtends = array('Contribution');
44 protected $_customGroupGroupBy = TRUE;
46 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
48 function __construct() {
50 // Check if CiviCampaign is a) enabled and b) has active campaigns
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
);
59 $this->_columns
= array(
62 'dao' => 'CRM_Contact_DAO_Contact',
66 array('title' => ts('Contact Name'),
69 'postal_greeting_display' =>
70 array('title' => ts('Postal Greeting')),
77 'grouping' => 'contact-fields',
81 array('title' => ts('Contact ID')),
83 array('title' => ts('Contact Name'),
89 'dao' => 'CRM_Core_DAO_Email',
93 array('title' => ts('Email'),
97 'grouping' => 'contact-fields',
101 'dao' => 'CRM_Core_DAO_Phone',
105 array('title' => ts('Phone'),
109 'grouping' => 'contact-fields',
111 'civicrm_financial_type' =>
112 array('dao' => 'CRM_Financial_DAO_FinancialType',
113 'fields' => array('financial_type' => null,),
114 'grouping' => 'contri-fields',
115 'group_bys' => array(
116 'financial_type' => array('title' => ts('Financial Type')),
119 'civicrm_contribution' =>
121 'dao' => 'CRM_Contribute_DAO_Contribution',
122 //'bao' => 'CRM_Contribute_BAO_Contribution',
125 'contribution_source' => array('title' => ts('Source'), ),
127 array('required' => TRUE,
128 'no_display' => TRUE,
131 array('title' => ts('Amount Statistics'),
135 array('sum' => ts('Aggregate Amount'),
136 'count' => ts('Donations'),
137 'avg' => ts('Average'),
141 'grouping' => 'contri-fields',
145 array('operatorType' => CRM_Report_Form
::OP_DATE
),
146 'contribution_status_id' =>
147 array('title' => ts('Donation Status'),
148 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
149 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
150 'default' => array(1),
151 'type' => CRM_Utils_Type
::T_INT
,
154 array('title' => 'Currency',
155 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
156 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
158 'type' => CRM_Utils_Type
::T_STRING
,
160 'financial_type_id' =>
161 array('title' => ts('Financial Type'),
162 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
163 'options' => CRM_Contribute_PseudoConstant
::financialType(),
164 'type' => CRM_Utils_Type
::T_INT
,
167 array('title' => ts('Donation Amount'),
170 array('title' => ts('Aggregate Amount'),
171 'type' => CRM_Report_Form
::OP_INT
,
172 'dbAlias' => 'civicrm_contribution_total_amount_sum',
176 array('title' => ts('Donation Count'),
177 'type' => CRM_Report_Form
::OP_INT
,
178 'dbAlias' => 'civicrm_contribution_total_amount_count',
182 array('title' => ts('Average'),
183 'type' => CRM_Report_Form
::OP_INT
,
184 'dbAlias' => 'civicrm_contribution_total_amount_avg',
196 'contribution_source' => NULL,
201 'dao' => 'CRM_Contact_DAO_GroupContact',
207 'name' => 'group_id',
208 'title' => ts('Group'),
209 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
211 'options' => CRM_Core_PseudoConstant
::group(),
212 'type' => CRM_Utils_Type
::T_INT
,
216 ) +
$this->addAddressFields();
218 // If we have a campaign, build out the relevant elements
219 $this->_tagFilter
= TRUE;
220 if ($campaignEnabled && !empty($this->activeCampaigns
)) {
221 $this->_columns
['civicrm_contribution']['fields']['campaign_id'] = array(
222 'title' => 'Campaign',
223 'default' => 'false',
225 $this->_columns
['civicrm_contribution']['filters']['campaign_id'] = array('title' => ts('Campaign'),
226 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
227 'options' => $this->activeCampaigns
,
229 $this->_columns
['civicrm_contribution']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
232 $this->_currencyColumn
= 'civicrm_contribution_currency';
233 parent
::__construct();
236 function preProcess() {
237 parent
::preProcess();
240 function setDefaultValues($freeze = TRUE) {
241 return parent
::setDefaultValues($freeze);
246 $this->_columnHeaders
= array();
247 foreach ($this->_columns
as $tableName => $table) {
248 if (array_key_exists('group_bys', $table)) {
249 foreach ($table['group_bys'] as $fieldName => $field) {
250 if ($tableName == 'civicrm_address') {
251 $this->_addressField
= TRUE;
253 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
254 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
256 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
257 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
258 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
259 $field['title'] = 'Week';
263 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
264 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
265 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
266 $field['title'] = 'Year';
270 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
271 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
272 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
273 $field['title'] = 'Month';
277 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
278 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
279 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
280 $field['title'] = 'Quarter';
283 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
284 $this->_interval
= $field['title'];
285 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
286 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
287 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
289 // just to make sure these values are transfered to rows.
290 // since we need that for calculation purpose,
291 // e.g making subtotals look nicer or graphs
292 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
293 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
299 if (array_key_exists('fields', $table)) {
300 foreach ($table['fields'] as $fieldName => $field) {
301 if ($tableName == 'civicrm_address') {
302 $this->_addressField
= TRUE;
304 if (CRM_Utils_Array
::value('required', $field) ||
305 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
308 // only include statistics columns if set
309 if (CRM_Utils_Array
::value('statistics', $field)) {
310 foreach ($field['statistics'] as $stat => $label) {
311 switch (strtolower($stat)) {
313 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
314 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
315 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
316 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
320 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
321 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
322 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
323 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
327 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
328 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
329 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
330 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
336 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
337 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
338 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
345 $this->_select
= "SELECT " . implode(', ', $select) . " ";
348 static function formRule($fields, $files, $self) {
349 $errors = $grouping = array();
350 //check for searching combination of dispaly columns and
352 $ignoreFields = array('total_amount', 'sort_name');
353 $errors = $self->customDataFormRule($fields, $ignoreFields);
355 if (!CRM_Utils_Array
::value('receive_date', $fields['group_bys'])) {
356 if (CRM_Utils_Array
::value('receive_date_relative', $fields) ||
357 CRM_Utils_Date
::isDate($fields['receive_date_from']) ||
358 CRM_Utils_Date
::isDate($fields['receive_date_to'])
360 $errors['receive_date_relative'] = ts("Do not use filter on Date if group by Receive Date is not used ");
363 if (!CRM_Utils_Array
::value('total_amount', $fields['fields'])) {
365 'total_count_value', 'total_sum_value', 'total_avg_value') as $val) {
366 if (CRM_Utils_Array
::value($val, $fields)) {
367 $errors[$val] = ts("Please select the Amount Statistics");
377 FROM civicrm_contact {$this->_aliases['civicrm_contact']}
378 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
379 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
380 {$this->_aliases['civicrm_contribution']}.is_test = 0
381 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
382 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
383 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
384 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
385 {$this->_aliases['civicrm_email']}.is_primary = 1)
387 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
388 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
389 {$this->_aliases['civicrm_phone']}.is_primary = 1)";
391 if ($this->_addressField
) {
393 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
394 ON {$this->_aliases['civicrm_contact']}.id =
395 {$this->_aliases['civicrm_address']}.contact_id AND
396 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
401 $this->_groupBy
= "";
403 if (is_array($this->_params
['group_bys']) &&
404 !empty($this->_params
['group_bys'])
406 foreach ($this->_columns
as $tableName => $table) {
407 if (array_key_exists('group_bys', $table)) {
408 foreach ($table['group_bys'] as $fieldName => $field) {
409 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
410 if (CRM_Utils_Array
::value('chart', $field)) {
411 $this->assign('chartSupported', TRUE);
414 if (CRM_Utils_Array
::value('frequency', $table['group_bys'][$fieldName]) &&
415 CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])
418 $append = "YEAR({$field['dbAlias']}),";
419 if (in_array(strtolower($this->_params
['group_bys_freq'][$fieldName]),
424 $this->_groupBy
[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
428 $this->_groupBy
[] = $field['dbAlias'];
435 if (!empty($this->_statFields
) &&
436 (($append && count($this->_groupBy
) <= 1) ||
(!$append)) && !$this->_having
438 $this->_rollup
= " WITH ROLLUP";
440 $this->_groupBy
= "GROUP BY " . implode(', ', $this->_groupBy
) . " {$this->_rollup} ";
443 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contact']}.id";
447 function statistics(&$rows) {
448 $statistics = parent
::statistics($rows);
450 if (!$this->_having
) {
452 SELECT COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as count,
453 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount,
454 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as avg, {$this->_aliases['civicrm_contribution']}.currency as currency
456 $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
457 $sql = "{$select} {$this->_from} {$this->_where}{$group}";
459 $dao = CRM_Core_DAO
::executeQuery($sql);
460 $totalAmount = $average = array();
462 while ($dao->fetch()) {
463 $totalAmount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
)."(".$dao->count
.")";
464 $average[] = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
465 $count +
= $dao->count
;
468 $statistics['counts']['amount'] = array(
469 'title' => ts('Total Amount'),
470 'value' => implode(', ', $totalAmount),
471 'type' => CRM_Utils_Type
::T_STRING
,
473 $statistics['counts']['count'] = array(
474 'title' => ts('Total Donations'),
477 $statistics['counts']['avg'] = array(
478 'title' => ts('Average'),
479 'value' => implode(', ', $average),
480 'type' => CRM_Utils_Type
::T_STRING
,
487 function postProcess() {
488 $this->buildACLClause($this->_aliases
['civicrm_contact']);
489 parent
::postProcess();
492 function buildChart(&$rows) {
493 $graphRows = array();
496 if (CRM_Utils_Array
::value('charts', $this->_params
)) {
497 foreach ($rows as $key => $row) {
498 if ($row['civicrm_contribution_receive_date_subtotal']) {
499 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
500 $graphRows[$this->_interval
][] = $row['civicrm_contribution_receive_date_interval'];
501 $graphRows['value'][] = $row['civicrm_contribution_total_amount_sum'];
506 if (CRM_Utils_Array
::value('receive_date', $this->_params
['group_bys'])) {
509 $config = CRM_Core_Config
::Singleton();
510 $graphRows['xname'] = $this->_interval
;
511 $graphRows['yname'] = "Amount ({$config->defaultCurrency})";
512 CRM_Utils_OpenFlashChart
::chart($graphRows, $this->_params
['charts'], $this->_interval
);
513 $this->assign('chartType', $this->_params
['charts']);
518 function alterDisplay(&$rows) {
519 // custom code to alter rows
522 foreach ($rows as $rowNum => $row) {
523 // make count columns point to detail report
524 if (CRM_Utils_Array
::value('receive_date', $this->_params
['group_bys']) &&
525 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
526 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
527 CRM_Utils_Array
::value('civicrm_contribution_receive_date_subtotal', $row)
530 $dateStart = CRM_Utils_Date
::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
531 $endDate = new DateTime($dateStart);
534 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
536 switch (strtolower($this->_params
['group_bys_freq']['receive_date'])) {
538 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
1,
539 $dateEnd['d'] - 1, $dateEnd['Y']
544 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
545 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
550 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
551 $dateEnd['d'] +
6, $dateEnd['Y']
556 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
3,
557 $dateEnd['d'] - 1, $dateEnd['Y']
561 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
562 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
565 $this->_drilldownReport
567 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
568 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
572 // make subtotals look nicer
573 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
574 !$row['civicrm_contribution_receive_date_subtotal']
576 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields
);
580 // convert display name to links
581 if (array_key_exists('civicrm_contact_sort_name', $row) &&
582 array_key_exists('civicrm_contact_id', $row)
584 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
585 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
586 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
588 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
589 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
593 // If using campaigns, convert campaign_id to campaign title
594 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
595 if ($value = $row['civicrm_contribution_campaign_id']) {
596 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns
[$value];
601 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
603 // skip looking further in rows, if first row itself doesn't
604 // have the column we need