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