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