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\Participant
;
16 use Civi\Api4\PaymentProcessor
;
21 * @copyright CiviCRM LLC https://civicrm.org/licensing
23 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
26 * Static field for all the contribution information that we can potentially import
30 public static $_importableFields = NULL;
33 * Static field for all the contribution information that we can potentially export
37 public static $_exportableFields = NULL;
40 * Static field to hold financial trxn id's.
44 public static $_trxnIDs = NULL;
47 * Field for all the objects related to this contribution
49 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
51 public $_relatedObjects = [];
54 * Field for the component - either 'event' (participant) or 'contribute'
55 * (any item related to a contribution page e.g. membership, pledge, contribution)
56 * This is used for composing messages because they have dependency on the
57 * contribution_page or event page - although over time we may eliminate that
60 * "contribution"\"event"
62 public $_component = NULL;
65 * Possibly obsolete variable.
67 * If you use it please explain why it is set in the create function here.
71 public $trxn_result_code;
76 public function __construct() {
77 parent
::__construct();
81 * Takes an associative array and creates a contribution object.
83 * the function extract all the params it needs to initialize the create a
84 * contribution object. the params array could contain additional unused name/value
87 * @param array $params
88 * (reference ) an assoc array of name/value pairs.
90 * @return \CRM_Contribute_BAO_Contribution
91 * @throws \CRM_Core_Exception
92 * @throws \CiviCRM_API3_Exception
94 public static function add(&$params) {
99 $contributionID = $params['id'] ??
NULL;
100 $action = $contributionID ?
'edit' : 'create';
102 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
103 $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)]);
104 throw new CRM_Core_Exception($message);
107 //set defaults in create mode
108 if (!$contributionID) {
109 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
110 if (empty($params['invoice_number']) && CRM_Invoicing_Utils
::isInvoicingEnabled()) {
111 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
112 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
116 $contributionStatusID = $params['contribution_status_id'] ??
NULL;
117 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
118 CRM_Core_Error
::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
120 if (!$contributionStatusID) {
121 // Since the fee amount is expecting this (later on) ensure it is always set.
122 // It would only not be set for an update where it is unchanged.
123 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
124 'id' => $contributionID,
125 'return' => 'contribution_status_id',
128 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
131 && !empty($params['membership_id'])
132 && Civi
::settings()->get('deferred_revenue_enabled')
134 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
135 if ($memberStartDate) {
136 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
139 self
::calculateMissingAmountParams($params, $contributionID);
141 if (!empty($params['payment_instrument_id'])) {
142 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
143 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
144 $params['check_number'] = 'null';
148 $setPrevContribution = TRUE;
149 if ($contributionID && $setPrevContribution) {
150 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
152 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
154 if ($contributionID && !empty($params['revenue_recognition_date'])
155 && !($previousContributionStatus === 'Pending')
156 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
158 unset($params['revenue_recognition_date']);
161 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
162 isset($params['financial_type_id']))) {
163 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
166 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
168 $contribution = new CRM_Contribute_BAO_Contribution();
169 $contribution->copyValues($params);
171 $contribution->id
= $contributionID;
173 if (empty($contribution->id
)) {
174 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
175 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
176 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
180 $result = $contribution->save();
182 // Add financial_trxn details as part of fix for CRM-4724
183 $contribution->trxn_result_code
= $params['trxn_result_code'] ??
NULL;
184 $contribution->payment_processor
= $params['payment_processor'] ??
NULL;
186 //add Account details
187 $params['contribution'] = $contribution;
188 if (empty($params['is_post_payment_create'])) {
189 // If this is being called from the Payment.create api/ BAO then that Entity
190 // takes responsibility for the financial transactions. In fact calling Payment.create
191 // to add payments & having it call completetransaction and / or contribution.create
192 // to update related entities is the preferred flow.
193 // Note that leveraging this parameter for any other code flow is not supported and
194 // is likely to break in future and / or cause serious problems in your data.
195 // https://github.com/civicrm/civicrm-core/pull/14673
196 self
::recordFinancialAccounts($params);
199 if (self
::isUpdateToRecurringContribution($params)) {
200 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
201 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
203 $params['receive_date'] ??
NULL
207 $params['contribution_id'] = $contribution->id
;
209 if (!empty($params['custom']) &&
210 is_array($params['custom'])
212 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
215 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
217 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
222 * Is this contribution updating an existing recurring contribution.
224 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
225 * pending payment is being confirmed (or failing).
227 * @param array $params
231 public static function isUpdateToRecurringContribution($params) {
232 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
235 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
238 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
241 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
242 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
249 * Get defaults for new entity.
253 public static function getDefaults() {
255 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
256 FALSE, FALSE, FALSE, 'AND is_default = 1')
258 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
259 'receive_date' => date('Y-m-d H:i:s'),
264 * Fetch the object and store the values in the values array.
266 * @param array $params
267 * Input parameters to find object.
268 * @param array $values
269 * Output values of the object.
271 * The array that holds all the db ids.
273 * @return CRM_Contribute_BAO_Contribution|null
274 * The found object or null
276 public static function getValues($params, &$values = [], &$ids = []) {
277 if (empty($params)) {
280 $contribution = new CRM_Contribute_BAO_Contribution();
282 $contribution->copyValues($params);
284 if ($contribution->find(TRUE)) {
285 $ids['contribution'] = $contribution->id
;
287 CRM_Core_DAO
::storeValues($contribution, $values);
289 return $contribution;
291 // return by reference
297 * Get the values and resolve the most common mappings.
299 * Since contribution status is resolved in almost every function that calls getValues it makes
300 * sense to have an extra function to resolve it rather than repeat the code.
302 * Think carefully before adding more mappings to be resolved as there could be performance implications
303 * if this function starts to be called from more iterative functions.
305 * @param array $params
306 * Input parameters to find object.
309 * Array of the found contribution.
310 * @throws CRM_Core_Exception
312 public static function getValuesWithMappings($params) {
314 $contribution = self
::getValues($params, $values, $ids);
315 if (is_null($contribution)) {
316 throw new CRM_Core_Exception('No contribution found');
318 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
323 * Calculate net_amount & fee_amount if they are not set.
325 * Net amount should be total - fee.
326 * This should only be called for new contributions.
328 * @param array $params
329 * Params for a new contribution before they are saved.
330 * @param int|null $contributionID
331 * Contribution ID if we are dealing with an update.
333 * @throws \CiviCRM_API3_Exception
335 public static function calculateMissingAmountParams(&$params, $contributionID) {
336 if (!$contributionID && !isset($params['fee_amount'])) {
337 if (isset($params['total_amount']) && isset($params['net_amount'])) {
338 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
341 $params['fee_amount'] = 0;
344 if (!isset($params['net_amount'])) {
345 if (!$contributionID) {
346 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
349 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
350 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
351 // net_amount may need adjusting.
352 $contribution = civicrm_api3('Contribution', 'getsingle', [
353 'id' => $contributionID,
354 'return' => ['total_amount', 'net_amount', 'fee_amount'],
356 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
357 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
358 $params['net_amount'] = $totalAmount - $feeAmount;
366 * @param $billingLocationTypeID
370 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
371 $hasBillingField = FALSE;
380 //build address array
382 $addressParams['location_type_id'] = $billingLocationTypeID;
383 $addressParams['is_billing'] = 1;
385 $billingFirstName = $params['billing_first_name'] ??
NULL;
386 $billingMiddleName = $params['billing_middle_name'] ??
NULL;
387 $billingLastName = $params['billing_last_name'] ??
NULL;
388 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
390 foreach ($billingFields as $value) {
391 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ??
NULL;
392 if (!empty($addressParams[$value])) {
393 $hasBillingField = TRUE;
396 return [$hasBillingField, $addressParams];
400 * Get address params ready to be passed to the payment processor.
402 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
403 * To create an address we need state_province_id.
405 * @param array $params
406 * @param int $billingLocationTypeID
410 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
411 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
412 foreach ($addressParams as $name => $field) {
413 if (substr($name, 0, 8) == 'billing_') {
414 $addressParams[substr($name, 9)] = $addressParams[$field];
417 return [$hasBillingField, $addressParams];
421 * Get the number of terms for this contribution for a given membership type
422 * based on querying the line item table and relevant price field values
423 * Note that any one contribution should only be able to have one line item relating to a particular membership
426 * @param int $membershipTypeID
428 * @param int $contributionID
432 public static function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
433 $numTerms = CRM_Core_DAO
::singleValueQuery("
434 SELECT membership_num_terms FROM civicrm_line_item li
435 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
436 WHERE contribution_id = %1 AND membership_type_id = %2",
437 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
439 // default of 1 is precautionary
440 return empty($numTerms) ?
1 : $numTerms;
444 * Takes an associative array and creates a contribution object.
446 * @param array $params
447 * (reference ) an assoc array of name/value pairs.
449 * @return CRM_Contribute_BAO_Contribution
451 * @throws \API_Exception
452 * @throws \CRM_Core_Exception
453 * @throws \CiviCRM_API3_Exception
455 public static function create(&$params) {
457 $transaction = new CRM_Core_Transaction();
460 $contribution = self
::add($params);
462 catch (CRM_Core_Exception
$e) {
463 $transaction->rollback();
467 $params['contribution_id'] = $contribution->id
;
468 $session = CRM_Core_Session
::singleton();
470 if (!empty($params['note'])) {
472 'entity_table' => 'civicrm_contribution',
473 'note' => $params['note'],
474 'entity_id' => $contribution->id
,
475 'contact_id' => $session->get('userID'),
477 if (!$noteParams['contact_id']) {
478 $noteParams['contact_id'] = $params['contact_id'];
480 CRM_Core_BAO_Note
::add($noteParams);
483 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
485 $transaction->commit();
487 if (empty($contribution->contact_id
)) {
488 $contribution->find(TRUE);
491 $isCompleted = ('Completed' === CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
));
492 if (!empty($params['on_behalf'])
495 $existingActivity = Activity
::get(FALSE)->setWhere([
496 ['source_record_id', '=', $contribution->id
],
497 ['activity_type_id:name', '=', 'Contribution'],
498 ])->execute()->first();
500 $campaignParams = isset($params['campaign_id']) ?
['campaign_id' => ($params['campaign_id'] ??
NULL)] : [];
501 Activity
::save(FALSE)->addRecord(array_merge([
502 'activity_type_id:name' => 'Contribution',
503 'source_record_id' => $contribution->id
,
504 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ?
: $contribution->contact_id
,
505 'target_contact_id' => CRM_Core_Session
::getLoggedInContactID() ?
[$contribution->contact_id
] : [],
506 'activity_date_time' => $contribution->receive_date
,
507 'is_test' => (bool) $contribution->is_test
,
508 'status_id:name' => $isCompleted ?
'Completed' : 'Scheduled',
509 'skipRecentView' => TRUE,
510 'subject' => CRM_Activity_BAO_Activity
::getActivitySubject($contribution),
511 'id' => $existingActivity['id'] ??
NULL,
512 ], $campaignParams))->execute();
515 // do not add to recent items for import, CRM-4399
516 if (empty($params['skipRecentView'])) {
517 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
518 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
520 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
527 $retrieveRequired = 0;
528 foreach ($titleFields as $titleField) {
529 if (!isset($contribution->$titleField)) {
530 $retrieveRequired = 1;
534 if ($retrieveRequired == 1) {
535 $contribution->find(TRUE);
537 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
538 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
541 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
542 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
543 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
547 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
548 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
549 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
553 // add the recently created Contribution
554 CRM_Utils_Recent
::add($title,
558 $contribution->contact_id
,
564 return $contribution;
568 * Get the values for pseudoconstants for name->value and reverse.
570 * @param array $defaults
571 * (reference) the default values, some of which need to be resolved.
572 * @param bool $reverse
573 * True if we want to resolve the values in the reverse direction (value -> name).
575 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
576 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
577 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
578 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
579 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
583 * Convert associative array names to values and vice-versa.
585 * This function is used by both the web form layer and the api. Note that
586 * the api needs the name => value conversion, also the view layer typically
587 * requires value => name conversion
589 * @param array $defaults
590 * @param string $property
591 * @param array $lookup
592 * @param bool $reverse
596 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
597 $id = $property . '_id';
599 $src = $reverse ?
$property : $id;
600 $dst = $reverse ?
$id : $property;
602 if (!array_key_exists($src, $defaults)) {
606 $look = $reverse ?
array_flip($lookup) : $lookup;
608 if (is_array($look)) {
609 if (!array_key_exists($defaults[$src], $look)) {
613 $defaults[$dst] = $look[$defaults[$src]];
618 * Retrieve DB object based on input parameters.
620 * It also stores all the retrieved values in the default array.
622 * @param array $params
623 * (reference ) an assoc array of name/value pairs.
624 * @param array $defaults
625 * (reference ) an assoc array to hold the name / value pairs.
626 * in a hierarchical manner
628 * (reference) the array that holds all the db ids.
630 * @return CRM_Contribute_BAO_Contribution
632 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
633 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
634 return $contribution;
638 * Combine all the importable fields from the lower levels object.
640 * The ordering is important, since currently we do not have a weight
641 * scheme. Adding weight is super important and should be done in the
642 * next week or so, before this can be called complete.
644 * @param string $contactType
645 * @param bool $status
648 * array of importable Fields
650 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
651 if (!self
::$_importableFields) {
652 if (!self
::$_importableFields) {
653 self
::$_importableFields = [];
657 $fields = ['' => ['title' => ts('- do not import -')]];
660 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
663 $note = CRM_Core_DAO_Note
::import();
664 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
665 unset($tmpFields['option_value']);
666 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
667 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
669 // Using new Dedupe rule.
671 'contact_type' => $contactType,
672 'used' => 'Unsupervised',
674 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
675 $tmpContactField = [];
676 if (is_array($fieldsArray)) {
677 foreach ($fieldsArray as $value) {
678 //skip if there is no dupe rule
679 if ($value == 'none') {
682 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
687 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
688 $tmpContactField[trim($value)] = $contactFields[trim($value)];
690 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
693 $title = $tmpContactField[trim($value)]['title'];
695 $tmpContactField[trim($value)]['title'] = $title;
699 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
700 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
701 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
702 $fields = array_merge($fields, $tmpContactField);
703 $fields = array_merge($fields, $tmpFields);
704 $fields = array_merge($fields, $note);
705 $fields = array_merge($fields, $optionFields);
706 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
707 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
708 self
::$_importableFields = $fields;
710 return self
::$_importableFields;
714 * Combine all the exportable fields from the lower level objects.
716 * @param bool $checkPermission
719 * array of exportable Fields
721 public static function &exportableFields($checkPermission = TRUE) {
722 if (!self
::$_exportableFields) {
723 if (!self
::$_exportableFields) {
724 self
::$_exportableFields = [];
727 $fields = CRM_Contribute_DAO_Contribution
::export();
728 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
729 $fields = array_merge(
731 CRM_Contribute_DAO_Product
::export(),
732 CRM_Contribute_DAO_ContributionProduct
::export(),
733 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
735 'contribution_product_id' => [
736 'title' => ts('Premium'),
737 'name' => 'contribution_product_id',
738 'where' => 'civicrm_product.id',
739 'data_type' => CRM_Utils_Type
::T_INT
,
745 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
747 $contributionPage = [
748 'contribution_page' => [
749 'title' => ts('Contribution Page'),
750 'name' => 'contribution_page',
751 'where' => 'civicrm_contribution_page.title',
752 'data_type' => CRM_Utils_Type
::T_STRING
,
756 $contributionNote = [
757 'contribution_note' => [
758 'title' => ts('Contribution Note'),
759 'name' => 'contribution_note',
760 'data_type' => CRM_Utils_Type
::T_TEXT
,
765 'contribution_batch' => [
766 'title' => ts('Batch Name'),
772 'contribution_campaign_title' => [
773 'title' => ts('Campaign Title'),
774 'name' => 'campaign_title',
775 'where' => 'civicrm_campaign.title',
776 'data_type' => CRM_Utils_Type
::T_STRING
,
779 $softCreditFields = [
780 'contribution_soft_credit_name' => [
781 'name' => 'contribution_soft_credit_name',
782 'title' => ts('Soft Credit For'),
783 'where' => 'civicrm_contact_d.display_name',
784 'data_type' => CRM_Utils_Type
::T_STRING
,
786 'contribution_soft_credit_amount' => [
787 'name' => 'contribution_soft_credit_amount',
788 'title' => ts('Soft Credit Amount'),
789 'where' => 'civicrm_contribution_soft.amount',
790 'data_type' => CRM_Utils_Type
::T_MONEY
,
792 'contribution_soft_credit_type' => [
793 'name' => 'contribution_soft_credit_type',
794 'title' => ts('Soft Credit Type'),
795 'where' => 'contribution_softcredit_type.label',
796 'data_type' => CRM_Utils_Type
::T_STRING
,
798 'contribution_soft_credit_contribution_id' => [
799 'name' => 'contribution_soft_credit_contribution_id',
800 'title' => ts('Soft Credit For Contribution ID'),
801 'where' => 'civicrm_contribution_soft.contribution_id',
802 'data_type' => CRM_Utils_Type
::T_INT
,
804 'contribution_soft_credit_contact_id' => [
805 'name' => 'contribution_soft_credit_contact_id',
806 'title' => ts('Soft Credit For Contact ID'),
807 'where' => 'civicrm_contact_d.id',
808 'data_type' => CRM_Utils_Type
::T_INT
,
812 $fields = array_merge($fields, $contributionPage,
813 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
814 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
817 self
::$_exportableFields = $fields;
820 return self
::$_exportableFields;
824 * Record an activity when a payment is received.
826 * @todo this is intended to be moved to payment BAO class as a protected function
827 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
828 * merit it's own function as it makes the code less rather than more readable.
830 * @param int $contributionId
831 * @param int $participantId
832 * @param string $totalAmount
833 * @param string $currency
834 * @param string $trxnDate
836 * @throws \CRM_Core_Exception
837 * @throws \CiviCRM_API3_Exception
839 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
840 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
842 if ($participantId) {
843 $inputParams['id'] = $participantId;
846 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
847 $entityObj = $entityObj[$participantId];
848 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
851 $entityObj = new CRM_Contribute_BAO_Contribution();
852 $entityObj->id
= $contributionId;
853 $entityObj->find(TRUE);
854 $title = ts('Contribution');
856 // @todo per block above this is not a logical splitting off of functionality.
857 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
861 * Get the value for the To Financial Account.
863 * @param $contribution
868 public static function getToFinancialAccount($contribution, $params) {
869 if (!empty($params['payment_processor_id'])) {
870 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
872 if (!empty($params['payment_instrument_id'])) {
873 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
876 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
877 $queryParams = [1 => [$relationTypeId, 'Integer']];
878 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
883 * Get memberships related to the contribution.
885 * @param int $contributionID
889 protected static function getRelatedMemberships($contributionID) {
890 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
891 'return' => 'membership_id',
892 'contribution_id' => (int) $contributionID,
895 foreach ($membershipPayments as $membershipPayment) {
896 $membershipIDs[] = $membershipPayment['membership_id'];
898 if (empty($membershipIDs)) {
901 // We could combine this with the MembershipPayment.get - we'd
902 // need to re-wrangle the params (here or in the calling function)
903 // as they would then me membership.contact_id, membership.is_test etc
904 return civicrm_api3('Membership', 'get', [
905 'id' => ['IN' => $membershipIDs],
906 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
911 * Cancel contribution.
913 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
915 * @param $processContributionObject
916 * @param $memberships
917 * @param $contributionId
918 * @param $membershipStatuses
919 * @param $updateResult
920 * @param $participant
922 * @param $pledgePayment
924 * @param $pledgePaymentIDs
925 * @param $contributionStatusId
929 protected static function cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
930 // @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
931 $processContribution = FALSE;
932 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
933 if (is_array($memberships)) {
934 foreach ($memberships as $membership) {
936 //Update Membership status if there is no other completed contribution associated with the membership.
937 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
938 foreach ($relatedContributions as $contriId) {
939 if ($contriId == $contributionId) {
942 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
943 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
947 if ($membership && $update) {
948 $newStatus = array_search('Cancelled', $membershipStatuses);
951 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
953 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
954 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
955 'target_contact_id' => $membership->contact_id
,
956 'source_record_id' => $membership->id
,
957 'activity_type_id' => 'Change Membership Status',
958 'status_id' => 'Completed',
959 'priority_id' => 'Normal',
960 'activity_date_time' => 'now',
963 $membership->status_id
= $newStatus;
964 $membership->is_override
= TRUE;
965 $membership->status_override_end_date
= 'null';
967 civicrm_api3('activity', 'create', $activityParam);
969 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
970 if ($processContributionObject) {
971 $processContribution = TRUE;
978 $updatedStatusId = array_search('Cancelled', $participantStatuses);
979 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
981 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
982 if ($processContributionObject) {
983 $processContribution = TRUE;
987 if ($pledgePayment) {
988 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
990 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
991 if ($processContributionObject) {
992 $processContribution = TRUE;
995 return [$updateResult, $processContribution];
999 * Do any accounting updates required as a result of a contribution status change.
1001 * Currently we have a bit of a roundabout where adding a payment results in this being called &
1002 * this may attempt to add a payment. We need to resolve that....
1004 * The 'right' way to add payments or refunds is through the Payment.create api. That api
1005 * then updates the contribution but this process should not also record another financial trxn.
1006 * Currently we have weak detection fot that scenario & where it is detected the first returned
1007 * value is FALSE - meaning 'do not continue'.
1009 * We should also look at the fact that the calling function - updateFinancialAccounts
1010 * bunches together some disparate processes rather than having separate appropriate
1013 * @param array $params
1016 * Return indicates whether the updateFinancialAccounts function should continue.
1018 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
1019 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
1020 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
1022 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
1023 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
1024 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1025 // why it is here or where it is handled instead.
1026 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
1027 && $currentContributionStatus == 'Partially paid'))
1032 if (self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
1033 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1034 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1036 elseif (($previousContributionStatus == 'Pending'
1037 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
1039 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
1040 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1042 if ($currentContributionStatus == 'Cancelled') {
1043 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1044 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1045 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1048 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1049 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1053 if (($previousContributionStatus == 'Pending'
1054 ||
$previousContributionStatus == 'In Progress')
1055 && ($currentContributionStatus == 'Completed')
1057 if (empty($params['line_item'])) {
1059 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1060 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1061 // & this can be removed
1064 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1065 // This is an update so original currency if none passed in.
1066 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1068 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1069 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1070 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1071 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1073 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1076 'entity_table' => 'civicrm_financial_item',
1078 foreach ($params['line_item'] as $fieldId => $fields) {
1079 foreach ($fields as $fieldValueId => $lineItemDetails) {
1080 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1082 1 => [$lineItemDetails['id'], 'Integer'],
1084 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1085 while ($financialItem->fetch()) {
1086 $entityParams['entity_id'] = $financialItem->id
;
1087 $entityParams['amount'] = $financialItem->amount
;
1088 foreach (self
::$_trxnIDs as $tID) {
1089 $entityParams['financial_trxn_id'] = $tID;
1090 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1101 * It is possible to override the membership id that is updated from the payment processor.
1103 * Historically Paypal does this & it still does if it determines data is messed up - see
1104 * https://lab.civicrm.org/dev/membership/issues/13
1106 * Read the comment block on repeattransaction for more information
1107 * about how things should work.
1109 * @param int $contributionID
1110 * @param array $input
1112 * @throws \CiviCRM_API3_Exception
1114 protected static function handleMembershipIDOverride($contributionID, $input) {
1115 if (!empty($input['membership_id'])) {
1116 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1117 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1122 * Update all financial items related to the line item tto have a status of paid.
1124 * @param int $lineItemID
1126 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1129 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1132 2 => [$lineItemID, 'Integer'],
1134 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1135 CRM_Core_DAO
::executeQuery($query, $fparams);
1139 * Create the financial items for the line.
1141 * @param array $params
1142 * @param string $context
1143 * @param array $fields
1144 * @param array $previousLineItems
1145 * @param array $inputParams
1146 * @param bool $isARefund
1147 * @param array $trxnIds
1148 * @param int $fieldId
1152 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1153 foreach ($fields as $fieldValueId => $lineItemDetails) {
1154 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
1155 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
1156 if ($params['contribution']->receive_date
) {
1157 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
1160 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1162 $currency = $params['prevContribution']->currency
;
1163 if ($params['contribution']->currency
) {
1164 $currency = $params['contribution']->currency
;
1166 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1168 'transaction_date' => $receiveDate,
1169 'contact_id' => $params['prevContribution']->contact_id
,
1170 'currency' => $currency,
1171 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1172 'description' => $prevFinancialItem['description'] ??
NULL,
1173 'status_id' => $prevFinancialItem['status_id'],
1174 'financial_account_id' => $financialAccount,
1175 'entity_table' => 'civicrm_line_item',
1176 'entity_id' => $lineItemDetails['id'],
1178 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1179 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1180 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
1182 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
1183 $taxAmount = (float) $lineItemDetails['tax_amount'];
1184 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1185 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1186 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1188 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1189 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1191 if ($taxAmount != 0) {
1192 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
1193 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
1194 if ($lineItemDetails['financial_type_id']) {
1195 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1197 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1205 * Does this contributtion status update represent a refund.
1207 * @param int $previousContributionStatusID
1208 * @param int $currentContributionStatusID
1212 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1213 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1216 return self
::isContributionStatusNegative($currentContributionStatusID);
1220 * Get transaction information about the contribution.
1222 * @param int $contributionId
1223 * @param int $financialTypeID
1227 protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) {
1229 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Expense Account is');
1231 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
1233 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
1235 ft.payment_instrument_id,
1236 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
1238 FROM civicrm_contribution con
1239 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
1240 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
1241 AND ft.to_financial_account_id != %2
1242 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
1243 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
1244 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
1246 WHERE con.id = %1 AND ft.is_payment = 1
1249 1 => [$contributionId, 'Integer'],
1250 2 => [$feeFinancialAccount, 'Integer'],
1252 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
1253 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
1255 while ($resultDAO->fetch()) {
1256 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1257 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1258 if ($resultDAO->card_type_id
) {
1259 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
1260 $pantruncation = '';
1261 if ($resultDAO->pan_truncation
) {
1262 $pantruncation = ": {$resultDAO->pan_truncation}";
1264 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
1267 // show payment edit link only for payments done via backoffice form
1268 $paymentEditLink = '';
1269 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
1271 CRM_Core_Action
::UPDATE
=> [
1272 'name' => ts('Edit Payment'),
1273 'icon' => 'fa-pencil',
1274 'url' => 'civicrm/payment/edit',
1275 'class' => 'medium-popup',
1276 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
1277 'title' => ts('Edit Payment'),
1280 $paymentEditLink = CRM_Core_Action
::formLink(
1282 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
1284 'id' => $resultDAO->id
,
1285 'contribution_id' => $contributionId,
1289 'Payment.edit.action',
1297 'id' => $resultDAO->id
,
1298 'total_amount' => $resultDAO->total_amount
,
1299 'financial_type' => $resultDAO->financial_account
,
1300 'payment_instrument' => $paidByLabel,
1301 'receive_date' => $resultDAO->trxn_date
,
1302 'trxn_id' => $resultDAO->trxn_id
,
1303 'status' => $statuses[$resultDAO->status_id
],
1304 'currency' => $resultDAO->currency
,
1305 'action' => $paymentEditLink,
1307 if ($paidByName == 'Check') {
1308 $val['check_number'] = $resultDAO->check_number
;
1316 * Should an email receipt be sent for this contribution on completion.
1318 * @param array $input
1319 * @param int $contributionPageID
1320 * @param int $recurringContributionID
1323 * @throws \API_Exception
1324 * @throws \Civi\API\Exception\UnauthorizedException
1326 protected static function isEmailReceipt(array $input, $contributionPageID, $recurringContributionID): bool {
1327 if (isset($input['is_email_receipt'])) {
1328 return (bool) $input['is_email_receipt'];
1330 if ($recurringContributionID) {
1331 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
1332 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
1333 // 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
1334 // Instance that had the table added via an upgrade in 4.1
1335 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
1336 // https://lab.civicrm.org/dev/core/issues/1245
1337 return (bool) ContributionRecur
::get(FALSE)->addWhere('id', '=', $recurringContributionID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1339 if ($contributionPageID) {
1340 return (bool) ContributionPage
::get(FALSE)->addWhere('id', '=', $contributionPageID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1342 // This would be the case for backoffice (where is_email_receipt is not passed in) or events, where Event::sendMail will filter
1348 * Process failed contribution.
1350 * @param $processContributionObject
1351 * @param $memberships
1352 * @param $contributionId
1353 * @param array $membershipStatuses
1354 * @param array $updateResult
1355 * @param $participant
1356 * @param $pledgePayment
1358 * @param array $pledgePaymentIDs
1359 * @param $contributionStatusId
1362 * @throws \CRM_Core_Exception
1364 protected static function processFail($processContributionObject, $memberships, $contributionId, array $membershipStatuses, array $updateResult, $participant, $pledgePayment, $pledgeID, array $pledgePaymentIDs, $contributionStatusId): array {
1365 $processContribution = FALSE;
1366 if (is_array($memberships)) {
1367 foreach ($memberships as $membership) {
1369 //Update Membership status if there is no other completed contribution associated with the membership.
1370 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1371 foreach ($relatedContributions as $contriId) {
1372 if ($contriId == $contributionId) {
1375 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1376 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1380 if ($membership && $update) {
1381 $membership->status_id
= array_search('Expired', $membershipStatuses);
1382 $membership->is_override
= TRUE;
1383 $membership->status_override_end_date
= 'null';
1384 $membership->save();
1386 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1387 if ($processContributionObject) {
1388 $processContribution = TRUE;
1394 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1398 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1399 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1400 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1402 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1403 if ($processContributionObject) {
1404 $processContribution = TRUE;
1408 if ($pledgePayment) {
1409 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1411 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1412 if ($processContributionObject) {
1413 $processContribution = TRUE;
1416 return [$updateResult, $processContribution];
1422 public function addSelectWhereClause() {
1423 $whereClauses = parent
::addSelectWhereClause();
1424 if ($whereClauses !== []) {
1425 // In this case permisssions have been applied & we assume the
1426 // financialaclreport is applying these
1427 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1428 return $whereClauses;
1431 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1432 return $whereClauses;
1434 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1435 if (empty($types)) {
1436 $whereClauses['financial_type_id'] = 'IN (0)';
1439 $whereClauses['financial_type_id'] = [
1440 'IN (' . implode(',', array_keys($types)) . ')',
1443 return $whereClauses;
1447 * @param null $status
1448 * @param null $startDate
1449 * @param null $endDate
1451 * @return array|null
1453 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1457 $where[] = 'contribution_status_id = 1';
1461 $where[] = 'contribution_status_id = 3';
1466 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1469 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1471 $financialTypeACLJoin = '';
1472 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1473 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1474 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1475 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1476 if ($financialTypes) {
1477 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1478 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1481 $where[] = "c.financial_type_id IN (0)";
1485 $whereCond = implode(' AND ', $where);
1488 SELECT sum( total_amount ) as total_amount,
1489 count( c.id ) as total_count,
1491 FROM civicrm_contribution c
1492 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1493 $financialTypeACLJoin
1495 AND ( is_test = 0 OR is_test IS NULL )
1496 AND contact.is_deleted = 0
1500 $dao = CRM_Core_DAO
::executeQuery($query);
1503 while ($dao->fetch()) {
1504 $count +
= $dao->total_count
;
1505 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1509 'amount' => implode(', ', $amount),
1517 * Delete the indirect records associated with this contribution first.
1521 * @return mixed|null
1522 * $results no of deleted Contribution on success, false otherwise
1524 public static function deleteContribution($id) {
1525 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
1527 $transaction = new CRM_Core_Transaction();
1530 //delete activity record
1532 'source_record_id' => $id,
1533 // activity type id for contribution
1534 'activity_type_id' => 6,
1537 CRM_Activity_BAO_Activity
::deleteActivity($params);
1539 //delete billing address if exists for this contribution.
1540 self
::deleteAddress($id);
1542 //update pledge and pledge payment, CRM-3961
1543 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1545 // remove entry from civicrm_price_set_entity, CRM-5095
1546 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1547 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1549 // cleanup line items.
1550 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1552 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1553 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1555 if ($participantId) {
1556 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1559 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1563 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1564 $noteId = key($note);
1566 CRM_Core_BAO_Note
::del($noteId, FALSE);
1569 $dao = new CRM_Contribute_DAO_Contribution();
1572 $results = $dao->delete();
1574 $transaction->commit();
1576 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1578 // delete the recently created Contribution
1579 $contributionRecent = [
1581 'type' => 'Contribution',
1583 CRM_Utils_Recent
::del($contributionRecent);
1589 * React to a financial transaction (payment) failure.
1591 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1592 * payments is important for forensic and outreach reasons.
1594 * @param int $contributionID
1595 * @param int $contactID
1596 * @param string $message
1598 * @throws \CiviCRM_API3_Exception
1600 public static function failPayment($contributionID, $contactID, $message) {
1601 civicrm_api3('activity', 'create', [
1602 'activity_type_id' => 'Failed Payment',
1603 'details' => $message,
1604 'subject' => ts('Payment failed at payment processor'),
1605 'source_record_id' => $contributionID,
1606 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1609 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1610 civicrm_api3('contribution', 'create', [
1611 'id' => $contributionID,
1612 'contribution_status_id' => 'Failed',
1617 * Check if there is a contribution with the same trxn_id or invoice_id.
1619 * @param array $input
1620 * An assoc array of name/value pairs.
1621 * @param array $duplicates
1622 * (reference) store ids of duplicate contribs.
1626 * true if duplicate, false otherwise
1628 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1630 $id = $input['id'] ??
NULL;
1632 $trxn_id = $input['trxn_id'] ??
NULL;
1633 $invoice_id = $input['invoice_id'] ??
NULL;
1639 $clause[] = "trxn_id = %1";
1640 $input[1] = [$trxn_id, 'String'];
1644 $clause[] = "invoice_id = %2";
1645 $input[2] = [$invoice_id, 'String'];
1648 if (empty($clause)) {
1652 $clause = implode(' OR ', $clause);
1654 $clause = "( $clause ) AND id != %3";
1655 $input[3] = [$id, 'Integer'];
1658 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1659 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1661 while ($dao->fetch()) {
1662 $duplicates[] = $dao->id
;
1669 * Takes an associative array and creates a contribution_product object.
1671 * the function extract all the params it needs to initialize the create a
1672 * contribution_product object. the params array could contain additional unused name/value
1675 * @param array $params
1676 * (reference) an assoc array of name/value pairs.
1678 * @return CRM_Contribute_DAO_ContributionProduct
1680 public static function addPremium(&$params) {
1681 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1682 $contributionProduct->copyValues($params);
1683 return $contributionProduct->save();
1687 * Get list of contribution fields for profile.
1688 * For now we only allow custom contribution fields to be in
1691 * @param bool $addExtraFields
1692 * True if special fields needs to be added.
1695 * the list of contribution fields
1697 public static function getContributionFields($addExtraFields = TRUE) {
1698 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1699 // @todo remove this - this line was added because payment_instrument_id was not
1700 // set to exportable - but now it is.
1701 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1703 if ($addExtraFields) {
1704 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1707 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1709 foreach ($contributionFields as $key => $var) {
1710 if ($key == 'contribution_contact_id') {
1713 elseif ($key == 'contribution_campaign_id') {
1714 $var['title'] = ts('Campaign');
1716 $fields[$key] = $var;
1719 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1724 * Add extra fields specific to contribution.
1726 public static function getSpecialContributionFields() {
1728 'contribution_soft_credit_name' => [
1729 'name' => 'contribution_soft_credit_name',
1730 'title' => ts('Soft Credit Name'),
1731 'headerPattern' => '/^soft_credit_name$/i',
1732 'where' => 'civicrm_contact_d.display_name',
1734 'contribution_soft_credit_email' => [
1735 'name' => 'contribution_soft_credit_email',
1736 'title' => ts('Soft Credit Email'),
1737 'headerPattern' => '/^soft_credit_email$/i',
1738 'where' => 'soft_email.email',
1740 'contribution_soft_credit_phone' => [
1741 'name' => 'contribution_soft_credit_phone',
1742 'title' => ts('Soft Credit Phone'),
1743 'headerPattern' => '/^soft_credit_phone$/i',
1744 'where' => 'soft_phone.phone',
1746 'contribution_soft_credit_contact_id' => [
1747 'name' => 'contribution_soft_credit_contact_id',
1748 'title' => ts('Soft Credit Contact ID'),
1749 'headerPattern' => '/^soft_credit_contact_id$/i',
1750 'where' => 'civicrm_contribution_soft.contact_id',
1752 'contribution_pcp_title' => [
1753 'name' => 'contribution_pcp_title',
1754 'title' => ts('Personal Campaign Page Title'),
1755 'headerPattern' => '/^contribution_pcp_title$/i',
1756 'where' => 'contribution_pcp.title',
1760 return $extraFields;
1764 * @param int $pageID
1768 public static function getCurrentandGoalAmount($pageID) {
1770 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1771 FROM civicrm_contribution_page p,
1772 civicrm_contribution c
1773 WHERE p.id = c.contribution_page_id
1775 AND c.cancel_date is null
1779 $config = CRM_Core_Config
::singleton();
1780 $params = [1 => [$pageID, 'Integer']];
1781 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1783 if ($dao->fetch()) {
1784 return [$dao->goal
, $dao->total
];
1787 return [NULL, NULL];
1792 * Get list of contributions which credit the passed in contact ID.
1794 * The returned array provides details about the original contribution & donor.
1796 * @param int $honorId
1797 * In Honor of Contact ID.
1800 * list of contribution fields
1801 * @todo - this is a confusing function called from one place. It has a test. It would be
1802 * nice to deprecate it.
1805 public static function getHonorContacts($honorId) {
1807 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1808 $honorDAO->contact_id
= $honorId;
1811 $type = CRM_Contribute_PseudoConstant
::financialType();
1813 while ($honorDAO->fetch()) {
1814 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1815 $contributionDAO->id
= $honorDAO->contribution_id
;
1817 if ($contributionDAO->find(TRUE)) {
1818 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1819 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1820 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1821 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1822 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1823 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1824 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1825 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1826 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1834 * Get the sort name of a contact for a particular contribution.
1837 * Id of the contribution.
1839 * @return null|string
1840 * sort name of the contact if found
1842 public static function sortName($id) {
1843 $id = CRM_Utils_Type
::escape($id, 'Integer');
1846 SELECT civicrm_contact.sort_name
1847 FROM civicrm_contribution, civicrm_contact
1848 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1849 AND civicrm_contribution.id = {$id}
1851 return CRM_Core_DAO
::singleValueQuery($query);
1855 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1857 * @param int|array $contactIDs
1861 public static function annual($contactIDs) {
1862 if (!is_array($contactIDs)) {
1863 // In practice I can't fine any evidence that this function is ever called with
1864 // anything other than a single contact id, but left like this due to .... fear.
1865 $contactIDs = explode(',', $contactIDs);
1868 $query = self
::getAnnualQuery($contactIDs);
1869 $dao = CRM_Core_DAO
::executeQuery($query);
1871 $amount = $average = [];
1872 while ($dao->fetch()) {
1873 if ($dao->count
> 0 && $dao->amount
> 0) {
1874 $count +
= $dao->count
;
1875 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1876 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1882 implode(', ', $amount),
1883 implode(', ', $average),
1890 * Check if there is a contribution with the params passed in.
1892 * Used for trxn_id,invoice_id and contribution_id
1894 * @param array $params
1895 * An assoc array of name/value pairs.
1898 * contribution id if success else NULL
1900 public static function checkDuplicateIds($params) {
1901 $dao = new CRM_Contribute_DAO_Contribution();
1905 foreach ($params as $k => $v) {
1907 $clause[] = "$k = '$v'";
1910 $clause = implode(' AND ', $clause);
1911 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1912 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1914 while ($dao->fetch()) {
1922 * Get the contribution details for component export.
1924 * @param int $exportMode
1926 * @param array $componentIds
1932 public static function getContributionDetails($exportMode, $componentIds) {
1933 $paymentDetails = [];
1934 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1936 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1937 $componentSelect = " civicrm_participant_payment.participant_id id";
1938 $additionalClause = "
1939 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1940 AND civicrm_participant_payment.participant_id {$componentClause} )
1943 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1944 $componentSelect = " civicrm_membership_payment.membership_id id";
1945 $additionalClause = "
1946 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1947 AND civicrm_membership_payment.membership_id {$componentClause} )
1950 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1951 $componentSelect = " civicrm_pledge_payment.id id";
1952 $additionalClause = "
1953 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1954 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1958 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1959 trxn_id, {$componentSelect}
1960 FROM civicrm_contribution
1961 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1962 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1963 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1964 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1965 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1966 AND option_group_contribution_status.id = contribution_status.option_group_id )
1970 $dao = CRM_Core_DAO
::executeQuery($query);
1972 while ($dao->fetch()) {
1973 $paymentDetails[$dao->id
] = [
1974 'total_amount' => $dao->total_amount
,
1975 'contribution_status' => $dao->status
,
1976 'receive_date' => $dao->receive_date
,
1977 'pay_instru' => $dao->payment_instrument
,
1978 'trxn_id' => $dao->trxn_id
,
1982 return $paymentDetails;
1986 * Create address associated with contribution record.
1988 * As long as there is one or more billing field in the parameters we will create the address.
1990 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1993 * @param array $params
1994 * @param int $billingLocationTypeID
1999 public static function createAddress($params, $billingLocationTypeID) {
2000 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
2001 if ($hasBillingField) {
2002 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
2003 return $address->id
;
2010 * Delete billing address record related contribution.
2012 * @param int $contributionId
2013 * @param int $contactId
2015 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
2017 $contactJoin = NULL;
2019 if ($contributionId) {
2020 $clauses[] = "cc.id = {$contributionId}";
2024 $clauses[] = "cco.id = {$contactId}";
2025 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
2028 if (empty($clauses)) {
2029 throw new CRM_Core_Exception('No Where clauses defined when deleting address');
2032 $condition = implode(' OR ', $clauses);
2036 FROM civicrm_address ca
2037 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
2041 $dao = CRM_Core_DAO
::executeQuery($query);
2043 while ($dao->fetch()) {
2044 $params = ['id' => $dao->id
];
2045 CRM_Core_BAO_Block
::blockDelete('Address', $params);
2050 * This function check online pending contribution associated w/
2051 * Online Event Registration or Online Membership signup.
2053 * @param int $componentId
2054 * Participant/membership id.
2055 * @param string $componentName
2059 * pending contribution id.
2061 public static function checkOnlinePendingContribution($componentId, $componentName) {
2062 $contributionId = NULL;
2063 if (!$componentId ||
2064 !in_array($componentName, ['Event', 'Membership'])
2066 return $contributionId;
2069 if ($componentName == 'Event') {
2070 $idName = 'participant_id';
2071 $componentTable = 'civicrm_participant';
2072 $paymentTable = 'civicrm_participant_payment';
2073 $source = ts('Online Event Registration');
2076 if ($componentName == 'Membership') {
2077 $idName = 'membership_id';
2078 $componentTable = 'civicrm_membership';
2079 $paymentTable = 'civicrm_membership_payment';
2080 $source = ts('Online Contribution');
2083 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
2086 SELECT component.id as {$idName},
2087 componentPayment.contribution_id as contribution_id,
2088 contribution.source source,
2089 contribution.contribution_status_id as contribution_status_id,
2090 contribution.is_pay_later as is_pay_later
2091 FROM $componentTable component
2092 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
2093 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
2094 WHERE component.id = {$componentId}";
2096 $dao = CRM_Core_DAO
::executeQuery($query);
2098 while ($dao->fetch()) {
2099 if ($dao->contribution_id
&&
2100 $dao->is_pay_later
&&
2101 $dao->contribution_status_id
== $pendingStatusId &&
2102 strpos($dao->source
, $source) !== FALSE
2104 $contributionId = $dao->contribution_id
;
2108 return $contributionId;
2112 * Update contribution as well as related objects.
2114 * This function by-passes hooks - to address this - don't use this function.
2116 * @param array $params
2117 * @param bool $processContributionObject
2121 * @throws CRM_Core_Exception
2122 * @throws \CiviCRM_API3_Exception
2125 * Use api contribute.completetransaction
2126 * For failures use failPayment (preferably exposing by api in the process).
2129 public static function transitionComponents($params, $processContributionObject = FALSE) {
2130 // get minimum required values.
2131 $contactId = $params['contact_id'] ??
NULL;
2132 $componentId = $params['component_id'] ??
NULL;
2133 $componentName = $params['componentName'] ??
NULL;
2134 $contributionId = $params['contribution_id'] ??
NULL;
2135 $contributionStatusId = $params['contribution_status_id'] ??
NULL;
2137 // if we already processed contribution object pass previous status id.
2138 $previousContriStatusId = $params['previous_contribution_status_id'] ??
NULL;
2142 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2144 // we process only ( Completed, Cancelled, or Failed ) contributions.
2145 if (!$contributionId ||
2146 !in_array($contributionStatusId, [
2147 array_search('Completed', $contributionStatuses),
2148 array_search('Cancelled', $contributionStatuses),
2149 array_search('Failed', $contributionStatuses),
2152 return $updateResult;
2155 if (!$componentName ||
!$componentId) {
2156 // get the related component details.
2157 $componentDetails = self
::getComponentDetails($contributionId);
2160 $componentDetails['contact_id'] = $contactId;
2161 $componentDetails['component'] = $componentName;
2163 if ($componentName == 'event') {
2164 $componentDetails['participant'] = $componentId;
2167 $componentDetails['membership'] = $componentId;
2171 if (!empty($componentDetails['contact_id'])) {
2172 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2178 // do check for required ids.
2179 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2180 return $updateResult;
2185 $input['component'] = $componentDetails['component'] ??
NULL;
2186 $ids['contribution'] = $contributionId;
2187 $ids['contact'] = $componentDetails['contact_id'] ??
NULL;
2188 $ids['membership'] = $componentDetails['membership'] ??
NULL;
2189 $ids['participant'] = $componentDetails['participant'] ??
NULL;
2190 $ids['event'] = $componentDetails['event'] ??
NULL;
2191 $ids['pledge_payment'] = $componentDetails['pledge_payment'] ??
NULL;
2192 $ids['contributionRecur'] = NULL;
2193 $ids['contributionPage'] = NULL;
2195 $contribution = new CRM_Contribute_BAO_Contribution();
2196 $contribution->id
= $ids['contribution'];
2197 $contribution->find();
2199 $contribution->loadRelatedObjects($input, $ids);
2201 $memberships = $contribution->_relatedObjects
['membership'] ??
[];
2202 $participant = $contribution->_relatedObjects
['participant'] ??
[];
2203 $pledgePayment = $contribution->_relatedObjects
['pledge_payment'] ??
[];
2205 $pledgeID = $oldStatus = NULL;
2206 $pledgePaymentIDs = [];
2207 if ($pledgePayment) {
2208 foreach ($pledgePayment as $key => $object) {
2209 $pledgePaymentIDs[] = $object->id
;
2211 $pledgeID = $pledgePayment[0]->pledge_id
;
2214 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2217 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2218 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2223 // we might want to process contribution object.
2224 $processContribution = FALSE;
2225 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2226 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2227 list($updateResult, $processContribution) = self
::cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2229 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2230 list($updateResult, $processContribution) = self
::processFail($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2232 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2234 // only pending contribution related object processed.
2235 if ($previousContriStatusId &&
2236 !in_array($contributionStatuses[$previousContriStatusId], [
2241 // this is case when we already processed contribution object.
2242 return $updateResult;
2244 elseif (!$previousContriStatusId &&
2245 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2250 // this is case when we are going to process contribution object later.
2251 return $updateResult;
2254 if (is_array($memberships)) {
2255 foreach ($memberships as $membership) {
2260 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2261 $membership->membership_type_id
,
2262 $membership->is_test
, $membership->id
2265 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2266 // this picks up membership type changes during renewals
2268 SELECT membership_type_id
2269 FROM civicrm_membership_log
2270 WHERE membership_id=$membership->id
2273 $dao = CRM_Core_DAO
::executeQuery($sql);
2274 if ($dao->fetch()) {
2275 if (!empty($dao->membership_type_id
)) {
2276 $membership->membership_type_id
= $dao->membership_type_id
;
2277 $membership->save();
2280 // else fall back to using current membership type
2281 // Figure out number of terms
2283 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2284 foreach ($lineitems as $lineitem) {
2285 if ($membership->membership_type_id
== ($lineitem['membership_type_id'] ??
NULL)) {
2286 $numterms = $lineitem['membership_num_terms'] ??
NULL;
2288 // in case membership_num_terms comes through as null or zero
2289 $numterms = $numterms >= 1 ?
$numterms : 1;
2294 // CRM-15735-to update the membership status as per the contribution receive date
2296 $oldStatus = $membership->status_id
;
2297 if (!empty($params['receive_date'])) {
2298 $joinDate = $params['receive_date'];
2299 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2300 $membership->end_date
,
2301 $membership->join_date
,
2302 $params['receive_date'],
2304 $membership->membership_type_id
,
2307 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2308 $membership->save();
2311 if ($currentMembership) {
2312 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2313 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2314 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2317 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2320 //get the status for membership.
2321 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2323 $dates['join_date'],
2326 $membership->membership_type_id
,
2330 $formattedParams = [
2331 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2332 array_search('Current', $membershipStatuses)
2334 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2335 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2336 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2339 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2341 $membership->copyValues($formattedParams);
2342 $membership->save();
2344 //updating the membership log
2345 $membershipLog = [];
2346 $membershipLog = $formattedParams;
2347 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'] ??
NULL, $format);
2348 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2350 $membershipLog['start_date'] = $logStartDate;
2351 $membershipLog['membership_id'] = $membership->id
;
2352 $membershipLog['modified_id'] = $membership->contact_id
;
2353 $membershipLog['modified_date'] = date('Ymd');
2354 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2356 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2358 //update related Memberships.
2359 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2361 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2362 $scheduledActivityID = CRM_Utils_Array
::value('id',
2363 civicrm_api3('Activity', 'Get',
2365 'source_record_id' => $membership->id
,
2366 'activity_type_id' => $activityType,
2367 'status_id' => 'Scheduled',
2370 'sort' => 'id DESC',
2375 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2376 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2377 if ($scheduledActivityID) {
2378 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2383 // track membership status change if any
2384 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2385 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2386 CRM_Activity_BAO_Activity
::addActivity($membership,
2387 'Change Membership Status',
2390 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2391 'source_contact_id' => $membershipLog['modified_id'],
2392 'priority_id' => 'Normal',
2397 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2398 if ($processContributionObject) {
2399 $processContribution = TRUE;
2402 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2408 $updatedStatusId = array_search('Registered', $participantStatuses);
2409 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2411 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2412 if ($processContributionObject) {
2413 $processContribution = TRUE;
2417 if ($pledgePayment) {
2418 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2420 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2421 if ($processContributionObject) {
2422 $processContribution = TRUE;
2427 // process contribution object.
2428 if ($processContribution) {
2429 $contributionParams = [];
2436 'payment_instrument_id',
2439 'financial_type_id',
2440 'contribution_status_id',
2441 'non_deductible_amount',
2445 foreach ($fields as $field) {
2446 if (empty($params[$field])) {
2449 $contributionParams[$field] = $params[$field];
2452 $contributionParams['id'] = $contributionId;
2453 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2456 return $updateResult;
2460 * Returns all contribution related object ids.
2462 * @param $contributionId
2466 public static function getComponentDetails($contributionId) {
2467 $componentDetails = $pledgePayment = [];
2468 if (!$contributionId) {
2469 return $componentDetails;
2473 SELECT c.id as contribution_id,
2474 c.contact_id as contact_id,
2475 c.contribution_recur_id,
2476 mp.membership_id as membership_id,
2477 m.membership_type_id as membership_type_id,
2478 pp.participant_id as participant_id,
2479 p.event_id as event_id,
2480 pgp.id as pledge_payment_id
2481 FROM civicrm_contribution c
2482 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2483 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2484 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2485 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2486 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2487 WHERE c.id = $contributionId";
2489 $dao = CRM_Core_DAO
::executeQuery($query);
2490 $componentDetails = [];
2492 while ($dao->fetch()) {
2493 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2494 $componentDetails['contact_id'] = $dao->contact_id
;
2495 if ($dao->event_id
) {
2496 $componentDetails['event'] = $dao->event_id
;
2498 if ($dao->participant_id
) {
2499 $componentDetails['participant'] = $dao->participant_id
;
2501 if ($dao->membership_id
) {
2502 if (!isset($componentDetails['membership'])) {
2503 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2505 $componentDetails['membership'][] = $dao->membership_id
;
2506 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2508 if ($dao->pledge_payment_id
) {
2509 $pledgePayment[] = $dao->pledge_payment_id
;
2511 if ($dao->contribution_recur_id
) {
2512 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2516 if ($pledgePayment) {
2517 $componentDetails['pledge_payment'] = $pledgePayment;
2520 return $componentDetails;
2524 * @param int $contactId
2525 * @param bool $includeSoftCredit
2527 * @return null|string
2529 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2533 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2534 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2535 $liWhere = " AND i.financial_type_id IN (0)";
2536 if (!empty($financialTypes)) {
2537 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2538 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2540 $contactContributionsSQL = "
2541 SELECT contribution.id AS id
2542 FROM civicrm_contribution contribution
2543 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2544 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2548 $contactSoftCreditContributionsSQL = "
2549 SELECT contribution.id
2550 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2551 ON ( contribution.id = softContribution.contribution_id )
2552 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2553 $query = "SELECT count( x.id ) count FROM ( ";
2554 $query .= $contactContributionsSQL;
2556 if ($includeSoftCredit) {
2557 $query .= " UNION ";
2558 $query .= $contactSoftCreditContributionsSQL;
2563 return CRM_Core_DAO
::singleValueQuery($query);
2567 * Repeat a transaction as part of a recurring series.
2570 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2571 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2572 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2573 * and associated entities.
2574 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2575 * which updates the various entities and sends appropriate emails.
2577 * Gaps in the above (@todo)
2578 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2579 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2580 * 3) Repeat transaction duplicates rather than calls Order.create
2581 * 4) Use of payment.create still limited - completetransaction is more common.
2582 * 5) the template transaction is tricky - historically we used the first contribution
2583 * linked to a recurring contribution. More recently that was changed to be the most recent.
2584 * Ideally it would be an actual template - not a contribution used as a template which
2585 * would give more appropriate flexibility. Note line_items have an entity so that table
2586 * could be used for the line item template - the difficulty is the custom fields...
2587 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2588 * to load the membership(s) referred to via line items in the template transactions. Any other
2589 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2590 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2591 * - membership_payment record
2592 * - civicrm_membership.contribution_recur_id
2594 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2595 * of historical processors since this has been handled 'forever' - specifically for paypal.
2596 * albeit by an even nastier mechanism than the current input override.
2597 * The count is out on how correct related entities wind up in this case.
2599 * @param CRM_Contribute_BAO_Contribution $contribution
2600 * @param array $input
2601 * @param array $contributionParams
2603 * @return bool|array
2604 * @throws CiviCRM_API3_Exception
2606 protected static function repeatTransaction(&$contribution, $input, $contributionParams) {
2607 if (!empty($contribution->id
)) {
2610 if (empty($contribution->id
)) {
2611 // Unclear why this would only be set for repeats.
2612 if (!empty($input['amount'])) {
2613 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2616 if (!empty($contributionParams['contribution_recur_id'])) {
2617 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2618 'id' => $contributionParams['contribution_recur_id'],
2620 if (!empty($recurringContribution['campaign_id'])) {
2621 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2622 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2624 if (!empty($recurringContribution['financial_type_id'])) {
2625 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2626 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2629 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2630 $contributionParams['contribution_recur_id'],
2631 array_intersect_key($contributionParams, [
2632 'total_amount' => TRUE,
2633 'financial_type_id' => TRUE,
2636 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2637 $contributionParams['status_id'] = 'Pending';
2639 if (isset($contributionParams['financial_type_id']) && count($input['line_item']) === 1) {
2640 // We permit the financial type to be overridden for single line items.
2641 // More comments on this are in getTemplateTransaction.
2642 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2645 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2647 foreach (['contact_id', 'currency', 'source'] as $fieldName) {
2648 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2651 $contributionParams['source'] = $contributionParams['source'] ?
: ts('Recurring contribution');
2653 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2654 //do not create CC or BCC emails or profile notifications.
2655 //The if is just to be safe. Not sure if we can ever arrive with this unset
2656 // but per CRM-19478 it seems it can be 'null'
2657 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2658 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2660 if (!empty($contribution->tax_amount
)) {
2661 $contributionParams['tax_amount'] = $contribution->tax_amount
;
2664 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2665 $contribution->id
= $createContribution['id'];
2666 $contribution->copyCustomFields($templateContribution['id'], $contribution->id
);
2667 self
::handleMembershipIDOverride($contribution->id
, $input);
2668 // Add new soft credit against current $contribution.
2669 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($contributionParams['contribution_recur_id'], $createContribution['id']);
2670 return $createContribution;
2675 * Get individual id for onbehalf contribution.
2677 * @param int $contributionId
2679 * @param int $contributorId
2683 * containing organization id and individual id
2685 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2689 if (!$contributionId) {
2693 // fetch contributor id if null
2694 if (!$contributorId) {
2695 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2696 $contributionId, 'contact_id'
2700 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2701 $activityTypeId = array_search('Contribution', $activityTypeIds);
2703 if ($activityTypeId && $contributorId) {
2705 SELECT civicrm_activity_contact.contact_id
2706 FROM civicrm_activity_contact
2707 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2708 WHERE civicrm_activity.activity_type_id = %1
2709 AND civicrm_activity.source_record_id = %2
2710 AND civicrm_activity_contact.record_type_id = %3
2713 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2714 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2717 1 => [$activityTypeId, 'Integer'],
2718 2 => [$contributionId, 'Integer'],
2719 3 => [$sourceID, 'Integer'],
2722 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2724 // for on behalf contribution source is individual and contributor is organization
2725 if ($sourceContactId && $sourceContactId != $contributorId) {
2726 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2727 // get rel type id for employee of relation
2728 foreach ($relationshipTypeIds as $id => $typeVals) {
2729 if ($typeVals['name_a_b'] == 'Employee of') {
2730 $relationshipTypeId = $id;
2735 $rel = new CRM_Contact_DAO_Relationship();
2736 $rel->relationship_type_id
= $relationshipTypeId;
2737 $rel->contact_id_a
= $sourceContactId;
2738 $rel->contact_id_b
= $contributorId;
2739 if ($rel->find(TRUE)) {
2740 $ids['individual_id'] = $rel->contact_id_a
;
2741 $ids['organization_id'] = $rel->contact_id_b
;
2752 public static function getContributionDates() {
2753 $config = CRM_Core_Config
::singleton();
2754 $currentMonth = date('m');
2755 $currentDay = date('d');
2756 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2757 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2758 (int ) $config->fiscalYearStart
['d'] > $currentDay
2761 $year = date('Y') - 1;
2766 $year = ['Y' => $year];
2767 $yearDate = $config->fiscalYearStart
;
2768 $yearDate = array_merge($year, $yearDate);
2769 $yearDate = CRM_Utils_Date
::format($yearDate);
2771 $monthDate = date('Ym') . '01';
2777 'yearDate' => $yearDate,
2778 'monthDate' => $monthDate,
2783 * Load objects relations to contribution object.
2784 * Objects are stored in the $_relatedObjects property
2785 * In the first instance we are just moving functionality from BASEIpn -
2787 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2789 * Note that the unit test for the BaseIPN class tests this function
2791 * @param array $input
2792 * Input as delivered from Payment Processor.
2794 * Ids as Loaded by Payment Processor.
2795 * @param bool $loadAll
2796 * Load all related objects - even where id not passed in? (allows API to call this).
2799 * @throws CRM_Core_Exception
2801 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
2802 // @todo deprecate this function - the steps should be
2803 // 1) add additional functions like 'getRelatedMemberships'
2804 // 2) switch all calls that refer to ->_relatedObjects to
2805 // using the helper functions
2806 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2807 // 4) make ->_relatedObjects protected
2808 // 5) hone up the individual functions to not use rely on this having been called
2809 // 6) deprecate like mad
2811 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2812 if (empty($ids['contact']) && isset($this->contact_id
)) {
2813 $ids['contact'] = $this->contact_id
;
2816 if (empty($this->_component
)) {
2817 if (!empty($ids['event'])) {
2818 $this->_component
= 'event';
2821 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2825 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2826 // refactoring than anything else, and has unit test coverage.
2827 if (empty($this->financial_type_id
)) {
2831 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2836 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2837 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2838 $this->contribution_page_id
,
2841 if ($paymentProcessorID) {
2842 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2846 $ids['contributionType'] = $this->financial_type_id
;
2847 $ids['financialType'] = $this->financial_type_id
;
2848 if ($this->contribution_page_id
) {
2849 $ids['contributionPage'] = $this->contribution_page_id
;
2852 $this->loadRelatedEntitiesByID($ids);
2854 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2855 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2858 if (!empty($ids['pledge_payment'])) {
2859 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2860 if (empty($paymentID)) {
2863 $payment = new CRM_Pledge_BAO_PledgePayment();
2864 $payment->id
= $paymentID;
2865 if (!$payment->find(TRUE)) {
2866 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
2868 $this->_relatedObjects
['pledge_payment'][] = $payment;
2872 // These are probably no longer accessed from anywhere
2873 // @todo remove this line, after ensuring not used.
2874 $ids = $this->loadRelatedMembershipObjects($ids);
2876 if ($this->_component
!= 'contribute') {
2877 // we are in event mode
2878 // make sure event exists and is valid
2879 $event = new CRM_Event_BAO_Event();
2880 $event->id
= $ids['event'];
2881 if ($ids['event'] &&
2884 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
2887 $this->_relatedObjects
['event'] = &$event;
2889 $participant = new CRM_Event_BAO_Participant();
2890 $participant->id
= $ids['participant'];
2891 if ($ids['participant'] &&
2892 !$participant->find(TRUE)
2894 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
2896 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2898 $this->_relatedObjects
['participant'] = &$participant;
2900 // get the payment processor id from event - this is inaccurate see CRM-16923
2901 // in future we should look at throwing an exception here rather than an dubious guess.
2902 if (!$paymentProcessorID) {
2903 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2904 if ($paymentProcessorID) {
2905 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2910 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($this->id
);
2911 if (!empty($relatedContact['individual_id'])) {
2912 $ids['related_contact'] = $relatedContact['individual_id'];
2915 if ($paymentProcessorID) {
2916 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2917 $this->is_test ?
'test' : 'live'
2919 $ids['paymentProcessor'] = $paymentProcessorID;
2920 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2923 // Add contribution id to $ids. CRM-20401
2924 $ids['contribution'] = $this->id
;
2929 * Create array of message information - ie. return html version, txt version, to field
2931 * @param array $input
2932 * Incoming information.
2933 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2934 * just check presence of recur object but maintaining legacy approach
2937 * IDs of related objects.
2938 * @param array $values
2939 * Any values that may have already been compiled by calling process.
2940 * This is augmented by values 'gathered' by gatherMessageValues
2941 * @param bool $returnMessageText
2942 * Distinguishes between whether to send message or return.
2943 * message text. We are working towards this function ALWAYS returning message text & calling
2944 * function doing emails / pdfs with it
2950 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2951 $this->loadRelatedObjects($input, $ids);
2953 if (empty($this->_component
)) {
2954 $this->_component
= $input['component'] ??
NULL;
2957 //not really sure what params might be passed in but lets merge em into values
2958 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2959 $values['is_email_receipt'] = !$returnMessageText;
2960 foreach (['receipt_date', 'cc_receipt', 'bcc_receipt', 'receipt_from_name', 'receipt_from_email', 'receipt_text'] as $fld) {
2961 if (!empty($input[$fld])) {
2962 $values[$fld] = $input[$fld];
2966 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2967 //what does recur 'mean here - to do with payment processor return functionality but
2968 // what is the importance
2969 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2970 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2972 $entityID = $entity = NULL;
2973 if (isset($ids['contribution'])) {
2974 $entity = 'contribution';
2975 $entityID = $ids['contribution'];
2977 if (!empty($ids['membership'])) {
2978 //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
2979 // 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
2980 // line having loaded an array
2981 $ids['membership'] = (array) $ids['membership'];
2982 $entity = 'membership';
2983 $entityID = $ids['membership'][0];
2986 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2987 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2988 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2990 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2991 //direct mode showing billing block, so use directIPN for temporary
2992 $template->assign('contributeMode', 'directIPN');
2995 // todo remove strtolower - check consistency
2996 if (strtolower($this->_component
) == 'event') {
2997 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2998 $values['event'] = [];
3000 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
3002 //get location details
3004 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
3005 'entity_table' => 'civicrm_event',
3007 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
3010 'entity_table' => 'civicrm_event',
3011 'entity_id' => $ids['event'],
3012 'module' => 'CiviEvent',
3015 list($custom_pre_id,
3017 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
3019 $values['custom_pre_id'] = $custom_pre_id;
3020 $values['custom_post_id'] = $custom_post_ids;
3021 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
3022 //and cases involving status updation through ipn
3023 // whatever that means!
3024 // total_amount appears to be the preferred input param & it is unclear why we support amount here
3025 // perhaps we should throw an e-notice if amount is set & force total_amount?
3026 if (!empty($input['amount'])) {
3027 $values['totalAmount'] = $input['amount'];
3029 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
3030 if ($values['event']['is_email_confirm']) {
3031 $values['is_email_receipt'] = 1;
3034 if (!empty($ids['contribution'])) {
3035 $values['contributionId'] = $ids['contribution'];
3038 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
3039 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
3043 $values['contribution_id'] = $this->id
;
3044 if (!empty($ids['related_contact'])) {
3045 $values['related_contact'] = $ids['related_contact'];
3046 if (isset($ids['onbehalf_dupe_alert'])) {
3047 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
3050 'contact_id' => $ids['contact'],
3051 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
3052 'Home', 'id', 'name'
3055 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
3056 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
3059 if ($this->is_test
) {
3062 if (!empty($this->_relatedObjects
['membership'])) {
3063 foreach ($this->_relatedObjects
['membership'] as $membership) {
3064 if ($membership->id
) {
3065 $values['membership_id'] = $membership->id
;
3066 $values['isMembership'] = TRUE;
3067 $values['membership_assign'] = TRUE;
3069 // need to set the membership values here
3070 $template->assign('membership_name',
3071 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
3073 $template->assign('mem_start_date', $membership->start_date
);
3074 $template->assign('mem_join_date', $membership->join_date
);
3075 $template->assign('mem_end_date', $membership->end_date
);
3076 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
3077 $template->assign('mem_status', $membership_status);
3078 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
3079 $values['is_pay_later'] = 1;
3081 // Pass amount to floatval as string '0.00' is considered a
3082 // valid amount and includes Fee section in the mail.
3083 if (isset($values['amount'])) {
3084 $values['amount'] = floatval($values['amount']);
3087 if (!empty($this->contribution_recur_id
) && $paymentObject) {
3088 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
3089 $template->assign('cancelSubscriptionUrl', $url);
3090 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
3091 $template->assign('updateSubscriptionBillingUrl', $url);
3092 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
3093 $template->assign('updateSubscriptionUrl', $url);
3096 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3099 // otherwise if its about sending emails, continue sending without return, as we
3100 // don't want to exit the loop.
3105 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3111 * Gather values for contribution mail - this function has been created
3112 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3113 * Values related to the contribution in question are gathered
3115 * @param array $input
3116 * Input into function (probably from payment processor).
3117 * @param array $values
3119 * The set of ids related to the input.
3122 * @throws \CRM_Core_Exception
3124 public function _gatherMessageValues($input, &$values, $ids = []) {
3125 // set display address of contributor
3126 $values['billingName'] = '';
3127 if ($this->address_id
) {
3128 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
3129 $addressDetails = reset($addressDetails);
3130 $values['billingName'] = $addressDetails['name'] ??
'';
3132 // Else we assign the billing address of the contribution contact.
3134 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
3135 $addressDetails = reset($addressDetails);
3137 $values['address'] = $addressDetails['display'] ??
'';
3139 if ($this->_component
=== 'contribute') {
3140 //get soft contributions
3141 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
3142 if (!empty($softContributions)) {
3143 // For pcp soft credit, there is no 'soft_credit' member it comes
3144 // back in different array members, but shortly after returning from
3145 // this function it calls _assignMessageVariablesToTemplate which does
3146 // its own lookup of any pcp soft credit, so we can skip it here.
3147 $values['softContributions'] = $softContributions['soft_credit'] ??
NULL;
3149 if (isset($this->contribution_page_id
)) {
3150 // This is a call we want to use less, in favour of loading related objects.
3151 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3152 if ($this->contribution_page_id
) {
3153 // This is precautionary as there are some legacy flows, but it should really be
3155 if (!isset($this->_relatedObjects
['contributionPage'])) {
3156 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
3158 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3161 // no contribution page -probably back office
3163 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3164 $values['title'] = 'Contribution';
3166 // set lineItem for contribution
3168 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3169 if (!empty($lineItems)) {
3170 $firstLineItem = reset($lineItems);
3172 if (!empty($firstLineItem['price_set_id'])) {
3173 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3174 'id' => $firstLineItem['price_set_id'],
3175 'return' => 'is_quick_config, id',
3177 $values['priceSetID'] = $priceSet['id'];
3179 foreach ($lineItems as &$eachItem) {
3180 if (isset($this->_relatedObjects
['membership'])
3181 && is_array($this->_relatedObjects
['membership'])
3182 && array_key_exists($eachItem['entity_id'] . '_' . $eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
3183 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->join_date
);
3184 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->start_date
);
3185 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->end_date
);
3187 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3188 // However, that does create upgrade pain so would be better to be phased in.
3189 $values['useForMember'] = empty($priceSet['is_quick_config']);
3191 $values['lineItem'][0] = $lineItems;
3195 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3199 // if this is onbehalf of contribution then set related contact
3200 if (!empty($relatedContact['individual_id'])) {
3201 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3205 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3208 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3211 foreach ($groupTree as $key => $group) {
3212 if ($key === 'info') {
3216 foreach ($group['fields'] as $k => $customField) {
3217 $groupLabel = $group['title'];
3218 if (!empty($customField['customValue'])) {
3219 foreach ($customField['customValue'] as $customFieldValues) {
3220 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
3225 $values['customGroup'] = $customGroup;
3227 $values['is_pay_later'] = $this->is_pay_later
;
3233 * Assign message variables to template but try to break the habit.
3235 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3236 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3237 * multiple recurring payments for processors like IATS that use tokens.
3239 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3240 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3241 * Note we send directly from this function in some cases because it is only partly refactored.
3243 * Don't call this function directly as the signature will change.
3247 * @param bool $returnMessageText
3251 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3252 // @todo - this should have a better separation of concerns - ie.
3253 // gatherMessageValues should build an array of values to be assigned to the template
3254 // and this function should assign them (assigning null if not set).
3255 // the way the pcpParams & honor Params section works is a baby-step towards this.
3256 $template = CRM_Core_Smarty
::singleton();
3257 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3258 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3259 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3260 $template->assign('billingName', $values['billingName']);
3262 // For some unit tests contribution cannot contain paymentProcessor information
3263 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3264 $template->assign('contributeMode', CRM_Core_SelectValues
::contributeMode()[$billingMode] ??
NULL);
3266 //assign honor information to receipt message
3267 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3270 'soft_credit_type' => NULL,
3271 'honor_block_is_active' => NULL,
3273 if (isset($softRecord['soft_credit'])) {
3274 //if id of contribution page is present
3275 if (!empty($values['id'])) {
3276 $values['honor'] = [
3277 'honor_profile_values' => [],
3278 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3279 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3282 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3283 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3286 //offline contribution
3287 $softCreditTypes = $softCredits = [];
3288 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3289 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3290 $softCredits[$key] = [
3291 'Name' => $softCredit['contact_name'],
3292 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3295 $template->assign('softCreditTypes', $softCreditTypes);
3296 $template->assign('softCredits', $softCredits);
3300 $dao = new CRM_Contribute_DAO_ContributionProduct();
3301 $dao->contribution_id
= $this->id
;
3302 if ($dao->find(TRUE)) {
3303 $premiumId = $dao->product_id
;
3304 $template->assign('option', $dao->product_option
);
3306 $productDAO = new CRM_Contribute_DAO_Product();
3307 $productDAO->id
= $premiumId;
3308 $productDAO->find(TRUE);
3309 $template->assign('selectPremium', TRUE);
3310 $template->assign('product_name', $productDAO->name
);
3311 $template->assign('price', $productDAO->price
);
3312 $template->assign('sku', $productDAO->sku
);
3314 $template->assign('title', $values['title'] ??
NULL);
3315 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3316 if (!$values['amount'] && isset($this->total_amount
)) {
3317 $values['amount'] = $this->total_amount
;
3322 'pcp_display_in_roll' => NULL,
3323 'pcp_roll_nickname' => NULL,
3324 'pcp_personal_note' => NULL,
3328 if (strtolower($this->_component
) == 'contribute') {
3330 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3331 $softDAO->contribution_id
= $this->id
;
3332 if ($softDAO->find(TRUE)) {
3333 $pcpParams['pcpBlock'] = TRUE;
3334 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3335 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3336 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3338 //assign the pcp page title for email subject
3339 $pcpDAO = new CRM_PCP_DAO_PCP();
3340 $pcpDAO->id
= $softDAO->pcp_id
;
3341 if ($pcpDAO->find(TRUE)) {
3342 $pcpParams['title'] = $pcpDAO->title
;
3346 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3347 $template->assign($templateKey, $templateValue);
3350 if ($this->financial_type_id
) {
3351 $values['financial_type_id'] = $this->financial_type_id
;
3354 $template->assign('trxn_id', $this->trxn_id
);
3355 $template->assign('receive_date',
3356 CRM_Utils_Date
::processDate($this->receive_date
)
3358 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3359 $template->assign('action', $this->is_test ?
1024 : 1);
3360 $template->assign('receipt_text', $values['receipt_text'] ??
NULL);
3361 $template->assign('is_monetary', 1);
3362 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3363 $template->assign('currency', $this->currency
);
3364 $template->assign('address', CRM_Utils_Address
::format($input));
3365 if (!empty($values['customGroup'])) {
3366 $template->assign('customGroup', $values['customGroup']);
3368 if (!empty($values['softContributions'])) {
3369 $template->assign('softContributions', $values['softContributions']);
3371 if ($this->_component
== 'event') {
3372 $template->assign('title', $values['event']['title']);
3373 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3375 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3376 $viewRoles[] = $participantRoles[$v];
3378 $values['event']['participant_role'] = implode(', ', $viewRoles);
3379 $template->assign('event', $values['event']);
3380 $template->assign('participant', $values['participant']);
3381 $template->assign('location', $values['location']);
3382 $template->assign('customPre', $values['custom_pre_id']);
3383 $template->assign('customPost', $values['custom_post_id']);
3386 if ($this->_relatedObjects
['participant']->is_test
) {
3390 $values['params'] = [];
3391 //to get email of primary participant.
3392 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3393 $primaryAmount[] = [
3394 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3395 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3397 //build an array of cId/pId of participants
3398 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3399 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3400 //send receipt to additional participant if exists
3401 if (count($additionalIDs)) {
3402 $template->assign('isPrimary', 0);
3403 $template->assign('customProfile', NULL);
3404 //set additionalParticipant true
3405 $values['params']['additionalParticipant'] = TRUE;
3406 foreach ($additionalIDs as $pId => $cId) {
3408 //to change the status pending to completed
3409 $additional = new CRM_Event_DAO_Participant();
3410 $additional->id
= $pId;
3411 $additional->contact_id
= $cId;
3412 $additional->find(TRUE);
3413 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3414 $additional->status_id
= 1;
3415 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3416 //if additional participant dont have email
3418 if (!$additionalParticipantInfo) {
3419 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3422 'label' => $additional->fee_level
,
3423 'amount' => $additional->fee_amount
,
3425 $primaryAmount[] = [
3426 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3427 'amount' => $additional->fee_amount
,
3429 $additional->save();
3430 $template->assign('amount', $amount);
3431 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3435 //build an array of custom profile and assigning it to template
3436 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3438 if (count($customProfile)) {
3439 $template->assign('customProfile', $customProfile);
3442 // for primary contact
3443 $values['params']['additionalParticipant'] = FALSE;
3444 $template->assign('isPrimary', 1);
3445 $template->assign('amount', $primaryAmount);
3446 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3447 if ($this->payment_instrument_id
) {
3448 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3449 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3451 // carry paylater, since we did not created billing,
3452 // so need to pull email from primary location, CRM-4395
3453 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3459 * Check whether payment processor supports
3460 * cancellation of contribution subscription
3462 * @param int $contributionId
3465 * @param bool $isNotCancelled
3469 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3470 $cacheKeyString = "$contributionId";
3471 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3473 static $supportsCancel = [];
3475 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3476 $supportsCancel[$cacheKeyString] = FALSE;
3477 $isCancelled = FALSE;
3479 if ($isNotCancelled) {
3480 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3483 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3484 if (!empty($paymentObject)) {
3485 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3488 return $supportsCancel[$cacheKeyString];
3492 * Check whether subscription is already cancelled.
3494 * @param int $contributionId
3498 * contribution status
3500 public static function isSubscriptionCancelled($contributionId) {
3502 SELECT cr.contribution_status_id
3503 FROM civicrm_contribution_recur cr
3504 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3505 WHERE con.id = %1 LIMIT 1";
3506 $params = [1 => [$contributionId, 'Integer']];
3507 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3508 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3509 if ($status == 'Cancelled') {
3516 * Create all financial accounts entry.
3518 * @param array $params
3519 * Contribution object, line item array and params for trxn.
3522 * @param array $financialTrxnValues
3524 * @return null|\CRM_Core_BAO_FinancialTrxn
3526 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3527 $skipRecords = $update = $return = $isRelatedId = FALSE;
3528 $isUpdate = !empty($params['prevContribution']);
3530 $additionalParticipantId = [];
3531 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3532 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3534 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3535 $entityId = $params['participant_id'];
3536 $entityTable = 'civicrm_participant';
3537 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3539 elseif (!empty($params['membership_id'])) {
3540 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3541 // are created off one contribution should be handled elsewhere
3542 $entityId = $params['membership_id'];
3543 $entityTable = 'civicrm_membership';
3546 $entityId = $params['contribution']->id
;
3547 $entityTable = 'civicrm_contribution';
3550 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3551 $isRelatedId = TRUE;
3554 $entityID[] = $entityId;
3555 if (!empty($additionalParticipantId)) {
3556 $entityID +
= $additionalParticipantId;
3558 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3559 if (empty($params['prevContribution'])) {
3563 $statusId = $params['contribution']->contribution_status_id
;
3565 // build line item array if its not set in $params
3566 if (empty($params['line_item']) ||
$additionalParticipantId) {
3567 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3570 if ($contributionStatus != 'Failed' &&
3571 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3573 $skipRecords = TRUE;
3578 if (in_array($contributionStatus, $pendingStatus)) {
3579 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3580 $params['financial_type_id'],
3581 'Accounts Receivable Account is'
3584 elseif (!empty($params['payment_processor'])) {
3585 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3586 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3587 'id' => $params['payment_processor'],
3588 'return' => 'payment_instrument_id',
3591 elseif (!empty($params['payment_instrument_id'])) {
3592 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3595 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3596 $queryParams = [1 => [$relationTypeId, 'Integer']];
3597 $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);
3600 $totalAmount = $params['total_amount'] ??
NULL;
3601 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3602 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3604 //build financial transaction params
3606 'contribution_id' => $params['contribution']->id
,
3607 'to_financial_account_id' => $params['to_financial_account_id'],
3608 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3609 'total_amount' => $totalAmount,
3610 'fee_amount' => $params['fee_amount'] ??
NULL,
3611 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3612 'currency' => $params['contribution']->currency
,
3613 'trxn_id' => $params['contribution']->trxn_id
,
3614 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3615 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3616 // this should really default to completed (after discussion).
3617 'status_id' => $statusId,
3618 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3619 'check_number' => $params['check_number'] ??
NULL,
3620 'pan_truncation' => $params['pan_truncation'] ??
NULL,
3621 'card_type_id' => $params['card_type_id'] ??
NULL,
3623 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3624 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3625 if (isset($params['refund_trxn_id'])) {
3626 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3627 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3630 //CRM-16259, set is_payment flag for non pending status
3631 if (!in_array($contributionStatus, $pendingStatus)) {
3632 $trxnParams['is_payment'] = 1;
3634 if (!empty($params['payment_processor'])) {
3635 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3638 if (isset($fromFinancialAccountId)) {
3639 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3642 // consider external values passed for recording transaction entry
3643 if (!empty($financialTrxnValues)) {
3644 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3646 if (empty($trxnParams['payment_processor_id'])) {
3647 unset($trxnParams['payment_processor_id']);
3650 $params['trxnParams'] = $trxnParams;
3654 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3655 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3656 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3657 if (!isset($params['trxnParams']['trxn_id'])) {
3658 // Actually I have no idea why we are overwriting any values from the previous contribution.
3659 // (filling makes sense to me). However, only protecting this value as I really really know we
3660 // don't want this one overwritten.
3662 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3664 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3666 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3667 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3668 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3670 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3671 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3674 //if financial type is changed
3675 if (!empty($params['financial_type_id']) &&
3676 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3678 $accountRelationship = 'Income Account is';
3679 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3680 $accountRelationship = 'Deferred Revenue Account is';
3682 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3683 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3684 if ($oldFinancialAccount != $newFinancialAccount) {
3685 $params['total_amount'] = 0;
3686 // If we have a fee amount set reverse this as well.
3687 if (isset($params['fee_amount'])) {
3688 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3690 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3691 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3692 $params['prevContribution']->financial_type_id
, $accountRelationship);
3695 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3696 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3697 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3700 self
::updateFinancialAccounts($params, 'changeFinancialType');
3701 $params['skipLineItem'] = FALSE;
3702 foreach ($params['line_item'] as &$lineItems) {
3703 foreach ($lineItems as &$line) {
3704 $line['financial_type_id'] = $params['financial_type_id'];
3707 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3708 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3709 $params['financial_account_id'] = $newFinancialAccount;
3710 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3711 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3712 if (isset($params['fee_amount'])) {
3713 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3715 self
::updateFinancialAccounts($params);
3716 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3717 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3719 $params['deferred_financial_account_id'] = $newFinancialAccount;
3723 //Update contribution status
3724 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3725 if (!isset($params['refund_trxn_id'])) {
3726 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3727 // gets preference over another so I am only 'protecting' a very specific tested flow
3728 // and letting natural justice take care of the rest.
3729 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3731 if (!empty($params['contribution_status_id']) &&
3732 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3734 //Update Financial Records
3735 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3736 if ($callUpdateFinancialAccounts) {
3737 self
::updateFinancialAccounts($params, 'changedStatus');
3738 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3743 // change Payment Instrument for a Completed contribution
3744 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3745 // instrument is null and now new payment instrument is added along with the payment
3746 if (!$params['contribution']->payment_instrument_id
) {
3747 $params['contribution']->find(TRUE);
3749 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3750 $params['trxnParams']['check_number'] = $params['check_number'] ??
NULL;
3752 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3753 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3756 //if Change contribution amount
3757 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ??
NULL;
3758 $params['trxnParams']['net_amount'] = $params['net_amount'] ??
NULL;
3759 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3760 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3761 if (isset($totalAmount) &&
3762 $totalAmount != $params['prevContribution']->total_amount
3764 //Update Financial Records
3765 $params['trxnParams']['from_financial_account_id'] = NULL;
3766 self
::updateFinancialAccounts($params, 'changedAmount');
3767 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3772 // Looks like we might have a data correction update.
3773 // This would be a case where a transaction id has been entered but it is incorrect &
3774 // the person goes back in & fixes it, as opposed to a new transaction.
3775 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3776 // the data fix scenario.
3778 if (isset($params['refund_trxn_id'])) {
3779 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3780 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3781 civicrm_api3('FinancialTrxn', 'create', [
3782 'id' => $refundIDs['financialTrxnId'],
3783 'trxn_id' => $params['refund_trxn_id'],
3787 $cardType = $params['card_type_id'] ??
NULL;
3788 $panTruncation = $params['pan_truncation'] ??
NULL;
3789 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3794 // records finanical trxn and entity financial trxn
3795 // also make it available as return value
3796 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3797 $trxnParams['pan_truncation'] = $params['pan_truncation'] ??
NULL;
3798 $trxnParams['card_type_id'] = $params['card_type_id'] ??
NULL;
3799 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3800 $params['entity_id'] = $financialTxn->id
;
3801 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3802 self
::$_trxnIDs[] = $financialTxn->id
;
3806 // record line items and financial items
3807 if (empty($params['skipLineItem'])) {
3808 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
3811 // create batch entry if batch_id is passed and
3812 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3813 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3815 'batch_id' => $params['batch_id'],
3816 'entity_table' => 'civicrm_financial_trxn',
3817 'entity_id' => $financialTxn->id
,
3819 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3822 // when a fee is charged
3823 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3824 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3827 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3828 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3830 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3831 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3832 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3834 unset($params['line_item']);
3835 self
::$_trxnIDs = NULL;
3840 * Update all financial accounts entry.
3842 * @param array $params
3843 * Contribution object, line item array and params for trxn.
3845 * @param string $context
3848 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3849 * adds unpredictability.
3852 public static function updateFinancialAccounts(&$params, $context = NULL) {
3854 $inputParams = $params;
3855 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3857 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3858 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3859 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3862 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3863 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3864 $params['entity_id'] = $trxn->id
;
3866 $itemParams['entity_table'] = 'civicrm_line_item';
3867 $trxnIds['id'] = $params['entity_id'];
3868 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3869 foreach ($params['line_item'] as $fieldId => $fields) {
3870 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3875 * Is this contribution status a reversal.
3877 * If so we would expect to record a negative value in the financial_trxn table.
3879 * @param int $status_id
3883 public static function isContributionStatusNegative($status_id) {
3884 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3885 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3889 * Check status validation on update of a contribution.
3891 * @param array $values
3892 * Previous form values before submit.
3894 * @param array $fields
3895 * The input form values.
3897 * @param array $errors
3902 public static function checkStatusValidation($values, &$fields, &$errors) {
3903 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3904 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3905 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3909 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3911 'Cancelled' => ['Completed', 'Refunded'],
3912 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3913 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3914 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3915 'Refunded' => ['Cancelled', 'Completed'],
3916 'Partially paid' => ['Completed'],
3917 'Pending refund' => ['Completed', 'Refunded'],
3918 'Failed' => ['Pending'],
3921 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3922 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3924 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3925 1 => $contributionStatuses[$values['contribution_status_id']],
3926 2 => $contributionStatuses[$fields['contribution_status_id']],
3932 * Delete contribution of contact.
3934 * @see https://issues.civicrm.org/jira/browse/CRM-12155
3936 * @param int $contactId
3940 public static function deleteContactContribution($contactId) {
3941 $contribution = new CRM_Contribute_DAO_Contribution();
3942 $contribution->contact_id
= $contactId;
3943 $contribution->find();
3944 while ($contribution->fetch()) {
3945 self
::deleteContribution($contribution->id
);
3950 * Get options for a given contribution field.
3952 * @param string $fieldName
3953 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3954 * @param array $props whatever is known about this dao object.
3956 * @return array|bool
3957 * @see CRM_Core_DAO::buildOptions
3960 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3961 $className = __CLASS__
;
3963 if (isset($props['orderColumn'])) {
3964 $params['orderColumn'] = $props['orderColumn'];
3966 switch ($fieldName) {
3967 // This field is not part of this object but the api supports it
3968 case 'payment_processor':
3969 $className = 'CRM_Contribute_BAO_ContributionPage';
3970 // Filter results by contribution page
3971 if (!empty($props['contribution_page_id'])) {
3972 $page = civicrm_api('contribution_page', 'getsingle', [
3974 'id' => ($props['contribution_page_id']),
3976 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3977 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3981 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3982 case 'honor_type_id':
3983 $className = 'CRM_Contribute_BAO_ContributionSoft';
3984 $fieldName = 'soft_credit_type_id';
3985 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3988 case 'contribution_status_id':
3989 if ($context !== 'validate') {
3990 $params['condition'] = "v.name <> 'Template'";
3993 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3997 * Validate financial type.
3999 * @see https://issues.civicrm.org/jira/browse/CRM-13231
4001 * @param int $financialTypeId
4002 * Financial Type id.
4004 * @param string $relationName
4006 * @return array|bool
4008 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
4009 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
4011 if (!$financialAccount) {
4012 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
4018 * @param int $targetCid
4019 * @param $activityType
4020 * @param string $title
4021 * @param int $contributionId
4022 * @param string $totalAmount
4023 * @param string $currency
4024 * @param string $trxn_date
4026 * @throws \CRM_Core_Exception
4027 * @throws \CiviCRM_API3_Exception
4029 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
4030 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
4031 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
4032 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
4033 // source record id would be the contribution id
4034 $srcRecId = $contributionId;
4038 'source_contact_id' => $targetCid,
4039 'source_record_id' => $srcRecId,
4040 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
4041 'subject' => $subject,
4042 'activity_date_time' => $date,
4043 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
4044 'skipRecentView' => TRUE,
4047 // create activity with target contacts
4048 $session = CRM_Core_Session
::singleton();
4049 $id = $session->get('userID');
4051 $activityParams['source_contact_id'] = $id;
4052 $activityParams['target_contact_id'][] = $targetCid;
4054 civicrm_api3('Activity', 'create', $activityParams);
4058 * Get list of payments displayed by Contribute_Page_PaymentInfo.
4061 * @param string $component
4062 * @param bool $getTrxnInfo
4066 * @throws \CRM_Core_Exception
4067 * @throws \CiviCRM_API3_Exception
4069 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
4070 // @todo deprecate passing in component - always call with contribution.
4071 if ($component == 'event') {
4072 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4074 if (!$contributionId) {
4075 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4076 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4077 $id = $primaryParticipantId;
4079 if (!$contributionId) {
4084 elseif ($component == 'membership') {
4085 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4088 $contributionId = $id;
4091 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
4092 // but need to unpick the whole trxn_id it's returning first.
4093 $oldCalculation = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4094 $baseTrxnId = !empty($oldCalculation['trxn_id']) ?
$oldCalculation['trxn_id'] : NULL;
4096 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4097 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4099 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4101 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
4103 $contribution = civicrm_api3('Contribution', 'getsingle', [
4104 'id' => $contributionId,
4108 'contribution_status_id',
4109 'financial_type_id',
4113 $info['payLater'] = $contribution['is_pay_later'];
4114 $info['contribution_status'] = $contribution['contribution_status'];
4115 $info['currency'] = $contribution['currency'];
4117 $info['total'] = $total;
4118 $info['paid'] = $total - $paymentBalance;
4119 $info['balance'] = $paymentBalance;
4121 $info['component'] = $component;
4122 if ($getTrxnInfo && $baseTrxnId) {
4123 $info['transaction'] = self
::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
4126 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4131 * Get the outstanding balance on a contribution.
4133 * @param int $contributionId
4134 * @param float $contributionTotal
4135 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4139 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4140 if ($contributionTotal === NULL) {
4141 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4144 return (float) CRM_Utils_Money
::subtractCurrencies(
4146 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
4147 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4152 * Get the tax amount (misnamed function).
4154 * @param array $params
4157 * @throws \CiviCRM_API3_Exception
4159 protected static function checkTaxAmount($params) {
4160 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4162 // Update contribution.
4163 if (!empty($params['id'])) {
4164 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4165 // there are no tax implications - early return.
4166 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4169 if (empty($params['prevContribution'])) {
4170 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4173 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4174 if (!isset($params[$field])) {
4175 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4176 // Tax amount gets added back on later....
4177 $params['total_amount'] = $params['prevContribution']->total_amount
-
4178 $params['prevContribution']->tax_amount
;
4181 $params[$field] = $params['prevContribution']->$field;
4182 if ($params[$field] != $params['prevContribution']->$field) {
4188 self
::calculateMissingAmountParams($params, $params['id']);
4189 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4190 // Assign tax Amount on update of contribution
4191 if (!empty($params['prevContribution']->tax_amount
)) {
4192 $params['tax_amount'] = 'null';
4193 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4194 foreach ($params['line_item'] as $setID => $priceField) {
4195 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4196 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4203 // New Contribution and update of contribution with tax rate financial type
4204 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4205 empty($params['skipLineItem'])) {
4206 $taxRateParams = $taxRates[$params['financial_type_id']];
4207 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4208 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4210 // Get Line Item on update of contribution
4211 if (isset($params['id'])) {
4212 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4215 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4217 foreach ($params['line_item'] as $setID => $priceField) {
4218 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4219 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4222 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4224 elseif (isset($params['api.line_item.create'])) {
4225 // Update total amount of contribution using lineItem
4226 $taxAmountArray = [];
4227 foreach ($params['api.line_item.create'] as $key => $value) {
4228 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4229 $taxRate = $taxRates[$value['financial_type_id']];
4230 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4231 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4234 $params['tax_amount'] = array_sum($taxAmountArray);
4235 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4242 * Check financial type validation on update of a contribution.
4244 * @param int $financialTypeId
4245 * Value of latest Financial Type.
4247 * @param int $contributionId
4250 * @param array $errors
4255 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4256 if (!empty($financialTypeId)) {
4257 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4258 if ($oldFinancialTypeId == $financialTypeId) {
4262 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4264 '1' => [$contributionId, 'Integer'],
4266 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4267 if ($result->N
> 1) {
4268 $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.');
4273 * Update related pledge payment payments.
4275 * This function has been refactored out of the back office contribution form and may
4276 * still overlap with other functions.
4278 * @param string $action
4279 * @param int $pledgePaymentID
4280 * @param int $contributionID
4281 * @param bool $adjustTotalAmount
4282 * @param float $total_amount
4283 * @param float $original_total_amount
4284 * @param int $contribution_status_id
4285 * @param int $original_contribution_status_id
4287 public static function updateRelatedPledge(
4293 $original_total_amount,
4294 $contribution_status_id,
4295 $original_contribution_status_id
4297 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4301 if ($pledgePaymentID) {
4302 //store contribution id in payment record.
4303 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4306 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4313 if (!$pledgePaymentID) {
4316 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4322 $updatePledgePaymentStatus = FALSE;
4324 // If either the status or the amount has changed we update the pledge status.
4325 if ($action & CRM_Core_Action
::ADD
) {
4326 $updatePledgePaymentStatus = TRUE;
4328 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4329 ($original_total_amount != $total_amount))
4331 $updatePledgePaymentStatus = TRUE;
4334 if ($updatePledgePaymentStatus) {
4335 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4337 $contribution_status_id,
4346 * Is there only one line item attached to the contribution.
4352 * @throws \CiviCRM_API3_Exception
4354 public static function isSingleLineItem($id) {
4355 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4356 return ($lineItemCount == 1);
4360 * Complete an order.
4362 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4364 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4366 * Moving it out of the BaseIPN class is just the first step.
4368 * @param array $input
4370 * @param \CRM_Contribute_BAO_Contribution $contribution
4371 * @param bool $isPostPaymentCreate
4372 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4373 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4374 * transitioning related elements).
4377 * @throws \CRM_Core_Exception
4378 * @throws \CiviCRM_API3_Exception
4380 public static function completeOrder($input, $ids, $contribution, $isPostPaymentCreate = FALSE) {
4381 $transaction = new CRM_Core_Transaction();
4382 // @todo see if we even need this - it's used further down to create an activity
4383 // but the BAO layer should create that - we just need to add a test to cover it & can
4384 // maybe remove $ids altogether.
4385 $contributionContactID = $ids['related_contact'];
4386 $participantID = $ids['participant'];
4387 $recurringContributionID = $ids['contributionRecur'];
4389 // Unset ids just to make it clear it's not used again.
4391 // The previous details are used when calculating line items so keep it before any code that 'does something'
4392 if (!empty($contribution->id
)) {
4393 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4395 $inputContributionWhiteList = [
4400 'payment_instrument_id',
4405 'contribution_status_id',
4408 'financial_type_id',
4411 $paymentProcessorId = $input['payment_processor_id'] ??
NULL;
4413 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4415 $contributionParams = array_merge([
4416 'contribution_status_id' => $completedContributionStatusID,
4417 'source' => self
::getRecurringContributionDescription($contribution, $participantID),
4418 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4421 $contributionParams['payment_processor'] = $paymentProcessorId;
4423 if (empty($contributionParams['payment_instrument_id']) && $paymentProcessorId) {
4424 $contributionParams['payment_instrument_id'] = PaymentProcessor
::get(FALSE)->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id'];
4427 if ($recurringContributionID) {
4428 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4430 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4432 $contributionResult = self
::repeatTransaction($contribution, $input, $contributionParams);
4433 $contributionID = (int) $contribution->id
;
4435 if ($input['component'] == 'contribute') {
4436 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4437 self
::updateMembershipBasedOnCompletionOfContribution(
4444 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4445 $participantParams['id'] = $participantID;
4446 $participantParams['status_id'] = 'Registered';
4447 civicrm_api3('Participant', 'create', $participantParams);
4451 $contributionParams['id'] = $contributionID;
4452 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4454 if (!$contributionResult) {
4455 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4458 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4460 CRM_Core_Error
::debug_log_message('Contribution record updated successfully');
4461 $transaction->commit();
4463 // @todo - check if Contribution::create does this, test, remove.
4464 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contributionID, $recurringContributionID,
4465 $contributionParams['contribution_status_id'], $input['amount']);
4467 // create an activity record
4468 // @todo - check if Contribution::create does this, test, remove.
4469 if ($input['component'] == 'contribute') {
4471 $targetContactID = NULL;
4472 if ($contributionContactID) {
4473 $targetContactID = $contribution->contact_id
;
4474 $contribution->contact_id
= $contributionContactID;
4476 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution', $targetContactID);
4479 if (self
::isEmailReceipt($input, $contribution->contribution_page_id
, $recurringContributionID)) {
4480 civicrm_api3('Contribution', 'sendconfirmation', [
4481 'id' => $contributionID,
4482 'payment_processor_id' => $paymentProcessorId,
4484 CRM_Core_Error
::debug_log_message("Receipt sent");
4487 CRM_Core_Error
::debug_log_message("Success: Database updated");
4488 return $contributionResult;
4492 * Send receipt from contribution.
4494 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4496 * Note that the compose message part has been moved to contribution
4497 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4499 * @param array $input
4500 * Incoming data from Payment processor.
4502 * Related object IDs.
4503 * @param int $contributionID
4504 * @param bool $returnMessageText
4505 * Should text be returned instead of sent. This.
4506 * is because the function is also used to generate pdfs
4509 * @throws \CRM_Core_Exception
4510 * @throws \CiviCRM_API3_Exception
4511 * @throws \Exception
4513 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4515 $contribution = new CRM_Contribute_BAO_Contribution();
4516 $contribution->id
= $contributionID;
4517 if (!$contribution->find(TRUE)) {
4518 throw new CRM_Core_Exception('Contribution does not exist');
4520 $contribution->loadRelatedObjects($input, $ids, TRUE);
4521 // set receipt from e-mail and name in value
4522 if (!$returnMessageText) {
4523 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4525 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4526 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4527 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4528 civicrm_api3('Contribution', 'create', [
4529 'receipt_date' => 'now',
4530 'id' => $contribution->id
,
4537 * Generate From email and from name in an array values
4539 * @param array $input
4540 * @param \CRM_Contribute_BAO_Contribution $contribution
4544 public static function generateFromEmailAndName($input, $contribution) {
4545 // Use input value if supplied.
4546 if (!empty($input['receipt_from_email'])) {
4548 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4549 $input['receipt_from_email'],
4552 // if we are still empty see if we can use anything from a contribution page.
4554 if (!empty($contribution->contribution_page_id
)) {
4555 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4557 // if we are still empty see if we can use anything from a contribution page.
4558 if (!empty($pageValues['receipt_from_email'])) {
4560 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4561 $pageValues['receipt_from_email'],
4564 // If we are still empty fall back to the domain or logged in user information.
4565 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4569 * Load related memberships.
4573 * @return array $ids
4578 * Note that in theory it should be possible to retrieve these from the line_item table
4579 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4580 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4581 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4582 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4584 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4587 public function loadRelatedMembershipObjects($ids = []) {
4589 SELECT membership_id
4590 FROM civicrm_membership_payment
4591 WHERE contribution_id = %1 ";
4592 $params = [1 => [$this->id
, 'Integer']];
4593 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4595 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4596 while ($dao->fetch()) {
4597 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4598 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4602 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4603 foreach ($ids['membership'] as $id) {
4605 $membership = new CRM_Member_BAO_Membership();
4606 $membership->id
= $id;
4607 if (!$membership->find(TRUE)) {
4608 throw new Exception("Could not find membership record: $id");
4610 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4611 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4612 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4613 $this->_relatedObjects
['membership'][$membership->id
. '_' . $membership->membership_type_id
] = $membership;
4622 * Get the description (source field) for the recurring contribution.
4624 * @param CRM_Contribute_BAO_Contribution $contribution
4625 * @param int|null $participantID
4628 * @throws \CiviCRM_API3_Exception
4629 * @throws \API_Exception
4631 protected static function getRecurringContributionDescription($contribution, $participantID) {
4632 if (!empty($contribution->source
)) {
4633 return $contribution->source
;
4635 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4636 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4637 'id' => $contribution->contribution_page_id
,
4638 'return' => 'title',
4640 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4642 elseif ($participantID) {
4643 $eventTitle = Participant
::get(FALSE)
4644 ->addSelect('event.title')
4645 ->addWhere('id', '=', (int) $participantID)
4646 ->execute()->first()['event.title'];
4647 return ts('Online Event Registration') . ': ' . $eventTitle;
4649 elseif (!empty($contribution->contribution_recur_id
)) {
4650 return 'recurring contribution';
4656 * Function use to store line item proportionally in in entity financial trxn table
4658 * @param array $trxnParams
4660 * @param int $trxnId
4662 * @param float $contributionTotalAmount
4664 * @throws \CiviCRM_API3_Exception
4666 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4667 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4668 if (!empty($lineItems)) {
4669 // get financial item
4670 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4672 'contribution_total_amount' => $contributionTotalAmount,
4673 'trxn_total_amount' => $trxnParams['total_amount'],
4674 'trxn_id' => $trxnId,
4676 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4681 * Checks if line items total amounts
4682 * match the contribution total amount.
4684 * @param array $params
4685 * array of order params.
4687 * @throws \API_Exception
4689 public static function checkLineItems(&$params) {
4690 $totalAmount = $params['total_amount'] ??
NULL;
4691 $lineItemAmount = 0;
4693 foreach ($params['line_items'] as &$lineItems) {
4694 foreach ($lineItems['line_item'] as &$item) {
4695 if (empty($item['financial_type_id'])) {
4696 $item['financial_type_id'] = $params['financial_type_id'];
4698 $lineItemAmount +
= $item['line_total'] +
($item['tax_amount'] ??
0.00);
4702 if (!isset($totalAmount)) {
4703 $params['total_amount'] = $lineItemAmount;
4706 $currency = $params['currency'] ?? CRM_Core_Config
::singleton()->defaultCurrency
;
4708 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4709 throw new CRM_Contribute_Exception_CheckLineItemsException();
4715 * Get the financial account for the item associated with the new transaction.
4717 * @param array $params
4718 * @param int $default
4722 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4724 if (!empty($params['financial_account_id'])) {
4725 return $params['financial_account_id'];
4728 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4729 $preferredAccountsRelationships = [
4730 'Refunded' => 'Credit/Contra Revenue Account is',
4731 'Chargeback' => 'Chargeback Account is',
4734 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4735 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4736 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4738 $preferredAccountsRelationships[$contributionStatus]
4746 * ContributionPage values were being imposed onto values.
4748 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4749 * REALLY didn't want superimposed. The rest are left there in their overkill out
4752 * The rationale for making this explicit is that it was a case of carefully set values being
4753 * seemingly randonly overwritten without much care. In general I think array randomly setting
4754 * variables en mass is risky.
4756 * @param array $values
4760 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4761 $contributionPageValues = [];
4762 CRM_Contribute_BAO_ContributionPage
::setValues(
4763 $this->contribution_page_id
,
4764 $contributionPageValues
4767 // These are the values that I believe to be useful.
4770 'pay_later_receipt',
4772 'receipt_from_email',
4773 'receipt_from_name',
4777 'honoree_profile_id',
4778 'onbehalf_profile_id',
4779 'honor_block_is_active',
4780 // Kinda might be - but would be on the contribution...
4783 // Included for 'fear of regression' but can't justify any use for these....
4785 'payment_processor',
4786 'financial_type_id',
4787 'amount_block_is_active',
4792 'default_amount_id',
4796 'initial_amount_help_text',
4797 'initial_amount_label',
4799 'is_allow_other_amount',
4800 'is_billing_required',
4801 'is_confirm_enabled',
4802 'is_credit_card_only',
4804 'is_partial_payment',
4805 'is_recur_installments',
4806 'is_recur_interval',
4810 'min_initial_amount',
4811 'recur_frequency_unit',
4818 foreach ($valuesToCopy as $valueToCopy) {
4819 if (isset($contributionPageValues[$valueToCopy])) {
4820 if ($valueToCopy === 'title') {
4821 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
4824 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4832 * Get values of CiviContribute Settings
4833 * and check if its enabled or not.
4834 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4835 * in serialized form. Usually this should be stored as flat settings for each form fields
4836 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4837 * settings we will live with an inconsistency because it's too hard to change for now.
4838 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4841 * @param string $name
4846 public static function checkContributeSettings($name) {
4847 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
4848 return $contributeSettings[$name] ??
NULL;
4852 * This function process contribution related objects.
4854 * @param int $contributionId
4855 * @param int $statusId
4856 * @param int|null $previousStatusId
4858 * @param string $receiveDate
4860 * @return null|string
4862 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
4864 if (!$contributionId ||
!$statusId) {
4869 'contribution_id' => $contributionId,
4870 'contribution_status_id' => $statusId,
4871 'previous_contribution_status_id' => $previousStatusId,
4872 'receive_date' => $receiveDate,
4875 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
4877 if (!is_array($updateResult) ||
4878 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
4879 !is_array($updatedComponents) ||
4880 empty($updatedComponents)
4885 // get the user display name.
4887 SELECT display_name as displayName
4888 FROM civicrm_contact
4889 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
4890 WHERE civicrm_contribution.id = {$contributionId}";
4891 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
4893 // get the status message for user.
4894 foreach ($updatedComponents as $componentName => $updatedStatusId) {
4896 if ($componentName == 'CiviMember') {
4897 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
4898 CRM_Member_PseudoConstant
::membershipStatus()
4901 $statusNameMsgPart = 'updated';
4902 switch ($updatedStatusName) {
4905 $statusNameMsgPart = $updatedStatusName;
4909 $statusMsg .= "<br />" . ts("Membership for %1 has been %2.", [
4910 1 => $userDisplayName,
4911 2 => $statusNameMsgPart,
4915 if ($componentName == 'CiviEvent') {
4916 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
4917 CRM_Event_PseudoConstant
::participantStatus()
4919 if ($updatedStatusName == 'Cancelled') {
4920 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", [1 => $userDisplayName]);
4922 elseif ($updatedStatusName == 'Registered') {
4923 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", [1 => $userDisplayName]);
4927 if ($componentName == 'CiviPledge') {
4928 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
4929 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
4931 if ($updatedStatusName == 'Cancelled') {
4932 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", [1 => $userDisplayName]);
4934 elseif ($updatedStatusName == 'Failed') {
4935 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", [1 => $userDisplayName]);
4937 elseif ($updatedStatusName == 'Completed') {
4938 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", [1 => $userDisplayName]);
4947 * Get the contribution as it is in the database before being updated.
4949 * @param int $contributionID
4951 * @return \CRM_Contribute_BAO_Contribution|null
4953 private static function getOriginalContribution($contributionID) {
4954 return self
::getValues(['id' => $contributionID]);
4958 * Get the amount for the financial item row.
4960 * Helper function to start to break down recordFinancialTransactions for readability.
4962 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
4964 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
4965 * for historical reasons. Going forwards we can hope to add tests & improve readibility
4968 * @param array $params
4969 * Params as passed to contribution.create
4971 * @param string $context
4972 * changeFinancialType| changedAmount
4973 * @param array $lineItemDetails
4975 * @param bool $isARefund
4976 * Is this a refund / negative transaction.
4977 * @param int $previousLineItemTotal
4980 * @todo move recordFinancialAccounts & helper functions to their own class?
4983 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
4984 if ($context == 'changedAmount') {
4985 $lineTotal = $lineItemDetails['line_total'];
4986 if ($lineTotal != $previousLineItemTotal) {
4987 $lineTotal -= $previousLineItemTotal;
4991 elseif ($context == 'changeFinancialType') {
4992 return -$lineItemDetails['line_total'];
4994 elseif ($context == 'changedStatus') {
4995 $cancelledTaxAmount = 0;
4997 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
4999 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5001 elseif ($context === NULL) {
5002 // erm, yes because? but, hey, it's tested.
5003 return $lineItemDetails['line_total'];
5005 elseif (empty($lineItemDetails['line_total'])) {
5006 // follow legacy code path
5008 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
5009 return $params['total_amount'];
5012 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5017 * Get the multiplier for adjusting rows.
5019 * If we are dealing with a refund or cancellation then it will be a negative
5020 * amount to reflect the negative transaction.
5022 * If we are changing Financial Type it will be a negative amount to
5023 * adjust down the old type.
5025 * @param int $contribution_status_id
5026 * @param string $context
5030 protected static function getMultiplier($contribution_status_id, $context) {
5031 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5038 * Does this transaction reflect a payment instrument change.
5040 * @param array $params
5041 * @param array $pendingStatuses
5045 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5046 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
5048 if (array_key_exists('payment_instrument_id', $params)) {
5049 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
5050 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
5052 //check if status is changed from Pending to Completed
5053 // do not update payment instrument changes for Pending to Completed
5054 if (!($contributionStatus == 'Completed' &&
5055 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
5060 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
5061 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
5062 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5066 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
5067 $params['contribution']->check_number
!= $params['prevContribution']->check_number
5069 // another special case when check number is changed, create new financial records
5070 // create financial trxn with negative amount
5078 * Update the memberships associated with a contribution if it has been completed.
5080 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5081 * load them in this function. Code clean up would compensate for any minor performance implication.
5083 * @param int $contributionID
5084 * @param string $changeDate
5086 * @throws \CRM_Core_Exception
5087 * @throws \CiviCRM_API3_Exception
5089 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
5090 $memberships = self
::getRelatedMemberships($contributionID);
5091 foreach ($memberships as $membership) {
5092 $membershipParams = [
5093 'id' => $membership['id'],
5094 'contact_id' => $membership['contact_id'],
5095 'is_test' => $membership['is_test'],
5096 'membership_type_id' => $membership['membership_type_id'],
5097 'membership_activity_status' => 'Completed',
5100 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
5101 $membershipParams['membership_type_id'],
5102 $membershipParams['is_test'],
5103 $membershipParams['id']
5106 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5107 // this picks up membership type changes during renewals
5108 // @todo this is almost certainly an obsolete sql call, the pre-change
5109 // membership is accessible via $this->_relatedObjects
5111 SELECT membership_type_id
5112 FROM civicrm_membership_log
5113 WHERE membership_id={$membershipParams['id']}
5116 $dao = CRM_Core_DAO
::executeQuery($sql);
5117 if ($dao->fetch()) {
5118 if (!empty($dao->membership_type_id
)) {
5119 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
5122 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
5123 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
5124 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
5125 // 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.
5126 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
5127 // @todo once apiv4 ships with core switch to that & find sanity.
5128 $membershipParams['num_terms'] = self
::getNumTermsByContributionAndMembershipType(
5129 $membershipParams['membership_type_id'],
5133 // @todo remove all this stuff in favour of letting the api call further down handle in
5134 // (it is a duplication of what the api does).
5135 $dates = array_fill_keys([
5140 if ($currentMembership) {
5142 * Fixed FOR CRM-4433
5143 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5144 * when Contribution mode is notify and membership is for renewal )
5146 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
5148 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5150 // @todo - we should pass membership_type_id instead of null here but not
5151 // adding as not sure of testing
5152 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
5153 $changeDate, NULL, $membershipParams['num_terms']
5155 $dates['join_date'] = $currentMembership['join_date'];
5158 //get the status for membership.
5159 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
5161 $dates['join_date'],
5164 $membershipParams['membership_type_id'],
5168 unset($dates['end_date']);
5169 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
5170 //we might be renewing membership,
5171 //so make status override false.
5172 $membershipParams['is_override'] = FALSE;
5173 $membershipParams['status_override_end_date'] = 'null';
5174 civicrm_api3('Membership', 'create', $membershipParams);
5179 * Get payment links as they relate to a contribution.
5181 * If a payment can be made then include a payment link & if a refund is appropriate
5182 * then a refund link.
5185 * @param float $balance
5186 * @param string $contributionStatus
5189 * $actionLinks Links array containing:
5193 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5194 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5195 // In general the balance is the best way to determine if a payment can be added or not,
5196 // but not for Failed contributions, where we don't accept additional payments at the moment.
5197 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5198 // do accept more payments agains them.
5203 'url' => CRM_Utils_System
::url('civicrm/payment', [
5209 'title' => ts('Record Payment'),
5212 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5214 'url' => CRM_Utils_System
::url('civicrm/payment', [
5221 'title' => ts('Submit Credit Card payment'),
5225 'url' => CRM_Utils_System
::url('civicrm/payment', [
5231 'title' => ts('Record Refund'),
5233 return $actionLinks;
5237 * Get a query to determine the amount donated by the contact/s in the current financial year.
5239 * @param array $contactIDs
5243 public static function getAnnualQuery($contactIDs) {
5244 $contactIDs = implode(',', $contactIDs);
5245 $config = CRM_Core_Config
::singleton();
5246 $currentMonth = date('m');
5247 $currentDay = date('d');
5249 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5251 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5252 (int) $config->fiscalYearStart
['d'] > $currentDay
5255 $year = date('Y') - 1;
5260 $nextYear = $year +
1;
5262 if ($config->fiscalYearStart
) {
5263 $newFiscalYearStart = $config->fiscalYearStart
;
5264 if ($newFiscalYearStart['M'] < 10) {
5265 // This is just a clumsy way of adding padding.
5266 // @todo next round look for a nicer way.
5267 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5269 if ($newFiscalYearStart['d'] < 10) {
5270 // This is just a clumsy way of adding padding.
5271 // @todo next round look for a nicer way.
5272 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5274 $config->fiscalYearStart
= $newFiscalYearStart;
5275 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5278 // First of January.
5281 $startDate = "$year$monthDay";
5282 $endDate = "$nextYear$monthDay";
5285 'contact_id' => 'IN (' . $contactIDs . ')',
5286 'is_test' => ' = 0',
5287 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5289 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5290 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5293 foreach ($whereClauses as $key => $clause) {
5294 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5296 $whereClauseString = implode(' AND ', $clauses);
5298 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5299 // this group by + having on contribution_status_id improves performance
5301 SELECT COUNT(*) as count,
5302 SUM(total_amount) as amount,
5303 AVG(total_amount) as average,
5305 FROM civicrm_contribution b
5306 WHERE " . $whereClauseString . "
5307 GROUP BY currency, contribution_status_id
5308 HAVING $havingClause
5314 * Assign Test Value.
5316 * @param string $fieldName
5317 * @param array $fieldDef
5318 * @param int $counter
5320 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5321 if ($fieldName == 'tax_amount') {
5322 $this->{$fieldName} = "0.00";
5324 elseif ($fieldName == 'net_amount') {
5325 $this->{$fieldName} = "2.00";
5327 elseif ($fieldName == 'total_amount') {
5328 $this->{$fieldName} = "3.00";
5330 elseif ($fieldName == 'fee_amount') {
5331 $this->{$fieldName} = "1.00";
5334 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5339 * Check if contribution has participant/membership payment.
5341 * @param int $contributionId
5346 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5347 // get line item for contribution
5348 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5349 // check if line item is for membership or participant
5350 foreach ($lineItems as $items) {
5351 if ($items['entity_table'] == 'civicrm_participant') {
5355 elseif ($items['entity_table'] == 'civicrm_membership') {
5367 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5369 * @param array $trxnParams
5370 * Financial trxn params
5371 * @param array $contributionParams
5372 * Contribution Params
5376 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5377 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5380 $statusId = $contributionParams['contribution']->contribution_status_id
;
5381 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5382 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5383 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5384 // Return if contribution status is not completed.
5385 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5386 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5387 && $contributionParams['prevContribution']->is_pay_later
== 0
5393 $params = $trxnParams;
5394 $financialTypeID = !empty($contributionParams['financial_type_id']) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5395 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5396 $params['to_financial_account_id'] = $arAccountId;
5397 $params['status_id'] = array_search('Pending', $contributionStatuses);
5398 $params['is_payment'] = FALSE;
5399 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5400 self
::$_trxnIDs[] = $trxn->id
;
5401 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5405 * Calculate financial item amount when contribution is updated.
5407 * @param array $params
5408 * contribution params
5409 * @param array $amountParams
5411 * @param string $context
5415 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5416 if (!empty($params['is_quick_config'])) {
5417 $amount = $amountParams['item_amount'];
5419 $amount = $params['total_amount'];
5420 if ($context === NULL) {
5421 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5426 $amount = $amountParams['line_total'];
5427 if ($context == 'changedAmount') {
5428 $amount -= $amountParams['previous_line_total'];
5430 $amount *= $amountParams['diff'];
5436 * Retrieve Sales Tax Financial Accounts.
5442 public static function getSalesTaxFinancialAccounts() {
5443 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5444 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5445 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5446 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5447 $queryParams = [1 => [$accountRel, 'Integer']];
5448 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5449 $financialAccount = [];
5450 while ($dao->fetch()) {
5451 $financialAccount[$dao->id
] = $dao->id
;
5453 return $financialAccount;
5457 * Create tax entry in civicrm_entity_financial_trxn table.
5459 * @param array $entityParams
5461 * @param array $eftParams
5463 * @throws \CiviCRM_API3_Exception
5465 public static function createProportionalEntry($entityParams, $eftParams) {
5467 if ($entityParams['contribution_total_amount'] != 0) {
5468 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5470 // Record Entity Financial Trxn; CRM-20145
5471 $eftParams['amount'] = $paid;
5472 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5476 * Create array of last financial item id's.
5478 * @param int $contributionId
5482 public static function getLastFinancialItemIds($contributionId) {
5483 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5484 FROM civicrm_financial_item fi
5485 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5486 WHERE li.contribution_id = %1";
5487 $dao = CRM_Core_DAO
::executeQuery($sql, [
5493 $ftIds = $taxItems = [];
5494 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5495 while ($dao->fetch()) {
5496 /* if sales tax item*/
5497 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5498 $taxItems[$dao->price_field_value_id
] = [
5499 'financial_item_id' => $dao->id
,
5500 'amount' => $dao->tax_amount
,
5504 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5507 return [$ftIds, $taxItems];
5511 * Create proportional entries in civicrm_entity_financial_trxn.
5513 * @param array $entityParams
5515 * @param array $lineItems
5517 * @param array $ftIds
5519 * @param array $taxItems
5521 * @throws \CiviCRM_API3_Exception
5523 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5525 'entity_table' => 'civicrm_financial_item',
5526 'financial_trxn_id' => $entityParams['trxn_id'],
5528 foreach ($lineItems as $key => $value) {
5529 if ($value['qty'] == 0) {
5532 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5533 $entityParams['line_item_amount'] = $value['line_total'];
5534 self
::createProportionalEntry($entityParams, $eftParams);
5535 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5536 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5537 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5538 self
::createProportionalEntry($entityParams, $eftParams);
5544 * Load entities related to the contribution into $this->_relatedObjects.
5548 * @throws \CRM_Core_Exception
5550 protected function loadRelatedEntitiesByID($ids) {
5552 'contact' => 'CRM_Contact_BAO_Contact',
5553 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5554 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5555 'financialType' => 'CRM_Financial_BAO_FinancialType',
5556 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5558 foreach ($entities as $entity => $bao) {
5559 if (!empty($ids[$entity])) {
5560 $this->_relatedObjects
[$entity] = new $bao();
5561 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5562 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5563 throw new CRM_Core_Exception($entity . ' could not be loaded');
5570 * Function to replace contribution tokens.
5572 * @param array $contributionIds
5574 * @param string $subject
5576 * @param array $subjectToken
5578 * @param string $text
5580 * @param string $html
5582 * @param array $messageToken
5584 * @param bool $escapeSmarty
5587 * @throws \CiviCRM_API3_Exception
5589 public static function replaceContributionTokens(
5598 if (empty($contributionIds)) {
5601 $contributionDetails = [];
5602 foreach ($contributionIds as $id) {
5603 $result = self
::getContributionTokenValues($id, $messageToken);
5604 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5605 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5606 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5608 return $contributionDetails;
5612 * Get the contribution fields for $id and display labels where
5613 * appropriate (if the token is present).
5616 * @param array $messageToken
5619 public static function getContributionTokenValues($id, $messageToken) {
5623 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5624 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5625 if (!empty($messageToken)) {
5626 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5627 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5628 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5636 * Get invoice_number for contribution.
5638 * @param int $contributionID
5642 public static function getInvoiceNumber($contributionID) {
5643 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix')) {
5644 return $invoicePrefix . $contributionID;
5651 * Load the values needed for the event message.
5653 * @param int $eventID
5654 * @param int $participantID
5655 * @param int|null $contributionID
5658 * @throws \CRM_Core_Exception
5660 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5665 $values = ['event' => []];
5667 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5668 // add custom fields for event
5669 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5671 $eventCustomGroup = [];
5672 foreach ($eventGroupTree as $key => $group) {
5673 if ($key === 'info') {
5677 foreach ($group['fields'] as $k => $customField) {
5678 $groupLabel = $group['title'];
5679 if (!empty($customField['customValue'])) {
5680 foreach ($customField['customValue'] as $customFieldValues) {
5681 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5686 $values['event']['customGroup'] = $eventCustomGroup;
5688 //get participant details
5689 $participantParams = [
5690 'id' => $participantID,
5693 $values['participant'] = [];
5695 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5696 // add custom fields for event
5697 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5698 $participantCustomGroup = [];
5699 foreach ($participantGroupTree as $key => $group) {
5700 if ($key === 'info') {
5704 foreach ($group['fields'] as $k => $customField) {
5705 $groupLabel = $group['title'];
5706 if (!empty($customField['customValue'])) {
5707 foreach ($customField['customValue'] as $customFieldValues) {
5708 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5713 $values['participant']['customGroup'] = $participantCustomGroup;
5715 //get location details
5717 'entity_id' => $eventID,
5718 'entity_table' => 'civicrm_event',
5720 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5723 'entity_table' => 'civicrm_event',
5724 'entity_id' => $eventID,
5725 'module' => 'CiviEvent',
5728 list($custom_pre_id,
5730 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5732 $values['custom_pre_id'] = $custom_pre_id;
5733 $values['custom_post_id'] = $custom_post_ids;
5735 // set lineItem for event contribution
5736 if ($contributionID) {
5737 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5738 if (!empty($participantIds)) {
5739 foreach ($participantIds as $pIDs) {
5740 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5741 if (!CRM_Utils_System
::isNull($lineItem)) {
5742 $values['lineItem'][] = $lineItem;