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