Merge pull request #18964 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 *
2129 * @return array
303007a3 2130 *
2131 * @throws CRM_Core_Exception
2132 * @throws \CiviCRM_API3_Exception
66d5d6f4 2133 * @deprecated
2134 *
2135 * Use api contribute.completetransaction
2136 * For failures use failPayment (preferably exposing by api in the process).
2137 *
6a488035 2138 */
00be9182 2139 public static function transitionComponents($params, $processContributionObject = FALSE) {
6a488035 2140 // get minimum required values.
9c1bc317
CW
2141 $contactId = $params['contact_id'] ?? NULL;
2142 $componentId = $params['component_id'] ?? NULL;
2143 $componentName = $params['componentName'] ?? NULL;
2144 $contributionId = $params['contribution_id'] ?? NULL;
2145 $contributionStatusId = $params['contribution_status_id'] ?? NULL;
6a488035
TO
2146
2147 // if we already processed contribution object pass previous status id.
9c1bc317 2148 $previousContriStatusId = $params['previous_contribution_status_id'] ?? NULL;
6a488035 2149
66d5d6f4 2150 $updateResult = [];
6a488035
TO
2151
2152 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2153
2154 // we process only ( Completed, Cancelled, or Failed ) contributions.
2155 if (!$contributionId ||
66d5d6f4 2156 !in_array($contributionStatusId, [
f2b2a3ff
TO
2157 array_search('Completed', $contributionStatuses),
2158 array_search('Cancelled', $contributionStatuses),
2159 array_search('Failed', $contributionStatuses),
66d5d6f4 2160 ])
6a488035
TO
2161 ) {
2162 return $updateResult;
2163 }
2164
2165 if (!$componentName || !$componentId) {
2166 // get the related component details.
2167 $componentDetails = self::getComponentDetails($contributionId);
2168 }
2169 else {
2170 $componentDetails['contact_id'] = $contactId;
2171 $componentDetails['component'] = $componentName;
2172
2173 if ($componentName == 'event') {
2174 $componentDetails['participant'] = $componentId;
2175 }
2176 else {
2177 $componentDetails['membership'] = $componentId;
2178 }
2179 }
2180
a7488080 2181 if (!empty($componentDetails['contact_id'])) {
6a488035
TO
2182 $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2183 $contributionId,
2184 'contact_id'
2185 );
2186 }
2187
2188 // do check for required ids.
8cc574cf 2189 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) {
6a488035
TO
2190 return $updateResult;
2191 }
2192
863592c3 2193 $input = $ids = [];
6a488035 2194
9c1bc317 2195 $input['component'] = $componentDetails['component'] ?? NULL;
6a488035 2196 $ids['contribution'] = $contributionId;
9c1bc317
CW
2197 $ids['contact'] = $componentDetails['contact_id'] ?? NULL;
2198 $ids['membership'] = $componentDetails['membership'] ?? NULL;
2199 $ids['participant'] = $componentDetails['participant'] ?? NULL;
2200 $ids['event'] = $componentDetails['event'] ?? NULL;
2201 $ids['pledge_payment'] = $componentDetails['pledge_payment'] ?? NULL;
6a488035
TO
2202 $ids['contributionRecur'] = NULL;
2203 $ids['contributionPage'] = NULL;
2204
863592c3 2205 $contribution = new CRM_Contribute_BAO_Contribution();
2206 $contribution->id = $ids['contribution'];
2207 $contribution->find();
2208
2209 $contribution->loadRelatedObjects($input, $ids);
2210
2211 $memberships = $contribution->_relatedObjects['membership'] ?? [];
2212 $participant = $contribution->_relatedObjects['participant'] ?? [];
2213 $pledgePayment = $contribution->_relatedObjects['pledge_payment'] ?? [];
6a488035 2214
1ee67fa2 2215 $pledgeID = $oldStatus = NULL;
2216 $pledgePaymentIDs = [];
6a488035 2217 if ($pledgePayment) {
6a488035
TO
2218 foreach ($pledgePayment as $key => $object) {
2219 $pledgePaymentIDs[] = $object->id;
2220 }
2221 $pledgeID = $pledgePayment[0]->pledge_id;
2222 }
2223
6a488035
TO
2224 $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
2225
2226 if ($participant) {
2227 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
2228 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
2229 $participant->id,
2230 'status_id'
2231 );
2232 }
2233 // we might want to process contribution object.
2234 $processContribution = FALSE;
2235 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1ee67fa2 2236 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2237 list($updateResult, $processContribution) = self::cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
6a488035
TO
2238 }
2239 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
0dcc88fc 2240 list($updateResult, $processContribution) = self::processFail($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
6a488035
TO
2241 }
2242 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2243
2244 // only pending contribution related object processed.
2245 if ($previousContriStatusId &&
66d5d6f4 2246 !in_array($contributionStatuses[$previousContriStatusId], [
2247 'Pending',
2248 'Partially paid',
2249 ])
6a488035
TO
2250 ) {
2251 // this is case when we already processed contribution object.
2252 return $updateResult;
2253 }
2254 elseif (!$previousContriStatusId &&
66d5d6f4 2255 !in_array($contributionStatuses[$contribution->contribution_status_id], [
2256 'Pending',
2257 'Partially paid',
2258 ])
6a488035
TO
2259 ) {
2260 // this is case when we are going to process contribution object later.
2261 return $updateResult;
2262 }
2263
2264 if (is_array($memberships)) {
2265 foreach ($memberships as $membership) {
2266 if ($membership) {
2267 $format = '%Y%m%d';
2268
2269 //CRM-4523
2270 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
2271 $membership->membership_type_id,
2272 $membership->is_test, $membership->id
2273 );
2274
2275 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2276 // this picks up membership type changes during renewals
2277 $sql = "
2278 SELECT membership_type_id
2279 FROM civicrm_membership_log
2280 WHERE membership_id=$membership->id
2281 ORDER BY id DESC
2282 LIMIT 1;";
fa00d91f 2283 $dao = CRM_Core_DAO::executeQuery($sql);
6a488035
TO
2284 if ($dao->fetch()) {
2285 if (!empty($dao->membership_type_id)) {
2286 $membership->membership_type_id = $dao->membership_type_id;
2287 $membership->save();
2288 }
2289 }
2290 // else fall back to using current membership type
9c09f5b7
AH
2291 // Figure out number of terms
2292 $numterms = 1;
77dbdcbc 2293 $lineitems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId);
9c09f5b7 2294 foreach ($lineitems as $lineitem) {
d4578334 2295 if ($membership->membership_type_id == ($lineitem['membership_type_id'] ?? NULL)) {
9c1bc317 2296 $numterms = $lineitem['membership_num_terms'] ?? NULL;
2d77a516 2297
9c09f5b7
AH
2298 // in case membership_num_terms comes through as null or zero
2299 $numterms = $numterms >= 1 ? $numterms : 1;
2300 break;
2301 }
2302 }
2303
e8c64fab 2304 // CRM-15735-to update the membership status as per the contribution receive date
35874a67 2305 $joinDate = NULL;
98f0683a 2306 $oldStatus = $membership->status_id;
e8c64fab 2307 if (!empty($params['receive_date'])) {
35874a67 2308 $joinDate = $params['receive_date'];
e8c64fab 2309 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date,
2310 $membership->end_date,
2311 $membership->join_date,
2312 $params['receive_date'],
2313 FALSE,
2314 $membership->membership_type_id,
2315 (array) $membership
2316 );
2317 $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id);
2318 $membership->save();
2319 }
2320
6a488035 2321 if ($currentMembership) {
9c09f5b7
AH
2322 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2323 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
6a488035
TO
2324 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
2325 }
2326 else {
35874a67 2327 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, $joinDate, NULL, NULL, $numterms);
6a488035
TO
2328 }
2329
2330 //get the status for membership.
2331 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
2332 $dates['end_date'],
2333 $dates['join_date'],
2cb64970 2334 'now',
5f11bbcc
EM
2335 TRUE,
2336 $membership->membership_type_id,
2337 (array) $membership
6a488035
TO
2338 );
2339
66d5d6f4 2340 $formattedParams = [
6a488035
TO
2341 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
2342 array_search('Current', $membershipStatuses)
2343 ),
2344 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
2345 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
2346 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
66d5d6f4 2347 ];
6a488035 2348
c2585c5b 2349 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
6a488035 2350
c2585c5b 2351 $membership->copyValues($formattedParams);
6a488035
TO
2352 $membership->save();
2353
2354 //updating the membership log
66d5d6f4 2355 $membershipLog = [];
c2585c5b 2356 $membershipLog = $formattedParams;
d4578334 2357 $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'] ?? NULL, $format);
f2b2a3ff 2358 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
6a488035
TO
2359
2360 $membershipLog['start_date'] = $logStartDate;
2361 $membershipLog['membership_id'] = $membership->id;
2362 $membershipLog['modified_id'] = $membership->contact_id;
2363 $membershipLog['modified_date'] = date('Ymd');
2364 $membershipLog['membership_type_id'] = $membership->membership_type_id;
2365
4ed92e91 2366 CRM_Member_BAO_MembershipLog::add($membershipLog);
6a488035
TO
2367
2368 //update related Memberships.
c2585c5b 2369 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
6a488035 2370
66d5d6f4 2371 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
b6d493f3
MD
2372 $scheduledActivityID = CRM_Utils_Array::value('id',
2373 civicrm_api3('Activity', 'Get',
66d5d6f4 2374 [
b6d493f3
MD
2375 'source_record_id' => $membership->id,
2376 'activity_type_id' => $activityType,
2377 'status_id' => 'Scheduled',
66d5d6f4 2378 'options' => [
66a1e31f
MD
2379 'limit' => 1,
2380 'sort' => 'id DESC',
66d5d6f4 2381 ],
2382 ]
b6d493f3
MD
2383 )
2384 );
66a1e31f 2385 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
b6d493f3
MD
2386 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2387 if ($scheduledActivityID) {
66d5d6f4 2388 CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $membership->contact_id, ['id' => $scheduledActivityID]);
b6d493f3
MD
2389 break;
2390 }
2391 }
2392
2393 // track membership status change if any
2394 if (!empty($oldStatus) && $membership->status_id != $oldStatus) {
2395 $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get');
2396 CRM_Activity_BAO_Activity::addActivity($membership,
2397 'Change Membership Status',
2398 NULL,
66d5d6f4 2399 [
b6d493f3
MD
2400 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2401 'source_contact_id' => $membershipLog['modified_id'],
66a1e31f 2402 'priority_id' => 'Normal',
66d5d6f4 2403 ]
b6d493f3
MD
2404 );
2405 }
0f07bb06 2406
6a488035
TO
2407 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
2408 if ($processContributionObject) {
2409 $processContribution = TRUE;
2410 }
2411
2412 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
2413 }
2414 }
2415 }
2416
2417 if ($participant) {
2418 $updatedStatusId = array_search('Registered', $participantStatuses);
2419 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
2420
2421 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2422 if ($processContributionObject) {
2423 $processContribution = TRUE;
2424 }
2425 }
2426
2427 if ($pledgePayment) {
2428 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2429
2430 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2431 if ($processContributionObject) {
2432 $processContribution = TRUE;
2433 }
2434 }
2435 }
2436
2437 // process contribution object.
2438 if ($processContribution) {
66d5d6f4 2439 $contributionParams = [];
2440 $fields = [
f2b2a3ff
TO
2441 'contact_id',
2442 'total_amount',
2443 'receive_date',
2444 'is_test',
2445 'campaign_id',
2446 'payment_instrument_id',
2447 'trxn_id',
2448 'invoice_id',
2449 'financial_type_id',
2450 'contribution_status_id',
2451 'non_deductible_amount',
2452 'receipt_date',
2453 'check_number',
66d5d6f4 2454 ];
6a488035 2455 foreach ($fields as $field) {
a7488080 2456 if (empty($params[$field])) {
6a488035
TO
2457 continue;
2458 }
2459 $contributionParams[$field] = $params[$field];
2460 }
2461
70d43afb 2462 $contributionParams['id'] = $contributionId;
2463 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams);
6a488035
TO
2464 }
2465
2466 return $updateResult;
2467 }
2468
2469 /**
16b10e64 2470 * Returns all contribution related object ids.
7a9ab499
EM
2471 *
2472 * @param $contributionId
2473 *
2474 * @return array
6a488035 2475 */
291ca04f 2476 public static function getComponentDetails($contributionId) {
66d5d6f4 2477 $componentDetails = $pledgePayment = [];
6a488035
TO
2478 if (!$contributionId) {
2479 return $componentDetails;
2480 }
2481
2482 $query = "
2483 SELECT c.id as contribution_id,
2484 c.contact_id as contact_id,
d97c96dc 2485 c.contribution_recur_id,
6a488035
TO
2486 mp.membership_id as membership_id,
2487 m.membership_type_id as membership_type_id,
2488 pp.participant_id as participant_id,
2489 p.event_id as event_id,
2490 pgp.id as pledge_payment_id
2491 FROM civicrm_contribution c
2492 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2493 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2494 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2495 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2496 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2497 WHERE c.id = $contributionId";
2498
2499 $dao = CRM_Core_DAO::executeQuery($query);
66d5d6f4 2500 $componentDetails = [];
6a488035
TO
2501
2502 while ($dao->fetch()) {
2503 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
2504 $componentDetails['contact_id'] = $dao->contact_id;
2505 if ($dao->event_id) {
2506 $componentDetails['event'] = $dao->event_id;
2507 }
2508 if ($dao->participant_id) {
2509 $componentDetails['participant'] = $dao->participant_id;
2510 }
2511 if ($dao->membership_id) {
2512 if (!isset($componentDetails['membership'])) {
66d5d6f4 2513 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
6a488035
TO
2514 }
2515 $componentDetails['membership'][] = $dao->membership_id;
2516 $componentDetails['membership_type'][] = $dao->membership_type_id;
2517 }
2518 if ($dao->pledge_payment_id) {
2519 $pledgePayment[] = $dao->pledge_payment_id;
2520 }
d97c96dc
EM
2521 if ($dao->contribution_recur_id) {
2522 $componentDetails['contributionRecur'] = $dao->contribution_recur_id;
2523 }
6a488035
TO
2524 }
2525
2526 if ($pledgePayment) {
2527 $componentDetails['pledge_payment'] = $pledgePayment;
2528 }
2529
2530 return $componentDetails;
2531 }
2532
186c9c17 2533 /**
100fef9d 2534 * @param int $contactId
186c9c17
EM
2535 * @param bool $includeSoftCredit
2536 *
2537 * @return null|string
2538 */
00be9182 2539 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
6a488035
TO
2540 if (!$contactId) {
2541 return 0;
2542 }
d51d109d 2543 $financialTypes = CRM_Financial_BAO_FinancialType::getAllAvailableFinancialTypes();
7fb041e3 2544 $additionalWhere = " AND contribution.financial_type_id IN (0)";
9cec2e9f 2545 $liWhere = " AND i.financial_type_id IN (0)";
7fb041e3 2546 if (!empty($financialTypes)) {
40c655aa
E
2547 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2548 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
7fb041e3 2549 }
bbde790f
RN
2550 $contactContributionsSQL = "
2551 SELECT contribution.id AS id
2552 FROM civicrm_contribution contribution
ad37ac8e 2553 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2554 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2555 $additionalWhere
9cec2e9f 2556 AND i.id IS NULL";
bbde790f 2557
bbde790f
RN
2558 $contactSoftCreditContributionsSQL = "
2559 SELECT contribution.id
2560 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2561 ON ( contribution.id = softContribution.contribution_id )
2562 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2563 $query = "SELECT count( x.id ) count FROM ( ";
2564 $query .= $contactContributionsSQL;
2565
6a488035 2566 if ($includeSoftCredit) {
bbde790f
RN
2567 $query .= " UNION ";
2568 $query .= $contactSoftCreditContributionsSQL;
6a488035 2569 }
bbde790f 2570
bbde790f 2571 $query .= ") x";
6a488035
TO
2572
2573 return CRM_Core_DAO::singleValueQuery($query);
2574 }
2575
b3b7f4c5 2576 /**
2577 * Repeat a transaction as part of a recurring series.
2578 *
fefee636 2579 * The ideal flow is
2580 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2581 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2582 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2583 * and associated entities.
2584 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2585 * which updates the various entities and sends appropriate emails.
2586 *
2587 * Gaps in the above (@todo)
2588 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2589 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2590 * 3) Repeat transaction duplicates rather than calls Order.create
2591 * 4) Use of payment.create still limited - completetransaction is more common.
2592 * 5) the template transaction is tricky - historically we used the first contribution
2593 * linked to a recurring contribution. More recently that was changed to be the most recent.
2594 * Ideally it would be an actual template - not a contribution used as a template which
2595 * would give more appropriate flexibility. Note line_items have an entity so that table
2596 * could be used for the line item template - the difficulty is the custom fields...
2597 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2598 * to load the membership(s) referred to via line items in the template transactions. Any other
2599 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2600 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2601 * - membership_payment record
2602 * - civicrm_membership.contribution_recur_id
2603 * - input override.
2604 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2605 * of historical processors since this has been handled 'forever' - specifically for paypal.
2606 * albeit by an even nastier mechanism than the current input override.
2607 * The count is out on how correct related entities wind up in this case.
b3b7f4c5 2608 *
2609 * @param CRM_Contribute_BAO_Contribution $contribution
2610 * @param array $input
2611 * @param array $contributionParams
2612 *
c80d977f 2613 * @return bool|array
43c8d1dd 2614 * @throws CiviCRM_API3_Exception
b3b7f4c5 2615 */
34dc58e7 2616 protected static function repeatTransaction(&$contribution, $input, $contributionParams) {
b3b7f4c5 2617 if (!empty($contribution->id)) {
2618 return FALSE;
2619 }
2620 if (empty($contribution->id)) {
2621 // Unclear why this would only be set for repeats.
2622 if (!empty($input['amount'])) {
2623 $contribution->total_amount = $contributionParams['total_amount'] = $input['amount'];
2624 }
43c8d1dd 2625
8da8c1d0 2626 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2627 'id' => $contributionParams['contribution_recur_id'],
2628 ]);
8da8c1d0 2629 if (!empty($recurringContribution['financial_type_id'])) {
2630 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2631 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
c02c17df 2632 }
43c8d1dd 2633 $templateContribution = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution(
2634 $contributionParams['contribution_recur_id'],
66d5d6f4 2635 array_intersect_key($contributionParams, [
2636 'total_amount' => TRUE,
2637 'financial_type_id' => TRUE,
2638 ])
43c8d1dd 2639 );
2640 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
f8c94f00 2641 $contributionParams['status_id'] = 'Pending';
fa839a68 2642
2643 if (isset($contributionParams['financial_type_id']) && count($input['line_item']) === 1) {
2644 // We permit the financial type to be overridden for single line items.
2645 // More comments on this are in getTemplateTransaction.
3c49d90c 2646 $contribution->financial_type_id = $contributionParams['financial_type_id'];
2647 }
2648 else {
2649 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2650 }
a64d6127 2651 foreach (['contact_id', 'currency', 'source', 'amount_level', 'address_id'] as $fieldName) {
2652 if (isset($templateContribution[$fieldName])) {
2653 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2654 }
2655 }
2656 if (!empty($recurringContribution['campaign_id'])) {
2657 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2658 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2659 }
2660 if (!isset($contributionParams['campaign_id']) && isset($templateContribution['campaign_id'])) {
2661 // Fall back on value from the previous contribution if not passed in as input
2662 // or loadable from the recurring contribution.
2663 $contributionParams['campaign_id'] = $templateContribution['campaign_id'];
aed0a241 2664 }
aed0a241 2665 $contributionParams['source'] = $contributionParams['source'] ?: ts('Recurring contribution');
43c8d1dd 2666
44fec73b
BS
2667 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2668 //do not create CC or BCC emails or profile notifications.
2669 //The if is just to be safe. Not sure if we can ever arrive with this unset
8536e5a0 2670 // but per CRM-19478 it seems it can be 'null'
2671 if (isset($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) {
4194dd55 2672 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id;
a4facb5c 2673 }
8891c196
JP
2674 if (!empty($contribution->tax_amount)) {
2675 $contributionParams['tax_amount'] = $contribution->tax_amount;
2676 }
44fec73b 2677
b3b7f4c5 2678 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2679 $contribution->id = $createContribution['id'];
b2250d14 2680 $contribution->copyCustomFields($templateContribution['id'], $contribution->id);
fefee636 2681 self::handleMembershipIDOverride($contribution->id, $input);
0bd5e6bf 2682 // Add new soft credit against current $contribution.
2683 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($contributionParams['contribution_recur_id'], $createContribution['id']);
c80d977f 2684 return $createContribution;
b3b7f4c5 2685 }
2686 }
2687
6a488035 2688 /**
fe482240 2689 * Get individual id for onbehalf contribution.
6a488035 2690 *
014c4014
TO
2691 * @param int $contributionId
2692 * Contribution id.
2693 * @param int $contributorId
2694 * Contributor id.
6a488035 2695 *
a6c01b45
CW
2696 * @return array
2697 * containing organization id and individual id
6a488035 2698 */
00be9182 2699 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
6a488035 2700
66d5d6f4 2701 $ids = [];
6a488035
TO
2702
2703 if (!$contributionId) {
2704 return $ids;
2705 }
2706
2707 // fetch contributor id if null
2708 if (!$contributorId) {
2709 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2710 $contributionId, 'contact_id'
2711 );
2712 }
2713
2714 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
2715 $activityTypeId = array_search('Contribution', $activityTypeIds);
2716
2717 if ($activityTypeId && $contributorId) {
2718 $activityQuery = "
2d77a516
DL
2719SELECT civicrm_activity_contact.contact_id
2720 FROM civicrm_activity_contact
2721INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2722 WHERE civicrm_activity.activity_type_id = %1
2723 AND civicrm_activity.source_record_id = %2
2724 AND civicrm_activity_contact.record_type_id = %3
2725";
6a488035 2726
44f817d4 2727 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2d77a516
DL
2728 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2729
66d5d6f4 2730 $params = [
2731 1 => [$activityTypeId, 'Integer'],
2732 2 => [$contributionId, 'Integer'],
2733 3 => [$sourceID, 'Integer'],
2734 ];
6a488035
TO
2735
2736 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
2737
2738 // for on behalf contribution source is individual and contributor is organization
2739 if ($sourceContactId && $sourceContactId != $contributorId) {
2740 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
2741 // get rel type id for employee of relation
2742 foreach ($relationshipTypeIds as $id => $typeVals) {
2743 if ($typeVals['name_a_b'] == 'Employee of') {
2744 $relationshipTypeId = $id;
2745 break;
2746 }
2747 }
2748
2749 $rel = new CRM_Contact_DAO_Relationship();
2750 $rel->relationship_type_id = $relationshipTypeId;
2751 $rel->contact_id_a = $sourceContactId;
2752 $rel->contact_id_b = $contributorId;
2753 if ($rel->find(TRUE)) {
2754 $ids['individual_id'] = $rel->contact_id_a;
2755 $ids['organization_id'] = $rel->contact_id_b;
2756 }
2757 }
2758 }
2759
2760 return $ids;
2761 }
2762
2763 /**
2764 * @return array
6a488035 2765 */
00be9182 2766 public static function getContributionDates() {
f2b2a3ff 2767 $config = CRM_Core_Config::singleton();
6a488035 2768 $currentMonth = date('m');
f2b2a3ff 2769 $currentDay = date('d');
6a488035
TO
2770 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
2771 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
2772 (int ) $config->fiscalYearStart['d'] > $currentDay
2773 )
2774 ) {
2775 $year = date('Y') - 1;
2776 }
2777 else {
2778 $year = date('Y');
2779 }
66d5d6f4 2780 $year = ['Y' => $year];
6a488035
TO
2781 $yearDate = $config->fiscalYearStart;
2782 $yearDate = array_merge($year, $yearDate);
2783 $yearDate = CRM_Utils_Date::format($yearDate);
2784
2785 $monthDate = date('Ym') . '01';
2786
2787 $now = date('Ymd');
2788
66d5d6f4 2789 return [
6a488035
TO
2790 'now' => $now,
2791 'yearDate' => $yearDate,
2792 'monthDate' => $monthDate,
66d5d6f4 2793 ];
6a488035
TO
2794 }
2795
16b10e64 2796 /**
fe482240 2797 * Load objects relations to contribution object.
6a488035
TO
2798 * Objects are stored in the $_relatedObjects property
2799 * In the first instance we are just moving functionality from BASEIpn -
66d5d6f4 2800 *
16b10e64
CW
2801 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2802 *
2803 * Note that the unit test for the BaseIPN class tests this function
6a488035 2804 *
014c4014
TO
2805 * @param array $input
2806 * Input as delivered from Payment Processor.
2807 * @param array $ids
2808 * Ids as Loaded by Payment Processor.
014c4014
TO
2809 * @param bool $loadAll
2810 * Load all related objects - even where id not passed in? (allows API to call this).
186c9c17
EM
2811 *
2812 * @return bool
49ed4888 2813 * @throws CRM_Core_Exception
186c9c17 2814 */
ad64fa72 2815 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
72d57998 2816 // @todo deprecate this function - the steps should be
2817 // 1) add additional functions like 'getRelatedMemberships'
2818 // 2) switch all calls that refer to ->_relatedObjects to
2819 // using the helper functions
2820 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2821 // 4) make ->_relatedObjects protected
2822 // 5) hone up the individual functions to not use rely on this having been called
2823 // 6) deprecate like mad
f2b2a3ff
TO
2824 if ($loadAll) {
2825 $ids = array_merge($this->getComponentDetails($this->id), $ids);
2826 if (empty($ids['contact']) && isset($this->contact_id)) {
6a488035
TO
2827 $ids['contact'] = $this->contact_id;
2828 }
2829 }
2830 if (empty($this->_component)) {
f2b2a3ff 2831 if (!empty($ids['event'])) {
6a488035
TO
2832 $this->_component = 'event';
2833 }
2834 else {
2835 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
2836 }
2837 }
474ebab9 2838
2b57dd9f 2839 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2840 // refactoring than anything else, and has unit test coverage.
2841 if (empty($this->financial_type_id)) {
2842 $this->find(TRUE);
2843 }
2844
474ebab9 2845 $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value(
2846 'paymentProcessor',
2847 $ids
2848 ));
2849
18135422 2850 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id) {
474ebab9 2851 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2852 $this->contribution_page_id,
2853 'payment_processor'
2854 );
ef6ae9af 2855 if ($paymentProcessorID) {
2856 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2857 }
474ebab9 2858 }
2859
2b57dd9f 2860 $ids['contributionType'] = $this->financial_type_id;
2861 $ids['financialType'] = $this->financial_type_id;
55df1211
AS
2862 if ($this->contribution_page_id) {
2863 $ids['contributionPage'] = $this->contribution_page_id;
474ebab9 2864 }
2865
55df1211
AS
2866 $this->loadRelatedEntitiesByID($ids);
2867
2b57dd9f 2868 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2869 $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id;
6a488035 2870 }
6a488035 2871
474ebab9 2872 if (!empty($ids['pledge_payment'])) {
2873 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2874 if (empty($paymentID)) {
2875 continue;
2876 }
2877 $payment = new CRM_Pledge_BAO_PledgePayment();
2878 $payment->id = $paymentID;
2879 if (!$payment->find(TRUE)) {
49ed4888 2880 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
474ebab9 2881 }
2882 $this->_relatedObjects['pledge_payment'][] = $payment;
2883 }
2884 }
2885
72d57998 2886 // These are probably no longer accessed from anywhere
2887 // @todo remove this line, after ensuring not used.
e6c7e48d 2888 $ids = $this->loadRelatedMembershipObjects($ids);
aadcdd50 2889
2890 if ($this->_component != 'contribute') {
6a488035
TO
2891 // we are in event mode
2892 // make sure event exists and is valid
2893 $event = new CRM_Event_BAO_Event();
2894 $event->id = $ids['event'];
2895 if ($ids['event'] &&
2896 !$event->find(TRUE)
2897 ) {
49ed4888 2898 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
6a488035
TO
2899 }
2900
2901 $this->_relatedObjects['event'] = &$event;
2902
2903 $participant = new CRM_Event_BAO_Participant();
2904 $participant->id = $ids['participant'];
2905 if ($ids['participant'] &&
2906 !$participant->find(TRUE)
2907 ) {
49ed4888 2908 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
6a488035
TO
2909 }
2910 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
2911
2912 $this->_relatedObjects['participant'] = &$participant;
2913
474ebab9 2914 // get the payment processor id from event - this is inaccurate see CRM-16923
2915 // in future we should look at throwing an exception here rather than an dubious guess.
6a488035
TO
2916 if (!$paymentProcessorID) {
2917 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
ef6ae9af 2918 if ($paymentProcessorID) {
2919 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2920 }
6a488035
TO
2921 }
2922 }
2923
d33f8fc4
JP
2924 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds($this->id);
2925 if (!empty($relatedContact['individual_id'])) {
2926 $ids['related_contact'] = $relatedContact['individual_id'];
2927 }
2928
6a488035
TO
2929 if ($paymentProcessorID) {
2930 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2931 $this->is_test ? 'test' : 'live'
2932 );
2933 $ids['paymentProcessor'] = $paymentProcessorID;
d6944518 2934 $this->_relatedObjects['paymentProcessor'] = $paymentProcessor;
6a488035 2935 }
5f3d5a7a
AS
2936
2937 // Add contribution id to $ids. CRM-20401
2938 $ids['contribution'] = $this->id;
5bfb071e 2939 return TRUE;
6a488035
TO
2940 }
2941
16b10e64 2942 /**
6a488035
TO
2943 * Create array of message information - ie. return html version, txt version, to field
2944 *
014c4014
TO
2945 * @param array $input
2946 * Incoming information.
16b10e64 2947 * - is_recur - should this be treated as recurring (not sure why you wouldn't
6a488035
TO
2948 * just check presence of recur object but maintaining legacy approach
2949 * to be careful)
014c4014
TO
2950 * @param array $ids
2951 * IDs of related objects.
2952 * @param array $values
2953 * Any values that may have already been compiled by calling process.
6a488035 2954 * This is augmented by values 'gathered' by gatherMessageValues
014c4014
TO
2955 * @param bool $returnMessageText
2956 * Distinguishes between whether to send message or return.
6a488035
TO
2957 * message text. We are working towards this function ALWAYS returning message text & calling
2958 * function doing emails / pdfs with it
16b10e64 2959 *
a6c01b45
CW
2960 * @return array
2961 * messages
186c9c17
EM
2962 * @throws Exception
2963 */
d891a273 2964 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
4ff927bc 2965 $this->loadRelatedObjects($input, $ids);
2966
6a488035 2967 if (empty($this->_component)) {
9c1bc317 2968 $this->_component = $input['component'] ?? NULL;
6a488035
TO
2969 }
2970
2971 //not really sure what params might be passed in but lets merge em into values
2972 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
081ee444 2973 $values['is_email_receipt'] = !$returnMessageText;
94db3e6e
JP
2974 foreach (['receipt_date', 'cc_receipt', 'bcc_receipt', 'receipt_from_name', 'receipt_from_email', 'receipt_text'] as $fld) {
2975 if (!empty($input[$fld])) {
2976 $values[$fld] = $input[$fld];
2977 }
d9924163
E
2978 }
2979
d891a273 2980 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
6a488035
TO
2981 //what does recur 'mean here - to do with payment processor return functionality but
2982 // what is the importance
d891a273 2983 if (!empty($this->contribution_recur_id) && !empty($this->_relatedObjects['paymentProcessor'])) {
35cd38f5 2984 $paymentObject = Civi\Payment\System::singleton()->getByProcessor($this->_relatedObjects['paymentProcessor']);
6a488035
TO
2985
2986 $entityID = $entity = NULL;
2987 if (isset($ids['contribution'])) {
2988 $entity = 'contribution';
2989 $entityID = $ids['contribution'];
2990 }
dccb668e
EM
2991 if (!empty($ids['membership'])) {
2992 //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
2993 // 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
2994 // line having loaded an array
2995 $ids['membership'] = (array) $ids['membership'];
6a488035 2996 $entity = 'membership';
dccb668e 2997 $entityID = $ids['membership'][0];
6a488035
TO
2998 }
2999
3e473c0b 3000 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
66df7769 3001 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
3002 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
6a488035
TO
3003
3004 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
3005 //direct mode showing billing block, so use directIPN for temporary
3006 $template->assign('contributeMode', 'directIPN');
3007 }
3008 }
3009 // todo remove strtolower - check consistency
3010 if (strtolower($this->_component) == 'event') {
66d5d6f4 3011 $eventParams = ['id' => $this->_relatedObjects['participant']->event_id];
3012 $values['event'] = [];
66df7769 3013
3014 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
3015
3016 //get location details
66d5d6f4 3017 $locationParams = [
3018 'entity_id' => $this->_relatedObjects['participant']->event_id,
3019 'entity_table' => 'civicrm_event',
3020 ];
66df7769 3021 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
3022
66d5d6f4 3023 $ufJoinParams = [
66df7769 3024 'entity_table' => 'civicrm_event',
3025 'entity_id' => $ids['event'],
3026 'module' => 'CiviEvent',
66d5d6f4 3027 ];
66df7769 3028
3029 list($custom_pre_id,
3030 $custom_post_ids
3031 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
3032
3033 $values['custom_pre_id'] = $custom_pre_id;
3034 $values['custom_post_id'] = $custom_post_ids;
ec5b3633 3035 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
66df7769 3036 //and cases involving status updation through ipn
3037 // whatever that means!
95e5776c 3038 // total_amount appears to be the preferred input param & it is unclear why we support amount here
3039 // perhaps we should throw an e-notice if amount is set & force total_amount?
3040 if (!empty($input['amount'])) {
3041 $values['totalAmount'] = $input['amount'];
3042 }
55df1211 3043 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
66df7769 3044 if ($values['event']['is_email_confirm']) {
3045 $values['is_email_receipt'] = 1;
3046 }
b7bef093 3047
2b65b515 3048 if (!empty($ids['contribution'])) {
3049 $values['contributionId'] = $ids['contribution'];
3050 }
b7bef093 3051
6a488035
TO
3052 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
3053 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
3054 );
3055 }
3056 else {
3057 $values['contribution_id'] = $this->id;
a7488080 3058 if (!empty($ids['related_contact'])) {
6a488035
TO
3059 $values['related_contact'] = $ids['related_contact'];
3060 if (isset($ids['onbehalf_dupe_alert'])) {
3061 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
3062 }
66d5d6f4 3063 $entityBlock = [
6a488035
TO
3064 'contact_id' => $ids['contact'],
3065 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
3066 'Home', 'id', 'name'
3067 ),
66d5d6f4 3068 ];
6a488035
TO
3069 $address = CRM_Core_BAO_Address::getValues($entityBlock);
3070 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
3071 }
3072 $isTest = FALSE;
3073 if ($this->is_test) {
3074 $isTest = TRUE;
3075 }
3076 if (!empty($this->_relatedObjects['membership'])) {
3077 foreach ($this->_relatedObjects['membership'] as $membership) {
3078 if ($membership->id) {
487c1b17 3079 $values['membership_id'] = $membership->id;
85dea18b 3080 $values['isMembership'] = TRUE;
858f7096 3081 $values['membership_assign'] = TRUE;
6a488035
TO
3082
3083 // need to set the membership values here
6a488035
TO
3084 $template->assign('membership_name',
3085 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
3086 );
3087 $template->assign('mem_start_date', $membership->start_date);
3088 $template->assign('mem_join_date', $membership->join_date);
3089 $template->assign('mem_end_date', $membership->end_date);
3090 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
3091 $template->assign('mem_status', $membership_status);
3092 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
c2358f41 3093 $values['is_pay_later'] = 1;
6a488035 3094 }
37c88e84
JP
3095 // Pass amount to floatval as string '0.00' is considered a
3096 // valid amount and includes Fee section in the mail.
3097 if (isset($values['amount'])) {
3098 $values['amount'] = floatval($values['amount']);
3099 }
6a488035 3100
d891a273 3101 if (!empty($this->contribution_recur_id) && $paymentObject) {
3e473c0b 3102 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'cancel');
6a488035
TO
3103 $template->assign('cancelSubscriptionUrl', $url);
3104 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
3105 $template->assign('updateSubscriptionBillingUrl', $url);
3106 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
3107 $template->assign('updateSubscriptionUrl', $url);
3108 }
3109
3110 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3111
3112 return $result;
3113 // otherwise if its about sending emails, continue sending without return, as we
3114 // don't want to exit the loop.
3115 }
3116 }
3117 }
3118 else {
3119 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3120 }
3121 }
3122 }
3123
16b10e64 3124 /**
6a488035
TO
3125 * Gather values for contribution mail - this function has been created
3126 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3127 * Values related to the contribution in question are gathered
3128 *
014c4014
TO
3129 * @param array $input
3130 * Input into function (probably from payment processor).
16b10e64 3131 * @param array $values
014c4014 3132 * @param array $ids
16b10e64 3133 * The set of ids related to the input.
6a488035 3134 *
a6c01b45 3135 * @return array
0a12bb75 3136 * @throws \CRM_Core_Exception
186c9c17 3137 */
66d5d6f4 3138 public function _gatherMessageValues($input, &$values, $ids = []) {
6a488035 3139 // set display address of contributor
49cba3ad 3140 $values['billingName'] = '';
6a488035 3141 if ($this->address_id) {
49cba3ad 3142 $addressDetails = CRM_Core_BAO_Address::getValues(['id' => $this->address_id], FALSE, 'id');
3143 $addressDetails = reset($addressDetails);
3144 $values['billingName'] = $addressDetails['name'] ?? '';
6a488035 3145 }
2b221bad
TM
3146 // Else we assign the billing address of the contribution contact.
3147 else {
49cba3ad 3148 $addressDetails = (array) CRM_Core_BAO_Address::getValues(['contact_id' => $this->contact_id, 'is_billing' => 1]);
3149 $addressDetails = reset($addressDetails);
2b221bad 3150 }
49cba3ad 3151 $values['address'] = $addressDetails['display'] ?? '';
2a0df9d9 3152
49cba3ad 3153 if ($this->_component === 'contribute') {
a49aa7dd
TM
3154 //get soft contributions
3155 $softContributions = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id, TRUE);
3156 if (!empty($softContributions)) {
126c4e4d 3157 // For pcp soft credit, there is no 'soft_credit' member it comes
3158 // back in different array members, but shortly after returning from
3159 // this function it calls _assignMessageVariablesToTemplate which does
3160 // its own lookup of any pcp soft credit, so we can skip it here.
3161 $values['softContributions'] = $softContributions['soft_credit'] ?? NULL;
a49aa7dd 3162 }
6a488035 3163 if (isset($this->contribution_page_id)) {
55df1211 3164 // This is a call we want to use less, in favour of loading related objects.
f99a6f98 3165 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
6a488035 3166 if ($this->contribution_page_id) {
55df1211
AS
3167 // This is precautionary as there are some legacy flows, but it should really be
3168 // loaded by now.
3169 if (!isset($this->_relatedObjects['contributionPage'])) {
66d5d6f4 3170 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id]);
55df1211 3171 }
85939a77 3172 CRM_Contribute_BAO_Contribution_Utils::overrideDefaultCurrency($values);
6a488035
TO
3173 }
3174 }
3175 // no contribution page -probably back office
3176 else {
3177 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
6a488035
TO
3178 $values['title'] = 'Contribution';
3179 }
3180 // set lineItem for contribution
3181 if ($this->id) {
270ff672 3182 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->id);
3183 if (!empty($lineItems)) {
3184 $firstLineItem = reset($lineItems);
66d5d6f4 3185 $priceSet = [];
de6c59ca 3186 if (!empty($firstLineItem['price_set_id'])) {
66d5d6f4 3187 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3188 'id' => $firstLineItem['price_set_id'],
3189 'return' => 'is_quick_config, id',
3190 ]);
e81d9dcf
AS
3191 $values['priceSetID'] = $priceSet['id'];
3192 }
270ff672 3193 foreach ($lineItems as &$eachItem) {
7c063f32 3194 if (isset($this->_relatedObjects['membership'])
66d5d6f4 3195 && is_array($this->_relatedObjects['membership'])
6e948f0d
SP
3196 && array_key_exists($eachItem['entity_id'] . '_' . $eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
3197 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->join_date);
3198 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->start_date);
3199 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->end_date);
6a488035 3200 }
270ff672 3201 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3202 // However, that does create upgrade pain so would be better to be phased in.
c95c2012 3203 $values['useForMember'] = empty($priceSet['is_quick_config']);
6a488035 3204 }
270ff672 3205 $values['lineItem'][0] = $lineItems;
f2b2a3ff 3206 }
6a488035
TO
3207 }
3208
3209 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
3210 $this->id,
3211 $this->contact_id
3212 );
3213 // if this is onbehalf of contribution then set related contact
a7488080 3214 if (!empty($relatedContact['individual_id'])) {
6a488035
TO
3215 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3216 }
3217 }
3218 else {
0a12bb75 3219 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects['participant']->id, $this->id));
6a488035
TO
3220 }
3221
0b330e6d 3222 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', NULL, $this->id);
7089d2d8 3223
66d5d6f4 3224 $customGroup = [];
7089d2d8
TM
3225 foreach ($groupTree as $key => $group) {
3226 if ($key === 'info') {
3227 continue;
3228 }
3229
3230 foreach ($group['fields'] as $k => $customField) {
3231 $groupLabel = $group['title'];
3232 if (!empty($customField['customValue'])) {
3233 foreach ($customField['customValue'] as $customFieldValues) {
9c1bc317 3234 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ?? NULL;
7089d2d8
TM
3235 }
3236 }
3237 }
3238 }
3239 $values['customGroup'] = $customGroup;
3240
dbacb875 3241 $values['is_pay_later'] = $this->is_pay_later;
717fdb8a 3242
6a488035
TO
3243 return $values;
3244 }
3245
3246 /**
9daadfce 3247 * Assign message variables to template but try to break the habit.
3248 *
3249 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3250 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3251 * multiple recurring payments for processors like IATS that use tokens.
3252 *
6a488035
TO
3253 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3254 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
9daadfce 3255 * Note we send directly from this function in some cases because it is only partly refactored.
3256 *
3257 * Don't call this function directly as the signature will change.
02af3683
EM
3258 *
3259 * @param $values
3260 * @param $input
02af3683
EM
3261 * @param bool $returnMessageText
3262 *
3263 * @return mixed
6a488035 3264 */
d891a273 3265 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
5d6cf648
JM
3266 // @todo - this should have a better separation of concerns - ie.
3267 // gatherMessageValues should build an array of values to be assigned to the template
3268 // and this function should assign them (assigning null if not set).
3269 // the way the pcpParams & honor Params section works is a baby-step towards this.
d891a273 3270 $template = CRM_Core_Smarty::singleton();
6a488035
TO
3271 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
3272 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
3273 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
49cba3ad 3274 $template->assign('billingName', $values['billingName']);
367b5943 3275
3276 // For some unit tests contribution cannot contain paymentProcessor information
3277 $billingMode = empty($this->_relatedObjects['paymentProcessor']) ? CRM_Core_Payment::BILLING_MODE_NOTIFY : $this->_relatedObjects['paymentProcessor']['billing_mode'];
d4578334 3278 $template->assign('contributeMode', CRM_Core_SelectValues::contributeMode()[$billingMode] ?? NULL);
367b5943 3279
02af3683 3280 //assign honor information to receipt message
8af73472 3281 $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
6a488035 3282
66d5d6f4 3283 $honorParams = [
3284 'soft_credit_type' => NULL,
3285 'honor_block_is_active' => NULL,
3286 ];
8af73472 3287 if (isset($softRecord['soft_credit'])) {
7305d3e6 3288 //if id of contribution page is present
3289 if (!empty($values['id'])) {
66d5d6f4 3290 $values['honor'] = [
3291 'honor_profile_values' => [],
7305d3e6 3292 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3293 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
66d5d6f4 3294 ];
6a488035 3295
5d6cf648
JM
3296 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3297 $honorParams['honor_block_is_active'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
7305d3e6 3298 }
3299 else {
3300 //offline contribution
66d5d6f4 3301 $softCreditTypes = $softCredits = [];
7305d3e6 3302 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3303 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
66d5d6f4 3304 $softCredits[$key] = [
7305d3e6 3305 'Name' => $softCredit['contact_name'],
21dfd5f5 3306 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
66d5d6f4 3307 ];
7305d3e6 3308 }
3309 $template->assign('softCreditTypes', $softCreditTypes);
3310 $template->assign('softCredits', $softCredits);
3311 }
6a488035
TO
3312 }
3313
3314 $dao = new CRM_Contribute_DAO_ContributionProduct();
3315 $dao->contribution_id = $this->id;
3316 if ($dao->find(TRUE)) {
3317 $premiumId = $dao->product_id;
3318 $template->assign('option', $dao->product_option);
3319
3320 $productDAO = new CRM_Contribute_DAO_Product();
3321 $productDAO->id = $premiumId;
3322 $productDAO->find(TRUE);
3323 $template->assign('selectPremium', TRUE);
3324 $template->assign('product_name', $productDAO->name);
3325 $template->assign('price', $productDAO->price);
3326 $template->assign('sku', $productDAO->sku);
3327 }
d4578334 3328 $template->assign('title', $values['title'] ?? NULL);
858f7096 3329 $values['amount'] = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL);
3330 if (!$values['amount'] && isset($this->total_amount)) {
3331 $values['amount'] = $this->total_amount;
6a488035 3332 }
858f7096 3333
66d5d6f4 3334 $pcpParams = [
3335 'pcpBlock' => NULL,
3336 'pcp_display_in_roll' => NULL,
3337 'pcp_roll_nickname' => NULL,
3338 'pcp_personal_note' => NULL,
3339 'title' => NULL,
3340 ];
5d6cf648 3341
6a488035
TO
3342 if (strtolower($this->_component) == 'contribute') {
3343 //PCP Info
3344 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3345 $softDAO->contribution_id = $this->id;
3346 if ($softDAO->find(TRUE)) {
5d6cf648
JM
3347 $pcpParams['pcpBlock'] = TRUE;
3348 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll;
3349 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname;
3350 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note;
6a488035
TO
3351
3352 //assign the pcp page title for email subject
3353 $pcpDAO = new CRM_PCP_DAO_PCP();
3354 $pcpDAO->id = $softDAO->pcp_id;
3355 if ($pcpDAO->find(TRUE)) {
5d6cf648 3356 $pcpParams['title'] = $pcpDAO->title;
6a488035
TO
3357 }
3358 }
3359 }
5d6cf648
JM
3360 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3361 $template->assign($templateKey, $templateValue);
3362 }
6a488035
TO
3363
3364 if ($this->financial_type_id) {
3365 $values['financial_type_id'] = $this->financial_type_id;
3366 }
3367
6a488035
TO
3368 $template->assign('trxn_id', $this->trxn_id);
3369 $template->assign('receive_date',
5bab7daf 3370 CRM_Utils_Date::processDate($this->receive_date)
6a488035 3371 );
76e8d9c4 3372 $values['receipt_date'] = (empty($this->receipt_date) ? NULL : $this->receipt_date);
6a488035 3373 $template->assign('action', $this->is_test ? 1024 : 1);
d4578334 3374 $template->assign('receipt_text', $values['receipt_text'] ?? NULL);
6a488035 3375 $template->assign('is_monetary', 1);
d891a273 3376 $template->assign('is_recur', !empty($this->contribution_recur_id));
6a488035
TO
3377 $template->assign('currency', $this->currency);
3378 $template->assign('address', CRM_Utils_Address::format($input));
7089d2d8
TM
3379 if (!empty($values['customGroup'])) {
3380 $template->assign('customGroup', $values['customGroup']);
3381 }
a49aa7dd
TM
3382 if (!empty($values['softContributions'])) {
3383 $template->assign('softContributions', $values['softContributions']);
3384 }
6a488035
TO
3385 if ($this->_component == 'event') {
3386 $template->assign('title', $values['event']['title']);
3387 $participantRoles = CRM_Event_PseudoConstant::participantRole();
66d5d6f4 3388 $viewRoles = [];
6a488035
TO
3389 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
3390 $viewRoles[] = $participantRoles[$v];
3391 }
3392 $values['event']['participant_role'] = implode(', ', $viewRoles);
3393 $template->assign('event', $values['event']);
7089d2d8 3394 $template->assign('participant', $values['participant']);
6a488035
TO
3395 $template->assign('location', $values['location']);
3396 $template->assign('customPre', $values['custom_pre_id']);
3397 $template->assign('customPost', $values['custom_post_id']);
3398
3399 $isTest = FALSE;
3400 if ($this->_relatedObjects['participant']->is_test) {
3401 $isTest = TRUE;
3402 }
3403
66d5d6f4 3404 $values['params'] = [];
6a488035
TO
3405 //to get email of primary participant.
3406 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
66d5d6f4 3407 $primaryAmount[] = [
f2b2a3ff 3408 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail,
21dfd5f5 3409 'amount' => $this->_relatedObjects['participant']->fee_amount,
66d5d6f4 3410 ];
6a488035
TO
3411 //build an array of cId/pId of participants
3412 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
3413 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
3414 //send receipt to additional participant if exists
3415 if (count($additionalIDs)) {
3416 $template->assign('isPrimary', 0);
3417 $template->assign('customProfile', NULL);
3418 //set additionalParticipant true
3419 $values['params']['additionalParticipant'] = TRUE;
3420 foreach ($additionalIDs as $pId => $cId) {
66d5d6f4 3421 $amount = [];
6a488035
TO
3422 //to change the status pending to completed
3423 $additional = new CRM_Event_DAO_Participant();
3424 $additional->id = $pId;
3425 $additional->contact_id = $cId;
3426 $additional->find(TRUE);
3427 $additional->register_date = $this->_relatedObjects['participant']->register_date;
3428 $additional->status_id = 1;
3429 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
3430 //if additional participant dont have email
3431 //use display name.
3432 if (!$additionalParticipantInfo) {
3433 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
3434 }
66d5d6f4 3435 $amount[0] = [
3436 'label' => $additional->fee_level,
3437 'amount' => $additional->fee_amount,
3438 ];
3439 $primaryAmount[] = [
f2b2a3ff 3440 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo,
21dfd5f5 3441 'amount' => $additional->fee_amount,
66d5d6f4 3442 ];
6a488035 3443 $additional->save();
6a488035
TO
3444 $template->assign('amount', $amount);
3445 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3446 }
3447 }
3448
3449 //build an array of custom profile and assigning it to template
3450 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
3451
3452 if (count($customProfile)) {
3453 $template->assign('customProfile', $customProfile);
3454 }
3455
3456 // for primary contact
3457 $values['params']['additionalParticipant'] = FALSE;
3458 $template->assign('isPrimary', 1);
3459 $template->assign('amount', $primaryAmount);
3460 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
3461 if ($this->payment_instrument_id) {
3462 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
3463 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
3464 }
3465 // carry paylater, since we did not created billing,
3466 // so need to pull email from primary location, CRM-4395
3467 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
3468 }
3469 return $template;
3470 }
3471
3472 /**
100fef9d 3473 * Check whether payment processor supports
6a488035
TO
3474 * cancellation of contribution subscription
3475 *
014c4014
TO
3476 * @param int $contributionId
3477 * Contribution id.
6a488035 3478 *
77b97be7
EM
3479 * @param bool $isNotCancelled
3480 *
a130e045 3481 * @return bool
6a488035 3482 */
00be9182 3483 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
6a488035
TO
3484 $cacheKeyString = "$contributionId";
3485 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
3486
66d5d6f4 3487 static $supportsCancel = [];
6a488035
TO
3488
3489 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3490 $supportsCancel[$cacheKeyString] = FALSE;
3491 $isCancelled = FALSE;
3492
3493 if ($isNotCancelled) {
3494 $isCancelled = self::isSubscriptionCancelled($contributionId);
3495 }
3496
3497 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
3498 if (!empty($paymentObject)) {
1524a007 3499 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
6a488035
TO
3500 }
3501 }
3502 return $supportsCancel[$cacheKeyString];
3503 }
3504
3505 /**
fe482240 3506 * Check whether subscription is already cancelled.
6a488035 3507 *
014c4014
TO
3508 * @param int $contributionId
3509 * Contribution id.
6a488035 3510 *
a6c01b45
CW
3511 * @return string
3512 * contribution status
6a488035 3513 */
00be9182 3514 public static function isSubscriptionCancelled($contributionId) {
6a488035
TO
3515 $sql = "
3516 SELECT cr.contribution_status_id
3517 FROM civicrm_contribution_recur cr
3518 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3519 WHERE con.id = %1 LIMIT 1";
66d5d6f4 3520 $params = [1 => [$contributionId, 'Integer']];
6a488035 3521 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
27a3bca0 3522 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name');
6a488035
TO
3523 if ($status == 'Cancelled') {
3524 return TRUE;
3525 }
3526 return FALSE;
3527 }
3528
3529 /**
fe482240 3530 * Create all financial accounts entry.
6a488035 3531 *
014c4014
TO
3532 * @param array $params
3533 * Contribution object, line item array and params for trxn.
6a488035 3534 *
6a488035 3535 *
02af3683 3536 * @param array $financialTrxnValues
77b97be7 3537 *
9a2dce8d 3538 * @return null|\CRM_Core_BAO_FinancialTrxn
6a488035 3539 */
00be9182 3540 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
cb579c66 3541 $skipRecords = $update = $return = $isRelatedId = FALSE;
1a459cc2 3542 $isUpdate = !empty($params['prevContribution']);
02af3683 3543
66d5d6f4 3544 $additionalParticipantId = [];
6a488035 3545 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
10fd773f 3546 $contributionStatus = empty($params['contribution_status_id']) ? NULL : $contributionStatuses[$params['contribution_status_id']];
6a488035
TO
3547
3548 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
3549 $entityId = $params['participant_id'];
3550 $entityTable = 'civicrm_participant';
d37ade2e 3551 $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
6a488035 3552 }
8aa7457a
EM
3553 elseif (!empty($params['membership_id'])) {
3554 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3555 // are created off one contribution should be handled elsewhere
3556 $entityId = $params['membership_id'];
3557 $entityTable = 'civicrm_membership';
3558 }
6a488035
TO
3559 else {
3560 $entityId = $params['contribution']->id;
3561 $entityTable = 'civicrm_contribution';
3562 }
4d34aefa 3563
cb579c66
PN
3564 if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') {
3565 $isRelatedId = TRUE;
3566 }
85dea18b 3567
464bb009 3568 $entityID[] = $entityId;
d37ade2e 3569 if (!empty($additionalParticipantId)) {
3570 $entityID += $additionalParticipantId;
464bb009 3571 }
4d34aefa 3572 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
a7488080 3573 if (empty($params['prevContribution'])) {
6a488035
TO
3574 $entityID = NULL;
3575 }
4d34aefa 3576
f8325309 3577 $statusId = $params['contribution']->contribution_status_id;
f8325309 3578
6a488035 3579 // build line item array if its not set in $params
a7488080 3580 if (empty($params['line_item']) || $additionalParticipantId) {
cb579c66 3581 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
6a488035
TO
3582 }
3583
4e92d4f4 3584 if ($contributionStatus != 'Failed' &&
3585 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later)
f2b2a3ff 3586 ) {
6a488035 3587 $skipRecords = TRUE;
66d5d6f4 3588 $pendingStatus = [
4e92d4f4 3589 'Pending',
3590 'In Progress',
66d5d6f4 3591 ];
4e92d4f4 3592 if (in_array($contributionStatus, $pendingStatus)) {
bf2cf926 3593 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
3594 $params['financial_type_id'],
3595 'Accounts Receivable Account is'
3596 );
6a488035 3597 }
a7488080 3598 elseif (!empty($params['payment_processor'])) {
74afdc40 3599 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
66d5d6f4 3600 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
bf722049 3601 'id' => $params['payment_processor'],
3602 'return' => 'payment_instrument_id',
66d5d6f4 3603 ]);
6a488035 3604 }
a7488080 3605 elseif (!empty($params['payment_instrument_id'])) {
6a488035
TO
3606 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
3607 }
3608 else {
ac7514c2 3609 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
66d5d6f4 3610 $queryParams = [1 => [$relationTypeId, 'Integer']];
ac7514c2 3611 $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
3612 }
3613
9c1bc317 3614 $totalAmount = $params['total_amount'] ?? NULL;
8cc574cf 3615 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
6a488035
TO
3616 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
3617 }
3618 //build financial transaction params
66d5d6f4 3619 $trxnParams = [
6a488035
TO
3620 'contribution_id' => $params['contribution']->id,
3621 'to_financial_account_id' => $params['to_financial_account_id'],
2d8ae159 3622 'trxn_date' => !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'),
6a488035 3623 'total_amount' => $totalAmount,
6b409353 3624 'fee_amount' => $params['fee_amount'] ?? NULL,
60a2aeee 3625 'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount),
6a488035
TO
3626 'currency' => $params['contribution']->currency,
3627 'trxn_id' => $params['contribution']->trxn_id,
2561fc11 3628 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3629 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3630 // this should really default to completed (after discussion).
f8325309 3631 'status_id' => $statusId,
bf722049 3632 'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id),
6b409353
CW
3633 'check_number' => $params['check_number'] ?? NULL,
3634 'pan_truncation' => $params['pan_truncation'] ?? NULL,
3635 'card_type_id' => $params['card_type_id'] ?? NULL,
66d5d6f4 3636 ];
8a0c74ae 3637 if ($contributionStatus == 'Refunded' || $contributionStatus == 'Chargeback' || $contributionStatus == 'Cancelled') {
10fd773f 3638 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date) ? $params['contribution']->cancel_date : date('YmdHis');
797d4c52 3639 if (isset($params['refund_trxn_id'])) {
3640 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3641 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3642 }
10fd773f 3643 }
a246714d 3644 //CRM-16259, set is_payment flag for non pending status
0170d873 3645 if (!in_array($contributionStatus, $pendingStatus)) {
a246714d
PN
3646 $trxnParams['is_payment'] = 1;
3647 }
a7488080 3648 if (!empty($params['payment_processor'])) {
8ef12e64 3649 $trxnParams['payment_processor_id'] = $params['payment_processor'];
6a488035 3650 }
0f602e3f
PJ
3651
3652 if (isset($fromFinancialAccountId)) {
3653 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3654 }
3655
3656 // consider external values passed for recording transaction entry
02af3683
EM
3657 if (!empty($financialTrxnValues)) {
3658 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
0f602e3f 3659 }
80c9b98c
PN
3660 if (empty($trxnParams['payment_processor_id'])) {
3661 unset($trxnParams['payment_processor_id']);
3662 }
0f602e3f 3663
6a488035
TO
3664 $params['trxnParams'] = $trxnParams;
3665
1a459cc2 3666 if ($isUpdate) {
99cdd94d 3667 $updated = FALSE;
404f77c9
PN
3668 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount;
3669 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount;
3670 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount;
797d4c52 3671 if (!isset($params['trxnParams']['trxn_id'])) {
3672 // Actually I have no idea why we are overwriting any values from the previous contribution.
3673 // (filling makes sense to me). However, only protecting this value as I really really know we
3674 // don't want this one overwritten.
3675 // CRM-17751.
3676 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id;
3677 }
404f77c9 3678 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id;
48ea0708 3679
182228d5 3680 if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)
f2b2a3ff
TO
3681 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses))
3682 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))
3683 ) {
182228d5
PN
3684 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
3685 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
3686 }
85dea18b 3687
404f77c9 3688 //if financial type is changed
a7488080 3689 if (!empty($params['financial_type_id']) &&
f2b2a3ff
TO
3690 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id
3691 ) {
8cf6bd83
PN
3692 $accountRelationship = 'Income Account is';
3693 if (!empty($params['revenue_recognition_date']) || $params['prevContribution']->revenue_recognition_date) {
3694 $accountRelationship = 'Deferred Revenue Account is';
3695 }
928a340b 3696 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id, $accountRelationship);
3697 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
404f77c9
PN
3698 if ($oldFinancialAccount != $newFinancialAccount) {
3699 $params['total_amount'] = 0;
1a3d69b0
SL
3700 // If we have a fee amount set reverse this as well.
3701 if (isset($params['fee_amount'])) {
3702 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3703 }
b81ee58c 3704 if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) {
928a340b 3705 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
876b8ab0 3706 $params['prevContribution']->financial_type_id, $accountRelationship);
404f77c9
PN
3707 }
3708 else {
3709 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
a7488080 3710 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
404f77c9
PN
3711 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3712 }
3713 }
3714 self::updateFinancialAccounts($params, 'changeFinancialType');
901094eb 3715 $params['skipLineItem'] = FALSE;
3716 foreach ($params['line_item'] as &$lineItems) {
3717 foreach ($lineItems as &$line) {
3718 $line['financial_type_id'] = $params['financial_type_id'];
3719 }
3720 }
3721 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
404f77c9
PN
3722 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3723 $params['financial_account_id'] = $newFinancialAccount;
8cf6bd83 3724 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
1a3d69b0
SL
3725 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3726 if (isset($params['fee_amount'])) {
3727 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3728 }
404f77c9 3729 self::updateFinancialAccounts($params);
901094eb 3730 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE);
404f77c9 3731 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
99cdd94d 3732 $updated = TRUE;
8cf6bd83 3733 $params['deferred_financial_account_id'] = $newFinancialAccount;
404f77c9 3734 }
6a488035 3735 }
48ea0708 3736
6a488035 3737 //Update contribution status
404f77c9 3738 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
797d4c52 3739 if (!isset($params['refund_trxn_id'])) {
3740 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3741 // gets preference over another so I am only 'protecting' a very specific tested flow
3742 // and letting natural justice take care of the rest.
3743 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3744 }
a7488080 3745 if (!empty($params['contribution_status_id']) &&
f2b2a3ff
TO
3746 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3747 ) {
6a488035 3748 //Update Financial Records
f8cd7ee2 3749 $callUpdateFinancialAccounts = self::updateFinancialAccountsOnContributionStatusChange($params);
3750 if ($callUpdateFinancialAccounts) {
3751 self::updateFinancialAccounts($params, 'changedStatus');
901094eb 3752 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
f8cd7ee2 3753 }
99cdd94d 3754 $updated = TRUE;
6a488035
TO
3755 }
3756
3757 // change Payment Instrument for a Completed contribution
3758 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3759 // instrument is null and now new payment instrument is added along with the payment
04cd605c 3760 if (!$params['contribution']->payment_instrument_id) {
3761 $params['contribution']->find(TRUE);
3762 }
404f77c9 3763 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
9c1bc317 3764 $params['trxnParams']['check_number'] = $params['check_number'] ?? NULL;
5ca657dd 3765
3766 if (self::isPaymentInstrumentChange($params, $pendingStatus)) {
3767 $updated = CRM_Core_BAO_FinancialTrxn::updateFinancialAccountsOnPaymentInstrumentChange($params);
6a488035 3768 }
48ea0708 3769
404f77c9 3770 //if Change contribution amount
9c1bc317
CW
3771 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ?? NULL;
3772 $params['trxnParams']['net_amount'] = $params['net_amount'] ?? NULL;
d9814f68 3773 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
404f77c9
PN
3774 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3775 if (isset($totalAmount) &&
f2b2a3ff
TO
3776 $totalAmount != $params['prevContribution']->total_amount
3777 ) {
404f77c9
PN
3778 //Update Financial Records
3779 $params['trxnParams']['from_financial_account_id'] = NULL;
404f77c9 3780 self::updateFinancialAccounts($params, 'changedAmount');
901094eb 3781 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
99cdd94d 3782 $updated = TRUE;
3783 }
3784
3785 if (!$updated) {
3786 // Looks like we might have a data correction update.
3787 // This would be a case where a transaction id has been entered but it is incorrect &
3788 // the person goes back in & fixes it, as opposed to a new transaction.
3789 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3790 // the data fix scenario.
3791 // CRM-17751.
3792 if (isset($params['refund_trxn_id'])) {
3793 $refundIDs = CRM_Core_BAO_FinancialTrxn::getRefundTransactionIDs($params['id']);
48714ae7 3794 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
66d5d6f4 3795 civicrm_api3('FinancialTrxn', 'create', [
3796 'id' => $refundIDs['financialTrxnId'],
3797 'trxn_id' => $params['refund_trxn_id'],
3798 ]);
99cdd94d 3799 }
3800 }
9c1bc317
CW
3801 $cardType = $params['card_type_id'] ?? NULL;
3802 $panTruncation = $params['pan_truncation'] ?? NULL;
2c4a6dc8 3803 CRM_Core_BAO_FinancialTrxn::updateCreditCardDetails($params['contribution']->id, $panTruncation, $cardType);
6a488035 3804 }
6a488035
TO
3805 }
3806
1a459cc2 3807 else {
1c19e0a3
PJ
3808 // records finanical trxn and entity financial trxn
3809 // also make it available as return value
9c472292 3810 self::recordAlwaysAccountsReceivable($trxnParams, $params);
9c1bc317
CW
3811 $trxnParams['pan_truncation'] = $params['pan_truncation'] ?? NULL;
3812 $trxnParams['card_type_id'] = $params['card_type_id'] ?? NULL;
1c19e0a3 3813 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
3d93e98e 3814 $params['entity_id'] = $financialTxn->id;
f49cdeab 3815 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3d93e98e
PN
3816 self::$_trxnIDs[] = $financialTxn->id;
3817 }
6a488035 3818 }
e005ab6b 3819 }
b44e3f84 3820 // record line items and financial items
a7488080 3821 if (empty($params['skipLineItem'])) {
1a459cc2 3822 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
6a488035
TO
3823 }
3824
14b74ca6 3825 // create batch entry if batch_id is passed and
3826 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3827 if (!empty($params['batch_id']) && !empty($financialTxn)) {
66d5d6f4 3828 $entityParams = [
6a488035
TO
3829 'batch_id' => $params['batch_id'],
3830 'entity_table' => 'civicrm_financial_trxn',
3831 'entity_id' => $financialTxn->id,
66d5d6f4 3832 ];
ee20d7be 3833 CRM_Batch_BAO_EntityBatch::create($entityParams);
6a488035
TO
3834 }
3835
3836 // when a fee is charged
8cc574cf 3837 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
6a488035
TO
3838 CRM_Core_BAO_FinancialTrxn::recordFees($params);
3839 }
3840
a7488080 3841 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
f2b2a3ff
TO
3842 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3843 ) {
6a488035
TO
3844 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3845 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
3846 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
3847 }
3848 unset($params['line_item']);
7b361924 3849 self::$_trxnIDs = NULL;
1c19e0a3 3850 return $return;
6a488035
TO
3851 }
3852
3853 /**
fe482240 3854 * Update all financial accounts entry.
6a488035 3855 *
014c4014
TO
3856 * @param array $params
3857 * Contribution object, line item array and params for trxn.
6a488035 3858 *
014c4014
TO
3859 * @param string $context
3860 * Update scenarios.
6a488035 3861 *
66d5d6f4 3862 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3863 * adds unpredictability.
3864 *
6a488035 3865 */
8a477059 3866 public static function updateFinancialAccounts(&$params, $context = NULL) {
3867 $trxnID = NULL;
3868 $inputParams = $params;
05a42c4a 3869 $isARefund = self::isContributionUpdateARefund($params['prevContribution']->contribution_status_id, $params['contribution']->contribution_status_id);
8a477059 3870
ea2ca75d 3871 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
3872 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3873 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount);
3874 }
3875
b34861f3 3876 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
8a40179e 3877 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
b34861f3 3878 $params['entity_id'] = $trxn->id;
6a488035 3879
efb16c63 3880 $itemParams['entity_table'] = 'civicrm_line_item';
3881 $trxnIds['id'] = $params['entity_id'];
3882 $previousLineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($params['contribution']->id);
3883 foreach ($params['line_item'] as $fieldId => $fields) {
592a64a0 3884 $params = self::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
6a488035
TO
3885 }
3886 }
3887
52da5b1e 3888 /**
3889 * Is this contribution status a reversal.
3890 *
3891 * If so we would expect to record a negative value in the financial_trxn table.
3892 *
3893 * @param int $status_id
3894 *
3895 * @return bool
3896 */
3897 public static function isContributionStatusNegative($status_id) {
66d5d6f4 3898 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
05a42c4a 3899 return in_array(CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
52da5b1e 3900 }
3901
6a488035 3902 /**
fe482240 3903 * Check status validation on update of a contribution.
6a488035 3904 *
014c4014
TO
3905 * @param array $values
3906 * Previous form values before submit.
6a488035 3907 *
014c4014
TO
3908 * @param array $fields
3909 * The input form values.
6a488035 3910 *
014c4014
TO
3911 * @param array $errors
3912 * List of errors.
6a488035 3913 *
77b97be7 3914 * @return bool
6a488035 3915 */
00be9182 3916 public static function checkStatusValidation($values, &$fields, &$errors) {
8cc574cf 3917 if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) {
c71ae314
PN
3918 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3919 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3920 return FALSE;
3921 }
3922 }
6a488035 3923 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
66d5d6f4 3924 $checkStatus = [
3925 'Cancelled' => ['Completed', 'Refunded'],
3926 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3927 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3928 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3929 'Refunded' => ['Cancelled', 'Completed'],
3930 'Partially paid' => ['Completed'],
7142a4c8 3931 'Pending refund' => ['Completed', 'Refunded'],
5acf0703 3932 'Failed' => ['Pending'],
66d5d6f4 3933 ];
6a488035 3934
da017017 3935 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
66d5d6f4 3936 CRM_Utils_Array::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
da017017 3937 ) {
66d5d6f4 3938 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
353ffa53
TO
3939 1 => $contributionStatuses[$values['contribution_status_id']],
3940 2 => $contributionStatuses[$fields['contribution_status_id']],
66d5d6f4 3941 ]);
6a488035
TO
3942 }
3943 }
c3d24ba7
PN
3944
3945 /**
fe482240 3946 * Delete contribution of contact.
c3d24ba7 3947 *
0e480632 3948 * @see https://issues.civicrm.org/jira/browse/CRM-12155
c3d24ba7 3949 *
014c4014
TO
3950 * @param int $contactId
3951 * Contact id.
c3d24ba7 3952 *
c3d24ba7 3953 */
00be9182 3954 public static function deleteContactContribution($contactId) {
c3d24ba7
PN
3955 $contribution = new CRM_Contribute_DAO_Contribution();
3956 $contribution->contact_id = $contactId;
3957 $contribution->find();
3958 while ($contribution->fetch()) {
3959 self::deleteContribution($contribution->id);
3960 }
3961 }
16c0ec8d
CW
3962
3963 /**
3964 * Get options for a given contribution field.
16c0ec8d 3965 *
014c4014 3966 * @param string $fieldName
bed98343 3967 * @param string $context see CRM_Core_DAO::buildOptionsContext.
66d5d6f4 3968 * @param array $props whatever is known about this dao object.
77b97be7 3969 *
a130e045 3970 * @return array|bool
66d5d6f4 3971 * @see CRM_Core_DAO::buildOptions
3972 *
16c0ec8d 3973 */
66d5d6f4 3974 public static function buildOptions($fieldName, $context = NULL, $props = []) {
16c0ec8d 3975 $className = __CLASS__;
66d5d6f4 3976 $params = [];
9d5c7f14 3977 if (isset($props['orderColumn'])) {
3978 $params['orderColumn'] = $props['orderColumn'];
3979 }
16c0ec8d
CW
3980 switch ($fieldName) {
3981 // This field is not part of this object but the api supports it
3982 case 'payment_processor':
3983 $className = 'CRM_Contribute_BAO_ContributionPage';
3984 // Filter results by contribution page
3985 if (!empty($props['contribution_page_id'])) {
66d5d6f4 3986 $page = civicrm_api('contribution_page', 'getsingle', [
03a8c3dc 3987 'version' => 3,
21dfd5f5 3988 'id' => ($props['contribution_page_id']),
66d5d6f4 3989 ]);
16c0ec8d
CW
3990 $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0);
3991 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3992 }
33a429d4 3993 break;
ea100cb5 3994
33a429d4
CW
3995 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3996 case 'honor_type_id':
3997 $className = 'CRM_Contribute_BAO_ContributionSoft';
3998 $fieldName = 'soft_credit_type_id';
3999 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
4000 break;
f831ac20
EE
4001
4002 case 'contribution_status_id':
4003 if ($context !== 'validate') {
4004 $params['condition'] = "v.name <> 'Template'";
4005 }
16c0ec8d
CW
4006 }
4007 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
4008 }
03a8c3dc 4009
3b67ab13 4010 /**
fe482240 4011 * Validate financial type.
3b67ab13 4012 *
0e480632 4013 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3b67ab13 4014 *
014c4014
TO
4015 * @param int $financialTypeId
4016 * Financial Type id.
3b67ab13 4017 *
77b97be7
EM
4018 * @param string $relationName
4019 *
4020 * @return array|bool
3b67ab13 4021 */
00be9182 4022 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
876b8ab0 4023 $financialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeId, $relationName);
3b67ab13
PN
4024
4025 if (!$financialAccount) {
4026 return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
4027 }
4028 return FALSE;
4029 }
16c0ec8d 4030
186c9c17 4031 /**
f6044c2b 4032 * @param int $targetCid
186c9c17 4033 * @param $activityType
f6044c2b 4034 * @param string $title
100fef9d 4035 * @param int $contributionId
f59c3d85 4036 * @param string $totalAmount
4037 * @param string $currency
4038 * @param string $trxn_date
186c9c17 4039 *
f59c3d85 4040 * @throws \CRM_Core_Exception
4041 * @throws \CiviCRM_API3_Exception
186c9c17 4042 */
f59c3d85 4043 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
4044 $paymentAmount = CRM_Utils_Money::format($totalAmount, $currency);
685dc433 4045 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
f59c3d85 4046 $date = CRM_Utils_Date::isoToMysql($trxn_date);
685dc433
PN
4047 // source record id would be the contribution id
4048 $srcRecId = $contributionId;
bd99f5fe
PJ
4049
4050 // activity params
66d5d6f4 4051 $activityParams = [
bd99f5fe
PJ
4052 'source_contact_id' => $targetCid,
4053 'source_record_id' => $srcRecId,
d66c61b6 4054 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
bd99f5fe
PJ
4055 'subject' => $subject,
4056 'activity_date_time' => $date,
d66c61b6 4057 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
bd99f5fe 4058 'skipRecentView' => TRUE,
66d5d6f4 4059 ];
bd99f5fe
PJ
4060
4061 // create activity with target contacts
4062 $session = CRM_Core_Session::singleton();
4063 $id = $session->get('userID');
4064 if ($id) {
4065 $activityParams['source_contact_id'] = $id;
4066 $activityParams['target_contact_id'][] = $targetCid;
4067 }
f59c3d85 4068 civicrm_api3('Activity', 'create', $activityParams);
0f602e3f 4069 }
16c0ec8d 4070
186c9c17 4071 /**
fe482240 4072 * Get list of payments displayed by Contribute_Page_PaymentInfo.
8cf01b22 4073 *
100fef9d 4074 * @param int $id
4924bfe9 4075 * @param string $component
186c9c17 4076 * @param bool $getTrxnInfo
186c9c17
EM
4077 *
4078 * @return mixed
4924bfe9 4079 *
4080 * @throws \CRM_Core_Exception
4081 * @throws \CiviCRM_API3_Exception
186c9c17 4082 */
4924bfe9 4083 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
a79d2ec2 4084 // @todo deprecate passing in component - always call with contribution.
29c61b58 4085 if ($component == 'event') {
29c61b58 4086 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
ae53df5f
PJ
4087
4088 if (!$contributionId) {
4089 if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4090 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4091 $id = $primaryParticipantId;
4092 }
22825dfc 4093 if (!$contributionId) {
4094 return;
ae53df5f
PJ
4095 }
4096 }
29c61b58 4097 }
268a84f2 4098 elseif ($component == 'membership') {
268a84f2 4099 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4100 }
d4c0653f 4101 else {
4102 $contributionId = $id;
d4c0653f 4103 }
4104
4924bfe9 4105 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
4106 // but need to unpick the whole trxn_id it's returning first.
4107 $oldCalculation = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
4108 $baseTrxnId = !empty($oldCalculation['trxn_id']) ? $oldCalculation['trxn_id'] : NULL;
4d193d61 4109 if (!$baseTrxnId) {
5684b818
PJ
4110 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
4111 $baseTrxnId = $baseTrxnId['financialTrxnId'];
5684b818 4112 }
4924bfe9 4113 $total = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
1010c4e1 4114
abafc4c4 4115 $paymentBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionId, $total);
4116
66d5d6f4 4117 $contribution = civicrm_api3('Contribution', 'getsingle', [
4118 'id' => $contributionId,
4119 'return' => [
4120 'currency',
4121 'is_pay_later',
4122 'contribution_status_id',
4123 'financial_type_id',
4124 ],
4125 ]);
8cf01b22 4126
c0406a91 4127 $info['payLater'] = $contribution['is_pay_later'];
4128 $info['contribution_status'] = $contribution['contribution_status'];
eb6acea3 4129 $info['currency'] = $contribution['currency'];
c0406a91 4130
29c61b58
PJ
4131 $info['total'] = $total;
4132 $info['paid'] = $total - $paymentBalance;
4133 $info['balance'] = $paymentBalance;
4134 $info['id'] = $id;
4135 $info['component'] = $component;
bc2eeabb 4136 if ($getTrxnInfo && $baseTrxnId) {
c086e797 4137 $info['transaction'] = self::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
29c61b58 4138 }
c0406a91 4139
4140 $info['payment_links'] = self::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
29c61b58
PJ
4141 return $info;
4142 }
5a18a545 4143
26085eab 4144 /**
4145 * Get the outstanding balance on a contribution.
4146 *
4147 * @param int $contributionId
4148 * @param float $contributionTotal
4149 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4150 *
4151 * @return float
4152 */
4153 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
26085eab 4154 if ($contributionTotal === NULL) {
4155 $contributionTotal = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
4156 }
26085eab 4157
ee080cf8 4158 return (float) CRM_Utils_Money::subtractCurrencies(
89bfb100 4159 $contributionTotal,
5ab2fd4f 4160 CRM_Core_BAO_FinancialTrxn::getTotalPayments($contributionId, TRUE),
89bfb100
MD
4161 CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4162 );
26085eab 4163 }
4164
7a9ab499 4165 /**
2912ed09 4166 * Get the tax amount (misnamed function).
7a9ab499
EM
4167 *
4168 * @param array $params
7a9ab499 4169 *
2912ed09 4170 * @return array
ba63d813 4171 * @throws \CiviCRM_API3_Exception
7a9ab499 4172 */
ba63d813 4173 protected static function checkTaxAmount($params) {
b5935203 4174 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
4175
7a9ab499 4176 // Update contribution.
b5935203 4177 if (!empty($params['id'])) {
2912ed09 4178 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4179 // there are no tax implications - early return.
4180 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4181 return $params;
4182 }
4183 if (empty($params['prevContribution'])) {
4184 $params['prevContribution'] = self::getOriginalContribution($params['id']);
4185 }
a76b8bd8 4186
66d5d6f4 4187 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
2912ed09 4188 if (!isset($params[$field])) {
4189 if ($field == 'total_amount' && $params['prevContribution']->tax_amount) {
4190 // Tax amount gets added back on later....
4191 $params['total_amount'] = $params['prevContribution']->total_amount -
4192 $params['prevContribution']->tax_amount;
99a4cd32
SL
4193 }
4194 else {
2912ed09 4195 $params[$field] = $params['prevContribution']->$field;
4196 if ($params[$field] != $params['prevContribution']->$field) {
2912ed09 4197 }
99a4cd32
SL
4198 }
4199 }
b107e882 4200 }
a76b8bd8 4201
2912ed09 4202 self::calculateMissingAmountParams($params, $params['id']);
4203 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4204 // Assign tax Amount on update of contribution
4205 if (!empty($params['prevContribution']->tax_amount)) {
b5935203 4206 $params['tax_amount'] = 'null';
66d5d6f4 4207 CRM_Price_BAO_LineItem::getLineItemArray($params, [$params['id']]);
b5935203 4208 foreach ($params['line_item'] as $setID => $priceField) {
4209 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4210 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4211 }
4212 }
4213 }
4214 }
4215 }
4216
2912ed09 4217 // New Contribution and update of contribution with tax rate financial type
5525990d 4218 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
ba63d813 4219 empty($params['skipLineItem'])) {
f2b2a3ff 4220 $taxRateParams = $taxRates[$params['financial_type_id']];
6fec0f2e 4221 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount(CRM_Utils_Array::value('total_amount', $params), $taxRateParams);
4706ed3b 4222 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
b5935203 4223
f2b2a3ff
TO
4224 // Get Line Item on update of contribution
4225 if (isset($params['id'])) {
66d5d6f4 4226 CRM_Price_BAO_LineItem::getLineItemArray($params, [$params['id']]);
f2b2a3ff
TO
4227 }
4228 else {
4229 CRM_Price_BAO_LineItem::getLineItemArray($params);
4230 }
4231 foreach ($params['line_item'] as $setID => $priceField) {
4232 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4233 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
b5935203 4234 }
5525990d 4235 }
def7e770 4236 $params['total_amount'] = CRM_Utils_Array::value('total_amount', $params) + $params['tax_amount'];
f2b2a3ff 4237 }
4c9b6178 4238 elseif (isset($params['api.line_item.create'])) {
5525990d 4239 // Update total amount of contribution using lineItem
66d5d6f4 4240 $taxAmountArray = [];
b5935203 4241 foreach ($params['api.line_item.create'] as $key => $value) {
4242 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
f2b2a3ff 4243 $taxRate = $taxRates[$value['financial_type_id']];
5525990d 4244 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate);
4706ed3b 4245 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
b5935203 4246 }
4247 }
4248 $params['tax_amount'] = array_sum($taxAmountArray);
5525990d 4249 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
b5935203 4250 }
a5bf8a53 4251
b5935203 4252 return $params;
4253 }
96025800 4254
4d47ad17
PN
4255 /**
4256 * Check financial type validation on update of a contribution.
4257 *
5ba7d840 4258 * @param int $financialTypeId
4d47ad17
PN
4259 * Value of latest Financial Type.
4260 *
5ba7d840 4261 * @param int $contributionId
4d47ad17
PN
4262 * Contribution Id.
4263 *
4264 * @param array $errors
4265 * List of errors.
4266 *
81716ddb 4267 * @return void
4d47ad17
PN
4268 */
4269 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4270 if (!empty($financialTypeId)) {
4271 $oldFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4272 if ($oldFinancialTypeId == $financialTypeId) {
81716ddb 4273 return;
4d47ad17
PN
4274 }
4275 }
4276 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
66d5d6f4 4277 $params = [
4278 '1' => [$contributionId, 'Integer'],
4279 ];
4d47ad17
PN
4280 $result = CRM_Core_DAO::executeQuery($sql, $params);
4281 if ($result->N > 1) {
4282 $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.');
4283 }
4284 }
4285
6d0cf504
EM
4286 /**
4287 * Update related pledge payment payments.
4288 *
5e27919e
EM
4289 * This function has been refactored out of the back office contribution form and may
4290 * still overlap with other functions.
4291 *
6d0cf504
EM
4292 * @param string $action
4293 * @param int $pledgePaymentID
4294 * @param int $contributionID
4295 * @param bool $adjustTotalAmount
4296 * @param float $total_amount
4297 * @param float $original_total_amount
4298 * @param int $contribution_status_id
4299 * @param int $original_contribution_status_id
4300 */
5e27919e 4301 public static function updateRelatedPledge(
6d0cf504
EM
4302 $action,
4303 $pledgePaymentID,
4304 $contributionID,
4305 $adjustTotalAmount,
4306 $total_amount,
4307 $original_total_amount,
4308 $contribution_status_id,
4309 $original_contribution_status_id
4310 ) {
8e776a1a
SB
4311 if (!$pledgePaymentID && $action & CRM_Core_Action::ADD && !$contributionID) {
4312 return;
4313 }
4314
6d0cf504
EM
4315 if ($pledgePaymentID) {
4316 //store contribution id in payment record.
4317 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4318 }
4319 else {
4320 $pledgePaymentID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4321 $contributionID,
4322 'id',
4323 'contribution_id'
4324 );
4325 }
fcdf24a4 4326
8e776a1a 4327 if (!$pledgePaymentID) {
fcdf24a4
SB
4328 return;
4329 }
6d0cf504
EM
4330 $pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4331 $contributionID,
4332 'pledge_id',
4333 'contribution_id'
4334 );
4335
4336 $updatePledgePaymentStatus = FALSE;
4337
4338 // If either the status or the amount has changed we update the pledge status.
4339 if ($action & CRM_Core_Action::ADD) {
4340 $updatePledgePaymentStatus = TRUE;
4341 }
4342 elseif ($action & CRM_Core_Action::UPDATE && (($original_contribution_status_id != $contribution_status_id) ||
4343 ($original_total_amount != $total_amount))
4344 ) {
4345 $updatePledgePaymentStatus = TRUE;
4346 }
4347
4348 if ($updatePledgePaymentStatus) {
4349 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID,
66d5d6f4 4350 [$pledgePaymentID],
6d0cf504
EM
4351 $contribution_status_id,
4352 NULL,
4353 $total_amount,
4354 $adjustTotalAmount
4355 );
4356 }
4357 }
456b0145 4358
3c49d90c 4359 /**
4360 * Is there only one line item attached to the contribution.
4361 *
4362 * @param int $id
4363 * Contribution ID.
4364 *
4365 * @return bool
4366 * @throws \CiviCRM_API3_Exception
4367 */
4368 public static function isSingleLineItem($id) {
66d5d6f4 4369 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
3c49d90c 4370 return ($lineItemCount == 1);
4371 }
4372
db59bb73
EM
4373 /**
4374 * Complete an order.
4375 *
4376 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4377 *
4378 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4379 *
4380 * Moving it out of the BaseIPN class is just the first step.
4381 *
4382 * @param array $input
4383 * @param array $ids
fedc226f 4384 * @param \CRM_Contribute_BAO_Contribution $contribution
362f37fc 4385 * @param bool $isPostPaymentCreate
4386 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4387 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4388 * transitioning related elements).
bc854509 4389 *
4390 * @return array
362f37fc 4391 * @throws \CRM_Core_Exception
4392 * @throws \CiviCRM_API3_Exception
db59bb73 4393 */
fedc226f 4394 public static function completeOrder($input, $ids, $contribution, $isPostPaymentCreate = FALSE) {
884f7828 4395 $transaction = new CRM_Core_Transaction();
c7497653 4396 // @todo see if we even need this - it's used further down to create an activity
4397 // but the BAO layer should create that - we just need to add a test to cover it & can
4398 // maybe remove $ids altogether.
adb4fb96 4399 $contributionContactID = $ids['related_contact'];
4400 $participantID = $ids['participant'];
4401 $recurringContributionID = $ids['contributionRecur'];
4402
c7497653 4403 // Unset ids just to make it clear it's not used again.
4404 unset($ids);
66df7769 4405 // The previous details are used when calculating line items so keep it before any code that 'does something'
4406 if (!empty($contribution->id)) {
981e0d0b 4407 $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(['id' => $contribution->id]);
66df7769 4408 }
66d5d6f4 4409 $inputContributionWhiteList = [
b3b7f4c5 4410 'fee_amount',
4411 'net_amount',
4412 'trxn_id',
4413 'check_number',
4414 'payment_instrument_id',
4415 'is_test',
1c98b2d6 4416 'campaign_id',
12829b5d 4417 'receive_date',
d9924163 4418 'receipt_date',
d5580ed4 4419 'contribution_status_id',
a55e39e9 4420 'card_type_id',
4421 'pan_truncation',
fa839a68 4422 'financial_type_id',
66d5d6f4 4423 ];
b3b7f4c5 4424
dc65872a 4425 $paymentProcessorId = $input['payment_processor_id'] ?? NULL;
43c8d1dd 4426
b929cdb4 4427 $completedContributionStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4428
66d5d6f4 4429 $contributionParams = array_merge([
b929cdb4 4430 'contribution_status_id' => $completedContributionStatusID,
26626bac 4431 'source' => self::getRecurringContributionDescription($contribution, $participantID),
66d5d6f4 4432 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
b3b7f4c5 4433 ));
19893cf2 4434
34dc58e7 4435 $contributionParams['payment_processor'] = $paymentProcessorId;
b3b7f4c5 4436
55bc843d 4437 if (empty($contributionParams['payment_instrument_id']) && $paymentProcessorId) {
bf302610 4438 $contributionParams['payment_instrument_id'] = PaymentProcessor::get(FALSE)->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id'];
f443eb02
SL
4439 }
4440
294cc627 4441 if ($recurringContributionID) {
4442 $contributionParams['contribution_recur_id'] = $recurringContributionID;
b3b7f4c5 4443 }
7f4ef731 4444 $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
4445
c80d977f 4446 $contributionResult = self::repeatTransaction($contribution, $input, $contributionParams);
eed14abb 4447 $contributionID = (int) $contribution->id;
db59bb73 4448
db59bb73 4449 if ($input['component'] == 'contribute') {
185a4fe8
MW
4450 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4451 self::updateMembershipBasedOnCompletionOfContribution(
eed14abb 4452 $contributionID,
185a4fe8
MW
4453 $changeDate
4454 );
4455 }
db59bb73
EM
4456 }
4457 else {
0bad10e7 4458 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
adb4fb96 4459 $participantParams['id'] = $participantID;
1c98b2d6 4460 $participantParams['status_id'] = 'Registered';
66df7769 4461 civicrm_api3('Participant', 'create', $participantParams);
db59bb73 4462 }
db59bb73
EM
4463 }
4464
eed14abb 4465 $contributionParams['id'] = $contributionID;
362f37fc 4466 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
db59bb73 4467
c80d977f
JP
4468 if (!$contributionResult) {
4469 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4470 }
db59bb73 4471
d33f8fc4 4472 $contribution->contribution_status_id = $contributionParams['contribution_status_id'];
db59bb73 4473
6e902643 4474 CRM_Core_Error::debug_log_message('Contribution record updated successfully');
db59bb73
EM
4475 $transaction->commit();
4476
70a27406 4477 // @todo - check if Contribution::create does this, test, remove.
eed14abb 4478 CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contributionID, $recurringContributionID,
43c8d1dd 4479 $contributionParams['contribution_status_id'], $input['amount']);
db59bb73
EM
4480
4481 // create an activity record
70a27406 4482 // @todo - check if Contribution::create does this, test, remove.
db59bb73
EM
4483 if ($input['component'] == 'contribute') {
4484 //CRM-4027
4485 $targetContactID = NULL;
c7497653 4486 if ($contributionContactID) {
db59bb73 4487 $targetContactID = $contribution->contact_id;
c7497653 4488 $contribution->contact_id = $contributionContactID;
db59bb73 4489 }
7d2c3972 4490 CRM_Activity_BAO_Activity::addActivity($contribution, 'Contribution', $targetContactID);
db59bb73
EM
4491 }
4492
68dce20c 4493 if (self::isEmailReceipt($input, $contribution->contribution_page_id, $recurringContributionID)) {
66d5d6f4 4494 civicrm_api3('Contribution', 'sendconfirmation', [
eed14abb 4495 'id' => $contributionID,
ec7e3954 4496 'payment_processor_id' => $paymentProcessorId,
66d5d6f4 4497 ]);
db59bb73
EM
4498 CRM_Core_Error::debug_log_message("Receipt sent");
4499 }
4500
4501 CRM_Core_Error::debug_log_message("Success: Database updated");
734d2daa 4502 return $contributionResult;
db59bb73
EM
4503 }
4504
4505 /**
4506 * Send receipt from contribution.
4507 *
4508 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4509 *
4510 * Note that the compose message part has been moved to contribution
4511 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4512 *
4513 * @param array $input
4514 * Incoming data from Payment processor.
4515 * @param array $ids
4516 * Related object IDs.
ec7e3954 4517 * @param int $contributionID
db59bb73
EM
4518 * @param bool $returnMessageText
4519 * Should text be returned instead of sent. This.
4520 * is because the function is also used to generate pdfs
4521 *
4522 * @return array
ec7e3954
E
4523 * @throws \CRM_Core_Exception
4524 * @throws \CiviCRM_API3_Exception
49cba3ad 4525 * @throws \Exception
db59bb73 4526 */
0d07fe4e 4527 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4528 $values = [];
ec7e3954
E
4529 $contribution = new CRM_Contribute_BAO_Contribution();
4530 $contribution->id = $contributionID;
4531 if (!$contribution->find(TRUE)) {
4532 throw new CRM_Core_Exception('Contribution does not exist');
4533 }
4534 $contribution->loadRelatedObjects($input, $ids, TRUE);
db59bb73
EM
4535 // set receipt from e-mail and name in value
4536 if (!$returnMessageText) {
cefed6df 4537 list($values['receipt_from_name'], $values['receipt_from_email']) = self::generateFromEmailAndName($input, $contribution);
db59bb73 4538 }
3b28799d 4539 $values['contribution_status'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id);
d891a273 4540 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
2439fa7b 4541 if ((!isset($input['receipt_update']) || $input['receipt_update']) && empty($contribution->receipt_date)) {
66d5d6f4 4542 civicrm_api3('Contribution', 'create', [
4543 'receipt_date' => 'now',
4544 'id' => $contribution->id,
4545 ]);
cc7b912f 4546 }
76e8d9c4 4547 return $return;
db59bb73
EM
4548 }
4549
cefed6df
SL
4550 /**
4551 * Generate From email and from name in an array values
66d5d6f4 4552 *
81716ddb
EE
4553 * @param array $input
4554 * @param \CRM_Contribute_BAO_Contribution $contribution
66d5d6f4 4555 *
81716ddb 4556 * @return array
cefed6df
SL
4557 */
4558 public static function generateFromEmailAndName($input, $contribution) {
beac1417 4559 // Use input value if supplied.
cefed6df 4560 if (!empty($input['receipt_from_email'])) {
66d5d6f4 4561 return [
c91b34a5 4562 CRM_Utils_Array::value('receipt_from_name', $input, ''),
66d5d6f4 4563 $input['receipt_from_email'],
4564 ];
cefed6df
SL
4565 }
4566 // if we are still empty see if we can use anything from a contribution page.
66d5d6f4 4567 $pageValues = [];
cefed6df 4568 if (!empty($contribution->contribution_page_id)) {
66d5d6f4 4569 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id]);
cefed6df
SL
4570 }
4571 // if we are still empty see if we can use anything from a contribution page.
4572 if (!empty($pageValues['receipt_from_email'])) {
66d5d6f4 4573 return [
343ed83d 4574 CRM_Utils_Array::value('receipt_from_name', $pageValues),
66d5d6f4 4575 $pageValues['receipt_from_email'],
4576 ];
cefed6df 4577 }
b5bfb58f
SL
4578 // If we are still empty fall back to the domain or logged in user information.
4579 return CRM_Core_BAO_Domain::getDefaultReceiptFrom();
cefed6df
SL
4580 }
4581
4ae9c8ac 4582 /**
4583 * Load related memberships.
4584 *
66d5d6f4 4585 * @param array $ids
4586 *
4587 * @return array $ids
4588 *
4589 * @throws Exception
72d57998 4590 * @deprecated
4591 *
4ae9c8ac 4592 * Note that in theory it should be possible to retrieve these from the line_item table
4593 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4594 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4595 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4596 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4597 *
4598 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4599 *
4ae9c8ac 4600 */
e6c7e48d 4601 public function loadRelatedMembershipObjects($ids = []) {
4ae9c8ac 4602 $query = "
4603 SELECT membership_id
4604 FROM civicrm_membership_payment
4605 WHERE contribution_id = %1 ";
66d5d6f4 4606 $params = [1 => [$this->id, 'Integer']];
4607 $ids['membership'] = (array) CRM_Utils_Array::value('membership', $ids, []);
4ae9c8ac 4608
4609 $dao = CRM_Core_DAO::executeQuery($query, $params);
4610 while ($dao->fetch()) {
356bfcaf 4611 if ($dao->membership_id && !in_array($dao->membership_id, $ids['membership'])) {
4612 $ids['membership'][$dao->membership_id] = $dao->membership_id;
4ae9c8ac 4613 }
4614 }
4615
4616 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4617 foreach ($ids['membership'] as $id) {
4618 if (!empty($id)) {
4619 $membership = new CRM_Member_BAO_Membership();
4620 $membership->id = $id;
4621 if (!$membership->find(TRUE)) {
4622 throw new Exception("Could not find membership record: $id");
4623 }
4624 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
4625 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
4626 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
6e948f0d
SP
4627 $this->_relatedObjects['membership'][$membership->id . '_' . $membership->membership_type_id] = $membership;
4628
4ae9c8ac 4629 }
4630 }
4631 }
e6c7e48d 4632 return $ids;
4ae9c8ac 4633 }
4634
7f4ef731 4635 /**
467fe956 4636 * Get the description (source field) for the recurring contribution.
4637 *
4638 * @param CRM_Contribute_BAO_Contribution $contribution
26626bac 4639 * @param int|null $participantID
467fe956 4640 *
81716ddb 4641 * @return string
467fe956 4642 * @throws \CiviCRM_API3_Exception
26626bac 4643 * @throws \API_Exception
467fe956 4644 */
26626bac 4645 protected static function getRecurringContributionDescription($contribution, $participantID) {
6046ccbb 4646 if (!empty($contribution->source)) {
7b9947fb
ML
4647 return $contribution->source;
4648 }
4052b01e 4649 elseif (!empty($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) {
66d5d6f4 4650 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
7f4ef731 4651 'id' => $contribution->contribution_page_id,
4652 'return' => 'title',
66d5d6f4 4653 ]);
7f4ef731 4654 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4655 }
26626bac 4656 elseif ($participantID) {
4657 $eventTitle = Participant::get(FALSE)
4658 ->addSelect('event.title')
4659 ->addWhere('id', '=', (int) $participantID)
4660 ->execute()->first()['event.title'];
4661 return ts('Online Event Registration') . ': ' . $eventTitle;
7f4ef731 4662 }
bef53ccf 4663 elseif (!empty($contribution->contribution_recur_id)) {
4664 return 'recurring contribution';
4665 }
4666 return '';
7f4ef731 4667 }
4668
27d9f6c5 4669 /**
5ba7d840 4670 * Function use to store line item proportionally in in entity financial trxn table
27d9f6c5 4671 *
955ee56e 4672 * @param array $trxnParams
8de1ade9 4673 *
5ba7d840 4674 * @param int $trxnId
8de1ade9
PN
4675 *
4676 * @param float $contributionTotalAmount
27d9f6c5 4677 *
5ba7d840 4678 * @throws \CiviCRM_API3_Exception
27d9f6c5 4679 */
955ee56e
PN
4680 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4681 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($trxnParams['contribution_id']);
27d9f6c5
PN
4682 if (!empty($lineItems)) {
4683 // get financial item
8e10ee7c 4684 list($ftIds, $taxItems) = self::getLastFinancialItemIds($trxnParams['contribution_id']);
66d5d6f4 4685 $entityParams = [
8e10ee7c
PN
4686 'contribution_total_amount' => $contributionTotalAmount,
4687 'trxn_total_amount' => $trxnParams['total_amount'],
4688 'trxn_id' => $trxnId,
66d5d6f4 4689 ];
8e10ee7c 4690 self::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
27d9f6c5
PN
4691 }
4692 }
4693
5c8b902b 4694 /**
b8e45de5
O
4695 * Checks if line items total amounts
4696 * match the contribution total amount.
5c8b902b
PN
4697 *
4698 * @param array $params
4699 * array of order params.
4700 *
bc854509 4701 * @throws \API_Exception
5c8b902b
PN
4702 */
4703 public static function checkLineItems(&$params) {
9c1bc317 4704 $totalAmount = $params['total_amount'] ?? NULL;
5c8b902b 4705 $lineItemAmount = 0;
c16c6ad8 4706
5c8b902b
PN
4707 foreach ($params['line_items'] as &$lineItems) {
4708 foreach ($lineItems['line_item'] as &$item) {
4709 if (empty($item['financial_type_id'])) {
4710 $item['financial_type_id'] = $params['financial_type_id'];
4711 }
dffc9c5f 4712 $lineItemAmount += $item['line_total'] + ($item['tax_amount'] ?? 0.00);
5c8b902b
PN
4713 }
4714 }
c16c6ad8 4715
5c8b902b
PN
4716 if (!isset($totalAmount)) {
4717 $params['total_amount'] = $lineItemAmount;
4718 }
c16c6ad8 4719 else {
dffc9c5f 4720 $currency = $params['currency'] ?? CRM_Core_Config::singleton()->defaultCurrency;
c16c6ad8
CR
4721
4722 if (!CRM_Utils_Money::equals($totalAmount, $lineItemAmount, $currency)) {
4723 throw new CRM_Contribute_Exception_CheckLineItemsException();
4724 }
5c8b902b 4725 }
5c8b902b
PN
4726 }
4727
bf2cf926 4728 /**
4729 * Get the financial account for the item associated with the new transaction.
4730 *
4731 * @param array $params
cf28d075 4732 * @param int $default
bf2cf926 4733 *
4734 * @return int
4735 */
cf28d075 4736 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
bf2cf926 4737
4738 if (!empty($params['financial_account_id'])) {
4739 return $params['financial_account_id'];
4740 }
c16c6ad8 4741
bf2cf926 4742 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['contribution_status_id'], 'name');
66d5d6f4 4743 $preferredAccountsRelationships = [
bf2cf926 4744 'Refunded' => 'Credit/Contra Revenue Account is',
4745 'Chargeback' => 'Chargeback Account is',
66d5d6f4 4746 ];
c16c6ad8 4747
bf2cf926 4748 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4749 $financialTypeID = !empty($params['financial_type_id']) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
4750 return CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
4751 $financialTypeID,
4752 $preferredAccountsRelationships[$contributionStatus]
4753 );
4754 }
c16c6ad8 4755
cf28d075 4756 return $default;
bf2cf926 4757 }
4758
f99a6f98 4759 /**
4760 * ContributionPage values were being imposed onto values.
4761 *
4762 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4763 * REALLY didn't want superimposed. The rest are left there in their overkill out
4764 * of cautiousness.
4765 *
4766 * The rationale for making this explicit is that it was a case of carefully set values being
4767 * seemingly randonly overwritten without much care. In general I think array randomly setting
4768 * variables en mass is risky.
4769 *
4770 * @param array $values
4771 *
4772 * @return array
4773 */
4774 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
66d5d6f4 4775 $contributionPageValues = [];
f99a6f98 4776 CRM_Contribute_BAO_ContributionPage::setValues(
4777 $this->contribution_page_id,
4778 $contributionPageValues
4779 );
66d5d6f4 4780 $valuesToCopy = [
f99a6f98 4781 // These are the values that I believe to be useful.
e4dcb541 4782 'id',
f99a6f98 4783 'title',
f99a6f98 4784 'pay_later_receipt',
4785 'pay_later_text',
4786 'receipt_from_email',
4787 'receipt_from_name',
4788 'receipt_text',
ee1dffa7 4789 'custom_pre_id',
f99a6f98 4790 'custom_post_id',
4791 'honoree_profile_id',
4792 'onbehalf_profile_id',
ee1dffa7 4793 'honor_block_is_active',
f99a6f98 4794 // Kinda might be - but would be on the contribution...
4795 'campaign_id',
4796 'currency',
4797 // Included for 'fear of regression' but can't justify any use for these....
4798 'intro_text',
4799 'payment_processor',
4800 'financial_type_id',
4801 'amount_block_is_active',
4802 'bcc_receipt',
4803 'cc_receipt',
4804 'created_date',
4805 'created_id',
4806 'default_amount_id',
4807 'end_date',
4808 'footer_text',
4809 'goal_amount',
4810 'initial_amount_help_text',
4811 'initial_amount_label',
4812 'intro_text',
4813 'is_allow_other_amount',
4814 'is_billing_required',
4815 'is_confirm_enabled',
4816 'is_credit_card_only',
4817 'is_monetary',
4818 'is_partial_payment',
4819 'is_recur_installments',
4820 'is_recur_interval',
4821 'is_share',
4822 'max_amount',
4823 'min_amount',
4824 'min_initial_amount',
4825 'recur_frequency_unit',
4826 'start_date',
4827 'thankyou_footer',
4828 'thankyou_text',
4829 'thankyou_title',
4830
66d5d6f4 4831 ];
f99a6f98 4832 foreach ($valuesToCopy as $valueToCopy) {
4833 if (isset($contributionPageValues[$valueToCopy])) {
f56ef33f
SL
4834 if ($valueToCopy === 'title') {
4835 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils::getContributionPageTitle($this->contribution_page_id);
4836 }
4837 else {
4838 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4839 }
f99a6f98 4840 }
4841 }
4842 return $values;
4843 }
4844
ce7fc91a
PN
4845 /**
4846 * Get values of CiviContribute Settings
4847 * and check if its enabled or not.
756661dc
PN
4848 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4849 * in serialized form. Usually this should be stored as flat settings for each form fields
4850 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4851 * settings we will live with an inconsistency because it's too hard to change for now.
4852 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
ce7fc91a
PN
4853 *
4854 *
4855 * @param string $name
5d288dc4 4856 *
ce7fc91a
PN
4857 * @return string
4858 *
4859 */
5d288dc4 4860 public static function checkContributeSettings($name) {
ce7fc91a 4861 $contributeSettings = Civi::settings()->get('contribution_invoice_settings');
914d3734 4862 return $contributeSettings[$name] ?? NULL;
ce7fc91a
PN
4863 }
4864
2912ed09 4865 /**
4866 * Get the contribution as it is in the database before being updated.
4867 *
4868 * @param int $contributionID
4869 *
81716ddb 4870 * @return \CRM_Contribute_BAO_Contribution|null
2912ed09 4871 */
4872 private static function getOriginalContribution($contributionID) {
2b058da6 4873 return self::getValues(['id' => $contributionID]);
2912ed09 4874 }
4875
8a477059 4876 /**
4877 * Get the amount for the financial item row.
4878 *
4879 * Helper function to start to break down recordFinancialTransactions for readability.
4880 *
4881 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
4882 *
4883 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
4884 * for historical reasons. Going forwards we can hope to add tests & improve readibility
4885 * of that function
4886 *
8a477059 4887 * @param array $params
4888 * Params as passed to contribution.create
4889 *
4890 * @param string $context
4891 * changeFinancialType| changedAmount
4892 * @param array $lineItemDetails
4893 * Line items.
4894 * @param bool $isARefund
4895 * Is this a refund / negative transaction.
1330f57a 4896 * @param int $previousLineItemTotal
8a477059 4897 *
4898 * @return float
66d5d6f4 4899 * @todo move recordFinancialAccounts & helper functions to their own class?
4900 *
8a477059 4901 */
273056c5
PN
4902 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
4903 if ($context == 'changedAmount') {
4904 $lineTotal = $lineItemDetails['line_total'];
4905 if ($lineTotal != $previousLineItemTotal) {
4906 $lineTotal -= $previousLineItemTotal;
4907 }
4908 return $lineTotal;
4909 }
8205a69e 4910 elseif ($context == 'changeFinancialType') {
273056c5 4911 return -$lineItemDetails['line_total'];
8a477059 4912 }
4913 elseif ($context == 'changedStatus') {
4914 $cancelledTaxAmount = 0;
4915 if ($isARefund) {
13e8b7d5 4916 $cancelledTaxAmount = CRM_Utils_Array::value('tax_amount', $lineItemDetails, '0.00');
8a477059 4917 }
13e8b7d5 4918 return self::getMultiplier($params['contribution']->contribution_status_id, $context) * ((float) $lineItemDetails['line_total'] + (float) $cancelledTaxAmount);
8a477059 4919 }
4920 elseif ($context === NULL) {
4921 // erm, yes because? but, hey, it's tested.
273056c5 4922 return $lineItemDetails['line_total'];
8a477059 4923 }
4924 elseif (empty($lineItemDetails['line_total'])) {
4925 // follow legacy code path
4926 Civi::log()
66d5d6f4 4927 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
8a477059 4928 return $params['total_amount'];
4929 }
4930 else {
13e8b7d5 4931 return self::getMultiplier($params['contribution']->contribution_status_id, $context) * ((float) $lineItemDetails['line_total']);
8a477059 4932 }
4933 }
4934
4935 /**
4936 * Get the multiplier for adjusting rows.
4937 *
4938 * If we are dealing with a refund or cancellation then it will be a negative
4939 * amount to reflect the negative transaction.
4940 *
4941 * If we are changing Financial Type it will be a negative amount to
4942 * adjust down the old type.
4943 *
4944 * @param int $contribution_status_id
4945 * @param string $context
4946 *
4947 * @return int
4948 */
4949 protected static function getMultiplier($contribution_status_id, $context) {
4950 if ($context == 'changeFinancialType' || self::isContributionStatusNegative($contribution_status_id)) {
4951 return -1;
4952 }
4953 return 1;
4954 }
4955
5ca657dd 4956 /**
4957 * Does this transaction reflect a payment instrument change.
4958 *
4959 * @param array $params
4960 * @param array $pendingStatuses
4961 *
4962 * @return bool
4963 */
4964 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
4965 $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id);
4966
4967 if (array_key_exists('payment_instrument_id', $params)) {
4968 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
27fdea23 4969 !CRM_Utils_System::isNull($params['payment_instrument_id'])
5ca657dd 4970 ) {
4971 //check if status is changed from Pending to Completed
4972 // do not update payment instrument changes for Pending to Completed
4973 if (!($contributionStatus == 'Completed' &&
4974 in_array($params['prevContribution']->contribution_status_id, $pendingStatuses))
4975 ) {
4976 return TRUE;
4977 }
4978 }
27fdea23 4979 elseif ((!CRM_Utils_System::isNull($params['payment_instrument_id']) &&
5ca657dd 4980 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
17ea57cf 4981 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5ca657dd 4982 ) {
4983 return TRUE;
4984 }
4985 elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
4986 $params['contribution']->check_number != $params['prevContribution']->check_number
4987 ) {
4988 // another special case when check number is changed, create new financial records
4989 // create financial trxn with negative amount
4990 return TRUE;
4991 }
4992 }
4993 return FALSE;
4994 }
4995
aec171f3 4996 /**
4997 * Update the memberships associated with a contribution if it has been completed.
4998 *
4999 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5000 * load them in this function. Code clean up would compensate for any minor performance implication.
5001 *
eed14abb 5002 * @param int $contributionID
aec171f3 5003 * @param string $changeDate
aec171f3 5004 *
185a4fe8
MW
5005 * @throws \CRM_Core_Exception
5006 * @throws \CiviCRM_API3_Exception
aec171f3 5007 */
eed14abb 5008 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
5009 $memberships = self::getRelatedMemberships($contributionID);
5ed12039 5010 foreach ($memberships as $membership) {
66d5d6f4 5011 $membershipParams = [
8d315df3 5012 'id' => $membership['id'],
5013 'contact_id' => $membership['contact_id'],
5014 'is_test' => $membership['is_test'],
5015 'membership_type_id' => $membership['membership_type_id'],
5016 'membership_activity_status' => 'Completed',
66d5d6f4 5017 ];
aec171f3 5018
8d315df3 5019 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'],
5020 $membershipParams['membership_type_id'],
5021 $membershipParams['is_test'],
5022 $membershipParams['id']
5023 );
aec171f3 5024
8d315df3 5025 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5026 // this picks up membership type changes during renewals
5027 // @todo this is almost certainly an obsolete sql call, the pre-change
5028 // membership is accessible via $this->_relatedObjects
5029 $sql = "
aec171f3 5030SELECT membership_type_id
5031FROM civicrm_membership_log
5032WHERE membership_id={$membershipParams['id']}
5033ORDER BY id DESC
5034LIMIT 1;";
8d315df3 5035 $dao = CRM_Core_DAO::executeQuery($sql);
5036 if ($dao->fetch()) {
5037 if (!empty($dao->membership_type_id)) {
5038 $membershipParams['membership_type_id'] = $dao->membership_type_id;
185a4fe8 5039 }
8d315df3 5040 }
7365dd7f
AP
5041 if (empty($membership['end_date']) || (int) $membership['status_id'] !== CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
5042 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
5043 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
5044 // 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 5045 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
7365dd7f 5046 // @todo once apiv4 ships with core switch to that & find sanity.
eed14abb 5047 $membershipParams['num_terms'] = self::getNumTermsByContributionAndMembershipType(
7365dd7f 5048 $membershipParams['membership_type_id'],
eed14abb 5049 $contributionID
7365dd7f
AP
5050 );
5051 }
8d315df3 5052 // @todo remove all this stuff in favour of letting the api call further down handle in
5053 // (it is a duplication of what the api does).
66d5d6f4 5054 $dates = array_fill_keys([
8d315df3 5055 'join_date',
5056 'start_date',
5057 'end_date',
66d5d6f4 5058 ], NULL);
8d315df3 5059 if ($currentMembership) {
5060 /*
5061 * Fixed FOR CRM-4433
5062 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5063 * when Contribution mode is notify and membership is for renewal )
5064 */
4e6cd940 5065 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
5066 // Be afraid.
8d315df3 5067 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5068
5069 // @todo - we should pass membership_type_id instead of null here but not
5070 // adding as not sure of testing
5071 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'],
5072 $changeDate, NULL, $membershipParams['num_terms']
185a4fe8 5073 );
8d315df3 5074 $dates['join_date'] = $currentMembership['join_date'];
5075 }
185a4fe8 5076
8d315df3 5077 //get the status for membership.
5078 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
5079 $dates['end_date'],
5080 $dates['join_date'],
2cb64970 5081 'now',
8d315df3 5082 TRUE,
5083 $membershipParams['membership_type_id'],
5084 $membershipParams
5085 );
aec171f3 5086
8d315df3 5087 unset($dates['end_date']);
5088 $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
5089 //we might be renewing membership,
5090 //so make status override false.
5091 $membershipParams['is_override'] = FALSE;
5092 $membershipParams['status_override_end_date'] = 'null';
8d315df3 5093 civicrm_api3('Membership', 'create', $membershipParams);
aec171f3 5094 }
5095 }
5096
c0406a91 5097 /**
5098 * Get payment links as they relate to a contribution.
5099 *
5100 * If a payment can be made then include a payment link & if a refund is appropriate
5101 * then a refund link.
5102 *
5103 * @param int $id
5104 * @param float $balance
5105 * @param string $contributionStatus
5106 *
1330f57a
SL
5107 * @return array
5108 * $actionLinks Links array containing:
5109 * -url
5110 * -title
c0406a91 5111 */
5112 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5113 if ($contributionStatus === 'Failed' || !CRM_Core_Permission::check('edit contributions')) {
5114 // In general the balance is the best way to determine if a payment can be added or not,
5115 // but not for Failed contributions, where we don't accept additional payments at the moment.
5116 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5117 // do accept more payments agains them.
66d5d6f4 5118 return [];
c0406a91 5119 }
66d5d6f4 5120 $actionLinks = [];
4356c7dc 5121 $actionLinks[] = [
5122 'url' => CRM_Utils_System::url('civicrm/payment', [
5123 'action' => 'add',
5124 'reset' => 1,
5125 'id' => $id,
5126 'is_refund' => 0,
5127 ]),
5128 'title' => ts('Record Payment'),
5129 ];
5130
4cbe461a 5131 if (CRM_Core_Config::isEnabledBackOfficeCreditCardPayments()) {
66d5d6f4 5132 $actionLinks[] = [
5133 'url' => CRM_Utils_System::url('civicrm/payment', [
c0406a91 5134 'action' => 'add',
5135 'reset' => 1,
4cbe461a 5136 'is_refund' => 0,
c0406a91 5137 'id' => $id,
4cbe461a 5138 'mode' => 'live',
66d5d6f4 5139 ]),
4cbe461a 5140 'title' => ts('Submit Credit Card payment'),
66d5d6f4 5141 ];
c0406a91 5142 }
4cbe461a 5143 $actionLinks[] = [
5144 'url' => CRM_Utils_System::url('civicrm/payment', [
5145 'action' => 'add',
5146 'reset' => 1,
5147 'id' => $id,
5148 'is_refund' => 1,
5149 ]),
5150 'title' => ts('Record Refund'),
5151 ];
c0406a91 5152 return $actionLinks;
5153 }
5154
6b60d32c 5155 /**
5156 * Get a query to determine the amount donated by the contact/s in the current financial year.
5157 *
5158 * @param array $contactIDs
5159 *
5160 * @return string
5161 */
5162 public static function getAnnualQuery($contactIDs) {
5163 $contactIDs = implode(',', $contactIDs);
5164 $config = CRM_Core_Config::singleton();
5165 $currentMonth = date('m');
5166 $currentDay = date('d');
5167 if (
5168 (int) $config->fiscalYearStart['M'] > $currentMonth ||
5169 (
5170 (int) $config->fiscalYearStart['M'] == $currentMonth &&
5171 (int) $config->fiscalYearStart['d'] > $currentDay
5172 )
5173 ) {
5174 $year = date('Y') - 1;
5175 }
5176 else {
5177 $year = date('Y');
5178 }
5179 $nextYear = $year + 1;
5180
5181 if ($config->fiscalYearStart) {
5182 $newFiscalYearStart = $config->fiscalYearStart;
5183 if ($newFiscalYearStart['M'] < 10) {
5184 // This is just a clumsy way of adding padding.
5185 // @todo next round look for a nicer way.
5186 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5187 }
5188 if ($newFiscalYearStart['d'] < 10) {
5189 // This is just a clumsy way of adding padding.
5190 // @todo next round look for a nicer way.
5191 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5192 }
5193 $config->fiscalYearStart = $newFiscalYearStart;
5194 $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d'];
5195 }
5196 else {
5197 // First of January.
5198 $monthDay = '0101';
5199 }
5200 $startDate = "$year$monthDay";
5201 $endDate = "$nextYear$monthDay";
53666099 5202
6b60d32c 5203 $whereClauses = [
c77f8667 5204 'contact_id' => 'IN (' . $contactIDs . ')',
c77f8667 5205 'is_test' => ' = 0',
5206 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
6b60d32c 5207 ];
0c54553f 5208 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
c77f8667 5209 CRM_Financial_BAO_FinancialType::addACLClausesToWhereClauses($whereClauses);
5210
5211 $clauses = [];
5212 foreach ($whereClauses as $key => $clause) {
1330f57a 5213 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
c77f8667 5214 }
5215 $whereClauseString = implode(' AND ', $clauses);
5216
0c54553f 5217 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5218 // this group by + having on contribution_status_id improves performance
6b60d32c 5219 $query = "
5220 SELECT COUNT(*) as count,
5221 SUM(total_amount) as amount,
5222 AVG(total_amount) as average,
5223 currency
5224 FROM civicrm_contribution b
c77f8667 5225 WHERE " . $whereClauseString . "
0c54553f 5226 GROUP BY currency, contribution_status_id
5227 HAVING $havingClause
6b60d32c 5228 ";
5229 return $query;
5230 }
5231
94183dd6
SL
5232 /**
5233 * Assign Test Value.
5234 *
5235 * @param string $fieldName
5236 * @param array $fieldDef
5237 * @param int $counter
5238 */
5239 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5240 if ($fieldName == 'tax_amount') {
5241 $this->{$fieldName} = "0.00";
5242 }
5243 elseif ($fieldName == 'net_amount') {
5244 $this->{$fieldName} = "2.00";
5245 }
5246 elseif ($fieldName == 'total_amount') {
5247 $this->{$fieldName} = "3.00";
5248 }
5249 elseif ($fieldName == 'fee_amount') {
5250 $this->{$fieldName} = "1.00";
5251 }
5252 else {
5253 parent::assignTestValues($fieldName, $fieldDef, $counter);
5254 }
5255 }
5256
623712fb
PN
5257 /**
5258 * Check if contribution has participant/membership payment.
5259 *
5260 * @param int $contributionId
5261 * Contribution ID
5262 *
5263 * @return bool
5264 */
5265 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5266 // get line item for contribution
77dbdcbc 5267 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId);
623712fb
PN
5268 // check if line item is for membership or participant
5269 foreach ($lineItems as $items) {
5270 if ($items['entity_table'] == 'civicrm_participant') {
6f148218 5271 $flag = FALSE;
623712fb
PN
5272 break;
5273 }
5274 elseif ($items['entity_table'] == 'civicrm_membership') {
6f148218 5275 $flag = FALSE;
623712fb
PN
5276 }
5277 else {
6f148218 5278 $flag = TRUE;
623712fb
PN
5279 break;
5280 }
5281 }
5282 return $flag;
5283 }
5284
14b1ab0c
PN
5285 /**
5286 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5287 *
9c472292
PN
5288 * @param array $trxnParams
5289 * Financial trxn params
81716ddb 5290 * @param array $contributionParams
9c472292 5291 * Contribution Params
a9c48769 5292 *
81716ddb 5293 * @return null
14b1ab0c 5294 */
9c472292 5295 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
a17bec97 5296 if (!Civi::settings()->get('always_post_to_accounts_receivable')) {
14b1ab0c
PN
5297 return NULL;
5298 }
9c472292 5299 $statusId = $contributionParams['contribution']->contribution_status_id;
14b1ab0c 5300 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
a9c48769 5301 $contributionStatus = empty($statusId) ? NULL : $contributionStatuses[$statusId];
352cae98 5302 $previousContributionStatus = empty($contributionParams['prevContribution']) ? NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id];
14b1ab0c 5303 // Return if contribution status is not completed.
352cae98 5304 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
66d5d6f4 5305 || (!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5306 && $contributionParams['prevContribution']->is_pay_later == 0
5307 )))
352cae98 5308 ) {
14b1ab0c
PN
5309 return NULL;
5310 }
352cae98 5311
9c472292 5312 $params = $trxnParams;
e71c1326 5313 $financialTypeID = !empty($contributionParams['financial_type_id']) ? $contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id;
876b8ab0 5314 $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
9c472292
PN
5315 $params['to_financial_account_id'] = $arAccountId;
5316 $params['status_id'] = array_search('Pending', $contributionStatuses);
5317 $params['is_payment'] = FALSE;
5318 $trxn = CRM_Core_BAO_FinancialTrxn::create($params);
5319 self::$_trxnIDs[] = $trxn->id;
5320 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
14b1ab0c
PN
5321 }
5322
d9553c2e
PN
5323 /**
5324 * Calculate financial item amount when contribution is updated.
5325 *
5326 * @param array $params
5327 * contribution params
5328 * @param array $amountParams
5329 *
5330 * @param string $context
5331 *
5332 * @return float
5333 */
5334 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5335 if (!empty($params['is_quick_config'])) {
5336 $amount = $amountParams['item_amount'];
5337 if (!$amount) {
5338 $amount = $params['total_amount'];
5339 if ($context === NULL) {
5340 $amount -= CRM_Utils_Array::value('tax_amount', $params, 0);
5341 }
5342 }
5343 }
5344 else {
5345 $amount = $amountParams['line_total'];
5346 if ($context == 'changedAmount') {
5347 $amount -= $amountParams['previous_line_total'];
5348 }
5349 $amount *= $amountParams['diff'];
5350 }
5351 return $amount;
5352 }
5353
cdc6ce4d
PN
5354 /**
5355 * Retrieve Sales Tax Financial Accounts.
5356 *
5357 *
5358 * @return array
5359 *
5360 */
5361 public static function getSalesTaxFinancialAccounts() {
5362 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5363 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5364 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5365 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
66d5d6f4 5366 $queryParams = [1 => [$accountRel, 'Integer']];
cdc6ce4d 5367 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
66d5d6f4 5368 $financialAccount = [];
cdc6ce4d
PN
5369 while ($dao->fetch()) {
5370 $financialAccount[$dao->id] = $dao->id;
5371 }
5372 return $financialAccount;
5373 }
5374
53f969b9
PN
5375 /**
5376 * Create tax entry in civicrm_entity_financial_trxn table.
5377 *
5378 * @param array $entityParams
5379 *
5380 * @param array $eftParams
5381 *
66d5d6f4 5382 * @throws \CiviCRM_API3_Exception
53f969b9
PN
5383 */
5384 public static function createProportionalEntry($entityParams, $eftParams) {
ea8f914c
PN
5385 $paid = 0;
5386 if ($entityParams['contribution_total_amount'] != 0) {
5387 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5388 }
eb0af899 5389 // Record Entity Financial Trxn; CRM-20145
70fe7232 5390 $eftParams['amount'] = $paid;
53f969b9
PN
5391 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5392 }
5393
5394 /**
5395 * Create array of last financial item id's.
5396 *
bc854509 5397 * @param int $contributionId
53f969b9 5398 *
bc854509 5399 * @return array
53f969b9
PN
5400 */
5401 public static function getLastFinancialItemIds($contributionId) {
5402 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5403 FROM civicrm_financial_item fi
5404 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5405 WHERE li.contribution_id = %1";
66d5d6f4 5406 $dao = CRM_Core_DAO::executeQuery($sql, [
5407 1 => [
5408 $contributionId,
5409 'Integer',
5410 ],
5411 ]);
5412 $ftIds = $taxItems = [];
53f969b9
PN
5413 $salesTaxFinancialAccount = self::getSalesTaxFinancialAccounts();
5414 while ($dao->fetch()) {
5415 /* if sales tax item*/
5416 if (in_array($dao->financial_account_id, $salesTaxFinancialAccount)) {
66d5d6f4 5417 $taxItems[$dao->price_field_value_id] = [
53f969b9
PN
5418 'financial_item_id' => $dao->id,
5419 'amount' => $dao->tax_amount,
66d5d6f4 5420 ];
53f969b9
PN
5421 }
5422 else {
5423 $ftIds[$dao->price_field_value_id] = $dao->id;
5424 }
5425 }
66d5d6f4 5426 return [$ftIds, $taxItems];
53f969b9
PN
5427 }
5428
5429 /**
5430 * Create proportional entries in civicrm_entity_financial_trxn.
5431 *
5432 * @param array $entityParams
5433 *
5434 * @param array $lineItems
5435 *
5436 * @param array $ftIds
5437 *
5438 * @param array $taxItems
5439 *
66d5d6f4 5440 * @throws \CiviCRM_API3_Exception
53f969b9
PN
5441 */
5442 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
66d5d6f4 5443 $eftParams = [
53f969b9
PN
5444 'entity_table' => 'civicrm_financial_item',
5445 'financial_trxn_id' => $entityParams['trxn_id'],
66d5d6f4 5446 ];
53f969b9
PN
5447 foreach ($lineItems as $key => $value) {
5448 if ($value['qty'] == 0) {
5449 continue;
5450 }
5451 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5452 $entityParams['line_item_amount'] = $value['line_total'];
5453 self::createProportionalEntry($entityParams, $eftParams);
5454 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5455 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5456 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5457 self::createProportionalEntry($entityParams, $eftParams);
5458 }
5459 }
5460 }
5461
55df1211
AS
5462 /**
5463 * Load entities related to the contribution into $this->_relatedObjects.
5464 *
5465 * @param array $ids
5466 *
5467 * @throws \CRM_Core_Exception
5468 */
5469 protected function loadRelatedEntitiesByID($ids) {
66d5d6f4 5470 $entities = [
55df1211
AS
5471 'contact' => 'CRM_Contact_BAO_Contact',
5472 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5473 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5474 'financialType' => 'CRM_Financial_BAO_FinancialType',
5475 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
66d5d6f4 5476 ];
55df1211
AS
5477 foreach ($entities as $entity => $bao) {
5478 if (!empty($ids[$entity])) {
5479 $this->_relatedObjects[$entity] = new $bao();
5480 $this->_relatedObjects[$entity]->id = $ids[$entity];
5481 if (!$this->_relatedObjects[$entity]->find(TRUE)) {
5482 throw new CRM_Core_Exception($entity . ' could not be loaded');
5483 }
5484 }
5485 }
5486 }
5487
7e2ec997
E
5488 /**
5489 * Function to replace contribution tokens.
5490 *
5491 * @param array $contributionIds
5492 *
5493 * @param string $subject
5494 *
5495 * @param array $subjectToken
5496 *
5497 * @param string $text
5498 *
5499 * @param string $html
5500 *
5501 * @param array $messageToken
5502 *
5503 * @param bool $escapeSmarty
5504 *
5505 * @return array
66d5d6f4 5506 * @throws \CiviCRM_API3_Exception
7e2ec997
E
5507 */
5508 public static function replaceContributionTokens(
5509 $contributionIds,
5510 $subject,
5511 $subjectToken,
5512 $text,
5513 $html,
5514 $messageToken,
5515 $escapeSmarty
5516 ) {
5517 if (empty($contributionIds)) {
66d5d6f4 5518 return [];
7e2ec997 5519 }
66d5d6f4 5520 $contributionDetails = [];
7e2ec997 5521 foreach ($contributionIds as $id) {
fe7794b7 5522 $result = self::getContributionTokenValues($id, $messageToken);
7e2ec997
E
5523 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5524 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5525 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5526 }
5527 return $contributionDetails;
5528 }
5529
fe7794b7
JG
5530 /**
5531 * Get the contribution fields for $id and display labels where
5532 * appropriate (if the token is present).
5533 *
5534 * @param int $id
5535 * @param array $messageToken
5536 * @return array
5537 */
5538 public static function getContributionTokenValues($id, $messageToken) {
5539 if (empty($id)) {
5540 return [];
5541 }
5542 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5543 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5544 if (!empty($messageToken)) {
875e076b
JG
5545 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5546 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5547 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField::displayValue($result['values'][$id][$fieldName], $fieldName);
5548 }
5549 }
7e2ec997 5550 }
fe7794b7 5551 return $result;
7e2ec997
E
5552 }
5553
12a8f9d7 5554 /**
b07b172b 5555 * Get invoice_number for contribution.
12a8f9d7 5556 *
802c1c41 5557 * @param int $contributionID
12a8f9d7
PN
5558 *
5559 * @return string
5560 */
b07b172b 5561 public static function getInvoiceNumber($contributionID) {
5d288dc4 5562 if ($invoicePrefix = self::checkContributeSettings('invoice_prefix')) {
b07b172b 5563 return $invoicePrefix . $contributionID;
12a8f9d7 5564 }
802c1c41 5565
b07b172b 5566 return NULL;
12a8f9d7
PN
5567 }
5568
0a12bb75 5569 /**
5570 * Load the values needed for the event message.
5571 *
5572 * @param int $eventID
5573 * @param int $participantID
5574 * @param int|null $contributionID
5575 *
5576 * @return array
5577 * @throws \CRM_Core_Exception
5578 */
5579 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5580
5581 $eventParams = [
5582 'id' => $eventID,
5583 ];
ed7e2e99 5584 $values = ['event' => []];
0a12bb75 5585
5586 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
5587 // add custom fields for event
5588 $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Event', NULL, $eventID);
5589
5590 $eventCustomGroup = [];
5591 foreach ($eventGroupTree as $key => $group) {
5592 if ($key === 'info') {
5593 continue;
5594 }
5595
5596 foreach ($group['fields'] as $k => $customField) {
5597 $groupLabel = $group['title'];
5598 if (!empty($customField['customValue'])) {
5599 foreach ($customField['customValue'] as $customFieldValues) {
9c1bc317 5600 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ?? NULL;
0a12bb75 5601 }
5602 }
5603 }
5604 }
5605 $values['event']['customGroup'] = $eventCustomGroup;
5606
5607 //get participant details
5608 $participantParams = [
5609 'id' => $participantID,
5610 ];
5611
5612 $values['participant'] = [];
5613
5614 CRM_Event_BAO_Participant::getValues($participantParams, $values['participant'], $participantIds);
5615 // add custom fields for event
5616 $participantGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID);
5617 $participantCustomGroup = [];
5618 foreach ($participantGroupTree as $key => $group) {
5619 if ($key === 'info') {
5620 continue;
5621 }
5622
5623 foreach ($group['fields'] as $k => $customField) {
5624 $groupLabel = $group['title'];
5625 if (!empty($customField['customValue'])) {
5626 foreach ($customField['customValue'] as $customFieldValues) {
9c1bc317 5627 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ?? NULL;
0a12bb75 5628 }
5629 }
5630 }
5631 }
5632 $values['participant']['customGroup'] = $participantCustomGroup;
5633
5634 //get location details
5635 $locationParams = [
5636 'entity_id' => $eventID,
5637 'entity_table' => 'civicrm_event',
5638 ];
5639 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
5640
5641 $ufJoinParams = [
5642 'entity_table' => 'civicrm_event',
5643 'entity_id' => $eventID,
5644 'module' => 'CiviEvent',
5645 ];
5646
5647 list($custom_pre_id,
5648 $custom_post_ids
5649 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
5650
5651 $values['custom_pre_id'] = $custom_pre_id;
5652 $values['custom_post_id'] = $custom_post_ids;
5653
5654 // set lineItem for event contribution
5655 if ($contributionID) {
5656 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($contributionID);
5657 if (!empty($participantIds)) {
5658 foreach ($participantIds as $pIDs) {
5659 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
5660 if (!CRM_Utils_System::isNull($lineItem)) {
5661 $values['lineItem'][] = $lineItem;
5662 }
5663 }
5664 }
5665 }
5666 return $values;
5667 }
5668
5ce9cbe9 5669}