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