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