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