3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
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
;
24 * @copyright CiviCRM LLC https://civicrm.org/licensing
26 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
29 * Static field for all the contribution information that we can potentially import
33 public static $_importableFields = NULL;
36 * Static field for all the contribution information that we can potentially export
40 public static $_exportableFields = NULL;
43 * Static field to hold financial trxn id's.
47 public static $_trxnIDs = NULL;
50 * Field for all the objects related to this contribution.
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.
58 * However, it is no longer used by completeOrder.
60 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
64 public $_relatedObjects = [];
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
73 * "contribution"\"event"
75 public $_component = NULL;
78 * Possibly obsolete variable.
80 * If you use it please explain why it is set in the create function here.
84 public $trxn_result_code;
89 public function __construct() {
90 parent
::__construct();
94 * Takes an associative array and creates a contribution object.
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
100 * @param array $params
101 * (reference ) an assoc array of name/value pairs.
103 * @return \CRM_Contribute_BAO_Contribution
104 * @throws \CRM_Core_Exception
105 * @throws \CiviCRM_API3_Exception
107 public static function add(&$params) {
108 if (empty($params)) {
112 $contributionID = $params['id'] ??
NULL;
113 $action = $contributionID ?
'edit' : 'create';
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);
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);
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');
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',
141 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
144 && !empty($params['membership_id'])
145 && Civi
::settings()->get('deferred_revenue_enabled')
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));
152 self
::calculateMissingAmountParams($params, $contributionID);
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';
161 $setPrevContribution = TRUE;
162 if ($contributionID && $setPrevContribution) {
163 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
165 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
167 if ($contributionID && !empty($params['revenue_recognition_date'])
168 && !($previousContributionStatus === 'Pending')
169 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
171 unset($params['revenue_recognition_date']);
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);
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);
189 if (($params['tax_amount'] ??
'') === 'null') {
190 CRM_Core_Error
::deprecatedWarning('tax_amount should be not passed in (preferable) or a float');
192 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
193 isset($params['financial_type_id']))) {
194 $params['tax_amount'] = $taxAmount;
196 if (isset($params['tax_amount']) && empty($params['skipLineItem'])
197 && !CRM_Utils_Money
::equals($params['tax_amount'], $taxAmount, ($params['currency'] ?? Civi
::settings()->get('defaultCurrency')))
199 CRM_Core_Error
::deprecatedWarning('passing in incorrect tax amounts is deprecated');
202 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
204 $contribution = new CRM_Contribute_BAO_Contribution();
205 $contribution->copyValues($params);
207 $contribution->id
= $contributionID;
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
;
216 $result = $contribution->save();
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;
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);
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
),
239 $params['receive_date'] ??
'now'
243 $params['contribution_id'] = $contribution->id
;
245 if (!empty($params['custom']) &&
246 is_array($params['custom'])
248 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
251 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
253 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
258 * Is this contribution updating an existing recurring contribution.
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).
263 * @param array $params
267 public static function isUpdateToRecurringContribution($params) {
268 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
271 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
274 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
277 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
278 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
285 * Get defaults for new entity.
289 public static function getDefaults() {
291 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
292 FALSE, FALSE, FALSE, 'AND is_default = 1')
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'),
300 * Fetch the object and store the values in the values array.
302 * @param array $params
303 * Input parameters to find object.
304 * @param array $values
305 * Output values of the object.
307 * The array that holds all the db ids.
309 * @return CRM_Contribute_BAO_Contribution|null
310 * The found object or null
312 public static function getValues($params, &$values = [], &$ids = []) {
313 if (empty($params)) {
316 $contribution = new CRM_Contribute_BAO_Contribution();
318 $contribution->copyValues($params);
320 if ($contribution->find(TRUE)) {
321 $ids['contribution'] = $contribution->id
;
323 CRM_Core_DAO
::storeValues($contribution, $values);
325 return $contribution;
327 // return by reference
333 * Get the values and resolve the most common mappings.
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.
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.
341 * @param array $params
342 * Input parameters to find object.
345 * Array of the found contribution.
346 * @throws CRM_Core_Exception
348 public static function getValuesWithMappings($params) {
350 $contribution = self
::getValues($params, $values, $ids);
351 if (is_null($contribution)) {
352 throw new CRM_Core_Exception('No contribution found');
354 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
359 * Calculate net_amount & fee_amount if they are not set.
361 * Net amount should be total - fee.
362 * This should only be called for new contributions.
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.
369 * @throws \CiviCRM_API3_Exception
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'];
377 $params['fee_amount'] = 0;
380 if (!isset($params['net_amount'])) {
381 if (!$contributionID) {
382 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
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'],
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;
402 * @param $billingLocationTypeID
406 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
407 $hasBillingField = FALSE;
416 //build address array
418 $addressParams['location_type_id'] = $billingLocationTypeID;
419 $addressParams['is_billing'] = 1;
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}";
426 foreach ($billingFields as $value) {
427 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ??
NULL;
428 if (!empty($addressParams[$value])) {
429 $hasBillingField = TRUE;
432 return [$hasBillingField, $addressParams];
436 * Get address params ready to be passed to the payment processor.
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.
441 * @param array $params
442 * @param int $billingLocationTypeID
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];
453 return [$hasBillingField, $addressParams];
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
462 * @param int $membershipTypeID
464 * @param int $contributionID
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']]
475 // default of 1 is precautionary
476 return empty($numTerms) ?
1 : $numTerms;
480 * Takes an associative array and creates a contribution object.
482 * @param array $params
483 * (reference ) an assoc array of name/value pairs.
485 * @return CRM_Contribute_BAO_Contribution
487 * @throws \API_Exception
488 * @throws \CRM_Core_Exception
489 * @throws \CiviCRM_API3_Exception
491 public static function create(&$params) {
493 $transaction = new CRM_Core_Transaction();
496 $contribution = self
::add($params);
498 catch (CRM_Core_Exception
$e) {
499 $transaction->rollback();
503 $params['contribution_id'] = $contribution->id
;
504 $session = CRM_Core_Session
::singleton();
506 if (!empty($params['note'])) {
508 'entity_table' => 'civicrm_contribution',
509 'note' => $params['note'],
510 'entity_id' => $contribution->id
,
511 'contact_id' => $session->get('userID'),
513 if (!$noteParams['contact_id']) {
514 $noteParams['contact_id'] = $params['contact_id'];
516 CRM_Core_BAO_Note
::add($noteParams);
519 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
521 if (!empty($params['id']) && !empty($params['contribution_status_id'])
523 self
::disconnectPledgePaymentsIfCancelled((int) $params['id'], CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution_status_id']));
525 $transaction->commit();
527 if (empty($contribution->contact_id
)) {
528 $contribution->find(TRUE);
531 $isCompleted = ('Completed' === CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
));
532 if (!empty($params['on_behalf'])
535 $existingActivity = Activity
::get(FALSE)->setWhere([
536 ['source_record_id', '=', $contribution->id
],
537 ['activity_type_id:name', '=', 'Contribution'],
538 ])->execute()->first();
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,
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
];
556 [$sourceContactId, $targetContactId] = self
::getActivitySourceAndTarget($activityParams['id']);
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
;
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
];
569 Activity
::save(FALSE)->addRecord($activityParams)->execute();
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"
577 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
584 $retrieveRequired = 0;
585 foreach ($titleFields as $titleField) {
586 if (!isset($contribution->$titleField)) {
587 $retrieveRequired = 1;
591 if ($retrieveRequired == 1) {
592 $contribution->find(TRUE);
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 . ')';
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"
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"
610 // add the recently created Contribution
611 CRM_Utils_Recent
::add($title,
615 $contribution->contact_id
,
621 return $contribution;
625 * Get the values for pseudoconstants for name->value and reverse.
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).
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);
640 * Convert associative array names to values and vice-versa.
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
646 * @param array $defaults
647 * @param string $property
648 * @param array $lookup
649 * @param bool $reverse
653 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
654 $id = $property . '_id';
656 $src = $reverse ?
$property : $id;
657 $dst = $reverse ?
$id : $property;
659 if (!array_key_exists($src, $defaults)) {
663 $look = $reverse ?
array_flip($lookup) : $lookup;
665 if (is_array($look)) {
666 if (!array_key_exists($defaults[$src], $look)) {
670 $defaults[$dst] = $look[$defaults[$src]];
675 * Retrieve DB object based on input parameters.
677 * It also stores all the retrieved values in the default array.
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
685 * (reference) the array that holds all the db ids.
687 * @return CRM_Contribute_BAO_Contribution
689 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
690 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
691 return $contribution;
695 * Combine all the importable fields from the lower levels object.
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.
701 * @param string $contactType
702 * @param bool $status
705 * array of importable Fields
707 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
708 if (!self
::$_importableFields) {
709 if (!self
::$_importableFields) {
710 self
::$_importableFields = [];
714 $fields = ['' => ['title' => ts('- do not import -')]];
717 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
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);
726 // Using new Dedupe rule.
728 'contact_type' => $contactType,
729 'used' => 'Unsupervised',
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') {
739 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
744 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
745 $tmpContactField[trim($value)] = $contactFields[trim($value)];
747 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
750 $title = $tmpContactField[trim($value)]['title'];
752 $tmpContactField[trim($value)]['title'] = $title;
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;
767 return self
::$_importableFields;
771 * Combine all the exportable fields from the lower level objects.
773 * @param bool $checkPermission
776 * array of exportable Fields
778 public static function &exportableFields($checkPermission = TRUE) {
779 if (!self
::$_exportableFields) {
780 if (!self
::$_exportableFields) {
781 self
::$_exportableFields = [];
784 $fields = CRM_Contribute_DAO_Contribution
::export();
785 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
786 $fields = array_merge(
788 CRM_Contribute_DAO_Product
::export(),
789 CRM_Contribute_DAO_ContributionProduct
::export(),
790 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
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
,
802 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
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
,
813 $contributionNote = [
814 'contribution_note' => [
815 'title' => ts('Contribution Note'),
816 'name' => 'contribution_note',
817 'data_type' => CRM_Utils_Type
::T_TEXT
,
822 'contribution_batch' => [
823 'title' => ts('Batch Name'),
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
,
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
,
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
,
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
,
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
,
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
,
869 $fields = array_merge($fields, $contributionPage,
870 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
871 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
874 self
::$_exportableFields = $fields;
877 return self
::$_exportableFields;
881 * Record an activity when a payment is received.
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.
887 * @param int $contributionId
888 * @param int $participantId
889 * @param string $totalAmount
890 * @param string $currency
891 * @param string $trxnDate
893 * @throws \CRM_Core_Exception
894 * @throws \CiviCRM_API3_Exception
896 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
897 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
899 if ($participantId) {
900 $inputParams['id'] = $participantId;
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');
908 $entityObj = new CRM_Contribute_BAO_Contribution();
909 $entityObj->id
= $contributionId;
910 $entityObj->find(TRUE);
911 $title = ts('Contribution');
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);
918 * Get the value for the To Financial Account.
920 * @param $contribution
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');
929 if (!empty($params['payment_instrument_id'])) {
930 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
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);
940 * Get memberships related to the contribution.
942 * @param int $contributionID
945 * @throws \API_Exception
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'));
954 $doubleCheckParams = [
955 'return' => 'membership_id',
956 'contribution_id' => $contributionID,
958 if (!empty($membershipIDs)) {
959 $doubleCheckParams['membership_id'] = ['NOT IN' => $membershipIDs];
961 $membershipPayments = civicrm_api3('MembershipPayment', 'get', $doubleCheckParams)['values'];
962 if (!empty($membershipPayments)) {
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'];
969 if (empty($membershipIDs)) {
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'],
982 * Do any accounting updates required as a result of a contribution status change.
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....
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'.
992 * We should also look at the fact that the calling function - updateFinancialAccounts
993 * bunches together some disparate processes rather than having separate appropriate
996 * @param array $params
999 * Return indicates whether the updateFinancialAccounts function should continue.
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
);
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'))
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'];
1019 elseif (($previousContributionStatus === 'Pending'
1020 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus === 'In Progress'
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');
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'];
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;
1036 if (($previousContributionStatus === 'Pending'
1037 ||
$previousContributionStatus === 'In Progress')
1038 && ($currentContributionStatus === 'Completed')
1040 if (empty($params['line_item'])) {
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
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
);
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
;
1056 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1059 'entity_table' => 'civicrm_financial_item',
1061 foreach ($params['line_item'] as $fieldId => $fields) {
1062 foreach ($fields as $fieldValueId => $lineItemDetails) {
1063 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1065 1 => [$lineItemDetails['id'], 'Integer'],
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);
1084 * It is possible to override the membership id that is updated from the payment processor.
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
1089 * Read the comment block on repeattransaction for more information
1090 * about how things should work.
1092 * @param int $contributionID
1093 * @param array $input
1095 * @throws \CiviCRM_API3_Exception
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']]);
1105 * Update all financial items related to the line item tto have a status of paid.
1107 * @param int $lineItemID
1109 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1112 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1115 2 => [$lineItemID, 'Integer'],
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);
1122 * Create the financial items for the line.
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
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
);
1143 $financialAccount = CRM_Contribute_BAO_FinancialProcessor
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1145 $currency = $params['prevContribution']->currency
;
1146 if ($params['contribution']->currency
) {
1147 $currency = $params['contribution']->currency
;
1149 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
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'],
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
;
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);
1171 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1172 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
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']);
1180 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1188 * Does this contributtion status update represent a refund.
1190 * @param int $previousContributionStatusID
1191 * @param int $currentContributionStatusID
1195 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1196 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1199 return self
::isContributionStatusNegative($currentContributionStatusID);
1203 * Get transaction information about the contribution.
1205 * @param int $contributionId
1206 * @param int $financialTypeID
1210 protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) {
1212 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Expense Account is');
1214 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
1216 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
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
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
1229 WHERE con.id = %1 AND ft.is_payment = 1
1232 1 => [$contributionId, 'Integer'],
1233 2 => [$feeFinancialAccount, 'Integer'],
1235 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
1236 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
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}";
1247 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
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')) {
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'),
1263 $paymentEditLink = CRM_Core_Action
::formLink(
1265 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
1267 'id' => $resultDAO->id
,
1268 'contribution_id' => $contributionId,
1272 'Payment.edit.action',
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,
1290 if ($paidByName === 'Check') {
1291 $val['check_number'] = $resultDAO->check_number
;
1299 * Should an email receipt be sent for this contribution on completion.
1301 * @param array $input
1302 * @param int $contributionID
1303 * @param int $recurringContributionID
1306 * @throws \API_Exception
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'];
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'];
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();
1327 if (!empty($contributionPage)) {
1328 return (bool) $contributionPage['contribution_page_id.is_email_receipt'];
1330 // This would be the case for backoffice (where is_email_receipt is not passed in) or events, where Event::sendMail will filter
1336 * Disconnect pledge payments from cancelled or failed contributions.
1338 * If the contribution has been cancelled or has failed check to
1339 * see if it is linked to a pledge and unlink it.
1341 * @param int $pledgePaymentID
1342 * @param string $contributionStatus
1344 * @throws \API_Exception
1345 * @throws \Civi\API\Exception\UnauthorizedException
1347 protected static function disconnectPledgePaymentsIfCancelled(int $pledgePaymentID, $contributionStatus): void
{
1348 if (!in_array($contributionStatus, ['Failed', 'Cancelled'], TRUE)) {
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'])
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();
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;
1385 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1386 return $whereClauses;
1388 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1389 if (empty($types)) {
1390 $whereClauses['financial_type_id'] = 'IN (0)';
1393 $whereClauses['financial_type_id'] = [
1394 'IN (' . implode(',', array_keys($types)) . ')',
1397 return $whereClauses;
1401 * @param null $status
1402 * @param null $startDate
1403 * @param null $endDate
1405 * @return array|null
1407 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1411 $where[] = 'contribution_status_id = 1';
1415 $where[] = 'contribution_status_id = 3';
1420 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1423 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
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)) . ")";
1435 $where[] = "c.financial_type_id IN (0)";
1439 $whereCond = implode(' AND ', $where);
1442 SELECT sum( total_amount ) as total_amount,
1443 count( c.id ) as total_count,
1445 FROM civicrm_contribution c
1446 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1447 $financialTypeACLJoin
1449 AND ( is_test = 0 OR is_test IS NULL )
1450 AND contact.is_deleted = 0
1454 $dao = CRM_Core_DAO
::executeQuery($query);
1457 while ($dao->fetch()) {
1458 $count +
= $dao->total_count
;
1459 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1463 'amount' => implode(', ', $amount),
1471 * Delete the indirect records associated with this contribution first.
1475 * @return mixed|null
1476 * $results no of deleted Contribution on success, false otherwise
1478 public static function deleteContribution($id) {
1479 CRM_Utils_Hook
::pre('delete', 'Contribution', $id);
1481 $transaction = new CRM_Core_Transaction();
1484 //delete activity record
1486 'source_record_id' => $id,
1487 // activity type id for contribution
1488 'activity_type_id' => 6,
1491 CRM_Activity_BAO_Activity
::deleteActivity($params);
1493 //delete billing address if exists for this contribution.
1494 self
::deleteAddress($id);
1496 //update pledge and pledge payment, CRM-3961
1497 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
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);
1503 // cleanup line items.
1504 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1506 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1507 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1509 if ($participantId) {
1510 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1513 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1517 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1518 $noteId = key($note);
1520 CRM_Core_BAO_Note
::del($noteId, FALSE);
1523 $dao = new CRM_Contribute_DAO_Contribution();
1526 $results = $dao->delete();
1528 $transaction->commit();
1530 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1532 // delete the recently created Contribution
1533 $contributionRecent = [
1535 'type' => 'Contribution',
1537 CRM_Utils_Recent
::del($contributionRecent);
1543 * React to a financial transaction (payment) failure.
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.
1548 * @param int $contributionID
1549 * @param int $contactID
1550 * @param string $message
1552 * @throws \CiviCRM_API3_Exception
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,
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',
1571 * Check if there is a contribution with the same trxn_id or invoice_id.
1573 * @param array $input
1574 * An assoc array of name/value pairs.
1575 * @param array $duplicates
1576 * (reference) store ids of duplicate contribs.
1580 * true if duplicate, false otherwise
1582 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1584 $id = $input['id'] ??
NULL;
1586 $trxn_id = $input['trxn_id'] ??
NULL;
1587 $invoice_id = $input['invoice_id'] ??
NULL;
1593 $clause[] = 'trxn_id = %1';
1594 $input[1] = [$trxn_id, 'String'];
1598 $clause[] = "invoice_id = %2";
1599 $input[2] = [$invoice_id, 'String'];
1602 if (empty($clause)) {
1606 $clause = implode(' OR ', $clause);
1608 $clause = "( $clause ) AND id != %3";
1609 $input[3] = [$id, 'Integer'];
1612 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1613 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1615 while ($dao->fetch()) {
1616 $duplicates[] = $dao->id
;
1623 * Takes an associative array and creates a contribution_product object.
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
1629 * @param array $params
1630 * (reference) an assoc array of name/value pairs.
1632 * @return CRM_Contribute_DAO_ContributionProduct
1634 public static function addPremium(&$params) {
1635 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1636 $contributionProduct->copyValues($params);
1637 return $contributionProduct->save();
1641 * Get list of contribution fields for profile.
1642 * For now we only allow custom contribution fields to be in
1645 * @param bool $addExtraFields
1646 * True if special fields needs to be added.
1649 * the list of contribution fields
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'));
1657 if ($addExtraFields) {
1658 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1661 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1663 foreach ($contributionFields as $key => $var) {
1664 if ($key === 'contribution_contact_id') {
1667 elseif ($key === 'contribution_campaign_id') {
1668 $var['title'] = ts('Campaign');
1670 $fields[$key] = $var;
1673 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1678 * Add extra fields specific to contribution.
1680 public static function getSpecialContributionFields() {
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',
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',
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',
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',
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',
1714 return $extraFields;
1718 * @param int $pageID
1722 public static function getCurrentandGoalAmount($pageID) {
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
1729 AND c.cancel_date is null
1733 $config = CRM_Core_Config
::singleton();
1734 $params = [1 => [$pageID, 'Integer']];
1735 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1737 if ($dao->fetch()) {
1738 return [$dao->goal
, $dao->total
];
1741 return [NULL, NULL];
1746 * Get list of contributions which credit the passed in contact ID.
1748 * The returned array provides details about the original contribution & donor.
1750 * @param int $honorId
1751 * In Honor of Contact ID.
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.
1759 public static function getHonorContacts($honorId) {
1761 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1762 $honorDAO->contact_id
= $honorId;
1765 $type = CRM_Contribute_PseudoConstant
::financialType();
1767 while ($honorDAO->fetch()) {
1768 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1769 $contributionDAO->id
= $honorDAO->contribution_id
;
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');
1788 * Get the sort name of a contact for a particular contribution.
1791 * Id of the contribution.
1793 * @return null|string
1794 * sort name of the contact if found
1796 public static function sortName($id) {
1797 $id = CRM_Utils_Type
::escape($id, 'Integer');
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}
1805 return CRM_Core_DAO
::singleValueQuery($query);
1809 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1811 * @param int|array $contactIDs
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);
1822 $query = self
::getAnnualQuery($contactIDs);
1823 $dao = CRM_Core_DAO
::executeQuery($query);
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
);
1836 implode(', ', $amount),
1837 implode(', ', $average),
1844 * Check if there is a contribution with the params passed in.
1846 * Used for trxn_id,invoice_id and contribution_id
1848 * @param array $params
1849 * An assoc array of name/value pairs.
1852 * contribution id if success else NULL
1854 public static function checkDuplicateIds($params) {
1855 $dao = new CRM_Contribute_DAO_Contribution();
1859 foreach ($params as $k => $v) {
1861 $clause[] = "$k = '$v'";
1864 $clause = implode(' AND ', $clause);
1865 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1866 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1868 while ($dao->fetch()) {
1876 * Get the contribution details for component export.
1878 * @param int $exportMode
1880 * @param array $componentIds
1886 public static function getContributionDetails($exportMode, $componentIds) {
1887 $paymentDetails = [];
1888 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
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} )
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} )
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} )
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 )
1924 $dao = CRM_Core_DAO
::executeQuery($query);
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
,
1936 return $paymentDetails;
1940 * Create address associated with contribution record.
1942 * As long as there is one or more billing field in the parameters we will create the address.
1944 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1947 * @param array $params
1948 * @param int $billingLocationTypeID
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
;
1964 * Delete billing address record related contribution.
1966 * @param int $contributionId
1967 * @param int $contactId
1969 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1971 $contactJoin = NULL;
1973 if ($contributionId) {
1974 $clauses[] = "cc.id = {$contributionId}";
1978 $clauses[] = "cco.id = {$contactId}";
1979 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1982 if (empty($clauses)) {
1983 throw new CRM_Core_Exception('No Where clauses defined when deleting address');
1986 $condition = implode(' OR ', $clauses);
1990 FROM civicrm_address ca
1991 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1995 $dao = CRM_Core_DAO
::executeQuery($query);
1997 while ($dao->fetch()) {
1998 $params = ['id' => $dao->id
];
1999 CRM_Core_BAO_Block
::blockDelete('Address', $params);
2004 * This function check online pending contribution associated w/
2005 * Online Event Registration or Online Membership signup.
2007 * @param int $componentId
2008 * Participant/membership id.
2009 * @param string $componentName
2013 * pending contribution id.
2015 public static function checkOnlinePendingContribution($componentId, $componentName) {
2016 $contributionId = NULL;
2017 if (!$componentId ||
2018 !in_array($componentName, ['Event', 'Membership'])
2020 return $contributionId;
2023 if ($componentName === 'Event') {
2024 $idName = 'participant_id';
2025 $componentTable = 'civicrm_participant';
2026 $paymentTable = 'civicrm_participant_payment';
2027 $source = ts('Online Event Registration');
2030 if ($componentName === 'Membership') {
2031 $idName = 'membership_id';
2032 $componentTable = 'civicrm_membership';
2033 $paymentTable = 'civicrm_membership_payment';
2034 $source = ts('Online Contribution');
2037 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
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}";
2050 $dao = CRM_Core_DAO
::executeQuery($query);
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
2058 $contributionId = $dao->contribution_id
;
2062 return $contributionId;
2066 * Update contribution as well as related objects.
2068 * This function by-passes hooks - to address this - don't use this function.
2070 * @param array $params
2072 * @throws CRM_Core_Exception
2073 * @throws \CiviCRM_API3_Exception
2076 * Use api contribute.completetransaction
2077 * For failures use failPayment (preferably exposing by api in the process).
2080 public static function transitionComponents($params) {
2081 // @todo fix the one place that calls this function to use Payment.create
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;
2090 // if we already processed contribution object pass previous status id.
2091 $previousContriStatusId = $params['previous_contribution_status_id'] ??
NULL;
2093 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2095 // we process only ( Completed, Cancelled, or Failed ) contributions.
2096 if (!$contributionId ||
2097 !in_array($contributionStatusId, [
2098 array_search('Completed', $contributionStatuses),
2104 if (!$componentName ||
!$componentId) {
2105 // get the related component details.
2106 $componentDetails = self
::getComponentDetails($contributionId);
2109 $componentDetails['contact_id'] = $contactId;
2110 $componentDetails['component'] = $componentName;
2112 if ($componentName === 'event') {
2113 $componentDetails['participant'] = $componentId;
2116 $componentDetails['membership'] = $componentId;
2120 if (!empty($componentDetails['contact_id'])) {
2121 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2127 // do check for required ids.
2128 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
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;
2144 $contribution = new CRM_Contribute_BAO_Contribution();
2145 $contribution->id
= $ids['contribution'];
2146 $contribution->find();
2148 $contribution->loadRelatedObjects($input, $ids);
2150 $memberships = $contribution->_relatedObjects
['membership'] ??
[];
2151 $participant = $contribution->_relatedObjects
['participant'] ??
[];
2152 $pledgePayment = $contribution->_relatedObjects
['pledge_payment'] ??
[];
2154 $pledgeID = $oldStatus = NULL;
2155 $pledgePaymentIDs = [];
2156 if ($pledgePayment) {
2157 foreach ($pledgePayment as $key => $object) {
2158 $pledgePaymentIDs[] = $object->id
;
2160 $pledgeID = $pledgePayment[0]->pledge_id
;
2163 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2166 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2167 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2172 if ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2174 // only pending contribution related object processed.
2175 if ($previousContriStatusId &&
2176 !in_array($contributionStatuses[$previousContriStatusId], [
2181 // this is case when we already processed contribution object.
2184 elseif (!$previousContriStatusId &&
2185 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2190 // this is case when we are going to process contribution object later.
2194 if (is_array($memberships)) {
2195 foreach ($memberships as $membership) {
2200 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2201 $membership->membership_type_id
,
2202 $membership->is_test
, $membership->id
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
2208 SELECT membership_type_id
2209 FROM civicrm_membership_log
2210 WHERE membership_id=$membership->id
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();
2220 // else fall back to using current membership type
2221 // Figure out number of terms
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;
2228 // in case membership_num_terms comes through as null or zero
2229 $numterms = $numterms >= 1 ?
$numterms : 1;
2234 // CRM-15735-to update the membership status as per the contribution receive date
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'],
2244 $membership->membership_type_id
,
2247 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2248 $membership->save();
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);
2257 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2260 //get the status for membership.
2261 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2263 $dates['join_date'],
2266 $membership->membership_type_id
,
2270 $formattedParams = [
2271 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2272 array_search('Current', $membershipStatuses)
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),
2279 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2281 $membership->copyValues($formattedParams);
2282 $membership->save();
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'];
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
;
2295 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2297 //update related Memberships.
2298 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2300 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2301 $scheduledActivityID = CRM_Utils_Array
::value('id',
2302 civicrm_api3('Activity', 'Get',
2304 'source_record_id' => $membership->id
,
2305 'activity_type_id' => $activityType,
2306 'status_id' => 'Scheduled',
2309 'sort' => 'id DESC',
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]);
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',
2329 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2330 'source_contact_id' => $membershipLog['modified_id'],
2331 'priority_id' => 'Normal',
2336 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2342 $updatedStatusId = array_search('Registered', $participantStatuses);
2343 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2346 if ($pledgePayment) {
2347 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2354 * Returns all contribution related object ids.
2356 * @param $contributionId
2360 public static function getComponentDetails($contributionId) {
2361 $componentDetails = $pledgePayment = [];
2362 if (!$contributionId) {
2363 return $componentDetails;
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";
2383 $dao = CRM_Core_DAO
::executeQuery($query);
2384 $componentDetails = [];
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
;
2392 if ($dao->participant_id
) {
2393 $componentDetails['participant'] = $dao->participant_id
;
2395 if ($dao->membership_id
) {
2396 if (!isset($componentDetails['membership'])) {
2397 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2399 $componentDetails['membership'][] = $dao->membership_id
;
2400 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2402 if ($dao->pledge_payment_id
) {
2403 $pledgePayment[] = $dao->pledge_payment_id
;
2405 if ($dao->contribution_recur_id
) {
2406 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2410 if ($pledgePayment) {
2411 $componentDetails['pledge_payment'] = $pledgePayment;
2414 return $componentDetails;
2418 * @param int $contactId
2419 * @param bool $includeSoftCredit
2421 * @return null|string
2423 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
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)) . ")";
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}
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;
2450 if ($includeSoftCredit) {
2451 $query .= " UNION ";
2452 $query .= $contactSoftCreditContributionsSQL;
2457 return CRM_Core_DAO
::singleValueQuery($query);
2461 * Repeat a transaction as part of a recurring series.
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.
2471 * Gaps in the above (
2473 * @param array $input
2475 * @param array $contributionParams
2477 * @return bool|array
2478 * @throws \API_Exception
2479 * @throws \CiviCRM_API3_Exception
2480 * @throws \Civi\API\Exception\UnauthorizedException
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
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.
2498 protected static function repeatTransaction(array $input, array $contributionParams) {
2499 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2500 (int) $contributionParams['contribution_recur_id'],
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.
2508 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2509 $contributionParams['status_id'] = 'Pending';
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];
2517 $contributionParams['source'] = $contributionParams['source'] ??
ts('Recurring contribution');
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;
2529 * Get individual id for onbehalf contribution.
2531 * @param int $contributionId
2533 * @param int $contributorId
2537 * containing organization id and individual id
2539 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2543 if (!$contributionId) {
2547 // fetch contributor id if null
2548 if (!$contributorId) {
2549 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2550 $contributionId, 'contact_id'
2554 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2555 $activityTypeId = array_search('Contribution', $activityTypeIds);
2557 if ($activityTypeId && $contributorId) {
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
2567 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2568 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2571 1 => [$activityTypeId, 'Integer'],
2572 2 => [$contributionId, 'Integer'],
2573 3 => [$sourceID, 'Integer'],
2576 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
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;
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
;
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
2615 $year = date('Y') - 1;
2620 $year = ['Y' => $year];
2621 $yearDate = $config->fiscalYearStart
;
2622 $yearDate = array_merge($year, $yearDate);
2623 $yearDate = CRM_Utils_Date
::format($yearDate);
2625 $monthDate = date('Ym') . '01';
2631 'yearDate' => $yearDate,
2632 'monthDate' => $monthDate,
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 -
2641 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2643 * Note that the unit test for the BaseIPN class tests this function
2645 * @param array $input
2646 * Input as delivered from Payment Processor.
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).
2653 * @throws CRM_Core_Exception
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
2665 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2666 if (empty($ids['contact']) && isset($this->contact_id
)) {
2667 $ids['contact'] = $this->contact_id
;
2670 if (empty($this->_component
)) {
2671 if (!empty($ids['event'])) {
2672 $this->_component
= 'event';
2675 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
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
)) {
2685 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
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
,
2695 if ($paymentProcessorID) {
2696 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
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
;
2706 $this->loadRelatedEntitiesByID($ids);
2708 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2709 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2712 if (!empty($ids['pledge_payment'])) {
2713 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2714 if (empty($paymentID)) {
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);
2722 $this->_relatedObjects
['pledge_payment'][] = $payment;
2726 // These are probably no longer accessed from anywhere
2727 // @todo remove this line, after ensuring not used.
2728 $ids = $this->loadRelatedMembershipObjects($ids);
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'] &&
2738 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
2741 $this->_relatedObjects
['event'] = &$event;
2743 $participant = new CRM_Event_BAO_Participant();
2744 $participant->id
= $ids['participant'];
2745 if ($ids['participant'] &&
2746 !$participant->find(TRUE)
2748 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
2750 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2752 $this->_relatedObjects
['participant'] = &$participant;
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;
2764 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($this->id
);
2765 if (!empty($relatedContact['individual_id'])) {
2766 $ids['related_contact'] = $relatedContact['individual_id'];
2769 if ($paymentProcessorID) {
2770 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2771 $this->is_test ?
'test' : 'live'
2773 $ids['paymentProcessor'] = $paymentProcessorID;
2774 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2777 // Add contribution id to $ids. CRM-20401
2778 $ids['contribution'] = $this->id
;
2783 * Create array of message information - ie. return html version, txt version, to field
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
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
2804 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2805 $this->loadRelatedObjects($input, $ids, TRUE);
2807 if (empty($this->_component
)) {
2808 $this->_component
= $input['component'] ??
NULL;
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];
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']);
2826 $entityID = $entity = NULL;
2827 if (isset($ids['contribution'])) {
2828 $entity = 'contribution';
2829 $entityID = $ids['contribution'];
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];
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'));
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');
2849 // todo remove strtolower - check consistency
2850 if (strtolower($this->_component
) === 'event') {
2851 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2852 $values['event'] = [];
2854 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2856 //get location details
2858 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2859 'entity_table' => 'civicrm_event',
2861 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2864 'entity_table' => 'civicrm_event',
2865 'entity_id' => $ids['event'],
2866 'module' => 'CiviEvent',
2869 [$custom_pre_id, $custom_post_ids] = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
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'];
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;
2886 if (!empty($ids['contribution'])) {
2887 $values['contributionId'] = $ids['contribution'];
2890 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2891 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
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'];
2902 'contact_id' => $ids['contact'],
2903 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2904 'Home', 'id', 'name'
2907 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2908 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display'] ??
NULL);
2911 if ($this->is_test
) {
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;
2921 // need to set the membership values here
2922 $template->assign('membership_name',
2923 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
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;
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']);
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);
2948 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2951 // otherwise if its about sending emails, continue sending without return, as we
2952 // don't want to exit the loop.
2957 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
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
2967 * @param array $input
2968 * Input into function (probably from payment processor).
2969 * @param array $values
2971 * The set of ids related to the input.
2974 * @throws \CRM_Core_Exception
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'] ??
'';
2984 // Else we assign the billing address of the contribution contact.
2986 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
2987 $addressDetails = reset($addressDetails);
2989 $values['address'] = $addressDetails['display'] ??
'';
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;
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
3007 if (!isset($this->_relatedObjects
['contributionPage'])) {
3008 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
3010 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3013 // no contribution page -probably back office
3015 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3016 $values['title'] = 'Contribution';
3018 // set lineItem for contribution
3020 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3021 if (!empty($lineItems)) {
3022 $firstLineItem = reset($lineItems);
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',
3029 $values['priceSetID'] = $priceSet['id'];
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'],
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']);
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']);
3047 $values['lineItem'][0] = $lineItems;
3051 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
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'];
3061 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3064 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3067 foreach ($groupTree as $key => $group) {
3068 if ($key === 'info') {
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;
3081 $values['customGroup'] = $customGroup;
3083 $values['is_pay_later'] = $this->is_pay_later
;
3089 * Assign message variables to template but try to break the habit.
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.
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.
3099 * Don't call this function directly as the signature will change.
3103 * @param bool $returnMessageText
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']);
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);
3122 //assign honor information to receipt message
3123 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3126 'soft_credit_type' => NULL,
3127 'honor_block_is_active' => NULL,
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'],
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');
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']),
3151 $template->assign('softCreditTypes', $softCreditTypes);
3152 $template->assign('softCredits', $softCredits);
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
);
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
);
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
;
3178 'pcp_display_in_roll' => NULL,
3179 'pcp_roll_nickname' => NULL,
3180 'pcp_personal_note' => NULL,
3184 if (strtolower($this->_component
) == 'contribute') {
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
;
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
;
3202 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3203 $template->assign($templateKey, $templateValue);
3206 if ($this->financial_type_id
) {
3207 $values['financial_type_id'] = $this->financial_type_id
;
3210 $template->assign('trxn_id', $this->trxn_id
);
3211 $template->assign('receive_date',
3212 CRM_Utils_Date
::processDate($this->receive_date
)
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']);
3224 if (!empty($values['softContributions'])) {
3225 $template->assign('softContributions', $values['softContributions']);
3227 if ($this->_component
== 'event') {
3228 $template->assign('title', $values['event']['title']);
3229 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3231 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3232 $viewRoles[] = $participantRoles[$v];
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']);
3242 if ($this->_relatedObjects
['participant']->is_test
) {
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
,
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) {
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
3274 if (!$additionalParticipantInfo) {
3275 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3278 'label' => $additional->fee_level
,
3279 'amount' => $additional->fee_amount
,
3281 $primaryAmount[] = [
3282 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3283 'amount' => $additional->fee_amount
,
3285 $additional->save();
3286 $template->assign('amount', $amount);
3287 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
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);
3294 if (count($customProfile)) {
3295 $template->assign('customProfile', $customProfile);
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
]);
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
;
3315 * Check whether payment processor supports
3316 * cancellation of contribution subscription
3318 * @param int $contributionId
3321 * @param bool $isNotCancelled
3325 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3326 $cacheKeyString = "$contributionId";
3327 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3329 static $supportsCancel = [];
3331 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3332 $supportsCancel[$cacheKeyString] = FALSE;
3333 $isCancelled = FALSE;
3335 if ($isNotCancelled) {
3336 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3339 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3340 if (!empty($paymentObject)) {
3341 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3344 return $supportsCancel[$cacheKeyString];
3348 * Check whether subscription is already cancelled.
3350 * @param int $contributionId
3354 * contribution status
3356 public static function isSubscriptionCancelled($contributionId) {
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') {
3372 * Create all financial accounts entry.
3374 * @param array $params
3375 * Contribution object, line item array and params for trxn.
3378 * @return null|\CRM_Core_BAO_FinancialTrxn
3380 public static function recordFinancialAccounts(&$params) {
3381 $skipRecords = $return = FALSE;
3382 $isUpdate = !empty($params['prevContribution']);
3384 $additionalParticipantId = [];
3385 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3386 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
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);
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';
3400 $entityId = $params['contribution']->id
;
3401 $entityTable = 'civicrm_contribution';
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));
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'])) {
3417 $statusId = $params['contribution']->contribution_status_id
;
3419 if ($contributionStatus != 'Failed' &&
3420 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3422 $skipRecords = TRUE;
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'
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',
3440 elseif (!empty($params['payment_instrument_id'])) {
3441 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
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
);
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);
3453 $totalAmount = $params['total_amount'] ??
NULL;
3454 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3455 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3457 //build financial transaction params
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,
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'];
3483 //CRM-16259, set is_payment flag for non pending status
3484 if (!in_array($contributionStatus, $pendingStatus)) {
3485 $trxnParams['is_payment'] = 1;
3487 if (!empty($params['payment_processor'])) {
3488 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3491 if (empty($trxnParams['payment_processor_id'])) {
3492 unset($trxnParams['payment_processor_id']);
3495 $params['trxnParams'] = $trxnParams;
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.
3507 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3509 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
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))
3515 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3516 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3519 //if financial type is changed
3520 if (!empty($params['financial_type_id']) &&
3521 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3523 $accountRelationship = 'Income Account is';
3524 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3525 $accountRelationship = 'Deferred Revenue Account is';
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'];
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);
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');
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'];
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'];
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'];
3564 $params['deferred_financial_account_id'] = $newFinancialAccount;
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
;
3576 if (!empty($params['contribution_status_id']) &&
3577 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
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');
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);
3594 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3595 $params['trxnParams']['check_number'] = $params['check_number'] ??
NULL;
3597 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3598 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
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
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');
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.
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'],
3632 $cardType = $params['card_type_id'] ??
NULL;
3633 $panTruncation = $params['pan_truncation'] ??
NULL;
3634 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
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
;
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);
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)) {
3658 'batch_id' => $params['batch_id'],
3659 'entity_table' => 'civicrm_financial_trxn',
3660 'entity_id' => $financialTxn->id
,
3662 CRM_Batch_BAO_EntityBatch
::create($entityParams);
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);
3670 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3671 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
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);
3677 unset($params['line_item']);
3678 self
::$_trxnIDs = NULL;
3683 * Update all financial accounts entry.
3685 * @param array $params
3686 * Contribution object, line item array and params for trxn.
3688 * @param string $context
3691 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3692 * adds unpredictability.
3695 public static function updateFinancialAccounts(&$params, $context = NULL) {
3697 $inputParams = $params;
3698 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
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
);
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
;
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);
3718 * Is this contribution status a reversal.
3720 * If so we would expect to record a negative value in the financial_trxn table.
3722 * @param int $status_id
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);
3732 * Check status validation on update of a contribution.
3734 * @param array $values
3735 * Previous form values before submit.
3737 * @param array $fields
3738 * The input form values.
3740 * @param array $errors
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']) {
3752 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
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'],
3764 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3765 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
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']],
3775 * Delete contribution of contact.
3777 * @see https://issues.civicrm.org/jira/browse/CRM-12155
3779 * @param int $contactId
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
);
3793 * Get options for a given contribution field.
3795 * @param string $fieldName
3796 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3797 * @param array $props whatever is known about this dao object.
3799 * @return array|bool
3800 * @see CRM_Core_DAO::buildOptions
3803 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3804 $className = __CLASS__
;
3806 if (isset($props['orderColumn'])) {
3807 $params['orderColumn'] = $props['orderColumn'];
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', [
3817 'id' => ($props['contribution_page_id']),
3819 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3820 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
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')";
3831 case 'contribution_status_id':
3832 if ($context !== 'validate') {
3833 $params['condition'] = "v.name <> 'Template'";
3836 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3840 * Validate financial type.
3842 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3844 * @param int $financialTypeId
3845 * Financial Type id.
3847 * @param string $relationName
3849 * @return array|bool
3851 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3852 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3854 if (!$financialAccount) {
3855 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
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
3869 * @throws \CRM_Core_Exception
3870 * @throws \CiviCRM_API3_Exception
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;
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,
3890 // create activity with target contacts
3891 $session = CRM_Core_Session
::singleton();
3892 $id = $session->get('userID');
3894 $activityParams['source_contact_id'] = $id;
3895 $activityParams['target_contact_id'][] = $targetCid;
3897 civicrm_api3('Activity', 'create', $activityParams);
3901 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3904 * @param string $component
3905 * @param bool $getTrxnInfo
3909 * @throws \CRM_Core_Exception
3910 * @throws \CiviCRM_API3_Exception
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');
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;
3922 if (!$contributionId) {
3927 elseif ($component == 'membership') {
3928 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
3931 $contributionId = $id;
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;
3939 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3940 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3942 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3944 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
3946 $contribution = civicrm_api3('Contribution', 'getsingle', [
3947 'id' => $contributionId,
3951 'contribution_status_id',
3952 'financial_type_id',
3956 $info['payLater'] = $contribution['is_pay_later'];
3957 $info['contribution_status'] = $contribution['contribution_status'];
3958 $info['currency'] = $contribution['currency'];
3960 $info['total'] = $total;
3961 $info['paid'] = $total - $paymentBalance;
3962 $info['balance'] = $paymentBalance;
3964 $info['component'] = $component;
3965 if ($getTrxnInfo && $baseTrxnId) {
3966 $info['transaction'] = self
::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
3969 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
3974 * Get the outstanding balance on a contribution.
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).
3981 * @throws \CRM_Core_Exception
3983 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
3984 if ($contributionTotal === NULL) {
3985 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3988 return (float) CRM_Utils_Money
::subtractCurrencies(
3990 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
3991 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
3996 * Check financial type validation on update of a contribution.
3998 * @param int $financialTypeId
3999 * Value of latest Financial Type.
4001 * @param int $contributionId
4004 * @param array $errors
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) {
4016 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4018 '1' => [$contributionId, 'Integer'],
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.');
4027 * Update related pledge payment payments.
4029 * This function has been refactored out of the back office contribution form and may
4030 * still overlap with other functions.
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
4041 public static function updateRelatedPledge(
4047 $original_total_amount,
4048 $contribution_status_id,
4049 $original_contribution_status_id
4051 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4055 if ($pledgePaymentID) {
4056 //store contribution id in payment record.
4057 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4060 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4067 if (!$pledgePaymentID) {
4070 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4076 $updatePledgePaymentStatus = FALSE;
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;
4082 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4083 ($original_total_amount != $total_amount))
4085 $updatePledgePaymentStatus = TRUE;
4088 if ($updatePledgePaymentStatus) {
4089 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4091 $contribution_status_id,
4100 * Is there only one line item attached to the contribution.
4106 * @throws \CiviCRM_API3_Exception
4108 public static function isSingleLineItem($id) {
4109 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4110 return ($lineItemCount == 1);
4114 * Complete an order.
4116 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4118 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4120 * Moving it out of the BaseIPN class is just the first step.
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).
4131 * @throws \API_Exception
4132 * @throws \CRM_Core_Exception
4133 * @throws \CiviCRM_API3_Exception
4135 public static function completeOrder($input, $recurringContributionID, $contributionID, $isPostPaymentCreate = FALSE) {
4136 $transaction = new CRM_Core_Transaction();
4138 $inputContributionWhiteList = [
4143 'payment_instrument_id',
4148 'contribution_status_id',
4151 'financial_type_id',
4154 $paymentProcessorId = $input['payment_processor_id'] ??
NULL;
4156 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4158 $contributionParams = array_merge([
4159 'contribution_status_id' => $completedContributionStatusID,
4160 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4163 $contributionParams['payment_processor'] = $paymentProcessorId;
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'];
4169 if ($recurringContributionID) {
4170 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4173 if (!$contributionID) {
4174 $contributionResult = self
::repeatTransaction($input, $contributionParams);
4175 $contributionID = $contributionResult['id'];
4178 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4179 self
::updateMembershipBasedOnCompletionOfContribution(
4181 $input['trxn_date'] ??
date('YmdHis')
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);
4194 $contributionParams['id'] = $contributionID;
4195 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4197 if (empty($contributionResult)) {
4198 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4201 $transaction->commit();
4202 \Civi
::log()->info("Contribution {$contributionParams['id']} updated successfully");
4204 $contributionSoft = ContributionSoft
::get(FALSE)
4205 ->addWhere('contribution_id', '=', $contributionID)
4206 ->addWhere('pcp_id', '>', 0)
4208 ->execute()->first();
4209 if (!empty($contributionSoft)) {
4210 CRM_Contribute_BAO_ContributionSoft
::pcpNotifyOwner($contributionID, $contributionSoft);
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']);
4216 if (self
::isEmailReceipt($input, $contributionID, $recurringContributionID)) {
4217 civicrm_api3('Contribution', 'sendconfirmation', [
4218 'id' => $contributionID,
4219 'payment_processor_id' => $paymentProcessorId,
4221 \Civi
::log()->info("Contribution {$contributionParams['id']} Receipt sent");
4224 return $contributionResult;
4228 * Send receipt from contribution.
4230 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
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.
4235 * @param array $input
4236 * Incoming data from Payment processor.
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
4245 * @throws \CRM_Core_Exception
4246 * @throws \CiviCRM_API3_Exception
4247 * @throws \Exception
4249 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
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');
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);
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
,
4272 * Generate From email and from name in an array values
4274 * @param array $input
4275 * @param \CRM_Contribute_BAO_Contribution $contribution
4279 public static function generateFromEmailAndName($input, $contribution) {
4280 // Use input value if supplied.
4281 if (!empty($input['receipt_from_email'])) {
4283 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4284 $input['receipt_from_email'],
4287 // if we are still empty see if we can use anything from a contribution page.
4289 if (!empty($contribution->contribution_page_id
)) {
4290 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4292 // if we are still empty see if we can use anything from a contribution page.
4293 if (!empty($pageValues['receipt_from_email'])) {
4295 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4296 $pageValues['receipt_from_email'],
4299 // If we are still empty fall back to the domain or logged in user information.
4300 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4304 * Load related memberships.
4308 * @return array $ids
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.
4319 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4322 public function loadRelatedMembershipObjects($ids = []) {
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, []);
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
;
4337 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4338 foreach ($ids['membership'] as $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");
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;
4357 * Function use to store line item proportionally in in entity financial trxn table
4359 * @param array $trxnParams
4361 * @param int $trxnId
4363 * @param float $contributionTotalAmount
4365 * @throws \CiviCRM_API3_Exception
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']);
4373 'contribution_total_amount' => $contributionTotalAmount,
4374 'trxn_total_amount' => $trxnParams['total_amount'],
4375 'trxn_id' => $trxnId,
4377 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4382 * ContributionPage values were being imposed onto values.
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
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.
4392 * @param array $values
4396 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4397 $contributionPageValues = [];
4398 CRM_Contribute_BAO_ContributionPage
::setValues(
4399 $this->contribution_page_id
,
4400 $contributionPageValues
4403 // These are the values that I believe to be useful.
4406 'pay_later_receipt',
4408 'receipt_from_email',
4409 'receipt_from_name',
4413 'honoree_profile_id',
4414 'onbehalf_profile_id',
4415 'honor_block_is_active',
4416 // Kinda might be - but would be on the contribution...
4419 // Included for 'fear of regression' but can't justify any use for these....
4421 'payment_processor',
4422 'financial_type_id',
4423 'amount_block_is_active',
4428 'default_amount_id',
4432 'initial_amount_help_text',
4433 'initial_amount_label',
4435 'is_allow_other_amount',
4436 'is_billing_required',
4437 'is_confirm_enabled',
4438 'is_credit_card_only',
4440 'is_partial_payment',
4441 'is_recur_installments',
4442 'is_recur_interval',
4446 'min_initial_amount',
4447 'recur_frequency_unit',
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
);
4460 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
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
4477 * @param string $name
4482 public static function checkContributeSettings($name) {
4483 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
4484 return $contributeSettings[$name] ??
NULL;
4488 * Get the contribution as it is in the database before being updated.
4490 * @param int $contributionID
4492 * @return \CRM_Contribute_BAO_Contribution|null
4494 private static function getOriginalContribution($contributionID) {
4495 return self
::getValues(['id' => $contributionID]);
4499 * Get the amount for the financial item row.
4501 * Helper function to start to break down recordFinancialTransactions for readability.
4503 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
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
4509 * @param array $params
4510 * Params as passed to contribution.create
4512 * @param string $context
4513 * changeFinancialType| changedAmount
4514 * @param array $lineItemDetails
4516 * @param bool $isARefund
4517 * Is this a refund / negative transaction.
4518 * @param int $previousLineItemTotal
4521 * @todo move recordFinancialAccounts & helper functions to their own class?
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;
4532 elseif ($context == 'changeFinancialType') {
4533 return -$lineItemDetails['line_total'];
4535 elseif ($context == 'changedStatus') {
4536 $cancelledTaxAmount = 0;
4538 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
4540 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
4542 elseif ($context === NULL) {
4543 // erm, yes because? but, hey, it's tested.
4544 return $lineItemDetails['line_total'];
4547 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
4552 * Get the multiplier for adjusting rows.
4554 * If we are dealing with a refund or cancellation then it will be a negative
4555 * amount to reflect the negative transaction.
4557 * If we are changing Financial Type it will be a negative amount to
4558 * adjust down the old type.
4560 * @param int $contribution_status_id
4561 * @param string $context
4565 protected static function getMultiplier($contribution_status_id, $context) {
4566 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
4573 * Does this transaction reflect a payment instrument change.
4575 * @param array $params
4576 * @param array $pendingStatuses
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
);
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'])
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))
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
4601 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
4602 $params['contribution']->check_number
!= $params['prevContribution']->check_number
4604 // another special case when check number is changed, create new financial records
4605 // create financial trxn with negative amount
4613 * Update the memberships associated with a contribution if it has been completed.
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.
4618 * @param int $contributionID
4619 * @param string $changeDate
4621 * @throws \CRM_Core_Exception
4622 * @throws \CiviCRM_API3_Exception
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',
4635 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4636 $membershipParams['membership_type_id'],
4637 $membershipParams['is_test'],
4638 $membershipParams['id']
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
4646 SELECT membership_type_id
4647 FROM civicrm_membership_log
4648 WHERE membership_id={$membershipParams['id']}
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
;
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'],
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([
4675 if ($currentMembership) {
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 )
4681 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
4683 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
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']
4690 $dates['join_date'] = $currentMembership['join_date'];
4693 //get the status for membership.
4694 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4696 $dates['join_date'],
4699 $membershipParams['membership_type_id'],
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);
4714 * Get payment links as they relate to a contribution.
4716 * If a payment can be made then include a payment link & if a refund is appropriate
4717 * then a refund link.
4720 * @param float $balance
4721 * @param string $contributionStatus
4724 * $actionLinks Links array containing:
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.
4738 'url' => CRM_Utils_System
::url('civicrm/payment', [
4744 'title' => ts('Record Payment'),
4747 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
4749 'url' => CRM_Utils_System
::url('civicrm/payment', [
4756 'title' => ts('Submit Credit Card payment'),
4760 'url' => CRM_Utils_System
::url('civicrm/payment', [
4766 'title' => ts('Record Refund'),
4768 return $actionLinks;
4772 * Get a query to determine the amount donated by the contact/s in the current financial year.
4774 * @param array $contactIDs
4778 public static function getAnnualQuery($contactIDs) {
4779 $contactIDs = implode(',', $contactIDs);
4780 $config = CRM_Core_Config
::singleton();
4781 $currentMonth = date('m');
4782 $currentDay = date('d');
4784 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
4786 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
4787 (int) $config->fiscalYearStart
['d'] > $currentDay
4790 $year = date('Y') - 1;
4795 $nextYear = $year +
1;
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'];
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'];
4809 $config->fiscalYearStart
= $newFiscalYearStart;
4810 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
4813 // First of January.
4816 $startDate = "$year$monthDay";
4817 $endDate = "$nextYear$monthDay";
4820 'contact_id' => 'IN (' . $contactIDs . ')',
4821 'is_test' => ' = 0',
4822 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
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);
4828 foreach ($whereClauses as $key => $clause) {
4829 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
4831 $whereClauseString = implode(' AND ', $clauses);
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
4836 SELECT COUNT(*) as count,
4837 SUM(total_amount) as amount,
4838 AVG(total_amount) as average,
4840 FROM civicrm_contribution b
4841 WHERE " . $whereClauseString . "
4842 GROUP BY currency, contribution_status_id
4843 HAVING $havingClause
4849 * Assign Test Value.
4851 * @param string $fieldName
4852 * @param array $fieldDef
4853 * @param int $counter
4855 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
4856 if ($fieldName === 'tax_amount') {
4857 $this->{$fieldName} = "0.00";
4859 elseif ($fieldName === 'net_amount') {
4860 $this->{$fieldName} = '2.00';
4862 elseif ($fieldName === 'total_amount') {
4863 $this->{$fieldName} = "3.00";
4865 elseif ($fieldName === 'fee_amount') {
4866 $this->{$fieldName} = '1.00';
4869 parent
::assignTestValues($fieldName, $fieldDef, $counter);
4874 * Check if contribution has participant/membership payment.
4876 * @param int $contributionId
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') {
4890 elseif ($items['entity_table'] == 'civicrm_membership') {
4902 * Create Accounts Receivable financial trxn entry for Completed Contribution.
4904 * @param array $trxnParams
4905 * Financial trxn params
4906 * @param array $contributionParams
4907 * Contribution Params
4911 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
4912 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
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
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'];
4940 * Calculate financial item amount when contribution is updated.
4942 * @param array $params
4943 * contribution params
4944 * @param array $amountParams
4946 * @param string $context
4950 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
4951 if (!empty($params['is_quick_config'])) {
4952 $amount = $amountParams['item_amount'];
4954 $amount = $params['total_amount'];
4955 if ($context === NULL) {
4956 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
4961 $amount = $amountParams['line_total'];
4962 if ($context == 'changedAmount') {
4963 $amount -= $amountParams['previous_line_total'];
4965 $amount *= $amountParams['diff'];
4971 * Retrieve Sales Tax Financial Accounts.
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
;
4988 return $financialAccount;
4992 * Create tax entry in civicrm_entity_financial_trxn table.
4994 * @param array $entityParams
4996 * @param array $eftParams
4998 * @throws \CiviCRM_API3_Exception
5000 public static function createProportionalEntry($entityParams, $eftParams) {
5002 if ($entityParams['contribution_total_amount'] != 0) {
5003 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5005 // Record Entity Financial Trxn; CRM-20145
5006 $eftParams['amount'] = $paid;
5007 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5011 * Create array of last financial item id's.
5013 * @param int $contributionId
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, [
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
,
5039 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5042 return [$ftIds, $taxItems];
5046 * Create proportional entries in civicrm_entity_financial_trxn.
5048 * @param array $entityParams
5050 * @param array $lineItems
5052 * @param array $ftIds
5054 * @param array $taxItems
5056 * @throws \CiviCRM_API3_Exception
5058 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5060 'entity_table' => 'civicrm_financial_item',
5061 'financial_trxn_id' => $entityParams['trxn_id'],
5063 foreach ($lineItems as $key => $value) {
5064 if ($value['qty'] == 0) {
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);
5079 * Load entities related to the contribution into $this->_relatedObjects.
5083 * @throws \CRM_Core_Exception
5085 protected function loadRelatedEntitiesByID($ids) {
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',
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');
5105 * Function to replace contribution tokens.
5107 * @param array $contributionIds
5109 * @param string $subject
5111 * @param array $subjectToken
5113 * @param string $text
5115 * @param string $html
5117 * @param array $messageToken
5119 * @param bool $escapeSmarty
5122 * @throws \CiviCRM_API3_Exception
5124 public static function replaceContributionTokens(
5133 if (empty($contributionIds)) {
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);
5143 return $contributionDetails;
5147 * Get the contribution fields for $id and display labels where
5148 * appropriate (if the token is present).
5151 * @param array $messageToken
5154 * @throws \CRM_Core_Exception
5156 public static function getContributionTokenValues($id, $messageToken) {
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);
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]] ??
'');
5179 * Get invoice_number for contribution.
5181 * @param int $contributionID
5185 public static function getInvoiceNumber($contributionID) {
5186 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix')) {
5187 return $invoicePrefix . $contributionID;
5194 * Load the values needed for the event message.
5196 * @param int $eventID
5197 * @param int $participantID
5198 * @param int|null $contributionID
5201 * @throws \CRM_Core_Exception
5203 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5208 $values = ['event' => []];
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);
5214 $eventCustomGroup = [];
5215 foreach ($eventGroupTree as $key => $group) {
5216 if ($key === 'info') {
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;
5229 $values['event']['customGroup'] = $eventCustomGroup;
5231 //get participant details
5232 $participantParams = [
5233 'id' => $participantID,
5236 $values['participant'] = [];
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') {
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;
5256 $values['participant']['customGroup'] = $participantCustomGroup;
5258 //get location details
5260 'entity_id' => $eventID,
5261 'entity_table' => 'civicrm_event',
5263 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5266 'entity_table' => 'civicrm_event',
5267 'entity_id' => $eventID,
5268 'module' => 'CiviEvent',
5271 [$custom_pre_id, $custom_post_ids] = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5273 $values['custom_pre_id'] = $custom_pre_id;
5274 $values['custom_post_id'] = $custom_post_ids;
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;
5292 * Get the activity source and target contacts linked to a contribution
5294 * @param $activityId
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']],
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');
5307 $sourceContactId = NULL;
5308 $targetContactId = NULL;
5310 for ($i = 0; $i < $activityContactQuery->count(); $i++
) {
5311 $record = $activityContactQuery->itemAt($i);
5313 if ($record['record_type_id'] === $sourceContactKey) {
5314 $sourceContactId = $record['contact_id'];
5317 if ($record['record_type_id'] === $targetContactKey) {
5318 $targetContactId = $record['contact_id'];
5322 return [$sourceContactId, $targetContactId];