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() {
52 // Check if CiviCampaign is a) enabled and b) has active campaigns
53 $config = CRM_Core_Config
::singleton();
54 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents
);
55 if ($campaignEnabled) {
56 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
57 $this->activeCampaigns
= $getCampaigns['campaigns'];
58 asort($this->activeCampaigns
);
61 $this->_columns
= array(
64 'dao' => 'CRM_Contact_DAO_Contact',
68 array('title' => ts('Contact Name'),
71 'postal_greeting_display' =>
72 array('title' => ts('Postal Greeting')),
79 'grouping' => 'contact-fields',
83 array('title' => ts('Contact ID')),
85 array('title' => ts('Contact Name'),
91 'dao' => 'CRM_Core_DAO_Email',
95 array('title' => ts('Email'),
99 'grouping' => 'contact-fields',
103 'dao' => 'CRM_Core_DAO_Phone',
107 array('title' => ts('Phone'),
111 'grouping' => 'contact-fields',
113 'civicrm_financial_type' =>
114 array('dao' => 'CRM_Financial_DAO_FinancialType',
115 'fields' => array('financial_type' => null,),
116 'grouping' => 'contri-fields',
117 'group_bys' => array(
118 'financial_type' => array('title' => ts('Financial Type')),
121 'civicrm_contribution' =>
123 'dao' => 'CRM_Contribute_DAO_Contribution',
124 //'bao' => 'CRM_Contribute_BAO_Contribution',
127 'contribution_source' => array('title' => ts('Source'),
130 array('required' => TRUE,
131 'no_display' => TRUE,
134 array('title' => ts('Amount Statistics'),
138 array('sum' => ts('Aggregate Amount'),
139 'count' => ts('Donations'),
140 'avg' => ts('Average'),
144 'grouping' => 'contri-fields',
148 array('operatorType' => CRM_Report_Form
::OP_DATE
),
149 'contribution_status_id' =>
150 array('title' => ts('Donation Status'),
151 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
152 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
153 'default' => array(1),
154 'type' => CRM_Utils_Type
::T_INT
,
157 array('title' => 'Currency',
158 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
159 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
161 'type' => CRM_Utils_Type
::T_STRING
,
163 'financial_type_id' =>
164 array('title' => ts('Financial Type'),
165 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
166 'options' => CRM_Contribute_PseudoConstant
::financialType(),
167 'type' => CRM_Utils_Type
::T_INT
,
170 array('title' => ts('Donation Amount'),
173 array('title' => ts('Aggregate Amount'),
174 'type' => CRM_Report_Form
::OP_INT
,
175 'dbAlias' => 'civicrm_contribution_total_amount_sum',
179 array('title' => ts('Donation Count'),
180 'type' => CRM_Report_Form
::OP_INT
,
181 'dbAlias' => 'civicrm_contribution_total_amount_count',
185 array('title' => ts('Average'),
186 'type' => CRM_Report_Form
::OP_INT
,
187 'dbAlias' => 'civicrm_contribution_total_amount_avg',
199 'contribution_source' => NULL,
204 'dao' => 'CRM_Contact_DAO_GroupContact',
210 'name' => 'group_id',
211 'title' => ts('Group'),
212 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
214 'options' => CRM_Core_PseudoConstant
::group(),
215 'type' => CRM_Utils_Type
::T_INT
,
219 ) +
$this->addAddressFields();
221 // If we have a campaign, build out the relevant elements
222 $this->_tagFilter
= TRUE;
223 if ($campaignEnabled && !empty($this->activeCampaigns
)) {
224 $this->_columns
['civicrm_contribution']['fields']['campaign_id'] = array(
225 'title' => 'Campaign',
226 'default' => 'false',
228 $this->_columns
['civicrm_contribution']['filters']['campaign_id'] = array('title' => ts('Campaign'),
229 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
230 'options' => $this->activeCampaigns
,
232 $this->_columns
['civicrm_contribution']['grouping']['campaign_id'] = 'contri-fields';
233 $this->_columns
['civicrm_contribution']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
236 $this->_currencyColumn
= 'civicrm_contribution_currency';
237 parent
::__construct();
240 function preProcess() {
241 parent
::preProcess();
244 function setDefaultValues($freeze = TRUE) {
245 return parent
::setDefaultValues($freeze);
250 $this->_columnHeaders
= array();
251 foreach ($this->_columns
as $tableName => $table) {
252 if (array_key_exists('group_bys', $table)) {
253 foreach ($table['group_bys'] as $fieldName => $field) {
254 if ($tableName == 'civicrm_address') {
255 $this->_addressField
= TRUE;
257 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
258 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
260 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
261 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
262 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
263 $field['title'] = 'Week';
267 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
268 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
269 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
270 $field['title'] = 'Year';
274 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
275 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
276 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
277 $field['title'] = 'Month';
281 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
282 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
283 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
284 $field['title'] = 'Quarter';
287 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
288 $this->_interval
= $field['title'];
289 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
290 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
291 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
293 // just to make sure these values are transfered to rows.
294 // since we need that for calculation purpose,
295 // e.g making subtotals look nicer or graphs
296 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
297 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
303 if (array_key_exists('fields', $table)) {
304 foreach ($table['fields'] as $fieldName => $field) {
305 if ($tableName == 'civicrm_address') {
306 $this->_addressField
= TRUE;
308 if (CRM_Utils_Array
::value('required', $field) ||
309 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
312 // only include statistics columns if set
313 if (CRM_Utils_Array
::value('statistics', $field)) {
314 foreach ($field['statistics'] as $stat => $label) {
315 switch (strtolower($stat)) {
317 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
318 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
319 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
320 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
324 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
325 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
326 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
327 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
331 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
332 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
333 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
334 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
340 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
341 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
342 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
349 $this->_select
= "SELECT " . implode(', ', $select) . " ";
352 static function formRule($fields, $files, $self) {
353 $errors = $grouping = array();
354 //check for searching combination of dispaly columns and
356 $ignoreFields = array('total_amount', 'sort_name');
357 $errors = $self->customDataFormRule($fields, $ignoreFields);
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, {$this->_aliases['civicrm_contribution']}.currency as currency
460 $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
461 $sql = "{$select} {$this->_from} {$this->_where}{$group}";
463 $dao = CRM_Core_DAO
::executeQuery($sql);
464 $totalAmount = $average = array();
466 while ($dao->fetch()) {
467 $totalAmount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
)."(".$dao->count
.")";
468 $average[] = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
469 $count +
= $dao->count
;
472 $statistics['counts']['amount'] = array(
473 'title' => ts('Total Amount'),
474 'value' => implode(', ', $totalAmount),
475 'type' => CRM_Utils_Type
::T_STRING
,
477 $statistics['counts']['count'] = array(
478 'title' => ts('Total Donations'),
481 $statistics['counts']['avg'] = array(
482 'title' => ts('Average'),
483 'value' => implode(', ', $average),
484 'type' => CRM_Utils_Type
::T_STRING
,
491 function postProcess() {
492 $this->buildACLClause($this->_aliases
['civicrm_contact']);
493 parent
::postProcess();
496 function buildChart(&$rows) {
497 $graphRows = array();
500 if (CRM_Utils_Array
::value('charts', $this->_params
)) {
501 foreach ($rows as $key => $row) {
502 if ($row['civicrm_contribution_receive_date_subtotal']) {
503 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
504 $graphRows[$this->_interval
][] = $row['civicrm_contribution_receive_date_interval'];
505 $graphRows['value'][] = $row['civicrm_contribution_total_amount_sum'];
510 if (CRM_Utils_Array
::value('receive_date', $this->_params
['group_bys'])) {
513 $config = CRM_Core_Config
::Singleton();
514 $graphRows['xname'] = $this->_interval
;
515 $graphRows['yname'] = "Amount ({$config->defaultCurrency})";
516 CRM_Utils_OpenFlashChart
::chart($graphRows, $this->_params
['charts'], $this->_interval
);
517 $this->assign('chartType', $this->_params
['charts']);
522 function alterDisplay(&$rows) {
523 // custom code to alter rows
526 foreach ($rows as $rowNum => $row) {
527 // make count columns point to detail report
528 if (CRM_Utils_Array
::value('receive_date', $this->_params
['group_bys']) &&
529 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
530 CRM_Utils_Array
::value('civicrm_contribution_receive_date_start', $row) &&
531 CRM_Utils_Array
::value('civicrm_contribution_receive_date_subtotal', $row)
534 $dateStart = CRM_Utils_Date
::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
535 $endDate = new DateTime($dateStart);
538 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
540 switch (strtolower($this->_params
['group_bys_freq']['receive_date'])) {
542 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
1,
543 $dateEnd['d'] - 1, $dateEnd['Y']
548 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
549 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
554 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
555 $dateEnd['d'] +
6, $dateEnd['Y']
560 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
3,
561 $dateEnd['d'] - 1, $dateEnd['Y']
565 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
566 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
569 $this->_drilldownReport
571 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
572 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
576 // make subtotals look nicer
577 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
578 !$row['civicrm_contribution_receive_date_subtotal']
580 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields
);
584 // convert display name to links
585 if (array_key_exists('civicrm_contact_sort_name', $row) &&
586 array_key_exists('civicrm_contact_id', $row)
588 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
589 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
590 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
592 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
593 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
597 // If using campaigns, convert campaign_id to campaign title
598 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
599 if ($value = $row['civicrm_contribution_campaign_id']) {
600 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns
[$value];
605 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
607 // skip looking further in rows, if first row itself doesn't
608 // have the column we need