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