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