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