3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
35 class CRM_Report_Form_Member_Summary
extends CRM_Report_Form
{
37 protected $_summary = NULL;
38 protected $_interval = NULL;
39 protected $_charts = array(
41 'barChart' => 'Bar Chart',
42 'pieChart' => 'Pie Chart',
44 protected $_add2groupSupported = FALSE;
46 protected $_customGroupExtends = array('Membership');
47 protected $_customGroupGroupBy = FALSE;
48 public $_drilldownReport = array('member/detail' => 'Link to Detail Report');
54 public function __construct() {
56 // UI for selecting columns to appear in the report list
57 // Array containing the columns, group_bys and filters build and provided to Form
59 // Check if CiviCampaign is a) enabled and b) has active campaigns
60 $config = CRM_Core_Config
::singleton();
61 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents
);
62 if ($campaignEnabled) {
63 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
64 $this->activeCampaigns
= $getCampaigns['campaigns'];
65 asort($this->activeCampaigns
);
68 $this->_columns
= array(
69 'civicrm_membership' => array(
70 'dao' => 'CRM_Member_DAO_MembershipType',
71 'grouping' => 'member-fields',
73 'membership_type_id' => array(
74 'title' => 'Membership Type',
80 'title' => ts('Member Since'),
81 'type' => CRM_Utils_Type
::T_DATE
,
82 'operatorType' => CRM_Report_Form
::OP_DATE
,
84 'membership_start_date' => array(
85 'name' => 'start_date',
86 'title' => ts('Membership Start Date'),
87 'type' => CRM_Utils_Type
::T_DATE
,
88 'operatorType' => CRM_Report_Form
::OP_DATE
,
90 'membership_end_date' => array(
92 'title' => ts('Membership End Date'),
93 'type' => CRM_Utils_Type
::T_DATE
,
94 'operatorType' => CRM_Report_Form
::OP_DATE
,
96 'owner_membership_id' => array(
97 'title' => ts('Membership Owner ID'),
98 'type' => CRM_Utils_Type
::T_INT
,
99 'operatorType' => CRM_Report_Form
::OP_INT
,
101 'membership_type_id' => array(
102 'title' => ts('Membership Type'),
103 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
104 'options' => CRM_Member_PseudoConstant
::membershipType(),
106 'status_id' => array(
107 'title' => ts('Membership Status'),
108 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
109 'options' => CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label'),
112 'group_bys' => array(
113 'join_date' => array(
114 'title' => ts('Member Since'),
120 'membership_type_id' => array(
121 'title' => 'Membership Type',
127 'civicrm_contact' => array(
128 'dao' => 'CRM_Contact_DAO_Contact',
130 'contact_id' => array(
131 'no_display' => TRUE,
133 'contact_type' => array(
134 'title' => ts('Contact Type'),
136 'contact_sub_type' => array(
137 'title' => ts('Contact Subtype'),
141 'civicrm_contribution' => array(
142 'dao' => 'CRM_Contribute_DAO_Contribution',
146 'no_display' => TRUE,
148 'total_amount' => array(
149 'title' => ts('Amount Statistics'),
151 'statistics' => array(
152 'sum' => ts('Total Payments Made'),
153 'count' => ts('Contribution Count'),
154 'avg' => ts('Average'),
160 'title' => 'Currency',
161 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
162 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
164 'type' => CRM_Utils_Type
::T_STRING
,
166 'contribution_status_id' => array(
167 'title' => ts('Contribution Status'),
168 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
169 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
172 'grouping' => 'member-fields',
175 $this->_tagFilter
= TRUE;
177 // If we have a campaign, build out the relevant elements
178 if ($campaignEnabled && !empty($this->activeCampaigns
)) {
179 $this->_columns
['civicrm_membership']['fields']['campaign_id'] = array(
180 'title' => 'Campaign',
181 'default' => 'false',
183 $this->_columns
['civicrm_membership']['filters']['campaign_id'] = array(
184 'title' => ts('Campaign'),
185 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
186 'options' => $this->activeCampaigns
,
188 $this->_columns
['civicrm_membership']['grouping']['campaign_id'] = 'contri-fields';
189 $this->_columns
['civicrm_membership']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
192 $this->_groupFilter
= TRUE;
193 $this->_currencyColumn
= 'civicrm_contribution_currency';
194 parent
::__construct();
197 public function select() {
200 $this->_columnHeaders
= array();
201 $select[] = " COUNT( DISTINCT {$this->_aliases['civicrm_membership']}.id ) as civicrm_membership_member_count";
202 $select['joinDate'] = " {$this->_aliases['civicrm_membership']}.join_date as civicrm_membership_member_join_date";
203 $this->_columnHeaders
["civicrm_membership_member_join_date"] = array(
204 'title' => ts('Member Since'),
205 'type' => CRM_Utils_Type
::T_DATE
,
207 foreach ($this->_columns
as $tableName => $table) {
208 if (array_key_exists('group_bys', $table)) {
209 foreach ($table['group_bys'] as $fieldName => $field) {
210 if (!empty($this->_params
['group_bys'][$fieldName])) {
212 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
214 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
216 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
217 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
218 $field['title'] = 'Week';
222 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
223 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
224 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
225 $field['title'] = 'Year';
229 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
230 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
231 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
232 $field['title'] = 'Month';
236 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
237 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
238 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
239 $field['title'] = 'Quarter';
242 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
243 $this->_interval
= $field['title'];
244 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
245 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
246 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
248 // just to make sure these values are transferred to rows.
249 // since we need that for calculation purpose,
250 // e.g making subtotals look nicer or graphs
251 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
252 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
260 if (array_key_exists('fields', $table)) {
261 foreach ($table['fields'] as $fieldName => $field) {
262 if (!empty($field['required']) ||
263 !empty($this->_params
['fields'][$fieldName])
266 // only include statistics columns if set
267 if (!empty($field['statistics'])) {
268 $this->_statFields
[] = 'civicrm_membership_member_count';
269 foreach ($field['statistics'] as $stat => $label) {
270 switch (strtolower($stat)) {
272 $select[] = "IFNULL(SUM({$field['dbAlias']}), 0) as {$tableName}_{$fieldName}_{$stat}";
273 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
274 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
275 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
279 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
280 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
281 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
282 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
286 $select[] = "IFNULL(ROUND(AVG({$field['dbAlias']}),2), 0) as {$tableName}_{$fieldName}_{$stat}";
287 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
288 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
289 $this->_statFields
[] = "{$tableName}_{$fieldName}_{$stat}";
294 elseif ($fieldName == 'membership_type_id') {
295 if (empty($this->_params
['group_bys']['membership_type_id']) &&
296 !empty($this->_params
['group_bys']['join_date'])
298 $select[] = "GROUP_CONCAT(DISTINCT {$field['dbAlias']} ORDER BY {$field['dbAlias']} ) as {$tableName}_{$fieldName}";
301 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
303 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'];
304 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['operatorType'] = CRM_Utils_Array
::value('operatorType', $field);
307 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
308 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'];
309 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['operatorType'] = CRM_Utils_Array
::value('operatorType', $field);
314 $this->_columnHeaders
["civicrm_membership_member_count"] = array(
315 'title' => ts('Member Count'),
316 'type' => CRM_Utils_Type
::T_INT
,
319 //If grouping is availabled then remove join date from field
321 unset($select['joinDate']);
322 unset($this->_columnHeaders
["civicrm_membership_member_join_date"]);
324 $this->_select
= "SELECT " . implode(', ', $select) . " ";
327 public function from() {
329 FROM civicrm_membership {$this->_aliases['civicrm_membership']}
331 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']} ON ( {$this->_aliases['civicrm_membership']}.contact_id = {$this->_aliases['civicrm_contact']}.id )
333 LEFT JOIN civicrm_membership_status
334 ON ({$this->_aliases['civicrm_membership']}.status_id = civicrm_membership_status.id )
335 LEFT JOIN civicrm_membership_payment payment
336 ON ( {$this->_aliases['civicrm_membership']}.id = payment.membership_id )
337 LEFT JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
338 ON payment.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
341 public function where() {
342 $this->_whereClauses
[] = "{$this->_aliases['civicrm_membership']}.is_test = 0 AND
343 {$this->_aliases['civicrm_contact']}.is_deleted = 0";
347 public function groupBy() {
348 $this->_groupBy
= "";
349 if (is_array($this->_params
['group_bys']) &&
350 !empty($this->_params
['group_bys'])
352 foreach ($this->_columns
as $tableName => $table) {
353 if (array_key_exists('group_bys', $table)) {
354 foreach ($table['group_bys'] as $fieldName => $field) {
355 if (!empty($this->_params
['group_bys'][$fieldName])) {
356 if (!empty($field['chart'])) {
357 $this->assign('chartSupported', TRUE);
359 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
360 !empty($this->_params
['group_bys_freq'][$fieldName])
363 $append = "YEAR({$field['dbAlias']}),";
364 if (in_array(strtolower($this->_params
['group_bys_freq'][$fieldName]),
369 $this->_groupBy
[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
373 $this->_groupBy
[] = $field['dbAlias'];
380 $this->_rollup
= ' WITH ROLLUP';
381 $this->_groupBy
= 'GROUP BY ' . implode(', ', $this->_groupBy
) .
382 " {$this->_rollup} ";
385 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_membership']}.join_date";
394 public function statistics(&$rows) {
395 $statistics = parent
::statistics($rows);
397 SELECT COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as count,
398 IFNULL(SUM({$this->_aliases['civicrm_contribution']}.total_amount ), 0) as amount,
399 IFNULL(ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2),0) as avg,
400 COUNT( DISTINCT {$this->_aliases['civicrm_membership']}.id ) as memberCount,
401 {$this->_aliases['civicrm_contribution']}.currency as currency
404 $sql = "{$select} {$this->_from} {$this->_where}
405 GROUP BY {$this->_aliases['civicrm_contribution']}.currency
408 $dao = CRM_Core_DAO
::executeQuery($sql);
410 $totalAmount = $average = array();
411 $count = $memberCount = 0;
412 while ($dao->fetch()) {
413 $totalAmount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
) . "(" . $dao->count
. ")";
414 $average[] = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
415 $count +
= $dao->count
;
416 $memberCount +
= $dao->memberCount
;
418 $statistics['counts']['amount'] = array(
419 'title' => ts('Total Amount'),
420 'value' => implode(', ', $totalAmount),
421 'type' => CRM_Utils_Type
::T_STRING
,
423 $statistics['counts']['count'] = array(
424 'title' => ts('Total Contributions'),
427 $statistics['counts']['memberCount'] = array(
428 'title' => ts('Total Members'),
429 'value' => $memberCount,
431 $statistics['counts']['avg'] = array(
432 'title' => ts('Average'),
433 'value' => implode(', ', $average),
434 'type' => CRM_Utils_Type
::T_STRING
,
437 if (!(int) $statistics['counts']['amount']['value']) {
438 //if total amount is zero then hide Chart Options
439 $this->assign('chartSupported', FALSE);
445 public function postProcess() {
446 parent
::postProcess();
452 public function buildChart(&$rows) {
453 $graphRows = array();
455 $membershipTypeValues = CRM_Member_PseudoConstant
::membershipType();
456 $isMembershipType = CRM_Utils_Array
::value('membership_type_id', $this->_params
['group_bys']);
457 $isJoiningDate = CRM_Utils_Array
::value('join_date', $this->_params
['group_bys']);
458 if (!empty($this->_params
['charts'])) {
459 foreach ($rows as $key => $row) {
460 if (!($row['civicrm_membership_join_date_subtotal'] &&
461 $row['civicrm_membership_membership_type_id']
466 if ($isMembershipType) {
467 $join_date = CRM_Utils_Array
::value('civicrm_membership_join_date_start', $row);
468 $displayInterval = CRM_Utils_Array
::value('civicrm_membership_join_date_interval', $row);
470 list($year, $month) = explode('-', $join_date);
472 if (!empty($row['civicrm_membership_join_date_subtotal'])) {
474 switch ($this->_interval
) {
476 $displayRange = $displayInterval . ' ' . $year;
480 $displayRange = 'Quarter ' . $displayInterval . ' of ' . $year;
484 $displayRange = 'Week ' . $displayInterval . ' of ' . $year;
488 $displayRange = $year;
491 $membershipType = $displayRange . "-" .
492 $membershipTypeValues[$row['civicrm_membership_membership_type_id']];
496 $membershipType = $membershipTypeValues[$row['civicrm_membership_membership_type_id']];
499 $interval[$membershipType] = $membershipType;
500 $display[$membershipType] = $row['civicrm_contribution_total_amount_sum'];
503 $graphRows['receive_date'][] = CRM_Utils_Array
::value('civicrm_membership_join_date_start', $row);
504 $graphRows[$this->_interval
][] = CRM_Utils_Array
::value('civicrm_membership_join_date_interval', $row);
505 $graphRows['value'][] = $row['civicrm_contribution_total_amount_sum'];
511 if ($isMembershipType) {
512 $graphRows['value'] = $display;
514 'legend' => 'Membership Summary',
515 'xname' => 'Member Since / Member Type',
518 CRM_Utils_OpenFlashChart
::reportChart($graphRows, $this->_params
['charts'], $interval, $chartInfo);
521 CRM_Utils_OpenFlashChart
::chart($graphRows, $this->_params
['charts'], $this->_interval
);
524 $this->assign('chartType', $this->_params
['charts']);
528 * Alter display of rows.
530 * Iterate through the rows retrieved via SQL and make changes for display purposes,
531 * such as rendering contacts as links.
534 * Rows generated by SQL, with an array for each row.
536 public function alterDisplay(&$rows) {
538 foreach ($rows as $rowNum => $row) {
539 // make count columns point to detail report
540 if (!empty($this->_params
['group_bys']['join_date']) &&
541 !empty($row['civicrm_membership_join_date_start']) &&
542 $row['civicrm_membership_join_date_start'] &&
543 $row['civicrm_membership_join_date_subtotal']
546 $dateStart = CRM_Utils_Date
::customFormat($row['civicrm_membership_join_date_start'], '%Y%m%d');
547 $endDate = new DateTime($dateStart);
550 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
552 switch (strtolower($this->_params
['group_bys_freq']['join_date'])) {
554 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
1,
555 $dateEnd['d'] - 1, $dateEnd['Y']
560 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
561 $dateEnd['d'] - 1, $dateEnd['Y'] +
1
566 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
567 $dateEnd['d'] +
6, $dateEnd['Y']
572 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] +
3,
573 $dateEnd['d'] - 1, $dateEnd['Y']
578 if (!empty($this->_params
['group_bys']['membership_type_id']) &&
579 $typeID = $row['civicrm_membership_membership_type_id']
581 $typeUrl = "&tid_op=in&tid_value={$typeID}";
584 if (!empty($this->_params
['status_id_value'])) {
585 $statusUrl = "&sid_op=in&sid_value=" .
586 implode(",", $this->_params
['status_id_value']);
588 $url = CRM_Report_Utils_Report
::getNextUrl('member/detail',
589 "reset=1&force=1&join_date_from={$dateStart}&join_date_to={$dateEnd}{$typeUrl}{$statusUrl}",
590 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
592 $row['civicrm_membership_join_date_start'] = CRM_Utils_Date
::format($row['civicrm_membership_join_date_start']);
593 $rows[$rowNum]['civicrm_membership_join_date_start_link'] = $url;
594 $rows[$rowNum]['civicrm_membership_join_date_start_hover'] = ts("Lists Summary of Memberships for this date unit.");
599 // handle Membership Types
600 if (array_key_exists('civicrm_membership_membership_type_id', $row)) {
601 if ($value = $row['civicrm_membership_membership_type_id']) {
602 $value = explode(',', $value);
603 foreach ($value as $key => $id) {
604 $value[$key] = CRM_Member_PseudoConstant
::membershipType($id, FALSE);
606 $rows[$rowNum]['civicrm_membership_membership_type_id'] = implode(' , ', $value);
611 // make subtotals look nicer
612 if (array_key_exists('civicrm_membership_join_date_subtotal', $row) &&
613 !$row['civicrm_membership_join_date_subtotal']
615 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields
);
618 elseif (array_key_exists('civicrm_membership_join_date_subtotal', $row) &&
619 $row['civicrm_membership_join_date_subtotal'] &&
620 !$row['civicrm_membership_membership_type_id']
622 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields
, FALSE);
623 $rows[$rowNum]['civicrm_membership_membership_type_id'] = '<b>SubTotal</b>';
627 // If using campaigns, convert campaign_id to campaign title
628 if (array_key_exists('civicrm_membership_campaign_id', $row)) {
629 if ($value = $row['civicrm_membership_campaign_id']) {
630 $rows[$rowNum]['civicrm_membership_campaign_id'] = $this->activeCampaigns
[$value];
635 // skip looking further in rows, if first row itself doesn't
636 // have the column we need