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