Merge pull request #18063 from civicrm/5.28
[civicrm-core.git] / CRM / Contribute / Selector / Search.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 * @package CRM
14 * @copyright CiviCRM LLC https://civicrm.org/licensing
15 */
16
17 /**
18 * Class to render contribution search results.
19 */
20 class CRM_Contribute_Selector_Search extends CRM_Core_Selector_Base implements CRM_Core_Selector_API {
21
22 /**
23 * Array of action links.
24 *
25 * @var array
26 */
27 public static $_links = NULL;
28
29 /**
30 * We use desc to remind us what that column is, name is used in the tpl
31 *
32 * @var array
33 */
34 public static $_columnHeaders;
35
36 /**
37 * Properties of contact we're interested in displaying
38 * @var array
39 */
40 public static $_properties = [
41 'contact_id',
42 'contribution_id',
43 'contact_type',
44 'sort_name',
45 'amount_level',
46 'total_amount',
47 'financial_type',
48 'contribution_source',
49 'receive_date',
50 'thankyou_date',
51 'contribution_status_id',
52 'contribution_status',
53 'contribution_cancel_date',
54 'product_name',
55 'is_test',
56 'contribution_recur_id',
57 'receipt_date',
58 'membership_id',
59 'currency',
60 'contribution_campaign_id',
61 'contribution_soft_credit_name',
62 'contribution_soft_credit_contact_id',
63 'contribution_soft_credit_amount',
64 'contribution_soft_credit_type',
65 ];
66
67 /**
68 * Are we restricting ourselves to a single contact
69 *
70 * @var bool
71 */
72 protected $_single = FALSE;
73
74 /**
75 * Are we restricting ourselves to a single contact
76 *
77 * @var bool
78 */
79 protected $_limit = NULL;
80
81 /**
82 * What context are we being invoked from
83 *
84 * @var string
85 */
86 protected $_context = NULL;
87
88 /**
89 * What component context are we being invoked from
90 *
91 * @var string
92 */
93 protected $_compContext = NULL;
94
95 /**
96 * QueryParams is the array returned by exportValues called on
97 * the HTML_QuickForm_Controller for that page.
98 *
99 * @var array
100 */
101 public $_queryParams;
102
103 /**
104 * Represent the type of selector
105 *
106 * @var int
107 */
108 protected $_action;
109
110 /**
111 * The additional clause that we restrict the search with
112 *
113 * @var string
114 */
115 protected $_contributionClause = NULL;
116
117 /**
118 * The query object
119 *
120 * @var string
121 */
122 protected $_query;
123
124 protected $_includeSoftCredits = FALSE;
125
126 /**
127 * Class constructor.
128 *
129 * @param array $queryParams
130 * Array of parameters for query.
131 * @param \const|int $action - action of search basic or advanced.
132 * @param string $contributionClause
133 * If the caller wants to further restrict the search (used in contributions).
134 * @param bool $single
135 * Are we dealing only with one contact?.
136 * @param int $limit
137 * How many contributions do we want returned.
138 *
139 * @param string $context
140 * @param null $compContext
141 *
142 * @return \CRM_Contribute_Selector_Search
143 */
144 public function __construct(
145 &$queryParams,
146 $action = CRM_Core_Action::NONE,
147 $contributionClause = NULL,
148 $single = FALSE,
149 $limit = NULL,
150 $context = 'search',
151 $compContext = NULL
152 ) {
153
154 // submitted form values
155 $this->_queryParams = &$queryParams;
156
157 $this->_single = $single;
158 $this->_limit = $limit;
159 $this->_context = $context;
160 $this->_compContext = $compContext;
161
162 $this->_contributionClause = $contributionClause;
163
164 // type of selector
165 $this->_action = $action;
166 $returnProperties = CRM_Contribute_BAO_Query::selectorReturnProperties($this->_queryParams);
167 $this->_includeSoftCredits = CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled($this->_queryParams);
168 $this->_queryParams[] = ['contribution_id', '!=', 0, 0, 0];
169 $this->_query = new CRM_Contact_BAO_Query(
170 $this->_queryParams,
171 $returnProperties,
172 NULL, FALSE, FALSE,
173 CRM_Contact_BAO_Query::MODE_CONTRIBUTE
174 );
175 // @todo the function CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled should handle this
176 // can we remove? if not why not?
177 if ($this->_includeSoftCredits) {
178 $this->_query->_rowCountClause = " count(civicrm_contribution.id)";
179 $this->_query->_groupByComponentClause = " GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.contact_id, contribution_search_scredit_combined.scredit_id ";
180 }
181 else {
182 $this->_query->_distinctComponentClause = " civicrm_contribution.id";
183 $this->_query->_groupByComponentClause = " GROUP BY civicrm_contribution.id ";
184 }
185 }
186
187 /**
188 * This method returns the links that are given for each search row.
189 * currently the links added for each row are
190 *
191 * - View
192 * - Edit
193 *
194 * @param int $componentId
195 * @param null $componentAction
196 * @param null $key
197 * @param null $compContext
198 *
199 * @return array
200 */
201 public static function &links($componentId = NULL, $componentAction = NULL, $key = NULL, $compContext = NULL) {
202 $extraParams = NULL;
203 if ($componentId) {
204 $extraParams = "&compId={$componentId}&compAction={$componentAction}";
205 }
206 if ($compContext) {
207 $extraParams .= "&compContext={$compContext}";
208 }
209 if ($key) {
210 $extraParams .= "&key={$key}";
211 }
212
213 if (!(self::$_links)) {
214 self::$_links = [
215 CRM_Core_Action::VIEW => [
216 'name' => ts('View'),
217 'url' => 'civicrm/contact/view/contribution',
218 'qs' => "reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=contribute{$extraParams}",
219 'title' => ts('View Contribution'),
220 ],
221 CRM_Core_Action::UPDATE => [
222 'name' => ts('Edit'),
223 'url' => 'civicrm/contact/view/contribution',
224 'qs' => "reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}",
225 'title' => ts('Edit Contribution'),
226 ],
227 CRM_Core_Action::DELETE => [
228 'name' => ts('Delete'),
229 'url' => 'civicrm/contact/view/contribution',
230 'qs' => "reset=1&action=delete&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}",
231 'title' => ts('Delete Contribution'),
232 ],
233 ];
234 }
235 return self::$_links;
236 }
237
238 /**
239 * Getter for array of the parameters required for creating pager.
240 *
241 * @param $action
242 * @param array $params
243 */
244 public function getPagerParams($action, &$params) {
245 $params['status'] = ts('Contribution') . ' %%StatusMessage%%';
246 $params['csvString'] = NULL;
247 if ($this->_limit) {
248 $params['rowCount'] = $this->_limit;
249 }
250 else {
251 $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
252 }
253
254 $params['buttonTop'] = 'PagerTopButton';
255 $params['buttonBottom'] = 'PagerBottomButton';
256 }
257
258 /**
259 * Returns total number of rows for the query.
260 *
261 * @param string $action
262 *
263 * @return int
264 * Total number of rows
265 */
266 public function getTotalCount($action) {
267 return $this->_query->searchQuery(0, 0, NULL,
268 TRUE, FALSE,
269 FALSE, FALSE,
270 FALSE,
271 $this->_contributionClause
272 );
273 }
274
275 /**
276 * Returns all the rows in the given offset and rowCount.
277 *
278 * @param string $action
279 * The action being performed.
280 * @param int $offset
281 * The row number to start from.
282 * @param int $rowCount
283 * The number of rows to return.
284 * @param string $sort
285 * The sql string that describes the sort order.
286 * @param string $output
287 * What should the result set include (web/email/csv).
288 *
289 * @return int
290 * the total number of rows for this action
291 */
292 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
293 if ($this->_includeSoftCredits) {
294 // especial sort order when rows include soft credits
295 $sort = $sort->orderBy() . ", civicrm_contribution.id, civicrm_contribution_soft.id";
296 }
297 $result = $this->_query->searchQuery($offset, $rowCount, $sort,
298 FALSE, FALSE,
299 FALSE, FALSE,
300 FALSE,
301 $this->_contributionClause
302 );
303 // process the result of the query
304 $rows = [];
305
306 //CRM-4418 check for view/edit/delete
307 $permissions = [CRM_Core_Permission::VIEW];
308 if (CRM_Core_Permission::check('edit contributions')) {
309 $permissions[] = CRM_Core_Permission::EDIT;
310 }
311 if (CRM_Core_Permission::check('delete in CiviContribute')) {
312 $permissions[] = CRM_Core_Permission::DELETE;
313 }
314 $mask = CRM_Core_Action::mask($permissions);
315
316 $qfKey = $this->_key;
317 $componentId = $componentContext = NULL;
318 if ($this->_context != 'contribute') {
319 // @todo explain the significance of context & why we do not get these i that context.
320 $qfKey = CRM_Utils_Request::retrieve('key', 'String');
321 $componentId = CRM_Utils_Request::retrieve('id', 'Positive');
322 $componentAction = CRM_Utils_Request::retrieve('action', 'String');
323 $componentContext = CRM_Utils_Request::retrieve('compContext', 'String');
324
325 if (!$componentContext &&
326 $this->_compContext
327 ) {
328 // @todo explain when this condition might occur.
329 $componentContext = $this->_compContext;
330 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', CRM_Core_DAO::$_nullObject, NULL, FALSE, 'REQUEST');
331 }
332 // CRM-17628 for some reason qfKey is not always set when searching from contribution search.
333 // as a result if the edit link is opened using right-click + open in new tab
334 // then the browser is not returned to the search results on save.
335 // This is an effort to getting the qfKey without, sadly, understanding the intent of those who came before me.
336 if (empty($qfKey)) {
337 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', CRM_Core_DAO::$_nullObject, NULL, FALSE, 'REQUEST');
338 }
339 }
340
341 // get all contribution status
342 $contributionStatuses = CRM_Core_OptionGroup::values('contribution_status',
343 FALSE, FALSE, FALSE, NULL, 'name', FALSE
344 );
345
346 //get all campaigns.
347 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
348
349 while ($result->fetch()) {
350 $this->_query->convertToPseudoNames($result);
351 $links = self::links($componentId,
352 $componentAction,
353 $qfKey,
354 $componentContext
355 );
356 $checkLineItem = FALSE;
357 $row = [];
358 // Now check for lineItems
359 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
360 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($result->id);
361 foreach ($lineItems as $items) {
362 if (!CRM_Core_Permission::check('view contributions of type ' . CRM_Contribute_PseudoConstant::financialType($items['financial_type_id']))) {
363 $checkLineItem = TRUE;
364 break;
365 }
366 if (!CRM_Core_Permission::check('edit contributions of type ' . CRM_Contribute_PseudoConstant::financialType($items['financial_type_id']))) {
367 unset($links[CRM_Core_Action::UPDATE]);
368 }
369 if (!CRM_Core_Permission::check('delete contributions of type ' . CRM_Contribute_PseudoConstant::financialType($items['financial_type_id']))) {
370 unset($links[CRM_Core_Action::DELETE]);
371 }
372 }
373 if ($checkLineItem) {
374 continue;
375 }
376 if (!CRM_Core_Permission::check('edit contributions of type ' . CRM_Contribute_PseudoConstant::financialType($result->financial_type_id))) {
377 unset($links[CRM_Core_Action::UPDATE]);
378 }
379 if (!CRM_Core_Permission::check('delete contributions of type ' . CRM_Contribute_PseudoConstant::financialType($result->financial_type_id))) {
380 unset($links[CRM_Core_Action::DELETE]);
381 }
382 }
383 // the columns we are interested in
384 foreach (self::$_properties as $property) {
385 if (property_exists($result, $property)) {
386 $row[$property] = $result->$property;
387 }
388 }
389
390 //carry campaign on selectors.
391 // @todo - I can't find any evidence that 'carrying' the campaign on selectors actually
392 // results in it being displayed anywhere so why do we do this???
393 $row['campaign'] = $allCampaigns[$result->contribution_campaign_id] ?? NULL;
394 $row['campaign_id'] = $result->contribution_campaign_id;
395
396 // add contribution status name
397 $row['contribution_status_name'] = CRM_Utils_Array::value($row['contribution_status_id'],
398 $contributionStatuses
399 );
400
401 $isPayLater = FALSE;
402 if ($result->is_pay_later && CRM_Utils_Array::value('contribution_status_name', $row) == 'Pending') {
403 $isPayLater = TRUE;
404 $row['contribution_status'] .= ' (' . ts('Pay Later') . ')';
405 $links[CRM_Core_Action::ADD] = [
406 'name' => ts('Pay with Credit Card'),
407 'url' => 'civicrm/contact/view/contribution',
408 'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%&mode=live',
409 'title' => ts('Pay with Credit Card'),
410 ];
411 }
412 elseif (CRM_Utils_Array::value('contribution_status_name', $row) == 'Pending') {
413 $row['contribution_status'] .= ' (' . ts('Incomplete Transaction') . ')';
414 }
415
416 if ($row['is_test']) {
417 $row['financial_type'] = $row['financial_type'] . ' (' . ts('test') . ')';
418 }
419
420 $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contribution_id;
421
422 $actions = [
423 'id' => $result->contribution_id,
424 'cid' => $result->contact_id,
425 'cxt' => $this->_context,
426 ];
427
428 if (in_array($row['contribution_status_name'], ['Partially paid', 'Pending refund']) || $isPayLater) {
429 $buttonName = ts('Record Payment');
430 if ($row['contribution_status_name'] == 'Pending refund') {
431 $buttonName = ts('Record Refund');
432 }
433 elseif (CRM_Core_Config::isEnabledBackOfficeCreditCardPayments()) {
434 $links[CRM_Core_Action::BASIC] = [
435 'name' => ts('Submit Credit Card payment'),
436 'url' => 'civicrm/payment/add',
437 'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=contribution&mode=live',
438 'title' => ts('Submit Credit Card payment'),
439 ];
440 }
441 $links[CRM_Core_Action::ADD] = [
442 'name' => $buttonName,
443 'url' => 'civicrm/payment',
444 'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=contribution',
445 'title' => $buttonName,
446 ];
447 }
448
449 $row['action'] = CRM_Core_Action::formLink(
450 $links,
451 $mask, $actions,
452 ts('more'),
453 FALSE,
454 'contribution.selector.row',
455 'Contribution',
456 $result->contribution_id
457 );
458
459 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id
460 );
461
462 if (!empty($row['amount_level'])) {
463 CRM_Event_BAO_Participant::fixEventLevel($row['amount_level']);
464 }
465
466 $rows[] = $row;
467 }
468
469 return $rows;
470 }
471
472 /**
473 * @inheritDoc
474 */
475 public function getQILL() {
476 return $this->_query->qill();
477 }
478
479 /**
480 * Returns the column headers as an array of tuples:
481 * (name, sortName (key to the sort array))
482 *
483 * @param string $action
484 * The action being performed.
485 * @param string $output
486 * What should the result set include (web/email/csv).
487 *
488 * @return array
489 * the column headers that need to be displayed
490 */
491 public function &getColumnHeaders($action = NULL, $output = NULL) {
492 $pre = [];
493 self::$_columnHeaders = [
494 [
495 'name' => $this->_includeSoftCredits ? ts('Contribution Amount') : ts('Amount'),
496 'sort' => 'total_amount',
497 'direction' => CRM_Utils_Sort::DONTCARE,
498 'field_name' => 'total_amount',
499 ],
500 ];
501 if ($this->_includeSoftCredits) {
502 self::$_columnHeaders
503 = array_merge(
504 self::$_columnHeaders,
505 [
506 [
507 'name' => ts('Soft Credit Amount'),
508 'sort' => 'contribution_soft_credit_amount',
509 'field_name' => 'contribution_soft_credit_amount',
510 'direction' => CRM_Utils_Sort::DONTCARE,
511 ],
512 ]
513 );
514 }
515 self::$_columnHeaders
516 = array_merge(
517 self::$_columnHeaders,
518 [
519 [
520 'name' => ts('Type'),
521 'sort' => 'financial_type',
522 'field_name' => 'financial_type',
523 'direction' => CRM_Utils_Sort::DONTCARE,
524 ],
525 [
526 'name' => ts('Source'),
527 'sort' => 'contribution_source',
528 'field_name' => 'contribution_source',
529 'direction' => CRM_Utils_Sort::DONTCARE,
530 ],
531 [
532 'name' => ts('Received'),
533 'sort' => 'receive_date',
534 'field_name' => 'receive_date',
535 'type' => 'date',
536 'direction' => CRM_Utils_Sort::DESCENDING,
537 ],
538 [
539 'name' => ts('Thank-you Sent'),
540 'sort' => 'thankyou_date',
541 'field_name' => 'thankyou_date',
542 'type' => 'date',
543 'direction' => CRM_Utils_Sort::DONTCARE,
544 ],
545 [
546 'name' => ts('Status'),
547 'sort' => 'contribution_status',
548 'field_name' => 'contribution_status',
549 'direction' => CRM_Utils_Sort::DONTCARE,
550 ],
551 ]
552 );
553 if (CRM_Contribute_BAO_Query::isSiteHasProducts()) {
554 self::$_columnHeaders[] = [
555 'name' => ts('Premium'),
556 'sort' => 'product_name',
557 'field_name' => 'product_name',
558 'direction' => CRM_Utils_Sort::DONTCARE,
559 ];
560 }
561 if (!$this->_single) {
562 $pre = [
563 [
564 'name' => ts('Name'),
565 'sort' => 'sort_name',
566 'direction' => CRM_Utils_Sort::DONTCARE,
567 ],
568 ];
569 }
570 self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
571 if ($this->_includeSoftCredits) {
572 self::$_columnHeaders = array_merge(
573 self::$_columnHeaders,
574 [
575 [
576 'name' => ts('Soft Credit For'),
577 'sort' => 'contribution_soft_credit_name',
578 'direction' => CRM_Utils_Sort::DONTCARE,
579 ],
580 [
581 'name' => ts('Soft Credit Type'),
582 'sort' => 'contribution_soft_credit_type',
583 'direction' => CRM_Utils_Sort::ASCENDING,
584 ],
585 ]
586 );
587 }
588 self::$_columnHeaders
589 = array_merge(
590 self::$_columnHeaders, [
591 ['desc' => ts('Actions'), 'type' => 'actions'],
592 ]
593 );
594 foreach (array_keys(self::$_columnHeaders) as $index) {
595 // Add weight & space it out a bit to allow headers to be inserted.
596 self::$_columnHeaders[$index]['weight'] = $index * 10;
597 }
598
599 CRM_Core_Smarty::singleton()->assign('softCreditColumns', $this->_includeSoftCredits);
600 return self::$_columnHeaders;
601 }
602
603 /**
604 * @return mixed
605 */
606 public function alphabetQuery() {
607 return $this->_query->alphabetQuery();
608 }
609
610 /**
611 * @return \CRM_Contact_BAO_Query
612 */
613 public function &getQuery() {
614 return $this->_query;
615 }
616
617 /**
618 * Name of export file.
619 *
620 * @param string $output
621 * Type of output.
622 *
623 * @return string
624 * name of the file
625 */
626 public function getExportFileName($output = 'csv') {
627 return ts('CiviCRM Contribution Search');
628 }
629
630 /**
631 * @return mixed
632 */
633 public function getSummary() {
634 return $this->_query->summaryContribution($this->_context);
635 }
636
637 }