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