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