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