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