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