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