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