CRM-18439 - Report Fixes to include Full Group by clause
[civicrm-core.git] / CRM / Report / Form / Contribute / HouseholdSummary.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2016
32 * $Id$
33 *
34 */
35 class CRM_Report_Form_Contribute_HouseholdSummary extends CRM_Report_Form {
36
37 protected $_addressField = FALSE;
38
39 protected $_emailField = FALSE;
40
41 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
42
43 protected $_summary = NULL;
44
45 /**
46 */
47 /**
48 */
49 public function __construct() {
50 self::validRelationships();
51
52 $config = CRM_Core_Config::singleton();
53 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
54 if ($campaignEnabled) {
55 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
56 $this->activeCampaigns = $getCampaigns['campaigns'];
57 asort($this->activeCampaigns);
58 }
59
60 $this->_columns = array(
61 'civicrm_contact_household' => array(
62 'dao' => 'CRM_Contact_DAO_Contact',
63 'fields' => array(
64 'household_name' => array(
65 'title' => ts('Household Name'),
66 'required' => TRUE,
67 ),
68 'id' => array(
69 'no_display' => TRUE,
70 'required' => TRUE,
71 ),
72 'contact_type' => array(
73 'title' => ts('Contact Type'),
74 ),
75 'contact_sub_type' => array(
76 'title' => ts('Contact Subtype'),
77 ),
78 ),
79 'filters' => array(
80 'household_name' => array('title' => ts('Household Name')),
81 ),
82 'grouping' => 'household-fields',
83 ),
84 'civicrm_line_item' => array(
85 'dao' => 'CRM_Price_DAO_LineItem',
86 ),
87 'civicrm_relationship' => array(
88 'dao' => 'CRM_Contact_DAO_Relationship',
89 'fields' => array(
90 'relationship_type_id' => array(
91 'title' => ts('Relationship Type'),
92 ),
93 ),
94 'filters' => array(
95 'relationship_type_id' => array(
96 'title' => ts('Relationship Type'),
97 'type' => CRM_Utils_Type::T_INT,
98 'operatorType' => CRM_Report_Form::OP_SELECT,
99 'options' => $this->relationTypes,
100 'default' => key($this->relationTypes),
101 ),
102 ),
103 'grouping' => 'household-fields',
104 ),
105 'civicrm_contact' => array(
106 'dao' => 'CRM_Contact_DAO_Contact',
107 'fields' => array(
108 'sort_name' => array(
109 'title' => ts('Contact Name'),
110 'required' => TRUE,
111 ),
112 'id' => array(
113 'no_display' => TRUE,
114 'required' => TRUE,
115 ),
116 ),
117 'grouping' => 'contact-fields',
118 ),
119 'civicrm_contribution' => array(
120 'dao' => 'CRM_Contribute_DAO_Contribution',
121 'fields' => array(
122 'total_amount' => array(
123 'title' => ts('Amount'),
124 'required' => TRUE,
125 ),
126 'id' => array(
127 'no_display' => TRUE,
128 'required' => TRUE,
129 ),
130 'contribution_status_id' => array(
131 'title' => 'Contribution Status',
132 'default' => TRUE,
133 ),
134 'check_number' => array(
135 'title' => ts('Check Number'),
136 ),
137 'currency' => array(
138 'required' => TRUE,
139 'no_display' => TRUE,
140 ),
141 'trxn_id' => NULL,
142 'receive_date' => array('default' => TRUE),
143 'receipt_date' => NULL,
144 ),
145 'filters' => array(
146 'receive_date' => array('operatorType' => CRM_Report_Form::OP_DATE),
147 'total_amount' => array('title' => ts('Amount Between')),
148 'currency' => array(
149 'title' => 'Currency',
150 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
151 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
152 'default' => NULL,
153 'type' => CRM_Utils_Type::T_STRING,
154 ),
155 'contribution_status_id' => array(
156 'title' => ts('Contribution Status'),
157 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
158 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
159 'default' => array(1),
160 ),
161 ),
162 'grouping' => 'contri-fields',
163 ),
164 'civicrm_address' => array(
165 'dao' => 'CRM_Core_DAO_Address',
166 'fields' => array(
167 'street_address' => NULL,
168 'city' => NULL,
169 'postal_code' => NULL,
170 'state_province_id' => array(
171 'title' => ts('State/Province'),
172 ),
173 'country_id' => array(
174 'title' => ts('Country'),
175 ),
176 ),
177 'grouping' => 'contact-fields',
178 ),
179 'civicrm_email' => array(
180 'dao' => 'CRM_Core_DAO_Email',
181 'fields' => array(
182 'email' => NULL,
183 ),
184 'grouping' => 'contact-fields',
185 ),
186 );
187
188 if ($campaignEnabled && !empty($this->activeCampaigns)) {
189 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
190 'title' => 'Campaign',
191 'default' => 'false',
192 );
193 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
194 'title' => ts('Campaign'),
195 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
196 'options' => $this->activeCampaigns,
197 'type' => CRM_Utils_Type::T_INT,
198 );
199 }
200 $this->_currencyColumn = 'civicrm_contribution_currency';
201 parent::__construct();
202 }
203
204 public function preProcess() {
205 parent::preProcess();
206 }
207
208 public function select() {
209 $this->_columnHeaders = $select = array();
210 foreach ($this->_columns as $tableName => $table) {
211 if (array_key_exists('fields', $table)) {
212 foreach ($table['fields'] as $fieldName => $field) {
213 if (!empty($field['required']) ||
214 !empty($this->_params['fields'][$fieldName])
215 ) {
216 if ($tableName == 'civicrm_address') {
217 $this->_addressField = TRUE;
218 }
219 elseif ($tableName == 'civicrm_email') {
220 $this->_emailField = TRUE;
221 }
222
223 if (!empty($field['statistics'])) {
224 foreach ($field['statistics'] as $stat => $label) {
225 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}_{$stat}";
226 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
227 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
228 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
229 }
230 }
231 else {
232 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
233
234 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
235 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
236 }
237 }
238 }
239 }
240 }
241 $this->_selectClauses = $select;
242 $this->_select = "SELECT " . implode(', ', $select) . " ";
243 }
244
245 public function from() {
246
247 $this->_from = NULL;
248 $this->_from = "
249 FROM civicrm_relationship {$this->_aliases['civicrm_relationship']}
250 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact_household']} ON
251 ({$this->_aliases['civicrm_contact_household']}.id = {$this->_aliases['civicrm_relationship']}.$this->householdContact AND {$this->_aliases['civicrm_contact_household']}.contact_type='Household')
252 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']} ON
253 ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_relationship']}.$this->otherContact )
254 {$this->_aclFrom}
255 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']} ON
256 ({$this->_aliases['civicrm_contribution']}.contact_id = {$this->_aliases['civicrm_relationship']}.$this->otherContact ) AND {$this->_aliases['civicrm_contribution']}.is_test = 0 ";
257
258 if ($this->_addressField) {
259 $this->_from .= "
260 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']} ON
261 {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
262 {$this->_aliases['civicrm_address']}.is_primary = 1\n ";
263 }
264 if ($this->_emailField) {
265 $this->_from .= "
266 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']} ON
267 {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
268 {$this->_aliases['civicrm_email']}.is_primary = 1\n ";
269 }
270 $this->getPermissionedFTQuery($this);
271 }
272
273 public function where() {
274 $clauses = array();
275 foreach ($this->_columns as $tableName => $table) {
276 if (array_key_exists('filters', $table)) {
277 foreach ($table['filters'] as $fieldName => $field) {
278 $clause = NULL;
279 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
280 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
281 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
282 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
283 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
284 }
285 else {
286 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
287 if ($op) {
288 if ($fieldName == 'relationship_type_id') {
289 $clause = "{$this->_aliases['civicrm_relationship']}.relationship_type_id=" . $this->relationshipId;
290 }
291 else {
292 $clause = $this->whereClause($field,
293 $op,
294 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
295 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
296 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
297 );
298 }
299 }
300 }
301
302 if (!empty($clause)) {
303 $clauses[] = $clause;
304 }
305 }
306 }
307 }
308
309 if (empty($clauses)) {
310 $this->_where = "WHERE ( 1 )";
311 }
312 else {
313 $this->_where = "WHERE " . implode(' AND ', $clauses);
314 }
315
316 if ($this->_aclWhere) {
317 $this->_where .= " AND {$this->_aclWhere} ";
318 }
319 }
320
321 public function groupBy() {
322 $groupBy = array(
323 "{$this->_aliases['civicrm_relationship']}.$this->householdContact",
324 "{$this->_aliases['civicrm_relationship']}.$this->otherContact",
325 "{$this->_aliases['civicrm_contribution']}.id",
326 "{$this->_aliases['civicrm_relationship']}.relationship_type_id",
327 );
328 $this->_groupBy = " GROUP BY {$this->_aliases['civicrm_relationship']}.$this->householdContact, {$this->_aliases['civicrm_relationship']}.$this->otherContact , {$this->_aliases['civicrm_contribution']}.id, {$this->_aliases['civicrm_relationship']}.relationship_type_id ";
329 $this->_groupBy .= CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, $groupBy);
330 }
331
332 public function orderBy() {
333 $this->_orderBy = " ORDER BY {$this->_aliases['civicrm_contact_household']}.household_name, {$this->_aliases['civicrm_relationship']}.$this->householdContact, {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_relationship']}.$this->otherContact";
334 }
335
336 /**
337 * @param $rows
338 *
339 * @return array
340 */
341 public function statistics(&$rows) {
342 $statistics = parent::statistics($rows);
343
344 //hack filter display for relationship type
345 $type = substr($this->_params['relationship_type_id_value'], -3);
346 foreach ($statistics['filters'] as $id => $value) {
347 if (
348 $value['title'] == 'Relationship Type' &&
349 isset($this->relationTypes[$this->relationshipId . '_' . $type])
350 ) {
351 $statistics['filters'][$id]['value'] = 'Is equal to ' .
352 $this->relationTypes[$this->relationshipId . '_' . $type];
353 }
354 }
355 return $statistics;
356 }
357
358 public function postProcess() {
359
360 $this->beginPostProcess();
361 $this->buildACLClause(array(
362 $this->_aliases['civicrm_contact'],
363 $this->_aliases['civicrm_contact_household'],
364 ));
365 $sql = $this->buildQuery(TRUE);
366 $rows = array();
367
368 $this->buildRows($sql, $rows);
369 $this->formatDisplay($rows);
370 $this->doTemplateAssignment($rows);
371 $this->endPostProcess($rows);
372 }
373
374 /**
375 * Set variables to be accessed by API and form layer in processing.
376 */
377 public function beginPostProcessCommon() {
378 $getRelationship = $this->_params['relationship_type_id_value'];
379 $type = substr($getRelationship, -3);
380 $this->relationshipId = intval((substr($getRelationship, 0, strpos($getRelationship, '_'))));
381 if ($type == 'b_a') {
382 $this->householdContact = 'contact_id_b';
383 $this->otherContact = 'contact_id_a';
384 }
385 else {
386 $this->householdContact = 'contact_id_a';
387 $this->otherContact = 'contact_id_b';
388 }
389 }
390
391 public function validRelationships() {
392 $this->relationTypes = $relationTypes = array();
393
394 $params = array('contact_type_b' => 'Household', 'version' => 3);
395 $typesA = civicrm_api('relationship_type', 'get', $params);
396 if (empty($typesA['is_error'])) {
397 foreach ($typesA['values'] as $rel) {
398 $relationTypes[$rel['id']][$rel['id'] . '_b_a'] = $rel['label_b_a'];
399 }
400 }
401 $params = array('contact_type_a' => 'Household', 'version' => 3);
402 $typesB = civicrm_api('relationship_type', 'get', $params);
403 if (empty($typesB['is_error'])) {
404 foreach ($typesB['values'] as $rel) {
405 $relationTypes[$rel['id']][$rel['id'] . '_a_b'] = $rel['label_a_b'];
406 //$this->relationTypes[$rel['id'].'_a_b'] = $rel['label_a_b'];
407 }
408 }
409
410 ksort($relationTypes);
411 foreach ($relationTypes as $relationship) {
412 foreach ($relationship as $index => $label) {
413 $this->relationTypes[$index] = $label;
414 }
415 }
416 }
417
418 /**
419 * Alter display of rows.
420 *
421 * Iterate through the rows retrieved via SQL and make changes for display purposes,
422 * such as rendering contacts as links.
423 *
424 * @param array $rows
425 * Rows generated by SQL, with an array for each row.
426 */
427 public function alterDisplay(&$rows) {
428 $type = substr($this->_params['relationship_type_id_value'], -3);
429
430 $entryFound = FALSE;
431 $flagHousehold = $flagContact = 0;
432 foreach ($rows as $rowNum => $row) {
433
434 //replace retionship id by relationship name
435 if (array_key_exists('civicrm_relationship_relationship_type_id', $row)) {
436 if ($value = $row['civicrm_relationship_relationship_type_id']) {
437 $rows[$rowNum]['civicrm_relationship_relationship_type_id'] = $this->relationTypes[$value . '_' . $type];
438 $entryFound = TRUE;
439 }
440 }
441
442 //remove duplicate Organization names
443 if (array_key_exists('civicrm_contact_household_household_name', $row) &&
444 $this->_outputMode != 'csv'
445 ) {
446 if ($value = $row['civicrm_contact_household_household_name']) {
447 if ($rowNum == 0) {
448 $priviousHousehold = $value;
449 }
450 else {
451 if ($priviousHousehold == $value) {
452 $flagHousehold = 1;
453 $priviousHousehold = $value;
454 }
455 else {
456 $flagHousehold = 0;
457 $priviousHousehold = $value;
458 }
459 }
460
461 if ($flagHousehold == 1) {
462 $rows[$rowNum]['civicrm_contact_household_household_name'] = "";
463 }
464 else {
465 $url = CRM_Utils_System::url('civicrm/contact/view',
466 'reset=1&cid=' . $rows[$rowNum]['civicrm_contact_household_id'],
467 $this->_absoluteUrl
468 );
469
470 $rows[$rowNum]['civicrm_contact_household_household_name'] = "<a href='$url' title='" . ts('View contact summary for this househould') . "'>" . $value . '</a>';
471 }
472 $entryFound = TRUE;
473 }
474 }
475
476 //remove duplicate Contact names and relationship type
477 if (array_key_exists('civicrm_contact_id', $row) &&
478 $this->_outputMode != 'csv'
479 ) {
480 if ($value = $row['civicrm_contact_id']) {
481 if ($rowNum == 0) {
482 $priviousContact = $value;
483 }
484 else {
485 if ($priviousContact == $value) {
486 $flagContact = 1;
487 $priviousContact = $value;
488 }
489 else {
490 $flagContact = 0;
491 $priviousContact = $value;
492 }
493 }
494
495 if ($flagContact == 1 && $flagHousehold == 1) {
496 $rows[$rowNum]['civicrm_contact_sort_name'] = "";
497 $rows[$rowNum]['civicrm_relationship_relationship_type_id'] = "";
498 }
499
500 $entryFound = TRUE;
501 }
502 }
503
504 if (array_key_exists('civicrm_contribution_contribution_status_id', $row)) {
505 if ($value = $row['civicrm_contribution_contribution_status_id']) {
506 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = CRM_Contribute_PseudoConstant::contributionStatus($value);
507 }
508 }
509
510 // handle state province
511 if (array_key_exists('civicrm_address_state_province_id', $row)) {
512 if ($value = $row['civicrm_address_state_province_id']) {
513 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value, FALSE);
514 }
515 $entryFound = TRUE;
516 }
517
518 // handle country
519 if (array_key_exists('civicrm_address_country_id', $row)) {
520 if ($value = $row['civicrm_address_country_id']) {
521 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
522 }
523 $entryFound = TRUE;
524 }
525
526 // convert display name to links
527 if (array_key_exists('civicrm_contact_sort_name', $row) &&
528 $rows[$rowNum]['civicrm_contact_sort_name'] &&
529 array_key_exists('civicrm_contact_id', $row)
530 ) {
531 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
532 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
533 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
534 );
535 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
536 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts('View contribution details for this individual');
537
538 $entryFound = TRUE;
539 }
540
541 if (!empty($row['civicrm_contribution_total_amount'])) {
542 $row['civicrm_contribution_total_amount'] = CRM_Utils_Money::format($row['civicrm_contribution_total_amount'], $row['civicrm_contribution_currency']);
543 }
544
545 // Contribution amount links to view contribution
546 if (($value = CRM_Utils_Array::value('civicrm_contribution_total_amount', $row)) &&
547 CRM_Core_Permission::check('access CiviContribute')
548 ) {
549 $url = CRM_Utils_System::url("civicrm/contact/view/contribution",
550 "reset=1&id=" . $row['civicrm_contribution_id'] . "&cid=" .
551 $row['civicrm_contact_id'] .
552 "&action=view&context=contribution&selectedChild=contribute",
553 $this->_absoluteUrl
554 );
555 $rows[$rowNum]['civicrm_contribution_total_amount_link'] = $url;
556 $rows[$rowNum]['civicrm_contribution_total_amount_hover'] = ts("View this contribution.");
557 $entryFound = TRUE;
558 }
559
560 // convert campaign_id to campaign title
561 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
562 if ($value = $row['civicrm_contribution_campaign_id']) {
563 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
564 $entryFound = TRUE;
565 }
566 }
567
568 // skip looking further in rows, if first row itself doesn't
569 if (!$entryFound) {
570 break;
571 }
572 $lastKey = $rowNum;
573 }
574 }
575
576 }