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 = new CRM_Core_DAO();
2275 if ($dao->fetch()) {
2276 if (!empty($dao->membership_type_id
)) {
2277 $membership->membership_type_id
= $dao->membership_type_id
;
2278 $membership->save();
2281 // else fall back to using current membership type
2282 // Figure out number of terms
2284 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2285 foreach ($lineitems as $lineitem) {
2286 if ($membership->membership_type_id
== ($lineitem['membership_type_id'] ??
NULL)) {
2287 $numterms = $lineitem['membership_num_terms'] ??
NULL;
2289 // in case membership_num_terms comes through as null or zero
2290 $numterms = $numterms >= 1 ?
$numterms : 1;
2295 // CRM-15735-to update the membership status as per the contribution receive date
2297 $oldStatus = $membership->status_id
;
2298 if (!empty($params['receive_date'])) {
2299 $joinDate = $params['receive_date'];
2300 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2301 $membership->end_date
,
2302 $membership->join_date
,
2303 $params['receive_date'],
2305 $membership->membership_type_id
,
2308 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2309 $membership->save();
2312 if ($currentMembership) {
2313 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2314 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2315 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2318 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2321 //get the status for membership.
2322 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2324 $dates['join_date'],
2327 $membership->membership_type_id
,
2331 $formattedParams = [
2332 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2333 array_search('Current', $membershipStatuses)
2335 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2336 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2337 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2340 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2342 $membership->copyValues($formattedParams);
2343 $membership->save();
2345 //updating the membership log
2346 $membershipLog = [];
2347 $membershipLog = $formattedParams;
2348 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'] ??
NULL, $format);
2349 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2351 $membershipLog['start_date'] = $logStartDate;
2352 $membershipLog['membership_id'] = $membership->id
;
2353 $membershipLog['modified_id'] = $membership->contact_id
;
2354 $membershipLog['modified_date'] = date('Ymd');
2355 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2357 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2359 //update related Memberships.
2360 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2362 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2363 $scheduledActivityID = CRM_Utils_Array
::value('id',
2364 civicrm_api3('Activity', 'Get',
2366 'source_record_id' => $membership->id
,
2367 'activity_type_id' => $activityType,
2368 'status_id' => 'Scheduled',
2371 'sort' => 'id DESC',
2376 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2377 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2378 if ($scheduledActivityID) {
2379 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2384 // track membership status change if any
2385 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2386 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2387 CRM_Activity_BAO_Activity
::addActivity($membership,
2388 'Change Membership Status',
2391 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2392 'source_contact_id' => $membershipLog['modified_id'],
2393 'priority_id' => 'Normal',
2398 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2399 if ($processContributionObject) {
2400 $processContribution = TRUE;
2403 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2409 $updatedStatusId = array_search('Registered', $participantStatuses);
2410 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2412 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2413 if ($processContributionObject) {
2414 $processContribution = TRUE;
2418 if ($pledgePayment) {
2419 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2421 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2422 if ($processContributionObject) {
2423 $processContribution = TRUE;
2428 // process contribution object.
2429 if ($processContribution) {
2430 $contributionParams = [];
2437 'payment_instrument_id',
2440 'financial_type_id',
2441 'contribution_status_id',
2442 'non_deductible_amount',
2446 foreach ($fields as $field) {
2447 if (empty($params[$field])) {
2450 $contributionParams[$field] = $params[$field];
2453 $contributionParams['id'] = $contributionId;
2454 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2457 return $updateResult;
2461 * Returns all contribution related object ids.
2463 * @param $contributionId
2467 public static function getComponentDetails($contributionId) {
2468 $componentDetails = $pledgePayment = [];
2469 if (!$contributionId) {
2470 return $componentDetails;
2474 SELECT c.id as contribution_id,
2475 c.contact_id as contact_id,
2476 c.contribution_recur_id,
2477 mp.membership_id as membership_id,
2478 m.membership_type_id as membership_type_id,
2479 pp.participant_id as participant_id,
2480 p.event_id as event_id,
2481 pgp.id as pledge_payment_id
2482 FROM civicrm_contribution c
2483 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2484 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2485 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2486 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2487 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2488 WHERE c.id = $contributionId";
2490 $dao = CRM_Core_DAO
::executeQuery($query);
2491 $componentDetails = [];
2493 while ($dao->fetch()) {
2494 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2495 $componentDetails['contact_id'] = $dao->contact_id
;
2496 if ($dao->event_id
) {
2497 $componentDetails['event'] = $dao->event_id
;
2499 if ($dao->participant_id
) {
2500 $componentDetails['participant'] = $dao->participant_id
;
2502 if ($dao->membership_id
) {
2503 if (!isset($componentDetails['membership'])) {
2504 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2506 $componentDetails['membership'][] = $dao->membership_id
;
2507 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2509 if ($dao->pledge_payment_id
) {
2510 $pledgePayment[] = $dao->pledge_payment_id
;
2512 if ($dao->contribution_recur_id
) {
2513 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2517 if ($pledgePayment) {
2518 $componentDetails['pledge_payment'] = $pledgePayment;
2521 return $componentDetails;
2525 * @param int $contactId
2526 * @param bool $includeSoftCredit
2528 * @return null|string
2530 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2534 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2535 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2536 $liWhere = " AND i.financial_type_id IN (0)";
2537 if (!empty($financialTypes)) {
2538 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2539 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2541 $contactContributionsSQL = "
2542 SELECT contribution.id AS id
2543 FROM civicrm_contribution contribution
2544 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2545 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2549 $contactSoftCreditContributionsSQL = "
2550 SELECT contribution.id
2551 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2552 ON ( contribution.id = softContribution.contribution_id )
2553 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2554 $query = "SELECT count( x.id ) count FROM ( ";
2555 $query .= $contactContributionsSQL;
2557 if ($includeSoftCredit) {
2558 $query .= " UNION ";
2559 $query .= $contactSoftCreditContributionsSQL;
2564 return CRM_Core_DAO
::singleValueQuery($query);
2568 * Repeat a transaction as part of a recurring series.
2571 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2572 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2573 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2574 * and associated entities.
2575 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2576 * which updates the various entities and sends appropriate emails.
2578 * Gaps in the above (@todo)
2579 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2580 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2581 * 3) Repeat transaction duplicates rather than calls Order.create
2582 * 4) Use of payment.create still limited - completetransaction is more common.
2583 * 5) the template transaction is tricky - historically we used the first contribution
2584 * linked to a recurring contribution. More recently that was changed to be the most recent.
2585 * Ideally it would be an actual template - not a contribution used as a template which
2586 * would give more appropriate flexibility. Note line_items have an entity so that table
2587 * could be used for the line item template - the difficulty is the custom fields...
2588 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2589 * to load the membership(s) referred to via line items in the template transactions. Any other
2590 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2591 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2592 * - membership_payment record
2593 * - civicrm_membership.contribution_recur_id
2595 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2596 * of historical processors since this has been handled 'forever' - specifically for paypal.
2597 * albeit by an even nastier mechanism than the current input override.
2598 * The count is out on how correct related entities wind up in this case.
2600 * @param CRM_Contribute_BAO_Contribution $contribution
2601 * @param array $input
2602 * @param array $contributionParams
2604 * @return bool|array
2605 * @throws CiviCRM_API3_Exception
2607 protected static function repeatTransaction(&$contribution, $input, $contributionParams) {
2608 if (!empty($contribution->id
)) {
2611 if (empty($contribution->id
)) {
2612 // Unclear why this would only be set for repeats.
2613 if (!empty($input['amount'])) {
2614 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2617 if (!empty($contributionParams['contribution_recur_id'])) {
2618 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2619 'id' => $contributionParams['contribution_recur_id'],
2621 if (!empty($recurringContribution['campaign_id'])) {
2622 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2623 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2625 if (!empty($recurringContribution['financial_type_id'])) {
2626 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2627 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2630 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2631 $contributionParams['contribution_recur_id'],
2632 array_intersect_key($contributionParams, [
2633 'total_amount' => TRUE,
2634 'financial_type_id' => TRUE,
2637 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2638 $contributionParams['status_id'] = 'Pending';
2640 if (isset($contributionParams['financial_type_id']) && count($input['line_item']) === 1) {
2641 // We permit the financial type to be overridden for single line items.
2642 // More comments on this are in getTemplateTransaction.
2643 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2646 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2648 foreach (['contact_id', 'currency', 'source'] as $fieldName) {
2649 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2652 $contributionParams['source'] = $contributionParams['source'] ?
: ts('Recurring contribution');
2654 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2655 //do not create CC or BCC emails or profile notifications.
2656 //The if is just to be safe. Not sure if we can ever arrive with this unset
2657 // but per CRM-19478 it seems it can be 'null'
2658 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2659 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2661 if (!empty($contribution->tax_amount
)) {
2662 $contributionParams['tax_amount'] = $contribution->tax_amount
;
2665 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2666 $contribution->id
= $createContribution['id'];
2667 $contribution->copyCustomFields($templateContribution['id'], $contribution->id
);
2668 self
::handleMembershipIDOverride($contribution->id
, $input);
2669 return $createContribution;
2674 * Get individual id for onbehalf contribution.
2676 * @param int $contributionId
2678 * @param int $contributorId
2682 * containing organization id and individual id
2684 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2688 if (!$contributionId) {
2692 // fetch contributor id if null
2693 if (!$contributorId) {
2694 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2695 $contributionId, 'contact_id'
2699 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2700 $activityTypeId = array_search('Contribution', $activityTypeIds);
2702 if ($activityTypeId && $contributorId) {
2704 SELECT civicrm_activity_contact.contact_id
2705 FROM civicrm_activity_contact
2706 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2707 WHERE civicrm_activity.activity_type_id = %1
2708 AND civicrm_activity.source_record_id = %2
2709 AND civicrm_activity_contact.record_type_id = %3
2712 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2713 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2716 1 => [$activityTypeId, 'Integer'],
2717 2 => [$contributionId, 'Integer'],
2718 3 => [$sourceID, 'Integer'],
2721 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2723 // for on behalf contribution source is individual and contributor is organization
2724 if ($sourceContactId && $sourceContactId != $contributorId) {
2725 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2726 // get rel type id for employee of relation
2727 foreach ($relationshipTypeIds as $id => $typeVals) {
2728 if ($typeVals['name_a_b'] == 'Employee of') {
2729 $relationshipTypeId = $id;
2734 $rel = new CRM_Contact_DAO_Relationship();
2735 $rel->relationship_type_id
= $relationshipTypeId;
2736 $rel->contact_id_a
= $sourceContactId;
2737 $rel->contact_id_b
= $contributorId;
2738 if ($rel->find(TRUE)) {
2739 $ids['individual_id'] = $rel->contact_id_a
;
2740 $ids['organization_id'] = $rel->contact_id_b
;
2751 public static function getContributionDates() {
2752 $config = CRM_Core_Config
::singleton();
2753 $currentMonth = date('m');
2754 $currentDay = date('d');
2755 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2756 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2757 (int ) $config->fiscalYearStart
['d'] > $currentDay
2760 $year = date('Y') - 1;
2765 $year = ['Y' => $year];
2766 $yearDate = $config->fiscalYearStart
;
2767 $yearDate = array_merge($year, $yearDate);
2768 $yearDate = CRM_Utils_Date
::format($yearDate);
2770 $monthDate = date('Ym') . '01';
2776 'yearDate' => $yearDate,
2777 'monthDate' => $monthDate,
2782 * Load objects relations to contribution object.
2783 * Objects are stored in the $_relatedObjects property
2784 * In the first instance we are just moving functionality from BASEIpn -
2786 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2788 * Note that the unit test for the BaseIPN class tests this function
2790 * @param array $input
2791 * Input as delivered from Payment Processor.
2793 * Ids as Loaded by Payment Processor.
2794 * @param bool $loadAll
2795 * Load all related objects - even where id not passed in? (allows API to call this).
2798 * @throws CRM_Core_Exception
2800 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
2801 // @todo deprecate this function - the steps should be
2802 // 1) add additional functions like 'getRelatedMemberships'
2803 // 2) switch all calls that refer to ->_relatedObjects to
2804 // using the helper functions
2805 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2806 // 4) make ->_relatedObjects protected
2807 // 5) hone up the individual functions to not use rely on this having been called
2808 // 6) deprecate like mad
2810 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2811 if (empty($ids['contact']) && isset($this->contact_id
)) {
2812 $ids['contact'] = $this->contact_id
;
2815 if (empty($this->_component
)) {
2816 if (!empty($ids['event'])) {
2817 $this->_component
= 'event';
2820 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2824 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2825 // refactoring than anything else, and has unit test coverage.
2826 if (empty($this->financial_type_id
)) {
2830 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2835 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2836 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2837 $this->contribution_page_id
,
2840 if ($paymentProcessorID) {
2841 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2845 $ids['contributionType'] = $this->financial_type_id
;
2846 $ids['financialType'] = $this->financial_type_id
;
2847 if ($this->contribution_page_id
) {
2848 $ids['contributionPage'] = $this->contribution_page_id
;
2851 $this->loadRelatedEntitiesByID($ids);
2853 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2854 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2857 if (!empty($ids['pledge_payment'])) {
2858 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2859 if (empty($paymentID)) {
2862 $payment = new CRM_Pledge_BAO_PledgePayment();
2863 $payment->id
= $paymentID;
2864 if (!$payment->find(TRUE)) {
2865 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
2867 $this->_relatedObjects
['pledge_payment'][] = $payment;
2871 // These are probably no longer accessed from anywhere
2872 // @todo remove this line, after ensuring not used.
2873 $ids = $this->loadRelatedMembershipObjects($ids);
2875 if ($this->_component
!= 'contribute') {
2876 // we are in event mode
2877 // make sure event exists and is valid
2878 $event = new CRM_Event_BAO_Event();
2879 $event->id
= $ids['event'];
2880 if ($ids['event'] &&
2883 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
2886 $this->_relatedObjects
['event'] = &$event;
2888 $participant = new CRM_Event_BAO_Participant();
2889 $participant->id
= $ids['participant'];
2890 if ($ids['participant'] &&
2891 !$participant->find(TRUE)
2893 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
2895 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2897 $this->_relatedObjects
['participant'] = &$participant;
2899 // get the payment processor id from event - this is inaccurate see CRM-16923
2900 // in future we should look at throwing an exception here rather than an dubious guess.
2901 if (!$paymentProcessorID) {
2902 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2903 if ($paymentProcessorID) {
2904 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2909 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($this->id
);
2910 if (!empty($relatedContact['individual_id'])) {
2911 $ids['related_contact'] = $relatedContact['individual_id'];
2914 if ($paymentProcessorID) {
2915 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2916 $this->is_test ?
'test' : 'live'
2918 $ids['paymentProcessor'] = $paymentProcessorID;
2919 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2922 // Add contribution id to $ids. CRM-20401
2923 $ids['contribution'] = $this->id
;
2928 * Create array of message information - ie. return html version, txt version, to field
2930 * @param array $input
2931 * Incoming information.
2932 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2933 * just check presence of recur object but maintaining legacy approach
2936 * IDs of related objects.
2937 * @param array $values
2938 * Any values that may have already been compiled by calling process.
2939 * This is augmented by values 'gathered' by gatherMessageValues
2940 * @param bool $returnMessageText
2941 * Distinguishes between whether to send message or return.
2942 * message text. We are working towards this function ALWAYS returning message text & calling
2943 * function doing emails / pdfs with it
2949 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2950 $this->loadRelatedObjects($input, $ids);
2952 if (empty($this->_component
)) {
2953 $this->_component
= $input['component'] ??
NULL;
2956 //not really sure what params might be passed in but lets merge em into values
2957 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2958 $values['is_email_receipt'] = !$returnMessageText;
2959 if (!empty($input['receipt_date'])) {
2960 $values['receipt_date'] = $input['receipt_date'];
2963 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2964 //what does recur 'mean here - to do with payment processor return functionality but
2965 // what is the importance
2966 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2967 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2969 $entityID = $entity = NULL;
2970 if (isset($ids['contribution'])) {
2971 $entity = 'contribution';
2972 $entityID = $ids['contribution'];
2974 if (!empty($ids['membership'])) {
2975 //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
2976 // 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
2977 // line having loaded an array
2978 $ids['membership'] = (array) $ids['membership'];
2979 $entity = 'membership';
2980 $entityID = $ids['membership'][0];
2983 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2984 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2985 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2987 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2988 //direct mode showing billing block, so use directIPN for temporary
2989 $template->assign('contributeMode', 'directIPN');
2992 // todo remove strtolower - check consistency
2993 if (strtolower($this->_component
) == 'event') {
2994 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2995 $values['event'] = [];
2997 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2999 //get location details
3001 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
3002 'entity_table' => 'civicrm_event',
3004 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
3007 'entity_table' => 'civicrm_event',
3008 'entity_id' => $ids['event'],
3009 'module' => 'CiviEvent',
3012 list($custom_pre_id,
3014 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
3016 $values['custom_pre_id'] = $custom_pre_id;
3017 $values['custom_post_id'] = $custom_post_ids;
3018 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
3019 //and cases involving status updation through ipn
3020 // whatever that means!
3021 // total_amount appears to be the preferred input param & it is unclear why we support amount here
3022 // perhaps we should throw an e-notice if amount is set & force total_amount?
3023 if (!empty($input['amount'])) {
3024 $values['totalAmount'] = $input['amount'];
3026 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
3027 if ($values['event']['is_email_confirm']) {
3028 $values['is_email_receipt'] = 1;
3031 if (!empty($ids['contribution'])) {
3032 $values['contributionId'] = $ids['contribution'];
3035 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
3036 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
3040 $values['contribution_id'] = $this->id
;
3041 if (!empty($ids['related_contact'])) {
3042 $values['related_contact'] = $ids['related_contact'];
3043 if (isset($ids['onbehalf_dupe_alert'])) {
3044 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
3047 'contact_id' => $ids['contact'],
3048 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
3049 'Home', 'id', 'name'
3052 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
3053 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
3056 if ($this->is_test
) {
3059 if (!empty($this->_relatedObjects
['membership'])) {
3060 foreach ($this->_relatedObjects
['membership'] as $membership) {
3061 if ($membership->id
) {
3062 $values['membership_id'] = $membership->id
;
3063 $values['isMembership'] = TRUE;
3064 $values['membership_assign'] = TRUE;
3066 // need to set the membership values here
3067 $template->assign('membership_name',
3068 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
3070 $template->assign('mem_start_date', $membership->start_date
);
3071 $template->assign('mem_join_date', $membership->join_date
);
3072 $template->assign('mem_end_date', $membership->end_date
);
3073 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
3074 $template->assign('mem_status', $membership_status);
3075 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
3076 $values['is_pay_later'] = 1;
3078 // Pass amount to floatval as string '0.00' is considered a
3079 // valid amount and includes Fee section in the mail.
3080 if (isset($values['amount'])) {
3081 $values['amount'] = floatval($values['amount']);
3084 if (!empty($this->contribution_recur_id
) && $paymentObject) {
3085 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
3086 $template->assign('cancelSubscriptionUrl', $url);
3087 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
3088 $template->assign('updateSubscriptionBillingUrl', $url);
3089 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
3090 $template->assign('updateSubscriptionUrl', $url);
3093 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3096 // otherwise if its about sending emails, continue sending without return, as we
3097 // don't want to exit the loop.
3102 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3108 * Gather values for contribution mail - this function has been created
3109 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3110 * Values related to the contribution in question are gathered
3112 * @param array $input
3113 * Input into function (probably from payment processor).
3114 * @param array $values
3116 * The set of ids related to the input.
3119 * @throws \CRM_Core_Exception
3121 public function _gatherMessageValues($input, &$values, $ids = []) {
3122 // set display address of contributor
3123 $values['billingName'] = '';
3124 if ($this->address_id
) {
3125 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
3126 $addressDetails = reset($addressDetails);
3127 $values['billingName'] = $addressDetails['name'] ??
'';
3129 // Else we assign the billing address of the contribution contact.
3131 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
3132 $addressDetails = reset($addressDetails);
3134 $values['address'] = $addressDetails['display'] ??
'';
3136 if ($this->_component
=== 'contribute') {
3137 //get soft contributions
3138 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
3139 if (!empty($softContributions)) {
3140 // For pcp soft credit, there is no 'soft_credit' member it comes
3141 // back in different array members, but shortly after returning from
3142 // this function it calls _assignMessageVariablesToTemplate which does
3143 // its own lookup of any pcp soft credit, so we can skip it here.
3144 $values['softContributions'] = $softContributions['soft_credit'] ??
NULL;
3146 if (isset($this->contribution_page_id
)) {
3147 // This is a call we want to use less, in favour of loading related objects.
3148 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3149 if ($this->contribution_page_id
) {
3150 // This is precautionary as there are some legacy flows, but it should really be
3152 if (!isset($this->_relatedObjects
['contributionPage'])) {
3153 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
3155 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3158 // no contribution page -probably back office
3160 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3161 $values['title'] = 'Contribution';
3163 // set lineItem for contribution
3165 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3166 if (!empty($lineItems)) {
3167 $firstLineItem = reset($lineItems);
3169 if (!empty($firstLineItem['price_set_id'])) {
3170 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3171 'id' => $firstLineItem['price_set_id'],
3172 'return' => 'is_quick_config, id',
3174 $values['priceSetID'] = $priceSet['id'];
3176 foreach ($lineItems as &$eachItem) {
3177 if (isset($this->_relatedObjects
['membership'])
3178 && is_array($this->_relatedObjects
['membership'])
3179 && array_key_exists($eachItem['entity_id'] . '_' . $eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
3180 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->join_date
);
3181 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->start_date
);
3182 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->end_date
);
3184 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3185 // However, that does create upgrade pain so would be better to be phased in.
3186 $values['useForMember'] = empty($priceSet['is_quick_config']);
3188 $values['lineItem'][0] = $lineItems;
3192 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3196 // if this is onbehalf of contribution then set related contact
3197 if (!empty($relatedContact['individual_id'])) {
3198 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3202 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3205 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3208 foreach ($groupTree as $key => $group) {
3209 if ($key === 'info') {
3213 foreach ($group['fields'] as $k => $customField) {
3214 $groupLabel = $group['title'];
3215 if (!empty($customField['customValue'])) {
3216 foreach ($customField['customValue'] as $customFieldValues) {
3217 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
3222 $values['customGroup'] = $customGroup;
3224 $values['is_pay_later'] = $this->is_pay_later
;
3230 * Assign message variables to template but try to break the habit.
3232 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3233 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3234 * multiple recurring payments for processors like IATS that use tokens.
3236 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3237 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3238 * Note we send directly from this function in some cases because it is only partly refactored.
3240 * Don't call this function directly as the signature will change.
3244 * @param bool $returnMessageText
3248 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3249 // @todo - this should have a better separation of concerns - ie.
3250 // gatherMessageValues should build an array of values to be assigned to the template
3251 // and this function should assign them (assigning null if not set).
3252 // the way the pcpParams & honor Params section works is a baby-step towards this.
3253 $template = CRM_Core_Smarty
::singleton();
3254 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3255 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3256 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3257 $template->assign('billingName', $values['billingName']);
3259 // For some unit tests contribution cannot contain paymentProcessor information
3260 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3261 $template->assign('contributeMode', CRM_Core_SelectValues
::contributeMode()[$billingMode] ??
NULL);
3263 //assign honor information to receipt message
3264 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3267 'soft_credit_type' => NULL,
3268 'honor_block_is_active' => NULL,
3270 if (isset($softRecord['soft_credit'])) {
3271 //if id of contribution page is present
3272 if (!empty($values['id'])) {
3273 $values['honor'] = [
3274 'honor_profile_values' => [],
3275 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3276 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3279 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3280 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3283 //offline contribution
3284 $softCreditTypes = $softCredits = [];
3285 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3286 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3287 $softCredits[$key] = [
3288 'Name' => $softCredit['contact_name'],
3289 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3292 $template->assign('softCreditTypes', $softCreditTypes);
3293 $template->assign('softCredits', $softCredits);
3297 $dao = new CRM_Contribute_DAO_ContributionProduct();
3298 $dao->contribution_id
= $this->id
;
3299 if ($dao->find(TRUE)) {
3300 $premiumId = $dao->product_id
;
3301 $template->assign('option', $dao->product_option
);
3303 $productDAO = new CRM_Contribute_DAO_Product();
3304 $productDAO->id
= $premiumId;
3305 $productDAO->find(TRUE);
3306 $template->assign('selectPremium', TRUE);
3307 $template->assign('product_name', $productDAO->name
);
3308 $template->assign('price', $productDAO->price
);
3309 $template->assign('sku', $productDAO->sku
);
3311 $template->assign('title', $values['title'] ??
NULL);
3312 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3313 if (!$values['amount'] && isset($this->total_amount
)) {
3314 $values['amount'] = $this->total_amount
;
3319 'pcp_display_in_roll' => NULL,
3320 'pcp_roll_nickname' => NULL,
3321 'pcp_personal_note' => NULL,
3325 if (strtolower($this->_component
) == 'contribute') {
3327 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3328 $softDAO->contribution_id
= $this->id
;
3329 if ($softDAO->find(TRUE)) {
3330 $pcpParams['pcpBlock'] = TRUE;
3331 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3332 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3333 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3335 //assign the pcp page title for email subject
3336 $pcpDAO = new CRM_PCP_DAO_PCP();
3337 $pcpDAO->id
= $softDAO->pcp_id
;
3338 if ($pcpDAO->find(TRUE)) {
3339 $pcpParams['title'] = $pcpDAO->title
;
3343 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3344 $template->assign($templateKey, $templateValue);
3347 if ($this->financial_type_id
) {
3348 $values['financial_type_id'] = $this->financial_type_id
;
3351 $template->assign('trxn_id', $this->trxn_id
);
3352 $template->assign('receive_date',
3353 CRM_Utils_Date
::processDate($this->receive_date
)
3355 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3356 $template->assign('action', $this->is_test ?
1024 : 1);
3357 $template->assign('receipt_text', $values['receipt_text'] ??
NULL);
3358 $template->assign('is_monetary', 1);
3359 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3360 $template->assign('currency', $this->currency
);
3361 $template->assign('address', CRM_Utils_Address
::format($input));
3362 if (!empty($values['customGroup'])) {
3363 $template->assign('customGroup', $values['customGroup']);
3365 if (!empty($values['softContributions'])) {
3366 $template->assign('softContributions', $values['softContributions']);
3368 if ($this->_component
== 'event') {
3369 $template->assign('title', $values['event']['title']);
3370 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3372 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3373 $viewRoles[] = $participantRoles[$v];
3375 $values['event']['participant_role'] = implode(', ', $viewRoles);
3376 $template->assign('event', $values['event']);
3377 $template->assign('participant', $values['participant']);
3378 $template->assign('location', $values['location']);
3379 $template->assign('customPre', $values['custom_pre_id']);
3380 $template->assign('customPost', $values['custom_post_id']);
3383 if ($this->_relatedObjects
['participant']->is_test
) {
3387 $values['params'] = [];
3388 //to get email of primary participant.
3389 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3390 $primaryAmount[] = [
3391 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3392 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3394 //build an array of cId/pId of participants
3395 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3396 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3397 //send receipt to additional participant if exists
3398 if (count($additionalIDs)) {
3399 $template->assign('isPrimary', 0);
3400 $template->assign('customProfile', NULL);
3401 //set additionalParticipant true
3402 $values['params']['additionalParticipant'] = TRUE;
3403 foreach ($additionalIDs as $pId => $cId) {
3405 //to change the status pending to completed
3406 $additional = new CRM_Event_DAO_Participant();
3407 $additional->id
= $pId;
3408 $additional->contact_id
= $cId;
3409 $additional->find(TRUE);
3410 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3411 $additional->status_id
= 1;
3412 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3413 //if additional participant dont have email
3415 if (!$additionalParticipantInfo) {
3416 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3419 'label' => $additional->fee_level
,
3420 'amount' => $additional->fee_amount
,
3422 $primaryAmount[] = [
3423 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3424 'amount' => $additional->fee_amount
,
3426 $additional->save();
3427 $template->assign('amount', $amount);
3428 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3432 //build an array of custom profile and assigning it to template
3433 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3435 if (count($customProfile)) {
3436 $template->assign('customProfile', $customProfile);
3439 // for primary contact
3440 $values['params']['additionalParticipant'] = FALSE;
3441 $template->assign('isPrimary', 1);
3442 $template->assign('amount', $primaryAmount);
3443 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3444 if ($this->payment_instrument_id
) {
3445 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3446 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3448 // carry paylater, since we did not created billing,
3449 // so need to pull email from primary location, CRM-4395
3450 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3456 * Check whether payment processor supports
3457 * cancellation of contribution subscription
3459 * @param int $contributionId
3462 * @param bool $isNotCancelled
3466 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3467 $cacheKeyString = "$contributionId";
3468 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3470 static $supportsCancel = [];
3472 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3473 $supportsCancel[$cacheKeyString] = FALSE;
3474 $isCancelled = FALSE;
3476 if ($isNotCancelled) {
3477 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3480 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3481 if (!empty($paymentObject)) {
3482 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3485 return $supportsCancel[$cacheKeyString];
3489 * Check whether subscription is already cancelled.
3491 * @param int $contributionId
3495 * contribution status
3497 public static function isSubscriptionCancelled($contributionId) {
3499 SELECT cr.contribution_status_id
3500 FROM civicrm_contribution_recur cr
3501 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3502 WHERE con.id = %1 LIMIT 1";
3503 $params = [1 => [$contributionId, 'Integer']];
3504 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3505 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3506 if ($status == 'Cancelled') {
3513 * Create all financial accounts entry.
3515 * @param array $params
3516 * Contribution object, line item array and params for trxn.
3519 * @param array $financialTrxnValues
3521 * @return null|\CRM_Core_BAO_FinancialTrxn
3523 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3524 $skipRecords = $update = $return = $isRelatedId = FALSE;
3525 $isUpdate = !empty($params['prevContribution']);
3527 $additionalParticipantId = [];
3528 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3529 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3531 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3532 $entityId = $params['participant_id'];
3533 $entityTable = 'civicrm_participant';
3534 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3536 elseif (!empty($params['membership_id'])) {
3537 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3538 // are created off one contribution should be handled elsewhere
3539 $entityId = $params['membership_id'];
3540 $entityTable = 'civicrm_membership';
3543 $entityId = $params['contribution']->id
;
3544 $entityTable = 'civicrm_contribution';
3547 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3548 $isRelatedId = TRUE;
3551 $entityID[] = $entityId;
3552 if (!empty($additionalParticipantId)) {
3553 $entityID +
= $additionalParticipantId;
3555 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3556 if (empty($params['prevContribution'])) {
3560 $statusId = $params['contribution']->contribution_status_id
;
3562 // build line item array if its not set in $params
3563 if (empty($params['line_item']) ||
$additionalParticipantId) {
3564 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3567 if ($contributionStatus != 'Failed' &&
3568 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3570 $skipRecords = TRUE;
3575 if (in_array($contributionStatus, $pendingStatus)) {
3576 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3577 $params['financial_type_id'],
3578 'Accounts Receivable Account is'
3581 elseif (!empty($params['payment_processor'])) {
3582 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3583 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3584 'id' => $params['payment_processor'],
3585 'return' => 'payment_instrument_id',
3588 elseif (!empty($params['payment_instrument_id'])) {
3589 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3592 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3593 $queryParams = [1 => [$relationTypeId, 'Integer']];
3594 $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);
3597 $totalAmount = $params['total_amount'] ??
NULL;
3598 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3599 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3601 //build financial transaction params
3603 'contribution_id' => $params['contribution']->id
,
3604 'to_financial_account_id' => $params['to_financial_account_id'],
3605 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3606 'total_amount' => $totalAmount,
3607 'fee_amount' => $params['fee_amount'] ??
NULL,
3608 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3609 'currency' => $params['contribution']->currency
,
3610 'trxn_id' => $params['contribution']->trxn_id
,
3611 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3612 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3613 // this should really default to completed (after discussion).
3614 'status_id' => $statusId,
3615 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3616 'check_number' => $params['check_number'] ??
NULL,
3617 'pan_truncation' => $params['pan_truncation'] ??
NULL,
3618 'card_type_id' => $params['card_type_id'] ??
NULL,
3620 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3621 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3622 if (isset($params['refund_trxn_id'])) {
3623 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3624 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3627 //CRM-16259, set is_payment flag for non pending status
3628 if (!in_array($contributionStatus, $pendingStatus)) {
3629 $trxnParams['is_payment'] = 1;
3631 if (!empty($params['payment_processor'])) {
3632 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3635 if (isset($fromFinancialAccountId)) {
3636 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3639 // consider external values passed for recording transaction entry
3640 if (!empty($financialTrxnValues)) {
3641 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3643 if (empty($trxnParams['payment_processor_id'])) {
3644 unset($trxnParams['payment_processor_id']);
3647 $params['trxnParams'] = $trxnParams;
3651 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3652 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3653 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3654 if (!isset($params['trxnParams']['trxn_id'])) {
3655 // Actually I have no idea why we are overwriting any values from the previous contribution.
3656 // (filling makes sense to me). However, only protecting this value as I really really know we
3657 // don't want this one overwritten.
3659 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3661 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3663 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3664 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3665 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3667 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3668 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3671 //if financial type is changed
3672 if (!empty($params['financial_type_id']) &&
3673 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3675 $accountRelationship = 'Income Account is';
3676 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3677 $accountRelationship = 'Deferred Revenue Account is';
3679 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3680 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3681 if ($oldFinancialAccount != $newFinancialAccount) {
3682 $params['total_amount'] = 0;
3683 // If we have a fee amount set reverse this as well.
3684 if (isset($params['fee_amount'])) {
3685 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3687 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3688 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3689 $params['prevContribution']->financial_type_id
, $accountRelationship);
3692 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3693 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3694 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3697 self
::updateFinancialAccounts($params, 'changeFinancialType');
3698 $params['skipLineItem'] = FALSE;
3699 foreach ($params['line_item'] as &$lineItems) {
3700 foreach ($lineItems as &$line) {
3701 $line['financial_type_id'] = $params['financial_type_id'];
3704 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3705 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3706 $params['financial_account_id'] = $newFinancialAccount;
3707 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3708 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3709 if (isset($params['fee_amount'])) {
3710 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3712 self
::updateFinancialAccounts($params);
3713 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3714 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3716 $params['deferred_financial_account_id'] = $newFinancialAccount;
3720 //Update contribution status
3721 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3722 if (!isset($params['refund_trxn_id'])) {
3723 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3724 // gets preference over another so I am only 'protecting' a very specific tested flow
3725 // and letting natural justice take care of the rest.
3726 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3728 if (!empty($params['contribution_status_id']) &&
3729 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3731 //Update Financial Records
3732 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3733 if ($callUpdateFinancialAccounts) {
3734 self
::updateFinancialAccounts($params, 'changedStatus');
3735 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3740 // change Payment Instrument for a Completed contribution
3741 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3742 // instrument is null and now new payment instrument is added along with the payment
3743 if (!$params['contribution']->payment_instrument_id
) {
3744 $params['contribution']->find(TRUE);
3746 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3747 $params['trxnParams']['check_number'] = $params['check_number'] ??
NULL;
3749 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3750 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3753 //if Change contribution amount
3754 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ??
NULL;
3755 $params['trxnParams']['net_amount'] = $params['net_amount'] ??
NULL;
3756 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3757 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3758 if (isset($totalAmount) &&
3759 $totalAmount != $params['prevContribution']->total_amount
3761 //Update Financial Records
3762 $params['trxnParams']['from_financial_account_id'] = NULL;
3763 self
::updateFinancialAccounts($params, 'changedAmount');
3764 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3769 // Looks like we might have a data correction update.
3770 // This would be a case where a transaction id has been entered but it is incorrect &
3771 // the person goes back in & fixes it, as opposed to a new transaction.
3772 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3773 // the data fix scenario.
3775 if (isset($params['refund_trxn_id'])) {
3776 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3777 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3778 civicrm_api3('FinancialTrxn', 'create', [
3779 'id' => $refundIDs['financialTrxnId'],
3780 'trxn_id' => $params['refund_trxn_id'],
3784 $cardType = $params['card_type_id'] ??
NULL;
3785 $panTruncation = $params['pan_truncation'] ??
NULL;
3786 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3791 // records finanical trxn and entity financial trxn
3792 // also make it available as return value
3793 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3794 $trxnParams['pan_truncation'] = $params['pan_truncation'] ??
NULL;
3795 $trxnParams['card_type_id'] = $params['card_type_id'] ??
NULL;
3796 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3797 $params['entity_id'] = $financialTxn->id
;
3798 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3799 self
::$_trxnIDs[] = $financialTxn->id
;
3803 // record line items and financial items
3804 if (empty($params['skipLineItem'])) {
3805 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
3808 // create batch entry if batch_id is passed and
3809 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3810 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3812 'batch_id' => $params['batch_id'],
3813 'entity_table' => 'civicrm_financial_trxn',
3814 'entity_id' => $financialTxn->id
,
3816 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3819 // when a fee is charged
3820 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3821 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3824 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3825 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3827 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3828 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3829 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3831 unset($params['line_item']);
3832 self
::$_trxnIDs = NULL;
3837 * Update all financial accounts entry.
3839 * @param array $params
3840 * Contribution object, line item array and params for trxn.
3842 * @param string $context
3845 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3846 * adds unpredictability.
3849 public static function updateFinancialAccounts(&$params, $context = NULL) {
3851 $inputParams = $params;
3852 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3854 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3855 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3856 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3859 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3860 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3861 $params['entity_id'] = $trxn->id
;
3863 $itemParams['entity_table'] = 'civicrm_line_item';
3864 $trxnIds['id'] = $params['entity_id'];
3865 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3866 foreach ($params['line_item'] as $fieldId => $fields) {
3867 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3872 * Is this contribution status a reversal.
3874 * If so we would expect to record a negative value in the financial_trxn table.
3876 * @param int $status_id
3880 public static function isContributionStatusNegative($status_id) {
3881 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3882 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3886 * Check status validation on update of a contribution.
3888 * @param array $values
3889 * Previous form values before submit.
3891 * @param array $fields
3892 * The input form values.
3894 * @param array $errors
3899 public static function checkStatusValidation($values, &$fields, &$errors) {
3900 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3901 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3902 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3906 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3908 'Cancelled' => ['Completed', 'Refunded'],
3909 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3910 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3911 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3912 'Refunded' => ['Cancelled', 'Completed'],
3913 'Partially paid' => ['Completed'],
3914 'Pending refund' => ['Completed', 'Refunded'],
3915 'Failed' => ['Pending'],
3918 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3919 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3921 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3922 1 => $contributionStatuses[$values['contribution_status_id']],
3923 2 => $contributionStatuses[$fields['contribution_status_id']],
3929 * Delete contribution of contact.
3931 * @see https://issues.civicrm.org/jira/browse/CRM-12155
3933 * @param int $contactId
3937 public static function deleteContactContribution($contactId) {
3938 $contribution = new CRM_Contribute_DAO_Contribution();
3939 $contribution->contact_id
= $contactId;
3940 $contribution->find();
3941 while ($contribution->fetch()) {
3942 self
::deleteContribution($contribution->id
);
3947 * Get options for a given contribution field.
3949 * @param string $fieldName
3950 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3951 * @param array $props whatever is known about this dao object.
3953 * @return array|bool
3954 * @see CRM_Core_DAO::buildOptions
3957 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3958 $className = __CLASS__
;
3960 if (isset($props['orderColumn'])) {
3961 $params['orderColumn'] = $props['orderColumn'];
3963 switch ($fieldName) {
3964 // This field is not part of this object but the api supports it
3965 case 'payment_processor':
3966 $className = 'CRM_Contribute_BAO_ContributionPage';
3967 // Filter results by contribution page
3968 if (!empty($props['contribution_page_id'])) {
3969 $page = civicrm_api('contribution_page', 'getsingle', [
3971 'id' => ($props['contribution_page_id']),
3973 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3974 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3978 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3979 case 'honor_type_id':
3980 $className = 'CRM_Contribute_BAO_ContributionSoft';
3981 $fieldName = 'soft_credit_type_id';
3982 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3985 case 'contribution_status_id':
3986 if ($context !== 'validate') {
3987 $params['condition'] = "v.name <> 'Template'";
3990 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3994 * Validate financial type.
3996 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3998 * @param int $financialTypeId
3999 * Financial Type id.
4001 * @param string $relationName
4003 * @return array|bool
4005 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
4006 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
4008 if (!$financialAccount) {
4009 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
4015 * @param int $targetCid
4016 * @param $activityType
4017 * @param string $title
4018 * @param int $contributionId
4019 * @param string $totalAmount
4020 * @param string $currency
4021 * @param string $trxn_date
4023 * @throws \CRM_Core_Exception
4024 * @throws \CiviCRM_API3_Exception
4026 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
4027 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
4028 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
4029 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
4030 // source record id would be the contribution id
4031 $srcRecId = $contributionId;
4035 'source_contact_id' => $targetCid,
4036 'source_record_id' => $srcRecId,
4037 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
4038 'subject' => $subject,
4039 'activity_date_time' => $date,
4040 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
4041 'skipRecentView' => TRUE,
4044 // create activity with target contacts
4045 $session = CRM_Core_Session
::singleton();
4046 $id = $session->get('userID');
4048 $activityParams['source_contact_id'] = $id;
4049 $activityParams['target_contact_id'][] = $targetCid;
4051 civicrm_api3('Activity', 'create', $activityParams);
4055 * Get list of payments displayed by Contribute_Page_PaymentInfo.
4058 * @param string $component
4059 * @param bool $getTrxnInfo
4063 * @throws \CRM_Core_Exception
4064 * @throws \CiviCRM_API3_Exception
4066 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
4067 // @todo deprecate passing in component - always call with contribution.
4068 if ($component == 'event') {
4069 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4071 if (!$contributionId) {
4072 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4073 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4074 $id = $primaryParticipantId;
4076 if (!$contributionId) {
4081 elseif ($component == 'membership') {
4082 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4085 $contributionId = $id;
4088 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
4089 // but need to unpick the whole trxn_id it's returning first.
4090 $oldCalculation = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4091 $baseTrxnId = !empty($oldCalculation['trxn_id']) ?
$oldCalculation['trxn_id'] : NULL;
4093 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4094 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4096 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4098 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
4100 $contribution = civicrm_api3('Contribution', 'getsingle', [
4101 'id' => $contributionId,
4105 'contribution_status_id',
4106 'financial_type_id',
4110 $info['payLater'] = $contribution['is_pay_later'];
4111 $info['contribution_status'] = $contribution['contribution_status'];
4112 $info['currency'] = $contribution['currency'];
4114 $info['total'] = $total;
4115 $info['paid'] = $total - $paymentBalance;
4116 $info['balance'] = $paymentBalance;
4118 $info['component'] = $component;
4119 if ($getTrxnInfo && $baseTrxnId) {
4120 $info['transaction'] = self
::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
4123 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4128 * Get the outstanding balance on a contribution.
4130 * @param int $contributionId
4131 * @param float $contributionTotal
4132 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4136 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4137 if ($contributionTotal === NULL) {
4138 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4141 return (float) CRM_Utils_Money
::subtractCurrencies(
4143 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
4144 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4149 * Get the tax amount (misnamed function).
4151 * @param array $params
4154 * @throws \CiviCRM_API3_Exception
4156 protected static function checkTaxAmount($params) {
4157 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4159 // Update contribution.
4160 if (!empty($params['id'])) {
4161 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4162 // there are no tax implications - early return.
4163 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4166 if (empty($params['prevContribution'])) {
4167 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4170 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4171 if (!isset($params[$field])) {
4172 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4173 // Tax amount gets added back on later....
4174 $params['total_amount'] = $params['prevContribution']->total_amount
-
4175 $params['prevContribution']->tax_amount
;
4178 $params[$field] = $params['prevContribution']->$field;
4179 if ($params[$field] != $params['prevContribution']->$field) {
4185 self
::calculateMissingAmountParams($params, $params['id']);
4186 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4187 // Assign tax Amount on update of contribution
4188 if (!empty($params['prevContribution']->tax_amount
)) {
4189 $params['tax_amount'] = 'null';
4190 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4191 foreach ($params['line_item'] as $setID => $priceField) {
4192 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4193 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4200 // New Contribution and update of contribution with tax rate financial type
4201 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4202 empty($params['skipLineItem'])) {
4203 $taxRateParams = $taxRates[$params['financial_type_id']];
4204 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4205 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4207 // Get Line Item on update of contribution
4208 if (isset($params['id'])) {
4209 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4212 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4214 foreach ($params['line_item'] as $setID => $priceField) {
4215 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4216 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4219 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4221 elseif (isset($params['api.line_item.create'])) {
4222 // Update total amount of contribution using lineItem
4223 $taxAmountArray = [];
4224 foreach ($params['api.line_item.create'] as $key => $value) {
4225 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4226 $taxRate = $taxRates[$value['financial_type_id']];
4227 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4228 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4231 $params['tax_amount'] = array_sum($taxAmountArray);
4232 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4239 * Check financial type validation on update of a contribution.
4241 * @param int $financialTypeId
4242 * Value of latest Financial Type.
4244 * @param int $contributionId
4247 * @param array $errors
4252 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4253 if (!empty($financialTypeId)) {
4254 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4255 if ($oldFinancialTypeId == $financialTypeId) {
4259 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4261 '1' => [$contributionId, 'Integer'],
4263 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4264 if ($result->N
> 1) {
4265 $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.');
4270 * Update related pledge payment payments.
4272 * This function has been refactored out of the back office contribution form and may
4273 * still overlap with other functions.
4275 * @param string $action
4276 * @param int $pledgePaymentID
4277 * @param int $contributionID
4278 * @param bool $adjustTotalAmount
4279 * @param float $total_amount
4280 * @param float $original_total_amount
4281 * @param int $contribution_status_id
4282 * @param int $original_contribution_status_id
4284 public static function updateRelatedPledge(
4290 $original_total_amount,
4291 $contribution_status_id,
4292 $original_contribution_status_id
4294 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4298 if ($pledgePaymentID) {
4299 //store contribution id in payment record.
4300 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4303 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4310 if (!$pledgePaymentID) {
4313 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4319 $updatePledgePaymentStatus = FALSE;
4321 // If either the status or the amount has changed we update the pledge status.
4322 if ($action & CRM_Core_Action
::ADD
) {
4323 $updatePledgePaymentStatus = TRUE;
4325 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4326 ($original_total_amount != $total_amount))
4328 $updatePledgePaymentStatus = TRUE;
4331 if ($updatePledgePaymentStatus) {
4332 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4334 $contribution_status_id,
4343 * Is there only one line item attached to the contribution.
4349 * @throws \CiviCRM_API3_Exception
4351 public static function isSingleLineItem($id) {
4352 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4353 return ($lineItemCount == 1);
4357 * Complete an order.
4359 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4361 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4363 * Moving it out of the BaseIPN class is just the first step.
4365 * @param array $input
4367 * @param array $objects
4368 * @param bool $isPostPaymentCreate
4369 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4370 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4371 * transitioning related elements).
4374 * @throws \CRM_Core_Exception
4375 * @throws \CiviCRM_API3_Exception
4377 public static function completeOrder($input, $ids, $objects, $isPostPaymentCreate = FALSE) {
4378 $transaction = new CRM_Core_Transaction();
4379 $contribution = $objects['contribution'];
4380 // Unset objects just to make it clear it's not used again.
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 // Add new soft credit against current $contribution.
4459 if ($recurringContributionID) {
4460 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($recurringContributionID, $contributionID);
4463 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4465 CRM_Core_Error
::debug_log_message('Contribution record updated successfully');
4466 $transaction->commit();
4468 // @todo - check if Contribution::create does this, test, remove.
4469 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contributionID, $recurringContributionID,
4470 $contributionParams['contribution_status_id'], $input['amount']);
4472 // create an activity record
4473 // @todo - check if Contribution::create does this, test, remove.
4474 if ($input['component'] == 'contribute') {
4476 $targetContactID = NULL;
4477 if ($contributionContactID) {
4478 $targetContactID = $contribution->contact_id
;
4479 $contribution->contact_id
= $contributionContactID;
4481 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution', $targetContactID);
4484 if (self
::isEmailReceipt($input, $contribution->contribution_page_id
, $recurringContributionID)) {
4485 civicrm_api3('Contribution', 'sendconfirmation', [
4486 'id' => $contributionID,
4487 'payment_processor_id' => $paymentProcessorId,
4489 CRM_Core_Error
::debug_log_message("Receipt sent");
4492 CRM_Core_Error
::debug_log_message("Success: Database updated");
4493 return $contributionResult;
4497 * Send receipt from contribution.
4499 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4501 * Note that the compose message part has been moved to contribution
4502 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4504 * @param array $input
4505 * Incoming data from Payment processor.
4507 * Related object IDs.
4508 * @param int $contributionID
4509 * @param bool $returnMessageText
4510 * Should text be returned instead of sent. This.
4511 * is because the function is also used to generate pdfs
4514 * @throws \CRM_Core_Exception
4515 * @throws \CiviCRM_API3_Exception
4516 * @throws \Exception
4518 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4520 $contribution = new CRM_Contribute_BAO_Contribution();
4521 $contribution->id
= $contributionID;
4522 if (!$contribution->find(TRUE)) {
4523 throw new CRM_Core_Exception('Contribution does not exist');
4525 $contribution->loadRelatedObjects($input, $ids, TRUE);
4526 // set receipt from e-mail and name in value
4527 if (!$returnMessageText) {
4528 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4530 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4531 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4532 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4533 civicrm_api3('Contribution', 'create', [
4534 'receipt_date' => 'now',
4535 'id' => $contribution->id
,
4542 * Generate From email and from name in an array values
4544 * @param array $input
4545 * @param \CRM_Contribute_BAO_Contribution $contribution
4549 public static function generateFromEmailAndName($input, $contribution) {
4550 // Use input value if supplied.
4551 if (!empty($input['receipt_from_email'])) {
4553 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4554 $input['receipt_from_email'],
4557 // if we are still empty see if we can use anything from a contribution page.
4559 if (!empty($contribution->contribution_page_id
)) {
4560 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4562 // if we are still empty see if we can use anything from a contribution page.
4563 if (!empty($pageValues['receipt_from_email'])) {
4565 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4566 $pageValues['receipt_from_email'],
4569 // If we are still empty fall back to the domain or logged in user information.
4570 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4574 * Load related memberships.
4578 * @return array $ids
4583 * Note that in theory it should be possible to retrieve these from the line_item table
4584 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4585 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4586 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4587 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4589 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4592 public function loadRelatedMembershipObjects($ids = []) {
4594 SELECT membership_id
4595 FROM civicrm_membership_payment
4596 WHERE contribution_id = %1 ";
4597 $params = [1 => [$this->id
, 'Integer']];
4598 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4600 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4601 while ($dao->fetch()) {
4602 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4603 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4607 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4608 foreach ($ids['membership'] as $id) {
4610 $membership = new CRM_Member_BAO_Membership();
4611 $membership->id
= $id;
4612 if (!$membership->find(TRUE)) {
4613 throw new Exception("Could not find membership record: $id");
4615 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4616 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4617 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4618 $this->_relatedObjects
['membership'][$membership->id
. '_' . $membership->membership_type_id
] = $membership;
4627 * Get the description (source field) for the recurring contribution.
4629 * @param CRM_Contribute_BAO_Contribution $contribution
4630 * @param int|null $participantID
4633 * @throws \CiviCRM_API3_Exception
4634 * @throws \API_Exception
4636 protected static function getRecurringContributionDescription($contribution, $participantID) {
4637 if (!empty($contribution->source
)) {
4638 return $contribution->source
;
4640 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4641 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4642 'id' => $contribution->contribution_page_id
,
4643 'return' => 'title',
4645 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4647 elseif ($participantID) {
4648 $eventTitle = Participant
::get(FALSE)
4649 ->addSelect('event.title')
4650 ->addWhere('id', '=', (int) $participantID)
4651 ->execute()->first()['event.title'];
4652 return ts('Online Event Registration') . ': ' . $eventTitle;
4654 elseif (!empty($contribution->contribution_recur_id
)) {
4655 return 'recurring contribution';
4661 * Function use to store line item proportionally in in entity financial trxn table
4663 * @param array $trxnParams
4665 * @param int $trxnId
4667 * @param float $contributionTotalAmount
4669 * @throws \CiviCRM_API3_Exception
4671 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4672 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4673 if (!empty($lineItems)) {
4674 // get financial item
4675 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4677 'contribution_total_amount' => $contributionTotalAmount,
4678 'trxn_total_amount' => $trxnParams['total_amount'],
4679 'trxn_id' => $trxnId,
4681 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4686 * Checks if line items total amounts
4687 * match the contribution total amount.
4689 * @param array $params
4690 * array of order params.
4692 * @throws \API_Exception
4694 public static function checkLineItems(&$params) {
4695 $totalAmount = $params['total_amount'] ??
NULL;
4696 $lineItemAmount = 0;
4698 foreach ($params['line_items'] as &$lineItems) {
4699 foreach ($lineItems['line_item'] as &$item) {
4700 if (empty($item['financial_type_id'])) {
4701 $item['financial_type_id'] = $params['financial_type_id'];
4703 $lineItemAmount +
= $item['line_total'] +
($item['tax_amount'] ??
0.00);
4707 if (!isset($totalAmount)) {
4708 $params['total_amount'] = $lineItemAmount;
4711 $currency = $params['currency'] ?? CRM_Core_Config
::singleton()->defaultCurrency
;
4713 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4714 throw new CRM_Contribute_Exception_CheckLineItemsException();
4720 * Get the financial account for the item associated with the new transaction.
4722 * @param array $params
4723 * @param int $default
4727 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4729 if (!empty($params['financial_account_id'])) {
4730 return $params['financial_account_id'];
4733 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4734 $preferredAccountsRelationships = [
4735 'Refunded' => 'Credit/Contra Revenue Account is',
4736 'Chargeback' => 'Chargeback Account is',
4739 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4740 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4741 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4743 $preferredAccountsRelationships[$contributionStatus]
4751 * ContributionPage values were being imposed onto values.
4753 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4754 * REALLY didn't want superimposed. The rest are left there in their overkill out
4757 * The rationale for making this explicit is that it was a case of carefully set values being
4758 * seemingly randonly overwritten without much care. In general I think array randomly setting
4759 * variables en mass is risky.
4761 * @param array $values
4765 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4766 $contributionPageValues = [];
4767 CRM_Contribute_BAO_ContributionPage
::setValues(
4768 $this->contribution_page_id
,
4769 $contributionPageValues
4772 // These are the values that I believe to be useful.
4775 'pay_later_receipt',
4777 'receipt_from_email',
4778 'receipt_from_name',
4782 'honoree_profile_id',
4783 'onbehalf_profile_id',
4784 'honor_block_is_active',
4785 // Kinda might be - but would be on the contribution...
4788 // Included for 'fear of regression' but can't justify any use for these....
4790 'payment_processor',
4791 'financial_type_id',
4792 'amount_block_is_active',
4797 'default_amount_id',
4801 'initial_amount_help_text',
4802 'initial_amount_label',
4804 'is_allow_other_amount',
4805 'is_billing_required',
4806 'is_confirm_enabled',
4807 'is_credit_card_only',
4809 'is_partial_payment',
4810 'is_recur_installments',
4811 'is_recur_interval',
4815 'min_initial_amount',
4816 'recur_frequency_unit',
4823 foreach ($valuesToCopy as $valueToCopy) {
4824 if (isset($contributionPageValues[$valueToCopy])) {
4825 if ($valueToCopy === 'title') {
4826 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
4829 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4837 * Get values of CiviContribute Settings
4838 * and check if its enabled or not.
4839 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4840 * in serialized form. Usually this should be stored as flat settings for each form fields
4841 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4842 * settings we will live with an inconsistency because it's too hard to change for now.
4843 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4846 * @param string $name
4851 public static function checkContributeSettings($name) {
4852 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
4853 return $contributeSettings[$name] ??
NULL;
4857 * This function process contribution related objects.
4859 * @param int $contributionId
4860 * @param int $statusId
4861 * @param int|null $previousStatusId
4863 * @param string $receiveDate
4865 * @return null|string
4867 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
4869 if (!$contributionId ||
!$statusId) {
4874 'contribution_id' => $contributionId,
4875 'contribution_status_id' => $statusId,
4876 'previous_contribution_status_id' => $previousStatusId,
4877 'receive_date' => $receiveDate,
4880 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
4882 if (!is_array($updateResult) ||
4883 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
4884 !is_array($updatedComponents) ||
4885 empty($updatedComponents)
4890 // get the user display name.
4892 SELECT display_name as displayName
4893 FROM civicrm_contact
4894 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
4895 WHERE civicrm_contribution.id = {$contributionId}";
4896 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
4898 // get the status message for user.
4899 foreach ($updatedComponents as $componentName => $updatedStatusId) {
4901 if ($componentName == 'CiviMember') {
4902 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
4903 CRM_Member_PseudoConstant
::membershipStatus()
4906 $statusNameMsgPart = 'updated';
4907 switch ($updatedStatusName) {
4910 $statusNameMsgPart = $updatedStatusName;
4914 $statusMsg .= "<br />" . ts("Membership for %1 has been %2.", [
4915 1 => $userDisplayName,
4916 2 => $statusNameMsgPart,
4920 if ($componentName == 'CiviEvent') {
4921 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
4922 CRM_Event_PseudoConstant
::participantStatus()
4924 if ($updatedStatusName == 'Cancelled') {
4925 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", [1 => $userDisplayName]);
4927 elseif ($updatedStatusName == 'Registered') {
4928 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", [1 => $userDisplayName]);
4932 if ($componentName == 'CiviPledge') {
4933 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
4934 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
4936 if ($updatedStatusName == 'Cancelled') {
4937 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", [1 => $userDisplayName]);
4939 elseif ($updatedStatusName == 'Failed') {
4940 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", [1 => $userDisplayName]);
4942 elseif ($updatedStatusName == 'Completed') {
4943 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", [1 => $userDisplayName]);
4952 * Get the contribution as it is in the database before being updated.
4954 * @param int $contributionID
4956 * @return \CRM_Contribute_BAO_Contribution|null
4958 private static function getOriginalContribution($contributionID) {
4959 return self
::getValues(['id' => $contributionID]);
4963 * Get the amount for the financial item row.
4965 * Helper function to start to break down recordFinancialTransactions for readability.
4967 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
4969 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
4970 * for historical reasons. Going forwards we can hope to add tests & improve readibility
4973 * @param array $params
4974 * Params as passed to contribution.create
4976 * @param string $context
4977 * changeFinancialType| changedAmount
4978 * @param array $lineItemDetails
4980 * @param bool $isARefund
4981 * Is this a refund / negative transaction.
4982 * @param int $previousLineItemTotal
4985 * @todo move recordFinancialAccounts & helper functions to their own class?
4988 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
4989 if ($context == 'changedAmount') {
4990 $lineTotal = $lineItemDetails['line_total'];
4991 if ($lineTotal != $previousLineItemTotal) {
4992 $lineTotal -= $previousLineItemTotal;
4996 elseif ($context == 'changeFinancialType') {
4997 return -$lineItemDetails['line_total'];
4999 elseif ($context == 'changedStatus') {
5000 $cancelledTaxAmount = 0;
5002 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
5004 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5006 elseif ($context === NULL) {
5007 // erm, yes because? but, hey, it's tested.
5008 return $lineItemDetails['line_total'];
5010 elseif (empty($lineItemDetails['line_total'])) {
5011 // follow legacy code path
5013 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
5014 return $params['total_amount'];
5017 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5022 * Get the multiplier for adjusting rows.
5024 * If we are dealing with a refund or cancellation then it will be a negative
5025 * amount to reflect the negative transaction.
5027 * If we are changing Financial Type it will be a negative amount to
5028 * adjust down the old type.
5030 * @param int $contribution_status_id
5031 * @param string $context
5035 protected static function getMultiplier($contribution_status_id, $context) {
5036 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5043 * Does this transaction reflect a payment instrument change.
5045 * @param array $params
5046 * @param array $pendingStatuses
5050 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5051 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
5053 if (array_key_exists('payment_instrument_id', $params)) {
5054 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
5055 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
5057 //check if status is changed from Pending to Completed
5058 // do not update payment instrument changes for Pending to Completed
5059 if (!($contributionStatus == 'Completed' &&
5060 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
5065 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
5066 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
5067 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5071 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
5072 $params['contribution']->check_number
!= $params['prevContribution']->check_number
5074 // another special case when check number is changed, create new financial records
5075 // create financial trxn with negative amount
5083 * Update the memberships associated with a contribution if it has been completed.
5085 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5086 * load them in this function. Code clean up would compensate for any minor performance implication.
5088 * @param int $contributionID
5089 * @param string $changeDate
5091 * @throws \CRM_Core_Exception
5092 * @throws \CiviCRM_API3_Exception
5094 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
5095 $memberships = self
::getRelatedMemberships($contributionID);
5096 foreach ($memberships as $membership) {
5097 $membershipParams = [
5098 'id' => $membership['id'],
5099 'contact_id' => $membership['contact_id'],
5100 'is_test' => $membership['is_test'],
5101 'membership_type_id' => $membership['membership_type_id'],
5102 'membership_activity_status' => 'Completed',
5105 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
5106 $membershipParams['membership_type_id'],
5107 $membershipParams['is_test'],
5108 $membershipParams['id']
5111 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5112 // this picks up membership type changes during renewals
5113 // @todo this is almost certainly an obsolete sql call, the pre-change
5114 // membership is accessible via $this->_relatedObjects
5116 SELECT membership_type_id
5117 FROM civicrm_membership_log
5118 WHERE membership_id={$membershipParams['id']}
5121 $dao = CRM_Core_DAO
::executeQuery($sql);
5122 if ($dao->fetch()) {
5123 if (!empty($dao->membership_type_id
)) {
5124 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
5127 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
5128 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
5129 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
5130 // 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.
5131 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
5132 // @todo once apiv4 ships with core switch to that & find sanity.
5133 $membershipParams['num_terms'] = self
::getNumTermsByContributionAndMembershipType(
5134 $membershipParams['membership_type_id'],
5138 // @todo remove all this stuff in favour of letting the api call further down handle in
5139 // (it is a duplication of what the api does).
5140 $dates = array_fill_keys([
5145 if ($currentMembership) {
5147 * Fixed FOR CRM-4433
5148 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5149 * when Contribution mode is notify and membership is for renewal )
5151 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
5153 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5155 // @todo - we should pass membership_type_id instead of null here but not
5156 // adding as not sure of testing
5157 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
5158 $changeDate, NULL, $membershipParams['num_terms']
5160 $dates['join_date'] = $currentMembership['join_date'];
5163 //get the status for membership.
5164 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
5166 $dates['join_date'],
5169 $membershipParams['membership_type_id'],
5173 unset($dates['end_date']);
5174 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
5175 //we might be renewing membership,
5176 //so make status override false.
5177 $membershipParams['is_override'] = FALSE;
5178 $membershipParams['status_override_end_date'] = 'null';
5179 civicrm_api3('Membership', 'create', $membershipParams);
5184 * Get payment links as they relate to a contribution.
5186 * If a payment can be made then include a payment link & if a refund is appropriate
5187 * then a refund link.
5190 * @param float $balance
5191 * @param string $contributionStatus
5194 * $actionLinks Links array containing:
5198 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5199 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5200 // In general the balance is the best way to determine if a payment can be added or not,
5201 // but not for Failed contributions, where we don't accept additional payments at the moment.
5202 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5203 // do accept more payments agains them.
5208 'url' => CRM_Utils_System
::url('civicrm/payment', [
5214 'title' => ts('Record Payment'),
5217 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5219 'url' => CRM_Utils_System
::url('civicrm/payment', [
5226 'title' => ts('Submit Credit Card payment'),
5230 'url' => CRM_Utils_System
::url('civicrm/payment', [
5236 'title' => ts('Record Refund'),
5238 return $actionLinks;
5242 * Get a query to determine the amount donated by the contact/s in the current financial year.
5244 * @param array $contactIDs
5248 public static function getAnnualQuery($contactIDs) {
5249 $contactIDs = implode(',', $contactIDs);
5250 $config = CRM_Core_Config
::singleton();
5251 $currentMonth = date('m');
5252 $currentDay = date('d');
5254 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5256 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5257 (int) $config->fiscalYearStart
['d'] > $currentDay
5260 $year = date('Y') - 1;
5265 $nextYear = $year +
1;
5267 if ($config->fiscalYearStart
) {
5268 $newFiscalYearStart = $config->fiscalYearStart
;
5269 if ($newFiscalYearStart['M'] < 10) {
5270 // This is just a clumsy way of adding padding.
5271 // @todo next round look for a nicer way.
5272 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5274 if ($newFiscalYearStart['d'] < 10) {
5275 // This is just a clumsy way of adding padding.
5276 // @todo next round look for a nicer way.
5277 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5279 $config->fiscalYearStart
= $newFiscalYearStart;
5280 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5283 // First of January.
5286 $startDate = "$year$monthDay";
5287 $endDate = "$nextYear$monthDay";
5290 'contact_id' => 'IN (' . $contactIDs . ')',
5291 'is_test' => ' = 0',
5292 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5294 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5295 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5298 foreach ($whereClauses as $key => $clause) {
5299 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5301 $whereClauseString = implode(' AND ', $clauses);
5303 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5304 // this group by + having on contribution_status_id improves performance
5306 SELECT COUNT(*) as count,
5307 SUM(total_amount) as amount,
5308 AVG(total_amount) as average,
5310 FROM civicrm_contribution b
5311 WHERE " . $whereClauseString . "
5312 GROUP BY currency, contribution_status_id
5313 HAVING $havingClause
5319 * Assign Test Value.
5321 * @param string $fieldName
5322 * @param array $fieldDef
5323 * @param int $counter
5325 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5326 if ($fieldName == 'tax_amount') {
5327 $this->{$fieldName} = "0.00";
5329 elseif ($fieldName == 'net_amount') {
5330 $this->{$fieldName} = "2.00";
5332 elseif ($fieldName == 'total_amount') {
5333 $this->{$fieldName} = "3.00";
5335 elseif ($fieldName == 'fee_amount') {
5336 $this->{$fieldName} = "1.00";
5339 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5344 * Check if contribution has participant/membership payment.
5346 * @param int $contributionId
5351 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5352 // get line item for contribution
5353 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5354 // check if line item is for membership or participant
5355 foreach ($lineItems as $items) {
5356 if ($items['entity_table'] == 'civicrm_participant') {
5360 elseif ($items['entity_table'] == 'civicrm_membership') {
5372 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5374 * @param array $trxnParams
5375 * Financial trxn params
5376 * @param array $contributionParams
5377 * Contribution Params
5381 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5382 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5385 $statusId = $contributionParams['contribution']->contribution_status_id
;
5386 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5387 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5388 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5389 // Return if contribution status is not completed.
5390 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5391 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5392 && $contributionParams['prevContribution']->is_pay_later
== 0
5398 $params = $trxnParams;
5399 $financialTypeID = !empty($contributionParams['financial_type_id']) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5400 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5401 $params['to_financial_account_id'] = $arAccountId;
5402 $params['status_id'] = array_search('Pending', $contributionStatuses);
5403 $params['is_payment'] = FALSE;
5404 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5405 self
::$_trxnIDs[] = $trxn->id
;
5406 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5410 * Calculate financial item amount when contribution is updated.
5412 * @param array $params
5413 * contribution params
5414 * @param array $amountParams
5416 * @param string $context
5420 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5421 if (!empty($params['is_quick_config'])) {
5422 $amount = $amountParams['item_amount'];
5424 $amount = $params['total_amount'];
5425 if ($context === NULL) {
5426 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5431 $amount = $amountParams['line_total'];
5432 if ($context == 'changedAmount') {
5433 $amount -= $amountParams['previous_line_total'];
5435 $amount *= $amountParams['diff'];
5441 * Retrieve Sales Tax Financial Accounts.
5447 public static function getSalesTaxFinancialAccounts() {
5448 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5449 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5450 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5451 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5452 $queryParams = [1 => [$accountRel, 'Integer']];
5453 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5454 $financialAccount = [];
5455 while ($dao->fetch()) {
5456 $financialAccount[$dao->id
] = $dao->id
;
5458 return $financialAccount;
5462 * Create tax entry in civicrm_entity_financial_trxn table.
5464 * @param array $entityParams
5466 * @param array $eftParams
5468 * @throws \CiviCRM_API3_Exception
5470 public static function createProportionalEntry($entityParams, $eftParams) {
5472 if ($entityParams['contribution_total_amount'] != 0) {
5473 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5475 // Record Entity Financial Trxn; CRM-20145
5476 $eftParams['amount'] = $paid;
5477 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5481 * Create array of last financial item id's.
5483 * @param int $contributionId
5487 public static function getLastFinancialItemIds($contributionId) {
5488 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5489 FROM civicrm_financial_item fi
5490 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5491 WHERE li.contribution_id = %1";
5492 $dao = CRM_Core_DAO
::executeQuery($sql, [
5498 $ftIds = $taxItems = [];
5499 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5500 while ($dao->fetch()) {
5501 /* if sales tax item*/
5502 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5503 $taxItems[$dao->price_field_value_id
] = [
5504 'financial_item_id' => $dao->id
,
5505 'amount' => $dao->tax_amount
,
5509 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5512 return [$ftIds, $taxItems];
5516 * Create proportional entries in civicrm_entity_financial_trxn.
5518 * @param array $entityParams
5520 * @param array $lineItems
5522 * @param array $ftIds
5524 * @param array $taxItems
5526 * @throws \CiviCRM_API3_Exception
5528 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5530 'entity_table' => 'civicrm_financial_item',
5531 'financial_trxn_id' => $entityParams['trxn_id'],
5533 foreach ($lineItems as $key => $value) {
5534 if ($value['qty'] == 0) {
5537 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5538 $entityParams['line_item_amount'] = $value['line_total'];
5539 self
::createProportionalEntry($entityParams, $eftParams);
5540 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5541 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5542 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5543 self
::createProportionalEntry($entityParams, $eftParams);
5549 * Load entities related to the contribution into $this->_relatedObjects.
5553 * @throws \CRM_Core_Exception
5555 protected function loadRelatedEntitiesByID($ids) {
5557 'contact' => 'CRM_Contact_BAO_Contact',
5558 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5559 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5560 'financialType' => 'CRM_Financial_BAO_FinancialType',
5561 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5563 foreach ($entities as $entity => $bao) {
5564 if (!empty($ids[$entity])) {
5565 $this->_relatedObjects
[$entity] = new $bao();
5566 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5567 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5568 throw new CRM_Core_Exception($entity . ' could not be loaded');
5575 * Function to replace contribution tokens.
5577 * @param array $contributionIds
5579 * @param string $subject
5581 * @param array $subjectToken
5583 * @param string $text
5585 * @param string $html
5587 * @param array $messageToken
5589 * @param bool $escapeSmarty
5592 * @throws \CiviCRM_API3_Exception
5594 public static function replaceContributionTokens(
5603 if (empty($contributionIds)) {
5606 $contributionDetails = [];
5607 foreach ($contributionIds as $id) {
5608 $result = self
::getContributionTokenValues($id, $messageToken);
5609 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5610 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5611 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5613 return $contributionDetails;
5617 * Get the contribution fields for $id and display labels where
5618 * appropriate (if the token is present).
5621 * @param array $messageToken
5624 public static function getContributionTokenValues($id, $messageToken) {
5628 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5629 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5630 if (!empty($messageToken)) {
5631 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5632 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5633 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5641 * Get invoice_number for contribution.
5643 * @param int $contributionID
5647 public static function getInvoiceNumber($contributionID) {
5648 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix')) {
5649 return $invoicePrefix . $contributionID;
5656 * Load the values needed for the event message.
5658 * @param int $eventID
5659 * @param int $participantID
5660 * @param int|null $contributionID
5663 * @throws \CRM_Core_Exception
5665 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5670 $values = ['event' => []];
5672 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5673 // add custom fields for event
5674 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5676 $eventCustomGroup = [];
5677 foreach ($eventGroupTree as $key => $group) {
5678 if ($key === 'info') {
5682 foreach ($group['fields'] as $k => $customField) {
5683 $groupLabel = $group['title'];
5684 if (!empty($customField['customValue'])) {
5685 foreach ($customField['customValue'] as $customFieldValues) {
5686 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5691 $values['event']['customGroup'] = $eventCustomGroup;
5693 //get participant details
5694 $participantParams = [
5695 'id' => $participantID,
5698 $values['participant'] = [];
5700 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5701 // add custom fields for event
5702 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5703 $participantCustomGroup = [];
5704 foreach ($participantGroupTree as $key => $group) {
5705 if ($key === 'info') {
5709 foreach ($group['fields'] as $k => $customField) {
5710 $groupLabel = $group['title'];
5711 if (!empty($customField['customValue'])) {
5712 foreach ($customField['customValue'] as $customFieldValues) {
5713 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5718 $values['participant']['customGroup'] = $participantCustomGroup;
5720 //get location details
5722 'entity_id' => $eventID,
5723 'entity_table' => 'civicrm_event',
5725 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5728 'entity_table' => 'civicrm_event',
5729 'entity_id' => $eventID,
5730 'module' => 'CiviEvent',
5733 list($custom_pre_id,
5735 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5737 $values['custom_pre_id'] = $custom_pre_id;
5738 $values['custom_post_id'] = $custom_post_ids;
5740 // set lineItem for event contribution
5741 if ($contributionID) {
5742 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5743 if (!empty($participantIds)) {
5744 foreach ($participantIds as $pIDs) {
5745 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5746 if (!CRM_Utils_System
::isNull($lineItem)) {
5747 $values['lineItem'][] = $lineItem;