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'), ),
126 array('required' => TRUE,
127 'no_display' => TRUE,
130 array('title' => ts('Amount Statistics'),
134 array('sum' => ts('Aggregate Amount'),
135 'count' => ts('Donations'),
136 'avg' => ts('Average'),
140 'grouping' => 'contri-fields',
144 array('operatorType' => CRM_Report_Form
::OP_DATE
),
145 'contribution_status_id' =>
146 array('title' => ts('Donation Status'),
147 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
148 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
149 'default' => array(1),
150 'type' => CRM_Utils_Type
::T_INT
,
153 array('title' => 'Currency',
154 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
155 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
157 'type' => CRM_Utils_Type
::T_STRING
,
159 'financial_type_id' =>
160 array('title' => ts('Financial Type'),
161 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
162 'options' => CRM_Contribute_PseudoConstant
::financialType(),
163 'type' => CRM_Utils_Type
::T_INT
,
166 array('title' => ts('Donation Amount'),
169 array('title' => ts('Aggregate Amount'),
170 'type' => CRM_Report_Form
::OP_INT
,
171 'dbAlias' => 'civicrm_contribution_total_amount_sum',
175 array('title' => ts('Donation Count'),
176 'type' => CRM_Report_Form
::OP_INT
,
177 'dbAlias' => 'civicrm_contribution_total_amount_count',
181 array('title' => ts('Average'),
182 'type' => CRM_Report_Form
::OP_INT
,
183 'dbAlias' => 'civicrm_contribution_total_amount_avg',
195 'contribution_source' => NULL,
200 'dao' => 'CRM_Contact_DAO_GroupContact',
206 'name' => 'group_id',
207 'title' => ts('Group'),
208 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
210 'options' => CRM_Core_PseudoConstant
::group(),
211 'type' => CRM_Utils_Type
::T_INT
,
215 ) +
$this->addAddressFields();
217 $this->_tagFilter
= TRUE;
218 if ($campaignEnabled && !empty($this->activeCampaigns
)) {
219 $this->_columns
['civicrm_contribution']['fields']['campaign_id'] = array(
220 'title' => 'Campaign',
221 'default' => 'false',
223 $this->_columns
['civicrm_contribution']['filters']['campaign_id'] = array('title' => ts('Campaign'),
224 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
225 'options' => $this->activeCampaigns
,
227 $this->_columns
['civicrm_contribution']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
230 $this->_currencyColumn
= 'civicrm_contribution_currency';
231 parent
::__construct();
234 function preProcess() {
235 parent
::preProcess();
238 function setDefaultValues($freeze = TRUE) {
239 return parent
::setDefaultValues($freeze);
244 $this->_columnHeaders
= array();
245 foreach ($this->_columns
as $tableName => $table) {
246 if (array_key_exists('group_bys', $table)) {
247 foreach ($table['group_bys'] as $fieldName => $field) {
248 if ($tableName == 'civicrm_address') {
249 $this->_addressField
= TRUE;
251 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
252 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
254 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
255 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
256 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
257 $field['title'] = 'Week';
261 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
262 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
263 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
264 $field['title'] = 'Year';
268 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
269 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
270 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
271 $field['title'] = 'Month';
275 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
276 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
277 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
278 $field['title'] = 'Quarter';
281 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
282 $this->_interval
= $field['title'];
283 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
284 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
285 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
287 // just to make sure these values are transfered to rows.
288 // since we need that for calculation purpose,
289 // e.g making subtotals look nicer or graphs
290 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
291 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
297 if (array_key_exists('fields', $table)) {
298 foreach ($table['fields'] as $fieldName => $field) {
299 if ($tableName == 'civicrm_address') {
300 $this->_addressField
= TRUE;
302 if (CRM_Utils_Array
::value('required', $field) ||
303 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
306 // only include statistics columns if set
307 if (CRM_Utils_Array
::value('statistics', $field)) {
308 foreach ($field['statistics'] as $stat => $label) {
309 switch (strtolower($stat)) {
311 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
312 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
313 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
314 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
318 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
319 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
320 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
321 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
325 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
326 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
327 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
328 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
334 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
335 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
336 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
343 $this->_select
= "SELECT " . implode(', ', $select) . " ";
346 static function formRule($fields, $files, $self) {
347 $errors = $grouping = array();
348 //check for searching combination of dispaly columns and
350 $ignoreFields = array('total_amount', 'sort_name');
351 $errors = $self->customDataFormRule($fields, $ignoreFields);
353 if (!CRM_Utils_Array
::value('receive_date', $fields['group_bys'])) {
354 if (CRM_Utils_Array
::value('receive_date_relative', $fields) ||
355 CRM_Utils_Date
::isDate($fields['receive_date_from']) ||
356 CRM_Utils_Date
::isDate($fields['receive_date_to'])
358 $errors['receive_date_relative'] = ts("Do not use filter on Date if group by Receive Date is not used ");
361 if (!CRM_Utils_Array
::value('total_amount', $fields['fields'])) {
363 'total_count_value', 'total_sum_value', 'total_avg_value') as $val) {
364 if (CRM_Utils_Array
::value($val, $fields)) {
365 $errors[$val] = ts("Please select the Amount Statistics");
375 FROM civicrm_contact {$this->_aliases['civicrm_contact']}
376 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
377 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
378 {$this->_aliases['civicrm_contribution']}.is_test = 0
379 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
380 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
381 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
382 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
383 {$this->_aliases['civicrm_email']}.is_primary = 1)
385 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
386 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
387 {$this->_aliases['civicrm_phone']}.is_primary = 1)";
389 if ($this->_addressField
) {
391 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
392 ON {$this->_aliases['civicrm_contact']}.id =
393 {$this->_aliases['civicrm_address']}.contact_id AND
394 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
399 $this->_groupBy
= "";
401 if (is_array($this->_params
['group_bys']) &&
402 !empty($this->_params
['group_bys'])
404 foreach ($this->_columns
as $tableName => $table) {
405 if (array_key_exists('group_bys', $table)) {
406 foreach ($table['group_bys'] as $fieldName => $field) {
407 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
408 if (CRM_Utils_Array
::value('chart', $field)) {
409 $this->assign('chartSupported', TRUE);
412 if (CRM_Utils_Array
::value('frequency', $table['group_bys'][$fieldName]) &&
413 CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])
416 $append = "YEAR({$field['dbAlias']}),";
417 if (in_array(strtolower($this->_params
['group_bys_freq'][$fieldName]),
422 $this->_groupBy
[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
426 $this->_groupBy
[] = $field['dbAlias'];
433 if (!empty($this->_statFields
) &&
434 (($append && count($this->_groupBy
) <= 1) ||
(!$append)) && !$this->_having
436 $this->_rollup
= " WITH ROLLUP";
438 $this->_groupBy
= "GROUP BY " . implode(', ', $this->_groupBy
) . " {$this->_rollup} ";
441 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contact']}.id";
445 function statistics(&$rows) {
446 $statistics = parent
::statistics($rows);
448 if (!$this->_having
) {
450 SELECT COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as count,
451 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount,
452 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as avg, {$this->_aliases['civicrm_contribution']}.currency as currency
454 $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
455 $sql = "{$select} {$this->_from} {$this->_where}{$group}";
457 $dao = CRM_Core_DAO
::executeQuery($sql);
458 $totalAmount = $average = array();
460 while ($dao->fetch()) {
461 $totalAmount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
)."(".$dao->count
.")";
462 $average[] = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
463 $count +
= $dao->count
;
466 $statistics['counts']['amount'] = array(
467 'title' => ts('Total Amount'),
468 'value' => implode(', ', $totalAmount),
469 'type' => CRM_Utils_Type
::T_STRING
,
471 $statistics['counts']['count'] = array(
472 'title' => ts('Total Donations'),
475 $statistics['counts']['avg'] = array(
476 'title' => ts('Average'),
477 'value' => implode(', ', $average),
478 'type' => CRM_Utils_Type
::T_STRING
,
485 function postProcess() {
486 $this->buildACLClause($this->_aliases
['civicrm_contact']);
487 parent
::postProcess();
490 function buildChart(&$rows) {
491 $graphRows = array();
494 if (CRM_Utils_Array
::value('charts', $this->_params
)) {
495 foreach ($rows as $key => $row) {
496 if ($row['civicrm_contribution_receive_date_subtotal']) {
497 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
498 $graphRows[$this->_interval
][] = $row['civicrm_contribution_receive_date_interval'];
499 $graphRows['value'][] = $row['civicrm_contribution_total_amount_sum'];
504 if (CRM_Utils_Array
::value('receive_date', $this->_params
['group_bys'])) {
507 $config = CRM_Core_Config
::Singleton();
508 $graphRows['xname'] = $this->_interval
;
509 $graphRows['yname'] = "Amount ({$config->defaultCurrency})";
510 CRM_Utils_OpenFlashChart
::chart($graphRows, $this->_params
['charts'], $this->_interval
);
511 $this->assign('chartType', $this->_params
['charts']);
516 function alterDisplay(&$rows) {
517 // custom code to alter rows
520 foreach ($rows as $rowNum => $row) {
521 // make count columns point to detail report
522 if (CRM_Utils_Array
::value('receive_date', $this->_params
['group_bys']) &&
523 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
524 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
525 CRM_Utils_Array
::value('civicrm_contribution_receive_date_subtotal', $row)
528 $dateStart = CRM_Utils_Date
::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
529 $endDate = new DateTime($dateStart);
532 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
534 switch (strtolower($this->_params
['group_bys_freq']['receive_date'])) {
536 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
1,
537 $dateEnd['d'] - 1, $dateEnd['Y']
542 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
543 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
548 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
549 $dateEnd['d'] +
6, $dateEnd['Y']
554 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
3,
555 $dateEnd['d'] - 1, $dateEnd['Y']
559 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
560 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
563 $this->_drilldownReport
565 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
566 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
570 // make subtotals look nicer
571 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
572 !$row['civicrm_contribution_receive_date_subtotal']
574 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields
);
578 // convert display name to links
579 if (array_key_exists('civicrm_contact_sort_name', $row) &&
580 array_key_exists('civicrm_contact_id', $row)
582 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
583 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
584 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
586 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
587 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
591 // convert campaign_id to campaign title
592 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
593 if ($value = $row['civicrm_contribution_campaign_id']) {
594 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns
[$value];
598 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
601 // skip looking further in rows, if first row itself doesn't
602 // have the column we need