Merge pull request #15070 from eileenmcnaughton/deprecation
[civicrm-core.git] / CRM / Contribute / BAO / Query.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035 32 */
86a0d21e 33class CRM_Contribute_BAO_Query extends CRM_Core_BAO_Query {
6a488035 34
1330f57a 35 public static $_contribOrSoftCredit = "only_contribs";
3dbf477c 36
1330f57a 37 public static $_contribRecurPayment = NULL;
95974e8e 38
6a488035 39 /**
8f165fa5 40 * Function get the searchable fields for contribution.
41 *
42 * This is basically the contribution fields plus some related entity fields.
6a488035 43 *
e9ff5391 44 * @param bool $checkPermission
45 *
a6c01b45 46 * @return array
e9ff5391 47 * Associative array of contribution fields
6a488035 48 */
0ed9f379 49 public static function getFields($checkPermission = TRUE) {
23faf53d 50 if (!isset(\Civi::$statics[__CLASS__]) || !isset(\Civi::$statics[__CLASS__]['fields']) || !isset(\Civi::$statics[__CLASS__]['fields']['contribution'])) {
4edbe907 51 $recurFields = CRM_Contribute_DAO_ContributionRecur::fields();
52 foreach ($recurFields as $fieldKey => $field) {
53 // We can only safely add in those with unique names as those without could clobber others.
54 // The array is keyed by unique names so if it doesn't match the key there is no unique name & we unset
55 // Refer to CRM_Contribute_Form_SearchTest for existing tests ... and to add more!
56 if ($field['name'] === $fieldKey) {
57 unset($recurFields[$fieldKey]);
58 }
59 }
23faf53d 60 $fields = array_merge($recurFields, CRM_Contribute_BAO_Contribution::exportableFields($checkPermission));
a0090e6b 61 CRM_Contribute_BAO_Contribution::appendPseudoConstantsToFields($fields);
6a488035 62 unset($fields['contribution_contact_id']);
33a766c6 63 \Civi::$statics[__CLASS__]['fields']['contribution'] = $fields;
6a488035 64 }
33a766c6 65 return \Civi::$statics[__CLASS__]['fields']['contribution'];
6a488035
TO
66 }
67
68 /**
7fe37828 69 * If contributions are involved, add the specific contribute fields.
6a488035 70 *
35e6241a 71 * @param CRM_Contact_BAO_Query $query
6a488035 72 */
00be9182 73 public static function select(&$query) {
6a488035
TO
74 // if contribute mode add contribution id
75 if ($query->_mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
76 $query->_select['contribution_id'] = "civicrm_contribution.id as contribution_id";
77 $query->_element['contribution_id'] = 1;
78 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
79 }
80
6a488035 81 // get accounting code
a7488080 82 if (!empty($query->_returnProperties['accounting_code'])) {
353ffa53 83 $query->_select['accounting_code'] = "civicrm_financial_account.accounting_code as accounting_code";
6a488035
TO
84 $query->_element['accounting_code'] = 1;
85 $query->_tables['civicrm_accounting_code'] = 1;
86 $query->_tables['civicrm_financial_account'] = 1;
87 }
39b795ba 88
a7488080 89 if (!empty($query->_returnProperties['contribution_note'])) {
6a488035
TO
90 $query->_select['contribution_note'] = "civicrm_note.note as contribution_note";
91 $query->_element['contribution_note'] = 1;
92 $query->_tables['contribution_note'] = 1;
739189e4 93 $query->_tables['civicrm_contribution'] = 1;
6a488035
TO
94 }
95
a7488080 96 if (!empty($query->_returnProperties['contribution_batch'])) {
6a488035
TO
97 $query->_select['contribution_batch'] = "civicrm_batch.title as contribution_batch";
98 $query->_element['contribution_batch'] = 1;
898bfdcd 99 $query->_tables['civicrm_financial_trxn'] = 1;
6a488035
TO
100 $query->_tables['contribution_batch'] = 1;
101 }
102
9ebd3386 103 if (!empty($query->_returnProperties['contribution_campaign_title'])) {
104 $query->_select['contribution_campaign_title'] = "civicrm_campaign.title as contribution_campaign_title";
105 $query->_element['contribution_campaign_title'] = $query->_tables['civicrm_campaign'] = 1;
106 }
739a8336 107
686df921 108 self::addSoftCreditFields($query);
6a488035
TO
109 }
110
186c9c17 111 /**
35e6241a
EM
112 * Get where clause.
113 *
114 * @param CRM_Contact_BAO_Query $query
186c9c17 115 */
00be9182 116 public static function where(&$query) {
f654cacf 117 self::initializeAnySoftCreditClause($query);
6a488035 118 foreach (array_keys($query->_params) as $id) {
a7488080 119 if (empty($query->_params[$id][0])) {
6a488035
TO
120 continue;
121 }
afa0b07c 122 if (substr($query->_params[$id][0], 0, 13) == 'contribution_' || substr($query->_params[$id][0], 0, 10) == 'financial_' || substr($query->_params[$id][0], 0, 8) == 'payment_') {
2da8c6c4 123 if ($query->_mode == CRM_Contact_BAO_Query::MODE_CONTACTS) {
6a488035
TO
124 $query->_useDistinct = TRUE;
125 }
39b795ba
DL
126 // CRM-12065
127 if (
128 $query->_params[$id][0] == 'contribution_type_id' ||
129 $query->_params[$id][0] == 'contribution_type'
130 ) {
131 CRM_Core_Session::setStatus(
132 ts('The contribution type criteria is now obsolete, please update your smart group'),
133 '',
134 'alert'
135 );
136 continue;
137 }
138
6a488035
TO
139 self::whereClauseSingle($query->_params[$id], $query);
140 }
141 }
6a488035
TO
142 }
143
186c9c17 144 /**
35e6241a
EM
145 * Get where clause for a single value.
146 *
147 * @param array $values
148 * @param CRM_Contact_BAO_Query $query
7123f88c 149 *
150 * @throws \CiviCRM_API3_Exception
151 * @throws \CRM_Core_Exception
186c9c17 152 */
00be9182 153 public static function whereClauseSingle(&$values, &$query) {
6a488035
TO
154 list($name, $op, $value, $grouping, $wildcard) = $values;
155
dbc6f6d6 156 $quoteValue = NULL;
9d5c7f14 157 $fields = self::getFields();
163b1da9
KJ
158
159 if (!empty($value) && !is_array($value)) {
6a488035
TO
160 $quoteValue = "\"$value\"";
161 }
162
e38abf14 163 // These are legacy names.
164 // @todo enotices when these are hit so we can start to elimnate them.
be2fb01f 165 $fieldAliases = [
e38abf14 166 'financial_type' => 'financial_type_id',
167 'contribution_page' => 'contribution_page_id',
168 'payment_instrument' => 'payment_instrument_id',
169 // or payment_instrument_id?
170 'contribution_payment_instrument' => 'contribution_payment_instrument_id',
171 'contribution_status' => 'contribution_status_id',
be2fb01f 172 ];
4fc150ab 173
e38abf14 174 $name = isset($fieldAliases[$name]) ? $fieldAliases[$name] : $name;
3123273f 175 $qillName = $name;
4fc150ab 176 if (in_array($name, $fieldAliases)) {
177 $qillName = array_search($name, $fieldAliases);
178 }
be2fb01f 179 $pseudoExtraParam = [];
4edbe907 180 $fieldName = str_replace(['_high', '_low'], '', $name);
181 $fieldSpec = CRM_Utils_Array::value($fieldName, $fields, []);
182 $tableName = CRM_Utils_Array::value('table_name', $fieldSpec, 'civicrm_contribution');
183 $dataType = CRM_Utils_Type::typeToString(CRM_Utils_Array::value('type', $fieldSpec));
184 if ($dataType === 'Timestamp' || $dataType === 'Date') {
1157f03f 185 $title = empty($fieldSpec['unique_title']) ? $fieldSpec['title'] : $fieldSpec['unique_title'];
4edbe907 186 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
187 $query->dateQueryBuilder($values,
1157f03f 188 $tableName, $fieldName, $fieldSpec['name'], $title
4edbe907 189 );
190 return;
191 }
3123273f 192
6a488035
TO
193 switch ($name) {
194 case 'contribution_date':
195 case 'contribution_date_low':
196 case 'contribution_date_low_time':
197 case 'contribution_date_high':
198 case 'contribution_date_high_time':
0ae18acf 199 CRM_Core_Error::deprecatedFunctionWarning('search by receive_date');
6a488035
TO
200 // process to / from date
201 $query->dateQueryBuilder($values,
70c907d4 202 'civicrm_contribution', 'contribution_date', 'receive_date', ts('Contribution Date')
6a488035
TO
203 );
204 return;
205
206 case 'contribution_amount':
207 case 'contribution_amount_low':
208 case 'contribution_amount_high':
209 // process min/max amount
210 $query->numberRangeBuilder($values,
211 'civicrm_contribution', 'contribution_amount',
212 'total_amount', 'Contribution Amount',
213 NULL
214 );
215 return;
216
6a488035
TO
217 case 'contribution_thankyou_date_is_not_null':
218 if ($value) {
219 $op = "IS NOT NULL";
220 $query->_qill[$grouping][] = ts('Contribution Thank-you Sent');
221 }
222 else {
223 $op = "IS NULL";
224 $query->_qill[$grouping][] = ts('Contribution Thank-you Not Sent');
225 }
226 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.thankyou_date", $op);
227 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
228 return;
229
230 case 'contribution_receipt_date_is_not_null':
231 if ($value) {
232 $op = "IS NOT NULL";
233 $query->_qill[$grouping][] = ts('Contribution Receipt Sent');
234 }
235 else {
236 $op = "IS NULL";
237 $query->_qill[$grouping][] = ts('Contribution Receipt Not Sent');
238 }
239 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.receipt_date", $op);
240 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
241 return;
40c655aa 242
4ca8b3e8 243 case 'financial_type_id':
b5a37491 244 case 'invoice_id':
9cad3ff4 245 case 'invoice_number':
8fb22579
PN
246 case 'payment_instrument_id':
247 case 'contribution_payment_instrument_id':
3c151c70 248 case 'contribution_page_id':
7051f2e5 249 case 'contribution_status_id':
3c151c70 250 case 'contribution_id':
251 case 'contribution_currency_type':
252 case 'contribution_currency':
253 case 'contribution_source':
3c151c70 254 case 'contribution_trxn_id':
3a6eb174 255 case 'contribution_check_number':
994567a3 256 case 'contribution_contact_id':
3c151c70 257 case (strpos($name, '_amount') !== FALSE):
6f56dc34 258 case 'contribution_campaign_id':
3123273f 259
be2fb01f 260 $fieldNamesNotToStripContributionFrom = [
93548514 261 'contribution_currency_type',
262 'contribution_status_id',
263 'contribution_page_id',
be2fb01f 264 ];
93548514 265 // @todo these are mostly legacy params. Find a better way to deal with them.
266 if (!in_array($name, $fieldNamesNotToStripContributionFrom)
3c151c70 267 ) {
3123273f 268 if (!isset($fields[$name])) {
3c151c70 269 $qillName = str_replace('contribution_', '', $qillName);
dbc6f6d6 270 }
3123273f 271 $name = str_replace('contribution_', '', $name);
5bbd985a 272 }
be2fb01f 273 if (in_array($name, ['contribution_currency', 'contribution_currency_type'])) {
3c151c70 274 $qillName = $name = 'currency';
be2fb01f 275 $pseudoExtraParam = ['labelColumn' => 'name'];
3c151c70 276 }
5bbd985a 277
3c151c70 278 $dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
279
280 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.$name", $op, $value, $dataType);
9ab34172 281 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_Contribution', $name, $value, $op, $pseudoExtraParam);
6822e118 282 if (!($name == 'id' && $value == 0)) {
be2fb01f 283 $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
6822e118 284 }
6a488035
TO
285 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
286 return;
287
6a488035 288 case 'contribution_pcp_made_through_id':
3c151c70 289 case 'contribution_soft_credit_type_id':
290 $qillName = $name;
291 if ($name == 'contribution_pcp_made_through_id') {
292 $qillName = $name = 'pcp_id';
be2fb01f 293 $fields[$name] = ['title' => ts('Personal Campaign Page'), 'type' => 2];
3c151c70 294 }
295 if ($name == 'contribution_soft_credit_type_id') {
296 $qillName = str_replace('_id', '', $qillName);
297 $fields[$qillName]['type'] = $fields[$qillName]['data_type'];
298 $name = str_replace('contribution_', '', $name);
299 }
300 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_soft.$name",
301 $op, $value, CRM_Utils_Type::typeToString($fields[$qillName]['type'])
302 );
9ab34172 303 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_ContributionSoft', $name, $value, $op);
be2fb01f 304 $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
6a488035
TO
305 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
306 return;
307
36bf52ef
DS
308 case 'contribution_or_softcredits':
309 if ($value == 'only_scredits') {
3dbf477c 310 $query->_where[$grouping][] = "contribution_search_scredit_combined.scredit_id IS NOT NULL";
36bf52ef 311 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Soft Credits Only');
ed81a415 312 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
36bf52ef 313 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
0db6c3e1 314 }
4c9b6178 315 elseif ($value == 'both_related') {
3dbf477c 316 $query->_where[$grouping][] = "contribution_search_scredit_combined.filter_id IS NOT NULL";
4f3846df 317 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Soft Credits with related Hard Credit');
ed81a415 318 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
3dbf477c 319 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
0db6c3e1 320 }
4c9b6178 321 elseif ($value == 'both') {
36bf52ef 322 $query->_qill[$grouping][] = ts('Contributions OR Soft Credits? - Both');
ed81a415 323 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
36bf52ef
DS
324 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
325 }
326 // default option: $value == 'only_contribs'
327 return;
328
6a488035 329 case 'contribution_is_test':
3a6eb174 330 // By default is Contribution Search form we choose is_test = 0 in otherwords always show active contribution
331 // so in case if any one choose any Yes/No avoid the default clause otherwise it will be conflict in whereClause
332 $key = array_search('civicrm_contribution.is_test = 0', $query->_where[$grouping]);
333 if (!empty($key)) {
334 unset($query->_where[$grouping][$key]);
335 }
6a488035 336 case 'contribution_test':
4b58de38
CW
337 // We dont want to include all tests for sql OR CRM-7827
338 if (!$value || $query->getOperator() != 'OR') {
339 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.is_test", $op, $value, "Boolean");
340 if ($value) {
341 $query->_qill[$grouping][] = ts("Only Display Test Contributions");
342 }
343 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
6a488035 344 }
6a488035
TO
345 return;
346
347 case 'contribution_is_pay_later':
348 case 'contribution_pay_later':
349 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.is_pay_later", $op, $value, "Boolean");
350 if ($value) {
351 $query->_qill[$grouping][] = ts("Find Pay Later Contributions");
352 }
353 else {
354 $query->_qill[$grouping][] = ts("Exclude Pay Later Contributions");
355 }
356 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
357 return;
358
359 case 'contribution_recurring':
360 if ($value) {
361 $query->_where[$grouping][] = "civicrm_contribution.contribution_recur_id IS NOT NULL";
362 $query->_qill[$grouping][] = ts("Find Recurring Contributions");
363 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
364 }
365 else {
366 $query->_where[$grouping][] = "civicrm_contribution.contribution_recur_id IS NULL";
367 $query->_qill[$grouping][] = ts("Exclude Recurring Contributions");
368 }
369 return;
370
371 case 'contribution_recur_id':
372 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution.contribution_recur_id",
373 $op, $value, "Integer"
374 );
375 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
376 return;
377
5951bdaa 378 case 'contribution_recur_payment_processor_id':
64127e03 379 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_recur.payment_processor_id", $op, $value, "String");
be2fb01f
CW
380 $paymentProcessors = civicrm_api3('PaymentProcessor', 'get', []);
381 $paymentProcessorNames = [];
64127e03
MWMC
382 foreach ($value as $paymentProcessorId) {
383 $paymentProcessorNames[] = $paymentProcessors['values'][$paymentProcessorId]['name'];
384 }
be2fb01f 385 $query->_qill[$grouping][] = ts("Recurring Contribution Payment Processor %1 %2", [1 => $op, 2 => implode(', ', $paymentProcessorNames)]);
64127e03
MWMC
386 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
387 return;
388
389 case 'contribution_recur_processor_id':
95974e8e 390 case 'contribution_recur_trxn_id':
23faf53d 391 $spec = $fields[$name];
392 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($spec['where'],
95974e8e
DG
393 $op, $value, "String"
394 );
23faf53d 395 $query->_qill[$grouping][] = ts("Recurring Contribution %1 %2 '%3'", [1 => $fields[$name]['title'], 2 => $op, 3 => $value]);
396 $query->_tables[$spec['table_name']] = $query->_whereTables[$spec['table_name']] = 1;
95974e8e
DG
397 return;
398
399 case 'contribution_recur_payment_made':
400 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_recur.id", 'IS NOT EMPTY');
5aae2a90 401 if ($value == 2) {
95974e8e
DG
402 $query->_qill[$grouping][] = ts("Recurring contributions with at least one payment");
403 self::$_contribRecurPayment = TRUE;
404 }
405 else {
406 $query->_qill[$grouping][] = ts("All recurring contributions regardless of payments");
407 self::$_contribRecurPayment = FALSE;
408 }
409 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
5af1389d
VH
410 return;
411
412 case 'contribution_recur_contribution_status_id':
413 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_contribution_recur.contribution_status_id", $op, $value, 'String');
414 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_ContributionRecur', 'contribution_status_id', $value, $op, $pseudoExtraParam);
be2fb01f 415 $query->_qill[$grouping][] = ts("Recurring Contribution Status %1 '%2'", [1 => $op, 2 => $value]);
5af1389d 416 $query->_tables['civicrm_contribution_recur'] = $query->_whereTables['civicrm_contribution_recur'] = 1;
95974e8e
DG
417 return;
418
6a488035 419 case 'contribution_note':
d817ca8d 420 $value = CRM_Core_DAO::escapeString($value);
6a488035
TO
421 if ($wildcard) {
422 $value = "%$value%";
423 $op = 'LIKE';
424 }
d817ca8d 425 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_note.note', $op, $value, "String");
be2fb01f 426 $query->_qill[$grouping][] = ts('Contribution Note %1 %2', [1 => $op, 2 => $quoteValue]);
6a488035
TO
427 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = $query->_whereTables['contribution_note'] = 1;
428 return;
429
430 case 'contribution_membership_id':
431 $query->_where[$grouping][] = " civicrm_membership.id $op $value";
432 $query->_tables['contribution_membership'] = $query->_whereTables['contribution_membership'] = 1;
433
434 return;
435
436 case 'contribution_participant_id':
437 $query->_where[$grouping][] = " civicrm_participant.id $op $value";
438 $query->_tables['contribution_participant'] = $query->_whereTables['contribution_participant'] = 1;
439 return;
440
441 case 'contribution_pcp_display_in_roll':
442 $query->_where[$grouping][] = " civicrm_contribution_soft.pcp_display_in_roll $op '$value'";
443 if ($value) {
444 $query->_qill[$grouping][] = ts("Personal Campaign Page Honor Roll");
445 }
446 else {
447 $query->_qill[$grouping][] = ts("NOT Personal Campaign Page Honor Roll");
448 }
449 $query->_tables['civicrm_contribution_soft'] = $query->_whereTables['civicrm_contribution_soft'] = 1;
450 return;
451
6a488035 452 case 'contribution_batch_id':
3086e282 453 list($qillOp, $qillValue) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Batch_BAO_EntityBatch', 'batch_id', $value, $op);
be2fb01f 454 $query->_qill[$grouping][] = ts('Batch Name %1 %2', [1 => $qillOp, 2 => $qillValue]);
3086e282 455 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_entity_batch.batch_id', $op, $value);
39b795ba 456 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
898bfdcd 457 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
6a488035
TO
458 $query->_tables['contribution_batch'] = $query->_whereTables['contribution_batch'] = 1;
459 return;
460
6ffab5b7
WA
461 case 'contribution_product_id':
462 // CRM-16713 - contribution search by premiums on 'Find Contribution' form.
463 $qillName = $name;
464 list($operator, $productValue) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_Product', $name, $value, $op);
be2fb01f 465 $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $operator, 3 => $productValue]);
6ffab5b7
WA
466 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_product.id", $op, $value);
467 $query->_tables['civicrm_product'] = $query->_whereTables['civicrm_product'] = 1;
468 return;
469
d42c359d
PN
470 case 'contribution_is_payment':
471 $query->_where[$grouping][] = " civicrm_financial_trxn.is_payment $op $value";
898bfdcd
PN
472 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
473 return;
474
d72b084a 475 case 'financial_trxn_card_type_id':
476 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_financial_trxn.card_type_id', $op, $value);
898bfdcd
PN
477 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
478 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
d72b084a 479 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Financial_DAO_FinancialTrxn', 'card_type_id', $value, $op);
be2fb01f 480 $query->_qill[$grouping][] = ts('Card Type %1 %2', [1 => $op, 2 => $value]);
d42c359d
PN
481 return;
482
c6ba3619
E
483 case 'financial_trxn_pan_truncation':
484 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_financial_trxn.pan_truncation', $op, $value);
485 $query->_tables['civicrm_financial_trxn'] = $query->_whereTables['civicrm_financial_trxn'] = 1;
486 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
487 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Financial_DAO_FinancialTrxn', 'pan_truncation', $value, $op);
be2fb01f 488 $query->_qill[$grouping][] = ts('Card Number %1 %2', [1 => $op, 2 => $value]);
c6ba3619
E
489 return;
490
6a488035
TO
491 default:
492 //all other elements are handle in this case
353ffa53 493 $fldName = substr($name, 13);
ec8c4582
DL
494 if (!isset($fields[$fldName])) {
495 // CRM-12597
496 CRM_Core_Session::setStatus(ts(
fb5b081b 497 'We did not recognize the search field: %1. Please check and fix your contribution related smart groups.',
be2fb01f 498 [1 => $fldName]
ec8c4582
DL
499 )
500 );
501 return;
502 }
6a488035 503 $whereTable = $fields[$fldName];
927898c5 504 if (!is_array($value)) {
505 $value = trim($value);
506 }
6a488035 507
3c151c70 508 $dataType = "String";
509 if (!empty($whereTable['type'])) {
510 $dataType = CRM_Utils_Type::typeToString($whereTable['type']);
6a488035
TO
511 }
512
2b3e31ac 513 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($whereTable['where'], $op, $value, $dataType);
6a488035 514 $query->_qill[$grouping][] = "$whereTable[title] $op $quoteValue";
2b3e31ac 515 list($tableName) = explode('.', $whereTable['where'], 2);
6a488035 516 $query->_tables[$tableName] = $query->_whereTables[$tableName] = 1;
4edbe907 517 if ($tableName === 'civicrm_contribution_product') {
6a488035
TO
518 $query->_tables['civicrm_product'] = $query->_whereTables['civicrm_product'] = 1;
519 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
520 }
521 else {
522 $query->_tables['civicrm_contribution'] = $query->_whereTables['civicrm_contribution'] = 1;
523 }
524 }
525 }
526
186c9c17 527 /**
35e6241a
EM
528 * Get from clause.
529 *
100fef9d 530 * @param string $name
35e6241a
EM
531 * @param string $mode
532 * @param string $side
186c9c17 533 *
e60f24eb 534 * @return NULL|string
186c9c17 535 */
00be9182 536 public static function from($name, $mode, $side) {
6a488035
TO
537 $from = NULL;
538 switch ($name) {
353ffa53
TO
539 case 'civicrm_contribution':
540 $from = " $side JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id ";
be2fb01f 541 if (in_array(self::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
353ffa53 542 // switch the from table if its only soft credit search
bc438a52 543 $from = " $side JOIN " . \Civi::$statics[__CLASS__]['soft_credit_temp_table_name'] . " as contribution_search_scredit_combined ON contribution_search_scredit_combined.contact_id = contact_a.id ";
353ffa53
TO
544 $from .= " $side JOIN civicrm_contribution ON civicrm_contribution.id = contribution_search_scredit_combined.id ";
545 $from .= " $side JOIN civicrm_contribution_soft ON civicrm_contribution_soft.id = contribution_search_scredit_combined.scredit_id";
546 }
547 break;
6a488035
TO
548
549 case 'civicrm_contribution_recur':
86845f9b 550 if ($mode == 1) {
95974e8e 551 // 'Made payment for the recurring contributions?' is ticked yes
1415b394 552 $from = " $side JOIN civicrm_contribution_recur ON contact_a.id = civicrm_contribution_recur.contact_id ";
24782d26 553 if (self::$_contribRecurPayment == TRUE) {
5aae2a90 554 $from .= " INNER JOIN civicrm_contribution cr ON cr.contribution_recur_id = civicrm_contribution_recur.id ";
95974e8e 555 }
86845f9b 556 }
557 else {
558 $from = " $side JOIN civicrm_contribution_recur ON civicrm_contribution.contribution_recur_id = civicrm_contribution_recur.id ";
559 }
6a488035
TO
560 break;
561
562 case 'civicrm_financial_type':
563 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
564 $from = " INNER JOIN civicrm_financial_type ON civicrm_contribution.financial_type_id = civicrm_financial_type.id ";
565 }
566 else {
567 $from = " $side JOIN civicrm_financial_type ON civicrm_contribution.financial_type_id = civicrm_financial_type.id ";
568 }
569 break;
570
6ef17211 571 case 'civicrm_financial_account':
572 if ($mode & CRM_Contact_BAO_Query::MODE_CONTACTS) {
573 $from = " $side JOIN civicrm_financial_account ON contact_a.id = civicrm_financial_account.contact_id ";
574 }
575 break;
576
6a488035 577 case 'civicrm_accounting_code':
6ef17211 578 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
579 $from = " $side JOIN civicrm_entity_financial_account ON civicrm_entity_financial_account.entity_id = civicrm_contribution.financial_type_id AND civicrm_entity_financial_account.entity_table = 'civicrm_financial_type' ";
580 $from .= " INNER JOIN civicrm_financial_account ON civicrm_financial_account.id = civicrm_entity_financial_account.financial_account_id ";
581 $from .= " INNER JOIN civicrm_option_value cov ON cov.value = civicrm_entity_financial_account.account_relationship AND cov.name = 'Income Account is' ";
582 $from .= " INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id AND cog.name = 'account_relationship' ";
583 }
39b795ba 584 break;
6a488035
TO
585
586 case 'civicrm_contribution_page':
3c151c70 587 $from = " $side JOIN civicrm_contribution_page ON civicrm_contribution.contribution_page_id = civicrm_contribution_page.id";
6a488035
TO
588 break;
589
590 case 'civicrm_product':
591 $from = " $side JOIN civicrm_contribution_product ON civicrm_contribution_product.contribution_id = civicrm_contribution.id";
592 $from .= " $side JOIN civicrm_product ON civicrm_contribution_product.product_id =civicrm_product.id ";
593 break;
594
36bf52ef 595 case 'contribution_softcredit_type':
353ffa53 596 $from = " $side JOIN civicrm_option_group option_group_contribution_softcredit_type ON
36bf52ef 597 (option_group_contribution_softcredit_type.name = 'soft_credit_type')";
77b97be7 598 $from .= " $side JOIN civicrm_option_value contribution_softcredit_type ON
36bf52ef
DS
599 ( civicrm_contribution_soft.soft_credit_type_id = contribution_softcredit_type.value
600 AND option_group_contribution_softcredit_type.id = contribution_softcredit_type.option_group_id )";
601 break;
602
6a488035
TO
603 case 'contribution_note':
604 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contribution' AND
605 civicrm_contribution.id = civicrm_note.entity_id )";
606 break;
607
6a488035
TO
608 case 'contribution_membership':
609 $from = " $side JOIN civicrm_membership_payment ON civicrm_membership_payment.contribution_id = civicrm_contribution.id";
610 $from .= " $side JOIN civicrm_membership ON civicrm_membership_payment.membership_id = civicrm_membership.id ";
611 break;
612
9ebd3386 613 case 'civicrm_campaign':
38310a51 614 //CRM-16764 - get survey clause from campaign bao
615 if (!CRM_Campaign_BAO_Query::$_applySurveyClause) {
616 $from = " $side JOIN civicrm_campaign ON civicrm_campaign.id = civicrm_contribution.campaign_id";
617 }
9ebd3386 618 break;
619
6a488035
TO
620 case 'contribution_participant':
621 $from = " $side JOIN civicrm_participant_payment ON civicrm_participant_payment.contribution_id = civicrm_contribution.id";
622 $from .= " $side JOIN civicrm_participant ON civicrm_participant_payment.participant_id = civicrm_participant.id ";
623 break;
624
625 case 'civicrm_contribution_soft':
be2fb01f 626 if (!in_array(self::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
3dbf477c
DS
627 $from = " $side JOIN civicrm_contribution_soft ON civicrm_contribution_soft.contribution_id = civicrm_contribution.id";
628 }
6a488035
TO
629 break;
630
631 case 'civicrm_contribution_soft_contact':
be2fb01f 632 if (in_array(self::$_contribOrSoftCredit, ["only_scredits", "both_related", "both"])) {
77b97be7 633 $from .= " $side JOIN civicrm_contact civicrm_contact_d ON (civicrm_contribution.contact_id = civicrm_contact_d.id )
3dbf477c 634 AND contribution_search_scredit_combined.scredit_id IS NOT NULL";
0db6c3e1
TO
635 }
636 else {
3dbf477c
DS
637 $from .= " $side JOIN civicrm_contact civicrm_contact_d ON (civicrm_contribution_soft.contact_id = civicrm_contact_d.id )";
638 }
6a488035
TO
639 break;
640
641 case 'civicrm_contribution_soft_email':
642 $from .= " $side JOIN civicrm_email as soft_email ON (civicrm_contact_d.id = soft_email.contact_id )";
643 break;
644
645 case 'civicrm_contribution_soft_phone':
646 $from .= " $side JOIN civicrm_phone as soft_phone ON (civicrm_contact_d.id = soft_phone.contact_id )";
647 break;
39b795ba 648
6a488035 649 case 'contribution_batch':
61412579 650 $from .= " $side JOIN civicrm_entity_batch ON ( civicrm_entity_batch.entity_table = 'civicrm_financial_trxn'
651 AND civicrm_financial_trxn.id = civicrm_entity_batch.entity_id )";
652
6a488035
TO
653 $from .= " $side JOIN civicrm_batch ON civicrm_entity_batch.batch_id = civicrm_batch.id";
654 break;
898bfdcd
PN
655
656 case 'civicrm_financial_trxn':
657 $from .= " $side JOIN civicrm_entity_financial_trxn ON (
658 civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution'
659 AND civicrm_contribution.id = civicrm_entity_financial_trxn.entity_id )";
660
661 $from .= " $side JOIN civicrm_financial_trxn ON (
662 civicrm_entity_financial_trxn.financial_trxn_id = civicrm_financial_trxn.id )";
663 break;
6a488035
TO
664 }
665 return $from;
666 }
667
186c9c17 668 /**
35e6241a
EM
669 * Initialise the soft credit clause.
670 *
671 * @param CRM_Contact_BAO_Query $query
186c9c17 672 */
00be9182 673 public static function initializeAnySoftCreditClause(&$query) {
5928ea72 674 // @todo have a generic initialize on all components that gets called every query
675 // & rename this to match that fn name.
9ae25b56 676 if ($query->_mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
677 if (self::isSoftCreditOptionEnabled($query->_params)) {
ed81a415 678 unset($query->_distinctComponentClause);
f654cacf 679 $query->_rowCountClause = " count(civicrm_contribution.id)";
ed81a415 680 $query->_groupByComponentClause = " GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.contact_id, contribution_search_scredit_combined.scredit_id ";
36bf52ef 681 }
9ae25b56 682 else {
683 $query->_distinctComponentClause = ' civicrm_contribution.id';
684 }
f654cacf
DS
685 }
686 }
687
186c9c17 688 /**
35e6241a
EM
689 * Check if soft credits are enables.
690 *
186c9c17
EM
691 * @param array $queryParams
692 *
693 * @return bool
694 */
be2fb01f 695 public static function isSoftCreditOptionEnabled($queryParams = []) {
f654cacf
DS
696 if (!empty($queryParams)) {
697 foreach (array_keys($queryParams) as $id) {
698 if (empty($queryParams[$id][0])) {
699 continue;
700 }
38e1cb31
DS
701 if ($queryParams[$id][0] == 'contribution_or_softcredits') {
702 self::$_contribOrSoftCredit = $queryParams[$id][2];
703 }
f654cacf
DS
704 }
705 }
77b97be7 706 if (in_array(self::$_contribOrSoftCredit,
be2fb01f 707 ["only_scredits", "both_related", "both"])) {
bc438a52 708 if (!isset(\Civi::$statics[__CLASS__]['soft_credit_temp_table_name'])) {
353ffa53
TO
709 // build a temp table which is union of contributions and soft credits
710 // note: group-by in first part ensures uniqueness in counts
bc438a52 711 $tempQuery = '
77b97be7 712 SELECT con.id as id, con.contact_id, cso.id as filter_id, NULL as scredit_id
3dbf477c 713 FROM civicrm_contribution con
4f3846df 714 LEFT JOIN civicrm_contribution_soft cso ON con.id = cso.contribution_id
e5cceea5 715 GROUP BY id, contact_id, scredit_id, cso.id
3dbf477c 716 UNION ALL
77b97be7 717 SELECT scredit.contribution_id as id, scredit.contact_id, scredit.id as filter_id, scredit.id as scredit_id
bc438a52 718 FROM civicrm_contribution_soft as scredit';
719 \Civi::$statics[__CLASS__]['soft_credit_temp_table_name'] = CRM_Utils_SQL_TempTable::build()->createWithQuery(
720 $tempQuery
721 )->getName();
f654cacf 722 }
353ffa53
TO
723 return TRUE;
724 }
36bf52ef
DS
725 return FALSE;
726 }
727
186c9c17 728 /**
35e6241a
EM
729 * Get return properties for soft credits.
730 *
186c9c17
EM
731 * @param bool $isExportMode
732 *
733 * @return array
734 */
353ffa53 735 public static function softCreditReturnProperties($isExportMode = FALSE) {
be2fb01f 736 $properties = [
353ffa53 737 'contribution_soft_credit_name' => 1,
4f3846df 738 'contribution_soft_credit_amount' => 1,
353ffa53 739 'contribution_soft_credit_type' => 1,
be2fb01f 740 ];
4f3846df 741 if ($isExportMode) {
5850d2e9 742 $properties['contribution_soft_credit_contact_id'] = 1;
4f3846df
DS
743 $properties['contribution_soft_credit_contribution_id'] = 1;
744 }
745 return $properties;
746 }
747
186c9c17 748 /**
c7940124 749 * Get the list of fields required to populate the selector.
750 *
751 * The default return properties array returns far too many fields for 'everyday use. Every field you add to this array
752 * kills a small kitten so add carefully.
b4bb60fc
OH
753 *
754 * @param array $queryParams
755 * @return array
c7940124 756 */
b4bb60fc 757 public static function selectorReturnProperties($queryParams) {
be2fb01f 758 $properties = [
c7940124 759 'contact_type' => 1,
760 'contact_sub_type' => 1,
761 'sort_name' => 1,
762 'financial_type' => 1,
763 'contribution_source' => 1,
764 'is_test' => 1,
765 'receive_date' => 1,
766 'is_pay_later' => 1,
767 'thankyou_date' => 1,
768 'total_amount' => 1,
5deb2f24 769 // Without this value here we get an e-notice BUT the value does not appear to be rendered anywhere.
770 'contribution_campaign_id' => 1,
c7940124 771 'contribution_status_id' => 1,
772 // @todo return this & fix query to do pseudoconstant thing.
773 'contribution_status' => 1,
9a59ce91 774 'currency' => 1,
1eae0d75 775 'cancel_date' => 1,
2e80df5b 776 'contribution_recur_id' => 1,
be2fb01f 777 ];
c8dd6301 778 if (self::isSiteHasProducts()) {
779 $properties['product_name'] = 1;
780 $properties['contribution_product_id'] = 1;
781 }
b4bb60fc 782 if (self::isSoftCreditOptionEnabled($queryParams)) {
8f7c2652 783 $properties = array_merge($properties, self::softCreditReturnProperties());
784 }
785
786 return $properties;
c7940124 787 }
788
c8dd6301 789 /**
790 * Do any products exist in this site's database.
791 *
792 * @return bool
793 */
794 public static function isSiteHasProducts() {
795 if (!isset(\Civi::$statics[__CLASS__]['has_products'])) {
796 \Civi::$statics[__CLASS__]['has_products'] = (bool) CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_contribution_product LIMIT 1');
797 }
798 return \Civi::$statics[__CLASS__]['has_products'];
799 }
800
c7940124 801 /**
802 * Function you should avoid.
803 *
804 * This function returns default properties for contribution queries. However, they are
805 * far more than are required in 'most' cases and you should always try to return the return properties
806 * you actually require.
807 *
808 * It would be nice to throw an e-notice when this is called but it would trash the tests :-(.
809 *
810 * @param int $mode
186c9c17
EM
811 * @param bool $includeCustomFields
812 *
e60f24eb 813 * @return array|NULL
186c9c17 814 */
00be9182 815 public static function defaultReturnProperties($mode, $includeCustomFields = TRUE) {
6a488035
TO
816 $properties = NULL;
817 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
be2fb01f 818 $properties = [
5928ea72 819 // add
6a488035 820 'contact_type' => 1,
5928ea72 821 // fields
6a488035 822 'contact_sub_type' => 1,
5928ea72 823 // to
6a488035 824 'sort_name' => 1,
5928ea72 825 //this
6a488035 826 'display_name' => 1,
5928ea72 827 // array
6a488035 828 'financial_type' => 1,
5928ea72 829 // to
6a488035 830 'contribution_source' => 1,
5928ea72 831 // strangle
6a488035 832 'receive_date' => 1,
5928ea72 833 // site
6a488035 834 'thankyou_date' => 1,
5928ea72 835 // performance
6e7cc0f5 836 'contribution_cancel_date' => 1,
5928ea72 837 // and
6a488035 838 'total_amount' => 1,
5928ea72 839 // torture
6a488035 840 'accounting_code' => 1,
5928ea72 841 // small
afa0b07c 842 'payment_instrument' => 1,
5928ea72 843 // kittens
3a6eb174 844 'payment_instrument_id' => 1,
5928ea72 845 // argh
7bc1d4da 846 'contribution_check_number' => 1,
5928ea72 847 // no
6a488035 848 'non_deductible_amount' => 1,
5928ea72 849 // not
6a488035 850 'fee_amount' => 1,
5928ea72 851 // another
6a488035 852 'net_amount' => 1,
5928ea72 853 // expensive
6a488035 854 'trxn_id' => 1,
5928ea72 855 // join
6a488035 856 'invoice_id' => 1,
802c1c41 857 'invoice_number' => 1,
5928ea72 858 // added
6a488035 859 'currency' => 1,
5928ea72 860 // to
6a488035 861 'cancel_reason' => 1,
5928ea72 862 //every
6a488035 863 'receipt_date' => 1,
5928ea72 864 // query
5928ea72 865 //whether
5928ea72 866 // or
5928ea72 867 // not
5928ea72 868 // the
5928ea72 869 // field
5928ea72 870 // is
6a488035 871 'is_test' => 1,
5928ea72 872 // actually
6a488035 873 'is_pay_later' => 1,
5928ea72 874 // required
6a488035 875 'contribution_status' => 1,
5928ea72 876 // instead
6a488035 877 'contribution_status_id' => 1,
5928ea72 878 // of
6a488035 879 'contribution_recur_id' => 1,
5928ea72 880 // adding
6a488035 881 'amount_level' => 1,
5928ea72 882 // here
6a488035 883 'contribution_note' => 1,
5928ea72 884 // set
6a488035 885 'contribution_batch' => 1,
5928ea72 886 // return properties
9ebd3386 887 'contribution_campaign_title' => 1,
5928ea72 888 // on
36bf52ef 889 'contribution_campaign_id' => 1,
5928ea72 890 // calling
5928ea72 891 //function
be2fb01f 892 ];
c8dd6301 893 if (self::isSiteHasProducts()) {
894 $properties['fulfilled_date'] = 1;
895 $properties['product_name'] = 1;
896 $properties['contribution_product_id'] = 1;
897 $properties['product_option'] = 1;
898 $properties['sku'] = 1;
899 $properties['contribution_start_date'] = 1;
900 $properties['contribution_end_date'] = 1;
901 }
d4e2b978 902 if (self::isSoftCreditOptionEnabled()) {
4f3846df 903 $properties = array_merge($properties, self::softCreditReturnProperties());
36bf52ef 904 }
6a488035
TO
905 if ($includeCustomFields) {
906 // also get all the custom contribution properties
907 $fields = CRM_Core_BAO_CustomField::getFieldsForImport('Contribution');
908 if (!empty($fields)) {
909 foreach ($fields as $name => $dontCare) {
910 $properties[$name] = 1;
911 }
912 }
913 }
914 }
915 return $properties;
916 }
917
7123f88c 918 /**
919 * Get the metadata for fields to be included on the search form.
920 *
921 * @throws \CiviCRM_API3_Exception
922 */
923 public static function getSearchFieldMetadata() {
924 $fields = [
925 'contribution_source',
926 'cancel_reason',
927 'invoice_number',
6e7cc0f5
SL
928 'receive_date',
929 'contribution_cancel_date',
7123f88c 930 ];
931 $metadata = civicrm_api3('Contribution', 'getfields', [])['values'];
932 return array_intersect_key($metadata, array_flip($fields));
933 }
934
6a488035 935 /**
fe482240 936 * Add all the elements shared between contribute search and advnaced search.
6a488035 937 *
7123f88c 938 * @param \CRM_Contribute_Form_Search $form
939 *
940 * @throws \CRM_Core_Exception
941 * @throws \CiviCRM_API3_Exception
6a488035 942 */
00be9182 943 public static function buildSearchForm(&$form) {
6a488035 944
7123f88c 945 $form->addSearchFieldMetadata(['Contribution' => self::getSearchFieldMetadata()]);
1157f03f 946 $form->addSearchFieldMetadata(['ContributionRecur' => CRM_Contribute_BAO_ContributionRecur::getContributionRecurSearchFieldMetadata()]);
7123f88c 947 $form->addFormFieldsFromMetadata();
6a488035 948
be2fb01f
CW
949 $form->add('text', 'contribution_amount_low', ts('From'), ['size' => 8, 'maxlength' => 8]);
950 $form->addRule('contribution_amount_low', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('9.99', ' ')]), 'money');
6a488035 951
be2fb01f
CW
952 $form->add('text', 'contribution_amount_high', ts('To'), ['size' => 8, 'maxlength' => 8]);
953 $form->addRule('contribution_amount_high', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('99.99', ' ')]), 'money');
6a488035
TO
954
955 // Adding select option for curreny type -- CRM-4711
956 $form->add('select', 'contribution_currency_type',
957 ts('Currency Type'),
be2fb01f 958 [
7c550ca0 959 '' => ts('- any -'),
be2fb01f
CW
960 ] +
961 CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', ['labelColumn' => 'name']),
962 FALSE, ['class' => 'crm-select2']
6a488035
TO
963 );
964
1f0d8c92 965 // CRM-13848
573fd305 966 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::VIEW);
15cf9198 967 $form->addSelect('financial_type_id',
be2fb01f 968 ['entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => $financialTypes]
6a488035
TO
969 );
970
971 $form->add('select', 'contribution_page_id',
972 ts('Contribution Page'),
ab345ca5 973 CRM_Contribute_PseudoConstant::contributionPage(),
be2fb01f 974 FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]
6a488035
TO
975 );
976
6e219d15
SP
977 // use contribution_payment_instrument_id instead of payment_instrument_id
978 // Contribution Edit form (pop-up on contribution/Contact(display Result as Contribution) open on search form),
979 // then payment method change action not working properly because of same html ID present two time on one page
980 $form->addSelect('contribution_payment_instrument_id',
be2fb01f 981 ['entity' => 'contribution', 'field' => 'payment_instrument_id', 'multiple' => 'multiple', 'label' => ts('Payment Method'), 'option_url' => NULL, 'placeholder' => ts('- any -')]
6a488035
TO
982 );
983
1517c3e8 984 $form->add('select',
985 'contribution_pcp_made_through_id',
986 ts('Personal Campaign Page'),
be2fb01f 987 CRM_Contribute_PseudoConstant::pcPage(), FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]);
6a488035 988
2b65bb8c 989 $statusValues = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id');
2b65bb8c 990 $form->add('select', 'contribution_status_id',
991 ts('Contribution Status'), $statusValues,
be2fb01f 992 FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']
3c151c70 993 );
6a488035
TO
994
995 // Add fields for thank you and receipt
8a4f27dc
CW
996 $form->addYesNo('contribution_thankyou_date_is_not_null', ts('Thank-you sent?'), TRUE);
997 $form->addYesNo('contribution_receipt_date_is_not_null', ts('Receipt sent?'), TRUE);
6a488035 998
8a4f27dc
CW
999 $form->addYesNo('contribution_pay_later', ts('Contribution is Pay Later?'), TRUE);
1000 $form->addYesNo('contribution_recurring', ts('Contribution is Recurring?'), TRUE);
b32bc653 1001
8a4f27dc 1002 $form->addYesNo('contribution_test', ts('Contribution is a Test?'), TRUE);
6a488035
TO
1003
1004 // Add field for transaction ID search
3c151c70 1005 $form->addElement('text', 'contribution_trxn_id', ts("Transaction ID"));
6a488035
TO
1006 $form->addElement('text', 'contribution_check_number', ts('Check Number'));
1007
1008 // Add field for pcp display in roll search
8a4f27dc 1009 $form->addYesNo('contribution_pcp_display_in_roll', ts('Personal Campaign Page Honor Roll?'), TRUE);
6a488035 1010
36bf52ef 1011 // Soft credit related fields
be2fb01f 1012 $options = [
3dbf477c 1013 'only_contribs' => ts('Contributions Only'),
e0b774f0 1014 'only_scredits' => ts('Soft Credits Only'),
353ffa53
TO
1015 'both_related' => ts('Soft Credits with related Hard Credit'),
1016 'both' => ts('Both'),
be2fb01f
CW
1017 ];
1018 $form->add('select', 'contribution_or_softcredits', ts('Contributions OR Soft Credits?'), $options, FALSE, ['class' => "crm-select2"]);
e88186f4 1019 $form->addSelect(
77b97be7 1020 'contribution_soft_credit_type_id',
be2fb01f 1021 [
353ffa53
TO
1022 'entity' => 'contribution_soft',
1023 'field' => 'soft_credit_type_id',
1024 'multiple' => TRUE,
1025 'context' => 'search',
be2fb01f 1026 ]
e88186f4 1027 );
36bf52ef 1028
be2fb01f 1029 $form->addField('financial_trxn_card_type_id', ['entity' => 'FinancialTrxn', 'name' => 'card_type_id', 'action' => 'get']);
898bfdcd 1030
be2fb01f 1031 $form->add('text', 'financial_trxn_pan_truncation', ts('Card Number'), [
c6ba3619
E
1032 'size' => 5,
1033 'maxlength' => 4,
1034 'autocomplete' => 'off',
be2fb01f 1035 ]);
c6ba3619 1036
c8dd6301 1037 if (CRM_Contribute_BAO_Query::isSiteHasProducts()) {
1038 // CRM-16713 - contribution search by premiums on 'Find Contribution' form.
1039 $form->add('select', 'contribution_product_id',
1040 ts('Premium'),
1041 CRM_Contribute_PseudoConstant::products(),
1042 FALSE, [
1043 'class' => 'crm-select2',
1044 'multiple' => 'multiple',
1330f57a 1045 'placeholder' => ts('- any -'),
c8dd6301 1046 ]
1047 );
1048 }
6ffab5b7 1049
be2fb01f 1050 self::addCustomFormFields($form, ['Contribution']);
6a488035
TO
1051
1052 CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'contribution_campaign_id');
1053
1054 // Add batch select
91aff94c 1055 $batches = CRM_Contribute_PseudoConstant::batch();
39b795ba 1056
481a74f4 1057 if (!empty($batches)) {
6a488035
TO
1058 $form->add('select', 'contribution_batch_id',
1059 ts('Batch Name'),
be2fb01f 1060 [
dc7b39df
JV
1061 '' => ts('- any -'),
1062 // CRM-19325
3086e282 1063 'IS NULL' => ts('None'),
be2fb01f
CW
1064 ] + $batches,
1065 FALSE, ['class' => 'crm-select2']
ab345ca5 1066 );
6a488035
TO
1067 }
1068
1069 $form->assign('validCiviContribute', TRUE);
be2fb01f 1070 $form->setDefaults(['contribution_test' => 0]);
24782d26 1071
1072 CRM_Contribute_BAO_ContributionRecur::recurringContribution($form);
6a488035
TO
1073 }
1074
186c9c17 1075 /**
35e6241a
EM
1076 * Get table names.
1077 *
1078 * @todo better function comment needed - what IS the point of this?
1079 *
1080 * @param array $tables
186c9c17 1081 */
00be9182 1082 public static function tableNames(&$tables) {
6a488035 1083 // Add contribution table
a7488080 1084 if (!empty($tables['civicrm_product'])) {
be2fb01f 1085 $tables = array_merge(['civicrm_contribution' => 1], $tables);
6a488035
TO
1086 }
1087
8cc574cf 1088 if (!empty($tables['civicrm_contribution_product']) && empty($tables['civicrm_product'])) {
6a488035
TO
1089 $tables['civicrm_product'] = 1;
1090 }
1091 }
a91e698a 1092
1093 /**
fe482240 1094 * Add the where for dates.
77b97be7 1095 *
014c4014
TO
1096 * @param array $values
1097 * Array of query values.
1098 * @param object $query
1099 * The query object.
1100 * @param string $name
1101 * Query field that is set.
1102 * @param string $field
1103 * Name of field to be set.
1104 * @param string $title
1105 * Title of the field.
77b97be7
EM
1106 *
1107 * @return bool
a91e698a 1108 */
00be9182 1109 public static function buildDateWhere(&$values, $query, $name, $field, $title) {
a91e698a 1110 $fieldPart = strpos($name, $field);
22e263ad 1111 if ($fieldPart === FALSE) {
7c550ca0 1112 return NULL;
a91e698a 1113 }
1114 // we only have recurring dates using this ATM so lets' short cut to find the table name
1115 $table = 'contribution_recur';
d3e86119 1116 $fieldName = explode($table . '_', $field);
a91e698a 1117 $query->dateQueryBuilder($values,
1118 'civicrm_' . $table, $field, $fieldName[1], $title
1119 );
1120 return TRUE;
1121 }
b32bc653 1122
686df921 1123 /**
1124 * Add the soft credit fields to the select fields.
1125 *
1126 * Extracted into separate function to improve readability of main select function.
1127 *
1128 * @param $query
1129 */
1130 private static function addSoftCreditFields(&$query) {
1131 $includeSoftCredits = self::isSoftCreditOptionEnabled($query->_params);
1132 if (!empty($query->_returnProperties['contribution_soft_credit_name'])) {
1133 if ($includeSoftCredits) {
1134 $query->_select['contribution_soft_credit_name'] = "civicrm_contact_d.sort_name as contribution_soft_credit_name";
1135 // also include contact id. Will help build hyperlinks
1136 $query->_select['contribution_soft_credit_contact_id'] = "civicrm_contact_d.id as contribution_soft_credit_contact_id";
1137 }
1138 $query->_element['contribution_soft_credit_name'] = 1;
1139 $query->_element['contribution_soft_credit_contact_id'] = 1;
1140
1141 $query->_tables['civicrm_contribution'] = 1;
1142 $query->_tables['civicrm_contribution_soft'] = 1;
1143 $query->_tables['civicrm_contribution_soft_contact'] = 1;
1144 }
1145
1146 if (!empty($query->_returnProperties['contribution_soft_credit_contact_id'])) {
1147 $query->_tables['civicrm_contribution'] = 1;
1148 $query->_tables['civicrm_contribution_soft'] = 1;
1149 $query->_tables['civicrm_contribution_soft_contact'] = 1;
1150 }
1151
1152 if (!empty($query->_returnProperties['contribution_soft_credit_amount'])) {
1153 if ($includeSoftCredits) {
1154 $query->_select['contribution_soft_credit_amount'] = "civicrm_contribution_soft.amount as contribution_soft_credit_amount";
1155 }
1156 $query->_element['contribution_soft_credit_amount'] = 1;
1157 $query->_tables['civicrm_contribution'] = 1;
1158 $query->_tables['civicrm_contribution_soft'] = 1;
1159 }
1160
1161 if (!empty($query->_returnProperties['contribution_soft_credit_type'])) {
1162 if ($includeSoftCredits) {
1163 $query->_select['contribution_soft_credit_type'] = "contribution_softcredit_type.label as contribution_soft_credit_type";
1164 }
1165 $query->_element['contribution_soft_credit_type'] = 1;
1166 $query->_tables['civicrm_contribution'] = 1;
1167 $query->_tables['contribution_softcredit_type'] = 1;
1168 }
1169
1170 if (!empty($query->_returnProperties['contribution_soft_credit_contribution_id'])) {
1171 if ($includeSoftCredits) {
1172 $query->_select['contribution_soft_credit_contribution_id'] = "civicrm_contribution_soft.contribution_id as contribution_soft_credit_contribution_id";
1173 }
1174 $query->_element['contribution_soft_credit_contribution_id'] = 1;
1175 $query->_tables['civicrm_contribution'] = 1;
1176 $query->_tables['civicrm_contribution_soft'] = 1;
1177 }
1178
1179 if (!empty($query->_returnProperties['contribution_soft_credit_email'])) {
1180 $query->_select['contribution_soft_credit_email'] = "soft_email.email as contribution_soft_credit_email";
1181 $query->_element['contribution_soft_credit_email'] = 1;
1182 $query->_tables['civicrm_contribution'] = 1;
1183 $query->_tables['civicrm_contribution_soft'] = 1;
1184 $query->_tables['civicrm_contribution_soft_contact'] = 1;
1185 $query->_tables['civicrm_contribution_soft_email'] = 1;
1186 }
1187
1188 if (!empty($query->_returnProperties['contribution_soft_credit_phone'])) {
1189 $query->_select['contribution_soft_credit_email'] = "soft_phone.phone as contribution_soft_credit_phone";
1190 $query->_element['contribution_soft_credit_phone'] = 1;
1191 $query->_tables['civicrm_contribution'] = 1;
1192 $query->_tables['civicrm_contribution_soft'] = 1;
1193 $query->_tables['civicrm_contribution_soft_contact'] = 1;
1194 $query->_tables['civicrm_contribution_soft_phone'] = 1;
1195 }
1196
1197 if (!empty($query->_returnProperties['contribution_soft_credit_pcp_id'])) {
1198 $query->_select['contribution_soft_credit_pcp_id'] = "civicrm_contribution_soft.pcp_id as contribution_soft_credit_pcp_id";
1199 $query->_element['contribution_soft_credit_pcp_id'] = 1;
1200 $query->_tables['civicrm_contribution'] = 1;
1201 $query->_tables['civicrm_contribution_soft'] = 1;
1202 }
1203 }
1204
6a488035 1205}