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