Merge pull request #18979 from eileenmcnaughton/trans
[civicrm-core.git] / CRM / Contribute / BAO / Contribution.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035 11
6e902643 12use Civi\Api4\Activity;
68dce20c 13use Civi\Api4\ContributionPage;
14use Civi\Api4\ContributionRecur;
26626bac 15use Civi\Api4\Participant;
62a721ed 16use Civi\Api4\PaymentProcessor;
6e902643 17
6a488035
TO
18/**
19 *
20 * @package CRM
ca5cec67 21 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
22 */
23class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
24
25 /**
100fef9d 26 * Static field for all the contribution information that we can potentially import
6a488035
TO
27 *
28 * @var array
6a488035 29 */
1330f57a 30 public static $_importableFields = NULL;
6a488035
TO
31
32 /**
100fef9d 33 * Static field for all the contribution information that we can potentially export
6a488035
TO
34 *
35 * @var array
6a488035 36 */
1330f57a 37 public static $_exportableFields = NULL;
6a488035 38
9c472292
PN
39 /**
40 * Static field to hold financial trxn id's.
41 *
42 * @var array
43 */
1330f57a 44 public static $_trxnIDs = NULL;
9c472292 45
6a488035 46 /**
7d73f1ef 47 * Field for all the objects related to this contribution.
48 *
49 * This is used from
50 * 1) deprecated function transitionComponents
51 * 2) function to send contribution receipts _assignMessageVariablesToTemplate
52 * 3) some invoice code that is copied from 2
53 * 4) odds & sods that need to be investigated and fixed.
54 *
55 * However, it is no longer used by completeOrder.
66d5d6f4 56 *
5ba7d840 57 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
7d73f1ef 58 *
59 * @deprecated
6a488035 60 */
66d5d6f4 61 public $_relatedObjects = [];
6a488035
TO
62
63 /**
100fef9d 64 * Field for the component - either 'event' (participant) or 'contribute'
6a488035
TO
65 * (any item related to a contribution page e.g. membership, pledge, contribution)
66 * This is used for composing messages because they have dependency on the
67 * contribution_page or event page - although over time we may eliminate that
68 *
51dda21e
SL
69 * @var string
70 * "contribution"\"event"
6a488035
TO
71 */
72 public $_component = NULL;
73
0be43473
EM
74 /**
75 * Possibly obsolete variable.
76 *
77 * If you use it please explain why it is set in the create function here.
78 *
79 * @var string
80 */
81 public $trxn_result_code;
82
186c9c17 83 /**
fe482240 84 * Class constructor.
186c9c17 85 */
00be9182 86 public function __construct() {
6a488035
TO
87 parent::__construct();
88 }
89
90 /**
fe482240 91 * Takes an associative array and creates a contribution object.
6a488035
TO
92 *
93 * the function extract all the params it needs to initialize the create a
94 * contribution object. the params array could contain additional unused name/value
95 * pairs
96 *
014c4014
TO
97 * @param array $params
98 * (reference ) an assoc array of name/value pairs.
6a488035 99 *
77beddbe 100 * @return \CRM_Contribute_BAO_Contribution
101 * @throws \CRM_Core_Exception
66d5d6f4 102 * @throws \CiviCRM_API3_Exception
6a488035 103 */
87c5b5b4 104 public static function add(&$params) {
6a488035 105 if (empty($params)) {
bed98343 106 return NULL;
6a488035 107 }
87c5b5b4 108
109 $contributionID = $params['id'] ?? NULL;
80e74f7b 110 $action = $contributionID ? 'edit' : 'create';
66d5d6f4 111 $duplicates = [];
504a78f6 112 if (self::checkDuplicate($params, $duplicates, $contributionID)) {
6dabf459 113 $message = ts("Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: %1", [1 => implode(', ', $duplicates)]);
77beddbe 114 throw new CRM_Core_Exception($message);
6a488035
TO
115 }
116
16e268ad 117 //set defaults in create mode
118 if (!$contributionID) {
119 CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
5d288dc4 120 if (empty($params['invoice_number']) && CRM_Invoicing_Utils::isInvoicingEnabled()) {
b07b172b 121 $nextContributionID = CRM_Core_DAO::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
122 $params['invoice_number'] = self::getInvoiceNumber($nextContributionID);
123 }
16e268ad 124 }
125
b048ed17 126 $contributionStatusID = $params['contribution_status_id'] ?? NULL;
127 if (CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
128 CRM_Core_Error::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
129 }
130 if (!$contributionStatusID) {
76c28c8d
DG
131 // Since the fee amount is expecting this (later on) ensure it is always set.
132 // It would only not be set for an update where it is unchanged.
66d5d6f4 133 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
134 'id' => $contributionID,
135 'return' => 'contribution_status_id',
136 ]);
76c28c8d 137 }
b048ed17 138 $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
4add5adb 139
8cf6bd83 140 if (!$contributionID
b99f3e96 141 && !empty($params['membership_id'])
a17bec97 142 && Civi::settings()->get('deferred_revenue_enabled')
8cf6bd83
PN
143 ) {
144 $memberStartDate = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
145 if ($memberStartDate) {
146 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
147 }
148 }
080a561b 149 self::calculateMissingAmountParams($params, $contributionID);
6a488035 150
a7488080 151 if (!empty($params['payment_instrument_id'])) {
6a488035
TO
152 $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name');
153 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
154 $params['check_number'] = 'null';
155 }
156 }
157
5e494d5c 158 $setPrevContribution = TRUE;
19393e51 159 if ($contributionID && $setPrevContribution) {
2912ed09 160 $params['prevContribution'] = self::getOriginalContribution($contributionID);
19393e51 161 }
b048ed17 162 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id) : NULL;
ede1935f 163
b048ed17 164 if ($contributionID && !empty($params['revenue_recognition_date'])
165 && !($previousContributionStatus === 'Pending')
1a55f42e
PN
166 && !self::allowUpdateRevenueRecognitionDate($contributionID)
167 ) {
168 unset($params['revenue_recognition_date']);
169 }
96039749 170
bf4385cb
SL
171 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
172 isset($params['financial_type_id']))) {
1fca875f 173 $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
2912ed09 174 }
175
80e74f7b 176 CRM_Utils_Hook::pre($action, 'Contribution', $contributionID, $params);
177
6a488035
TO
178 $contribution = new CRM_Contribute_BAO_Contribution();
179 $contribution->copyValues($params);
180
504a78f6 181 $contribution->id = $contributionID;
6a488035 182
10cd9458 183 if (empty($contribution->id)) {
184 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
185 if (!CRM_Utils_Rule::currencyCode($contribution->currency)) {
4e92d4f4 186 $contribution->currency = CRM_Core_Config::singleton()->defaultCurrency;
10cd9458 187 }
6a488035
TO
188 }
189
6a488035
TO
190 $result = $contribution->save();
191
192 // Add financial_trxn details as part of fix for CRM-4724
9c1bc317
CW
193 $contribution->trxn_result_code = $params['trxn_result_code'] ?? NULL;
194 $contribution->payment_processor = $params['payment_processor'] ?? NULL;
6a488035
TO
195
196 //add Account details
197 $params['contribution'] = $contribution;
362f37fc 198 if (empty($params['is_post_payment_create'])) {
199 // If this is being called from the Payment.create api/ BAO then that Entity
200 // takes responsibility for the financial transactions. In fact calling Payment.create
201 // to add payments & having it call completetransaction and / or contribution.create
202 // to update related entities is the preferred flow.
203 // Note that leveraging this parameter for any other code flow is not supported and
204 // is likely to break in future and / or cause serious problems in your data.
205 // https://github.com/civicrm/civicrm-core/pull/14673
206 self::recordFinancialAccounts($params);
207 }
6a488035 208
91259407 209 if (self::isUpdateToRecurringContribution($params)) {
210 CRM_Contribute_BAO_ContributionRecur::updateOnNewPayment(
d4009c22 211 (!empty($params['contribution_recur_id']) ? $params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id),
b048ed17 212 $contributionStatus,
d4578334 213 $params['receive_date'] ?? NULL
91259407 214 );
215 }
216
80e74f7b 217 $params['contribution_id'] = $contribution->id;
6a488035 218
80e74f7b 219 if (!empty($params['custom']) &&
220 is_array($params['custom'])
221 ) {
222 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id, $action);
6a488035
TO
223 }
224
80e74f7b 225 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
226
227 CRM_Utils_Hook::post($action, 'Contribution', $contribution->id, $contribution);
6a488035
TO
228 return $result;
229 }
230
91259407 231 /**
232 * Is this contribution updating an existing recurring contribution.
233 *
234 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
235 * pending payment is being confirmed (or failing).
236 *
237 * @param array $params
238 *
239 * @return bool
240 */
241 public static function isUpdateToRecurringContribution($params) {
242 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
243 return TRUE;
244 }
245 if (empty($params['prevContribution']) || empty($params['contribution_status_id'])) {
246 return FALSE;
247 }
248 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id)) {
249 return FALSE;
250 }
251 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
252 if ($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)) {
253 return TRUE;
254 }
255 return FALSE;
256 }
257
44a2db2b 258 /**
fe482240 259 * Get defaults for new entity.
66d5d6f4 260 *
44a2db2b
EM
261 * @return array
262 */
00be9182 263 public static function getDefaults() {
66d5d6f4 264 return [
44a2db2b 265 'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument',
66d5d6f4 266 FALSE, FALSE, FALSE, 'AND is_default = 1')
44a2db2b 267 ),
66d5d6f4 268 'contribution_status_id' => CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
ffc9d3b2 269 'receive_date' => date('Y-m-d H:i:s'),
66d5d6f4 270 ];
44a2db2b
EM
271 }
272
6a488035 273 /**
9a7e53b0 274 * Fetch the object and store the values in the values array.
6a488035 275 *
014c4014
TO
276 * @param array $params
277 * Input parameters to find object.
278 * @param array $values
279 * Output values of the object.
280 * @param array $ids
281 * The array that holds all the db ids.
6a488035 282 *
a380f4a0
EM
283 * @return CRM_Contribute_BAO_Contribution|null
284 * The found object or null
6a488035 285 */
981e0d0b 286 public static function getValues($params, &$values = [], &$ids = []) {
6a488035
TO
287 if (empty($params)) {
288 return NULL;
289 }
290 $contribution = new CRM_Contribute_BAO_Contribution();
291
292 $contribution->copyValues($params);
293
294 if ($contribution->find(TRUE)) {
295 $ids['contribution'] = $contribution->id;
296
297 CRM_Core_DAO::storeValues($contribution, $values);
298
299 return $contribution;
300 }
1330f57a
SL
301 // return by reference
302 $null = NULL;
7e5524d4 303 return $null;
6a488035
TO
304 }
305
99cdd94d 306 /**
307 * Get the values and resolve the most common mappings.
308 *
309 * Since contribution status is resolved in almost every function that calls getValues it makes
310 * sense to have an extra function to resolve it rather than repeat the code.
311 *
312 * Think carefully before adding more mappings to be resolved as there could be performance implications
313 * if this function starts to be called from more iterative functions.
314 *
315 * @param array $params
316 * Input parameters to find object.
317 *
318 * @return array
319 * Array of the found contribution.
320 * @throws CRM_Core_Exception
321 */
322 public static function getValuesWithMappings($params) {
66d5d6f4 323 $values = $ids = [];
99cdd94d 324 $contribution = self::getValues($params, $values, $ids);
325 if (is_null($contribution)) {
326 throw new CRM_Core_Exception('No contribution found');
327 }
328 $values['contribution_status'] = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
329 return $values;
330 }
331
44a2db2b 332 /**
0be43473 333 * Calculate net_amount & fee_amount if they are not set.
44a2db2b 334 *
0be43473
EM
335 * Net amount should be total - fee.
336 * This should only be called for new contributions.
337 *
338 * @param array $params
339 * Params for a new contribution before they are saved.
080a561b 340 * @param int|null $contributionID
341 * Contribution ID if we are dealing with an update.
342 *
343 * @throws \CiviCRM_API3_Exception
44a2db2b 344 */
080a561b 345 public static function calculateMissingAmountParams(&$params, $contributionID) {
346 if (!$contributionID && !isset($params['fee_amount'])) {
44a2db2b
EM
347 if (isset($params['total_amount']) && isset($params['net_amount'])) {
348 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
349 }
350 else {
351 $params['fee_amount'] = 0;
352 }
353 }
354 if (!isset($params['net_amount'])) {
080a561b 355 if (!$contributionID) {
356 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
357 }
358 else {
359 if (isset($params['fee_amount']) || isset($params['total_amount'])) {
360 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
361 // net_amount may need adjusting.
66d5d6f4 362 $contribution = civicrm_api3('Contribution', 'getsingle', [
080a561b 363 'id' => $contributionID,
66d5d6f4 364 'return' => ['total_amount', 'net_amount', 'fee_amount'],
365 ]);
d4f6c9f9 366 $totalAmount = (isset($params['total_amount']) ? (float) $params['total_amount'] : (float) CRM_Utils_Array::value('total_amount', $contribution));
367 $feeAmount = (isset($params['fee_amount']) ? (float) $params['fee_amount'] : (float) CRM_Utils_Array::value('fee_amount', $contribution));
080a561b 368 $params['net_amount'] = $totalAmount - $feeAmount;
369 }
370 }
44a2db2b
EM
371 }
372 }
373
0816949d
EM
374 /**
375 * @param $params
376 * @param $billingLocationTypeID
377 *
378 * @return array
379 */
380 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
381 $hasBillingField = FALSE;
66d5d6f4 382 $billingFields = [
0816949d
EM
383 'street_address',
384 'city',
385 'state_province_id',
386 'postal_code',
387 'country_id',
66d5d6f4 388 ];
0816949d
EM
389
390 //build address array
66d5d6f4 391 $addressParams = [];
0816949d
EM
392 $addressParams['location_type_id'] = $billingLocationTypeID;
393 $addressParams['is_billing'] = 1;
394
9c1bc317
CW
395 $billingFirstName = $params['billing_first_name'] ?? NULL;
396 $billingMiddleName = $params['billing_middle_name'] ?? NULL;
397 $billingLastName = $params['billing_last_name'] ?? NULL;
0816949d
EM
398 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}";
399
400 foreach ($billingFields as $value) {
9c1bc317 401 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ?? NULL;
0816949d
EM
402 if (!empty($addressParams[$value])) {
403 $hasBillingField = TRUE;
404 }
405 }
66d5d6f4 406 return [$hasBillingField, $addressParams];
0816949d
EM
407 }
408
409 /**
410 * Get address params ready to be passed to the payment processor.
411 *
412 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
413 * To create an address we need state_province_id.
414 *
415 * @param array $params
416 * @param int $billingLocationTypeID
417 *
418 * @return array
419 */
420 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
421 list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID);
422 foreach ($addressParams as $name => $field) {
423 if (substr($name, 0, 8) == 'billing_') {
424 $addressParams[substr($name, 9)] = $addressParams[$field];
425 }
426 }
66d5d6f4 427 return [$hasBillingField, $addressParams];
0816949d
EM
428 }
429
2243fe93
EM
430 /**
431 * Get the number of terms for this contribution for a given membership type
432 * based on querying the line item table and relevant price field values
433 * Note that any one contribution should only be able to have one line item relating to a particular membership
434 * type
a284891b 435 *
2243fe93
EM
436 * @param int $membershipTypeID
437 *
a284891b
EM
438 * @param int $contributionID
439 *
2243fe93
EM
440 * @return int
441 */
eed14abb 442 public static function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
f2b2a3ff 443 $numTerms = CRM_Core_DAO::singleValueQuery("
2243fe93
EM
444 SELECT membership_num_terms FROM civicrm_line_item li
445 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
29347f3d 446 WHERE contribution_id = %1 AND membership_type_id = %2",
66d5d6f4 447 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
2243fe93
EM
448 );
449 // default of 1 is precautionary
450 return empty($numTerms) ? 1 : $numTerms;
451 }
452
6a488035 453 /**
fe482240 454 * Takes an associative array and creates a contribution object.
6a488035 455 *
014c4014
TO
456 * @param array $params
457 * (reference ) an assoc array of name/value pairs.
6a488035 458 *
16b10e64 459 * @return CRM_Contribute_BAO_Contribution
80e74f7b 460 *
6e902643 461 * @throws \API_Exception
80e74f7b 462 * @throws \CRM_Core_Exception
463 * @throws \CiviCRM_API3_Exception
6a488035 464 */
3e358ffb 465 public static function create(&$params) {
6a488035 466
6a488035
TO
467 $transaction = new CRM_Core_Transaction();
468
77beddbe 469 try {
70d43afb 470 $contribution = self::add($params);
77beddbe 471 }
472 catch (CRM_Core_Exception $e) {
6a488035 473 $transaction->rollback();
77beddbe 474 throw $e;
6a488035
TO
475 }
476
477 $params['contribution_id'] = $contribution->id;
6a488035
TO
478 $session = CRM_Core_Session::singleton();
479
a7488080 480 if (!empty($params['note'])) {
66d5d6f4 481 $noteParams = [
6a488035
TO
482 'entity_table' => 'civicrm_contribution',
483 'note' => $params['note'],
484 'entity_id' => $contribution->id,
485 'contact_id' => $session->get('userID'),
66d5d6f4 486 ];
6a488035
TO
487 if (!$noteParams['contact_id']) {
488 $noteParams['contact_id'] = $params['contact_id'];
489 }
504a78f6 490 CRM_Core_BAO_Note::add($noteParams);
6a488035
TO
491 }
492
7a13735b 493 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
2cfc0f58 494
6a488035
TO
495 $transaction->commit();
496
3f160c1c 497 if (empty($contribution->contact_id)) {
498 $contribution->find(TRUE);
499 }
6e902643 500
501 $isCompleted = ('Completed' === CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id));
502 if (!empty($params['on_behalf'])
503 || $isCompleted
504 ) {
505 $existingActivity = Activity::get(FALSE)->setWhere([
506 ['source_record_id', '=', $contribution->id],
507 ['activity_type_id:name', '=', 'Contribution'],
508 ])->execute()->first();
509
510 $campaignParams = isset($params['campaign_id']) ? ['campaign_id' => ($params['campaign_id'] ?? NULL)] : [];
511 Activity::save(FALSE)->addRecord(array_merge([
512 'activity_type_id:name' => 'Contribution',
513 'source_record_id' => $contribution->id,
514 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ?: $contribution->contact_id,
515 'target_contact_id' => CRM_Core_Session::getLoggedInContactID() ? [$contribution->contact_id] : [],
516 'activity_date_time' => $contribution->receive_date,
517 'is_test' => (bool) $contribution->is_test,
518 'status_id:name' => $isCompleted ? 'Completed' : 'Scheduled',
519 'skipRecentView' => TRUE,
520 'subject' => CRM_Activity_BAO_Activity::getActivitySubject($contribution),
521 'id' => $existingActivity['id'] ?? NULL,
522 ], $campaignParams))->execute();
523 }
464ff9cc 524
6a488035 525 // do not add to recent items for import, CRM-4399
a7488080 526 if (empty($params['skipRecentView'])) {
6a488035
TO
527 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
528 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
529 );
530 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
66d5d6f4 531 $titleFields = [
6a488035
TO
532 'contact_id',
533 'total_amount',
534 'currency',
535 'financial_type_id',
66d5d6f4 536 ];
d37ade2e 537 $retrieveRequired = 0;
6a488035 538 foreach ($titleFields as $titleField) {
f2b2a3ff 539 if (!isset($contribution->$titleField)) {
d37ade2e 540 $retrieveRequired = 1;
6a488035
TO
541 break;
542 }
543 }
f2b2a3ff 544 if ($retrieveRequired == 1) {
2cfc0f58 545 $contribution->find(TRUE);
6a488035 546 }
d51d109d
SL
547 $financialType = CRM_Contribute_PseudoConstant::financialType($contribution->financial_type_id);
548 $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $financialType . ')';
6a488035 549
66d5d6f4 550 $recentOther = [];
6a488035
TO
551 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
552 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
553 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
554 );
555 }
556
557 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
558 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
559 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
560 );
561 }
562
563 // add the recently created Contribution
564 CRM_Utils_Recent::add($title,
565 $url,
566 $contribution->id,
567 'Contribution',
568 $contribution->contact_id,
569 NULL,
570 $recentOther
571 );
572 }
573
574 return $contribution;
575 }
576
577 /**
578 * Get the values for pseudoconstants for name->value and reverse.
579 *
014c4014
TO
580 * @param array $defaults
581 * (reference) the default values, some of which need to be resolved.
582 * @param bool $reverse
583 * True if we want to resolve the values in the reverse direction (value -> name).
6a488035 584 */
00be9182 585 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
6a488035
TO
586 self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse);
587 self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse);
c3b82060 588 self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label'), $reverse);
6a488035
TO
589 self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse);
590 }
591
592 /**
74ab7ba8 593 * Convert associative array names to values and vice-versa.
6a488035
TO
594 *
595 * This function is used by both the web form layer and the api. Note that
596 * the api needs the name => value conversion, also the view layer typically
597 * requires value => name conversion
74ab7ba8
EM
598 *
599 * @param array $defaults
600 * @param string $property
601 * @param array $lookup
602 * @param bool $reverse
603 *
604 * @return bool
6a488035 605 */
00be9182 606 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
6a488035
TO
607 $id = $property . '_id';
608
609 $src = $reverse ? $property : $id;
610 $dst = $reverse ? $id : $property;
611
612 if (!array_key_exists($src, $defaults)) {
613 return FALSE;
614 }
615
616 $look = $reverse ? array_flip($lookup) : $lookup;
617
618 if (is_array($look)) {
619 if (!array_key_exists($defaults[$src], $look)) {
620 return FALSE;
621 }
622 }
623 $defaults[$dst] = $look[$defaults[$src]];
624 return TRUE;
625 }
626
627 /**
fe482240
EM
628 * Retrieve DB object based on input parameters.
629 *
630 * It also stores all the retrieved values in the default array.
6a488035 631 *
014c4014
TO
632 * @param array $params
633 * (reference ) an assoc array of name/value pairs.
634 * @param array $defaults
635 * (reference ) an assoc array to hold the name / value pairs.
6a488035 636 * in a hierarchical manner
014c4014
TO
637 * @param array $ids
638 * (reference) the array that holds all the db ids.
6a488035 639 *
16b10e64 640 * @return CRM_Contribute_BAO_Contribution
6a488035 641 */
db62d3a5 642 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
6a488035
TO
643 $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
644 return $contribution;
645 }
646
647 /**
fe482240 648 * Combine all the importable fields from the lower levels object.
6a488035
TO
649 *
650 * The ordering is important, since currently we do not have a weight
651 * scheme. Adding weight is super important and should be done in the
652 * next week or so, before this can be called complete.
653 *
8efea814
EM
654 * @param string $contactType
655 * @param bool $status
656 *
a6c01b45
CW
657 * @return array
658 * array of importable Fields
6a488035 659 */
00be9182 660 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
6a488035
TO
661 if (!self::$_importableFields) {
662 if (!self::$_importableFields) {
66d5d6f4 663 self::$_importableFields = [];
6a488035
TO
664 }
665
666 if (!$status) {
66d5d6f4 667 $fields = ['' => ['title' => ts('- do not import -')]];
6a488035
TO
668 }
669 else {
66d5d6f4 670 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
6a488035
TO
671 }
672
673 $note = CRM_Core_DAO_Note::import();
674 $tmpFields = CRM_Contribute_DAO_Contribution::import();
675 unset($tmpFields['option_value']);
676 $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
c2585c5b 677 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
6a488035
TO
678
679 // Using new Dedupe rule.
66d5d6f4 680 $ruleParams = [
c2585c5b 681 'contact_type' => $contactType,
f2b2a3ff 682 'used' => 'Unsupervised',
66d5d6f4 683 ];
6a488035 684 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
66d5d6f4 685 $tmpContactField = [];
6a488035
TO
686 if (is_array($fieldsArray)) {
687 foreach ($fieldsArray as $value) {
688 //skip if there is no dupe rule
689 if ($value == 'none') {
690 continue;
691 }
692 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
693 $value,
694 'id',
695 'column_name'
696 );
697 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
c2585c5b 698 $tmpContactField[trim($value)] = $contactFields[trim($value)];
6a488035 699 if (!$status) {
c2585c5b 700 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
6a488035
TO
701 }
702 else {
c2585c5b 703 $title = $tmpContactField[trim($value)]['title'];
6a488035 704 }
c2585c5b 705 $tmpContactField[trim($value)]['title'] = $title;
6a488035
TO
706 }
707 }
708
c2585c5b 709 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
710 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
6a488035 711 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
c2585c5b 712 $fields = array_merge($fields, $tmpContactField);
6a488035
TO
713 $fields = array_merge($fields, $tmpFields);
714 $fields = array_merge($fields, $note);
715 $fields = array_merge($fields, $optionFields);
716 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export());
717 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
718 self::$_importableFields = $fields;
719 }
720 return self::$_importableFields;
721 }
722
186c9c17 723 /**
e9ff5391 724 * Combine all the exportable fields from the lower level objects.
725 *
726 * @param bool $checkPermission
727 *
186c9c17 728 * @return array
e9ff5391 729 * array of exportable Fields
186c9c17 730 */
5837835b 731 public static function &exportableFields($checkPermission = TRUE) {
6a488035
TO
732 if (!self::$_exportableFields) {
733 if (!self::$_exportableFields) {
66d5d6f4 734 self::$_exportableFields = [];
6a488035
TO
735 }
736
c8dd6301 737 $fields = CRM_Contribute_DAO_Contribution::export();
738 if (CRM_Contribute_BAO_Query::isSiteHasProducts()) {
739 $fields = array_merge(
740 $fields,
741 CRM_Contribute_DAO_Product::export(),
742 CRM_Contribute_DAO_ContributionProduct::export(),
743 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
744 [
745 'contribution_product_id' => [
746 'title' => ts('Premium'),
747 'name' => 'contribution_product_id',
748 'where' => 'civicrm_product.id',
749 'data_type' => CRM_Utils_Type::T_INT,
750 ],
751 ]
752 );
753 }
b55d81b4 754
f2b2a3ff 755 $financialAccount = CRM_Financial_DAO_FinancialAccount::export();
6a488035 756
66d5d6f4 757 $contributionPage = [
758 'contribution_page' => [
3c151c70 759 'title' => ts('Contribution Page'),
760 'name' => 'contribution_page',
761 'where' => 'civicrm_contribution_page.title',
a130e045 762 'data_type' => CRM_Utils_Type::T_STRING,
66d5d6f4 763 ],
764 ];
3c151c70 765
66d5d6f4 766 $contributionNote = [
767 'contribution_note' => [
a130e045
DG
768 'title' => ts('Contribution Note'),
769 'name' => 'contribution_note',
770 'data_type' => CRM_Utils_Type::T_TEXT,
66d5d6f4 771 ],
772 ];
6a488035 773
66d5d6f4 774 $extraFields = [
775 'contribution_batch' => [
21dfd5f5 776 'title' => ts('Batch Name'),
66d5d6f4 777 ],
778 ];
6a488035 779
124b978e 780 // CRM-17787
66d5d6f4 781 $campaignTitle = [
782 'contribution_campaign_title' => [
124b978e
WA
783 'title' => ts('Campaign Title'),
784 'name' => 'campaign_title',
785 'where' => 'civicrm_campaign.title',
786 'data_type' => CRM_Utils_Type::T_STRING,
66d5d6f4 787 ],
788 ];
789 $softCreditFields = [
790 'contribution_soft_credit_name' => [
81ec6180 791 'name' => 'contribution_soft_credit_name',
e300cf31 792 'title' => ts('Soft Credit For'),
81ec6180 793 'where' => 'civicrm_contact_d.display_name',
21dfd5f5 794 'data_type' => CRM_Utils_Type::T_STRING,
66d5d6f4 795 ],
796 'contribution_soft_credit_amount' => [
81ec6180 797 'name' => 'contribution_soft_credit_amount',
e300cf31 798 'title' => ts('Soft Credit Amount'),
81ec6180 799 'where' => 'civicrm_contribution_soft.amount',
21dfd5f5 800 'data_type' => CRM_Utils_Type::T_MONEY,
66d5d6f4 801 ],
802 'contribution_soft_credit_type' => [
81ec6180 803 'name' => 'contribution_soft_credit_type',
e300cf31 804 'title' => ts('Soft Credit Type'),
81ec6180 805 'where' => 'contribution_softcredit_type.label',
21dfd5f5 806 'data_type' => CRM_Utils_Type::T_STRING,
66d5d6f4 807 ],
808 'contribution_soft_credit_contribution_id' => [
81ec6180 809 'name' => 'contribution_soft_credit_contribution_id',
e300cf31 810 'title' => ts('Soft Credit For Contribution ID'),
81ec6180 811 'where' => 'civicrm_contribution_soft.contribution_id',
21dfd5f5 812 'data_type' => CRM_Utils_Type::T_INT,
66d5d6f4 813 ],
814 'contribution_soft_credit_contact_id' => [
5850d2e9 815 'name' => 'contribution_soft_credit_contact_id',
e300cf31 816 'title' => ts('Soft Credit For Contact ID'),
9a74243e 817 'where' => 'civicrm_contact_d.id',
5850d2e9 818 'data_type' => CRM_Utils_Type::T_INT,
66d5d6f4 819 ],
820 ];
81ec6180 821
b55d81b4 822 $fields = array_merge($fields, $contributionPage,
c8dd6301 823 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
5837835b 824 CRM_Core_BAO_CustomField::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
6a488035
TO
825 );
826
827 self::$_exportableFields = $fields;
828 }
829
830 return self::$_exportableFields;
831 }
832
3d6a264e 833 /**
f59c3d85 834 * Record an activity when a payment is received.
835 *
836 * @todo this is intended to be moved to payment BAO class as a protected function
837 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
838 * merit it's own function as it makes the code less rather than more readable.
839 *
840 * @param int $contributionId
841 * @param int $participantId
842 * @param string $totalAmount
843 * @param string $currency
844 * @param string $trxnDate
3d6a264e 845 *
f59c3d85 846 * @throws \CRM_Core_Exception
847 * @throws \CiviCRM_API3_Exception
3d6a264e 848 */
957655fe 849 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
f59c3d85 850 $activityType = ($totalAmount < 0) ? 'Refund' : 'Payment';
851
3d6a264e 852 if ($participantId) {
853 $inputParams['id'] = $participantId;
854 $values = [];
855 $ids = [];
3d6a264e 856 $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
857 $entityObj = $entityObj[$participantId];
f6044c2b 858 $title = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title');
3d6a264e 859 }
860 else {
861 $entityObj = new CRM_Contribute_BAO_Contribution();
862 $entityObj->id = $contributionId;
863 $entityObj->find(TRUE);
f6044c2b 864 $title = ts('Contribution');
3d6a264e 865 }
f59c3d85 866 // @todo per block above this is not a logical splitting off of functionality.
867 self::addActivityForPayment($entityObj->contact_id, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
3d6a264e 868 }
869
6cbecbad 870 /**
871 * Get the value for the To Financial Account.
872 *
873 * @param $contribution
874 * @param $params
875 *
876 * @return int
877 */
88a20030 878 public static function getToFinancialAccount($contribution, $params) {
6cc6cb8c 879 if (!empty($params['payment_processor_id'])) {
880 return CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
6cbecbad 881 }
362f37fc 882 if (!empty($params['payment_instrument_id'])) {
6cbecbad 883 return CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
884 }
885 else {
886 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
887 $queryParams = [1 => [$relationTypeId, 'Integer']];
888 return CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
889 }
890 }
891
5ed12039 892 /**
bb088986 893 * Get memberships related to the contribution.
5ed12039 894 *
895 * @param int $contributionID
896 *
897 * @return array
898 */
899 protected static function getRelatedMemberships($contributionID) {
72d57998 900 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
901 'return' => 'membership_id',
902 'contribution_id' => (int) $contributionID,
903 ])['values'];
904 $membershipIDs = [];
905 foreach ($membershipPayments as $membershipPayment) {
906 $membershipIDs[] = $membershipPayment['membership_id'];
907 }
908 if (empty($membershipIDs)) {
909 return [];
910 }
911 // We could combine this with the MembershipPayment.get - we'd
912 // need to re-wrangle the params (here or in the calling function)
913 // as they would then me membership.contact_id, membership.is_test etc
914 return civicrm_api3('Membership', 'get', [
915 'id' => ['IN' => $membershipIDs],
7365dd7f 916 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
72d57998 917 ])['values'];
5ed12039 918 }
919
1ee67fa2 920 /**
921 * Cancel contribution.
922 *
923 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
924 *
925 * @param $processContributionObject
926 * @param $memberships
927 * @param $contributionId
928 * @param $membershipStatuses
929 * @param $updateResult
930 * @param $participant
931 * @param $oldStatus
932 * @param $pledgePayment
933 * @param $pledgeID
934 * @param $pledgePaymentIDs
935 * @param $contributionStatusId
66d5d6f4 936 *
1ee67fa2 937 * @return array
938 */
939 protected static function cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
e143136a 940 // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it
1ee67fa2 941 $processContribution = FALSE;
942 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
943 if (is_array($memberships)) {
944 foreach ($memberships as $membership) {
945 $update = TRUE;
946 //Update Membership status if there is no other completed contribution associated with the membership.
947 $relatedContributions = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id, TRUE);
948 foreach ($relatedContributions as $contriId) {
949 if ($contriId == $contributionId) {
950 continue;
951 }
952 $statusId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
953 if (CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
954 $update = FALSE;
955 }
956 }
957 if ($membership && $update) {
958 $newStatus = array_search('Cancelled', $membershipStatuses);
959
960 // Create activity
961 $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get');
962 $activityParam = [
963 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
964 'source_contact_id' => CRM_Core_Session::singleton()->get('userID'),
965 'target_contact_id' => $membership->contact_id,
966 'source_record_id' => $membership->id,
967 'activity_type_id' => 'Change Membership Status',
968 'status_id' => 'Completed',
969 'priority_id' => 'Normal',
970 'activity_date_time' => 'now',
971 ];
972
973 $membership->status_id = $newStatus;
974 $membership->is_override = TRUE;
975 $membership->status_override_end_date = 'null';
976 $membership->save();
977 civicrm_api3('activity', 'create', $activityParam);
978
979 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
980 if ($processContributionObject) {
981 $processContribution = TRUE;
982 }
983 }
984 }
985 }
986
987 if ($participant) {
988 $updatedStatusId = array_search('Cancelled', $participantStatuses);
989 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
990
991 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
992 if ($processContributionObject) {
993 $processContribution = TRUE;
994 }
995 }
996
997 if ($pledgePayment) {
998 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
999
1000 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1001 if ($processContributionObject) {
1002 $processContribution = TRUE;
1003 }
1004 }
1005 return [$updateResult, $processContribution];
1006 }
1007
e85f6b6b 1008 /**
1009 * Do any accounting updates required as a result of a contribution status change.
1010 *
1011 * Currently we have a bit of a roundabout where adding a payment results in this being called &
1012 * this may attempt to add a payment. We need to resolve that....
1013 *
1014 * The 'right' way to add payments or refunds is through the Payment.create api. That api
1015 * then updates the contribution but this process should not also record another financial trxn.
1016 * Currently we have weak detection fot that scenario & where it is detected the first returned
1017 * value is FALSE - meaning 'do not continue'.
1018 *
1019 * We should also look at the fact that the calling function - updateFinancialAccounts
1020 * bunches together some disparate processes rather than having separate appropriate
1021 * functions.
1022 *
1023 * @param array $params
e85f6b6b 1024 *
05a42c4a 1025 * @return bool
1026 * Return indicates whether the updateFinancialAccounts function should continue.
e85f6b6b 1027 */
666f314b 1028 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
3edf9a49 1029 $previousContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['prevContribution']->contribution_status_id, 'name');
1030 $currentContributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id);
1031
e85f6b6b 1032 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
1033 || ($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
1034 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1035 // why it is here or where it is handled instead.
1036 || ($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later == TRUE
1037 && $currentContributionStatus == 'Partially paid'))
1038 ) {
05a42c4a 1039 return FALSE;
e85f6b6b 1040 }
666f314b 1041
05a42c4a 1042 if (self::isContributionUpdateARefund($params['prevContribution']->contribution_status_id, $params['contribution']->contribution_status_id)) {
666f314b 1043 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1044 $params['trxnParams']['total_amount'] = -$params['total_amount'];
666f314b 1045 }
1046 elseif (($previousContributionStatus == 'Pending'
1047 && $params['prevContribution']->is_pay_later) || $previousContributionStatus == 'In Progress'
1048 ) {
e71c1326 1049 $financialTypeID = !empty($params['financial_type_id']) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
666f314b 1050 $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1051
1052 if ($currentContributionStatus == 'Cancelled') {
e85f6b6b 1053 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
666f314b 1054 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
e85f6b6b 1055 $params['trxnParams']['total_amount'] = -$params['total_amount'];
e85f6b6b 1056 }
666f314b 1057 else {
1058 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1059 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
e85f6b6b 1060 }
666f314b 1061 }
e85f6b6b 1062
666f314b 1063 if (($previousContributionStatus == 'Pending'
1064 || $previousContributionStatus == 'In Progress')
1065 && ($currentContributionStatus == 'Completed')
1066 ) {
1067 if (empty($params['line_item'])) {
1068 //CRM-15296
1069 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1070 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1071 // & this can be removed
05a42c4a 1072 return FALSE;
666f314b 1073 }
1074 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1075 // This is an update so original currency if none passed in.
1076 $params['trxnParams']['currency'] = CRM_Utils_Array::value('currency', $params, $params['prevContribution']->currency);
e85f6b6b 1077
666f314b 1078 self::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1079 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
1080 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1081 $params['entity_id'] = self::$_trxnIDs[] = $trxn->id;
099f5435 1082
666f314b 1083 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
e85f6b6b 1084
666f314b 1085 $entityParams = [
1086 'entity_table' => 'civicrm_financial_item',
1087 ];
1088 foreach ($params['line_item'] as $fieldId => $fields) {
1089 foreach ($fields as $fieldValueId => $lineItemDetails) {
099f5435 1090 self::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
666f314b 1091 $fparams = [
1092 1 => [$lineItemDetails['id'], 'Integer'],
1093 ];
1094 $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams);
1095 while ($financialItem->fetch()) {
1096 $entityParams['entity_id'] = $financialItem->id;
1097 $entityParams['amount'] = $financialItem->amount;
1098 foreach (self::$_trxnIDs as $tID) {
1099 $entityParams['financial_trxn_id'] = $tID;
1100 CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams);
e85f6b6b 1101 }
1102 }
1103 }
e85f6b6b 1104 }
05a42c4a 1105 return FALSE;
e85f6b6b 1106 }
05a42c4a 1107 return TRUE;
e85f6b6b 1108 }
1109
fefee636 1110 /**
1111 * It is possible to override the membership id that is updated from the payment processor.
1112 *
1113 * Historically Paypal does this & it still does if it determines data is messed up - see
1114 * https://lab.civicrm.org/dev/membership/issues/13
1115 *
1116 * Read the comment block on repeattransaction for more information
1117 * about how things should work.
1118 *
1119 * @param int $contributionID
1120 * @param array $input
1121 *
1122 * @throws \CiviCRM_API3_Exception
1123 */
1124 protected static function handleMembershipIDOverride($contributionID, $input) {
1125 if (!empty($input['membership_id'])) {
1126 Civi::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1127 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1128 }
1129 }
1130
099f5435 1131 /**
1132 * Update all financial items related to the line item tto have a status of paid.
1133 *
1134 * @param int $lineItemID
1135 */
1136 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1137 $fparams = [
1138 1 => [
1139 CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1140 'Integer',
1141 ],
1142 2 => [$lineItemID, 'Integer'],
1143 ];
1144 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1145 CRM_Core_DAO::executeQuery($query, $fparams);
1146 }
1147
592a64a0 1148 /**
1149 * Create the financial items for the line.
1150 *
1151 * @param array $params
1152 * @param string $context
1153 * @param array $fields
1154 * @param array $previousLineItems
1155 * @param array $inputParams
1156 * @param bool $isARefund
1157 * @param array $trxnIds
1158 * @param int $fieldId
1159 *
1160 * @return array
1161 */
1162 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1163 foreach ($fields as $fieldValueId => $lineItemDetails) {
1164 $prevFinancialItem = CRM_Financial_BAO_FinancialItem::getPreviousFinancialItem($lineItemDetails['id']);
1165 $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date);
1166 if ($params['contribution']->receive_date) {
1167 $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date);
1168 }
1169
1170 $financialAccount = self::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array::value('financial_account_id', $prevFinancialItem));
1171
1172 $currency = $params['prevContribution']->currency;
1173 if ($params['contribution']->currency) {
1174 $currency = $params['contribution']->currency;
1175 }
1176 $previousLineItemTotal = CRM_Utils_Array::value('line_total', CRM_Utils_Array::value($fieldValueId, $previousLineItems), 0);
1177 $itemParams = [
1178 'transaction_date' => $receiveDate,
1179 'contact_id' => $params['prevContribution']->contact_id,
1180 'currency' => $currency,
1181 'amount' => self::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
6b409353 1182 'description' => $prevFinancialItem['description'] ?? NULL,
592a64a0 1183 'status_id' => $prevFinancialItem['status_id'],
1184 'financial_account_id' => $financialAccount,
1185 'entity_table' => 'civicrm_line_item',
1186 'entity_id' => $lineItemDetails['id'],
1187 ];
1188 $financialItem = CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
1189 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1190 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id;
1191
1192 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') || ($context == 'changeFinancialType')) {
1193 $taxAmount = (float) $lineItemDetails['tax_amount'];
1194 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1195 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1196 $taxAmount = CRM_Utils_Array::value('tax_amount', CRM_Utils_Array::value($fieldValueId, $previousLineItems), 0);
1197 }
1198 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1199 $taxAmount -= CRM_Utils_Array::value('tax_amount', CRM_Utils_Array::value($fieldValueId, $previousLineItems), 0);
1200 }
1201 if ($taxAmount != 0) {
1202 $itemParams['amount'] = self::getMultiplier($params['contribution']->contribution_status_id, $context) * $taxAmount;
1203 $itemParams['description'] = CRM_Invoicing_Utils::getTaxTerm();
1204 if ($lineItemDetails['financial_type_id']) {
1205 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1206 }
1207 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
1208 }
1209 }
1210 }
1211 return $params;
1212 }
1213
05a42c4a 1214 /**
1215 * Does this contributtion status update represent a refund.
1216 *
1217 * @param int $previousContributionStatusID
1218 * @param int $currentContributionStatusID
1219 *
1220 * @return bool
1221 */
1222 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1223 if ('Completed' !== CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1224 return FALSE;
1225 }
1226 return self::isContributionStatusNegative($currentContributionStatusID);
1227 }
1228
c086e797 1229 /**
1230 * Get transaction information about the contribution.
1231 *
1232 * @param int $contributionId
1233 * @param int $financialTypeID
1234 *
1235 * @return mixed
1236 */
1237 protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) {
1238 $rows = [];
1239 $feeFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeID, 'Expense Account is');
1240
1241 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
1242 $sql = "
1243 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
1244 ft.total_amount,
1245 ft.payment_instrument_id,
1246 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
1247
1248 FROM civicrm_contribution con
1249 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
1250 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
1251 AND ft.to_financial_account_id != %2
1252 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
1253 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
1254 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
1255
1256 WHERE con.id = %1 AND ft.is_payment = 1
1257 GROUP BY ft.id";
1258 $queryParams = [
1259 1 => [$contributionId, 'Integer'],
1260 2 => [$feeFinancialAccount, 'Integer'],
1261 ];
1262 $resultDAO = CRM_Core_DAO::executeQuery($sql, $queryParams);
1263 $statuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label');
1264
1265 while ($resultDAO->fetch()) {
1266 $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
1267 $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
1268 if ($resultDAO->card_type_id) {
1269 $creditCardType = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id);
1270 $pantruncation = '';
1271 if ($resultDAO->pan_truncation) {
1272 $pantruncation = ": {$resultDAO->pan_truncation}";
1273 }
1274 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
1275 }
1276
1277 // show payment edit link only for payments done via backoffice form
1278 $paymentEditLink = '';
1279 if (empty($resultDAO->payment_processor_id) && CRM_Core_Permission::check('edit contributions')) {
1280 $links = [
1281 CRM_Core_Action::UPDATE => [
cc71b2ea
AH
1282 'name' => ts('Edit Payment'),
1283 'icon' => 'fa-pencil',
c086e797 1284 'url' => 'civicrm/payment/edit',
1285 'class' => 'medium-popup',
1286 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
1287 'title' => ts('Edit Payment'),
1288 ],
1289 ];
1290 $paymentEditLink = CRM_Core_Action::formLink(
1291 $links,
1292 CRM_Core_Action::mask([CRM_Core_Permission::EDIT]),
1293 [
1294 'id' => $resultDAO->id,
1295 'contribution_id' => $contributionId,
1296 ],
1297 ts('more'),
1298 FALSE,
1299 'Payment.edit.action',
1300 'Payment',
7261f9ca
AH
1301 $resultDAO->id,
1302 'icon'
c086e797 1303 );
1304 }
1305
1306 $val = [
1307 'id' => $resultDAO->id,
1308 'total_amount' => $resultDAO->total_amount,
1309 'financial_type' => $resultDAO->financial_account,
1310 'payment_instrument' => $paidByLabel,
1311 'receive_date' => $resultDAO->trxn_date,
1312 'trxn_id' => $resultDAO->trxn_id,
1313 'status' => $statuses[$resultDAO->status_id],
1314 'currency' => $resultDAO->currency,
1315 'action' => $paymentEditLink,
1316 ];
1317 if ($paidByName == 'Check') {
1318 $val['check_number'] = $resultDAO->check_number;
1319 }
1320 $rows[] = $val;
1321 }
1322 return $rows;
1323 }
1324
68dce20c 1325 /**
1326 * Should an email receipt be sent for this contribution on completion.
1327 *
1328 * @param array $input
1329 * @param int $contributionPageID
1330 * @param int $recurringContributionID
1331 *
1332 * @return bool
1333 * @throws \API_Exception
1334 * @throws \Civi\API\Exception\UnauthorizedException
1335 */
1336 protected static function isEmailReceipt(array $input, $contributionPageID, $recurringContributionID): bool {
1337 if (isset($input['is_email_receipt'])) {
1338 return (bool) $input['is_email_receipt'];
1339 }
1340 if ($recurringContributionID) {
1341 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
1342 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
1343 // dev/core#1245 this maybe not the desired effect because the default value for is_email_receipt is set to 0 rather than 1 in
1344 // Instance that had the table added via an upgrade in 4.1
1345 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
1346 // https://lab.civicrm.org/dev/core/issues/1245
1347 return (bool) ContributionRecur::get(FALSE)->addWhere('id', '=', $recurringContributionID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1348 }
1349 if ($contributionPageID) {
1350 return (bool) ContributionPage::get(FALSE)->addWhere('id', '=', $contributionPageID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1351 }
1352 // This would be the case for backoffice (where is_email_receipt is not passed in) or events, where Event::sendMail will filter
1353 // again anyway.
1354 return TRUE;
1355 }
1356
0dcc88fc 1357 /**
1358 * Process failed contribution.
1359 *
1360 * @param $processContributionObject
1361 * @param $memberships
1362 * @param $contributionId
1363 * @param array $membershipStatuses
1364 * @param array $updateResult
1365 * @param $participant
1366 * @param $pledgePayment
1367 * @param $pledgeID
1368 * @param array $pledgePaymentIDs
1369 * @param $contributionStatusId
1370 *
1371 * @return array
1372 * @throws \CRM_Core_Exception
1373 */
1374 protected static function processFail($processContributionObject, $memberships, $contributionId, array $membershipStatuses, array $updateResult, $participant, $pledgePayment, $pledgeID, array $pledgePaymentIDs, $contributionStatusId): array {
1375 $processContribution = FALSE;
1376 if (is_array($memberships)) {
1377 foreach ($memberships as $membership) {
1378 $update = TRUE;
1379 //Update Membership status if there is no other completed contribution associated with the membership.
1380 $relatedContributions = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id, TRUE);
1381 foreach ($relatedContributions as $contriId) {
1382 if ($contriId == $contributionId) {
1383 continue;
1384 }
1385 $statusId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1386 if (CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1387 $update = FALSE;
1388 }
1389 }
1390 if ($membership && $update) {
1391 $membership->status_id = array_search('Expired', $membershipStatuses);
1392 $membership->is_override = TRUE;
1393 $membership->status_override_end_date = 'null';
1394 $membership->save();
1395
1396 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1397 if ($processContributionObject) {
1398 $processContribution = TRUE;
1399 }
1400 }
1401 }
1402 }
1403 if ($participant) {
1404 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1405 $participant->id,
1406 'status_id'
1407 );
1408 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1409 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1410 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1411
1412 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1413 if ($processContributionObject) {
1414 $processContribution = TRUE;
1415 }
1416 }
1417
1418 if ($pledgePayment) {
1419 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1420
1421 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1422 if ($processContributionObject) {
1423 $processContribution = TRUE;
1424 }
1425 }
1426 return [$updateResult, $processContribution];
1427 }
1428
61076736 1429 /**
1430 * @inheritDoc
1431 */
1432 public function addSelectWhereClause() {
1433 $whereClauses = parent::addSelectWhereClause();
1434 if ($whereClauses !== []) {
1435 // In this case permisssions have been applied & we assume the
1436 // financialaclreport is applying these
1437 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1438 return $whereClauses;
1439 }
1440
1441 if (!CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
1442 return $whereClauses;
1443 }
1444 $types = CRM_Financial_BAO_FinancialType::getAllEnabledAvailableFinancialTypes();
1445 if (empty($types)) {
1446 $whereClauses['financial_type_id'] = 'IN (0)';
1447 }
1448 else {
1449 $whereClauses['financial_type_id'] = [
1330f57a 1450 'IN (' . implode(',', array_keys($types)) . ')',
61076736 1451 ];
1452 }
1453 return $whereClauses;
1454 }
1455
186c9c17
EM
1456 /**
1457 * @param null $status
1458 * @param null $startDate
1459 * @param null $endDate
1460 *
1461 * @return array|null
1462 */
00be9182 1463 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
66d5d6f4 1464 $where = [];
6a488035
TO
1465 switch ($status) {
1466 case 'Valid':
1467 $where[] = 'contribution_status_id = 1';
1468 break;
1469
1470 case 'Cancelled':
1471 $where[] = 'contribution_status_id = 3';
1472 break;
1473 }
1474
1475 if ($startDate) {
1476 $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
1477 }
1478 if ($endDate) {
1479 $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
1480 }
370b4d88 1481 $financialTypeACLJoin = '';
1482 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
1483 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1484 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
1485 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
1486 if ($financialTypes) {
1487 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1488 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1489 }
1490 else {
1491 $where[] = "c.financial_type_id IN (0)";
1492 }
54d8de6b 1493 }
6a488035
TO
1494
1495 $whereCond = implode(' AND ', $where);
1496
1497 $query = "
1498 SELECT sum( total_amount ) as total_amount,
54d8de6b 1499 count( c.id ) as total_count,
6a488035 1500 currency
54d8de6b
E
1501 FROM civicrm_contribution c
1502INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
370b4d88 1503 $financialTypeACLJoin
6a488035
TO
1504 WHERE $whereCond
1505 AND ( is_test = 0 OR is_test IS NULL )
1506 AND contact.is_deleted = 0
1507 GROUP BY currency
1508";
1509
9d2678f4 1510 $dao = CRM_Core_DAO::executeQuery($query);
66d5d6f4 1511 $amount = [];
f2b2a3ff 1512 $count = 0;
6a488035
TO
1513 while ($dao->fetch()) {
1514 $count += $dao->total_count;
1515 $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
1516 }
1517 if ($count) {
66d5d6f4 1518 return [
f2b2a3ff 1519 'amount' => implode(', ', $amount),
6a488035 1520 'count' => $count,
66d5d6f4 1521 ];
6a488035
TO
1522 }
1523 return NULL;
1524 }
1525
1526 /**
fe482240 1527 * Delete the indirect records associated with this contribution first.
6a488035 1528 *
100fef9d 1529 * @param int $id
8efea814 1530 *
72b3a70c
CW
1531 * @return mixed|null
1532 * $results no of deleted Contribution on success, false otherwise
6a488035 1533 */
00be9182 1534 public static function deleteContribution($id) {
6a488035
TO
1535 CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray);
1536
1537 $transaction = new CRM_Core_Transaction();
1538
1539 $results = NULL;
1540 //delete activity record
66d5d6f4 1541 $params = [
6a488035
TO
1542 'source_record_id' => $id,
1543 // activity type id for contribution
1544 'activity_type_id' => 6,
66d5d6f4 1545 ];
6a488035
TO
1546
1547 CRM_Activity_BAO_Activity::deleteActivity($params);
1548
1549 //delete billing address if exists for this contribution.
1550 self::deleteAddress($id);
1551
1552 //update pledge and pledge payment, CRM-3961
1553 CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id);
1554
1555 // remove entry from civicrm_price_set_entity, CRM-5095
9da8dc8c 1556 if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) {
1557 CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id);
6a488035
TO
1558 }
1559 // cleanup line items.
1560 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1561
de1c25e1
PN
1562 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1563 CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id);
6a488035
TO
1564
1565 if ($participantId) {
1566 CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant');
1567 }
1568 else {
1569 CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution');
1570 }
1571
1572 //delete note.
1573 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution');
1574 $noteId = key($note);
1575 if ($noteId) {
1576 CRM_Core_BAO_Note::del($noteId, FALSE);
1577 }
1578
1579 $dao = new CRM_Contribute_DAO_Contribution();
1580 $dao->id = $id;
1581
1582 $results = $dao->delete();
1583
1584 $transaction->commit();
1585
1586 CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao);
1587
1588 // delete the recently created Contribution
66d5d6f4 1589 $contributionRecent = [
6a488035
TO
1590 'id' => $id,
1591 'type' => 'Contribution',
66d5d6f4 1592 ];
6a488035
TO
1593 CRM_Utils_Recent::del($contributionRecent);
1594
1595 return $results;
1596 }
1597
7758bd2b
EM
1598 /**
1599 * React to a financial transaction (payment) failure.
1600 *
1601 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1602 * payments is important for forensic and outreach reasons.
1603 *
06d062ce 1604 * @param int $contributionID
ad37ac8e 1605 * @param int $contactID
06d062ce 1606 * @param string $message
ad37ac8e 1607 *
1608 * @throws \CiviCRM_API3_Exception
7758bd2b 1609 */
06d062ce 1610 public static function failPayment($contributionID, $contactID, $message) {
66d5d6f4 1611 civicrm_api3('activity', 'create', [
06d062ce
EM
1612 'activity_type_id' => 'Failed Payment',
1613 'details' => $message,
1614 'subject' => ts('Payment failed at payment processor'),
1615 'source_record_id' => $contributionID,
66d5d6f4 1616 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : $contactID,
1617 ]);
ee165a1c
ML
1618
1619 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
66d5d6f4 1620 civicrm_api3('contribution', 'create', [
ee165a1c 1621 'id' => $contributionID,
d7b226af 1622 'contribution_status_id' => 'Failed',
66d5d6f4 1623 ]);
7758bd2b
EM
1624 }
1625
6a488035 1626 /**
fe482240 1627 * Check if there is a contribution with the same trxn_id or invoice_id.
6a488035 1628 *
014c4014
TO
1629 * @param array $input
1630 * An assoc array of name/value pairs.
1631 * @param array $duplicates
16b10e64 1632 * (reference) store ids of duplicate contribs.
100fef9d 1633 * @param int $id
6a488035 1634 *
a130e045 1635 * @return bool
a6c01b45 1636 * true if duplicate, false otherwise
6a488035 1637 */
00be9182 1638 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
6a488035 1639 if (!$id) {
9c1bc317 1640 $id = $input['id'] ?? NULL;
6a488035 1641 }
9c1bc317
CW
1642 $trxn_id = $input['trxn_id'] ?? NULL;
1643 $invoice_id = $input['invoice_id'] ?? NULL;
6a488035 1644
66d5d6f4 1645 $clause = [];
1646 $input = [];
6a488035
TO
1647
1648 if ($trxn_id) {
1649 $clause[] = "trxn_id = %1";
66d5d6f4 1650 $input[1] = [$trxn_id, 'String'];
6a488035
TO
1651 }
1652
1653 if ($invoice_id) {
1654 $clause[] = "invoice_id = %2";
66d5d6f4 1655 $input[2] = [$invoice_id, 'String'];
6a488035
TO
1656 }
1657
1658 if (empty($clause)) {
1659 return FALSE;
1660 }
1661
1662 $clause = implode(' OR ', $clause);
1663 if ($id) {
1664 $clause = "( $clause ) AND id != %3";
66d5d6f4 1665 $input[3] = [$id, 'Integer'];
6a488035
TO
1666 }
1667
f2b2a3ff
TO
1668 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1669 $dao = CRM_Core_DAO::executeQuery($query, $input);
6a488035
TO
1670 $result = FALSE;
1671 while ($dao->fetch()) {
1672 $duplicates[] = $dao->id;
1673 $result = TRUE;
1674 }
1675 return $result;
1676 }
1677
1678 /**
fe482240 1679 * Takes an associative array and creates a contribution_product object.
6a488035
TO
1680 *
1681 * the function extract all the params it needs to initialize the create a
1682 * contribution_product object. the params array could contain additional unused name/value
1683 * pairs
1684 *
014c4014 1685 * @param array $params
16b10e64 1686 * (reference) an assoc array of name/value pairs.
6a488035 1687 *
16b10e64 1688 * @return CRM_Contribute_DAO_ContributionProduct
6a488035 1689 */
00be9182 1690 public static function addPremium(&$params) {
6a488035
TO
1691 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1692 $contributionProduct->copyValues($params);
1693 return $contributionProduct->save();
1694 }
1695
1696 /**
fe482240 1697 * Get list of contribution fields for profile.
6a488035
TO
1698 * For now we only allow custom contribution fields to be in
1699 * profile
1700 *
014c4014
TO
1701 * @param bool $addExtraFields
1702 * True if special fields needs to be added.
6a488035 1703 *
a6c01b45
CW
1704 * @return array
1705 * the list of contribution fields
6a488035 1706 */
00be9182 1707 public static function getContributionFields($addExtraFields = TRUE) {
6a488035 1708 $contributionFields = CRM_Contribute_DAO_Contribution::export();
9d5c7f14 1709 // @todo remove this - this line was added because payment_instrument_id was not
1710 // set to exportable - but now it is.
6a488035
TO
1711 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute'));
1712
1713 if ($addExtraFields) {
1714 $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields());
1715 }
1716
1717 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export());
1718
1719 foreach ($contributionFields as $key => $var) {
1720 if ($key == 'contribution_contact_id') {
1721 continue;
1722 }
1723 elseif ($key == 'contribution_campaign_id') {
1724 $var['title'] = ts('Campaign');
1725 }
1726 $fields[$key] = $var;
1727 }
1728
1729 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
1730 return $fields;
1731 }
1732
1733 /**
74ab7ba8 1734 * Add extra fields specific to contribution.
6a488035 1735 */
00be9182 1736 public static function getSpecialContributionFields() {
66d5d6f4 1737 $extraFields = [
1738 'contribution_soft_credit_name' => [
81ec6180 1739 'name' => 'contribution_soft_credit_name',
e300cf31 1740 'title' => ts('Soft Credit Name'),
6a488035
TO
1741 'headerPattern' => '/^soft_credit_name$/i',
1742 'where' => 'civicrm_contact_d.display_name',
66d5d6f4 1743 ],
1744 'contribution_soft_credit_email' => [
81ec6180 1745 'name' => 'contribution_soft_credit_email',
e300cf31 1746 'title' => ts('Soft Credit Email'),
6a488035
TO
1747 'headerPattern' => '/^soft_credit_email$/i',
1748 'where' => 'soft_email.email',
66d5d6f4 1749 ],
1750 'contribution_soft_credit_phone' => [
81ec6180 1751 'name' => 'contribution_soft_credit_phone',
e300cf31 1752 'title' => ts('Soft Credit Phone'),
6a488035
TO
1753 'headerPattern' => '/^soft_credit_phone$/i',
1754 'where' => 'soft_phone.phone',
66d5d6f4 1755 ],
1756 'contribution_soft_credit_contact_id' => [
81ec6180 1757 'name' => 'contribution_soft_credit_contact_id',
e300cf31 1758 'title' => ts('Soft Credit Contact ID'),
6a488035
TO
1759 'headerPattern' => '/^soft_credit_contact_id$/i',
1760 'where' => 'civicrm_contribution_soft.contact_id',
66d5d6f4 1761 ],
1762 'contribution_pcp_title' => [
03ad81ae 1763 'name' => 'contribution_pcp_title',
e300cf31 1764 'title' => ts('Personal Campaign Page Title'),
03ad81ae
AH
1765 'headerPattern' => '/^contribution_pcp_title$/i',
1766 'where' => 'contribution_pcp.title',
66d5d6f4 1767 ],
1768 ];
6a488035
TO
1769
1770 return $extraFields;
1771 }
1772
186c9c17 1773 /**
100fef9d 1774 * @param int $pageID
186c9c17
EM
1775 *
1776 * @return array
1777 */
00be9182 1778 public static function getCurrentandGoalAmount($pageID) {
6a488035
TO
1779 $query = "
1780SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1781 FROM civicrm_contribution_page p,
1782 civicrm_contribution c
1783 WHERE p.id = c.contribution_page_id
1784 AND p.id = %1
1785 AND c.cancel_date is null
1786GROUP BY p.id
1787";
1788
1789 $config = CRM_Core_Config::singleton();
66d5d6f4 1790 $params = [1 => [$pageID, 'Integer']];
f2b2a3ff 1791 $dao = CRM_Core_DAO::executeQuery($query, $params);
6a488035
TO
1792
1793 if ($dao->fetch()) {
66d5d6f4 1794 return [$dao->goal, $dao->total];
6a488035
TO
1795 }
1796 else {
66d5d6f4 1797 return [NULL, NULL];
6a488035
TO
1798 }
1799 }
1800
6a488035 1801 /**
2449fe69 1802 * Get list of contributions which credit the passed in contact ID.
1803 *
1804 * The returned array provides details about the original contribution & donor.
1805 *
014c4014
TO
1806 * @param int $honorId
1807 * In Honor of Contact ID.
6a488035 1808 *
72b3a70c
CW
1809 * @return array
1810 * list of contribution fields
66d5d6f4 1811 * @todo - this is a confusing function called from one place. It has a test. It would be
1812 * nice to deprecate it.
1813 *
6a488035 1814 */
00be9182 1815 public static function getHonorContacts($honorId) {
66d5d6f4 1816 $params = [];
8381af80 1817 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1818 $honorDAO->contact_id = $honorId;
6a488035
TO
1819 $honorDAO->find();
1820
6a488035
TO
1821 $type = CRM_Contribute_PseudoConstant::financialType();
1822
1823 while ($honorDAO->fetch()) {
8381af80 1824 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1825 $contributionDAO->id = $honorDAO->contribution_id;
1826
1827 if ($contributionDAO->find(TRUE)) {
43321dd5 1828 $params[$contributionDAO->id]['honor_type'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id);
8381af80 1829 $params[$contributionDAO->id]['honorId'] = $contributionDAO->contact_id;
1830 $params[$contributionDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id, 'display_name');
1831 $params[$contributionDAO->id]['type'] = $type[$contributionDAO->financial_type_id];
1832 $params[$contributionDAO->id]['type_id'] = $contributionDAO->financial_type_id;
1833 $params[$contributionDAO->id]['amount'] = CRM_Utils_Money::format($contributionDAO->total_amount, $contributionDAO->currency);
1834 $params[$contributionDAO->id]['source'] = $contributionDAO->source;
1835 $params[$contributionDAO->id]['receive_date'] = $contributionDAO->receive_date;
28ee38ed 1836 $params[$contributionDAO->id]['contribution_status'] = CRM_Contribute_PseudoConstant::contributionStatus($contributionDAO->contribution_status_id, 'label');
8381af80 1837 }
6a488035
TO
1838 }
1839
1840 return $params;
1841 }
1842
1843 /**
fe482240 1844 * Get the sort name of a contact for a particular contribution.
6a488035 1845 *
014c4014
TO
1846 * @param int $id
1847 * Id of the contribution.
6a488035 1848 *
72b3a70c
CW
1849 * @return null|string
1850 * sort name of the contact if found
6a488035 1851 */
00be9182 1852 public static function sortName($id) {
6a488035
TO
1853 $id = CRM_Utils_Type::escape($id, 'Integer');
1854
1855 $query = "
1856SELECT civicrm_contact.sort_name
1857FROM civicrm_contribution, civicrm_contact
1858WHERE civicrm_contribution.contact_id = civicrm_contact.id
1859 AND civicrm_contribution.id = {$id}
1860";
9d2678f4 1861 return CRM_Core_DAO::singleValueQuery($query);
6a488035
TO
1862 }
1863
186c9c17 1864 /**
6b60d32c 1865 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1866 *
1867 * @param int|array $contactIDs
186c9c17
EM
1868 *
1869 * @return array
1870 */
6b60d32c 1871 public static function annual($contactIDs) {
1872 if (!is_array($contactIDs)) {
1873 // In practice I can't fine any evidence that this function is ever called with
1874 // anything other than a single contact id, but left like this due to .... fear.
1875 $contactIDs = explode(',', $contactIDs);
6a488035
TO
1876 }
1877
6b60d32c 1878 $query = self::getAnnualQuery($contactIDs);
33621c4f 1879 $dao = CRM_Core_DAO::executeQuery($query);
f2b2a3ff 1880 $count = 0;
66d5d6f4 1881 $amount = $average = [];
6a488035
TO
1882 while ($dao->fetch()) {
1883 if ($dao->count > 0 && $dao->amount > 0) {
1884 $count += $dao->count;
1885 $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency);
1886 $average[] = CRM_Utils_Money::format($dao->average, $dao->currency);
1887 }
1888 }
1889 if ($count > 0) {
66d5d6f4 1890 return [
6a488035
TO
1891 $count,
1892 implode(',&nbsp;', $amount),
1893 implode(',&nbsp;', $average),
66d5d6f4 1894 ];
6a488035 1895 }
66d5d6f4 1896 return [0, 0, 0];
6a488035
TO
1897 }
1898
1899 /**
1900 * Check if there is a contribution with the params passed in.
a380f4a0 1901 *
6a488035
TO
1902 * Used for trxn_id,invoice_id and contribution_id
1903 *
014c4014
TO
1904 * @param array $params
1905 * An assoc array of name/value pairs.
6a488035 1906 *
a6c01b45
CW
1907 * @return array
1908 * contribution id if success else NULL
6a488035 1909 */
00be9182 1910 public static function checkDuplicateIds($params) {
6a488035
TO
1911 $dao = new CRM_Contribute_DAO_Contribution();
1912
66d5d6f4 1913 $clause = [];
1914 $input = [];
6a488035
TO
1915 foreach ($params as $k => $v) {
1916 if ($v) {
1917 $clause[] = "$k = '$v'";
1918 }
1919 }
1920 $clause = implode(' AND ', $clause);
f2b2a3ff
TO
1921 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1922 $dao = CRM_Core_DAO::executeQuery($query, $input);
6a488035
TO
1923
1924 while ($dao->fetch()) {
1925 $result = $dao->id;
1926 return $result;
1927 }
1928 return NULL;
1929 }
1930
1931 /**
fe482240 1932 * Get the contribution details for component export.
6a488035 1933 *
014c4014
TO
1934 * @param int $exportMode
1935 * Export mode.
81716ddb 1936 * @param array $componentIds
014c4014 1937 * Component ids.
6a488035 1938 *
a6c01b45
CW
1939 * @return array
1940 * associated array
6a488035 1941 */
00be9182 1942 public static function getContributionDetails($exportMode, $componentIds) {
66d5d6f4 1943 $paymentDetails = [];
6a488035
TO
1944 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1945
1946 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
1947 $componentSelect = " civicrm_participant_payment.participant_id id";
1948 $additionalClause = "
1949INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1950AND civicrm_participant_payment.participant_id {$componentClause} )
1951";
1952 }
1953 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
1954 $componentSelect = " civicrm_membership_payment.membership_id id";
1955 $additionalClause = "
1956INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1957AND civicrm_membership_payment.membership_id {$componentClause} )
1958";
1959 }
1960 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
1961 $componentSelect = " civicrm_pledge_payment.id id";
1962 $additionalClause = "
1963INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1964AND civicrm_pledge_payment.pledge_id {$componentClause} )
1965";
1966 }
1967
1968 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1969 trxn_id, {$componentSelect}
1970FROM civicrm_contribution
1971LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1972LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1973 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1974LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1975LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1976 AND option_group_contribution_status.id = contribution_status.option_group_id )
1977{$additionalClause}
1978";
1979
c7940124 1980 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
1981
1982 while ($dao->fetch()) {
66d5d6f4 1983 $paymentDetails[$dao->id] = [
6a488035
TO
1984 'total_amount' => $dao->total_amount,
1985 'contribution_status' => $dao->status,
1986 'receive_date' => $dao->receive_date,
1987 'pay_instru' => $dao->payment_instrument,
1988 'trxn_id' => $dao->trxn_id,
66d5d6f4 1989 ];
6a488035
TO
1990 }
1991
1992 return $paymentDetails;
1993 }
1994
1995 /**
c490a46a 1996 * Create address associated with contribution record.
6a488035 1997 *
4914efff
EM
1998 * As long as there is one or more billing field in the parameters we will create the address.
1999 *
2000 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
2001 * thought).
2002 *
014c4014 2003 * @param array $params
c490a46a 2004 * @param int $billingLocationTypeID
fd31fa4c 2005 *
72b3a70c
CW
2006 * @return int
2007 * address id
6a488035 2008 */
4914efff 2009 public static function createAddress($params, $billingLocationTypeID) {
0816949d 2010 list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID);
4914efff
EM
2011 if ($hasBillingField) {
2012 $address = CRM_Core_BAO_Address::add($addressParams, FALSE);
739a8336 2013 return $address->id;
6a488035 2014 }
739a8336 2015 return NULL;
6a488035 2016
6a488035
TO
2017 }
2018
6a488035 2019 /**
fe482240 2020 * Delete billing address record related contribution.
6a488035 2021 *
c490a46a
CW
2022 * @param int $contributionId
2023 * @param int $contactId
6a488035 2024 */
00be9182 2025 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
66d5d6f4 2026 $clauses = [];
6a488035
TO
2027 $contactJoin = NULL;
2028
2029 if ($contributionId) {
2030 $clauses[] = "cc.id = {$contributionId}";
2031 }
2032
2033 if ($contactId) {
2034 $clauses[] = "cco.id = {$contactId}";
2035 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
2036 }
2037
2038 if (empty($clauses)) {
7980012b 2039 throw new CRM_Core_Exception('No Where clauses defined when deleting address');
6a488035
TO
2040 }
2041
2042 $condition = implode(' OR ', $clauses);
2043
2044 $query = "
2045SELECT ca.id
2046FROM civicrm_address ca
2047INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
2048 $contactJoin
2049WHERE $condition
2050";
2051 $dao = CRM_Core_DAO::executeQuery($query);
2052
2053 while ($dao->fetch()) {
66d5d6f4 2054 $params = ['id' => $dao->id];
6a488035
TO
2055 CRM_Core_BAO_Block::blockDelete('Address', $params);
2056 }
2057 }
2058
2059 /**
2060 * This function check online pending contribution associated w/
2061 * Online Event Registration or Online Membership signup.
2062 *
014c4014
TO
2063 * @param int $componentId
2064 * Participant/membership id.
2065 * @param string $componentName
2066 * Event/Membership.
6a488035 2067 *
16b10e64
CW
2068 * @return int
2069 * pending contribution id.
6a488035 2070 */
00be9182 2071 public static function checkOnlinePendingContribution($componentId, $componentName) {
6a488035
TO
2072 $contributionId = NULL;
2073 if (!$componentId ||
66d5d6f4 2074 !in_array($componentName, ['Event', 'Membership'])
6a488035
TO
2075 ) {
2076 return $contributionId;
2077 }
2078
2079 if ($componentName == 'Event') {
f2b2a3ff 2080 $idName = 'participant_id';
6a488035 2081 $componentTable = 'civicrm_participant';
f2b2a3ff
TO
2082 $paymentTable = 'civicrm_participant_payment';
2083 $source = ts('Online Event Registration');
6a488035
TO
2084 }
2085
2086 if ($componentName == 'Membership') {
f2b2a3ff 2087 $idName = 'membership_id';
6a488035 2088 $componentTable = 'civicrm_membership';
f2b2a3ff
TO
2089 $paymentTable = 'civicrm_membership_payment';
2090 $source = ts('Online Contribution');
6a488035
TO
2091 }
2092
2093 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
2094
2095 $query = "
2096 SELECT component.id as {$idName},
2097 componentPayment.contribution_id as contribution_id,
2098 contribution.source source,
2099 contribution.contribution_status_id as contribution_status_id,
2100 contribution.is_pay_later as is_pay_later
2101 FROM $componentTable component
2102LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
2103LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
2104 WHERE component.id = {$componentId}";
2105
2106 $dao = CRM_Core_DAO::executeQuery($query);
2107
2108 while ($dao->fetch()) {
2109 if ($dao->contribution_id &&
2110 $dao->is_pay_later &&
2111 $dao->contribution_status_id == $pendingStatusId &&
2112 strpos($dao->source, $source) !== FALSE
2113 ) {
2114 $contributionId = $dao->contribution_id;
6a488035
TO
2115 }
2116 }
2117
2118 return $contributionId;
2119 }
2120
2121 /**
16b10e64 2122 * Update contribution as well as related objects.
74ab7ba8 2123 *
f8c94f00 2124 * This function by-passes hooks - to address this - don't use this function.
2125 *
74ab7ba8
EM
2126 * @param array $params
2127 * @param bool $processContributionObject
2128 *
303007a3 2129 * @throws CRM_Core_Exception
2130 * @throws \CiviCRM_API3_Exception
66d5d6f4 2131 * @deprecated
2132 *
2133 * Use api contribute.completetransaction
2134 * For failures use failPayment (preferably exposing by api in the process).
2135 *
6a488035 2136 */
00be9182 2137 public static function transitionComponents($params, $processContributionObject = FALSE) {
6a488035 2138 // get minimum required values.
9c1bc317
CW
2139 $contactId = $params['contact_id'] ?? NULL;
2140 $componentId = $params['component_id'] ?? NULL;
2141 $componentName = $params['componentName'] ?? NULL;
2142 $contributionId = $params['contribution_id'] ?? NULL;
2143 $contributionStatusId = $params['contribution_status_id'] ?? NULL;
6a488035
TO
2144
2145 // if we already processed contribution object pass previous status id.
9c1bc317 2146 $previousContriStatusId = $params['previous_contribution_status_id'] ?? NULL;
6a488035 2147
66d5d6f4 2148 $updateResult = [];
6a488035
TO
2149
2150 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2151
2152 // we process only ( Completed, Cancelled, or Failed ) contributions.
2153 if (!$contributionId ||
66d5d6f4 2154 !in_array($contributionStatusId, [
f2b2a3ff
TO
2155 array_search('Completed', $contributionStatuses),
2156 array_search('Cancelled', $contributionStatuses),
2157 array_search('Failed', $contributionStatuses),
66d5d6f4 2158 ])
6a488035 2159 ) {
c41da2b7 2160 return;
6a488035
TO
2161 }
2162
2163 if (!$componentName || !$componentId) {
2164 // get the related component details.
2165 $componentDetails = self::getComponentDetails($contributionId);
2166 }
2167 else {
2168 $componentDetails['contact_id'] = $contactId;
2169 $componentDetails['component'] = $componentName;
2170
2171 if ($componentName == 'event') {
2172 $componentDetails['participant'] = $componentId;
2173 }
2174 else {
2175 $componentDetails['membership'] = $componentId;
2176 }
2177 }
2178
a7488080 2179 if (!empty($componentDetails['contact_id'])) {
6a488035
TO
2180 $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2181 $contributionId,
2182 'contact_id'
2183 );
2184 }
2185
2186 // do check for required ids.
8cc574cf 2187 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) {
c41da2b7 2188 return;
6a488035
TO
2189 }
2190
863592c3 2191 $input = $ids = [];
6a488035 2192
9c1bc317 2193 $input['component'] = $componentDetails['component'] ?? NULL;
6a488035 2194 $ids['contribution'] = $contributionId;
9c1bc317
CW
2195 $ids['contact'] = $componentDetails['contact_id'] ?? NULL;
2196 $ids['membership'] = $componentDetails['membership'] ?? NULL;
2197 $ids['participant'] = $componentDetails['participant'] ?? NULL;
2198 $ids['event'] = $componentDetails['event'] ?? NULL;
2199 $ids['pledge_payment'] = $componentDetails['pledge_payment'] ?? NULL;
6a488035
TO
2200 $ids['contributionRecur'] = NULL;
2201 $ids['contributionPage'] = NULL;
2202
863592c3 2203 $contribution = new CRM_Contribute_BAO_Contribution();
2204 $contribution->id = $ids['contribution'];
2205 $contribution->find();
2206
2207 $contribution->loadRelatedObjects($input, $ids);
2208
2209 $memberships = $contribution->_relatedObjects['membership'] ?? [];
2210 $participant = $contribution->_relatedObjects['participant'] ?? [];
2211 $pledgePayment = $contribution->_relatedObjects['pledge_payment'] ?? [];
6a488035 2212
1ee67fa2 2213 $pledgeID = $oldStatus = NULL;
2214 $pledgePaymentIDs = [];
6a488035 2215 if ($pledgePayment) {
6a488035
TO
2216 foreach ($pledgePayment as $key => $object) {
2217 $pledgePaymentIDs[] = $object->id;
2218 }
2219 $pledgeID = $pledgePayment[0]->pledge_id;
2220 }
2221
6a488035
TO
2222 $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
2223
2224 if ($participant) {
2225 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
2226 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
2227 $participant->id,
2228 'status_id'
2229 );
2230 }
2231 // we might want to process contribution object.
2232 $processContribution = FALSE;
2233 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1ee67fa2 2234 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2235 list($updateResult, $processContribution) = self::cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
6a488035
TO
2236 }
2237 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
0dcc88fc 2238 list($updateResult, $processContribution) = self::processFail($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
6a488035
TO
2239 }
2240 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2241
2242 // only pending contribution related object processed.
2243 if ($previousContriStatusId &&
66d5d6f4 2244 !in_array($contributionStatuses[$previousContriStatusId], [
2245 'Pending',
2246 'Partially paid',
2247 ])
6a488035
TO
2248 ) {
2249 // this is case when we already processed contribution object.
c41da2b7 2250 return;
6a488035
TO
2251 }
2252 elseif (!$previousContriStatusId &&
66d5d6f4 2253 !in_array($contributionStatuses[$contribution->contribution_status_id], [
2254 'Pending',
2255 'Partially paid',
2256 ])
6a488035
TO
2257 ) {
2258 // this is case when we are going to process contribution object later.
c41da2b7 2259 return;
6a488035
TO
2260 }
2261
2262 if (is_array($memberships)) {
2263 foreach ($memberships as $membership) {
2264 if ($membership) {
2265 $format = '%Y%m%d';
2266
2267 //CRM-4523
2268 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
2269 $membership->membership_type_id,
2270 $membership->is_test, $membership->id
2271 );
2272
2273 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2274 // this picks up membership type changes during renewals
2275 $sql = "
2276 SELECT membership_type_id
2277 FROM civicrm_membership_log
2278 WHERE membership_id=$membership->id
2279 ORDER BY id DESC
2280 LIMIT 1;";
fa00d91f 2281 $dao = CRM_Core_DAO::executeQuery($sql);
6a488035
TO
2282 if ($dao->fetch()) {
2283 if (!empty($dao->membership_type_id)) {
2284 $membership->membership_type_id = $dao->membership_type_id;
2285 $membership->save();
2286 }
2287 }
2288 // else fall back to using current membership type
9c09f5b7
AH
2289 // Figure out number of terms
2290 $numterms = 1;
77dbdcbc 2291 $lineitems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId);
9c09f5b7 2292 foreach ($lineitems as $lineitem) {
d4578334 2293 if ($membership->membership_type_id == ($lineitem['membership_type_id'] ?? NULL)) {
9c1bc317 2294 $numterms = $lineitem['membership_num_terms'] ?? NULL;
2d77a516 2295
9c09f5b7
AH
2296 // in case membership_num_terms comes through as null or zero
2297 $numterms = $numterms >= 1 ? $numterms : 1;
2298 break;
2299 }
2300 }
2301
e8c64fab 2302 // CRM-15735-to update the membership status as per the contribution receive date
35874a67 2303 $joinDate = NULL;
98f0683a 2304 $oldStatus = $membership->status_id;
e8c64fab 2305 if (!empty($params['receive_date'])) {
35874a67 2306 $joinDate = $params['receive_date'];
e8c64fab 2307 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date,
2308 $membership->end_date,
2309 $membership->join_date,
2310 $params['receive_date'],
2311 FALSE,
2312 $membership->membership_type_id,
2313 (array) $membership
2314 );
2315 $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id);
2316 $membership->save();
2317 }
2318
6a488035 2319 if ($currentMembership) {
9c09f5b7
AH
2320 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2321 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
6a488035
TO
2322 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
2323 }
2324 else {
35874a67 2325 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, $joinDate, NULL, NULL, $numterms);
6a488035
TO
2326 }
2327
2328 //get the status for membership.
2329 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
2330 $dates['end_date'],
2331 $dates['join_date'],
2cb64970 2332 'now',
5f11bbcc
EM
2333 TRUE,
2334 $membership->membership_type_id,
2335 (array) $membership
6a488035
TO
2336 );
2337
66d5d6f4 2338 $formattedParams = [
6a488035
TO
2339 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
2340 array_search('Current', $membershipStatuses)
2341 ),
2342 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
2343 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
2344 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
66d5d6f4 2345 ];
6a488035 2346
c2585c5b 2347 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
6a488035 2348
c2585c5b 2349 $membership->copyValues($formattedParams);
6a488035
TO
2350 $membership->save();
2351
2352 //updating the membership log
66d5d6f4 2353 $membershipLog = [];
c2585c5b 2354 $membershipLog = $formattedParams;
d4578334 2355 $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'] ?? NULL, $format);
f2b2a3ff 2356 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
6a488035
TO
2357
2358 $membershipLog['start_date'] = $logStartDate;
2359 $membershipLog['membership_id'] = $membership->id;
2360 $membershipLog['modified_id'] = $membership->contact_id;
2361 $membershipLog['modified_date'] = date('Ymd');
2362 $membershipLog['membership_type_id'] = $membership->membership_type_id;
2363
4ed92e91 2364 CRM_Member_BAO_MembershipLog::add($membershipLog);
6a488035
TO
2365
2366 //update related Memberships.
c2585c5b 2367 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
6a488035 2368
66d5d6f4 2369 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
b6d493f3
MD
2370 $scheduledActivityID = CRM_Utils_Array::value('id',
2371 civicrm_api3('Activity', 'Get',
66d5d6f4 2372 [
b6d493f3
MD
2373 'source_record_id' => $membership->id,
2374 'activity_type_id' => $activityType,
2375 'status_id' => 'Scheduled',
66d5d6f4 2376 'options' => [
66a1e31f
MD
2377 'limit' => 1,
2378 'sort' => 'id DESC',
66d5d6f4 2379 ],
2380 ]
b6d493f3
MD
2381 )
2382 );
66a1e31f 2383 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
b6d493f3
MD
2384 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2385 if ($scheduledActivityID) {
66d5d6f4 2386 CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $membership->contact_id, ['id' => $scheduledActivityID]);
b6d493f3
MD
2387 break;
2388 }
2389 }
2390
2391 // track membership status change if any
2392 if (!empty($oldStatus) && $membership->status_id != $oldStatus) {
2393 $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get');
2394 CRM_Activity_BAO_Activity::addActivity($membership,
2395 'Change Membership Status',
2396 NULL,
66d5d6f4 2397 [
b6d493f3
MD
2398 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2399 'source_contact_id' => $membershipLog['modified_id'],
66a1e31f 2400 'priority_id' => 'Normal',
66d5d6f4 2401 ]
b6d493f3
MD
2402 );
2403 }
0f07bb06 2404
6a488035
TO
2405 if ($processContributionObject) {
2406 $processContribution = TRUE;
2407 }
2408
2409 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
2410 }
2411 }
2412 }
2413
2414 if ($participant) {
2415 $updatedStatusId = array_search('Registered', $participantStatuses);
2416 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
2417
6a488035
TO
2418 if ($processContributionObject) {
2419 $processContribution = TRUE;
2420 }
2421 }
2422
2423 if ($pledgePayment) {
2424 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2425
6a488035
TO
2426 if ($processContributionObject) {
2427 $processContribution = TRUE;
2428 }
2429 }
2430 }
2431
2432 // process contribution object.
2433 if ($processContribution) {
66d5d6f4 2434 $contributionParams = [];
2435 $fields = [
f2b2a3ff
TO
2436 'contact_id',
2437 'total_amount',
2438 'receive_date',
2439 'is_test',
2440 'campaign_id',
2441 'payment_instrument_id',
2442 'trxn_id',
2443 'invoice_id',
2444 'financial_type_id',
2445 'contribution_status_id',
2446 'non_deductible_amount',
2447 'receipt_date',
2448 'check_number',
66d5d6f4 2449 ];
6a488035 2450 foreach ($fields as $field) {
a7488080 2451 if (empty($params[$field])) {
6a488035
TO
2452 continue;
2453 }
2454 $contributionParams[$field] = $params[$field];
2455 }
2456
70d43afb 2457 $contributionParams['id'] = $contributionId;
2458 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams);
6a488035
TO
2459 }
2460
6a488035
TO
2461 }
2462
2463 /**
16b10e64 2464 * Returns all contribution related object ids.
7a9ab499
EM
2465 *
2466 * @param $contributionId
2467 *
2468 * @return array
6a488035 2469 */
291ca04f 2470 public static function getComponentDetails($contributionId) {
66d5d6f4 2471 $componentDetails = $pledgePayment = [];
6a488035
TO
2472 if (!$contributionId) {
2473 return $componentDetails;
2474 }
2475
2476 $query = "
2477 SELECT c.id as contribution_id,
2478 c.contact_id as contact_id,
d97c96dc 2479 c.contribution_recur_id,
6a488035
TO
2480 mp.membership_id as membership_id,
2481 m.membership_type_id as membership_type_id,
2482 pp.participant_id as participant_id,
2483 p.event_id as event_id,
2484 pgp.id as pledge_payment_id
2485 FROM civicrm_contribution c
2486 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2487 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2488 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2489 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2490 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2491 WHERE c.id = $contributionId";
2492
2493 $dao = CRM_Core_DAO::executeQuery($query);
66d5d6f4 2494 $componentDetails = [];
6a488035
TO
2495
2496 while ($dao->fetch()) {
2497 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
2498 $componentDetails['contact_id'] = $dao->contact_id;
2499 if ($dao->event_id) {
2500 $componentDetails['event'] = $dao->event_id;
2501 }
2502 if ($dao->participant_id) {
2503 $componentDetails['participant'] = $dao->participant_id;
2504 }
2505 if ($dao->membership_id) {
2506 if (!isset($componentDetails['membership'])) {
66d5d6f4 2507 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
6a488035
TO
2508 }
2509 $componentDetails['membership'][] = $dao->membership_id;
2510 $componentDetails['membership_type'][] = $dao->membership_type_id;
2511 }
2512 if ($dao->pledge_payment_id) {
2513 $pledgePayment[] = $dao->pledge_payment_id;
2514 }
d97c96dc
EM
2515 if ($dao->contribution_recur_id) {
2516 $componentDetails['contributionRecur'] = $dao->contribution_recur_id;
2517 }
6a488035
TO
2518 }
2519
2520 if ($pledgePayment) {
2521 $componentDetails['pledge_payment'] = $pledgePayment;
2522 }
2523
2524 return $componentDetails;
2525 }
2526
186c9c17 2527 /**
100fef9d 2528 * @param int $contactId
186c9c17
EM
2529 * @param bool $includeSoftCredit
2530 *
2531 * @return null|string
2532 */
00be9182 2533 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
6a488035
TO
2534 if (!$contactId) {
2535 return 0;
2536 }
d51d109d 2537 $financialTypes = CRM_Financial_BAO_FinancialType::getAllAvailableFinancialTypes();
7fb041e3 2538 $additionalWhere = " AND contribution.financial_type_id IN (0)";
9cec2e9f 2539 $liWhere = " AND i.financial_type_id IN (0)";
7fb041e3 2540 if (!empty($financialTypes)) {
40c655aa
E
2541 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2542 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
7fb041e3 2543 }
bbde790f
RN
2544 $contactContributionsSQL = "
2545 SELECT contribution.id AS id
2546 FROM civicrm_contribution contribution
ad37ac8e 2547 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2548 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2549 $additionalWhere
9cec2e9f 2550 AND i.id IS NULL";
bbde790f 2551
bbde790f
RN
2552 $contactSoftCreditContributionsSQL = "
2553 SELECT contribution.id
2554 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2555 ON ( contribution.id = softContribution.contribution_id )
2556 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2557 $query = "SELECT count( x.id ) count FROM ( ";
2558 $query .= $contactContributionsSQL;
2559
6a488035 2560 if ($includeSoftCredit) {
bbde790f
RN
2561 $query .= " UNION ";
2562 $query .= $contactSoftCreditContributionsSQL;
6a488035 2563 }
bbde790f 2564
bbde790f 2565 $query .= ") x";
6a488035
TO
2566
2567 return CRM_Core_DAO::singleValueQuery($query);
2568 }
2569
b3b7f4c5 2570 /**
2571 * Repeat a transaction as part of a recurring series.
2572 *
fefee636 2573 * The ideal flow is
2574 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2575 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2576 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2577 * and associated entities.
2578 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2579 * which updates the various entities and sends appropriate emails.
2580 *
2581 * Gaps in the above (@todo)
2582 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2583 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2584 * 3) Repeat transaction duplicates rather than calls Order.create
2585 * 4) Use of payment.create still limited - completetransaction is more common.
2586 * 5) the template transaction is tricky - historically we used the first contribution
2587 * linked to a recurring contribution. More recently that was changed to be the most recent.
2588 * Ideally it would be an actual template - not a contribution used as a template which
2589 * would give more appropriate flexibility. Note line_items have an entity so that table
2590 * could be used for the line item template - the difficulty is the custom fields...
2591 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2592 * to load the membership(s) referred to via line items in the template transactions. Any other
2593 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2594 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2595 * - membership_payment record
2596 * - civicrm_membership.contribution_recur_id
2597 * - input override.
2598 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2599 * of historical processors since this has been handled 'forever' - specifically for paypal.
2600 * albeit by an even nastier mechanism than the current input override.
2601 * The count is out on how correct related entities wind up in this case.
b3b7f4c5 2602 *
2603 * @param CRM_Contribute_BAO_Contribution $contribution
2604 * @param array $input
2605 * @param array $contributionParams
2606 *
c80d977f 2607 * @return bool|array
43c8d1dd 2608 * @throws CiviCRM_API3_Exception
b3b7f4c5 2609 */
34dc58e7 2610 protected static function repeatTransaction(&$contribution, $input, $contributionParams) {
b3b7f4c5 2611 if (!empty($contribution->id)) {
2612 return FALSE;
2613 }
2614 if (empty($contribution->id)) {
2615 // Unclear why this would only be set for repeats.
2616 if (!empty($input['amount'])) {
2617 $contribution->total_amount = $contributionParams['total_amount'] = $input['amount'];
2618 }
43c8d1dd 2619
8da8c1d0 2620 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2621 'id' => $contributionParams['contribution_recur_id'],
2622 ]);
8da8c1d0 2623 if (!empty($recurringContribution['financial_type_id'])) {
2624 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2625 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
c02c17df 2626 }
43c8d1dd 2627 $templateContribution = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution(
2628 $contributionParams['contribution_recur_id'],
66d5d6f4 2629 array_intersect_key($contributionParams, [
2630 'total_amount' => TRUE,
2631 'financial_type_id' => TRUE,
2632 ])
43c8d1dd 2633 );
2634 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
f8c94f00 2635 $contributionParams['status_id'] = 'Pending';
fa839a68 2636
2637 if (isset($contributionParams['financial_type_id']) && count($input['line_item']) === 1) {
2638 // We permit the financial type to be overridden for single line items.
2639 // More comments on this are in getTemplateTransaction.
3c49d90c 2640 $contribution->financial_type_id = $contributionParams['financial_type_id'];
2641 }
2642 else {
2643 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2644 }
a64d6127 2645 foreach (['contact_id', 'currency', 'source', 'amount_level', 'address_id'] as $fieldName) {
2646 if (isset($templateContribution[$fieldName])) {
2647 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2648 }
2649 }
2650 if (!empty($recurringContribution['campaign_id'])) {
2651 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2652 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2653 }
2654 if (!isset($contributionParams['campaign_id']) && isset($templateContribution['campaign_id'])) {
2655 // Fall back on value from the previous contribution if not passed in as input
2656 // or loadable from the recurring contribution.
2657 $contributionParams['campaign_id'] = $templateContribution['campaign_id'];
aed0a241 2658 }
aed0a241 2659 $contributionParams['source'] = $contributionParams['source'] ?: ts('Recurring contribution');
43c8d1dd 2660
44fec73b
BS
2661 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2662 //do not create CC or BCC emails or profile notifications.
2663 //The if is just to be safe. Not sure if we can ever arrive with this unset
8536e5a0 2664 // but per CRM-19478 it seems it can be 'null'
2665 if (isset($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) {
4194dd55 2666 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id;
a4facb5c 2667 }
8891c196
JP
2668 if (!empty($contribution->tax_amount)) {
2669 $contributionParams['tax_amount'] = $contribution->tax_amount;
2670 }
44fec73b 2671
b3b7f4c5 2672 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2673 $contribution->id = $createContribution['id'];
b2250d14 2674 $contribution->copyCustomFields($templateContribution['id'], $contribution->id);
fefee636 2675 self::handleMembershipIDOverride($contribution->id, $input);
0bd5e6bf 2676 // Add new soft credit against current $contribution.
2677 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($contributionParams['contribution_recur_id'], $createContribution['id']);
c80d977f 2678 return $createContribution;
b3b7f4c5 2679 }
2680 }
2681
6a488035 2682 /**
fe482240 2683 * Get individual id for onbehalf contribution.
6a488035 2684 *
014c4014
TO
2685 * @param int $contributionId
2686 * Contribution id.
2687 * @param int $contributorId
2688 * Contributor id.
6a488035 2689 *
a6c01b45
CW
2690 * @return array
2691 * containing organization id and individual id
6a488035 2692 */
00be9182 2693 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
6a488035 2694
66d5d6f4 2695 $ids = [];
6a488035
TO
2696
2697 if (!$contributionId) {
2698 return $ids;
2699 }
2700
2701 // fetch contributor id if null
2702 if (!$contributorId) {
2703 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2704 $contributionId, 'contact_id'
2705 );
2706 }
2707
2708 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
2709 $activityTypeId = array_search('Contribution', $activityTypeIds);
2710
2711 if ($activityTypeId && $contributorId) {
2712 $activityQuery = "
2d77a516
DL
2713SELECT civicrm_activity_contact.contact_id
2714 FROM civicrm_activity_contact
2715INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2716 WHERE civicrm_activity.activity_type_id = %1
2717 AND civicrm_activity.source_record_id = %2
2718 AND civicrm_activity_contact.record_type_id = %3
2719";
6a488035 2720
44f817d4 2721 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2d77a516
DL
2722 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2723
66d5d6f4 2724 $params = [
2725 1 => [$activityTypeId, 'Integer'],
2726 2 => [$contributionId, 'Integer'],
2727 3 => [$sourceID, 'Integer'],
2728 ];
6a488035
TO
2729
2730 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
2731
2732 // for on behalf contribution source is individual and contributor is organization
2733 if ($sourceContactId && $sourceContactId != $contributorId) {
2734 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
2735 // get rel type id for employee of relation
2736 foreach ($relationshipTypeIds as $id => $typeVals) {
2737 if ($typeVals['name_a_b'] == 'Employee of') {
2738 $relationshipTypeId = $id;
2739 break;
2740 }
2741 }
2742
2743 $rel = new CRM_Contact_DAO_Relationship();
2744 $rel->relationship_type_id = $relationshipTypeId;
2745 $rel->contact_id_a = $sourceContactId;
2746 $rel->contact_id_b = $contributorId;
2747 if ($rel->find(TRUE)) {
2748 $ids['individual_id'] = $rel->contact_id_a;
2749 $ids['organization_id'] = $rel->contact_id_b;
2750 }
2751 }
2752 }
2753
2754 return $ids;
2755 }
2756
2757 /**
2758 * @return array
6a488035 2759 */
00be9182 2760 public static function getContributionDates() {
f2b2a3ff 2761 $config = CRM_Core_Config::singleton();
6a488035 2762 $currentMonth = date('m');
f2b2a3ff 2763 $currentDay = date('d');
6a488035
TO
2764 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
2765 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
2766 (int ) $config->fiscalYearStart['d'] > $currentDay
2767 )
2768 ) {
2769 $year = date('Y') - 1;
2770 }
2771 else {
2772 $year = date('Y');
2773 }
66d5d6f4 2774 $year = ['Y' => $year];
6a488035
TO
2775 $yearDate = $config->fiscalYearStart;
2776 $yearDate = array_merge($year, $yearDate);
2777 $yearDate = CRM_Utils_Date::format($yearDate);
2778
2779 $monthDate = date('Ym') . '01';
2780
2781 $now = date('Ymd');
2782
66d5d6f4 2783 return [
6a488035
TO
2784 'now' => $now,
2785 'yearDate' => $yearDate,
2786 'monthDate' => $monthDate,
66d5d6f4 2787 ];
6a488035
TO
2788 }
2789
16b10e64 2790 /**
fe482240 2791 * Load objects relations to contribution object.
6a488035
TO
2792 * Objects are stored in the $_relatedObjects property
2793 * In the first instance we are just moving functionality from BASEIpn -
66d5d6f4 2794 *
16b10e64
CW
2795 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2796 *
2797 * Note that the unit test for the BaseIPN class tests this function
6a488035 2798 *
014c4014
TO
2799 * @param array $input
2800 * Input as delivered from Payment Processor.
2801 * @param array $ids
2802 * Ids as Loaded by Payment Processor.
014c4014
TO
2803 * @param bool $loadAll
2804 * Load all related objects - even where id not passed in? (allows API to call this).
186c9c17
EM
2805 *
2806 * @return bool
49ed4888 2807 * @throws CRM_Core_Exception
186c9c17 2808 */
ad64fa72 2809 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
72d57998 2810 // @todo deprecate this function - the steps should be
2811 // 1) add additional functions like 'getRelatedMemberships'
2812 // 2) switch all calls that refer to ->_relatedObjects to
2813 // using the helper functions
2814 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2815 // 4) make ->_relatedObjects protected
2816 // 5) hone up the individual functions to not use rely on this having been called
2817 // 6) deprecate like mad
f2b2a3ff
TO
2818 if ($loadAll) {
2819 $ids = array_merge($this->getComponentDetails($this->id), $ids);
2820 if (empty($ids['contact']) && isset($this->contact_id)) {
6a488035
TO
2821 $ids['contact'] = $this->contact_id;
2822 }
2823 }
2824 if (empty($this->_component)) {
f2b2a3ff 2825 if (!empty($ids['event'])) {
6a488035
TO
2826 $this->_component = 'event';
2827 }
2828 else {
2829 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
2830 }
2831 }
474ebab9 2832
2b57dd9f 2833 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2834 // refactoring than anything else, and has unit test coverage.
2835 if (empty($this->financial_type_id)) {
2836 $this->find(TRUE);
2837 }
2838
474ebab9 2839 $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value(
2840 'paymentProcessor',
2841 $ids
2842 ));
2843
18135422 2844 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id) {
474ebab9 2845 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2846 $this->contribution_page_id,
2847 'payment_processor'
2848 );
ef6ae9af 2849 if ($paymentProcessorID) {
2850 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2851 }
474ebab9 2852 }
2853
2b57dd9f 2854 $ids['contributionType'] = $this->financial_type_id;
2855 $ids['financialType'] = $this->financial_type_id;
55df1211
AS
2856 if ($this->contribution_page_id) {
2857 $ids['contributionPage'] = $this->contribution_page_id;
474ebab9 2858 }
2859
55df1211
AS
2860 $this->loadRelatedEntitiesByID($ids);
2861
2b57dd9f 2862 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2863 $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id;
6a488035 2864 }
6a488035 2865
474ebab9 2866 if (!empty($ids['pledge_payment'])) {
2867 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2868 if (empty($paymentID)) {
2869 continue;
2870 }
2871 $payment = new CRM_Pledge_BAO_PledgePayment();
2872 $payment->id = $paymentID;
2873 if (!$payment->find(TRUE)) {
49ed4888 2874 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
474ebab9 2875 }
2876 $this->_relatedObjects['pledge_payment'][] = $payment;
2877 }
2878 }
2879
72d57998 2880 // These are probably no longer accessed from anywhere
2881 // @todo remove this line, after ensuring not used.
e6c7e48d 2882 $ids = $this->loadRelatedMembershipObjects($ids);
aadcdd50 2883
2884 if ($this->_component != 'contribute') {
6a488035
TO
2885 // we are in event mode
2886 // make sure event exists and is valid
2887 $event = new CRM_Event_BAO_Event();
2888 $event->id = $ids['event'];
2889 if ($ids['event'] &&
2890 !$event->find(TRUE)
2891 ) {
49ed4888 2892 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
6a488035
TO
2893 }
2894
2895 $this->_relatedObjects['event'] = &$event;
2896
2897 $participant = new CRM_Event_BAO_Participant();
2898 $participant->id = $ids['participant'];
2899 if ($ids['participant'] &&
2900 !$participant->find(TRUE)
2901 ) {
49ed4888 2902 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
6a488035
TO
2903 }
2904 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
2905
2906 $this->_relatedObjects['participant'] = &$participant;
2907
474ebab9 2908 // get the payment processor id from event - this is inaccurate see CRM-16923
2909 // in future we should look at throwing an exception here rather than an dubious guess.
6a488035
TO
2910 if (!$paymentProcessorID) {
2911 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
ef6ae9af 2912 if ($paymentProcessorID) {
2913 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2914 }
6a488035
TO
2915 }
2916 }
2917
d33f8fc4
JP
2918 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds($this->id);
2919 if (!empty($relatedContact['individual_id'])) {
2920 $ids['related_contact'] = $relatedContact['individual_id'];
2921 }
2922
6a488035
TO
2923 if ($paymentProcessorID) {
2924 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2925 $this->is_test ? 'test' : 'live'
2926 );
2927 $ids['paymentProcessor'] = $paymentProcessorID;
d6944518 2928 $this->_relatedObjects['paymentProcessor'] = $paymentProcessor;
6a488035 2929 }
5f3d5a7a
AS
2930
2931 // Add contribution id to $ids. CRM-20401
2932 $ids['contribution'] = $this->id;
5bfb071e 2933 return TRUE;
6a488035
TO
2934 }
2935
16b10e64 2936 /**
6a488035
TO
2937 * Create array of message information - ie. return html version, txt version, to field
2938 *
014c4014
TO
2939 * @param array $input
2940 * Incoming information.
16b10e64 2941 * - is_recur - should this be treated as recurring (not sure why you wouldn't
6a488035
TO
2942 * just check presence of recur object but maintaining legacy approach
2943 * to be careful)
014c4014
TO
2944 * @param array $ids
2945 * IDs of related objects.
2946 * @param array $values
2947 * Any values that may have already been compiled by calling process.
6a488035 2948 * This is augmented by values 'gathered' by gatherMessageValues
014c4014
TO
2949 * @param bool $returnMessageText
2950 * Distinguishes between whether to send message or return.
6a488035
TO
2951 * message text. We are working towards this function ALWAYS returning message text & calling
2952 * function doing emails / pdfs with it
16b10e64 2953 *
a6c01b45
CW
2954 * @return array
2955 * messages
186c9c17
EM
2956 * @throws Exception
2957 */
d891a273 2958 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
4ff927bc 2959 $this->loadRelatedObjects($input, $ids);
2960
6a488035 2961 if (empty($this->_component)) {
9c1bc317 2962 $this->_component = $input['component'] ?? NULL;
6a488035
TO
2963 }
2964
2965 //not really sure what params might be passed in but lets merge em into values
2966 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
081ee444 2967 $values['is_email_receipt'] = !$returnMessageText;
94db3e6e
JP
2968 foreach (['receipt_date', 'cc_receipt', 'bcc_receipt', 'receipt_from_name', 'receipt_from_email', 'receipt_text'] as $fld) {
2969 if (!empty($input[$fld])) {
2970 $values[$fld] = $input[$fld];
2971 }
d9924163
E
2972 }
2973
d891a273 2974 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
6a488035
TO
2975 //what does recur 'mean here - to do with payment processor return functionality but
2976 // what is the importance
d891a273 2977 if (!empty($this->contribution_recur_id) && !empty($this->_relatedObjects['paymentProcessor'])) {
35cd38f5 2978 $paymentObject = Civi\Payment\System::singleton()->getByProcessor($this->_relatedObjects['paymentProcessor']);
6a488035
TO
2979
2980 $entityID = $entity = NULL;
2981 if (isset($ids['contribution'])) {
2982 $entity = 'contribution';
2983 $entityID = $ids['contribution'];
2984 }
dccb668e
EM
2985 if (!empty($ids['membership'])) {
2986 //not sure whether is is possible for this not to be an array - load related contacts loads an array but this code was expecting a string
2987 // the addition of the casting is in case it could get here & be a string. Added in 4.6 - maybe remove later? This AuthorizeNetIPN & PaypalIPN tests hit this
2988 // line having loaded an array
2989 $ids['membership'] = (array) $ids['membership'];
6a488035 2990 $entity = 'membership';
dccb668e 2991 $entityID = $ids['membership'][0];
6a488035
TO
2992 }
2993
3e473c0b 2994 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
66df7769 2995 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2996 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
6a488035
TO
2997
2998 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2999 //direct mode showing billing block, so use directIPN for temporary
3000 $template->assign('contributeMode', 'directIPN');
3001 }
3002 }
3003 // todo remove strtolower - check consistency
3004 if (strtolower($this->_component) == 'event') {
66d5d6f4 3005 $eventParams = ['id' => $this->_relatedObjects['participant']->event_id];
3006 $values['event'] = [];
66df7769 3007
3008 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
3009
3010 //get location details
66d5d6f4 3011 $locationParams = [
3012 'entity_id' => $this->_relatedObjects['participant']->event_id,
3013 'entity_table' => 'civicrm_event',
3014 ];
66df7769 3015 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
3016
66d5d6f4 3017 $ufJoinParams = [
66df7769 3018 'entity_table' => 'civicrm_event',
3019 'entity_id' => $ids['event'],
3020 'module' => 'CiviEvent',
66d5d6f4 3021 ];
66df7769 3022
3023 list($custom_pre_id,
3024 $custom_post_ids
3025 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
3026
3027 $values['custom_pre_id'] = $custom_pre_id;
3028 $values['custom_post_id'] = $custom_post_ids;
ec5b3633 3029 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
66df7769 3030 //and cases involving status updation through ipn
3031 // whatever that means!
95e5776c 3032 // total_amount appears to be the preferred input param & it is unclear why we support amount here
3033 // perhaps we should throw an e-notice if amount is set & force total_amount?
3034 if (!empty($input['amount'])) {
3035 $values['totalAmount'] = $input['amount'];
3036 }
55df1211 3037 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
66df7769 3038 if ($values['event']['is_email_confirm']) {
3039 $values['is_email_receipt'] = 1;
3040 }
b7bef093 3041
2b65b515 3042 if (!empty($ids['contribution'])) {
3043 $values['contributionId'] = $ids['contribution'];
3044 }
b7bef093 3045
6a488035
TO
3046 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
3047 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
3048 );
3049 }
3050 else {
3051 $values['contribution_id'] = $this->id;
a7488080 3052 if (!empty($ids['related_contact'])) {
6a488035
TO
3053 $values['related_contact'] = $ids['related_contact'];
3054 if (isset($ids['onbehalf_dupe_alert'])) {
3055 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
3056 }
66d5d6f4 3057 $entityBlock = [
6a488035
TO
3058 'contact_id' => $ids['contact'],
3059 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
3060 'Home', 'id', 'name'
3061 ),
66d5d6f4 3062 ];
6a488035
TO
3063 $address = CRM_Core_BAO_Address::getValues($entityBlock);
3064 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
3065 }
3066 $isTest = FALSE;
3067 if ($this->is_test) {
3068 $isTest = TRUE;
3069 }
3070 if (!empty($this->_relatedObjects['membership'])) {
3071 foreach ($this->_relatedObjects['membership'] as $membership) {
3072 if ($membership->id) {
487c1b17 3073 $values['membership_id'] = $membership->id;
85dea18b 3074 $values['isMembership'] = TRUE;
858f7096 3075 $values['membership_assign'] = TRUE;
6a488035
TO
3076
3077 // need to set the membership values here
6a488035
TO
3078 $template->assign('membership_name',
3079 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
3080 );
3081 $template->assign('mem_start_date', $membership->start_date);
3082 $template->assign('mem_join_date', $membership->join_date);
3083 $template->assign('mem_end_date', $membership->end_date);
3084 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
3085 $template->assign('mem_status', $membership_status);
3086 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
c2358f41 3087 $values['is_pay_later'] = 1;
6a488035 3088 }
37c88e84
JP
3089 // Pass amount to floatval as string '0.00' is considered a
3090 // valid amount and includes Fee section in the mail.
3091 if (isset($values['amount'])) {
3092 $values['amount'] = floatval($values['amount']);
3093 }
6a488035 3094
d891a273 3095 if (!empty($this->contribution_recur_id) && $paymentObject) {
3e473c0b 3096 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'cancel');
6a488035
TO
3097 $template->assign('cancelSubscriptionUrl', $url);
3098 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
3099 $template->assign('updateSubscriptionBillingUrl', $url);
3100 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
3101 $template->assign('updateSubscriptionUrl', $url);
3102 }
3103
3104 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3105
3106 return $result;
3107 // otherwise if its about sending emails, continue sending without return, as we
3108 // don't want to exit the loop.
3109 }
3110 }
3111 }
3112 else {
3113 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3114 }
3115 }
3116 }
3117
16b10e64 3118 /**
6a488035
TO
3119 * Gather values for contribution mail - this function has been created
3120 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3121 * Values related to the contribution in question are gathered
3122 *
014c4014
TO
3123 * @param array $input
3124 * Input into function (probably from payment processor).
16b10e64 3125 * @param array $values
014c4014 3126 * @param array $ids
16b10e64 3127 * The set of ids related to the input.
6a488035 3128 *
a6c01b45 3129 * @return array
0a12bb75 3130 * @throws \CRM_Core_Exception
186c9c17 3131 */
66d5d6f4 3132 public function _gatherMessageValues($input, &$values, $ids = []) {
6a488035 3133 // set display address of contributor
49cba3ad 3134 $values['billingName'] = '';
6a488035 3135 if ($this->address_id) {
49cba3ad 3136 $addressDetails = CRM_Core_BAO_Address::getValues(['id' => $this->address_id], FALSE, 'id');
3137 $addressDetails = reset($addressDetails);
3138 $values['billingName'] = $addressDetails['name'] ?? '';
6a488035 3139 }
2b221bad
TM
3140 // Else we assign the billing address of the contribution contact.
3141 else {
49cba3ad 3142 $addressDetails = (array) CRM_Core_BAO_Address::getValues(['contact_id' => $this->contact_id, 'is_billing' => 1]);
3143 $addressDetails = reset($addressDetails);
2b221bad 3144 }
49cba3ad 3145 $values['address'] = $addressDetails['display'] ?? '';
2a0df9d9 3146
49cba3ad 3147 if ($this->_component === 'contribute') {
a49aa7dd
TM
3148 //get soft contributions
3149 $softContributions = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id, TRUE);
3150 if (!empty($softContributions)) {
126c4e4d 3151 // For pcp soft credit, there is no 'soft_credit' member it comes
3152 // back in different array members, but shortly after returning from
3153 // this function it calls _assignMessageVariablesToTemplate which does
3154 // its own lookup of any pcp soft credit, so we can skip it here.
3155 $values['softContributions'] = $softContributions['soft_credit'] ?? NULL;
a49aa7dd 3156 }
6a488035 3157 if (isset($this->contribution_page_id)) {
55df1211 3158 // This is a call we want to use less, in favour of loading related objects.
f99a6f98 3159 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
6a488035 3160 if ($this->contribution_page_id) {
55df1211
AS
3161 // This is precautionary as there are some legacy flows, but it should really be
3162 // loaded by now.
3163 if (!isset($this->_relatedObjects['contributionPage'])) {
66d5d6f4 3164 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id]);
55df1211 3165 }
85939a77 3166 CRM_Contribute_BAO_Contribution_Utils::overrideDefaultCurrency($values);
6a488035
TO
3167 }
3168 }
3169 // no contribution page -probably back office
3170 else {
3171 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
6a488035
TO
3172 $values['title'] = 'Contribution';
3173 }
3174 // set lineItem for contribution
3175 if ($this->id) {
270ff672 3176 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->id);
3177 if (!empty($lineItems)) {
3178 $firstLineItem = reset($lineItems);
66d5d6f4 3179 $priceSet = [];
de6c59ca 3180 if (!empty($firstLineItem['price_set_id'])) {
66d5d6f4 3181 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3182 'id' => $firstLineItem['price_set_id'],
3183 'return' => 'is_quick_config, id',
3184 ]);
e81d9dcf
AS
3185 $values['priceSetID'] = $priceSet['id'];
3186 }
270ff672 3187 foreach ($lineItems as &$eachItem) {
7c063f32 3188 if (isset($this->_relatedObjects['membership'])
66d5d6f4 3189 && is_array($this->_relatedObjects['membership'])
6e948f0d
SP
3190 && array_key_exists($eachItem['entity_id'] . '_' . $eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
3191 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->join_date);
3192 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->start_date);
3193 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->end_date);
6a488035 3194 }
270ff672 3195 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3196 // However, that does create upgrade pain so would be better to be phased in.
c95c2012 3197 $values['useForMember'] = empty($priceSet['is_quick_config']);
6a488035 3198 }
270ff672 3199 $values['lineItem'][0] = $lineItems;
f2b2a3ff 3200 }
6a488035
TO
3201 }
3202
3203 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
3204 $this->id,
3205 $this->contact_id
3206 );
3207 // if this is onbehalf of contribution then set related contact
a7488080 3208 if (!empty($relatedContact['individual_id'])) {
6a488035
TO
3209 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3210 }
3211 }
3212 else {
0a12bb75 3213 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects['participant']->id, $this->id));
6a488035
TO
3214 }
3215
0b330e6d 3216 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', NULL, $this->id);
7089d2d8 3217
66d5d6f4 3218 $customGroup = [];
7089d2d8
TM
3219 foreach ($groupTree as $key => $group) {
3220 if ($key === 'info') {
3221 continue;
3222 }
3223
3224 foreach ($group['fields'] as $k => $customField) {
3225 $groupLabel = $group['title'];
3226 if (!empty($customField['customValue'])) {
3227 foreach ($customField['customValue'] as $customFieldValues) {
9c1bc317 3228 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ?? NULL;
7089d2d8
TM
3229 }
3230 }
3231 }
3232 }
3233 $values['customGroup'] = $customGroup;
3234
dbacb875 3235 $values['is_pay_later'] = $this->is_pay_later;
717fdb8a 3236
6a488035
TO
3237 return $values;
3238 }
3239
3240 /**
9daadfce 3241 * Assign message variables to template but try to break the habit.
3242 *
3243 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3244 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3245 * multiple recurring payments for processors like IATS that use tokens.
3246 *
6a488035
TO
3247 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3248 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
9daadfce 3249 * Note we send directly from this function in some cases because it is only partly refactored.
3250 *
3251 * Don't call this function directly as the signature will change.
02af3683
EM
3252 *
3253 * @param $values
3254 * @param $input
02af3683
EM
3255 * @param bool $returnMessageText
3256 *
3257 * @return mixed
6a488035 3258 */
d891a273 3259 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
5d6cf648
JM
3260 // @todo - this should have a better separation of concerns - ie.
3261 // gatherMessageValues should build an array of values to be assigned to the template
3262 // and this function should assign them (assigning null if not set).
3263 // the way the pcpParams & honor Params section works is a baby-step towards this.
d891a273 3264 $template = CRM_Core_Smarty::singleton();
6a488035
TO
3265 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
3266 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
3267 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
49cba3ad 3268 $template->assign('billingName', $values['billingName']);
367b5943 3269
3270 // For some unit tests contribution cannot contain paymentProcessor information
3271 $billingMode = empty($this->_relatedObjects['paymentProcessor']) ? CRM_Core_Payment::BILLING_MODE_NOTIFY : $this->_relatedObjects['paymentProcessor']['billing_mode'];
d4578334 3272 $template->assign('contributeMode', CRM_Core_SelectValues::contributeMode()[$billingMode] ?? NULL);
367b5943 3273
02af3683 3274 //assign honor information to receipt message
8af73472 3275 $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
6a488035 3276
66d5d6f4 3277 $honorParams = [
3278 'soft_credit_type' => NULL,
3279 'honor_block_is_active' => NULL,
3280 ];
8af73472 3281 if (isset($softRecord['soft_credit'])) {
7305d3e6 3282 //if id of contribution page is present
3283 if (!empty($values['id'])) {
66d5d6f4 3284 $values['honor'] = [
3285 'honor_profile_values' => [],
7305d3e6 3286 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3287 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
66d5d6f4 3288 ];
6a488035 3289
5d6cf648
JM
3290 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3291 $honorParams['honor_block_is_active'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
7305d3e6 3292 }
3293 else {
3294 //offline contribution
66d5d6f4 3295 $softCreditTypes = $softCredits = [];
7305d3e6 3296 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3297 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
66d5d6f4 3298 $softCredits[$key] = [
7305d3e6 3299 'Name' => $softCredit['contact_name'],
21dfd5f5 3300 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
66d5d6f4 3301 ];
7305d3e6 3302 }
3303 $template->assign('softCreditTypes', $softCreditTypes);
3304 $template->assign('softCredits', $softCredits);
3305 }
6a488035
TO
3306 }
3307
3308 $dao = new CRM_Contribute_DAO_ContributionProduct();
3309 $dao->contribution_id = $this->id;
3310 if ($dao->find(TRUE)) {
3311 $premiumId = $dao->product_id;
3312 $template->assign('option', $dao->product_option);
3313
3314 $productDAO = new CRM_Contribute_DAO_Product();
3315 $productDAO->id = $premiumId;
3316 $productDAO->find(TRUE);
3317 $template->assign('selectPremium', TRUE);
3318 $template->assign('product_name', $productDAO->name);
3319 $template->assign('price', $productDAO->price);
3320 $template->assign('sku', $productDAO->sku);
3321 }
d4578334 3322 $template->assign('title', $values['title'] ?? NULL);
858f7096 3323 $values['amount'] = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL);
3324 if (!$values['amount'] && isset($this->total_amount)) {
3325 $values['amount'] = $this->total_amount;
6a488035 3326 }
858f7096 3327
66d5d6f4 3328 $pcpParams = [
3329 'pcpBlock' => NULL,
3330 'pcp_display_in_roll' => NULL,
3331 'pcp_roll_nickname' => NULL,
3332 'pcp_personal_note' => NULL,
3333 'title' => NULL,
3334 ];
5d6cf648 3335
6a488035
TO
3336 if (strtolower($this->_component) == 'contribute') {
3337 //PCP Info
3338 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3339 $softDAO->contribution_id = $this->id;
3340 if ($softDAO->find(TRUE)) {
5d6cf648
JM
3341 $pcpParams['pcpBlock'] = TRUE;
3342 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll;
3343 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname;
3344 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note;
6a488035
TO
3345
3346 //assign the pcp page title for email subject
3347 $pcpDAO = new CRM_PCP_DAO_PCP();
3348 $pcpDAO->id = $softDAO->pcp_id;
3349 if ($pcpDAO->find(TRUE)) {
5d6cf648 3350 $pcpParams['title'] = $pcpDAO->title;
6a488035
TO
3351 }
3352 }
3353 }
5d6cf648
JM
3354 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3355 $template->assign($templateKey, $templateValue);
3356 }
6a488035
TO
3357
3358 if ($this->financial_type_id) {
3359 $values['financial_type_id'] = $this->financial_type_id;
3360 }
3361
6a488035
TO
3362 $template->assign('trxn_id', $this->trxn_id);
3363 $template->assign('receive_date',
5bab7daf 3364 CRM_Utils_Date::processDate($this->receive_date)
6a488035 3365 );
76e8d9c4 3366 $values['receipt_date'] = (empty($this->receipt_date) ? NULL : $this->receipt_date);
6a488035 3367 $template->assign('action', $this->is_test ? 1024 : 1);
d4578334 3368 $template->assign('receipt_text', $values['receipt_text'] ?? NULL);
6a488035 3369 $template->assign('is_monetary', 1);
d891a273 3370 $template->assign('is_recur', !empty($this->contribution_recur_id));
6a488035
TO
3371 $template->assign('currency', $this->currency);
3372 $template->assign('address', CRM_Utils_Address::format($input));
7089d2d8
TM
3373 if (!empty($values['customGroup'])) {
3374 $template->assign('customGroup', $values['customGroup']);
3375 }
a49aa7dd
TM
3376 if (!empty($values['softContributions'])) {
3377 $template->assign('softContributions', $values['softContributions']);
3378 }
6a488035
TO
3379 if ($this->_component == 'event') {
3380 $template->assign('title', $values['event']['title']);
3381 $participantRoles = CRM_Event_PseudoConstant::participantRole();
66d5d6f4 3382 $viewRoles = [];
6a488035
TO
3383 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
3384 $viewRoles[] = $participantRoles[$v];
3385 }
3386 $values['event']['participant_role'] = implode(', ', $viewRoles);
3387 $template->assign('event', $values['event']);
7089d2d8 3388 $template->assign('participant', $values['participant']);
6a488035
TO
3389 $template->assign('location', $values['location']);
3390 $template->assign('customPre', $values['custom_pre_id']);
3391 $template->assign('customPost', $values['custom_post_id']);
3392
3393 $isTest = FALSE;
3394 if ($this->_relatedObjects['participant']->is_test) {
3395 $isTest = TRUE;
3396 }
3397
66d5d6f4 3398 $values['params'] = [];
6a488035
TO
3399 //to get email of primary participant.
3400 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
66d5d6f4 3401 $primaryAmount[] = [
f2b2a3ff 3402 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail,
21dfd5f5 3403 'amount' => $this->_relatedObjects['participant']->fee_amount,
66d5d6f4 3404 ];
6a488035
TO
3405 //build an array of cId/pId of participants
3406 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
3407 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
3408 //send receipt to additional participant if exists
3409 if (count($additionalIDs)) {
3410 $template->assign('isPrimary', 0);
3411 $template->assign('customProfile', NULL);
3412 //set additionalParticipant true
3413 $values['params']['additionalParticipant'] = TRUE;
3414 foreach ($additionalIDs as $pId => $cId) {
66d5d6f4 3415 $amount = [];
6a488035
TO
3416 //to change the status pending to completed
3417 $additional = new CRM_Event_DAO_Participant();
3418 $additional->id = $pId;
3419 $additional->contact_id = $cId;
3420 $additional->find(TRUE);
3421 $additional->register_date = $this->_relatedObjects['participant']->register_date;
3422 $additional->status_id = 1;
3423 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
3424 //if additional participant dont have email
3425 //use display name.
3426 if (!$additionalParticipantInfo) {
3427 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
3428 }
66d5d6f4 3429 $amount[0] = [
3430 'label' => $additional->fee_level,
3431 'amount' => $additional->fee_amount,
3432 ];
3433 $primaryAmount[] = [
f2b2a3ff 3434 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo,
21dfd5f5 3435 'amount' => $additional->fee_amount,
66d5d6f4 3436 ];
6a488035 3437 $additional->save();
6a488035
TO
3438 $template->assign('amount', $amount);
3439 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3440 }
3441 }
3442
3443 //build an array of custom profile and assigning it to template
3444 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
3445
3446 if (count($customProfile)) {
3447 $template->assign('customProfile', $customProfile);
3448 }
3449
3450 // for primary contact
3451 $values['params']['additionalParticipant'] = FALSE;
3452 $template->assign('isPrimary', 1);
3453 $template->assign('amount', $primaryAmount);
3454 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
3455 if ($this->payment_instrument_id) {
3456 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
3457 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
3458 }
3459 // carry paylater, since we did not created billing,
3460 // so need to pull email from primary location, CRM-4395
3461 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
3462 }
3463 return $template;
3464 }
3465
3466 /**
100fef9d 3467 * Check whether payment processor supports
6a488035
TO
3468 * cancellation of contribution subscription
3469 *
014c4014
TO
3470 * @param int $contributionId
3471 * Contribution id.
6a488035 3472 *
77b97be7
EM
3473 * @param bool $isNotCancelled
3474 *
a130e045 3475 * @return bool
6a488035 3476 */
00be9182 3477 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
6a488035
TO
3478 $cacheKeyString = "$contributionId";
3479 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
3480
66d5d6f4 3481 static $supportsCancel = [];
6a488035
TO
3482
3483 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3484 $supportsCancel[$cacheKeyString] = FALSE;
3485 $isCancelled = FALSE;
3486
3487 if ($isNotCancelled) {
3488 $isCancelled = self::isSubscriptionCancelled($contributionId);
3489 }
3490
3491 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
3492 if (!empty($paymentObject)) {
1524a007 3493 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
6a488035
TO
3494 }
3495 }
3496 return $supportsCancel[$cacheKeyString];
3497 }
3498
3499 /**
fe482240 3500 * Check whether subscription is already cancelled.
6a488035 3501 *
014c4014
TO
3502 * @param int $contributionId
3503 * Contribution id.
6a488035 3504 *
a6c01b45
CW
3505 * @return string
3506 * contribution status
6a488035 3507 */
00be9182 3508 public static function isSubscriptionCancelled($contributionId) {
6a488035
TO
3509 $sql = "
3510 SELECT cr.contribution_status_id
3511 FROM civicrm_contribution_recur cr
3512 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3513 WHERE con.id = %1 LIMIT 1";
66d5d6f4 3514 $params = [1 => [$contributionId, 'Integer']];
6a488035 3515 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
27a3bca0 3516 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name');
6a488035
TO
3517 if ($status == 'Cancelled') {
3518 return TRUE;
3519 }
3520 return FALSE;
3521 }
3522
3523 /**
fe482240 3524 * Create all financial accounts entry.
6a488035 3525 *
014c4014
TO
3526 * @param array $params
3527 * Contribution object, line item array and params for trxn.
6a488035 3528 *
6a488035 3529 *
02af3683 3530 * @param array $financialTrxnValues
77b97be7 3531 *
9a2dce8d 3532 * @return null|\CRM_Core_BAO_FinancialTrxn
6a488035 3533 */
00be9182 3534 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
cb579c66 3535 $skipRecords = $update = $return = $isRelatedId = FALSE;
1a459cc2 3536 $isUpdate = !empty($params['prevContribution']);
02af3683 3537
66d5d6f4 3538 $additionalParticipantId = [];
6a488035 3539 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
10fd773f 3540 $contributionStatus = empty($params['contribution_status_id']) ? NULL : $contributionStatuses[$params['contribution_status_id']];
6a488035
TO
3541
3542 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
3543 $entityId = $params['participant_id'];
3544 $entityTable = 'civicrm_participant';
d37ade2e 3545 $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
6a488035 3546 }
8aa7457a
EM
3547 elseif (!empty($params['membership_id'])) {
3548 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3549 // are created off one contribution should be handled elsewhere
3550 $entityId = $params['membership_id'];
3551 $entityTable = 'civicrm_membership';
3552 }
6a488035
TO
3553 else {
3554 $entityId = $params['contribution']->id;
3555 $entityTable = 'civicrm_contribution';
3556 }
4d34aefa 3557
cb579c66
PN
3558 if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') {
3559 $isRelatedId = TRUE;
3560 }
85dea18b 3561
464bb009 3562 $entityID[] = $entityId;
d37ade2e 3563 if (!empty($additionalParticipantId)) {
3564 $entityID += $additionalParticipantId;
464bb009 3565 }
4d34aefa 3566 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
a7488080 3567 if (empty($params['prevContribution'])) {
6a488035
TO
3568 $entityID = NULL;
3569 }
4d34aefa 3570
f8325309 3571 $statusId = $params['contribution']->contribution_status_id;
f8325309 3572
6a488035 3573 // build line item array if its not set in $params
a7488080 3574 if (empty($params['line_item']) || $additionalParticipantId) {
cb579c66 3575 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
6a488035
TO
3576 }
3577
4e92d4f4 3578 if ($contributionStatus != 'Failed' &&
3579 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later)
f2b2a3ff 3580 ) {
6a488035 3581 $skipRecords = TRUE;
66d5d6f4 3582 $pendingStatus = [
4e92d4f4 3583 'Pending',
3584 'In Progress',
66d5d6f4 3585 ];
4e92d4f4 3586 if (in_array($contributionStatus, $pendingStatus)) {
bf2cf926 3587 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
3588 $params['financial_type_id'],
3589 'Accounts Receivable Account is'
3590 );
6a488035 3591 }
a7488080 3592 elseif (!empty($params['payment_processor'])) {
74afdc40 3593 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
66d5d6f4 3594 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
bf722049 3595 'id' => $params['payment_processor'],
3596 'return' => 'payment_instrument_id',
66d5d6f4 3597 ]);
6a488035 3598 }
a7488080 3599 elseif (!empty($params['payment_instrument_id'])) {
6a488035
TO
3600 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
3601 }
3602 else {
ac7514c2 3603 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
66d5d6f4 3604 $queryParams = [1 => [$relationTypeId, 'Integer']];
ac7514c2 3605 $params['to_financial_account_id'] = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
6a488035
TO
3606 }
3607
9c1bc317 3608 $totalAmount = $params['total_amount'] ?? NULL;
8cc574cf 3609 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
6a488035
TO
3610 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
3611 }
3612 //build financial transaction params
66d5d6f4 3613 $trxnParams = [
6a488035
TO
3614 'contribution_id' => $params['contribution']->id,
3615 'to_financial_account_id' => $params['to_financial_account_id'],
2d8ae159 3616 'trxn_date' => !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'),
6a488035 3617 'total_amount' => $totalAmount,
6b409353 3618 'fee_amount' => $params['fee_amount'] ?? NULL,
60a2aeee 3619 'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount),
6a488035
TO
3620 'currency' => $params['contribution']->currency,
3621 'trxn_id' => $params['contribution']->trxn_id,
2561fc11 3622 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3623 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3624 // this should really default to completed (after discussion).
f8325309 3625 'status_id' => $statusId,
bf722049 3626 'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id),
6b409353
CW
3627 'check_number' => $params['check_number'] ?? NULL,
3628 'pan_truncation' => $params['pan_truncation'] ?? NULL,
3629 'card_type_id' => $params['card_type_id'] ?? NULL,
66d5d6f4 3630 ];
8a0c74ae 3631 if ($contributionStatus == 'Refunded' || $contributionStatus == 'Chargeback' || $contributionStatus == 'Cancelled') {
10fd773f 3632 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date) ? $params['contribution']->cancel_date : date('YmdHis');
797d4c52 3633 if (isset($params['refund_trxn_id'])) {
3634 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3635 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3636 }
10fd773f 3637 }
a246714d 3638 //CRM-16259, set is_payment flag for non pending status
0170d873 3639 if (!in_array($contributionStatus, $pendingStatus)) {
a246714d
PN
3640 $trxnParams['is_payment'] = 1;
3641 }
a7488080 3642 if (!empty($params['payment_processor'])) {
8ef12e64 3643 $trxnParams['payment_processor_id'] = $params['payment_processor'];
6a488035 3644 }
0f602e3f
PJ
3645
3646 if (isset($fromFinancialAccountId)) {
3647 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3648 }
3649
3650 // consider external values passed for recording transaction entry
02af3683
EM
3651 if (!empty($financialTrxnValues)) {
3652 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
0f602e3f 3653 }
80c9b98c
PN
3654 if (empty($trxnParams['payment_processor_id'])) {
3655 unset($trxnParams['payment_processor_id']);
3656 }
0f602e3f 3657
6a488035
TO
3658 $params['trxnParams'] = $trxnParams;
3659
1a459cc2 3660 if ($isUpdate) {
99cdd94d 3661 $updated = FALSE;
404f77c9
PN
3662 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount;
3663 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount;
3664 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount;
797d4c52 3665 if (!isset($params['trxnParams']['trxn_id'])) {
3666 // Actually I have no idea why we are overwriting any values from the previous contribution.
3667 // (filling makes sense to me). However, only protecting this value as I really really know we
3668 // don't want this one overwritten.
3669 // CRM-17751.
3670 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id;
3671 }
404f77c9 3672 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id;
48ea0708 3673
182228d5 3674 if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)
f2b2a3ff
TO
3675 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses))
3676 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))
3677 ) {
182228d5
PN
3678 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
3679 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
3680 }
85dea18b 3681
404f77c9 3682 //if financial type is changed
a7488080 3683 if (!empty($params['financial_type_id']) &&
f2b2a3ff
TO
3684 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id
3685 ) {
8cf6bd83
PN
3686 $accountRelationship = 'Income Account is';
3687 if (!empty($params['revenue_recognition_date']) || $params['prevContribution']->revenue_recognition_date) {
3688 $accountRelationship = 'Deferred Revenue Account is';
3689 }
928a340b 3690 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id, $accountRelationship);
3691 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
404f77c9
PN
3692 if ($oldFinancialAccount != $newFinancialAccount) {
3693 $params['total_amount'] = 0;
1a3d69b0
SL
3694 // If we have a fee amount set reverse this as well.
3695 if (isset($params['fee_amount'])) {
3696 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3697 }
b81ee58c 3698 if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) {
928a340b 3699 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
876b8ab0 3700 $params['prevContribution']->financial_type_id, $accountRelationship);
404f77c9
PN
3701 }
3702 else {
3703 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
a7488080 3704 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
404f77c9
PN
3705 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3706 }
3707 }
3708 self::updateFinancialAccounts($params, 'changeFinancialType');
901094eb 3709 $params['skipLineItem'] = FALSE;
3710 foreach ($params['line_item'] as &$lineItems) {
3711 foreach ($lineItems as &$line) {
3712 $line['financial_type_id'] = $params['financial_type_id'];
3713 }
3714 }
3715 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
404f77c9
PN
3716 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3717 $params['financial_account_id'] = $newFinancialAccount;
8cf6bd83 3718 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
1a3d69b0
SL
3719 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3720 if (isset($params['fee_amount'])) {
3721 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3722 }
404f77c9 3723 self::updateFinancialAccounts($params);
901094eb 3724 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE);
404f77c9 3725 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
99cdd94d 3726 $updated = TRUE;
8cf6bd83 3727 $params['deferred_financial_account_id'] = $newFinancialAccount;
404f77c9 3728 }
6a488035 3729 }
48ea0708 3730
6a488035 3731 //Update contribution status
404f77c9 3732 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
797d4c52 3733 if (!isset($params['refund_trxn_id'])) {
3734 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3735 // gets preference over another so I am only 'protecting' a very specific tested flow
3736 // and letting natural justice take care of the rest.
3737 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3738 }
a7488080 3739 if (!empty($params['contribution_status_id']) &&
f2b2a3ff
TO
3740 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3741 ) {
6a488035 3742 //Update Financial Records
f8cd7ee2 3743 $callUpdateFinancialAccounts = self::updateFinancialAccountsOnContributionStatusChange($params);
3744 if ($callUpdateFinancialAccounts) {
3745 self::updateFinancialAccounts($params, 'changedStatus');
901094eb 3746 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
f8cd7ee2 3747 }
99cdd94d 3748 $updated = TRUE;
6a488035
TO
3749 }
3750
3751 // change Payment Instrument for a Completed contribution
3752 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3753 // instrument is null and now new payment instrument is added along with the payment
04cd605c 3754 if (!$params['contribution']->payment_instrument_id) {
3755 $params['contribution']->find(TRUE);
3756 }
404f77c9 3757 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
9c1bc317 3758 $params['trxnParams']['check_number'] = $params['check_number'] ?? NULL;
5ca657dd 3759
3760 if (self::isPaymentInstrumentChange($params, $pendingStatus)) {
3761 $updated = CRM_Core_BAO_FinancialTrxn::updateFinancialAccountsOnPaymentInstrumentChange($params);
6a488035 3762 }
48ea0708 3763
404f77c9 3764 //if Change contribution amount
9c1bc317
CW
3765 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ?? NULL;
3766 $params['trxnParams']['net_amount'] = $params['net_amount'] ?? NULL;
d9814f68 3767 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
404f77c9
PN
3768 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3769 if (isset($totalAmount) &&
f2b2a3ff
TO
3770 $totalAmount != $params['prevContribution']->total_amount
3771 ) {
404f77c9
PN
3772 //Update Financial Records
3773 $params['trxnParams']['from_financial_account_id'] = NULL;
404f77c9 3774 self::updateFinancialAccounts($params, 'changedAmount');
901094eb 3775 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
99cdd94d 3776 $updated = TRUE;
3777 }
3778
3779 if (!$updated) {
3780 // Looks like we might have a data correction update.
3781 // This would be a case where a transaction id has been entered but it is incorrect &
3782 // the person goes back in & fixes it, as opposed to a new transaction.
3783 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3784 // the data fix scenario.
3785 // CRM-17751.
3786 if (isset($params['refund_trxn_id'])) {
3787 $refundIDs = CRM_Core_BAO_FinancialTrxn::getRefundTransactionIDs($params['id']);
48714ae7 3788 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
66d5d6f4 3789 civicrm_api3('FinancialTrxn', 'create', [
3790 'id' => $refundIDs['financialTrxnId'],
3791 'trxn_id' => $params['refund_trxn_id'],
3792 ]);
99cdd94d 3793 }
3794 }
9c1bc317
CW
3795 $cardType = $params['card_type_id'] ?? NULL;
3796 $panTruncation = $params['pan_truncation'] ?? NULL;
2c4a6dc8 3797 CRM_Core_BAO_FinancialTrxn::updateCreditCardDetails($params['contribution']->id, $panTruncation, $cardType);
6a488035 3798 }
6a488035
TO
3799 }
3800
1a459cc2 3801 else {
1c19e0a3
PJ
3802 // records finanical trxn and entity financial trxn
3803 // also make it available as return value
9c472292 3804 self::recordAlwaysAccountsReceivable($trxnParams, $params);
9c1bc317
CW
3805 $trxnParams['pan_truncation'] = $params['pan_truncation'] ?? NULL;
3806 $trxnParams['card_type_id'] = $params['card_type_id'] ?? NULL;
1c19e0a3 3807 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
3d93e98e 3808 $params['entity_id'] = $financialTxn->id;
f49cdeab 3809 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3d93e98e
PN
3810 self::$_trxnIDs[] = $financialTxn->id;
3811 }
6a488035 3812 }
e005ab6b 3813 }
b44e3f84 3814 // record line items and financial items
a7488080 3815 if (empty($params['skipLineItem'])) {
1a459cc2 3816 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
6a488035
TO
3817 }
3818
14b74ca6 3819 // create batch entry if batch_id is passed and
3820 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3821 if (!empty($params['batch_id']) && !empty($financialTxn)) {
66d5d6f4 3822 $entityParams = [
6a488035
TO
3823 'batch_id' => $params['batch_id'],
3824 'entity_table' => 'civicrm_financial_trxn',
3825 'entity_id' => $financialTxn->id,
66d5d6f4 3826 ];
ee20d7be 3827 CRM_Batch_BAO_EntityBatch::create($entityParams);
6a488035
TO
3828 }
3829
3830 // when a fee is charged
8cc574cf 3831 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
6a488035
TO
3832 CRM_Core_BAO_FinancialTrxn::recordFees($params);
3833 }
3834
a7488080 3835 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
f2b2a3ff
TO
3836 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3837 ) {
6a488035
TO
3838 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3839 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
3840 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
3841 }
3842 unset($params['line_item']);
7b361924 3843 self::$_trxnIDs = NULL;
1c19e0a3 3844 return $return;
6a488035
TO
3845 }
3846
3847 /**
fe482240 3848 * Update all financial accounts entry.
6a488035 3849 *
014c4014
TO
3850 * @param array $params
3851 * Contribution object, line item array and params for trxn.
6a488035 3852 *
014c4014
TO
3853 * @param string $context
3854 * Update scenarios.
6a488035 3855 *
66d5d6f4 3856 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3857 * adds unpredictability.
3858 *
6a488035 3859 */
8a477059 3860 public static function updateFinancialAccounts(&$params, $context = NULL) {
3861 $trxnID = NULL;
3862 $inputParams = $params;
05a42c4a 3863 $isARefund = self::isContributionUpdateARefund($params['prevContribution']->contribution_status_id, $params['contribution']->contribution_status_id);
8a477059 3864
ea2ca75d 3865 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
3866 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3867 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount);
3868 }
3869
b34861f3 3870 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
8a40179e 3871 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
b34861f3 3872 $params['entity_id'] = $trxn->id;
6a488035 3873
efb16c63 3874 $itemParams['entity_table'] = 'civicrm_line_item';
3875 $trxnIds['id'] = $params['entity_id'];
3876 $previousLineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($params['contribution']->id);
3877 foreach ($params['line_item'] as $fieldId => $fields) {
592a64a0 3878 $params = self::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
6a488035
TO
3879 }
3880 }
3881
52da5b1e 3882 /**
3883 * Is this contribution status a reversal.
3884 *
3885 * If so we would expect to record a negative value in the financial_trxn table.
3886 *
3887 * @param int $status_id
3888 *
3889 * @return bool
3890 */
3891 public static function isContributionStatusNegative($status_id) {
66d5d6f4 3892 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
05a42c4a 3893 return in_array(CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
52da5b1e 3894 }
3895
6a488035 3896 /**
fe482240 3897 * Check status validation on update of a contribution.
6a488035 3898 *
014c4014
TO
3899 * @param array $values
3900 * Previous form values before submit.
6a488035 3901 *
014c4014
TO
3902 * @param array $fields
3903 * The input form values.
6a488035 3904 *
014c4014
TO
3905 * @param array $errors
3906 * List of errors.
6a488035 3907 *
77b97be7 3908 * @return bool
6a488035 3909 */
00be9182 3910 public static function checkStatusValidation($values, &$fields, &$errors) {
8cc574cf 3911 if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) {
c71ae314
PN
3912 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3913 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3914 return FALSE;
3915 }
3916 }
6a488035 3917 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
66d5d6f4 3918 $checkStatus = [
3919 'Cancelled' => ['Completed', 'Refunded'],
3920 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3921 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3922 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3923 'Refunded' => ['Cancelled', 'Completed'],
3924 'Partially paid' => ['Completed'],
7142a4c8 3925 'Pending refund' => ['Completed', 'Refunded'],
5acf0703 3926 'Failed' => ['Pending'],
66d5d6f4 3927 ];
6a488035 3928
da017017 3929 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
66d5d6f4 3930 CRM_Utils_Array::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
da017017 3931 ) {
66d5d6f4 3932 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
353ffa53
TO
3933 1 => $contributionStatuses[$values['contribution_status_id']],
3934 2 => $contributionStatuses[$fields['contribution_status_id']],
66d5d6f4 3935 ]);
6a488035
TO
3936 }
3937 }
c3d24ba7
PN
3938
3939 /**
fe482240 3940 * Delete contribution of contact.
c3d24ba7 3941 *
0e480632 3942 * @see https://issues.civicrm.org/jira/browse/CRM-12155
c3d24ba7 3943 *
014c4014
TO
3944 * @param int $contactId
3945 * Contact id.
c3d24ba7 3946 *
c3d24ba7 3947 */
00be9182 3948 public static function deleteContactContribution($contactId) {
c3d24ba7
PN
3949 $contribution = new CRM_Contribute_DAO_Contribution();
3950 $contribution->contact_id = $contactId;
3951 $contribution->find();
3952 while ($contribution->fetch()) {
3953 self::deleteContribution($contribution->id);
3954 }
3955 }
16c0ec8d
CW
3956
3957 /**
3958 * Get options for a given contribution field.
16c0ec8d 3959 *
014c4014 3960 * @param string $fieldName
bed98343 3961 * @param string $context see CRM_Core_DAO::buildOptionsContext.
66d5d6f4 3962 * @param array $props whatever is known about this dao object.
77b97be7 3963 *
a130e045 3964 * @return array|bool
66d5d6f4 3965 * @see CRM_Core_DAO::buildOptions
3966 *
16c0ec8d 3967 */
66d5d6f4 3968 public static function buildOptions($fieldName, $context = NULL, $props = []) {
16c0ec8d 3969 $className = __CLASS__;
66d5d6f4 3970 $params = [];
9d5c7f14 3971 if (isset($props['orderColumn'])) {
3972 $params['orderColumn'] = $props['orderColumn'];
3973 }
16c0ec8d
CW
3974 switch ($fieldName) {
3975 // This field is not part of this object but the api supports it
3976 case 'payment_processor':
3977 $className = 'CRM_Contribute_BAO_ContributionPage';
3978 // Filter results by contribution page
3979 if (!empty($props['contribution_page_id'])) {
66d5d6f4 3980 $page = civicrm_api('contribution_page', 'getsingle', [
03a8c3dc 3981 'version' => 3,
21dfd5f5 3982 'id' => ($props['contribution_page_id']),
66d5d6f4 3983 ]);
16c0ec8d
CW
3984 $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0);
3985 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3986 }
33a429d4 3987 break;
ea100cb5 3988
33a429d4
CW
3989 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3990 case 'honor_type_id':
3991 $className = 'CRM_Contribute_BAO_ContributionSoft';
3992 $fieldName = 'soft_credit_type_id';
3993 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3994 break;
f831ac20
EE
3995
3996 case 'contribution_status_id':
3997 if ($context !== 'validate') {
3998 $params['condition'] = "v.name <> 'Template'";
3999 }
16c0ec8d
CW
4000 }
4001 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
4002 }
03a8c3dc 4003
3b67ab13 4004 /**
fe482240 4005 * Validate financial type.
3b67ab13 4006 *
0e480632 4007 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3b67ab13 4008 *
014c4014
TO
4009 * @param int $financialTypeId
4010 * Financial Type id.
3b67ab13 4011 *
77b97be7
EM
4012 * @param string $relationName
4013 *
4014 * @return array|bool
3b67ab13 4015 */
00be9182 4016 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
876b8ab0 4017 $financialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeId, $relationName);
3b67ab13
PN
4018
4019 if (!$financialAccount) {
4020 return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
4021 }
4022 return FALSE;
4023 }
16c0ec8d 4024
186c9c17 4025 /**
f6044c2b 4026 * @param int $targetCid
186c9c17 4027 * @param $activityType
f6044c2b 4028 * @param string $title
100fef9d 4029 * @param int $contributionId
f59c3d85 4030 * @param string $totalAmount
4031 * @param string $currency
4032 * @param string $trxn_date
186c9c17 4033 *
f59c3d85 4034 * @throws \CRM_Core_Exception
4035 * @throws \CiviCRM_API3_Exception
186c9c17 4036 */
f59c3d85 4037 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
4038 $paymentAmount = CRM_Utils_Money::format($totalAmount, $currency);
685dc433 4039 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
f59c3d85 4040 $date = CRM_Utils_Date::isoToMysql($trxn_date);
685dc433
PN
4041 // source record id would be the contribution id
4042 $srcRecId = $contributionId;
bd99f5fe
PJ
4043
4044 // activity params
66d5d6f4 4045 $activityParams = [
bd99f5fe
PJ
4046 'source_contact_id' => $targetCid,
4047 'source_record_id' => $srcRecId,
d66c61b6 4048 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
bd99f5fe
PJ
4049 'subject' => $subject,
4050 'activity_date_time' => $date,
d66c61b6 4051 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
bd99f5fe 4052 'skipRecentView' => TRUE,
66d5d6f4 4053 ];
bd99f5fe
PJ
4054
4055 // create activity with target contacts
4056 $session = CRM_Core_Session::singleton();
4057 $id = $session->get('userID');
4058 if ($id) {
4059 $activityParams['source_contact_id'] = $id;
4060 $activityParams['target_contact_id'][] = $targetCid;
4061 }
f59c3d85 4062 civicrm_api3('Activity', 'create', $activityParams);
0f602e3f 4063 }
16c0ec8d 4064
186c9c17 4065 /**
fe482240 4066 * Get list of payments displayed by Contribute_Page_PaymentInfo.
8cf01b22 4067 *
100fef9d 4068 * @param int $id
4924bfe9 4069 * @param string $component
186c9c17 4070 * @param bool $getTrxnInfo
186c9c17
EM
4071 *
4072 * @return mixed
4924bfe9 4073 *
4074 * @throws \CRM_Core_Exception
4075 * @throws \CiviCRM_API3_Exception
186c9c17 4076 */
4924bfe9 4077 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
a79d2ec2 4078 // @todo deprecate passing in component - always call with contribution.
29c61b58 4079 if ($component == 'event') {
29c61b58 4080 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
ae53df5f
PJ
4081
4082 if (!$contributionId) {
4083 if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4084 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4085 $id = $primaryParticipantId;
4086 }
22825dfc 4087 if (!$contributionId) {
4088 return;
ae53df5f
PJ
4089 }
4090 }
29c61b58 4091 }
268a84f2 4092 elseif ($component == 'membership') {
268a84f2 4093 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4094 }
d4c0653f 4095 else {
4096 $contributionId = $id;
d4c0653f 4097 }
4098
4924bfe9 4099 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
4100 // but need to unpick the whole trxn_id it's returning first.
4101 $oldCalculation = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
4102 $baseTrxnId = !empty($oldCalculation['trxn_id']) ? $oldCalculation['trxn_id'] : NULL;
4d193d61 4103 if (!$baseTrxnId) {
5684b818
PJ
4104 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
4105 $baseTrxnId = $baseTrxnId['financialTrxnId'];
5684b818 4106 }
4924bfe9 4107 $total = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
1010c4e1 4108
abafc4c4 4109 $paymentBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionId, $total);
4110
66d5d6f4 4111 $contribution = civicrm_api3('Contribution', 'getsingle', [
4112 'id' => $contributionId,
4113 'return' => [
4114 'currency',
4115 'is_pay_later',
4116 'contribution_status_id',
4117 'financial_type_id',
4118 ],
4119 ]);
8cf01b22 4120
c0406a91 4121 $info['payLater'] = $contribution['is_pay_later'];
4122 $info['contribution_status'] = $contribution['contribution_status'];
eb6acea3 4123 $info['currency'] = $contribution['currency'];
c0406a91 4124
29c61b58
PJ
4125 $info['total'] = $total;
4126 $info['paid'] = $total - $paymentBalance;
4127 $info['balance'] = $paymentBalance;
4128 $info['id'] = $id;
4129 $info['component'] = $component;
bc2eeabb 4130 if ($getTrxnInfo && $baseTrxnId) {
c086e797 4131 $info['transaction'] = self::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
29c61b58 4132 }
c0406a91 4133
4134 $info['payment_links'] = self::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
29c61b58
PJ
4135 return $info;
4136 }
5a18a545 4137
26085eab 4138 /**
4139 * Get the outstanding balance on a contribution.
4140 *
4141 * @param int $contributionId
4142 * @param float $contributionTotal
4143 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4144 *
4145 * @return float
4146 */
4147 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
26085eab 4148 if ($contributionTotal === NULL) {
4149 $contributionTotal = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
4150 }
26085eab 4151
ee080cf8 4152 return (float) CRM_Utils_Money::subtractCurrencies(
89bfb100 4153 $contributionTotal,
5ab2fd4f 4154 CRM_Core_BAO_FinancialTrxn::getTotalPayments($contributionId, TRUE),
89bfb100
MD
4155 CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4156 );
26085eab 4157 }
4158
7a9ab499 4159 /**
2912ed09 4160 * Get the tax amount (misnamed function).
7a9ab499
EM
4161 *
4162 * @param array $params
7a9ab499 4163 *
2912ed09 4164 * @return array
ba63d813 4165 * @throws \CiviCRM_API3_Exception
7a9ab499 4166 */
ba63d813 4167 protected static function checkTaxAmount($params) {
b5935203 4168 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
4169
7a9ab499 4170 // Update contribution.
b5935203 4171 if (!empty($params['id'])) {
2912ed09 4172 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4173 // there are no tax implications - early return.
4174 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4175 return $params;
4176 }
4177 if (empty($params['prevContribution'])) {
4178 $params['prevContribution'] = self::getOriginalContribution($params['id']);
4179 }
a76b8bd8 4180
66d5d6f4 4181 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
2912ed09 4182 if (!isset($params[$field])) {
4183 if ($field == 'total_amount' && $params['prevContribution']->tax_amount) {
4184 // Tax amount gets added back on later....
4185 $params['total_amount'] = $params['prevContribution']->total_amount -
4186 $params['prevContribution']->tax_amount;
99a4cd32
SL
4187 }
4188 else {
2912ed09 4189 $params[$field] = $params['prevContribution']->$field;
4190 if ($params[$field] != $params['prevContribution']->$field) {
2912ed09 4191 }
99a4cd32
SL
4192 }
4193 }
b107e882 4194 }
a76b8bd8 4195
2912ed09 4196 self::calculateMissingAmountParams($params, $params['id']);
4197 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4198 // Assign tax Amount on update of contribution
4199 if (!empty($params['prevContribution']->tax_amount)) {
b5935203 4200 $params['tax_amount'] = 'null';
66d5d6f4 4201 CRM_Price_BAO_LineItem::getLineItemArray($params, [$params['id']]);
b5935203 4202 foreach ($params['line_item'] as $setID => $priceField) {
4203 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4204 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4205 }
4206 }
4207 }
4208 }
4209 }
4210
2912ed09 4211 // New Contribution and update of contribution with tax rate financial type
5525990d 4212 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
ba63d813 4213 empty($params['skipLineItem'])) {
f2b2a3ff 4214 $taxRateParams = $taxRates[$params['financial_type_id']];
6fec0f2e 4215 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount(CRM_Utils_Array::value('total_amount', $params), $taxRateParams);
4706ed3b 4216 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
b5935203 4217
f2b2a3ff
TO
4218 // Get Line Item on update of contribution
4219 if (isset($params['id'])) {
66d5d6f4 4220 CRM_Price_BAO_LineItem::getLineItemArray($params, [$params['id']]);
f2b2a3ff
TO
4221 }
4222 else {
4223 CRM_Price_BAO_LineItem::getLineItemArray($params);
4224 }
4225 foreach ($params['line_item'] as $setID => $priceField) {
4226 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4227 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
b5935203 4228 }
5525990d 4229 }
def7e770 4230 $params['total_amount'] = CRM_Utils_Array::value('total_amount', $params) + $params['tax_amount'];
f2b2a3ff 4231 }
4c9b6178 4232 elseif (isset($params['api.line_item.create'])) {
5525990d 4233 // Update total amount of contribution using lineItem
66d5d6f4 4234 $taxAmountArray = [];
b5935203 4235 foreach ($params['api.line_item.create'] as $key => $value) {
4236 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
f2b2a3ff 4237 $taxRate = $taxRates[$value['financial_type_id']];
5525990d 4238 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate);
4706ed3b 4239 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
b5935203 4240 }
4241 }
4242 $params['tax_amount'] = array_sum($taxAmountArray);
5525990d 4243 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
b5935203 4244 }
a5bf8a53 4245
b5935203 4246 return $params;
4247 }
96025800 4248
4d47ad17
PN
4249 /**
4250 * Check financial type validation on update of a contribution.
4251 *
5ba7d840 4252 * @param int $financialTypeId
4d47ad17
PN
4253 * Value of latest Financial Type.
4254 *
5ba7d840 4255 * @param int $contributionId
4d47ad17
PN
4256 * Contribution Id.
4257 *
4258 * @param array $errors
4259 * List of errors.
4260 *
81716ddb 4261 * @return void
4d47ad17
PN
4262 */
4263 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4264 if (!empty($financialTypeId)) {
4265 $oldFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4266 if ($oldFinancialTypeId == $financialTypeId) {
81716ddb 4267 return;
4d47ad17
PN
4268 }
4269 }
4270 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
66d5d6f4 4271 $params = [
4272 '1' => [$contributionId, 'Integer'],
4273 ];
4d47ad17
PN
4274 $result = CRM_Core_DAO::executeQuery($sql, $params);
4275 if ($result->N > 1) {
4276 $errors['financial_type_id'] = ts('One or more line items have a different financial type than the contribution. Editing the financial type is not yet supported in this situation.');
4277 }
4278 }
4279
6d0cf504
EM
4280 /**
4281 * Update related pledge payment payments.
4282 *
5e27919e
EM
4283 * This function has been refactored out of the back office contribution form and may
4284 * still overlap with other functions.
4285 *
6d0cf504
EM
4286 * @param string $action
4287 * @param int $pledgePaymentID
4288 * @param int $contributionID
4289 * @param bool $adjustTotalAmount
4290 * @param float $total_amount
4291 * @param float $original_total_amount
4292 * @param int $contribution_status_id
4293 * @param int $original_contribution_status_id
4294 */
5e27919e 4295 public static function updateRelatedPledge(
6d0cf504
EM
4296 $action,
4297 $pledgePaymentID,
4298 $contributionID,
4299 $adjustTotalAmount,
4300 $total_amount,
4301 $original_total_amount,
4302 $contribution_status_id,
4303 $original_contribution_status_id
4304 ) {
8e776a1a
SB
4305 if (!$pledgePaymentID && $action & CRM_Core_Action::ADD && !$contributionID) {
4306 return;
4307 }
4308
6d0cf504
EM
4309 if ($pledgePaymentID) {
4310 //store contribution id in payment record.
4311 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4312 }
4313 else {
4314 $pledgePaymentID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4315 $contributionID,
4316 'id',
4317 'contribution_id'
4318 );
4319 }
fcdf24a4 4320
8e776a1a 4321 if (!$pledgePaymentID) {
fcdf24a4
SB
4322 return;
4323 }
6d0cf504
EM
4324 $pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4325 $contributionID,
4326 'pledge_id',
4327 'contribution_id'
4328 );
4329
4330 $updatePledgePaymentStatus = FALSE;
4331
4332 // If either the status or the amount has changed we update the pledge status.
4333 if ($action & CRM_Core_Action::ADD) {
4334 $updatePledgePaymentStatus = TRUE;
4335 }
4336 elseif ($action & CRM_Core_Action::UPDATE && (($original_contribution_status_id != $contribution_status_id) ||
4337 ($original_total_amount != $total_amount))
4338 ) {
4339 $updatePledgePaymentStatus = TRUE;
4340 }
4341
4342 if ($updatePledgePaymentStatus) {
4343 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID,
66d5d6f4 4344 [$pledgePaymentID],
6d0cf504
EM
4345 $contribution_status_id,
4346 NULL,
4347 $total_amount,
4348 $adjustTotalAmount
4349 );
4350 }
4351 }
456b0145 4352
3c49d90c 4353 /**
4354 * Is there only one line item attached to the contribution.
4355 *
4356 * @param int $id
4357 * Contribution ID.
4358 *
4359 * @return bool
4360 * @throws \CiviCRM_API3_Exception
4361 */
4362 public static function isSingleLineItem($id) {
66d5d6f4 4363 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
3c49d90c 4364 return ($lineItemCount == 1);
4365 }
4366
db59bb73
EM
4367 /**
4368 * Complete an order.
4369 *
4370 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4371 *
4372 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4373 *
4374 * Moving it out of the BaseIPN class is just the first step.
4375 *
4376 * @param array $input
4377 * @param array $ids
fedc226f 4378 * @param \CRM_Contribute_BAO_Contribution $contribution
362f37fc 4379 * @param bool $isPostPaymentCreate
4380 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4381 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4382 * transitioning related elements).
bc854509 4383 *
4384 * @return array
362f37fc 4385 * @throws \CRM_Core_Exception
4386 * @throws \CiviCRM_API3_Exception
db59bb73 4387 */
fedc226f 4388 public static function completeOrder($input, $ids, $contribution, $isPostPaymentCreate = FALSE) {
884f7828 4389 $transaction = new CRM_Core_Transaction();
c7497653 4390 // @todo see if we even need this - it's used further down to create an activity
4391 // but the BAO layer should create that - we just need to add a test to cover it & can
4392 // maybe remove $ids altogether.
adb4fb96 4393 $contributionContactID = $ids['related_contact'];
4394 $participantID = $ids['participant'];
4395 $recurringContributionID = $ids['contributionRecur'];
4396
c7497653 4397 // Unset ids just to make it clear it's not used again.
4398 unset($ids);
66df7769 4399 // The previous details are used when calculating line items so keep it before any code that 'does something'
4400 if (!empty($contribution->id)) {
981e0d0b 4401 $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(['id' => $contribution->id]);
66df7769 4402 }
66d5d6f4 4403 $inputContributionWhiteList = [
b3b7f4c5 4404 'fee_amount',
4405 'net_amount',
4406 'trxn_id',
4407 'check_number',
4408 'payment_instrument_id',
4409 'is_test',
1c98b2d6 4410 'campaign_id',
12829b5d 4411 'receive_date',
d9924163 4412 'receipt_date',
d5580ed4 4413 'contribution_status_id',
a55e39e9 4414 'card_type_id',
4415 'pan_truncation',
fa839a68 4416 'financial_type_id',
66d5d6f4 4417 ];
b3b7f4c5 4418
dc65872a 4419 $paymentProcessorId = $input['payment_processor_id'] ?? NULL;
43c8d1dd 4420
b929cdb4 4421 $completedContributionStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4422
66d5d6f4 4423 $contributionParams = array_merge([
b929cdb4 4424 'contribution_status_id' => $completedContributionStatusID,
26626bac 4425 'source' => self::getRecurringContributionDescription($contribution, $participantID),
66d5d6f4 4426 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
b3b7f4c5 4427 ));
19893cf2 4428
34dc58e7 4429 $contributionParams['payment_processor'] = $paymentProcessorId;
b3b7f4c5 4430
55bc843d 4431 if (empty($contributionParams['payment_instrument_id']) && $paymentProcessorId) {
bf302610 4432 $contributionParams['payment_instrument_id'] = PaymentProcessor::get(FALSE)->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id'];
f443eb02
SL
4433 }
4434
294cc627 4435 if ($recurringContributionID) {
4436 $contributionParams['contribution_recur_id'] = $recurringContributionID;
b3b7f4c5 4437 }
7f4ef731 4438 $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
4439
c80d977f 4440 $contributionResult = self::repeatTransaction($contribution, $input, $contributionParams);
eed14abb 4441 $contributionID = (int) $contribution->id;
db59bb73 4442
db59bb73 4443 if ($input['component'] == 'contribute') {
185a4fe8
MW
4444 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4445 self::updateMembershipBasedOnCompletionOfContribution(
eed14abb 4446 $contributionID,
185a4fe8
MW
4447 $changeDate
4448 );
4449 }
db59bb73
EM
4450 }
4451 else {
0bad10e7 4452 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
adb4fb96 4453 $participantParams['id'] = $participantID;
1c98b2d6 4454 $participantParams['status_id'] = 'Registered';
66df7769 4455 civicrm_api3('Participant', 'create', $participantParams);
db59bb73 4456 }
db59bb73
EM
4457 }
4458
eed14abb 4459 $contributionParams['id'] = $contributionID;
362f37fc 4460 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
db59bb73 4461
c80d977f
JP
4462 if (!$contributionResult) {
4463 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4464 }
db59bb73 4465
d33f8fc4 4466 $contribution->contribution_status_id = $contributionParams['contribution_status_id'];
db59bb73 4467
6e902643 4468 CRM_Core_Error::debug_log_message('Contribution record updated successfully');
db59bb73
EM
4469 $transaction->commit();
4470
70a27406 4471 // @todo - check if Contribution::create does this, test, remove.
eed14abb 4472 CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contributionID, $recurringContributionID,
43c8d1dd 4473 $contributionParams['contribution_status_id'], $input['amount']);
db59bb73
EM
4474
4475 // create an activity record
70a27406 4476 // @todo - check if Contribution::create does this, test, remove.
db59bb73
EM
4477 if ($input['component'] == 'contribute') {
4478 //CRM-4027
4479 $targetContactID = NULL;
c7497653 4480 if ($contributionContactID) {
db59bb73 4481 $targetContactID = $contribution->contact_id;
c7497653 4482 $contribution->contact_id = $contributionContactID;
db59bb73 4483 }
7d2c3972 4484 CRM_Activity_BAO_Activity::addActivity($contribution, 'Contribution', $targetContactID);
db59bb73
EM
4485 }
4486
68dce20c 4487 if (self::isEmailReceipt($input, $contribution->contribution_page_id, $recurringContributionID)) {
66d5d6f4 4488 civicrm_api3('Contribution', 'sendconfirmation', [
eed14abb 4489 'id' => $contributionID,
ec7e3954 4490 'payment_processor_id' => $paymentProcessorId,
66d5d6f4 4491 ]);
db59bb73
EM
4492 CRM_Core_Error::debug_log_message("Receipt sent");
4493 }
4494
4495 CRM_Core_Error::debug_log_message("Success: Database updated");
734d2daa 4496 return $contributionResult;
db59bb73
EM
4497 }
4498
4499 /**
4500 * Send receipt from contribution.
4501 *
4502 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4503 *
4504 * Note that the compose message part has been moved to contribution
4505 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4506 *
4507 * @param array $input
4508 * Incoming data from Payment processor.
4509 * @param array $ids
4510 * Related object IDs.
ec7e3954 4511 * @param int $contributionID
db59bb73
EM
4512 * @param bool $returnMessageText
4513 * Should text be returned instead of sent. This.
4514 * is because the function is also used to generate pdfs
4515 *
4516 * @return array
ec7e3954
E
4517 * @throws \CRM_Core_Exception
4518 * @throws \CiviCRM_API3_Exception
49cba3ad 4519 * @throws \Exception
db59bb73 4520 */
0d07fe4e 4521 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4522 $values = [];
ec7e3954
E
4523 $contribution = new CRM_Contribute_BAO_Contribution();
4524 $contribution->id = $contributionID;
4525 if (!$contribution->find(TRUE)) {
4526 throw new CRM_Core_Exception('Contribution does not exist');
4527 }
4528 $contribution->loadRelatedObjects($input, $ids, TRUE);
db59bb73
EM
4529 // set receipt from e-mail and name in value
4530 if (!$returnMessageText) {
cefed6df 4531 list($values['receipt_from_name'], $values['receipt_from_email']) = self::generateFromEmailAndName($input, $contribution);
db59bb73 4532 }
3b28799d 4533 $values['contribution_status'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id);
d891a273 4534 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
2439fa7b 4535 if ((!isset($input['receipt_update']) || $input['receipt_update']) && empty($contribution->receipt_date)) {
66d5d6f4 4536 civicrm_api3('Contribution', 'create', [
4537 'receipt_date' => 'now',
4538 'id' => $contribution->id,
4539 ]);
cc7b912f 4540 }
76e8d9c4 4541 return $return;
db59bb73
EM
4542 }
4543
cefed6df
SL
4544 /**
4545 * Generate From email and from name in an array values
66d5d6f4 4546 *
81716ddb
EE
4547 * @param array $input
4548 * @param \CRM_Contribute_BAO_Contribution $contribution
66d5d6f4 4549 *
81716ddb 4550 * @return array
cefed6df
SL
4551 */
4552 public static function generateFromEmailAndName($input, $contribution) {
beac1417 4553 // Use input value if supplied.
cefed6df 4554 if (!empty($input['receipt_from_email'])) {
66d5d6f4 4555 return [
c91b34a5 4556 CRM_Utils_Array::value('receipt_from_name', $input, ''),
66d5d6f4 4557 $input['receipt_from_email'],
4558 ];
cefed6df
SL
4559 }
4560 // if we are still empty see if we can use anything from a contribution page.
66d5d6f4 4561 $pageValues = [];
cefed6df 4562 if (!empty($contribution->contribution_page_id)) {
66d5d6f4 4563 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id]);
cefed6df
SL
4564 }
4565 // if we are still empty see if we can use anything from a contribution page.
4566 if (!empty($pageValues['receipt_from_email'])) {
66d5d6f4 4567 return [
343ed83d 4568 CRM_Utils_Array::value('receipt_from_name', $pageValues),
66d5d6f4 4569 $pageValues['receipt_from_email'],
4570 ];
cefed6df 4571 }
b5bfb58f
SL
4572 // If we are still empty fall back to the domain or logged in user information.
4573 return CRM_Core_BAO_Domain::getDefaultReceiptFrom();
cefed6df
SL
4574 }
4575
4ae9c8ac 4576 /**
4577 * Load related memberships.
4578 *
66d5d6f4 4579 * @param array $ids
4580 *
4581 * @return array $ids
4582 *
4583 * @throws Exception
72d57998 4584 * @deprecated
4585 *
4ae9c8ac 4586 * Note that in theory it should be possible to retrieve these from the line_item table
4587 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4588 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4589 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4590 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4591 *
4592 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4593 *
4ae9c8ac 4594 */
e6c7e48d 4595 public function loadRelatedMembershipObjects($ids = []) {
4ae9c8ac 4596 $query = "
4597 SELECT membership_id
4598 FROM civicrm_membership_payment
4599 WHERE contribution_id = %1 ";
66d5d6f4 4600 $params = [1 => [$this->id, 'Integer']];
4601 $ids['membership'] = (array) CRM_Utils_Array::value('membership', $ids, []);
4ae9c8ac 4602
4603 $dao = CRM_Core_DAO::executeQuery($query, $params);
4604 while ($dao->fetch()) {
356bfcaf 4605 if ($dao->membership_id && !in_array($dao->membership_id, $ids['membership'])) {
4606 $ids['membership'][$dao->membership_id] = $dao->membership_id;
4ae9c8ac 4607 }
4608 }
4609
4610 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4611 foreach ($ids['membership'] as $id) {
4612 if (!empty($id)) {
4613 $membership = new CRM_Member_BAO_Membership();
4614 $membership->id = $id;
4615 if (!$membership->find(TRUE)) {
4616 throw new Exception("Could not find membership record: $id");
4617 }
4618 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
4619 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
4620 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
6e948f0d
SP
4621 $this->_relatedObjects['membership'][$membership->id . '_' . $membership->membership_type_id] = $membership;
4622
4ae9c8ac 4623 }
4624 }
4625 }
e6c7e48d 4626 return $ids;
4ae9c8ac 4627 }
4628
7f4ef731 4629 /**
467fe956 4630 * Get the description (source field) for the recurring contribution.
4631 *
4632 * @param CRM_Contribute_BAO_Contribution $contribution
26626bac 4633 * @param int|null $participantID
467fe956 4634 *
81716ddb 4635 * @return string
467fe956 4636 * @throws \CiviCRM_API3_Exception
26626bac 4637 * @throws \API_Exception
467fe956 4638 */
26626bac 4639 protected static function getRecurringContributionDescription($contribution, $participantID) {
6046ccbb 4640 if (!empty($contribution->source)) {
7b9947fb
ML
4641 return $contribution->source;
4642 }
4052b01e 4643 elseif (!empty($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) {
66d5d6f4 4644 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
7f4ef731 4645 'id' => $contribution->contribution_page_id,
4646 'return' => 'title',
66d5d6f4 4647 ]);
7f4ef731 4648 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4649 }
26626bac 4650 elseif ($participantID) {
4651 $eventTitle = Participant::get(FALSE)
4652 ->addSelect('event.title')
4653 ->addWhere('id', '=', (int) $participantID)
4654 ->execute()->first()['event.title'];
4655 return ts('Online Event Registration') . ': ' . $eventTitle;
7f4ef731 4656 }
bef53ccf 4657 elseif (!empty($contribution->contribution_recur_id)) {
4658 return 'recurring contribution';
4659 }
4660 return '';
7f4ef731 4661 }
4662
27d9f6c5 4663 /**
5ba7d840 4664 * Function use to store line item proportionally in in entity financial trxn table
27d9f6c5 4665 *
955ee56e 4666 * @param array $trxnParams
8de1ade9 4667 *
5ba7d840 4668 * @param int $trxnId
8de1ade9
PN
4669 *
4670 * @param float $contributionTotalAmount
27d9f6c5 4671 *
5ba7d840 4672 * @throws \CiviCRM_API3_Exception
27d9f6c5 4673 */
955ee56e
PN
4674 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4675 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($trxnParams['contribution_id']);
27d9f6c5
PN
4676 if (!empty($lineItems)) {
4677 // get financial item
8e10ee7c 4678 list($ftIds, $taxItems) = self::getLastFinancialItemIds($trxnParams['contribution_id']);
66d5d6f4 4679 $entityParams = [
8e10ee7c
PN
4680 'contribution_total_amount' => $contributionTotalAmount,
4681 'trxn_total_amount' => $trxnParams['total_amount'],
4682 'trxn_id' => $trxnId,
66d5d6f4 4683 ];
8e10ee7c 4684 self::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
27d9f6c5
PN
4685 }
4686 }
4687
5c8b902b 4688 /**
b8e45de5
O
4689 * Checks if line items total amounts
4690 * match the contribution total amount.
5c8b902b
PN
4691 *
4692 * @param array $params
4693 * array of order params.
4694 *
bc854509 4695 * @throws \API_Exception
5c8b902b
PN
4696 */
4697 public static function checkLineItems(&$params) {
9c1bc317 4698 $totalAmount = $params['total_amount'] ?? NULL;
5c8b902b 4699 $lineItemAmount = 0;
c16c6ad8 4700
5c8b902b
PN
4701 foreach ($params['line_items'] as &$lineItems) {
4702 foreach ($lineItems['line_item'] as &$item) {
4703 if (empty($item['financial_type_id'])) {
4704 $item['financial_type_id'] = $params['financial_type_id'];
4705 }
dffc9c5f 4706 $lineItemAmount += $item['line_total'] + ($item['tax_amount'] ?? 0.00);
5c8b902b
PN
4707 }
4708 }
c16c6ad8 4709
5c8b902b
PN
4710 if (!isset($totalAmount)) {
4711 $params['total_amount'] = $lineItemAmount;
4712 }
c16c6ad8 4713 else {
dffc9c5f 4714 $currency = $params['currency'] ?? CRM_Core_Config::singleton()->defaultCurrency;
c16c6ad8
CR
4715
4716 if (!CRM_Utils_Money::equals($totalAmount, $lineItemAmount, $currency)) {
4717 throw new CRM_Contribute_Exception_CheckLineItemsException();
4718 }
5c8b902b 4719 }
5c8b902b
PN
4720 }
4721
bf2cf926 4722 /**
4723 * Get the financial account for the item associated with the new transaction.
4724 *
4725 * @param array $params
cf28d075 4726 * @param int $default
bf2cf926 4727 *
4728 * @return int
4729 */
cf28d075 4730 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
bf2cf926 4731
4732 if (!empty($params['financial_account_id'])) {
4733 return $params['financial_account_id'];
4734 }
c16c6ad8 4735
bf2cf926 4736 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['contribution_status_id'], 'name');
66d5d6f4 4737 $preferredAccountsRelationships = [
bf2cf926 4738 'Refunded' => 'Credit/Contra Revenue Account is',
4739 'Chargeback' => 'Chargeback Account is',
66d5d6f4 4740 ];
c16c6ad8 4741
bf2cf926 4742 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4743 $financialTypeID = !empty($params['financial_type_id']) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
4744 return CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
4745 $financialTypeID,
4746 $preferredAccountsRelationships[$contributionStatus]
4747 );
4748 }
c16c6ad8 4749
cf28d075 4750 return $default;
bf2cf926 4751 }
4752
f99a6f98 4753 /**
4754 * ContributionPage values were being imposed onto values.
4755 *
4756 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4757 * REALLY didn't want superimposed. The rest are left there in their overkill out
4758 * of cautiousness.
4759 *
4760 * The rationale for making this explicit is that it was a case of carefully set values being
4761 * seemingly randonly overwritten without much care. In general I think array randomly setting
4762 * variables en mass is risky.
4763 *
4764 * @param array $values
4765 *
4766 * @return array
4767 */
4768 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
66d5d6f4 4769 $contributionPageValues = [];
f99a6f98 4770 CRM_Contribute_BAO_ContributionPage::setValues(
4771 $this->contribution_page_id,
4772 $contributionPageValues
4773 );
66d5d6f4 4774 $valuesToCopy = [
f99a6f98 4775 // These are the values that I believe to be useful.
e4dcb541 4776 'id',
f99a6f98 4777 'title',
f99a6f98 4778 'pay_later_receipt',
4779 'pay_later_text',
4780 'receipt_from_email',
4781 'receipt_from_name',
4782 'receipt_text',
ee1dffa7 4783 'custom_pre_id',
f99a6f98 4784 'custom_post_id',
4785 'honoree_profile_id',
4786 'onbehalf_profile_id',
ee1dffa7 4787 'honor_block_is_active',
f99a6f98 4788 // Kinda might be - but would be on the contribution...
4789 'campaign_id',
4790 'currency',
4791 // Included for 'fear of regression' but can't justify any use for these....
4792 'intro_text',
4793 'payment_processor',
4794 'financial_type_id',
4795 'amount_block_is_active',
4796 'bcc_receipt',
4797 'cc_receipt',
4798 'created_date',
4799 'created_id',
4800 'default_amount_id',
4801 'end_date',
4802 'footer_text',
4803 'goal_amount',
4804 'initial_amount_help_text',
4805 'initial_amount_label',
4806 'intro_text',
4807 'is_allow_other_amount',
4808 'is_billing_required',
4809 'is_confirm_enabled',
4810 'is_credit_card_only',
4811 'is_monetary',
4812 'is_partial_payment',
4813 'is_recur_installments',
4814 'is_recur_interval',
4815 'is_share',
4816 'max_amount',
4817 'min_amount',
4818 'min_initial_amount',
4819 'recur_frequency_unit',
4820 'start_date',
4821 'thankyou_footer',
4822 'thankyou_text',
4823 'thankyou_title',
4824
66d5d6f4 4825 ];
f99a6f98 4826 foreach ($valuesToCopy as $valueToCopy) {
4827 if (isset($contributionPageValues[$valueToCopy])) {
f56ef33f
SL
4828 if ($valueToCopy === 'title') {
4829 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils::getContributionPageTitle($this->contribution_page_id);
4830 }
4831 else {
4832 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4833 }
f99a6f98 4834 }
4835 }
4836 return $values;
4837 }
4838
ce7fc91a
PN
4839 /**
4840 * Get values of CiviContribute Settings
4841 * and check if its enabled or not.
756661dc
PN
4842 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4843 * in serialized form. Usually this should be stored as flat settings for each form fields
4844 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4845 * settings we will live with an inconsistency because it's too hard to change for now.
4846 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
ce7fc91a
PN
4847 *
4848 *
4849 * @param string $name
5d288dc4 4850 *
ce7fc91a
PN
4851 * @return string
4852 *
4853 */
5d288dc4 4854 public static function checkContributeSettings($name) {
ce7fc91a 4855 $contributeSettings = Civi::settings()->get('contribution_invoice_settings');
914d3734 4856 return $contributeSettings[$name] ?? NULL;
ce7fc91a
PN
4857 }
4858
2912ed09 4859 /**
4860 * Get the contribution as it is in the database before being updated.
4861 *
4862 * @param int $contributionID
4863 *
81716ddb 4864 * @return \CRM_Contribute_BAO_Contribution|null
2912ed09 4865 */
4866 private static function getOriginalContribution($contributionID) {
2b058da6 4867 return self::getValues(['id' => $contributionID]);
2912ed09 4868 }
4869
8a477059 4870 /**
4871 * Get the amount for the financial item row.
4872 *
4873 * Helper function to start to break down recordFinancialTransactions for readability.
4874 *
4875 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
4876 *
4877 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
4878 * for historical reasons. Going forwards we can hope to add tests & improve readibility
4879 * of that function
4880 *
8a477059 4881 * @param array $params
4882 * Params as passed to contribution.create
4883 *
4884 * @param string $context
4885 * changeFinancialType| changedAmount
4886 * @param array $lineItemDetails
4887 * Line items.
4888 * @param bool $isARefund
4889 * Is this a refund / negative transaction.
1330f57a 4890 * @param int $previousLineItemTotal
8a477059 4891 *
4892 * @return float
66d5d6f4 4893 * @todo move recordFinancialAccounts & helper functions to their own class?
4894 *
8a477059 4895 */
273056c5
PN
4896 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
4897 if ($context == 'changedAmount') {
4898 $lineTotal = $lineItemDetails['line_total'];
4899 if ($lineTotal != $previousLineItemTotal) {
4900 $lineTotal -= $previousLineItemTotal;
4901 }
4902 return $lineTotal;
4903 }
8205a69e 4904 elseif ($context == 'changeFinancialType') {
273056c5 4905 return -$lineItemDetails['line_total'];
8a477059 4906 }
4907 elseif ($context == 'changedStatus') {
4908 $cancelledTaxAmount = 0;
4909 if ($isARefund) {
13e8b7d5 4910 $cancelledTaxAmount = CRM_Utils_Array::value('tax_amount', $lineItemDetails, '0.00');
8a477059 4911 }
13e8b7d5 4912 return self::getMultiplier($params['contribution']->contribution_status_id, $context) * ((float) $lineItemDetails['line_total'] + (float) $cancelledTaxAmount);
8a477059 4913 }
4914 elseif ($context === NULL) {
4915 // erm, yes because? but, hey, it's tested.
273056c5 4916 return $lineItemDetails['line_total'];
8a477059 4917 }
4918 elseif (empty($lineItemDetails['line_total'])) {
4919 // follow legacy code path
4920 Civi::log()
66d5d6f4 4921 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
8a477059 4922 return $params['total_amount'];
4923 }
4924 else {
13e8b7d5 4925 return self::getMultiplier($params['contribution']->contribution_status_id, $context) * ((float) $lineItemDetails['line_total']);
8a477059 4926 }
4927 }
4928
4929 /**
4930 * Get the multiplier for adjusting rows.
4931 *
4932 * If we are dealing with a refund or cancellation then it will be a negative
4933 * amount to reflect the negative transaction.
4934 *
4935 * If we are changing Financial Type it will be a negative amount to
4936 * adjust down the old type.
4937 *
4938 * @param int $contribution_status_id
4939 * @param string $context
4940 *
4941 * @return int
4942 */
4943 protected static function getMultiplier($contribution_status_id, $context) {
4944 if ($context == 'changeFinancialType' || self::isContributionStatusNegative($contribution_status_id)) {
4945 return -1;
4946 }
4947 return 1;
4948 }
4949
5ca657dd 4950 /**
4951 * Does this transaction reflect a payment instrument change.
4952 *
4953 * @param array $params
4954 * @param array $pendingStatuses
4955 *
4956 * @return bool
4957 */
4958 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
4959 $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id);
4960
4961 if (array_key_exists('payment_instrument_id', $params)) {
4962 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
27fdea23 4963 !CRM_Utils_System::isNull($params['payment_instrument_id'])
5ca657dd 4964 ) {
4965 //check if status is changed from Pending to Completed
4966 // do not update payment instrument changes for Pending to Completed
4967 if (!($contributionStatus == 'Completed' &&
4968 in_array($params['prevContribution']->contribution_status_id, $pendingStatuses))
4969 ) {
4970 return TRUE;
4971 }
4972 }
27fdea23 4973 elseif ((!CRM_Utils_System::isNull($params['payment_instrument_id']) &&
5ca657dd 4974 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
17ea57cf 4975 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5ca657dd 4976 ) {
4977 return TRUE;
4978 }
4979 elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
4980 $params['contribution']->check_number != $params['prevContribution']->check_number
4981 ) {
4982 // another special case when check number is changed, create new financial records
4983 // create financial trxn with negative amount
4984 return TRUE;
4985 }
4986 }
4987 return FALSE;
4988 }
4989
aec171f3 4990 /**
4991 * Update the memberships associated with a contribution if it has been completed.
4992 *
4993 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
4994 * load them in this function. Code clean up would compensate for any minor performance implication.
4995 *
eed14abb 4996 * @param int $contributionID
aec171f3 4997 * @param string $changeDate
aec171f3 4998 *
185a4fe8
MW
4999 * @throws \CRM_Core_Exception
5000 * @throws \CiviCRM_API3_Exception
aec171f3 5001 */
eed14abb 5002 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
5003 $memberships = self::getRelatedMemberships($contributionID);
5ed12039 5004 foreach ($memberships as $membership) {
66d5d6f4 5005 $membershipParams = [
8d315df3 5006 'id' => $membership['id'],
5007 'contact_id' => $membership['contact_id'],
5008 'is_test' => $membership['is_test'],
5009 'membership_type_id' => $membership['membership_type_id'],
5010 'membership_activity_status' => 'Completed',
66d5d6f4 5011 ];
aec171f3 5012
8d315df3 5013 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'],
5014 $membershipParams['membership_type_id'],
5015 $membershipParams['is_test'],
5016 $membershipParams['id']
5017 );
aec171f3 5018
8d315df3 5019 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5020 // this picks up membership type changes during renewals
5021 // @todo this is almost certainly an obsolete sql call, the pre-change
5022 // membership is accessible via $this->_relatedObjects
5023 $sql = "
aec171f3 5024SELECT membership_type_id
5025FROM civicrm_membership_log
5026WHERE membership_id={$membershipParams['id']}
5027ORDER BY id DESC
5028LIMIT 1;";
8d315df3 5029 $dao = CRM_Core_DAO::executeQuery($sql);
5030 if ($dao->fetch()) {
5031 if (!empty($dao->membership_type_id)) {
5032 $membershipParams['membership_type_id'] = $dao->membership_type_id;
185a4fe8 5033 }
8d315df3 5034 }
7365dd7f
AP
5035 if (empty($membership['end_date']) || (int) $membership['status_id'] !== CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
5036 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
5037 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
5038 // The api assumes num_terms is a special sauce for 'is_renewal' so we need to not pass it when updating a pending to completed.
7e9abd5a 5039 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
7365dd7f 5040 // @todo once apiv4 ships with core switch to that & find sanity.
eed14abb 5041 $membershipParams['num_terms'] = self::getNumTermsByContributionAndMembershipType(
7365dd7f 5042 $membershipParams['membership_type_id'],
eed14abb 5043 $contributionID
7365dd7f
AP
5044 );
5045 }
8d315df3 5046 // @todo remove all this stuff in favour of letting the api call further down handle in
5047 // (it is a duplication of what the api does).
66d5d6f4 5048 $dates = array_fill_keys([
8d315df3 5049 'join_date',
5050 'start_date',
5051 'end_date',
66d5d6f4 5052 ], NULL);
8d315df3 5053 if ($currentMembership) {
5054 /*
5055 * Fixed FOR CRM-4433
5056 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5057 * when Contribution mode is notify and membership is for renewal )
5058 */
4e6cd940 5059 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
5060 // Be afraid.
8d315df3 5061 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5062
5063 // @todo - we should pass membership_type_id instead of null here but not
5064 // adding as not sure of testing
5065 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'],
5066 $changeDate, NULL, $membershipParams['num_terms']
185a4fe8 5067 );
8d315df3 5068 $dates['join_date'] = $currentMembership['join_date'];
5069 }
185a4fe8 5070
8d315df3 5071 //get the status for membership.
5072 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
5073 $dates['end_date'],
5074 $dates['join_date'],
2cb64970 5075 'now',
8d315df3 5076 TRUE,
5077 $membershipParams['membership_type_id'],
5078 $membershipParams
5079 );
aec171f3 5080
8d315df3 5081 unset($dates['end_date']);
5082 $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
5083 //we might be renewing membership,
5084 //so make status override false.
5085 $membershipParams['is_override'] = FALSE;
5086 $membershipParams['status_override_end_date'] = 'null';
8d315df3 5087 civicrm_api3('Membership', 'create', $membershipParams);
aec171f3 5088 }
5089 }
5090
c0406a91 5091 /**
5092 * Get payment links as they relate to a contribution.
5093 *
5094 * If a payment can be made then include a payment link & if a refund is appropriate
5095 * then a refund link.
5096 *
5097 * @param int $id
5098 * @param float $balance
5099 * @param string $contributionStatus
5100 *
1330f57a
SL
5101 * @return array
5102 * $actionLinks Links array containing:
5103 * -url
5104 * -title
c0406a91 5105 */
5106 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5107 if ($contributionStatus === 'Failed' || !CRM_Core_Permission::check('edit contributions')) {
5108 // In general the balance is the best way to determine if a payment can be added or not,
5109 // but not for Failed contributions, where we don't accept additional payments at the moment.
5110 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5111 // do accept more payments agains them.
66d5d6f4 5112 return [];
c0406a91 5113 }
66d5d6f4 5114 $actionLinks = [];
4356c7dc 5115 $actionLinks[] = [
5116 'url' => CRM_Utils_System::url('civicrm/payment', [
5117 'action' => 'add',
5118 'reset' => 1,
5119 'id' => $id,
5120 'is_refund' => 0,
5121 ]),
5122 'title' => ts('Record Payment'),
5123 ];
5124
4cbe461a 5125 if (CRM_Core_Config::isEnabledBackOfficeCreditCardPayments()) {
66d5d6f4 5126 $actionLinks[] = [
5127 'url' => CRM_Utils_System::url('civicrm/payment', [
c0406a91 5128 'action' => 'add',
5129 'reset' => 1,
4cbe461a 5130 'is_refund' => 0,
c0406a91 5131 'id' => $id,
4cbe461a 5132 'mode' => 'live',
66d5d6f4 5133 ]),
4cbe461a 5134 'title' => ts('Submit Credit Card payment'),
66d5d6f4 5135 ];
c0406a91 5136 }
4cbe461a 5137 $actionLinks[] = [
5138 'url' => CRM_Utils_System::url('civicrm/payment', [
5139 'action' => 'add',
5140 'reset' => 1,
5141 'id' => $id,
5142 'is_refund' => 1,
5143 ]),
5144 'title' => ts('Record Refund'),
5145 ];
c0406a91 5146 return $actionLinks;
5147 }
5148
6b60d32c 5149 /**
5150 * Get a query to determine the amount donated by the contact/s in the current financial year.
5151 *
5152 * @param array $contactIDs
5153 *
5154 * @return string
5155 */
5156 public static function getAnnualQuery($contactIDs) {
5157 $contactIDs = implode(',', $contactIDs);
5158 $config = CRM_Core_Config::singleton();
5159 $currentMonth = date('m');
5160 $currentDay = date('d');
5161 if (
5162 (int) $config->fiscalYearStart['M'] > $currentMonth ||
5163 (
5164 (int) $config->fiscalYearStart['M'] == $currentMonth &&
5165 (int) $config->fiscalYearStart['d'] > $currentDay
5166 )
5167 ) {
5168 $year = date('Y') - 1;
5169 }
5170 else {
5171 $year = date('Y');
5172 }
5173 $nextYear = $year + 1;
5174
5175 if ($config->fiscalYearStart) {
5176 $newFiscalYearStart = $config->fiscalYearStart;
5177 if ($newFiscalYearStart['M'] < 10) {
5178 // This is just a clumsy way of adding padding.
5179 // @todo next round look for a nicer way.
5180 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5181 }
5182 if ($newFiscalYearStart['d'] < 10) {
5183 // This is just a clumsy way of adding padding.
5184 // @todo next round look for a nicer way.
5185 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5186 }
5187 $config->fiscalYearStart = $newFiscalYearStart;
5188 $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d'];
5189 }
5190 else {
5191 // First of January.
5192 $monthDay = '0101';
5193 }
5194 $startDate = "$year$monthDay";
5195 $endDate = "$nextYear$monthDay";
53666099 5196
6b60d32c 5197 $whereClauses = [
c77f8667 5198 'contact_id' => 'IN (' . $contactIDs . ')',
c77f8667 5199 'is_test' => ' = 0',
5200 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
6b60d32c 5201 ];
0c54553f 5202 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
c77f8667 5203 CRM_Financial_BAO_FinancialType::addACLClausesToWhereClauses($whereClauses);
5204
5205 $clauses = [];
5206 foreach ($whereClauses as $key => $clause) {
1330f57a 5207 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
c77f8667 5208 }
5209 $whereClauseString = implode(' AND ', $clauses);
5210
0c54553f 5211 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5212 // this group by + having on contribution_status_id improves performance
6b60d32c 5213 $query = "
5214 SELECT COUNT(*) as count,
5215 SUM(total_amount) as amount,
5216 AVG(total_amount) as average,
5217 currency
5218 FROM civicrm_contribution b
c77f8667 5219 WHERE " . $whereClauseString . "
0c54553f 5220 GROUP BY currency, contribution_status_id
5221 HAVING $havingClause
6b60d32c 5222 ";
5223 return $query;
5224 }
5225
94183dd6
SL
5226 /**
5227 * Assign Test Value.
5228 *
5229 * @param string $fieldName
5230 * @param array $fieldDef
5231 * @param int $counter
5232 */
5233 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5234 if ($fieldName == 'tax_amount') {
5235 $this->{$fieldName} = "0.00";
5236 }
5237 elseif ($fieldName == 'net_amount') {
5238 $this->{$fieldName} = "2.00";
5239 }
5240 elseif ($fieldName == 'total_amount') {
5241 $this->{$fieldName} = "3.00";
5242 }
5243 elseif ($fieldName == 'fee_amount') {
5244 $this->{$fieldName} = "1.00";
5245 }
5246 else {
5247 parent::assignTestValues($fieldName, $fieldDef, $counter);
5248 }
5249 }
5250
623712fb
PN
5251 /**
5252 * Check if contribution has participant/membership payment.
5253 *
5254 * @param int $contributionId
5255 * Contribution ID
5256 *
5257 * @return bool
5258 */
5259 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5260 // get line item for contribution
77dbdcbc 5261 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId);
623712fb
PN
5262 // check if line item is for membership or participant
5263 foreach ($lineItems as $items) {
5264 if ($items['entity_table'] == 'civicrm_participant') {
6f148218 5265 $flag = FALSE;
623712fb
PN
5266 break;
5267 }
5268 elseif ($items['entity_table'] == 'civicrm_membership') {
6f148218 5269 $flag = FALSE;
623712fb
PN
5270 }
5271 else {
6f148218 5272 $flag = TRUE;
623712fb
PN
5273 break;
5274 }
5275 }
5276 return $flag;
5277 }
5278
14b1ab0c
PN
5279 /**
5280 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5281 *
9c472292
PN
5282 * @param array $trxnParams
5283 * Financial trxn params
81716ddb 5284 * @param array $contributionParams
9c472292 5285 * Contribution Params
a9c48769 5286 *
81716ddb 5287 * @return null
14b1ab0c 5288 */
9c472292 5289 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
a17bec97 5290 if (!Civi::settings()->get('always_post_to_accounts_receivable')) {
14b1ab0c
PN
5291 return NULL;
5292 }
9c472292 5293 $statusId = $contributionParams['contribution']->contribution_status_id;
14b1ab0c 5294 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
a9c48769 5295 $contributionStatus = empty($statusId) ? NULL : $contributionStatuses[$statusId];
352cae98 5296 $previousContributionStatus = empty($contributionParams['prevContribution']) ? NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id];
14b1ab0c 5297 // Return if contribution status is not completed.
352cae98 5298 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
66d5d6f4 5299 || (!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5300 && $contributionParams['prevContribution']->is_pay_later == 0
5301 )))
352cae98 5302 ) {
14b1ab0c
PN
5303 return NULL;
5304 }
352cae98 5305
9c472292 5306 $params = $trxnParams;
e71c1326 5307 $financialTypeID = !empty($contributionParams['financial_type_id']) ? $contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id;
876b8ab0 5308 $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
9c472292
PN
5309 $params['to_financial_account_id'] = $arAccountId;
5310 $params['status_id'] = array_search('Pending', $contributionStatuses);
5311 $params['is_payment'] = FALSE;
5312 $trxn = CRM_Core_BAO_FinancialTrxn::create($params);
5313 self::$_trxnIDs[] = $trxn->id;
5314 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
14b1ab0c
PN
5315 }
5316
d9553c2e
PN
5317 /**
5318 * Calculate financial item amount when contribution is updated.
5319 *
5320 * @param array $params
5321 * contribution params
5322 * @param array $amountParams
5323 *
5324 * @param string $context
5325 *
5326 * @return float
5327 */
5328 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5329 if (!empty($params['is_quick_config'])) {
5330 $amount = $amountParams['item_amount'];
5331 if (!$amount) {
5332 $amount = $params['total_amount'];
5333 if ($context === NULL) {
5334 $amount -= CRM_Utils_Array::value('tax_amount', $params, 0);
5335 }
5336 }
5337 }
5338 else {
5339 $amount = $amountParams['line_total'];
5340 if ($context == 'changedAmount') {
5341 $amount -= $amountParams['previous_line_total'];
5342 }
5343 $amount *= $amountParams['diff'];
5344 }
5345 return $amount;
5346 }
5347
cdc6ce4d
PN
5348 /**
5349 * Retrieve Sales Tax Financial Accounts.
5350 *
5351 *
5352 * @return array
5353 *
5354 */
5355 public static function getSalesTaxFinancialAccounts() {
5356 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5357 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5358 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5359 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
66d5d6f4 5360 $queryParams = [1 => [$accountRel, 'Integer']];
cdc6ce4d 5361 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
66d5d6f4 5362 $financialAccount = [];
cdc6ce4d
PN
5363 while ($dao->fetch()) {
5364 $financialAccount[$dao->id] = $dao->id;
5365 }
5366 return $financialAccount;
5367 }
5368
53f969b9
PN
5369 /**
5370 * Create tax entry in civicrm_entity_financial_trxn table.
5371 *
5372 * @param array $entityParams
5373 *
5374 * @param array $eftParams
5375 *
66d5d6f4 5376 * @throws \CiviCRM_API3_Exception
53f969b9
PN
5377 */
5378 public static function createProportionalEntry($entityParams, $eftParams) {
ea8f914c
PN
5379 $paid = 0;
5380 if ($entityParams['contribution_total_amount'] != 0) {
5381 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5382 }
eb0af899 5383 // Record Entity Financial Trxn; CRM-20145
70fe7232 5384 $eftParams['amount'] = $paid;
53f969b9
PN
5385 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5386 }
5387
5388 /**
5389 * Create array of last financial item id's.
5390 *
bc854509 5391 * @param int $contributionId
53f969b9 5392 *
bc854509 5393 * @return array
53f969b9
PN
5394 */
5395 public static function getLastFinancialItemIds($contributionId) {
5396 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5397 FROM civicrm_financial_item fi
5398 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5399 WHERE li.contribution_id = %1";
66d5d6f4 5400 $dao = CRM_Core_DAO::executeQuery($sql, [
5401 1 => [
5402 $contributionId,
5403 'Integer',
5404 ],
5405 ]);
5406 $ftIds = $taxItems = [];
53f969b9
PN
5407 $salesTaxFinancialAccount = self::getSalesTaxFinancialAccounts();
5408 while ($dao->fetch()) {
5409 /* if sales tax item*/
5410 if (in_array($dao->financial_account_id, $salesTaxFinancialAccount)) {
66d5d6f4 5411 $taxItems[$dao->price_field_value_id] = [
53f969b9
PN
5412 'financial_item_id' => $dao->id,
5413 'amount' => $dao->tax_amount,
66d5d6f4 5414 ];
53f969b9
PN
5415 }
5416 else {
5417 $ftIds[$dao->price_field_value_id] = $dao->id;
5418 }
5419 }
66d5d6f4 5420 return [$ftIds, $taxItems];
53f969b9
PN
5421 }
5422
5423 /**
5424 * Create proportional entries in civicrm_entity_financial_trxn.
5425 *
5426 * @param array $entityParams
5427 *
5428 * @param array $lineItems
5429 *
5430 * @param array $ftIds
5431 *
5432 * @param array $taxItems
5433 *
66d5d6f4 5434 * @throws \CiviCRM_API3_Exception
53f969b9
PN
5435 */
5436 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
66d5d6f4 5437 $eftParams = [
53f969b9
PN
5438 'entity_table' => 'civicrm_financial_item',
5439 'financial_trxn_id' => $entityParams['trxn_id'],
66d5d6f4 5440 ];
53f969b9
PN
5441 foreach ($lineItems as $key => $value) {
5442 if ($value['qty'] == 0) {
5443 continue;
5444 }
5445 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5446 $entityParams['line_item_amount'] = $value['line_total'];
5447 self::createProportionalEntry($entityParams, $eftParams);
5448 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5449 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5450 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5451 self::createProportionalEntry($entityParams, $eftParams);
5452 }
5453 }
5454 }
5455
55df1211
AS
5456 /**
5457 * Load entities related to the contribution into $this->_relatedObjects.
5458 *
5459 * @param array $ids
5460 *
5461 * @throws \CRM_Core_Exception
5462 */
5463 protected function loadRelatedEntitiesByID($ids) {
66d5d6f4 5464 $entities = [
55df1211
AS
5465 'contact' => 'CRM_Contact_BAO_Contact',
5466 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5467 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5468 'financialType' => 'CRM_Financial_BAO_FinancialType',
5469 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
66d5d6f4 5470 ];
55df1211
AS
5471 foreach ($entities as $entity => $bao) {
5472 if (!empty($ids[$entity])) {
5473 $this->_relatedObjects[$entity] = new $bao();
5474 $this->_relatedObjects[$entity]->id = $ids[$entity];
5475 if (!$this->_relatedObjects[$entity]->find(TRUE)) {
5476 throw new CRM_Core_Exception($entity . ' could not be loaded');
5477 }
5478 }
5479 }
5480 }
5481
7e2ec997
E
5482 /**
5483 * Function to replace contribution tokens.
5484 *
5485 * @param array $contributionIds
5486 *
5487 * @param string $subject
5488 *
5489 * @param array $subjectToken
5490 *
5491 * @param string $text
5492 *
5493 * @param string $html
5494 *
5495 * @param array $messageToken
5496 *
5497 * @param bool $escapeSmarty
5498 *
5499 * @return array
66d5d6f4 5500 * @throws \CiviCRM_API3_Exception
7e2ec997
E
5501 */
5502 public static function replaceContributionTokens(
5503 $contributionIds,
5504 $subject,
5505 $subjectToken,
5506 $text,
5507 $html,
5508 $messageToken,
5509 $escapeSmarty
5510 ) {
5511 if (empty($contributionIds)) {
66d5d6f4 5512 return [];
7e2ec997 5513 }
66d5d6f4 5514 $contributionDetails = [];
7e2ec997 5515 foreach ($contributionIds as $id) {
fe7794b7 5516 $result = self::getContributionTokenValues($id, $messageToken);
7e2ec997
E
5517 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5518 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5519 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5520 }
5521 return $contributionDetails;
5522 }
5523
fe7794b7
JG
5524 /**
5525 * Get the contribution fields for $id and display labels where
5526 * appropriate (if the token is present).
5527 *
5528 * @param int $id
5529 * @param array $messageToken
5530 * @return array
5531 */
5532 public static function getContributionTokenValues($id, $messageToken) {
5533 if (empty($id)) {
5534 return [];
5535 }
5536 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5537 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5538 if (!empty($messageToken)) {
875e076b
JG
5539 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5540 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5541 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField::displayValue($result['values'][$id][$fieldName], $fieldName);
5542 }
5543 }
7e2ec997 5544 }
fe7794b7 5545 return $result;
7e2ec997
E
5546 }
5547
12a8f9d7 5548 /**
b07b172b 5549 * Get invoice_number for contribution.
12a8f9d7 5550 *
802c1c41 5551 * @param int $contributionID
12a8f9d7
PN
5552 *
5553 * @return string
5554 */
b07b172b 5555 public static function getInvoiceNumber($contributionID) {
5d288dc4 5556 if ($invoicePrefix = self::checkContributeSettings('invoice_prefix')) {
b07b172b 5557 return $invoicePrefix . $contributionID;
12a8f9d7 5558 }
802c1c41 5559
b07b172b 5560 return NULL;
12a8f9d7
PN
5561 }
5562
0a12bb75 5563 /**
5564 * Load the values needed for the event message.
5565 *
5566 * @param int $eventID
5567 * @param int $participantID
5568 * @param int|null $contributionID
5569 *
5570 * @return array
5571 * @throws \CRM_Core_Exception
5572 */
5573 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5574
5575 $eventParams = [
5576 'id' => $eventID,
5577 ];
ed7e2e99 5578 $values = ['event' => []];
0a12bb75 5579
5580 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
5581 // add custom fields for event
5582 $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Event', NULL, $eventID);
5583
5584 $eventCustomGroup = [];
5585 foreach ($eventGroupTree as $key => $group) {
5586 if ($key === 'info') {
5587 continue;
5588 }
5589
5590 foreach ($group['fields'] as $k => $customField) {
5591 $groupLabel = $group['title'];
5592 if (!empty($customField['customValue'])) {
5593 foreach ($customField['customValue'] as $customFieldValues) {
9c1bc317 5594 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ?? NULL;
0a12bb75 5595 }
5596 }
5597 }
5598 }
5599 $values['event']['customGroup'] = $eventCustomGroup;
5600
5601 //get participant details
5602 $participantParams = [
5603 'id' => $participantID,
5604 ];
5605
5606 $values['participant'] = [];
5607
5608 CRM_Event_BAO_Participant::getValues($participantParams, $values['participant'], $participantIds);
5609 // add custom fields for event
5610 $participantGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID);
5611 $participantCustomGroup = [];
5612 foreach ($participantGroupTree as $key => $group) {
5613 if ($key === 'info') {
5614 continue;
5615 }
5616
5617 foreach ($group['fields'] as $k => $customField) {
5618 $groupLabel = $group['title'];
5619 if (!empty($customField['customValue'])) {
5620 foreach ($customField['customValue'] as $customFieldValues) {
9c1bc317 5621 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ?? NULL;
0a12bb75 5622 }
5623 }
5624 }
5625 }
5626 $values['participant']['customGroup'] = $participantCustomGroup;
5627
5628 //get location details
5629 $locationParams = [
5630 'entity_id' => $eventID,
5631 'entity_table' => 'civicrm_event',
5632 ];
5633 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
5634
5635 $ufJoinParams = [
5636 'entity_table' => 'civicrm_event',
5637 'entity_id' => $eventID,
5638 'module' => 'CiviEvent',
5639 ];
5640
5641 list($custom_pre_id,
5642 $custom_post_ids
5643 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
5644
5645 $values['custom_pre_id'] = $custom_pre_id;
5646 $values['custom_post_id'] = $custom_post_ids;
5647
5648 // set lineItem for event contribution
5649 if ($contributionID) {
5650 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($contributionID);
5651 if (!empty($participantIds)) {
5652 foreach ($participantIds as $pIDs) {
5653 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
5654 if (!CRM_Utils_System::isNull($lineItem)) {
5655 $values['lineItem'][] = $lineItem;
5656 }
5657 }
5658 }
5659 }
5660 return $values;
5661 }
5662
5ce9cbe9 5663}