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\ContributionPage
;
14 use Civi\Api4\ContributionRecur
;
15 use Civi\Api4\PaymentProcessor
;
20 * @copyright CiviCRM LLC https://civicrm.org/licensing
22 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
25 * Static field for all the contribution information that we can potentially import
29 public static $_importableFields = NULL;
32 * Static field for all the contribution information that we can potentially export
36 public static $_exportableFields = NULL;
39 * Static field to hold financial trxn id's.
43 public static $_trxnIDs = NULL;
46 * Field for all the objects related to this contribution.
49 * 1) deprecated function transitionComponents
50 * 2) function to send contribution receipts _assignMessageVariablesToTemplate
51 * 3) some invoice code that is copied from 2
52 * 4) odds & sods that need to be investigated and fixed.
54 * However, it is no longer used by completeOrder.
56 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
60 public $_relatedObjects = [];
63 * Field for the component - either 'event' (participant) or 'contribute'
64 * (any item related to a contribution page e.g. membership, pledge, contribution)
65 * This is used for composing messages because they have dependency on the
66 * contribution_page or event page - although over time we may eliminate that
69 * "contribution"\"event"
71 public $_component = NULL;
74 * Possibly obsolete variable.
76 * If you use it please explain why it is set in the create function here.
80 public $trxn_result_code;
85 public function __construct() {
86 parent
::__construct();
90 * Takes an associative array and creates a contribution object.
92 * the function extract all the params it needs to initialize the create a
93 * contribution object. the params array could contain additional unused name/value
96 * @param array $params
97 * (reference ) an assoc array of name/value pairs.
99 * @return \CRM_Contribute_BAO_Contribution
100 * @throws \CRM_Core_Exception
101 * @throws \CiviCRM_API3_Exception
103 public static function add(&$params) {
104 if (empty($params)) {
108 $contributionID = $params['id'] ??
NULL;
109 $action = $contributionID ?
'edit' : 'create';
111 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
112 $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)]);
113 throw new CRM_Core_Exception($message);
116 //set defaults in create mode
117 if (!$contributionID) {
118 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
119 if (empty($params['invoice_number']) && CRM_Invoicing_Utils
::isInvoicingEnabled()) {
120 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
121 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
125 $contributionStatusID = $params['contribution_status_id'] ??
NULL;
126 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
127 CRM_Core_Error
::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
129 if (!$contributionStatusID) {
130 // Since the fee amount is expecting this (later on) ensure it is always set.
131 // It would only not be set for an update where it is unchanged.
132 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
133 'id' => $contributionID,
134 'return' => 'contribution_status_id',
137 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
140 && !empty($params['membership_id'])
141 && Civi
::settings()->get('deferred_revenue_enabled')
143 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
144 if ($memberStartDate) {
145 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
148 self
::calculateMissingAmountParams($params, $contributionID);
150 if (!empty($params['payment_instrument_id'])) {
151 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
152 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
153 $params['check_number'] = 'null';
157 $setPrevContribution = TRUE;
158 if ($contributionID && $setPrevContribution) {
159 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
161 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
163 if ($contributionID && !empty($params['revenue_recognition_date'])
164 && !($previousContributionStatus === 'Pending')
165 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
167 unset($params['revenue_recognition_date']);
170 // Get Line Items if we don't have them already.
171 if (empty($params['line_item'])) {
172 if (isset($params['id'])) {
173 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
176 CRM_Price_BAO_LineItem
::getLineItemArray($params);
180 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
181 isset($params['financial_type_id']))) {
182 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
185 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
187 $contribution = new CRM_Contribute_BAO_Contribution();
188 $contribution->copyValues($params);
190 $contribution->id
= $contributionID;
192 if (empty($contribution->id
)) {
193 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
194 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
195 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
199 $result = $contribution->save();
201 // Add financial_trxn details as part of fix for CRM-4724
202 $contribution->trxn_result_code
= $params['trxn_result_code'] ??
NULL;
203 $contribution->payment_processor
= $params['payment_processor'] ??
NULL;
205 //add Account details
206 $params['contribution'] = $contribution;
207 if (empty($params['is_post_payment_create'])) {
208 // If this is being called from the Payment.create api/ BAO then that Entity
209 // takes responsibility for the financial transactions. In fact calling Payment.create
210 // to add payments & having it call completetransaction and / or contribution.create
211 // to update related entities is the preferred flow.
212 // Note that leveraging this parameter for any other code flow is not supported and
213 // is likely to break in future and / or cause serious problems in your data.
214 // https://github.com/civicrm/civicrm-core/pull/14673
215 self
::recordFinancialAccounts($params);
218 if (self
::isUpdateToRecurringContribution($params)) {
219 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
220 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
222 $params['receive_date'] ??
'now'
226 $params['contribution_id'] = $contribution->id
;
228 if (!empty($params['custom']) &&
229 is_array($params['custom'])
231 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
234 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
236 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
241 * Is this contribution updating an existing recurring contribution.
243 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
244 * pending payment is being confirmed (or failing).
246 * @param array $params
250 public static function isUpdateToRecurringContribution($params) {
251 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
254 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
257 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
260 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
261 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
268 * Get defaults for new entity.
272 public static function getDefaults() {
274 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
275 FALSE, FALSE, FALSE, 'AND is_default = 1')
277 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
278 'receive_date' => date('Y-m-d H:i:s'),
283 * Fetch the object and store the values in the values array.
285 * @param array $params
286 * Input parameters to find object.
287 * @param array $values
288 * Output values of the object.
290 * The array that holds all the db ids.
292 * @return CRM_Contribute_BAO_Contribution|null
293 * The found object or null
295 public static function getValues($params, &$values = [], &$ids = []) {
296 if (empty($params)) {
299 $contribution = new CRM_Contribute_BAO_Contribution();
301 $contribution->copyValues($params);
303 if ($contribution->find(TRUE)) {
304 $ids['contribution'] = $contribution->id
;
306 CRM_Core_DAO
::storeValues($contribution, $values);
308 return $contribution;
310 // return by reference
316 * Get the values and resolve the most common mappings.
318 * Since contribution status is resolved in almost every function that calls getValues it makes
319 * sense to have an extra function to resolve it rather than repeat the code.
321 * Think carefully before adding more mappings to be resolved as there could be performance implications
322 * if this function starts to be called from more iterative functions.
324 * @param array $params
325 * Input parameters to find object.
328 * Array of the found contribution.
329 * @throws CRM_Core_Exception
331 public static function getValuesWithMappings($params) {
333 $contribution = self
::getValues($params, $values, $ids);
334 if (is_null($contribution)) {
335 throw new CRM_Core_Exception('No contribution found');
337 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
342 * Calculate net_amount & fee_amount if they are not set.
344 * Net amount should be total - fee.
345 * This should only be called for new contributions.
347 * @param array $params
348 * Params for a new contribution before they are saved.
349 * @param int|null $contributionID
350 * Contribution ID if we are dealing with an update.
352 * @throws \CiviCRM_API3_Exception
354 public static function calculateMissingAmountParams(&$params, $contributionID) {
355 if (!$contributionID && (!isset($params['fee_amount']) ||
$params['fee_amount'] === '')) {
356 if (isset($params['total_amount']) && isset($params['net_amount'])) {
357 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
360 $params['fee_amount'] = 0;
363 if (!isset($params['net_amount'])) {
364 if (!$contributionID) {
365 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
368 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
369 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
370 // net_amount may need adjusting.
371 $contribution = civicrm_api3('Contribution', 'getsingle', [
372 'id' => $contributionID,
373 'return' => ['total_amount', 'net_amount', 'fee_amount'],
375 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
376 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
377 $params['net_amount'] = $totalAmount - $feeAmount;
385 * @param $billingLocationTypeID
389 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
390 $hasBillingField = FALSE;
399 //build address array
401 $addressParams['location_type_id'] = $billingLocationTypeID;
402 $addressParams['is_billing'] = 1;
404 $billingFirstName = $params['billing_first_name'] ??
NULL;
405 $billingMiddleName = $params['billing_middle_name'] ??
NULL;
406 $billingLastName = $params['billing_last_name'] ??
NULL;
407 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
409 foreach ($billingFields as $value) {
410 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ??
NULL;
411 if (!empty($addressParams[$value])) {
412 $hasBillingField = TRUE;
415 return [$hasBillingField, $addressParams];
419 * Get address params ready to be passed to the payment processor.
421 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
422 * To create an address we need state_province_id.
424 * @param array $params
425 * @param int $billingLocationTypeID
429 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
430 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
431 foreach ($addressParams as $name => $field) {
432 if (substr($name, 0, 8) == 'billing_') {
433 $addressParams[substr($name, 9)] = $addressParams[$field];
436 return [$hasBillingField, $addressParams];
440 * Get the number of terms for this contribution for a given membership type
441 * based on querying the line item table and relevant price field values
442 * Note that any one contribution should only be able to have one line item relating to a particular membership
445 * @param int $membershipTypeID
447 * @param int $contributionID
451 public static function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
452 $numTerms = CRM_Core_DAO
::singleValueQuery("
453 SELECT membership_num_terms FROM civicrm_line_item li
454 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
455 WHERE contribution_id = %1 AND membership_type_id = %2",
456 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
458 // default of 1 is precautionary
459 return empty($numTerms) ?
1 : $numTerms;
463 * Takes an associative array and creates a contribution object.
465 * @param array $params
466 * (reference ) an assoc array of name/value pairs.
468 * @return CRM_Contribute_BAO_Contribution
470 * @throws \API_Exception
471 * @throws \CRM_Core_Exception
472 * @throws \CiviCRM_API3_Exception
474 public static function create(&$params) {
476 $transaction = new CRM_Core_Transaction();
479 $contribution = self
::add($params);
481 catch (CRM_Core_Exception
$e) {
482 $transaction->rollback();
486 $params['contribution_id'] = $contribution->id
;
487 $session = CRM_Core_Session
::singleton();
489 if (!empty($params['note'])) {
491 'entity_table' => 'civicrm_contribution',
492 'note' => $params['note'],
493 'entity_id' => $contribution->id
,
494 'contact_id' => $session->get('userID'),
496 if (!$noteParams['contact_id']) {
497 $noteParams['contact_id'] = $params['contact_id'];
499 CRM_Core_BAO_Note
::add($noteParams);
502 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
504 $transaction->commit();
506 if (empty($contribution->contact_id
)) {
507 $contribution->find(TRUE);
510 $isCompleted = ('Completed' === CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
));
511 if (!empty($params['on_behalf'])
514 $existingActivity = Activity
::get(FALSE)->setWhere([
515 ['source_record_id', '=', $contribution->id
],
516 ['activity_type_id:name', '=', 'Contribution'],
517 ])->execute()->first();
519 $campaignParams = isset($params['campaign_id']) ?
['campaign_id' => ($params['campaign_id'] ??
NULL)] : [];
520 Activity
::save(FALSE)->addRecord(array_merge([
521 'activity_type_id:name' => 'Contribution',
522 'source_record_id' => $contribution->id
,
523 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ?
: $contribution->contact_id
,
524 'target_contact_id' => CRM_Core_Session
::getLoggedInContactID() ?
[$contribution->contact_id
] : [],
525 'activity_date_time' => $contribution->receive_date
,
526 'is_test' => (bool) $contribution->is_test
,
527 'status_id:name' => $isCompleted ?
'Completed' : 'Scheduled',
528 'skipRecentView' => TRUE,
529 'subject' => CRM_Activity_BAO_Activity
::getActivitySubject($contribution),
530 'id' => $existingActivity['id'] ??
NULL,
531 ], $campaignParams))->execute();
534 // do not add to recent items for import, CRM-4399
535 if (empty($params['skipRecentView'])) {
536 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
537 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
539 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
546 $retrieveRequired = 0;
547 foreach ($titleFields as $titleField) {
548 if (!isset($contribution->$titleField)) {
549 $retrieveRequired = 1;
553 if ($retrieveRequired == 1) {
554 $contribution->find(TRUE);
556 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
557 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
560 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
561 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
562 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
566 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
567 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
568 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
572 // add the recently created Contribution
573 CRM_Utils_Recent
::add($title,
577 $contribution->contact_id
,
583 return $contribution;
587 * Get the values for pseudoconstants for name->value and reverse.
589 * @param array $defaults
590 * (reference) the default values, some of which need to be resolved.
591 * @param bool $reverse
592 * True if we want to resolve the values in the reverse direction (value -> name).
594 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
595 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
596 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
597 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
598 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
602 * Convert associative array names to values and vice-versa.
604 * This function is used by both the web form layer and the api. Note that
605 * the api needs the name => value conversion, also the view layer typically
606 * requires value => name conversion
608 * @param array $defaults
609 * @param string $property
610 * @param array $lookup
611 * @param bool $reverse
615 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
616 $id = $property . '_id';
618 $src = $reverse ?
$property : $id;
619 $dst = $reverse ?
$id : $property;
621 if (!array_key_exists($src, $defaults)) {
625 $look = $reverse ?
array_flip($lookup) : $lookup;
627 if (is_array($look)) {
628 if (!array_key_exists($defaults[$src], $look)) {
632 $defaults[$dst] = $look[$defaults[$src]];
637 * Retrieve DB object based on input parameters.
639 * It also stores all the retrieved values in the default array.
641 * @param array $params
642 * (reference ) an assoc array of name/value pairs.
643 * @param array $defaults
644 * (reference ) an assoc array to hold the name / value pairs.
645 * in a hierarchical manner
647 * (reference) the array that holds all the db ids.
649 * @return CRM_Contribute_BAO_Contribution
651 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
652 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
653 return $contribution;
657 * Combine all the importable fields from the lower levels object.
659 * The ordering is important, since currently we do not have a weight
660 * scheme. Adding weight is super important and should be done in the
661 * next week or so, before this can be called complete.
663 * @param string $contactType
664 * @param bool $status
667 * array of importable Fields
669 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
670 if (!self
::$_importableFields) {
671 if (!self
::$_importableFields) {
672 self
::$_importableFields = [];
676 $fields = ['' => ['title' => ts('- do not import -')]];
679 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
682 $note = CRM_Core_DAO_Note
::import();
683 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
684 unset($tmpFields['option_value']);
685 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
686 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
688 // Using new Dedupe rule.
690 'contact_type' => $contactType,
691 'used' => 'Unsupervised',
693 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
694 $tmpContactField = [];
695 if (is_array($fieldsArray)) {
696 foreach ($fieldsArray as $value) {
697 //skip if there is no dupe rule
698 if ($value == 'none') {
701 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
706 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
707 $tmpContactField[trim($value)] = $contactFields[trim($value)];
709 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
712 $title = $tmpContactField[trim($value)]['title'];
714 $tmpContactField[trim($value)]['title'] = $title;
718 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
719 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
720 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
721 $fields = array_merge($fields, $tmpContactField);
722 $fields = array_merge($fields, $tmpFields);
723 $fields = array_merge($fields, $note);
724 $fields = array_merge($fields, $optionFields);
725 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
726 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
727 self
::$_importableFields = $fields;
729 return self
::$_importableFields;
733 * Combine all the exportable fields from the lower level objects.
735 * @param bool $checkPermission
738 * array of exportable Fields
740 public static function &exportableFields($checkPermission = TRUE) {
741 if (!self
::$_exportableFields) {
742 if (!self
::$_exportableFields) {
743 self
::$_exportableFields = [];
746 $fields = CRM_Contribute_DAO_Contribution
::export();
747 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
748 $fields = array_merge(
750 CRM_Contribute_DAO_Product
::export(),
751 CRM_Contribute_DAO_ContributionProduct
::export(),
752 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
754 'contribution_product_id' => [
755 'title' => ts('Premium'),
756 'name' => 'contribution_product_id',
757 'where' => 'civicrm_product.id',
758 'data_type' => CRM_Utils_Type
::T_INT
,
764 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
766 $contributionPage = [
767 'contribution_page' => [
768 'title' => ts('Contribution Page'),
769 'name' => 'contribution_page',
770 'where' => 'civicrm_contribution_page.title',
771 'data_type' => CRM_Utils_Type
::T_STRING
,
775 $contributionNote = [
776 'contribution_note' => [
777 'title' => ts('Contribution Note'),
778 'name' => 'contribution_note',
779 'data_type' => CRM_Utils_Type
::T_TEXT
,
784 'contribution_batch' => [
785 'title' => ts('Batch Name'),
791 'contribution_campaign_title' => [
792 'title' => ts('Campaign Title'),
793 'name' => 'campaign_title',
794 'where' => 'civicrm_campaign.title',
795 'data_type' => CRM_Utils_Type
::T_STRING
,
798 $softCreditFields = [
799 'contribution_soft_credit_name' => [
800 'name' => 'contribution_soft_credit_name',
801 'title' => ts('Soft Credit For'),
802 'where' => 'civicrm_contact_d.display_name',
803 'data_type' => CRM_Utils_Type
::T_STRING
,
805 'contribution_soft_credit_amount' => [
806 'name' => 'contribution_soft_credit_amount',
807 'title' => ts('Soft Credit Amount'),
808 'where' => 'civicrm_contribution_soft.amount',
809 'data_type' => CRM_Utils_Type
::T_MONEY
,
811 'contribution_soft_credit_type' => [
812 'name' => 'contribution_soft_credit_type',
813 'title' => ts('Soft Credit Type'),
814 'where' => 'contribution_softcredit_type.label',
815 'data_type' => CRM_Utils_Type
::T_STRING
,
817 'contribution_soft_credit_contribution_id' => [
818 'name' => 'contribution_soft_credit_contribution_id',
819 'title' => ts('Soft Credit For Contribution ID'),
820 'where' => 'civicrm_contribution_soft.contribution_id',
821 'data_type' => CRM_Utils_Type
::T_INT
,
823 'contribution_soft_credit_contact_id' => [
824 'name' => 'contribution_soft_credit_contact_id',
825 'title' => ts('Soft Credit For Contact ID'),
826 'where' => 'civicrm_contact_d.id',
827 'data_type' => CRM_Utils_Type
::T_INT
,
831 $fields = array_merge($fields, $contributionPage,
832 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
833 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
836 self
::$_exportableFields = $fields;
839 return self
::$_exportableFields;
843 * Record an activity when a payment is received.
845 * @todo this is intended to be moved to payment BAO class as a protected function
846 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
847 * merit it's own function as it makes the code less rather than more readable.
849 * @param int $contributionId
850 * @param int $participantId
851 * @param string $totalAmount
852 * @param string $currency
853 * @param string $trxnDate
855 * @throws \CRM_Core_Exception
856 * @throws \CiviCRM_API3_Exception
858 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
859 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
861 if ($participantId) {
862 $inputParams['id'] = $participantId;
865 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
866 $entityObj = $entityObj[$participantId];
867 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
870 $entityObj = new CRM_Contribute_BAO_Contribution();
871 $entityObj->id
= $contributionId;
872 $entityObj->find(TRUE);
873 $title = ts('Contribution');
875 // @todo per block above this is not a logical splitting off of functionality.
876 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
880 * Get the value for the To Financial Account.
882 * @param $contribution
887 public static function getToFinancialAccount($contribution, $params) {
888 if (!empty($params['payment_processor_id'])) {
889 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
891 if (!empty($params['payment_instrument_id'])) {
892 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
895 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
896 $queryParams = [1 => [$relationTypeId, 'Integer']];
897 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
902 * Get memberships related to the contribution.
904 * @param int $contributionID
908 protected static function getRelatedMemberships($contributionID) {
909 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
910 'return' => 'membership_id',
911 'contribution_id' => (int) $contributionID,
914 foreach ($membershipPayments as $membershipPayment) {
915 $membershipIDs[] = $membershipPayment['membership_id'];
917 if (empty($membershipIDs)) {
920 // We could combine this with the MembershipPayment.get - we'd
921 // need to re-wrangle the params (here or in the calling function)
922 // as they would then me membership.contact_id, membership.is_test etc
923 return civicrm_api3('Membership', 'get', [
924 'id' => ['IN' => $membershipIDs],
925 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
930 * Cancel contribution.
932 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
934 * @param $memberships
935 * @param $contributionId
936 * @param $membershipStatuses
937 * @param $participant
939 * @param $pledgePayment
941 * @param $pledgePaymentIDs
942 * @param $contributionStatusId
944 protected static function cancel($memberships, $contributionId, $membershipStatuses, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
945 // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it
946 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
948 $updatedStatusId = array_search('Cancelled', $participantStatuses);
949 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
952 if ($pledgePayment) {
953 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
958 * Do any accounting updates required as a result of a contribution status change.
960 * Currently we have a bit of a roundabout where adding a payment results in this being called &
961 * this may attempt to add a payment. We need to resolve that....
963 * The 'right' way to add payments or refunds is through the Payment.create api. That api
964 * then updates the contribution but this process should not also record another financial trxn.
965 * Currently we have weak detection fot that scenario & where it is detected the first returned
966 * value is FALSE - meaning 'do not continue'.
968 * We should also look at the fact that the calling function - updateFinancialAccounts
969 * bunches together some disparate processes rather than having separate appropriate
972 * @param array $params
975 * Return indicates whether the updateFinancialAccounts function should continue.
977 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
978 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
979 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
981 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
982 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
983 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
984 // why it is here or where it is handled instead.
985 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
986 && $currentContributionStatus == 'Partially paid'))
991 if (self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
992 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
993 $params['trxnParams']['total_amount'] = -$params['total_amount'];
995 elseif (($previousContributionStatus == 'Pending'
996 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
998 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
999 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1001 if ($currentContributionStatus == 'Cancelled') {
1002 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1003 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1004 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1007 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1008 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1012 if (($previousContributionStatus == 'Pending'
1013 ||
$previousContributionStatus == 'In Progress')
1014 && ($currentContributionStatus == 'Completed')
1016 if (empty($params['line_item'])) {
1018 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1019 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1020 // & this can be removed
1023 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1024 // This is an update so original currency if none passed in.
1025 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1027 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1028 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1029 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1030 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1032 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1035 'entity_table' => 'civicrm_financial_item',
1037 foreach ($params['line_item'] as $fieldId => $fields) {
1038 foreach ($fields as $fieldValueId => $lineItemDetails) {
1039 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1041 1 => [$lineItemDetails['id'], 'Integer'],
1043 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1044 while ($financialItem->fetch()) {
1045 $entityParams['entity_id'] = $financialItem->id
;
1046 $entityParams['amount'] = $financialItem->amount
;
1047 foreach (self
::$_trxnIDs as $tID) {
1048 $entityParams['financial_trxn_id'] = $tID;
1049 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1060 * It is possible to override the membership id that is updated from the payment processor.
1062 * Historically Paypal does this & it still does if it determines data is messed up - see
1063 * https://lab.civicrm.org/dev/membership/issues/13
1065 * Read the comment block on repeattransaction for more information
1066 * about how things should work.
1068 * @param int $contributionID
1069 * @param array $input
1071 * @throws \CiviCRM_API3_Exception
1073 protected static function handleMembershipIDOverride($contributionID, $input) {
1074 if (!empty($input['membership_id'])) {
1075 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1076 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1081 * Update all financial items related to the line item tto have a status of paid.
1083 * @param int $lineItemID
1085 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1088 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1091 2 => [$lineItemID, 'Integer'],
1093 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1094 CRM_Core_DAO
::executeQuery($query, $fparams);
1098 * Create the financial items for the line.
1100 * @param array $params
1101 * @param string $context
1102 * @param array $fields
1103 * @param array $previousLineItems
1104 * @param array $inputParams
1105 * @param bool $isARefund
1106 * @param array $trxnIds
1107 * @param int $fieldId
1111 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1112 foreach ($fields as $fieldValueId => $lineItemDetails) {
1113 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
1114 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
1115 if ($params['contribution']->receive_date
) {
1116 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
1119 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1121 $currency = $params['prevContribution']->currency
;
1122 if ($params['contribution']->currency
) {
1123 $currency = $params['contribution']->currency
;
1125 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1127 'transaction_date' => $receiveDate,
1128 'contact_id' => $params['prevContribution']->contact_id
,
1129 'currency' => $currency,
1130 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1131 'description' => $prevFinancialItem['description'] ??
NULL,
1132 'status_id' => $prevFinancialItem['status_id'],
1133 'financial_account_id' => $financialAccount,
1134 'entity_table' => 'civicrm_line_item',
1135 'entity_id' => $lineItemDetails['id'],
1137 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1138 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1139 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
1141 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
1142 $taxAmount = (float) $lineItemDetails['tax_amount'];
1143 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1144 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1145 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1147 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1148 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1150 if ($taxAmount != 0) {
1151 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
1152 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
1153 if ($lineItemDetails['financial_type_id']) {
1154 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1156 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1164 * Does this contributtion status update represent a refund.
1166 * @param int $previousContributionStatusID
1167 * @param int $currentContributionStatusID
1171 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1172 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1175 return self
::isContributionStatusNegative($currentContributionStatusID);
1179 * Get transaction information about the contribution.
1181 * @param int $contributionId
1182 * @param int $financialTypeID
1186 protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) {
1188 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Expense Account is');
1190 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
1192 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
1194 ft.payment_instrument_id,
1195 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
1197 FROM civicrm_contribution con
1198 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
1199 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
1200 AND ft.to_financial_account_id != %2
1201 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
1202 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
1203 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
1205 WHERE con.id = %1 AND ft.is_payment = 1
1208 1 => [$contributionId, 'Integer'],
1209 2 => [$feeFinancialAccount, 'Integer'],
1211 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
1212 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
1214 while ($resultDAO->fetch()) {
1215 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1216 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1217 if ($resultDAO->card_type_id
) {
1218 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
1219 $pantruncation = '';
1220 if ($resultDAO->pan_truncation
) {
1221 $pantruncation = ": {$resultDAO->pan_truncation}";
1223 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
1226 // show payment edit link only for payments done via backoffice form
1227 $paymentEditLink = '';
1228 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
1230 CRM_Core_Action
::UPDATE
=> [
1231 'name' => ts('Edit Payment'),
1232 'icon' => 'fa-pencil',
1233 'url' => 'civicrm/payment/edit',
1234 'class' => 'medium-popup',
1235 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
1236 'title' => ts('Edit Payment'),
1239 $paymentEditLink = CRM_Core_Action
::formLink(
1241 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
1243 'id' => $resultDAO->id
,
1244 'contribution_id' => $contributionId,
1248 'Payment.edit.action',
1256 'id' => $resultDAO->id
,
1257 'total_amount' => $resultDAO->total_amount
,
1258 'financial_type' => $resultDAO->financial_account
,
1259 'payment_instrument' => $paidByLabel,
1260 'receive_date' => $resultDAO->trxn_date
,
1261 'trxn_id' => $resultDAO->trxn_id
,
1262 'status' => $statuses[$resultDAO->status_id
],
1263 'currency' => $resultDAO->currency
,
1264 'action' => $paymentEditLink,
1266 if ($paidByName == 'Check') {
1267 $val['check_number'] = $resultDAO->check_number
;
1275 * Should an email receipt be sent for this contribution on completion.
1277 * @param array $input
1278 * @param int $contributionPageID
1279 * @param int $recurringContributionID
1282 * @throws \API_Exception
1283 * @throws \Civi\API\Exception\UnauthorizedException
1285 protected static function isEmailReceipt(array $input, $contributionPageID, $recurringContributionID): bool {
1286 if (isset($input['is_email_receipt'])) {
1287 return (bool) $input['is_email_receipt'];
1289 if ($recurringContributionID) {
1290 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
1291 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
1292 // 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
1293 // Instance that had the table added via an upgrade in 4.1
1294 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
1295 // https://lab.civicrm.org/dev/core/issues/1245
1296 return (bool) ContributionRecur
::get(FALSE)->addWhere('id', '=', $recurringContributionID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1298 if ($contributionPageID) {
1299 return (bool) ContributionPage
::get(FALSE)->addWhere('id', '=', $contributionPageID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1301 // This would be the case for backoffice (where is_email_receipt is not passed in) or events, where Event::sendMail will filter
1307 * Process failed contribution.
1309 * @param $memberships
1310 * @param $contributionId
1311 * @param array $membershipStatuses
1312 * @param $participant
1313 * @param $pledgePayment
1315 * @param array $pledgePaymentIDs
1316 * @param $contributionStatusId
1318 * @throws \CRM_Core_Exception
1320 protected static function processFail($memberships, $contributionId, array $membershipStatuses, array $participant, $pledgePayment, $pledgeID, array $pledgePaymentIDs, $contributionStatusId): void
{
1321 if (is_array($memberships)) {
1322 foreach ($memberships as $membership) {
1324 //Update Membership status if there is no other completed contribution associated with the membership.
1325 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1326 foreach ($relatedContributions as $contriId) {
1327 if ($contriId == $contributionId) {
1330 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1331 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1335 if ($membership && $update) {
1336 $membership->status_id
= array_search('Expired', $membershipStatuses);
1337 $membership->is_override
= TRUE;
1338 $membership->status_override_end_date
= 'null';
1339 $membership->save();
1344 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1348 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1349 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1350 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1353 if ($pledgePayment) {
1354 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1361 public function addSelectWhereClause() {
1362 $whereClauses = parent
::addSelectWhereClause();
1363 if ($whereClauses !== []) {
1364 // In this case permisssions have been applied & we assume the
1365 // financialaclreport is applying these
1366 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1367 return $whereClauses;
1370 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1371 return $whereClauses;
1373 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1374 if (empty($types)) {
1375 $whereClauses['financial_type_id'] = 'IN (0)';
1378 $whereClauses['financial_type_id'] = [
1379 'IN (' . implode(',', array_keys($types)) . ')',
1382 return $whereClauses;
1386 * @param null $status
1387 * @param null $startDate
1388 * @param null $endDate
1390 * @return array|null
1392 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1396 $where[] = 'contribution_status_id = 1';
1400 $where[] = 'contribution_status_id = 3';
1405 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1408 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1410 $financialTypeACLJoin = '';
1411 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1412 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1413 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1414 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1415 if ($financialTypes) {
1416 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1417 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1420 $where[] = "c.financial_type_id IN (0)";
1424 $whereCond = implode(' AND ', $where);
1427 SELECT sum( total_amount ) as total_amount,
1428 count( c.id ) as total_count,
1430 FROM civicrm_contribution c
1431 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1432 $financialTypeACLJoin
1434 AND ( is_test = 0 OR is_test IS NULL )
1435 AND contact.is_deleted = 0
1439 $dao = CRM_Core_DAO
::executeQuery($query);
1442 while ($dao->fetch()) {
1443 $count +
= $dao->total_count
;
1444 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1448 'amount' => implode(', ', $amount),
1456 * Delete the indirect records associated with this contribution first.
1460 * @return mixed|null
1461 * $results no of deleted Contribution on success, false otherwise
1463 public static function deleteContribution($id) {
1464 CRM_Utils_Hook
::pre('delete', 'Contribution', $id);
1466 $transaction = new CRM_Core_Transaction();
1469 //delete activity record
1471 'source_record_id' => $id,
1472 // activity type id for contribution
1473 'activity_type_id' => 6,
1476 CRM_Activity_BAO_Activity
::deleteActivity($params);
1478 //delete billing address if exists for this contribution.
1479 self
::deleteAddress($id);
1481 //update pledge and pledge payment, CRM-3961
1482 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1484 // remove entry from civicrm_price_set_entity, CRM-5095
1485 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1486 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1488 // cleanup line items.
1489 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1491 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1492 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1494 if ($participantId) {
1495 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1498 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1502 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1503 $noteId = key($note);
1505 CRM_Core_BAO_Note
::del($noteId, FALSE);
1508 $dao = new CRM_Contribute_DAO_Contribution();
1511 $results = $dao->delete();
1513 $transaction->commit();
1515 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1517 // delete the recently created Contribution
1518 $contributionRecent = [
1520 'type' => 'Contribution',
1522 CRM_Utils_Recent
::del($contributionRecent);
1528 * React to a financial transaction (payment) failure.
1530 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1531 * payments is important for forensic and outreach reasons.
1533 * @param int $contributionID
1534 * @param int $contactID
1535 * @param string $message
1537 * @throws \CiviCRM_API3_Exception
1539 public static function failPayment($contributionID, $contactID, $message) {
1540 civicrm_api3('activity', 'create', [
1541 'activity_type_id' => 'Failed Payment',
1542 'details' => $message,
1543 'subject' => ts('Payment failed at payment processor'),
1544 'source_record_id' => $contributionID,
1545 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1548 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1549 civicrm_api3('contribution', 'create', [
1550 'id' => $contributionID,
1551 'contribution_status_id' => 'Failed',
1556 * Check if there is a contribution with the same trxn_id or invoice_id.
1558 * @param array $input
1559 * An assoc array of name/value pairs.
1560 * @param array $duplicates
1561 * (reference) store ids of duplicate contribs.
1565 * true if duplicate, false otherwise
1567 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1569 $id = $input['id'] ??
NULL;
1571 $trxn_id = $input['trxn_id'] ??
NULL;
1572 $invoice_id = $input['invoice_id'] ??
NULL;
1578 $clause[] = "trxn_id = %1";
1579 $input[1] = [$trxn_id, 'String'];
1583 $clause[] = "invoice_id = %2";
1584 $input[2] = [$invoice_id, 'String'];
1587 if (empty($clause)) {
1591 $clause = implode(' OR ', $clause);
1593 $clause = "( $clause ) AND id != %3";
1594 $input[3] = [$id, 'Integer'];
1597 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1598 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1600 while ($dao->fetch()) {
1601 $duplicates[] = $dao->id
;
1608 * Takes an associative array and creates a contribution_product object.
1610 * the function extract all the params it needs to initialize the create a
1611 * contribution_product object. the params array could contain additional unused name/value
1614 * @param array $params
1615 * (reference) an assoc array of name/value pairs.
1617 * @return CRM_Contribute_DAO_ContributionProduct
1619 public static function addPremium(&$params) {
1620 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1621 $contributionProduct->copyValues($params);
1622 return $contributionProduct->save();
1626 * Get list of contribution fields for profile.
1627 * For now we only allow custom contribution fields to be in
1630 * @param bool $addExtraFields
1631 * True if special fields needs to be added.
1634 * the list of contribution fields
1636 public static function getContributionFields($addExtraFields = TRUE) {
1637 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1638 // @todo remove this - this line was added because payment_instrument_id was not
1639 // set to exportable - but now it is.
1640 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1642 if ($addExtraFields) {
1643 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1646 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1648 foreach ($contributionFields as $key => $var) {
1649 if ($key == 'contribution_contact_id') {
1652 elseif ($key == 'contribution_campaign_id') {
1653 $var['title'] = ts('Campaign');
1655 $fields[$key] = $var;
1658 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1663 * Add extra fields specific to contribution.
1665 public static function getSpecialContributionFields() {
1667 'contribution_soft_credit_name' => [
1668 'name' => 'contribution_soft_credit_name',
1669 'title' => ts('Soft Credit Name'),
1670 'headerPattern' => '/^soft_credit_name$/i',
1671 'where' => 'civicrm_contact_d.display_name',
1673 'contribution_soft_credit_email' => [
1674 'name' => 'contribution_soft_credit_email',
1675 'title' => ts('Soft Credit Email'),
1676 'headerPattern' => '/^soft_credit_email$/i',
1677 'where' => 'soft_email.email',
1679 'contribution_soft_credit_phone' => [
1680 'name' => 'contribution_soft_credit_phone',
1681 'title' => ts('Soft Credit Phone'),
1682 'headerPattern' => '/^soft_credit_phone$/i',
1683 'where' => 'soft_phone.phone',
1685 'contribution_soft_credit_contact_id' => [
1686 'name' => 'contribution_soft_credit_contact_id',
1687 'title' => ts('Soft Credit Contact ID'),
1688 'headerPattern' => '/^soft_credit_contact_id$/i',
1689 'where' => 'civicrm_contribution_soft.contact_id',
1691 'contribution_pcp_title' => [
1692 'name' => 'contribution_pcp_title',
1693 'title' => ts('Personal Campaign Page Title'),
1694 'headerPattern' => '/^contribution_pcp_title$/i',
1695 'where' => 'contribution_pcp.title',
1699 return $extraFields;
1703 * @param int $pageID
1707 public static function getCurrentandGoalAmount($pageID) {
1709 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1710 FROM civicrm_contribution_page p,
1711 civicrm_contribution c
1712 WHERE p.id = c.contribution_page_id
1714 AND c.cancel_date is null
1718 $config = CRM_Core_Config
::singleton();
1719 $params = [1 => [$pageID, 'Integer']];
1720 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1722 if ($dao->fetch()) {
1723 return [$dao->goal
, $dao->total
];
1726 return [NULL, NULL];
1731 * Get list of contributions which credit the passed in contact ID.
1733 * The returned array provides details about the original contribution & donor.
1735 * @param int $honorId
1736 * In Honor of Contact ID.
1739 * list of contribution fields
1740 * @todo - this is a confusing function called from one place. It has a test. It would be
1741 * nice to deprecate it.
1744 public static function getHonorContacts($honorId) {
1746 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1747 $honorDAO->contact_id
= $honorId;
1750 $type = CRM_Contribute_PseudoConstant
::financialType();
1752 while ($honorDAO->fetch()) {
1753 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1754 $contributionDAO->id
= $honorDAO->contribution_id
;
1756 if ($contributionDAO->find(TRUE)) {
1757 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1758 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1759 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1760 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1761 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1762 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1763 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1764 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1765 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1773 * Get the sort name of a contact for a particular contribution.
1776 * Id of the contribution.
1778 * @return null|string
1779 * sort name of the contact if found
1781 public static function sortName($id) {
1782 $id = CRM_Utils_Type
::escape($id, 'Integer');
1785 SELECT civicrm_contact.sort_name
1786 FROM civicrm_contribution, civicrm_contact
1787 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1788 AND civicrm_contribution.id = {$id}
1790 return CRM_Core_DAO
::singleValueQuery($query);
1794 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1796 * @param int|array $contactIDs
1800 public static function annual($contactIDs) {
1801 if (!is_array($contactIDs)) {
1802 // In practice I can't fine any evidence that this function is ever called with
1803 // anything other than a single contact id, but left like this due to .... fear.
1804 $contactIDs = explode(',', $contactIDs);
1807 $query = self
::getAnnualQuery($contactIDs);
1808 $dao = CRM_Core_DAO
::executeQuery($query);
1810 $amount = $average = [];
1811 while ($dao->fetch()) {
1812 if ($dao->count
> 0 && $dao->amount
> 0) {
1813 $count +
= $dao->count
;
1814 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1815 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1821 implode(', ', $amount),
1822 implode(', ', $average),
1829 * Check if there is a contribution with the params passed in.
1831 * Used for trxn_id,invoice_id and contribution_id
1833 * @param array $params
1834 * An assoc array of name/value pairs.
1837 * contribution id if success else NULL
1839 public static function checkDuplicateIds($params) {
1840 $dao = new CRM_Contribute_DAO_Contribution();
1844 foreach ($params as $k => $v) {
1846 $clause[] = "$k = '$v'";
1849 $clause = implode(' AND ', $clause);
1850 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1851 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1853 while ($dao->fetch()) {
1861 * Get the contribution details for component export.
1863 * @param int $exportMode
1865 * @param array $componentIds
1871 public static function getContributionDetails($exportMode, $componentIds) {
1872 $paymentDetails = [];
1873 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1875 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1876 $componentSelect = " civicrm_participant_payment.participant_id id";
1877 $additionalClause = "
1878 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1879 AND civicrm_participant_payment.participant_id {$componentClause} )
1882 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1883 $componentSelect = " civicrm_membership_payment.membership_id id";
1884 $additionalClause = "
1885 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1886 AND civicrm_membership_payment.membership_id {$componentClause} )
1889 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1890 $componentSelect = " civicrm_pledge_payment.id id";
1891 $additionalClause = "
1892 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1893 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1897 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1898 trxn_id, {$componentSelect}
1899 FROM civicrm_contribution
1900 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1901 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1902 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1903 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1904 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1905 AND option_group_contribution_status.id = contribution_status.option_group_id )
1909 $dao = CRM_Core_DAO
::executeQuery($query);
1911 while ($dao->fetch()) {
1912 $paymentDetails[$dao->id
] = [
1913 'total_amount' => $dao->total_amount
,
1914 'contribution_status' => $dao->status
,
1915 'receive_date' => $dao->receive_date
,
1916 'pay_instru' => $dao->payment_instrument
,
1917 'trxn_id' => $dao->trxn_id
,
1921 return $paymentDetails;
1925 * Create address associated with contribution record.
1927 * As long as there is one or more billing field in the parameters we will create the address.
1929 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1932 * @param array $params
1933 * @param int $billingLocationTypeID
1938 public static function createAddress($params, $billingLocationTypeID) {
1939 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1940 if ($hasBillingField) {
1941 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1942 return $address->id
;
1949 * Delete billing address record related contribution.
1951 * @param int $contributionId
1952 * @param int $contactId
1954 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1956 $contactJoin = NULL;
1958 if ($contributionId) {
1959 $clauses[] = "cc.id = {$contributionId}";
1963 $clauses[] = "cco.id = {$contactId}";
1964 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1967 if (empty($clauses)) {
1968 throw new CRM_Core_Exception('No Where clauses defined when deleting address');
1971 $condition = implode(' OR ', $clauses);
1975 FROM civicrm_address ca
1976 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1980 $dao = CRM_Core_DAO
::executeQuery($query);
1982 while ($dao->fetch()) {
1983 $params = ['id' => $dao->id
];
1984 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1989 * This function check online pending contribution associated w/
1990 * Online Event Registration or Online Membership signup.
1992 * @param int $componentId
1993 * Participant/membership id.
1994 * @param string $componentName
1998 * pending contribution id.
2000 public static function checkOnlinePendingContribution($componentId, $componentName) {
2001 $contributionId = NULL;
2002 if (!$componentId ||
2003 !in_array($componentName, ['Event', 'Membership'])
2005 return $contributionId;
2008 if ($componentName == 'Event') {
2009 $idName = 'participant_id';
2010 $componentTable = 'civicrm_participant';
2011 $paymentTable = 'civicrm_participant_payment';
2012 $source = ts('Online Event Registration');
2015 if ($componentName == 'Membership') {
2016 $idName = 'membership_id';
2017 $componentTable = 'civicrm_membership';
2018 $paymentTable = 'civicrm_membership_payment';
2019 $source = ts('Online Contribution');
2022 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
2025 SELECT component.id as {$idName},
2026 componentPayment.contribution_id as contribution_id,
2027 contribution.source source,
2028 contribution.contribution_status_id as contribution_status_id,
2029 contribution.is_pay_later as is_pay_later
2030 FROM $componentTable component
2031 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
2032 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
2033 WHERE component.id = {$componentId}";
2035 $dao = CRM_Core_DAO
::executeQuery($query);
2037 while ($dao->fetch()) {
2038 if ($dao->contribution_id
&&
2039 $dao->is_pay_later
&&
2040 $dao->contribution_status_id
== $pendingStatusId &&
2041 strpos($dao->source
, $source) !== FALSE
2043 $contributionId = $dao->contribution_id
;
2047 return $contributionId;
2051 * Update contribution as well as related objects.
2053 * This function by-passes hooks - to address this - don't use this function.
2055 * @param array $params
2057 * @throws CRM_Core_Exception
2058 * @throws \CiviCRM_API3_Exception
2061 * Use api contribute.completetransaction
2062 * For failures use failPayment (preferably exposing by api in the process).
2065 public static function transitionComponents($params) {
2066 // get minimum required values.
2067 $contactId = $params['contact_id'] ??
NULL;
2068 $componentId = $params['component_id'] ??
NULL;
2069 $componentName = $params['componentName'] ??
NULL;
2070 $contributionId = $params['contribution_id'] ??
NULL;
2071 $contributionStatusId = $params['contribution_status_id'] ??
NULL;
2073 // if we already processed contribution object pass previous status id.
2074 $previousContriStatusId = $params['previous_contribution_status_id'] ??
NULL;
2076 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2078 // we process only ( Completed, Cancelled, or Failed ) contributions.
2079 if (!$contributionId ||
2080 !in_array($contributionStatusId, [
2081 array_search('Completed', $contributionStatuses),
2082 array_search('Cancelled', $contributionStatuses),
2083 array_search('Failed', $contributionStatuses),
2089 if (!$componentName ||
!$componentId) {
2090 // get the related component details.
2091 $componentDetails = self
::getComponentDetails($contributionId);
2094 $componentDetails['contact_id'] = $contactId;
2095 $componentDetails['component'] = $componentName;
2097 if ($componentName == 'event') {
2098 $componentDetails['participant'] = $componentId;
2101 $componentDetails['membership'] = $componentId;
2105 if (!empty($componentDetails['contact_id'])) {
2106 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2112 // do check for required ids.
2113 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2119 $input['component'] = $componentDetails['component'] ??
NULL;
2120 $ids['contribution'] = $contributionId;
2121 $ids['contact'] = $componentDetails['contact_id'] ??
NULL;
2122 $ids['membership'] = $componentDetails['membership'] ??
NULL;
2123 $ids['participant'] = $componentDetails['participant'] ??
NULL;
2124 $ids['event'] = $componentDetails['event'] ??
NULL;
2125 $ids['pledge_payment'] = $componentDetails['pledge_payment'] ??
NULL;
2126 $ids['contributionRecur'] = NULL;
2127 $ids['contributionPage'] = NULL;
2129 $contribution = new CRM_Contribute_BAO_Contribution();
2130 $contribution->id
= $ids['contribution'];
2131 $contribution->find();
2133 $contribution->loadRelatedObjects($input, $ids);
2135 $memberships = $contribution->_relatedObjects
['membership'] ??
[];
2136 $participant = $contribution->_relatedObjects
['participant'] ??
[];
2137 $pledgePayment = $contribution->_relatedObjects
['pledge_payment'] ??
[];
2139 $pledgeID = $oldStatus = NULL;
2140 $pledgePaymentIDs = [];
2141 if ($pledgePayment) {
2142 foreach ($pledgePayment as $key => $object) {
2143 $pledgePaymentIDs[] = $object->id
;
2145 $pledgeID = $pledgePayment[0]->pledge_id
;
2148 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2151 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2152 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2157 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2158 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2159 self
::cancel($memberships, $contributionId, $membershipStatuses, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2161 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2162 self
::processFail($memberships, $contributionId, $membershipStatuses, $participant, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2164 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2166 // only pending contribution related object processed.
2167 if ($previousContriStatusId &&
2168 !in_array($contributionStatuses[$previousContriStatusId], [
2173 // this is case when we already processed contribution object.
2176 elseif (!$previousContriStatusId &&
2177 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2182 // this is case when we are going to process contribution object later.
2186 if (is_array($memberships)) {
2187 foreach ($memberships as $membership) {
2192 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2193 $membership->membership_type_id
,
2194 $membership->is_test
, $membership->id
2197 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2198 // this picks up membership type changes during renewals
2200 SELECT membership_type_id
2201 FROM civicrm_membership_log
2202 WHERE membership_id=$membership->id
2205 $dao = CRM_Core_DAO
::executeQuery($sql);
2206 if ($dao->fetch()) {
2207 if (!empty($dao->membership_type_id
)) {
2208 $membership->membership_type_id
= $dao->membership_type_id
;
2209 $membership->save();
2212 // else fall back to using current membership type
2213 // Figure out number of terms
2215 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2216 foreach ($lineitems as $lineitem) {
2217 if ($membership->membership_type_id
== ($lineitem['membership_type_id'] ??
NULL)) {
2218 $numterms = $lineitem['membership_num_terms'] ??
NULL;
2220 // in case membership_num_terms comes through as null or zero
2221 $numterms = $numterms >= 1 ?
$numterms : 1;
2226 // CRM-15735-to update the membership status as per the contribution receive date
2228 $oldStatus = $membership->status_id
;
2229 if (!empty($params['receive_date'])) {
2230 $joinDate = $params['receive_date'];
2231 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2232 $membership->end_date
,
2233 $membership->join_date
,
2234 $params['receive_date'],
2236 $membership->membership_type_id
,
2239 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2240 $membership->save();
2243 if ($currentMembership) {
2244 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2245 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2246 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2249 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2252 //get the status for membership.
2253 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2255 $dates['join_date'],
2258 $membership->membership_type_id
,
2262 $formattedParams = [
2263 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2264 array_search('Current', $membershipStatuses)
2266 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2267 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2268 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2271 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2273 $membership->copyValues($formattedParams);
2274 $membership->save();
2276 //updating the membership log
2277 $membershipLog = [];
2278 $membershipLog = $formattedParams;
2279 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'] ??
NULL, $format);
2280 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2282 $membershipLog['start_date'] = $logStartDate;
2283 $membershipLog['membership_id'] = $membership->id
;
2284 $membershipLog['modified_id'] = $membership->contact_id
;
2285 $membershipLog['modified_date'] = date('Ymd');
2286 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2288 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2290 //update related Memberships.
2291 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2293 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2294 $scheduledActivityID = CRM_Utils_Array
::value('id',
2295 civicrm_api3('Activity', 'Get',
2297 'source_record_id' => $membership->id
,
2298 'activity_type_id' => $activityType,
2299 'status_id' => 'Scheduled',
2302 'sort' => 'id DESC',
2307 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2308 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2309 if ($scheduledActivityID) {
2310 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2315 // track membership status change if any
2316 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2317 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2318 CRM_Activity_BAO_Activity
::addActivity($membership,
2319 'Change Membership Status',
2322 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2323 'source_contact_id' => $membershipLog['modified_id'],
2324 'priority_id' => 'Normal',
2329 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2335 $updatedStatusId = array_search('Registered', $participantStatuses);
2336 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2339 if ($pledgePayment) {
2340 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2347 * Returns all contribution related object ids.
2349 * @param $contributionId
2353 public static function getComponentDetails($contributionId) {
2354 $componentDetails = $pledgePayment = [];
2355 if (!$contributionId) {
2356 return $componentDetails;
2360 SELECT c.id as contribution_id,
2361 c.contact_id as contact_id,
2362 c.contribution_recur_id,
2363 mp.membership_id as membership_id,
2364 m.membership_type_id as membership_type_id,
2365 pp.participant_id as participant_id,
2366 p.event_id as event_id,
2367 pgp.id as pledge_payment_id
2368 FROM civicrm_contribution c
2369 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2370 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2371 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2372 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2373 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2374 WHERE c.id = $contributionId";
2376 $dao = CRM_Core_DAO
::executeQuery($query);
2377 $componentDetails = [];
2379 while ($dao->fetch()) {
2380 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2381 $componentDetails['contact_id'] = $dao->contact_id
;
2382 if ($dao->event_id
) {
2383 $componentDetails['event'] = $dao->event_id
;
2385 if ($dao->participant_id
) {
2386 $componentDetails['participant'] = $dao->participant_id
;
2388 if ($dao->membership_id
) {
2389 if (!isset($componentDetails['membership'])) {
2390 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2392 $componentDetails['membership'][] = $dao->membership_id
;
2393 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2395 if ($dao->pledge_payment_id
) {
2396 $pledgePayment[] = $dao->pledge_payment_id
;
2398 if ($dao->contribution_recur_id
) {
2399 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2403 if ($pledgePayment) {
2404 $componentDetails['pledge_payment'] = $pledgePayment;
2407 return $componentDetails;
2411 * @param int $contactId
2412 * @param bool $includeSoftCredit
2414 * @return null|string
2416 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2420 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2421 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2422 $liWhere = " AND i.financial_type_id IN (0)";
2423 if (!empty($financialTypes)) {
2424 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2425 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2427 $contactContributionsSQL = "
2428 SELECT contribution.id AS id
2429 FROM civicrm_contribution contribution
2430 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2431 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2435 $contactSoftCreditContributionsSQL = "
2436 SELECT contribution.id
2437 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2438 ON ( contribution.id = softContribution.contribution_id )
2439 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2440 $query = "SELECT count( x.id ) count FROM ( ";
2441 $query .= $contactContributionsSQL;
2443 if ($includeSoftCredit) {
2444 $query .= " UNION ";
2445 $query .= $contactSoftCreditContributionsSQL;
2450 return CRM_Core_DAO
::singleValueQuery($query);
2454 * Repeat a transaction as part of a recurring series.
2457 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2458 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2459 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2460 * and associated entities.
2461 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2462 * which updates the various entities and sends appropriate emails.
2464 * Gaps in the above (@todo)
2465 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2466 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2467 * 3) Repeat transaction duplicates rather than calls Order.create
2468 * 4) Use of payment.create still limited - completetransaction is more common.
2469 * 5) the template transaction is tricky - historically we used the first contribution
2470 * linked to a recurring contribution. More recently that was changed to be the most recent.
2471 * Ideally it would be an actual template - not a contribution used as a template which
2472 * would give more appropriate flexibility. Note line_items have an entity so that table
2473 * could be used for the line item template - the difficulty is the custom fields...
2474 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2475 * to load the membership(s) referred to via line items in the template transactions. Any other
2476 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2477 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2478 * - membership_payment record
2479 * - civicrm_membership.contribution_recur_id
2481 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2482 * of historical processors since this has been handled 'forever' - specifically for paypal.
2483 * albeit by an even nastier mechanism than the current input override.
2484 * The count is out on how correct related entities wind up in this case.
2486 * @param CRM_Contribute_BAO_Contribution $contribution
2487 * @param array $input
2488 * @param array $contributionParams
2490 * @return bool|array
2491 * @throws CiviCRM_API3_Exception
2493 protected static function repeatTransaction(&$contribution, $input, $contributionParams) {
2494 if (!empty($contribution->id
)) {
2497 if (empty($contribution->id
)) {
2498 // Unclear why this would only be set for repeats.
2499 if (!empty($input['amount'])) {
2500 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2503 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2504 'id' => $contributionParams['contribution_recur_id'],
2506 if (!empty($recurringContribution['financial_type_id'])) {
2507 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2508 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2510 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2511 $contributionParams['contribution_recur_id'],
2512 array_intersect_key($contributionParams, [
2513 'total_amount' => TRUE,
2514 'financial_type_id' => TRUE,
2517 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2518 $contributionParams['status_id'] = 'Pending';
2520 if (isset($contributionParams['financial_type_id']) && count($input['line_item']) === 1) {
2521 // We permit the financial type to be overridden for single line items.
2522 // More comments on this are in getTemplateTransaction.
2523 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2526 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2528 foreach (['contact_id', 'currency', 'source', 'amount_level', 'address_id'] as $fieldName) {
2529 if (isset($templateContribution[$fieldName])) {
2530 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2533 if (!empty($recurringContribution['campaign_id'])) {
2534 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2535 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2537 if (!isset($contributionParams['campaign_id']) && isset($templateContribution['campaign_id'])) {
2538 // Fall back on value from the previous contribution if not passed in as input
2539 // or loadable from the recurring contribution.
2540 $contributionParams['campaign_id'] = $templateContribution['campaign_id'];
2542 $contributionParams['source'] = $contributionParams['source'] ??
ts('Recurring contribution');
2544 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2545 //do not create CC or BCC emails or profile notifications.
2546 //The if is just to be safe. Not sure if we can ever arrive with this unset
2547 // but per CRM-19478 it seems it can be 'null'
2548 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2549 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2551 if (!empty($contribution->tax_amount
)) {
2552 $contributionParams['tax_amount'] = $contribution->tax_amount
;
2555 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2556 $contribution->id
= $createContribution['id'];
2557 $contribution->copyCustomFields($templateContribution['id'], $contribution->id
);
2558 self
::handleMembershipIDOverride($contribution->id
, $input);
2559 // Add new soft credit against current $contribution.
2560 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($contributionParams['contribution_recur_id'], $createContribution['id']);
2561 return $createContribution;
2566 * Get individual id for onbehalf contribution.
2568 * @param int $contributionId
2570 * @param int $contributorId
2574 * containing organization id and individual id
2576 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2580 if (!$contributionId) {
2584 // fetch contributor id if null
2585 if (!$contributorId) {
2586 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2587 $contributionId, 'contact_id'
2591 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2592 $activityTypeId = array_search('Contribution', $activityTypeIds);
2594 if ($activityTypeId && $contributorId) {
2596 SELECT civicrm_activity_contact.contact_id
2597 FROM civicrm_activity_contact
2598 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2599 WHERE civicrm_activity.activity_type_id = %1
2600 AND civicrm_activity.source_record_id = %2
2601 AND civicrm_activity_contact.record_type_id = %3
2604 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2605 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2608 1 => [$activityTypeId, 'Integer'],
2609 2 => [$contributionId, 'Integer'],
2610 3 => [$sourceID, 'Integer'],
2613 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2615 // for on behalf contribution source is individual and contributor is organization
2616 if ($sourceContactId && $sourceContactId != $contributorId) {
2617 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2618 // get rel type id for employee of relation
2619 foreach ($relationshipTypeIds as $id => $typeVals) {
2620 if ($typeVals['name_a_b'] == 'Employee of') {
2621 $relationshipTypeId = $id;
2626 $rel = new CRM_Contact_DAO_Relationship();
2627 $rel->relationship_type_id
= $relationshipTypeId;
2628 $rel->contact_id_a
= $sourceContactId;
2629 $rel->contact_id_b
= $contributorId;
2630 if ($rel->find(TRUE)) {
2631 $ids['individual_id'] = $rel->contact_id_a
;
2632 $ids['organization_id'] = $rel->contact_id_b
;
2643 public static function getContributionDates() {
2644 $config = CRM_Core_Config
::singleton();
2645 $currentMonth = date('m');
2646 $currentDay = date('d');
2647 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2648 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2649 (int ) $config->fiscalYearStart
['d'] > $currentDay
2652 $year = date('Y') - 1;
2657 $year = ['Y' => $year];
2658 $yearDate = $config->fiscalYearStart
;
2659 $yearDate = array_merge($year, $yearDate);
2660 $yearDate = CRM_Utils_Date
::format($yearDate);
2662 $monthDate = date('Ym') . '01';
2668 'yearDate' => $yearDate,
2669 'monthDate' => $monthDate,
2674 * Load objects relations to contribution object.
2675 * Objects are stored in the $_relatedObjects property
2676 * In the first instance we are just moving functionality from BASEIpn -
2678 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2680 * Note that the unit test for the BaseIPN class tests this function
2682 * @param array $input
2683 * Input as delivered from Payment Processor.
2685 * Ids as Loaded by Payment Processor.
2686 * @param bool $loadAll
2687 * Load all related objects - even where id not passed in? (allows API to call this).
2690 * @throws CRM_Core_Exception
2692 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
2693 // @todo deprecate this function - the steps should be
2694 // 1) add additional functions like 'getRelatedMemberships'
2695 // 2) switch all calls that refer to ->_relatedObjects to
2696 // using the helper functions
2697 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2698 // 4) make ->_relatedObjects protected
2699 // 5) hone up the individual functions to not use rely on this having been called
2700 // 6) deprecate like mad
2702 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2703 if (empty($ids['contact']) && isset($this->contact_id
)) {
2704 $ids['contact'] = $this->contact_id
;
2707 if (empty($this->_component
)) {
2708 if (!empty($ids['event'])) {
2709 $this->_component
= 'event';
2712 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2716 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2717 // refactoring than anything else, and has unit test coverage.
2718 if (empty($this->financial_type_id
)) {
2722 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2727 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2728 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2729 $this->contribution_page_id
,
2732 if ($paymentProcessorID) {
2733 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2737 $ids['contributionType'] = $this->financial_type_id
;
2738 $ids['financialType'] = $this->financial_type_id
;
2739 if ($this->contribution_page_id
) {
2740 $ids['contributionPage'] = $this->contribution_page_id
;
2743 $this->loadRelatedEntitiesByID($ids);
2745 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2746 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2749 if (!empty($ids['pledge_payment'])) {
2750 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2751 if (empty($paymentID)) {
2754 $payment = new CRM_Pledge_BAO_PledgePayment();
2755 $payment->id
= $paymentID;
2756 if (!$payment->find(TRUE)) {
2757 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
2759 $this->_relatedObjects
['pledge_payment'][] = $payment;
2763 // These are probably no longer accessed from anywhere
2764 // @todo remove this line, after ensuring not used.
2765 $ids = $this->loadRelatedMembershipObjects($ids);
2767 if ($this->_component
!= 'contribute') {
2768 // we are in event mode
2769 // make sure event exists and is valid
2770 $event = new CRM_Event_BAO_Event();
2771 $event->id
= $ids['event'];
2772 if ($ids['event'] &&
2775 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
2778 $this->_relatedObjects
['event'] = &$event;
2780 $participant = new CRM_Event_BAO_Participant();
2781 $participant->id
= $ids['participant'];
2782 if ($ids['participant'] &&
2783 !$participant->find(TRUE)
2785 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
2787 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2789 $this->_relatedObjects
['participant'] = &$participant;
2791 // get the payment processor id from event - this is inaccurate see CRM-16923
2792 // in future we should look at throwing an exception here rather than an dubious guess.
2793 if (!$paymentProcessorID) {
2794 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2795 if ($paymentProcessorID) {
2796 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2801 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($this->id
);
2802 if (!empty($relatedContact['individual_id'])) {
2803 $ids['related_contact'] = $relatedContact['individual_id'];
2806 if ($paymentProcessorID) {
2807 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2808 $this->is_test ?
'test' : 'live'
2810 $ids['paymentProcessor'] = $paymentProcessorID;
2811 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2814 // Add contribution id to $ids. CRM-20401
2815 $ids['contribution'] = $this->id
;
2820 * Create array of message information - ie. return html version, txt version, to field
2822 * @param array $input
2823 * Incoming information.
2824 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2825 * just check presence of recur object but maintaining legacy approach
2828 * IDs of related objects.
2829 * @param array $values
2830 * Any values that may have already been compiled by calling process.
2831 * This is augmented by values 'gathered' by gatherMessageValues
2832 * @param bool $returnMessageText
2833 * Distinguishes between whether to send message or return.
2834 * message text. We are working towards this function ALWAYS returning message text & calling
2835 * function doing emails / pdfs with it
2841 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2842 $this->loadRelatedObjects($input, $ids);
2844 if (empty($this->_component
)) {
2845 $this->_component
= $input['component'] ??
NULL;
2848 //not really sure what params might be passed in but lets merge em into values
2849 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2850 $values['is_email_receipt'] = !$returnMessageText;
2851 foreach (['receipt_date', 'cc_receipt', 'bcc_receipt', 'receipt_from_name', 'receipt_from_email', 'receipt_text', 'pay_later_receipt'] as $fld) {
2852 if (!empty($input[$fld])) {
2853 $values[$fld] = $input[$fld];
2857 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2858 //what does recur 'mean here - to do with payment processor return functionality but
2859 // what is the importance
2860 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2861 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2863 $entityID = $entity = NULL;
2864 if (isset($ids['contribution'])) {
2865 $entity = 'contribution';
2866 $entityID = $ids['contribution'];
2868 if (!empty($ids['membership'])) {
2869 //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
2870 // 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
2871 // line having loaded an array
2872 $ids['membership'] = (array) $ids['membership'];
2873 $entity = 'membership';
2874 $entityID = $ids['membership'][0];
2877 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2878 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2879 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2881 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2882 //direct mode showing billing block, so use directIPN for temporary
2883 $template->assign('contributeMode', 'directIPN');
2886 // todo remove strtolower - check consistency
2887 if (strtolower($this->_component
) == 'event') {
2888 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2889 $values['event'] = [];
2891 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2893 //get location details
2895 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2896 'entity_table' => 'civicrm_event',
2898 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2901 'entity_table' => 'civicrm_event',
2902 'entity_id' => $ids['event'],
2903 'module' => 'CiviEvent',
2906 list($custom_pre_id,
2908 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2910 $values['custom_pre_id'] = $custom_pre_id;
2911 $values['custom_post_id'] = $custom_post_ids;
2912 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2913 //and cases involving status updation through ipn
2914 // whatever that means!
2915 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2916 // perhaps we should throw an e-notice if amount is set & force total_amount?
2917 if (!empty($input['amount'])) {
2918 $values['totalAmount'] = $input['amount'];
2920 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2921 if ($values['event']['is_email_confirm']) {
2922 $values['is_email_receipt'] = 1;
2925 if (!empty($ids['contribution'])) {
2926 $values['contributionId'] = $ids['contribution'];
2929 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2930 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2934 $values['contribution_id'] = $this->id
;
2935 if (!empty($ids['related_contact'])) {
2936 $values['related_contact'] = $ids['related_contact'];
2937 if (isset($ids['onbehalf_dupe_alert'])) {
2938 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2941 'contact_id' => $ids['contact'],
2942 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2943 'Home', 'id', 'name'
2946 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2947 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2950 if ($this->is_test
) {
2953 if (!empty($this->_relatedObjects
['membership'])) {
2954 foreach ($this->_relatedObjects
['membership'] as $membership) {
2955 if ($membership->id
) {
2956 $values['membership_id'] = $membership->id
;
2957 $values['isMembership'] = TRUE;
2958 $values['membership_assign'] = TRUE;
2960 // need to set the membership values here
2961 $template->assign('membership_name',
2962 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2964 $template->assign('mem_start_date', $membership->start_date
);
2965 $template->assign('mem_join_date', $membership->join_date
);
2966 $template->assign('mem_end_date', $membership->end_date
);
2967 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2968 $template->assign('mem_status', $membership_status);
2969 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2970 $values['is_pay_later'] = 1;
2972 // Pass amount to floatval as string '0.00' is considered a
2973 // valid amount and includes Fee section in the mail.
2974 if (isset($values['amount'])) {
2975 $values['amount'] = floatval($values['amount']);
2978 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2979 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2980 $template->assign('cancelSubscriptionUrl', $url);
2981 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2982 $template->assign('updateSubscriptionBillingUrl', $url);
2983 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2984 $template->assign('updateSubscriptionUrl', $url);
2987 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2990 // otherwise if its about sending emails, continue sending without return, as we
2991 // don't want to exit the loop.
2996 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3002 * Gather values for contribution mail - this function has been created
3003 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3004 * Values related to the contribution in question are gathered
3006 * @param array $input
3007 * Input into function (probably from payment processor).
3008 * @param array $values
3010 * The set of ids related to the input.
3013 * @throws \CRM_Core_Exception
3015 public function _gatherMessageValues($input, &$values, $ids = []) {
3016 // set display address of contributor
3017 $values['billingName'] = '';
3018 if ($this->address_id
) {
3019 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
3020 $addressDetails = reset($addressDetails);
3021 $values['billingName'] = $addressDetails['name'] ??
'';
3023 // Else we assign the billing address of the contribution contact.
3025 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
3026 $addressDetails = reset($addressDetails);
3028 $values['address'] = $addressDetails['display'] ??
'';
3030 if ($this->_component
=== 'contribute') {
3031 //get soft contributions
3032 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
3033 if (!empty($softContributions)) {
3034 // For pcp soft credit, there is no 'soft_credit' member it comes
3035 // back in different array members, but shortly after returning from
3036 // this function it calls _assignMessageVariablesToTemplate which does
3037 // its own lookup of any pcp soft credit, so we can skip it here.
3038 $values['softContributions'] = $softContributions['soft_credit'] ??
NULL;
3040 if (isset($this->contribution_page_id
)) {
3041 // This is a call we want to use less, in favour of loading related objects.
3042 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3043 if ($this->contribution_page_id
) {
3044 // This is precautionary as there are some legacy flows, but it should really be
3046 if (!isset($this->_relatedObjects
['contributionPage'])) {
3047 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
3049 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3052 // no contribution page -probably back office
3054 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3055 $values['title'] = 'Contribution';
3057 // set lineItem for contribution
3059 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3060 if (!empty($lineItems)) {
3061 $firstLineItem = reset($lineItems);
3063 if (!empty($firstLineItem['price_set_id'])) {
3064 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3065 'id' => $firstLineItem['price_set_id'],
3066 'return' => 'is_quick_config, id',
3068 $values['priceSetID'] = $priceSet['id'];
3070 foreach ($lineItems as &$eachItem) {
3071 if (isset($this->_relatedObjects
['membership'])
3072 && is_array($this->_relatedObjects
['membership'])
3073 && array_key_exists($eachItem['entity_id'] . '_' . $eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
3074 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->join_date
);
3075 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->start_date
);
3076 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->end_date
);
3078 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3079 // However, that does create upgrade pain so would be better to be phased in.
3080 $values['useForMember'] = empty($priceSet['is_quick_config']);
3082 $values['lineItem'][0] = $lineItems;
3086 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3090 // if this is onbehalf of contribution then set related contact
3091 if (!empty($relatedContact['individual_id'])) {
3092 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3096 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3099 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3102 foreach ($groupTree as $key => $group) {
3103 if ($key === 'info') {
3107 foreach ($group['fields'] as $k => $customField) {
3108 $groupLabel = $group['title'];
3109 if (!empty($customField['customValue'])) {
3110 foreach ($customField['customValue'] as $customFieldValues) {
3111 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
3116 $values['customGroup'] = $customGroup;
3118 $values['is_pay_later'] = $this->is_pay_later
;
3124 * Assign message variables to template but try to break the habit.
3126 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3127 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3128 * multiple recurring payments for processors like IATS that use tokens.
3130 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3131 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3132 * Note we send directly from this function in some cases because it is only partly refactored.
3134 * Don't call this function directly as the signature will change.
3138 * @param bool $returnMessageText
3142 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3143 // @todo - this should have a better separation of concerns - ie.
3144 // gatherMessageValues should build an array of values to be assigned to the template
3145 // and this function should assign them (assigning null if not set).
3146 // the way the pcpParams & honor Params section works is a baby-step towards this.
3147 $template = CRM_Core_Smarty
::singleton();
3148 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3149 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3150 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3151 $template->assign('billingName', $values['billingName']);
3153 // For some unit tests contribution cannot contain paymentProcessor information
3154 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3155 $template->assign('contributeMode', CRM_Core_SelectValues
::contributeMode()[$billingMode] ??
NULL);
3157 //assign honor information to receipt message
3158 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3161 'soft_credit_type' => NULL,
3162 'honor_block_is_active' => NULL,
3164 if (isset($softRecord['soft_credit'])) {
3165 //if id of contribution page is present
3166 if (!empty($values['id'])) {
3167 $values['honor'] = [
3168 'honor_profile_values' => [],
3169 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3170 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3173 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3174 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3177 //offline contribution
3178 $softCreditTypes = $softCredits = [];
3179 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3180 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3181 $softCredits[$key] = [
3182 'Name' => $softCredit['contact_name'],
3183 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3186 $template->assign('softCreditTypes', $softCreditTypes);
3187 $template->assign('softCredits', $softCredits);
3191 $dao = new CRM_Contribute_DAO_ContributionProduct();
3192 $dao->contribution_id
= $this->id
;
3193 if ($dao->find(TRUE)) {
3194 $premiumId = $dao->product_id
;
3195 $template->assign('option', $dao->product_option
);
3197 $productDAO = new CRM_Contribute_DAO_Product();
3198 $productDAO->id
= $premiumId;
3199 $productDAO->find(TRUE);
3200 $template->assign('selectPremium', TRUE);
3201 $template->assign('product_name', $productDAO->name
);
3202 $template->assign('price', $productDAO->price
);
3203 $template->assign('sku', $productDAO->sku
);
3205 $template->assign('title', $values['title'] ??
NULL);
3206 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3207 if (!$values['amount'] && isset($this->total_amount
)) {
3208 $values['amount'] = $this->total_amount
;
3213 'pcp_display_in_roll' => NULL,
3214 'pcp_roll_nickname' => NULL,
3215 'pcp_personal_note' => NULL,
3219 if (strtolower($this->_component
) == 'contribute') {
3221 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3222 $softDAO->contribution_id
= $this->id
;
3223 if ($softDAO->find(TRUE)) {
3224 $pcpParams['pcpBlock'] = TRUE;
3225 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3226 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3227 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3229 //assign the pcp page title for email subject
3230 $pcpDAO = new CRM_PCP_DAO_PCP();
3231 $pcpDAO->id
= $softDAO->pcp_id
;
3232 if ($pcpDAO->find(TRUE)) {
3233 $pcpParams['title'] = $pcpDAO->title
;
3237 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3238 $template->assign($templateKey, $templateValue);
3241 if ($this->financial_type_id
) {
3242 $values['financial_type_id'] = $this->financial_type_id
;
3245 $template->assign('trxn_id', $this->trxn_id
);
3246 $template->assign('receive_date',
3247 CRM_Utils_Date
::processDate($this->receive_date
)
3249 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3250 $template->assign('action', $this->is_test ?
1024 : 1);
3251 $template->assign('receipt_text', $values['receipt_text'] ??
NULL);
3252 $template->assign('is_monetary', 1);
3253 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3254 $template->assign('currency', $this->currency
);
3255 $template->assign('address', CRM_Utils_Address
::format($input));
3256 if (!empty($values['customGroup'])) {
3257 $template->assign('customGroup', $values['customGroup']);
3259 if (!empty($values['softContributions'])) {
3260 $template->assign('softContributions', $values['softContributions']);
3262 if ($this->_component
== 'event') {
3263 $template->assign('title', $values['event']['title']);
3264 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3266 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3267 $viewRoles[] = $participantRoles[$v];
3269 $values['event']['participant_role'] = implode(', ', $viewRoles);
3270 $template->assign('event', $values['event']);
3271 $template->assign('participant', $values['participant']);
3272 $template->assign('location', $values['location']);
3273 $template->assign('customPre', $values['custom_pre_id']);
3274 $template->assign('customPost', $values['custom_post_id']);
3277 if ($this->_relatedObjects
['participant']->is_test
) {
3281 $values['params'] = [];
3282 //to get email of primary participant.
3283 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3284 $primaryAmount[] = [
3285 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3286 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3288 //build an array of cId/pId of participants
3289 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3290 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3291 //send receipt to additional participant if exists
3292 if (count($additionalIDs)) {
3293 $template->assign('isPrimary', 0);
3294 $template->assign('customProfile', NULL);
3295 //set additionalParticipant true
3296 $values['params']['additionalParticipant'] = TRUE;
3297 foreach ($additionalIDs as $pId => $cId) {
3299 //to change the status pending to completed
3300 $additional = new CRM_Event_DAO_Participant();
3301 $additional->id
= $pId;
3302 $additional->contact_id
= $cId;
3303 $additional->find(TRUE);
3304 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3305 $additional->status_id
= 1;
3306 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3307 //if additional participant dont have email
3309 if (!$additionalParticipantInfo) {
3310 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3313 'label' => $additional->fee_level
,
3314 'amount' => $additional->fee_amount
,
3316 $primaryAmount[] = [
3317 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3318 'amount' => $additional->fee_amount
,
3320 $additional->save();
3321 $template->assign('amount', $amount);
3322 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3326 //build an array of custom profile and assigning it to template
3327 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3329 if (count($customProfile)) {
3330 $template->assign('customProfile', $customProfile);
3333 // for primary contact
3334 $values['params']['additionalParticipant'] = FALSE;
3335 $template->assign('isPrimary', 1);
3336 $template->assign('amount', $primaryAmount);
3337 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3338 if ($this->payment_instrument_id
) {
3339 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3340 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3342 // carry paylater, since we did not created billing,
3343 // so need to pull email from primary location, CRM-4395
3344 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3350 * Check whether payment processor supports
3351 * cancellation of contribution subscription
3353 * @param int $contributionId
3356 * @param bool $isNotCancelled
3360 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3361 $cacheKeyString = "$contributionId";
3362 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3364 static $supportsCancel = [];
3366 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3367 $supportsCancel[$cacheKeyString] = FALSE;
3368 $isCancelled = FALSE;
3370 if ($isNotCancelled) {
3371 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3374 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3375 if (!empty($paymentObject)) {
3376 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3379 return $supportsCancel[$cacheKeyString];
3383 * Check whether subscription is already cancelled.
3385 * @param int $contributionId
3389 * contribution status
3391 public static function isSubscriptionCancelled($contributionId) {
3393 SELECT cr.contribution_status_id
3394 FROM civicrm_contribution_recur cr
3395 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3396 WHERE con.id = %1 LIMIT 1";
3397 $params = [1 => [$contributionId, 'Integer']];
3398 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3399 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3400 if ($status == 'Cancelled') {
3407 * Create all financial accounts entry.
3409 * @param array $params
3410 * Contribution object, line item array and params for trxn.
3413 * @param array $financialTrxnValues
3415 * @return null|\CRM_Core_BAO_FinancialTrxn
3417 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3418 $skipRecords = $update = $return = $isRelatedId = FALSE;
3419 $isUpdate = !empty($params['prevContribution']);
3421 $additionalParticipantId = [];
3422 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3423 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3425 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3426 $entityId = $params['participant_id'];
3427 $entityTable = 'civicrm_participant';
3428 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3430 elseif (!empty($params['membership_id'])) {
3431 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3432 // are created off one contribution should be handled elsewhere
3433 $entityId = $params['membership_id'];
3434 $entityTable = 'civicrm_membership';
3437 $entityId = $params['contribution']->id
;
3438 $entityTable = 'civicrm_contribution';
3441 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3442 $isRelatedId = TRUE;
3445 $entityID[] = $entityId;
3446 if (!empty($additionalParticipantId)) {
3447 $entityID +
= $additionalParticipantId;
3449 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3450 if (empty($params['prevContribution'])) {
3454 $statusId = $params['contribution']->contribution_status_id
;
3456 // build line item array if its not set in $params
3457 if (empty($params['line_item']) ||
$additionalParticipantId) {
3458 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3461 if ($contributionStatus != 'Failed' &&
3462 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3464 $skipRecords = TRUE;
3469 if (in_array($contributionStatus, $pendingStatus)) {
3470 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3471 $params['financial_type_id'],
3472 'Accounts Receivable Account is'
3475 elseif (!empty($params['payment_processor'])) {
3476 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3477 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3478 'id' => $params['payment_processor'],
3479 'return' => 'payment_instrument_id',
3482 elseif (!empty($params['payment_instrument_id'])) {
3483 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3485 // dev/financial#160 - If this is a contribution update, also check for an existing payment_instrument_id.
3486 elseif ($isUpdate && $params['prevContribution']->payment_instrument_id
) {
3487 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount((int) $params['prevContribution']->payment_instrument_id
);
3490 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3491 $queryParams = [1 => [$relationTypeId, 'Integer']];
3492 $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);
3495 $totalAmount = $params['total_amount'] ??
NULL;
3496 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3497 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3499 //build financial transaction params
3501 'contribution_id' => $params['contribution']->id
,
3502 'to_financial_account_id' => $params['to_financial_account_id'],
3503 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3504 'total_amount' => $totalAmount,
3505 'fee_amount' => $params['fee_amount'] ??
NULL,
3506 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3507 'currency' => $params['contribution']->currency
,
3508 'trxn_id' => $params['contribution']->trxn_id
,
3509 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3510 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3511 // this should really default to completed (after discussion).
3512 'status_id' => $statusId,
3513 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3514 'check_number' => $params['check_number'] ??
NULL,
3515 'pan_truncation' => $params['pan_truncation'] ??
NULL,
3516 'card_type_id' => $params['card_type_id'] ??
NULL,
3518 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3519 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3520 if (isset($params['refund_trxn_id'])) {
3521 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3522 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3525 //CRM-16259, set is_payment flag for non pending status
3526 if (!in_array($contributionStatus, $pendingStatus)) {
3527 $trxnParams['is_payment'] = 1;
3529 if (!empty($params['payment_processor'])) {
3530 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3533 if (isset($fromFinancialAccountId)) {
3534 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3537 // consider external values passed for recording transaction entry
3538 if (!empty($financialTrxnValues)) {
3539 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3541 if (empty($trxnParams['payment_processor_id'])) {
3542 unset($trxnParams['payment_processor_id']);
3545 $params['trxnParams'] = $trxnParams;
3549 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3550 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3551 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3552 if (!isset($params['trxnParams']['trxn_id'])) {
3553 // Actually I have no idea why we are overwriting any values from the previous contribution.
3554 // (filling makes sense to me). However, only protecting this value as I really really know we
3555 // don't want this one overwritten.
3557 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3559 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3561 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3562 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3563 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3565 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3566 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3569 //if financial type is changed
3570 if (!empty($params['financial_type_id']) &&
3571 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3573 $accountRelationship = 'Income Account is';
3574 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3575 $accountRelationship = 'Deferred Revenue Account is';
3577 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3578 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3579 if ($oldFinancialAccount != $newFinancialAccount) {
3580 $params['total_amount'] = 0;
3581 // If we have a fee amount set reverse this as well.
3582 if (isset($params['fee_amount'])) {
3583 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3585 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3586 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3587 $params['prevContribution']->financial_type_id
, $accountRelationship);
3590 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3591 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3592 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3595 self
::updateFinancialAccounts($params, 'changeFinancialType');
3596 $params['skipLineItem'] = FALSE;
3597 foreach ($params['line_item'] as &$lineItems) {
3598 foreach ($lineItems as &$line) {
3599 $line['financial_type_id'] = $params['financial_type_id'];
3602 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3603 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3604 $params['financial_account_id'] = $newFinancialAccount;
3605 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3606 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3607 if (isset($params['fee_amount'])) {
3608 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3610 self
::updateFinancialAccounts($params);
3611 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3612 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3614 $params['deferred_financial_account_id'] = $newFinancialAccount;
3618 //Update contribution status
3619 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3620 if (!isset($params['refund_trxn_id'])) {
3621 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3622 // gets preference over another so I am only 'protecting' a very specific tested flow
3623 // and letting natural justice take care of the rest.
3624 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3626 if (!empty($params['contribution_status_id']) &&
3627 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3629 //Update Financial Records
3630 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3631 if ($callUpdateFinancialAccounts) {
3632 self
::updateFinancialAccounts($params, 'changedStatus');
3633 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3638 // change Payment Instrument for a Completed contribution
3639 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3640 // instrument is null and now new payment instrument is added along with the payment
3641 if (!$params['contribution']->payment_instrument_id
) {
3642 $params['contribution']->find(TRUE);
3644 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3645 $params['trxnParams']['check_number'] = $params['check_number'] ??
NULL;
3647 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3648 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3651 //if Change contribution amount
3652 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ??
NULL;
3653 $params['trxnParams']['net_amount'] = $params['net_amount'] ??
NULL;
3654 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3655 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3656 if (isset($totalAmount) &&
3657 $totalAmount != $params['prevContribution']->total_amount
3659 //Update Financial Records
3660 $params['trxnParams']['from_financial_account_id'] = NULL;
3661 self
::updateFinancialAccounts($params, 'changedAmount');
3662 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3667 // Looks like we might have a data correction update.
3668 // This would be a case where a transaction id has been entered but it is incorrect &
3669 // the person goes back in & fixes it, as opposed to a new transaction.
3670 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3671 // the data fix scenario.
3673 if (isset($params['refund_trxn_id'])) {
3674 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3675 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3676 civicrm_api3('FinancialTrxn', 'create', [
3677 'id' => $refundIDs['financialTrxnId'],
3678 'trxn_id' => $params['refund_trxn_id'],
3682 $cardType = $params['card_type_id'] ??
NULL;
3683 $panTruncation = $params['pan_truncation'] ??
NULL;
3684 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3689 // records finanical trxn and entity financial trxn
3690 // also make it available as return value
3691 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3692 $trxnParams['pan_truncation'] = $params['pan_truncation'] ??
NULL;
3693 $trxnParams['card_type_id'] = $params['card_type_id'] ??
NULL;
3694 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3695 $params['entity_id'] = $financialTxn->id
;
3696 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3697 self
::$_trxnIDs[] = $financialTxn->id
;
3701 // record line items and financial items
3702 if (empty($params['skipLineItem'])) {
3703 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
3706 // create batch entry if batch_id is passed and
3707 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3708 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3710 'batch_id' => $params['batch_id'],
3711 'entity_table' => 'civicrm_financial_trxn',
3712 'entity_id' => $financialTxn->id
,
3714 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3717 // when a fee is charged
3718 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3719 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3722 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3723 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3725 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3726 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3727 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3729 unset($params['line_item']);
3730 self
::$_trxnIDs = NULL;
3735 * Update all financial accounts entry.
3737 * @param array $params
3738 * Contribution object, line item array and params for trxn.
3740 * @param string $context
3743 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3744 * adds unpredictability.
3747 public static function updateFinancialAccounts(&$params, $context = NULL) {
3749 $inputParams = $params;
3750 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3752 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3753 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3754 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3757 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3758 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3759 $params['entity_id'] = $trxn->id
;
3761 $itemParams['entity_table'] = 'civicrm_line_item';
3762 $trxnIds['id'] = $params['entity_id'];
3763 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3764 foreach ($params['line_item'] as $fieldId => $fields) {
3765 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3770 * Is this contribution status a reversal.
3772 * If so we would expect to record a negative value in the financial_trxn table.
3774 * @param int $status_id
3778 public static function isContributionStatusNegative($status_id) {
3779 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3780 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3784 * Check status validation on update of a contribution.
3786 * @param array $values
3787 * Previous form values before submit.
3789 * @param array $fields
3790 * The input form values.
3792 * @param array $errors
3797 public static function checkStatusValidation($values, &$fields, &$errors) {
3798 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3799 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3800 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3804 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3806 'Cancelled' => ['Completed', 'Refunded'],
3807 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3808 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3809 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3810 'Refunded' => ['Cancelled', 'Completed'],
3811 'Partially paid' => ['Completed'],
3812 'Pending refund' => ['Completed', 'Refunded'],
3813 'Failed' => ['Pending'],
3816 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3817 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3819 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3820 1 => $contributionStatuses[$values['contribution_status_id']],
3821 2 => $contributionStatuses[$fields['contribution_status_id']],
3827 * Delete contribution of contact.
3829 * @see https://issues.civicrm.org/jira/browse/CRM-12155
3831 * @param int $contactId
3835 public static function deleteContactContribution($contactId) {
3836 $contribution = new CRM_Contribute_DAO_Contribution();
3837 $contribution->contact_id
= $contactId;
3838 $contribution->find();
3839 while ($contribution->fetch()) {
3840 self
::deleteContribution($contribution->id
);
3845 * Get options for a given contribution field.
3847 * @param string $fieldName
3848 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3849 * @param array $props whatever is known about this dao object.
3851 * @return array|bool
3852 * @see CRM_Core_DAO::buildOptions
3855 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3856 $className = __CLASS__
;
3858 if (isset($props['orderColumn'])) {
3859 $params['orderColumn'] = $props['orderColumn'];
3861 switch ($fieldName) {
3862 // This field is not part of this object but the api supports it
3863 case 'payment_processor':
3864 $className = 'CRM_Contribute_BAO_ContributionPage';
3865 // Filter results by contribution page
3866 if (!empty($props['contribution_page_id'])) {
3867 $page = civicrm_api('contribution_page', 'getsingle', [
3869 'id' => ($props['contribution_page_id']),
3871 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3872 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3876 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3877 case 'honor_type_id':
3878 $className = 'CRM_Contribute_BAO_ContributionSoft';
3879 $fieldName = 'soft_credit_type_id';
3880 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3883 case 'contribution_status_id':
3884 if ($context !== 'validate') {
3885 $params['condition'] = "v.name <> 'Template'";
3888 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3892 * Validate financial type.
3894 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3896 * @param int $financialTypeId
3897 * Financial Type id.
3899 * @param string $relationName
3901 * @return array|bool
3903 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3904 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3906 if (!$financialAccount) {
3907 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3913 * @param int $targetCid
3914 * @param $activityType
3915 * @param string $title
3916 * @param int $contributionId
3917 * @param string $totalAmount
3918 * @param string $currency
3919 * @param string $trxn_date
3921 * @throws \CRM_Core_Exception
3922 * @throws \CiviCRM_API3_Exception
3924 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3925 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3926 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3927 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3928 // source record id would be the contribution id
3929 $srcRecId = $contributionId;
3933 'source_contact_id' => $targetCid,
3934 'source_record_id' => $srcRecId,
3935 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3936 'subject' => $subject,
3937 'activity_date_time' => $date,
3938 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3939 'skipRecentView' => TRUE,
3942 // create activity with target contacts
3943 $session = CRM_Core_Session
::singleton();
3944 $id = $session->get('userID');
3946 $activityParams['source_contact_id'] = $id;
3947 $activityParams['target_contact_id'][] = $targetCid;
3949 civicrm_api3('Activity', 'create', $activityParams);
3953 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3956 * @param string $component
3957 * @param bool $getTrxnInfo
3961 * @throws \CRM_Core_Exception
3962 * @throws \CiviCRM_API3_Exception
3964 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
3965 // @todo deprecate passing in component - always call with contribution.
3966 if ($component == 'event') {
3967 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3969 if (!$contributionId) {
3970 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3971 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3972 $id = $primaryParticipantId;
3974 if (!$contributionId) {
3979 elseif ($component == 'membership') {
3980 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
3983 $contributionId = $id;
3986 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
3987 // but need to unpick the whole trxn_id it's returning first.
3988 $oldCalculation = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3989 $baseTrxnId = !empty($oldCalculation['trxn_id']) ?
$oldCalculation['trxn_id'] : NULL;
3991 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3992 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3994 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3996 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
3998 $contribution = civicrm_api3('Contribution', 'getsingle', [
3999 'id' => $contributionId,
4003 'contribution_status_id',
4004 'financial_type_id',
4008 $info['payLater'] = $contribution['is_pay_later'];
4009 $info['contribution_status'] = $contribution['contribution_status'];
4010 $info['currency'] = $contribution['currency'];
4012 $info['total'] = $total;
4013 $info['paid'] = $total - $paymentBalance;
4014 $info['balance'] = $paymentBalance;
4016 $info['component'] = $component;
4017 if ($getTrxnInfo && $baseTrxnId) {
4018 $info['transaction'] = self
::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
4021 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4026 * Get the outstanding balance on a contribution.
4028 * @param int $contributionId
4029 * @param float $contributionTotal
4030 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4034 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4035 if ($contributionTotal === NULL) {
4036 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4039 return (float) CRM_Utils_Money
::subtractCurrencies(
4041 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
4042 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4047 * Get the tax amount (misnamed function).
4049 * @param array $params
4052 * @throws \CiviCRM_API3_Exception
4054 protected static function checkTaxAmount($params) {
4055 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4057 // Update contribution.
4058 if (!empty($params['id'])) {
4059 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4060 // there are no tax implications - early return.
4061 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4064 if (empty($params['prevContribution'])) {
4065 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4068 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4069 if (!isset($params[$field])) {
4070 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4071 // Tax amount gets added back on later....
4072 $params['total_amount'] = $params['prevContribution']->total_amount
-
4073 $params['prevContribution']->tax_amount
;
4076 $params[$field] = $params['prevContribution']->$field;
4077 if ($params[$field] != $params['prevContribution']->$field) {
4083 self
::calculateMissingAmountParams($params, $params['id']);
4084 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4085 // Assign tax Amount on update of contribution
4086 if (!empty($params['prevContribution']->tax_amount
)) {
4087 $params['tax_amount'] = 'null';
4088 foreach ($params['line_item'] as $setID => $priceField) {
4089 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4090 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4097 // New Contribution and update of contribution with tax rate financial type
4098 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4099 empty($params['skipLineItem'])) {
4100 $taxRateParams = $taxRates[$params['financial_type_id']];
4101 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4102 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4104 foreach ($params['line_item'] as $setID => $priceField) {
4105 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4106 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4109 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4111 elseif (isset($params['api.line_item.create'])) {
4112 // Update total amount of contribution using lineItem
4113 $taxAmountArray = [];
4114 foreach ($params['api.line_item.create'] as $key => $value) {
4115 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4116 $taxRate = $taxRates[$value['financial_type_id']];
4117 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4118 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4121 $params['tax_amount'] = array_sum($taxAmountArray);
4122 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4129 * Check financial type validation on update of a contribution.
4131 * @param int $financialTypeId
4132 * Value of latest Financial Type.
4134 * @param int $contributionId
4137 * @param array $errors
4142 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4143 if (!empty($financialTypeId)) {
4144 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4145 if ($oldFinancialTypeId == $financialTypeId) {
4149 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4151 '1' => [$contributionId, 'Integer'],
4153 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4154 if ($result->N
> 1) {
4155 $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.');
4160 * Update related pledge payment payments.
4162 * This function has been refactored out of the back office contribution form and may
4163 * still overlap with other functions.
4165 * @param string $action
4166 * @param int $pledgePaymentID
4167 * @param int $contributionID
4168 * @param bool $adjustTotalAmount
4169 * @param float $total_amount
4170 * @param float $original_total_amount
4171 * @param int $contribution_status_id
4172 * @param int $original_contribution_status_id
4174 public static function updateRelatedPledge(
4180 $original_total_amount,
4181 $contribution_status_id,
4182 $original_contribution_status_id
4184 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4188 if ($pledgePaymentID) {
4189 //store contribution id in payment record.
4190 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4193 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4200 if (!$pledgePaymentID) {
4203 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4209 $updatePledgePaymentStatus = FALSE;
4211 // If either the status or the amount has changed we update the pledge status.
4212 if ($action & CRM_Core_Action
::ADD
) {
4213 $updatePledgePaymentStatus = TRUE;
4215 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4216 ($original_total_amount != $total_amount))
4218 $updatePledgePaymentStatus = TRUE;
4221 if ($updatePledgePaymentStatus) {
4222 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4224 $contribution_status_id,
4233 * Is there only one line item attached to the contribution.
4239 * @throws \CiviCRM_API3_Exception
4241 public static function isSingleLineItem($id) {
4242 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4243 return ($lineItemCount == 1);
4247 * Complete an order.
4249 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4251 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4253 * Moving it out of the BaseIPN class is just the first step.
4255 * @param array $input
4257 * @param \CRM_Contribute_BAO_Contribution $contribution
4258 * @param bool $isPostPaymentCreate
4259 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4260 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4261 * transitioning related elements).
4264 * @throws \CRM_Core_Exception
4265 * @throws \CiviCRM_API3_Exception
4267 public static function completeOrder($input, $ids, $contribution, $isPostPaymentCreate = FALSE) {
4268 $transaction = new CRM_Core_Transaction();
4269 // @todo see if we even need this - it's used further down to create an activity
4270 // but the BAO layer should create that - we just need to add a test to cover it & can
4271 // maybe remove $ids altogether.
4272 $contributionContactID = $ids['related_contact'];
4273 $participantID = $ids['participant'];
4274 $recurringContributionID = $ids['contributionRecur'];
4276 // Unset ids just to make it clear it's not used again.
4278 // The previous details are used when calculating line items so keep it before any code that 'does something'
4279 if (!empty($contribution->id
)) {
4280 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4282 $inputContributionWhiteList = [
4287 'payment_instrument_id',
4292 'contribution_status_id',
4295 'financial_type_id',
4298 $paymentProcessorId = $input['payment_processor_id'] ??
NULL;
4300 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4302 $contributionParams = array_merge([
4303 'contribution_status_id' => $completedContributionStatusID,
4304 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4307 $contributionParams['payment_processor'] = $paymentProcessorId;
4309 if (empty($contributionParams['payment_instrument_id']) && $paymentProcessorId) {
4310 $contributionParams['payment_instrument_id'] = PaymentProcessor
::get(FALSE)->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id'];
4313 if ($recurringContributionID) {
4314 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4316 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4318 $contributionResult = self
::repeatTransaction($contribution, $input, $contributionParams);
4319 $contributionID = (int) $contribution->id
;
4321 if ($input['component'] == 'contribute') {
4322 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4323 self
::updateMembershipBasedOnCompletionOfContribution(
4330 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4331 $participantParams['id'] = $participantID;
4332 $participantParams['status_id'] = 'Registered';
4333 civicrm_api3('Participant', 'create', $participantParams);
4337 $contributionParams['id'] = $contributionID;
4338 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4340 if (!$contributionResult) {
4341 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4344 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4346 CRM_Core_Error
::debug_log_message('Contribution record updated successfully');
4347 $transaction->commit();
4349 // @todo - check if Contribution::create does this, test, remove.
4350 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contributionID, $recurringContributionID,
4351 $contributionParams['contribution_status_id'], $input['amount']);
4353 // create an activity record
4354 // @todo - check if Contribution::create does this, test, remove.
4355 if ($input['component'] == 'contribute') {
4357 $targetContactID = NULL;
4358 if ($contributionContactID) {
4359 $targetContactID = $contribution->contact_id
;
4360 $contribution->contact_id
= $contributionContactID;
4362 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution', $targetContactID);
4365 if (self
::isEmailReceipt($input, $contribution->contribution_page_id
, $recurringContributionID)) {
4366 civicrm_api3('Contribution', 'sendconfirmation', [
4367 'id' => $contributionID,
4368 'payment_processor_id' => $paymentProcessorId,
4370 CRM_Core_Error
::debug_log_message("Receipt sent");
4373 CRM_Core_Error
::debug_log_message("Success: Database updated");
4374 return $contributionResult;
4378 * Send receipt from contribution.
4380 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4382 * Note that the compose message part has been moved to contribution
4383 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4385 * @param array $input
4386 * Incoming data from Payment processor.
4388 * Related object IDs.
4389 * @param int $contributionID
4390 * @param bool $returnMessageText
4391 * Should text be returned instead of sent. This.
4392 * is because the function is also used to generate pdfs
4395 * @throws \CRM_Core_Exception
4396 * @throws \CiviCRM_API3_Exception
4397 * @throws \Exception
4399 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4401 $contribution = new CRM_Contribute_BAO_Contribution();
4402 $contribution->id
= $contributionID;
4403 if (!$contribution->find(TRUE)) {
4404 throw new CRM_Core_Exception('Contribution does not exist');
4406 $contribution->loadRelatedObjects($input, $ids, TRUE);
4407 // set receipt from e-mail and name in value
4408 if (!$returnMessageText) {
4409 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4411 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4412 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4413 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4414 civicrm_api3('Contribution', 'create', [
4415 'receipt_date' => 'now',
4416 'id' => $contribution->id
,
4423 * Generate From email and from name in an array values
4425 * @param array $input
4426 * @param \CRM_Contribute_BAO_Contribution $contribution
4430 public static function generateFromEmailAndName($input, $contribution) {
4431 // Use input value if supplied.
4432 if (!empty($input['receipt_from_email'])) {
4434 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4435 $input['receipt_from_email'],
4438 // if we are still empty see if we can use anything from a contribution page.
4440 if (!empty($contribution->contribution_page_id
)) {
4441 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4443 // if we are still empty see if we can use anything from a contribution page.
4444 if (!empty($pageValues['receipt_from_email'])) {
4446 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4447 $pageValues['receipt_from_email'],
4450 // If we are still empty fall back to the domain or logged in user information.
4451 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4455 * Load related memberships.
4459 * @return array $ids
4464 * Note that in theory it should be possible to retrieve these from the line_item table
4465 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4466 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4467 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4468 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4470 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4473 public function loadRelatedMembershipObjects($ids = []) {
4475 SELECT membership_id
4476 FROM civicrm_membership_payment
4477 WHERE contribution_id = %1 ";
4478 $params = [1 => [$this->id
, 'Integer']];
4479 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4481 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4482 while ($dao->fetch()) {
4483 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4484 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4488 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4489 foreach ($ids['membership'] as $id) {
4491 $membership = new CRM_Member_BAO_Membership();
4492 $membership->id
= $id;
4493 if (!$membership->find(TRUE)) {
4494 throw new Exception("Could not find membership record: $id");
4496 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4497 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4498 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4499 $this->_relatedObjects
['membership'][$membership->id
. '_' . $membership->membership_type_id
] = $membership;
4508 * Function use to store line item proportionally in in entity financial trxn table
4510 * @param array $trxnParams
4512 * @param int $trxnId
4514 * @param float $contributionTotalAmount
4516 * @throws \CiviCRM_API3_Exception
4518 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4519 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4520 if (!empty($lineItems)) {
4521 // get financial item
4522 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4524 'contribution_total_amount' => $contributionTotalAmount,
4525 'trxn_total_amount' => $trxnParams['total_amount'],
4526 'trxn_id' => $trxnId,
4528 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4533 * Checks if line items total amounts
4534 * match the contribution total amount.
4536 * @param array $params
4537 * array of order params.
4539 * @throws \API_Exception
4541 public static function checkLineItems(&$params) {
4542 $totalAmount = $params['total_amount'] ??
NULL;
4543 $lineItemAmount = 0;
4545 foreach ($params['line_items'] as &$lineItems) {
4546 foreach ($lineItems['line_item'] as &$item) {
4547 if (empty($item['financial_type_id'])) {
4548 $item['financial_type_id'] = $params['financial_type_id'];
4550 $lineItemAmount +
= $item['line_total'] +
($item['tax_amount'] ??
0.00);
4554 if (!isset($totalAmount)) {
4555 $params['total_amount'] = $lineItemAmount;
4558 $currency = $params['currency'] ?? CRM_Core_Config
::singleton()->defaultCurrency
;
4560 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4561 throw new CRM_Contribute_Exception_CheckLineItemsException();
4567 * Get the financial account for the item associated with the new transaction.
4569 * @param array $params
4570 * @param int $default
4574 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4576 if (!empty($params['financial_account_id'])) {
4577 return $params['financial_account_id'];
4580 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4581 $preferredAccountsRelationships = [
4582 'Refunded' => 'Credit/Contra Revenue Account is',
4583 'Chargeback' => 'Chargeback Account is',
4586 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4587 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4588 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4590 $preferredAccountsRelationships[$contributionStatus]
4598 * ContributionPage values were being imposed onto values.
4600 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4601 * REALLY didn't want superimposed. The rest are left there in their overkill out
4604 * The rationale for making this explicit is that it was a case of carefully set values being
4605 * seemingly randonly overwritten without much care. In general I think array randomly setting
4606 * variables en mass is risky.
4608 * @param array $values
4612 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4613 $contributionPageValues = [];
4614 CRM_Contribute_BAO_ContributionPage
::setValues(
4615 $this->contribution_page_id
,
4616 $contributionPageValues
4619 // These are the values that I believe to be useful.
4622 'pay_later_receipt',
4624 'receipt_from_email',
4625 'receipt_from_name',
4629 'honoree_profile_id',
4630 'onbehalf_profile_id',
4631 'honor_block_is_active',
4632 // Kinda might be - but would be on the contribution...
4635 // Included for 'fear of regression' but can't justify any use for these....
4637 'payment_processor',
4638 'financial_type_id',
4639 'amount_block_is_active',
4644 'default_amount_id',
4648 'initial_amount_help_text',
4649 'initial_amount_label',
4651 'is_allow_other_amount',
4652 'is_billing_required',
4653 'is_confirm_enabled',
4654 'is_credit_card_only',
4656 'is_partial_payment',
4657 'is_recur_installments',
4658 'is_recur_interval',
4662 'min_initial_amount',
4663 'recur_frequency_unit',
4670 foreach ($valuesToCopy as $valueToCopy) {
4671 if (isset($contributionPageValues[$valueToCopy])) {
4672 if ($valueToCopy === 'title') {
4673 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
4676 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4684 * Get values of CiviContribute Settings
4685 * and check if its enabled or not.
4686 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4687 * in serialized form. Usually this should be stored as flat settings for each form fields
4688 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4689 * settings we will live with an inconsistency because it's too hard to change for now.
4690 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4693 * @param string $name
4698 public static function checkContributeSettings($name) {
4699 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
4700 return $contributeSettings[$name] ??
NULL;
4704 * Get the contribution as it is in the database before being updated.
4706 * @param int $contributionID
4708 * @return \CRM_Contribute_BAO_Contribution|null
4710 private static function getOriginalContribution($contributionID) {
4711 return self
::getValues(['id' => $contributionID]);
4715 * Get the amount for the financial item row.
4717 * Helper function to start to break down recordFinancialTransactions for readability.
4719 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
4721 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
4722 * for historical reasons. Going forwards we can hope to add tests & improve readibility
4725 * @param array $params
4726 * Params as passed to contribution.create
4728 * @param string $context
4729 * changeFinancialType| changedAmount
4730 * @param array $lineItemDetails
4732 * @param bool $isARefund
4733 * Is this a refund / negative transaction.
4734 * @param int $previousLineItemTotal
4737 * @todo move recordFinancialAccounts & helper functions to their own class?
4740 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
4741 if ($context == 'changedAmount') {
4742 $lineTotal = $lineItemDetails['line_total'];
4743 if ($lineTotal != $previousLineItemTotal) {
4744 $lineTotal -= $previousLineItemTotal;
4748 elseif ($context == 'changeFinancialType') {
4749 return -$lineItemDetails['line_total'];
4751 elseif ($context == 'changedStatus') {
4752 $cancelledTaxAmount = 0;
4754 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
4756 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
4758 elseif ($context === NULL) {
4759 // erm, yes because? but, hey, it's tested.
4760 return $lineItemDetails['line_total'];
4762 elseif (empty($lineItemDetails['line_total'])) {
4763 // follow legacy code path
4765 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
4766 return $params['total_amount'];
4769 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
4774 * Get the multiplier for adjusting rows.
4776 * If we are dealing with a refund or cancellation then it will be a negative
4777 * amount to reflect the negative transaction.
4779 * If we are changing Financial Type it will be a negative amount to
4780 * adjust down the old type.
4782 * @param int $contribution_status_id
4783 * @param string $context
4787 protected static function getMultiplier($contribution_status_id, $context) {
4788 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
4795 * Does this transaction reflect a payment instrument change.
4797 * @param array $params
4798 * @param array $pendingStatuses
4802 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
4803 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
4805 if (array_key_exists('payment_instrument_id', $params)) {
4806 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
4807 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
4809 //check if status is changed from Pending to Completed
4810 // do not update payment instrument changes for Pending to Completed
4811 if (!($contributionStatus == 'Completed' &&
4812 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
4817 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
4818 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
4819 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
4823 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
4824 $params['contribution']->check_number
!= $params['prevContribution']->check_number
4826 // another special case when check number is changed, create new financial records
4827 // create financial trxn with negative amount
4835 * Update the memberships associated with a contribution if it has been completed.
4837 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
4838 * load them in this function. Code clean up would compensate for any minor performance implication.
4840 * @param int $contributionID
4841 * @param string $changeDate
4843 * @throws \CRM_Core_Exception
4844 * @throws \CiviCRM_API3_Exception
4846 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
4847 $memberships = self
::getRelatedMemberships($contributionID);
4848 foreach ($memberships as $membership) {
4849 $membershipParams = [
4850 'id' => $membership['id'],
4851 'contact_id' => $membership['contact_id'],
4852 'is_test' => $membership['is_test'],
4853 'membership_type_id' => $membership['membership_type_id'],
4854 'membership_activity_status' => 'Completed',
4857 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4858 $membershipParams['membership_type_id'],
4859 $membershipParams['is_test'],
4860 $membershipParams['id']
4863 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4864 // this picks up membership type changes during renewals
4865 // @todo this is almost certainly an obsolete sql call, the pre-change
4866 // membership is accessible via $this->_relatedObjects
4868 SELECT membership_type_id
4869 FROM civicrm_membership_log
4870 WHERE membership_id={$membershipParams['id']}
4873 $dao = CRM_Core_DAO
::executeQuery($sql);
4874 if ($dao->fetch()) {
4875 if (!empty($dao->membership_type_id
)) {
4876 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4879 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
4880 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
4881 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
4882 // 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.
4883 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
4884 // @todo once apiv4 ships with core switch to that & find sanity.
4885 $membershipParams['num_terms'] = self
::getNumTermsByContributionAndMembershipType(
4886 $membershipParams['membership_type_id'],
4890 // @todo remove all this stuff in favour of letting the api call further down handle in
4891 // (it is a duplication of what the api does).
4892 $dates = array_fill_keys([
4897 if ($currentMembership) {
4899 * Fixed FOR CRM-4433
4900 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4901 * when Contribution mode is notify and membership is for renewal )
4903 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
4905 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4907 // @todo - we should pass membership_type_id instead of null here but not
4908 // adding as not sure of testing
4909 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4910 $changeDate, NULL, $membershipParams['num_terms']
4912 $dates['join_date'] = $currentMembership['join_date'];
4915 //get the status for membership.
4916 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4918 $dates['join_date'],
4921 $membershipParams['membership_type_id'],
4925 unset($dates['end_date']);
4926 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4927 //we might be renewing membership,
4928 //so make status override false.
4929 $membershipParams['is_override'] = FALSE;
4930 $membershipParams['status_override_end_date'] = 'null';
4931 civicrm_api3('Membership', 'create', $membershipParams);
4936 * Get payment links as they relate to a contribution.
4938 * If a payment can be made then include a payment link & if a refund is appropriate
4939 * then a refund link.
4942 * @param float $balance
4943 * @param string $contributionStatus
4946 * $actionLinks Links array containing:
4950 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
4951 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
4952 // In general the balance is the best way to determine if a payment can be added or not,
4953 // but not for Failed contributions, where we don't accept additional payments at the moment.
4954 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
4955 // do accept more payments agains them.
4960 'url' => CRM_Utils_System
::url('civicrm/payment', [
4966 'title' => ts('Record Payment'),
4969 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
4971 'url' => CRM_Utils_System
::url('civicrm/payment', [
4978 'title' => ts('Submit Credit Card payment'),
4982 'url' => CRM_Utils_System
::url('civicrm/payment', [
4988 'title' => ts('Record Refund'),
4990 return $actionLinks;
4994 * Get a query to determine the amount donated by the contact/s in the current financial year.
4996 * @param array $contactIDs
5000 public static function getAnnualQuery($contactIDs) {
5001 $contactIDs = implode(',', $contactIDs);
5002 $config = CRM_Core_Config
::singleton();
5003 $currentMonth = date('m');
5004 $currentDay = date('d');
5006 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5008 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5009 (int) $config->fiscalYearStart
['d'] > $currentDay
5012 $year = date('Y') - 1;
5017 $nextYear = $year +
1;
5019 if ($config->fiscalYearStart
) {
5020 $newFiscalYearStart = $config->fiscalYearStart
;
5021 if ($newFiscalYearStart['M'] < 10) {
5022 // This is just a clumsy way of adding padding.
5023 // @todo next round look for a nicer way.
5024 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5026 if ($newFiscalYearStart['d'] < 10) {
5027 // This is just a clumsy way of adding padding.
5028 // @todo next round look for a nicer way.
5029 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5031 $config->fiscalYearStart
= $newFiscalYearStart;
5032 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5035 // First of January.
5038 $startDate = "$year$monthDay";
5039 $endDate = "$nextYear$monthDay";
5042 'contact_id' => 'IN (' . $contactIDs . ')',
5043 'is_test' => ' = 0',
5044 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5046 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5047 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5050 foreach ($whereClauses as $key => $clause) {
5051 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5053 $whereClauseString = implode(' AND ', $clauses);
5055 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5056 // this group by + having on contribution_status_id improves performance
5058 SELECT COUNT(*) as count,
5059 SUM(total_amount) as amount,
5060 AVG(total_amount) as average,
5062 FROM civicrm_contribution b
5063 WHERE " . $whereClauseString . "
5064 GROUP BY currency, contribution_status_id
5065 HAVING $havingClause
5071 * Assign Test Value.
5073 * @param string $fieldName
5074 * @param array $fieldDef
5075 * @param int $counter
5077 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5078 if ($fieldName == 'tax_amount') {
5079 $this->{$fieldName} = "0.00";
5081 elseif ($fieldName == 'net_amount') {
5082 $this->{$fieldName} = "2.00";
5084 elseif ($fieldName == 'total_amount') {
5085 $this->{$fieldName} = "3.00";
5087 elseif ($fieldName == 'fee_amount') {
5088 $this->{$fieldName} = "1.00";
5091 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5096 * Check if contribution has participant/membership payment.
5098 * @param int $contributionId
5103 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5104 // get line item for contribution
5105 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5106 // check if line item is for membership or participant
5107 foreach ($lineItems as $items) {
5108 if ($items['entity_table'] == 'civicrm_participant') {
5112 elseif ($items['entity_table'] == 'civicrm_membership') {
5124 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5126 * @param array $trxnParams
5127 * Financial trxn params
5128 * @param array $contributionParams
5129 * Contribution Params
5133 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5134 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5137 $statusId = $contributionParams['contribution']->contribution_status_id
;
5138 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5139 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5140 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5141 // Return if contribution status is not completed.
5142 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5143 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5144 && $contributionParams['prevContribution']->is_pay_later
== 0
5150 $params = $trxnParams;
5151 $financialTypeID = !empty($contributionParams['financial_type_id']) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5152 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5153 $params['to_financial_account_id'] = $arAccountId;
5154 $params['status_id'] = array_search('Pending', $contributionStatuses);
5155 $params['is_payment'] = FALSE;
5156 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5157 self
::$_trxnIDs[] = $trxn->id
;
5158 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5162 * Calculate financial item amount when contribution is updated.
5164 * @param array $params
5165 * contribution params
5166 * @param array $amountParams
5168 * @param string $context
5172 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5173 if (!empty($params['is_quick_config'])) {
5174 $amount = $amountParams['item_amount'];
5176 $amount = $params['total_amount'];
5177 if ($context === NULL) {
5178 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5183 $amount = $amountParams['line_total'];
5184 if ($context == 'changedAmount') {
5185 $amount -= $amountParams['previous_line_total'];
5187 $amount *= $amountParams['diff'];
5193 * Retrieve Sales Tax Financial Accounts.
5199 public static function getSalesTaxFinancialAccounts() {
5200 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5201 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5202 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5203 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5204 $queryParams = [1 => [$accountRel, 'Integer']];
5205 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5206 $financialAccount = [];
5207 while ($dao->fetch()) {
5208 $financialAccount[$dao->id
] = $dao->id
;
5210 return $financialAccount;
5214 * Create tax entry in civicrm_entity_financial_trxn table.
5216 * @param array $entityParams
5218 * @param array $eftParams
5220 * @throws \CiviCRM_API3_Exception
5222 public static function createProportionalEntry($entityParams, $eftParams) {
5224 if ($entityParams['contribution_total_amount'] != 0) {
5225 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5227 // Record Entity Financial Trxn; CRM-20145
5228 $eftParams['amount'] = $paid;
5229 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5233 * Create array of last financial item id's.
5235 * @param int $contributionId
5239 public static function getLastFinancialItemIds($contributionId) {
5240 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5241 FROM civicrm_financial_item fi
5242 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5243 WHERE li.contribution_id = %1";
5244 $dao = CRM_Core_DAO
::executeQuery($sql, [
5250 $ftIds = $taxItems = [];
5251 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5252 while ($dao->fetch()) {
5253 /* if sales tax item*/
5254 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5255 $taxItems[$dao->price_field_value_id
] = [
5256 'financial_item_id' => $dao->id
,
5257 'amount' => $dao->tax_amount
,
5261 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5264 return [$ftIds, $taxItems];
5268 * Create proportional entries in civicrm_entity_financial_trxn.
5270 * @param array $entityParams
5272 * @param array $lineItems
5274 * @param array $ftIds
5276 * @param array $taxItems
5278 * @throws \CiviCRM_API3_Exception
5280 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5282 'entity_table' => 'civicrm_financial_item',
5283 'financial_trxn_id' => $entityParams['trxn_id'],
5285 foreach ($lineItems as $key => $value) {
5286 if ($value['qty'] == 0) {
5289 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5290 $entityParams['line_item_amount'] = $value['line_total'];
5291 self
::createProportionalEntry($entityParams, $eftParams);
5292 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5293 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5294 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5295 self
::createProportionalEntry($entityParams, $eftParams);
5301 * Load entities related to the contribution into $this->_relatedObjects.
5305 * @throws \CRM_Core_Exception
5307 protected function loadRelatedEntitiesByID($ids) {
5309 'contact' => 'CRM_Contact_BAO_Contact',
5310 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5311 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5312 'financialType' => 'CRM_Financial_BAO_FinancialType',
5313 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5315 foreach ($entities as $entity => $bao) {
5316 if (!empty($ids[$entity])) {
5317 $this->_relatedObjects
[$entity] = new $bao();
5318 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5319 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5320 throw new CRM_Core_Exception($entity . ' could not be loaded');
5327 * Function to replace contribution tokens.
5329 * @param array $contributionIds
5331 * @param string $subject
5333 * @param array $subjectToken
5335 * @param string $text
5337 * @param string $html
5339 * @param array $messageToken
5341 * @param bool $escapeSmarty
5344 * @throws \CiviCRM_API3_Exception
5346 public static function replaceContributionTokens(
5355 if (empty($contributionIds)) {
5358 $contributionDetails = [];
5359 foreach ($contributionIds as $id) {
5360 $result = self
::getContributionTokenValues($id, $messageToken);
5361 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5362 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5363 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5365 return $contributionDetails;
5369 * Get the contribution fields for $id and display labels where
5370 * appropriate (if the token is present).
5373 * @param array $messageToken
5376 public static function getContributionTokenValues($id, $messageToken) {
5380 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5381 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5382 if (!empty($messageToken)) {
5383 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5384 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5385 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5393 * Get invoice_number for contribution.
5395 * @param int $contributionID
5399 public static function getInvoiceNumber($contributionID) {
5400 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix')) {
5401 return $invoicePrefix . $contributionID;
5408 * Load the values needed for the event message.
5410 * @param int $eventID
5411 * @param int $participantID
5412 * @param int|null $contributionID
5415 * @throws \CRM_Core_Exception
5417 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5422 $values = ['event' => []];
5424 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5425 // add custom fields for event
5426 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5428 $eventCustomGroup = [];
5429 foreach ($eventGroupTree as $key => $group) {
5430 if ($key === 'info') {
5434 foreach ($group['fields'] as $k => $customField) {
5435 $groupLabel = $group['title'];
5436 if (!empty($customField['customValue'])) {
5437 foreach ($customField['customValue'] as $customFieldValues) {
5438 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5443 $values['event']['customGroup'] = $eventCustomGroup;
5445 //get participant details
5446 $participantParams = [
5447 'id' => $participantID,
5450 $values['participant'] = [];
5452 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5453 // add custom fields for event
5454 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5455 $participantCustomGroup = [];
5456 foreach ($participantGroupTree as $key => $group) {
5457 if ($key === 'info') {
5461 foreach ($group['fields'] as $k => $customField) {
5462 $groupLabel = $group['title'];
5463 if (!empty($customField['customValue'])) {
5464 foreach ($customField['customValue'] as $customFieldValues) {
5465 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5470 $values['participant']['customGroup'] = $participantCustomGroup;
5472 //get location details
5474 'entity_id' => $eventID,
5475 'entity_table' => 'civicrm_event',
5477 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5480 'entity_table' => 'civicrm_event',
5481 'entity_id' => $eventID,
5482 'module' => 'CiviEvent',
5485 list($custom_pre_id,
5487 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5489 $values['custom_pre_id'] = $custom_pre_id;
5490 $values['custom_post_id'] = $custom_post_ids;
5492 // set lineItem for event contribution
5493 if ($contributionID) {
5494 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5495 if (!empty($participantIds)) {
5496 foreach ($participantIds as $pIDs) {
5497 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5498 if (!CRM_Utils_System
::isNull($lineItem)) {
5499 $values['lineItem'][] = $lineItem;