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