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