Merge pull request #2842 from totten/master-api-rollback-soft-errors
[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 /**
47 *
48 */
49 /**
50 *
51 */
52 function __construct() {
53 self::validRelationships();
54 $config = CRM_Core_Config::singleton();
55 $campaignEnabled = in_array('CiviCampaign', $config->enableComponents);
56 if ($campaignEnabled) {
57 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
58 $this->activeCampaigns = $getCampaigns['campaigns'];
59 asort($this->activeCampaigns);
60 }
61
62 $this->_columns = array(
63 'civicrm_contact_organization' =>
64 array(
65 'dao' => 'CRM_Contact_DAO_Contact',
66 'fields' =>
67 array(
68 'organization_name' =>
69 array('title' => ts('Organization Name'),
70 'required' => TRUE,
71 'no_repeat' => 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 'organization_name' =>
90 array('title' => ts('Organization Name')),
91 ),
92 'grouping' => 'organization-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' => 'organization-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
217 $this->_currencyColumn = 'civicrm_contribution_currency';
218 parent::__construct();
219 }
220
221 function preProcess() {
222 parent::preProcess();
223 }
224
225 function select() {
226 $this->_columnHeaders = $select = array();
227 foreach ($this->_columns as $tableName => $table) {
228 if (array_key_exists('fields', $table)) {
229 foreach ($table['fields'] as $fieldName => $field) {
230 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
231 if ($tableName == 'civicrm_address') {
232 $this->_addressField = TRUE;
233 }
234 elseif ($tableName == 'civicrm_email') {
235 $this->_emailField = TRUE;
236 }
237
238 if (!empty($field['statistics'])) {
239 foreach ($field['statistics'] as $stat => $label) {
240 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}_{$stat}";
241 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
242 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
243 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
244 }
245 }
246 else {
247 $select[] = "{$table['alias']}.{$fieldName} as {$tableName}_{$fieldName}";
248
249 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
250 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
251 }
252 }
253 }
254 }
255 }
256 $this->_select = "SELECT " . implode(', ', $select) . " ";
257 }
258
259 function from() {
260
261 $this->_from = NULL;
262 $this->_from = "
263 FROM civicrm_relationship {$this->_aliases['civicrm_relationship']}
264 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact_organization']} ON
265 ({$this->_aliases['civicrm_contact_organization']}.id = {$this->_aliases['civicrm_relationship']}.$this->orgContact AND {$this->_aliases['civicrm_contact_organization']}.contact_type='Organization')
266 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']} ON
267 ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_relationship']}.$this->otherContact )
268 {$this->_aclFrom}
269 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']} ON
270 ({$this->_aliases['civicrm_contribution']}.contact_id = {$this->_aliases['civicrm_relationship']}.$this->otherContact ) AND {$this->_aliases['civicrm_contribution']}.is_test = 0 ";
271
272 if ($this->_addressField) {
273 $this->_from .= "
274 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']} ON
275 {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
276 {$this->_aliases['civicrm_address']}.is_primary = 1\n ";
277 }
278 if ($this->_emailField) {
279 $this->_from .= "
280 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']} ON
281 {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
282 {$this->_aliases['civicrm_email']}.is_primary = 1\n ";
283 }
284 }
285
286 function where() {
287 $clauses = array();
288 foreach ($this->_columns as $tableName => $table) {
289 if (array_key_exists('filters', $table)) {
290 foreach ($table['filters'] as $fieldName => $field) {
291 $clause = NULL;
292 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
293 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
294 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
295 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
296
297 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
298 }
299 else {
300 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
301 if ($op) {
302 if ($fieldName == 'relationship_type_id') {
303 $clause = "{$this->_aliases['civicrm_relationship']}.relationship_type_id=" . $this->relationshipId;
304 }
305 else {
306 $clause = $this->whereClause($field,
307 $op,
308 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
309 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
310 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
311 );
312 }
313 }
314 }
315
316 if (!empty($clause)) {
317 $clauses[] = $clause;
318 }
319 }
320 }
321 }
322
323 if (empty($clauses)) {
324 $this->_where = "WHERE ( 1 )";
325 }
326 else {
327 $this->_where = "WHERE " . implode(' AND ', $clauses);
328 }
329
330 if ($this->_aclWhere) {
331 $this->_where .= " AND {$this->_aclWhere} ";
332 }
333 }
334
335 function groupBy() {
336 $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 ";
337 }
338
339 function orderBy() {
340 $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";
341 }
342
343 /**
344 * @param $rows
345 *
346 * @return array
347 */
348 function statistics(&$rows) {
349 $statistics = parent::statistics($rows);
350
351 //hack filter display for relationship type
352 $type = substr($this->_params['relationship_type_id_value'], -3);
353 foreach ($statistics['filters'] as $id => $value) {
354 if ($value['title'] == 'Relationship Type') {
355 $statistics['filters'][$id]['value'] = 'Is equal to ' . $this->relationTypes[$this->relationshipId . '_' . $type];
356 }
357 }
358 return $statistics;
359 }
360
361 function postProcess() {
362
363 $this->beginPostProcess();
364 $getRelationship = $this->_params['relationship_type_id_value'];
365 $type = substr($getRelationship, -3);
366 $this->relationshipId = intval((substr($getRelationship, 0, strpos($getRelationship, '_'))));
367 if ($type == 'b_a') {
368 $this->orgContact = 'contact_id_b';
369 $this->otherContact = 'contact_id_a';
370 }
371 else {
372 $this->orgContact = 'contact_id_a';
373 $this->otherContact = 'contact_id_b';
374 }
375
376 $this->buildACLClause(array($this->_aliases['civicrm_contact'], $this->_aliases['civicrm_contact_organization']));
377 $sql = $this->buildQuery(TRUE);
378 $rows = array();
379
380 $this->buildRows($sql, $rows);
381 $this->formatDisplay($rows);
382 $this->doTemplateAssignment($rows);
383 $this->endPostProcess($rows);
384 }
385
386 function validRelationships() {
387 $this->relationTypes = $relationTypes = array();
388
389 $params = array('contact_type_b' => 'Organization', 'version' => 3);
390 $typesA = &civicrm_api('relationship_type', 'get', $params);
391
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
398 $params = array('contact_type_a' => 'Organization', 'version' => 3);
399 $typesB = &civicrm_api('relationship_type', 'get', $params);
400
401 if (empty($typesB['is_error'])) {
402 foreach ($typesB['values'] as $rel) {
403 $relationTypes[$rel['id']][$rel['id'] . '_a_b'] = $rel['label_a_b'];
404 }
405 }
406
407 ksort($relationTypes);
408 foreach ($relationTypes as $relationship) {
409 foreach ($relationship as $index => $label) {
410 $this->relationTypes[$index] = $label;
411 }
412 }
413 }
414
415 /**
416 * @param $rows
417 */
418 function alterDisplay(&$rows) {
419 // custom code to alter rows
420 $type = substr($this->_params['relationship_type_id_value'], -3);
421
422 $entryFound = FALSE;
423 $flagOrganization = $flagContact = 0;
424
425 foreach ($rows as $rowNum => $row) {
426
427 //replace retionship id by relationship name
428 if (array_key_exists('civicrm_relationship_relationship_type_id', $row)) {
429 if ($value = $row['civicrm_relationship_relationship_type_id']) {
430 $rows[$rowNum]['civicrm_relationship_relationship_type_id'] = $this->relationTypes[$value . '_' . $type];
431 $entryFound = TRUE;
432 }
433 }
434
435 //remove duplicate Organization names
436 if (array_key_exists('civicrm_contact_organization_id', $row) && $this->_outputMode != 'csv') {
437 if ($value = $row['civicrm_contact_organization_id']) {
438 if ($rowNum == 0) {
439 $previousOrganization = $value;
440 }
441 else {
442 if ($previousOrganization == $value) {
443 $flagOrganization = 1;
444 $previousOrganization = $value;
445 }
446 else {
447 $flagOrganization = 0;
448 $previousOrganization = $value;
449 }
450 }
451
452 if ($flagOrganization == 1) {
453 foreach ($row as $colName => $colVal) {
454 if (in_array($colName, $this->_noRepeats)) {
455 unset($rows[$rowNum][$colName]);
456 }
457 }
458 }
459 $entryFound = TRUE;
460 }
461 }
462
463 // convert Organization display name to links
464 if (array_key_exists('civicrm_contact_organization_organization_name', $row) && !empty($rows[$rowNum]
465 ['civicrm_contact_organization_organization_name']) &&
466 array_key_exists('civicrm_contact_organization_id', $row)
467 ) {
468 $url = CRM_Utils_System::url('civicrm/contact/view',
469 'reset=1&cid=' .
470 $rows[$rowNum]['civicrm_contact_organization_id'],
471 $this->_absoluteUrl
472 );
473
474 $rows[$rowNum]['civicrm_contact_organization_organization_name_link'] = $url;
475 $rows[$rowNum]['civicrm_contact_organization_organization_name_hover'] = ts('View contact summary for this organization.');
476 }
477
478 //remove duplicate Contact names and relationship type
479 if (array_key_exists('civicrm_contact_id', $row) && $this->_outputMode != 'csv') {
480 if ($value = $row['civicrm_contact_id']) {
481 if ($rowNum == 0) {
482 $previousContact = $value;
483 }
484 else {
485 if ($previousContact == $value) {
486 $flagContact = 1;
487 $previousContact = $value;
488 }
489 else {
490 $flagContact = 0;
491 $previousContact = $value;
492 }
493 }
494
495 if ($flagContact == 1 && $flagOrganization == 1) {
496 $rows[$rowNum]['civicrm_contact_sort_name'] = "";
497 $rows[$rowNum]['civicrm_relationship_relationship_type_id'] = "";
498 }
499
500 $entryFound = TRUE;
501 }
502 }
503
504 if (array_key_exists('civicrm_contribution_contribution_status_id', $row)) {
505 if ($value = $row['civicrm_contribution_contribution_status_id']) {
506 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = CRM_Contribute_PseudoConstant::contributionStatus($value);
507 }
508 }
509
510 // handle state province
511 if (array_key_exists('civicrm_address_state_province_id', $row)) {
512 if ($value = $row['civicrm_address_state_province_id']) {
513 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value, FALSE);
514 }
515 $entryFound = TRUE;
516 }
517
518 // handle country
519 if (array_key_exists('civicrm_address_country_id', $row)) {
520 if ($value = $row['civicrm_address_country_id']) {
521 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
522 }
523 $entryFound = TRUE;
524 }
525
526 // convert Individual display name to links
527 if (array_key_exists('civicrm_contact_sort_name', $row) &&
528 $rows[$rowNum]['civicrm_contact_sort_name'] &&
529 array_key_exists('civicrm_contact_id', $row)
530 ) {
531 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
532 'reset=1&force=1&id_op=eq&id_value=' .
533 $row['civicrm_contact_id'],
534 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
535 );
536 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
537 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts('View contribution details for this individual');
538
539 $entryFound = TRUE;
540 }
541
542 // Contribution amount links to view contribution
543 if (($value = CRM_Utils_Array::value('civicrm_contribution_total_amount', $row)) &&
544 CRM_Core_Permission::check('access CiviContribute')
545 ) {
546 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
547 "reset=1&id=" . $row['civicrm_contribution_id'] . "&cid=" . $row['civicrm_contact_id'] . "&action=view&context=contribution&selectedChild=contribute",
548 $this->_absoluteUrl
549 );
550 $rows[$rowNum]['civicrm_contribution_total_amount_link'] = $url;
551 $rows[$rowNum]['civicrm_contribution_total_amount_hover'] = ts('View this contribution.');
552 $entryFound = TRUE;
553 }
554
555 // convert campaign_id to campaign title
556 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
557 if ($value = $row['civicrm_contribution_campaign_id']) {
558 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
559 $entryFound = TRUE;
560 }
561 }
562
563 // skip looking further in rows, if first row itself doesn't
564 if (!$entryFound) {
565 break;
566 }
567 $lastKey = $rowNum;
568 }
569 }
570 }
571