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